{
 "name": "Papierkram-Killer – Brief fotografieren, WhatsApp senden, Frist erledigt (OCR + KI + Nextcloud)",
 "nodes": [
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "papierkram",
    "responseMode": "responseNode",
    "options": {}
   },
   "name": "WhatsApp (WAHA-Webhook)",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    0
   ],
   "webhookId": "6c99b3f7-2de5-4776-a681-bc74b2073a57"
  },
  {
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify({ ok: true }) }}",
    "options": {}
   },
   "name": "Sofort 200 (WAHA)",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    120,
    0
   ]
  },
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "papierkram-upload",
    "responseMode": "responseNode",
    "options": {}
   },
   "name": "Upload-Webhook",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    200
   ],
   "webhookId": "ef0c837c-2513-40bd-9803-874bfbf91175"
  },
  {
   "parameters": {
    "rule": {
     "interval": [
      {
       "field": "days",
       "daysInterval": 1,
       "triggerAtHour": 8
      }
     ]
    }
   },
   "name": "Täglich 8 Uhr",
   "type": "n8n-nodes-base.scheduleTrigger",
   "typeVersion": 1.2,
   "position": [
    0,
    400
   ]
  },
  {
   "parameters": {
    "jsCode": "// ⚙️ KONFIGURATION – hier alles anpassen (Rest des Workflows nicht anfassen)\nconst cfg = {\n  apiBase: 'https://openai.inference.de-txl.ionos.com/v1', // jede OpenAI-kompatible API (Chat Completions)\n  ocrModel: 'lightonai/LightOnOCR-2-1B',                    // Vision-/OCR-Modell (liest das Foto)\n  llmModel: 'meta-llama/Llama-3.3-70B-Instruct',            // Text-Modell (versteht den Brief)\n  sprache: 'de',                // Sprache der Antworten: de | it | en\n  wahaUrl: 'http://waha:3000',  // Adresse deiner WAHA-Instanz (WhatsApp HTTP API)\n  wahaSession: 'default',\n  nextcloudUrl: '',             // z. B. https://cloud.example.com  (leer = nur WhatsApp-Antwort, kein Ablegen)\n  nextcloudUser: '',            // Nextcloud-Benutzername\n  ordner: 'Papierkram',         // Wurzelordner in Nextcloud\n  kalender: 'papierkram',        // Kalender für die Frist-Aufgabe, muss Aufgaben (VTODO) erlauben, z. B. neue Liste in Nextcloud Tasks anlegen\n  erinnerungTage: 3,            // so viele Tage vor der Frist erinnern\n  ocrTextSpeichern: true,       // Volltext als .txt neben das Foto (macht Fotos durchsuchbar)\n  erlaubteChats: [],            // leer = nur du im eigenen Chat \"Nachrichten an mich\". Besser: eine WhatsApp-Gruppe nur für Briefe, ihre ID hier eintragen, z. B. ['1203634…@g.us']\n  webToken: '',                 // Token für den Upload-Webhook (Header x-token). Leer = Webhook gesperrt\n};\nreturn $input.all().map(i => ({ json: { ...i.json, cfg }, binary: i.binary }));\n"
   },
   "name": "Konfiguration",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    240,
    200
   ]
  },
  {
   "parameters": {
    "jsCode": "const L = {\n  de: {\n    help: '📄 *Papierkram-Killer*\\nSchick mir ein *Foto* (oder PDF) von einem Brief – ich lese ihn, lege ihn ab und erinnere dich an die Frist.\\n\\n/offen – offene Fristen\\n/bezahlt 3 – Nr. 3 als erledigt markieren\\n/hilfe – diese Hilfe',\n    locked: '🔒 Dieser Bot ist privat.', unread: '😕 Ich konnte auf dem Bild keinen Text lesen. Bitte nochmal, gerade und gut beleuchtet.',\n    pdfScan: '😕 Das PDF ist ein Scan ohne Text. Bitte schick es als Foto.', tooBig: '😕 Datei zu groß (max. 8 MB).', unsupported: 'Bitte schick ein Foto oder PDF vom Brief.',\n    noneOpen: '🎉 Nichts offen. Papierkram-frei!', openHead: '📋 *Offene Fristen*', paidOk: '✅ Erledigt: ', paidBad: 'Diese Nummer kenne ich nicht.',\n    overdue: n => `${-n} Tag${n === -1 ? '' : 'e'} überfällig`, today: 'heute', tomorrow: 'morgen', inDays: n => `in ${n} Tagen`,\n    due: 'fällig', deadline: 'Frist', noDeadline: 'keine Frist erkannt', todo: 'Was tun', risk: 'Risiko', saved: '🗂 Abgelegt', noSave: 'Nicht abgelegt (Nextcloud nicht eingerichtet)', saveFail: '⚠️ Ablegen in Nextcloud fehlgeschlagen',\n    remind: d => `⏰ Erinnerung ${d} Tage vorher angelegt`, remindFail: '⚠️ Erinnerung konnte nicht angelegt werden', est: 'geschätzt, bitte prüfen', ref: 'Referenz', nr: 'Nr.', markPaid: 'Erledigt:',\n    remHead: '⏰ *Bald fällig*', weekHead: '🗓 *Wochenübersicht*',\n    typ: { rechnung: 'Rechnungen', mahnung: 'Mahnungen', behoerde: 'Behörden', steuer: 'Steuer', versicherung: 'Versicherung', vertrag: 'Verträge', bank: 'Bank', arzt: 'Gesundheit', miete: 'Wohnen', schule: 'Schule', werbung: 'Werbung', sonstiges: 'Sonstiges' },\n  },\n  it: {\n    help: '📄 *Papierkram-Killer*\\nMandami una *foto* (o un PDF) di una lettera: la leggo, la archivio e ti ricordo la scadenza.\\n\\n/offen – scadenze aperte\\n/bezahlt 3 – segna n. 3 come fatto\\n/hilfe – questo aiuto',\n    locked: '🔒 Questo bot è privato.', unread: '😕 Non riesco a leggere testo nell’immagine. Riprova, dritta e ben illuminata.',\n    pdfScan: '😕 Il PDF è una scansione senza testo. Mandalo come foto.', tooBig: '😕 File troppo grande (max 8 MB).', unsupported: 'Mandami una foto o un PDF della lettera.',\n    noneOpen: '🎉 Niente di aperto. Zero carte!', openHead: '📋 *Scadenze aperte*', paidOk: '✅ Fatto: ', paidBad: 'Numero sconosciuto.',\n    overdue: n => `scaduta da ${-n} giorn${n === -1 ? 'o' : 'i'}`, today: 'oggi', tomorrow: 'domani', inDays: n => `tra ${n} giorni`,\n    due: 'scade', deadline: 'Scadenza', noDeadline: 'nessuna scadenza trovata', todo: 'Cosa fare', risk: 'Rischio', saved: '🗂 Archiviata', noSave: 'Non archiviata (Nextcloud non configurato)', saveFail: '⚠️ Archiviazione su Nextcloud fallita',\n    remind: d => `⏰ Promemoria creato ${d} giorni prima`, remindFail: '⚠️ Promemoria non creato', est: 'stimata, da verificare', ref: 'Riferimento', nr: 'N.', markPaid: 'Fatto:',\n    remHead: '⏰ *In scadenza*', weekHead: '🗓 *Panoramica settimanale*',\n    typ: { rechnung: 'Fatture', mahnung: 'Solleciti', behoerde: 'Enti', steuer: 'Tasse', versicherung: 'Assicurazioni', vertrag: 'Contratti', bank: 'Banca', arzt: 'Salute', miete: 'Casa', schule: 'Scuola', werbung: 'Pubblicità', sonstiges: 'Altro' },\n  },\n  en: {\n    help: '📄 *Papierkram-Killer*\\nSend me a *photo* (or PDF) of a letter – I read it, file it and remind you of the deadline.\\n\\n/offen – open deadlines\\n/bezahlt 3 – mark no. 3 as done\\n/hilfe – this help',\n    locked: '🔒 This bot is private.', unread: '😕 I could not read any text in the image. Please retry, straight and well lit.',\n    pdfScan: '😕 The PDF is a scan without text. Please send it as a photo.', tooBig: '😕 File too large (max 8 MB).', unsupported: 'Please send a photo or PDF of the letter.',\n    noneOpen: '🎉 Nothing open. Paper-free!', openHead: '📋 *Open deadlines*', paidOk: '✅ Done: ', paidBad: 'I do not know that number.',\n    overdue: n => `${-n} day${n === -1 ? '' : 's'} overdue`, today: 'today', tomorrow: 'tomorrow', inDays: n => `in ${n} days`,\n    due: 'due', deadline: 'Deadline', noDeadline: 'no deadline found', todo: 'To do', risk: 'Risk', saved: '🗂 Filed', noSave: 'Not filed (Nextcloud not set up)', saveFail: '⚠️ Filing to Nextcloud failed',\n    remind: d => `⏰ Reminder set ${d} days before`, remindFail: '⚠️ Reminder could not be created', est: 'estimated, please check', ref: 'Reference', nr: 'No.', markPaid: 'Done:',\n    remHead: '⏰ *Due soon*', weekHead: '🗓 *Weekly overview*',\n    typ: { rechnung: 'Invoices', mahnung: 'Reminders', behoerde: 'Authorities', steuer: 'Tax', versicherung: 'Insurance', vertrag: 'Contracts', bank: 'Bank', arzt: 'Health', miete: 'Housing', schule: 'School', werbung: 'Ads', sonstiges: 'Other' },\n  },\n};\nconst esc = s => String(s == null ? '' : s).replace(/[*_~`]/g, '').replace(/\\s+/g, ' ').trim();\nconst euro = n => { const [a, b] = Math.abs(n).toFixed(2).split('.'); return (n < 0 ? '-' : '') + a.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.') + ',' + b + ' €'; };\nconst dmy = iso => iso ? iso.slice(8, 10) + '.' + iso.slice(5, 7) + '.' + iso.slice(0, 4) : '';\nconst todayISO = () => { try { return new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Berlin' }); } catch (e) { return new Date().toISOString().slice(0, 10); } };\nconst dayDiff = iso => Math.round((Date.UTC(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)) - Date.UTC(+todayISO().slice(0, 4), +todayISO().slice(5, 7) - 1, +todayISO().slice(8, 10))) / 864e5);\nconst light = d => d == null ? '⚪' : d <= 0 ? '🔴' : d <= 3 ? '🟠' : d <= 14 ? '🟡' : '🟢';\nconst when = (t, d) => d < 0 ? t.overdue(d) : d === 0 ? t.today : d === 1 ? t.tomorrow : t.inDays(d);\n\nconst sd = $getWorkflowStaticData('global');\nsd.docs = sd.docs || []; sd.n = sd.n || 0;\nconst it = $input.first(), j = it.json, cfg = j.cfg, t = L[cfg.sprache] || L.de;\nconst base = { cfg };\nconst reply = (text, extra) => [{ json: { ...base, route: 'reply', text, ...extra } }];\nconst open = () => sd.docs.filter(d => d.frist && !d.bezahlt).sort((a, b) => a.frist < b.frist ? -1 : 1);\nconst line = d => `${light(dayDiff(d.frist))} *${d.n}* · ${esc(d.absender)}${d.betrag ? ' · ' + euro(d.betrag) : ''} · ${dmy(d.frist)} (${when(t, dayDiff(d.frist))})`;\n\n// ⏰ Zeitplan: tägliche Erinnerung\nif (!j.body && !j.headers) {\n  const chatId = cfg.erlaubteChats.find(x => /@g\\.us$/.test(x)) || sd.owner || sd.chat; if (!chatId) return [];\n  const o = open(), soon = o.filter(d => dayDiff(d.frist) <= cfg.erinnerungTage);\n  const monday = new Date().toLocaleDateString('en-US', { timeZone: 'Europe/Berlin', weekday: 'short' }) === 'Mon';\n  let text = '';\n  if (soon.length) text = t.remHead + '\\n' + soon.map(line).join('\\n') + `\\n\\n${t.markPaid} /bezahlt ${o[0].n}`;\n  else if (monday && o.length) text = t.weekHead + '\\n' + o.slice(0, 10).map(line).join('\\n');\n  if (!text) return [];\n  return reply(text, { src: 'waha', chatId });\n}\n\n// 🌐 Web-Upload (zum Testen oder für eigene Apps)\nif (j.headers && !(j.body && j.body.event && j.body.payload)) {\n  if (!cfg.webToken || (j.headers['x-token'] || '') !== cfg.webToken) return reply('forbidden', { src: 'web', code: 403 });\n  if (!it.binary || !Object.keys(it.binary).length) return reply(t.unsupported, { src: 'web', code: 400 });\n  return [{ json: { ...base, route: 'webFile', src: 'web', chatId: 'web' }, binary: it.binary }];\n}\n\n// 💬 WhatsApp (WAHA-Webhook)\nconst ev = j.body || {}, p = ev.payload || {};\nif (!/^message(\\.any)?$/.test(ev.event || '') || !p.from) return [];\nconst meId = (ev.me && ev.me.id) || '';\nconst isGroup = /@g\\.us$/.test(p.from || '');\nif (/@(broadcast|newsletter)$/.test(p.from || '')) return [];\n// \"Notizen an mich\": eigene Nachricht an den eigenen Chat (fromMe, Ziel = ich selbst)\nconst self = !!p.fromMe && !!meId && (p.from === meId || p.to === meId);\nif (p.fromMe && !self && !isGroup) return [];\nconst chatId = self ? meId : p.from;\nconst cmd = /^\\/?(offen|open|aperte|hilfe|help|aiuto|start|(bezahlt|erledigt|fatto|done|paid)\\s+#?\\d+)\\s*$/i.test(String(p.body || '').trim());\n// In Gruppen und im Selbst-Chat nur Fotos/PDFs und Befehle beachten (eigene Bot-Antworten und Gruppengespräche werden ignoriert)\nif ((self || isGroup) && !(p.hasMedia || cmd)) return [];\nif (self && !cfg.erlaubteChats.length) sd.owner = sd.owner || chatId; // Besitzer = eigener Chat\n// Gruppen müssen in erlaubteChats stehen; alle Mitglieder der Gruppe dürfen dann Briefe schicken\nconst allowed = cfg.erlaubteChats.length ? (cfg.erlaubteChats.includes(chatId) || (self && cfg.erlaubteChats.includes(meId))) : (!isGroup && self && sd.owner === chatId);\nif (!allowed) return []; // Fremde werden still ignoriert (wichtig, wenn die eigene Nummer verbunden ist)\nsd.chat = chatId;\nconst txt = String(p.body || '').trim().toLowerCase().replace(/^\\//, '');\nconst mime = String((p.media && p.media.mimetype) || '').toLowerCase();\nif (p.hasMedia && p.media && p.media.url && (/^image\\//.test(mime) || mime === 'application/pdf')) {\n  const u = String(p.media.url), i = u.indexOf('/api/');\n  return [{ json: { ...base, route: 'wahaFile', src: 'waha', chatId, mime, mediaUrl: cfg.wahaUrl.replace(/\\/$/, '') + (i >= 0 ? u.slice(i) : '') } }];\n}\nconst out = x => reply(x, { src: 'waha', chatId });\nif (/^(offen|open|aperte)$/.test(txt)) { const o = open(); return out(o.length ? t.openHead + '\\n' + o.map(line).join('\\n') + `\\n\\n${t.markPaid} /bezahlt ${o[0].n}` : t.noneOpen); }\nconst m = txt.match(/^(bezahlt|erledigt|fatto|done|paid)\\s+#?(\\d+)/);\nif (m) { const d = sd.docs.find(x => x.n === +m[2]); if (!d) return out(t.paidBad); d.bezahlt = true; return out(t.paidOk + `*${d.n}* · ${esc(d.absender)}`); }\nif (p.hasMedia) return out(t.unsupported);\nreturn out(t.help);\n"
   },
   "name": "Eingang prüfen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    480,
    200
   ]
  },
  {
   "parameters": {
    "rules": {
     "values": [
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "loose",
         "version": 2
        },
        "conditions": [
         {
          "id": "a3bc2209-f92b-45c8-9725-d86639cc8501",
          "leftValue": "={{ $json.route }}",
          "operator": {
           "type": "string",
           "operation": "equals"
          },
          "rightValue": "reply"
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "Direkt antworten"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "loose",
         "version": 2
        },
        "conditions": [
         {
          "id": "b7f2fe5a-8a77-45cf-9c3f-ce9593c76a8f",
          "leftValue": "={{ $json.route }}",
          "operator": {
           "type": "string",
           "operation": "equals"
          },
          "rightValue": "wahaFile"
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "WhatsApp-Datei"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "loose",
         "version": 2
        },
        "conditions": [
         {
          "id": "f7629965-8b87-4d85-94f0-50996cb52af1",
          "leftValue": "={{ $json.route }}",
          "operator": {
           "type": "string",
           "operation": "equals"
          },
          "rightValue": "webFile"
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "Upload-Datei"
      }
     ]
    },
    "options": {}
   },
   "name": "Was ist es?",
   "type": "n8n-nodes-base.switch",
   "typeVersion": 3.2,
   "position": [
    720,
    200
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "url": "={{ $json.mediaUrl }}",
    "options": {
     "response": {
      "response": {
       "responseFormat": "file",
       "outputPropertyName": "data"
      }
     },
     "timeout": 30000
    }
   },
   "name": "WAHA Datei laden",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    960,
    260
   ],
   "credentials": {
    "httpHeaderAuth": {
     "name": "Papierkram · WAHA (Header X-Api-Key)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const L = {\n  de: {\n    help: '📄 *Papierkram-Killer*\\nSchick mir ein *Foto* (oder PDF) von einem Brief – ich lese ihn, lege ihn ab und erinnere dich an die Frist.\\n\\n/offen – offene Fristen\\n/bezahlt 3 – Nr. 3 als erledigt markieren\\n/hilfe – diese Hilfe',\n    locked: '🔒 Dieser Bot ist privat.', unread: '😕 Ich konnte auf dem Bild keinen Text lesen. Bitte nochmal, gerade und gut beleuchtet.',\n    pdfScan: '😕 Das PDF ist ein Scan ohne Text. Bitte schick es als Foto.', tooBig: '😕 Datei zu groß (max. 8 MB).', unsupported: 'Bitte schick ein Foto oder PDF vom Brief.',\n    noneOpen: '🎉 Nichts offen. Papierkram-frei!', openHead: '📋 *Offene Fristen*', paidOk: '✅ Erledigt: ', paidBad: 'Diese Nummer kenne ich nicht.',\n    overdue: n => `${-n} Tag${n === -1 ? '' : 'e'} überfällig`, today: 'heute', tomorrow: 'morgen', inDays: n => `in ${n} Tagen`,\n    due: 'fällig', deadline: 'Frist', noDeadline: 'keine Frist erkannt', todo: 'Was tun', risk: 'Risiko', saved: '🗂 Abgelegt', noSave: 'Nicht abgelegt (Nextcloud nicht eingerichtet)', saveFail: '⚠️ Ablegen in Nextcloud fehlgeschlagen',\n    remind: d => `⏰ Erinnerung ${d} Tage vorher angelegt`, remindFail: '⚠️ Erinnerung konnte nicht angelegt werden', est: 'geschätzt, bitte prüfen', ref: 'Referenz', nr: 'Nr.', markPaid: 'Erledigt:',\n    remHead: '⏰ *Bald fällig*', weekHead: '🗓 *Wochenübersicht*',\n    typ: { rechnung: 'Rechnungen', mahnung: 'Mahnungen', behoerde: 'Behörden', steuer: 'Steuer', versicherung: 'Versicherung', vertrag: 'Verträge', bank: 'Bank', arzt: 'Gesundheit', miete: 'Wohnen', schule: 'Schule', werbung: 'Werbung', sonstiges: 'Sonstiges' },\n  },\n  it: {\n    help: '📄 *Papierkram-Killer*\\nMandami una *foto* (o un PDF) di una lettera: la leggo, la archivio e ti ricordo la scadenza.\\n\\n/offen – scadenze aperte\\n/bezahlt 3 – segna n. 3 come fatto\\n/hilfe – questo aiuto',\n    locked: '🔒 Questo bot è privato.', unread: '😕 Non riesco a leggere testo nell’immagine. Riprova, dritta e ben illuminata.',\n    pdfScan: '😕 Il PDF è una scansione senza testo. Mandalo come foto.', tooBig: '😕 File troppo grande (max 8 MB).', unsupported: 'Mandami una foto o un PDF della lettera.',\n    noneOpen: '🎉 Niente di aperto. Zero carte!', openHead: '📋 *Scadenze aperte*', paidOk: '✅ Fatto: ', paidBad: 'Numero sconosciuto.',\n    overdue: n => `scaduta da ${-n} giorn${n === -1 ? 'o' : 'i'}`, today: 'oggi', tomorrow: 'domani', inDays: n => `tra ${n} giorni`,\n    due: 'scade', deadline: 'Scadenza', noDeadline: 'nessuna scadenza trovata', todo: 'Cosa fare', risk: 'Rischio', saved: '🗂 Archiviata', noSave: 'Non archiviata (Nextcloud non configurato)', saveFail: '⚠️ Archiviazione su Nextcloud fallita',\n    remind: d => `⏰ Promemoria creato ${d} giorni prima`, remindFail: '⚠️ Promemoria non creato', est: 'stimata, da verificare', ref: 'Riferimento', nr: 'N.', markPaid: 'Fatto:',\n    remHead: '⏰ *In scadenza*', weekHead: '🗓 *Panoramica settimanale*',\n    typ: { rechnung: 'Fatture', mahnung: 'Solleciti', behoerde: 'Enti', steuer: 'Tasse', versicherung: 'Assicurazioni', vertrag: 'Contratti', bank: 'Banca', arzt: 'Salute', miete: 'Casa', schule: 'Scuola', werbung: 'Pubblicità', sonstiges: 'Altro' },\n  },\n  en: {\n    help: '📄 *Papierkram-Killer*\\nSend me a *photo* (or PDF) of a letter – I read it, file it and remind you of the deadline.\\n\\n/offen – open deadlines\\n/bezahlt 3 – mark no. 3 as done\\n/hilfe – this help',\n    locked: '🔒 This bot is private.', unread: '😕 I could not read any text in the image. Please retry, straight and well lit.',\n    pdfScan: '😕 The PDF is a scan without text. Please send it as a photo.', tooBig: '😕 File too large (max 8 MB).', unsupported: 'Please send a photo or PDF of the letter.',\n    noneOpen: '🎉 Nothing open. Paper-free!', openHead: '📋 *Open deadlines*', paidOk: '✅ Done: ', paidBad: 'I do not know that number.',\n    overdue: n => `${-n} day${n === -1 ? '' : 's'} overdue`, today: 'today', tomorrow: 'tomorrow', inDays: n => `in ${n} days`,\n    due: 'due', deadline: 'Deadline', noDeadline: 'no deadline found', todo: 'To do', risk: 'Risk', saved: '🗂 Filed', noSave: 'Not filed (Nextcloud not set up)', saveFail: '⚠️ Filing to Nextcloud failed',\n    remind: d => `⏰ Reminder set ${d} days before`, remindFail: '⚠️ Reminder could not be created', est: 'estimated, please check', ref: 'Reference', nr: 'No.', markPaid: 'Done:',\n    remHead: '⏰ *Due soon*', weekHead: '🗓 *Weekly overview*',\n    typ: { rechnung: 'Invoices', mahnung: 'Reminders', behoerde: 'Authorities', steuer: 'Tax', versicherung: 'Insurance', vertrag: 'Contracts', bank: 'Bank', arzt: 'Health', miete: 'Housing', schule: 'School', werbung: 'Ads', sonstiges: 'Other' },\n  },\n};\nconst esc = s => String(s == null ? '' : s).replace(/[*_~`]/g, '').replace(/\\s+/g, ' ').trim();\nconst euro = n => { const [a, b] = Math.abs(n).toFixed(2).split('.'); return (n < 0 ? '-' : '') + a.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.') + ',' + b + ' €'; };\nconst dmy = iso => iso ? iso.slice(8, 10) + '.' + iso.slice(5, 7) + '.' + iso.slice(0, 4) : '';\nconst todayISO = () => { try { return new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Berlin' }); } catch (e) { return new Date().toISOString().slice(0, 10); } };\nconst dayDiff = iso => Math.round((Date.UTC(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)) - Date.UTC(+todayISO().slice(0, 4), +todayISO().slice(5, 7) - 1, +todayISO().slice(8, 10))) / 864e5);\nconst light = d => d == null ? '⚪' : d <= 0 ? '🔴' : d <= 3 ? '🟠' : d <= 14 ? '🟡' : '🟢';\nconst when = (t, d) => d < 0 ? t.overdue(d) : d === 0 ? t.today : d === 1 ? t.tomorrow : t.inDays(d);\n\nconst ctx = $('Eingang prüfen').first().json, cfg = ctx.cfg, t = L[cfg.sprache] || L.de;\nconst it = $input.first(), bk = Object.keys(it.binary || {})[0];\nconst fail = text => [{ json: { ...ctx, route: 'reply', text, code: 400 } }];\nif (!bk) return fail(t.unsupported);\nconst b = it.binary[bk];\nlet mime = String(b.mimeType || ctx.mime || '').toLowerCase();\nconst fn = String(b.fileName || '').toLowerCase();\nif (!/^(image\\/|application\\/pdf)/.test(mime)) mime = /\\.pdf$/.test(fn) ? 'application/pdf' : /\\.png$/.test(fn) ? 'image/png' : /\\.(jpe?g)$/.test(fn) ? 'image/jpeg' : /\\.webp$/.test(fn) ? 'image/webp' : mime;\nconst isPdf = mime === 'application/pdf';\nif (!isPdf && !/^image\\//.test(mime)) return fail(t.unsupported);\nconst buf = await this.helpers.getBinaryDataBuffer(0, bk);\nif (buf.length > 8 * 1024 * 1024) return fail(t.tooBig);\nconst ext = isPdf ? 'pdf' : (mime.split('/')[1] || 'jpg').replace('jpeg', 'jpg');\nconst json = { ...ctx, route: 'ok', isPdf, mime, ext };\nif (!isPdf) json.ocrBody = { model: cfg.ocrModel, max_tokens: 2500, temperature: 0, messages: [{ role: 'user', content: [{ type: 'image_url', image_url: { url: `data:${mime};base64,${buf.toString('base64')}` } }] }] };\nreturn [{ json, binary: { data: { ...b, mimeType: mime, fileName: 'brief.' + ext } } }];\n"
   },
   "name": "Bild vorbereiten",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1200,
    320
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "61ced702-4c67-447b-89e0-a064ffc22fe1",
       "leftValue": "={{ $json.route }}",
       "operator": {
        "type": "string",
        "operation": "equals"
       },
       "rightValue": "reply"
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Fehler?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1440,
    320
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "f4d519a4-7010-4973-9b77-4b63c950cf50",
       "leftValue": "={{ $json.isPdf }}",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "PDF?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1680,
    380
   ]
  },
  {
   "parameters": {
    "operation": "pdf",
    "binaryPropertyName": "data",
    "options": {}
   },
   "name": "PDF lesen",
   "type": "n8n-nodes-base.extractFromFile",
   "typeVersion": 1,
   "position": [
    1920,
    300
   ],
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "method": "POST",
    "url": "={{ $json.cfg.apiBase }}/chat/completions",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($json.ocrBody) }}",
    "options": {
     "timeout": 120000
    }
   },
   "name": "Texterkennung (OCR)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1920,
    460
   ],
   "credentials": {
    "httpHeaderAuth": {
     "name": "Papierkram · KI-API (Header Authorization = Bearer …)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const L = {\n  de: {\n    help: '📄 *Papierkram-Killer*\\nSchick mir ein *Foto* (oder PDF) von einem Brief – ich lese ihn, lege ihn ab und erinnere dich an die Frist.\\n\\n/offen – offene Fristen\\n/bezahlt 3 – Nr. 3 als erledigt markieren\\n/hilfe – diese Hilfe',\n    locked: '🔒 Dieser Bot ist privat.', unread: '😕 Ich konnte auf dem Bild keinen Text lesen. Bitte nochmal, gerade und gut beleuchtet.',\n    pdfScan: '😕 Das PDF ist ein Scan ohne Text. Bitte schick es als Foto.', tooBig: '😕 Datei zu groß (max. 8 MB).', unsupported: 'Bitte schick ein Foto oder PDF vom Brief.',\n    noneOpen: '🎉 Nichts offen. Papierkram-frei!', openHead: '📋 *Offene Fristen*', paidOk: '✅ Erledigt: ', paidBad: 'Diese Nummer kenne ich nicht.',\n    overdue: n => `${-n} Tag${n === -1 ? '' : 'e'} überfällig`, today: 'heute', tomorrow: 'morgen', inDays: n => `in ${n} Tagen`,\n    due: 'fällig', deadline: 'Frist', noDeadline: 'keine Frist erkannt', todo: 'Was tun', risk: 'Risiko', saved: '🗂 Abgelegt', noSave: 'Nicht abgelegt (Nextcloud nicht eingerichtet)', saveFail: '⚠️ Ablegen in Nextcloud fehlgeschlagen',\n    remind: d => `⏰ Erinnerung ${d} Tage vorher angelegt`, remindFail: '⚠️ Erinnerung konnte nicht angelegt werden', est: 'geschätzt, bitte prüfen', ref: 'Referenz', nr: 'Nr.', markPaid: 'Erledigt:',\n    remHead: '⏰ *Bald fällig*', weekHead: '🗓 *Wochenübersicht*',\n    typ: { rechnung: 'Rechnungen', mahnung: 'Mahnungen', behoerde: 'Behörden', steuer: 'Steuer', versicherung: 'Versicherung', vertrag: 'Verträge', bank: 'Bank', arzt: 'Gesundheit', miete: 'Wohnen', schule: 'Schule', werbung: 'Werbung', sonstiges: 'Sonstiges' },\n  },\n  it: {\n    help: '📄 *Papierkram-Killer*\\nMandami una *foto* (o un PDF) di una lettera: la leggo, la archivio e ti ricordo la scadenza.\\n\\n/offen – scadenze aperte\\n/bezahlt 3 – segna n. 3 come fatto\\n/hilfe – questo aiuto',\n    locked: '🔒 Questo bot è privato.', unread: '😕 Non riesco a leggere testo nell’immagine. Riprova, dritta e ben illuminata.',\n    pdfScan: '😕 Il PDF è una scansione senza testo. Mandalo come foto.', tooBig: '😕 File troppo grande (max 8 MB).', unsupported: 'Mandami una foto o un PDF della lettera.',\n    noneOpen: '🎉 Niente di aperto. Zero carte!', openHead: '📋 *Scadenze aperte*', paidOk: '✅ Fatto: ', paidBad: 'Numero sconosciuto.',\n    overdue: n => `scaduta da ${-n} giorn${n === -1 ? 'o' : 'i'}`, today: 'oggi', tomorrow: 'domani', inDays: n => `tra ${n} giorni`,\n    due: 'scade', deadline: 'Scadenza', noDeadline: 'nessuna scadenza trovata', todo: 'Cosa fare', risk: 'Rischio', saved: '🗂 Archiviata', noSave: 'Non archiviata (Nextcloud non configurato)', saveFail: '⚠️ Archiviazione su Nextcloud fallita',\n    remind: d => `⏰ Promemoria creato ${d} giorni prima`, remindFail: '⚠️ Promemoria non creato', est: 'stimata, da verificare', ref: 'Riferimento', nr: 'N.', markPaid: 'Fatto:',\n    remHead: '⏰ *In scadenza*', weekHead: '🗓 *Panoramica settimanale*',\n    typ: { rechnung: 'Fatture', mahnung: 'Solleciti', behoerde: 'Enti', steuer: 'Tasse', versicherung: 'Assicurazioni', vertrag: 'Contratti', bank: 'Banca', arzt: 'Salute', miete: 'Casa', schule: 'Scuola', werbung: 'Pubblicità', sonstiges: 'Altro' },\n  },\n  en: {\n    help: '📄 *Papierkram-Killer*\\nSend me a *photo* (or PDF) of a letter – I read it, file it and remind you of the deadline.\\n\\n/offen – open deadlines\\n/bezahlt 3 – mark no. 3 as done\\n/hilfe – this help',\n    locked: '🔒 This bot is private.', unread: '😕 I could not read any text in the image. Please retry, straight and well lit.',\n    pdfScan: '😕 The PDF is a scan without text. Please send it as a photo.', tooBig: '😕 File too large (max 8 MB).', unsupported: 'Please send a photo or PDF of the letter.',\n    noneOpen: '🎉 Nothing open. Paper-free!', openHead: '📋 *Open deadlines*', paidOk: '✅ Done: ', paidBad: 'I do not know that number.',\n    overdue: n => `${-n} day${n === -1 ? '' : 's'} overdue`, today: 'today', tomorrow: 'tomorrow', inDays: n => `in ${n} days`,\n    due: 'due', deadline: 'Deadline', noDeadline: 'no deadline found', todo: 'To do', risk: 'Risk', saved: '🗂 Filed', noSave: 'Not filed (Nextcloud not set up)', saveFail: '⚠️ Filing to Nextcloud failed',\n    remind: d => `⏰ Reminder set ${d} days before`, remindFail: '⚠️ Reminder could not be created', est: 'estimated, please check', ref: 'Reference', nr: 'No.', markPaid: 'Done:',\n    remHead: '⏰ *Due soon*', weekHead: '🗓 *Weekly overview*',\n    typ: { rechnung: 'Invoices', mahnung: 'Reminders', behoerde: 'Authorities', steuer: 'Tax', versicherung: 'Insurance', vertrag: 'Contracts', bank: 'Bank', arzt: 'Health', miete: 'Housing', schule: 'School', werbung: 'Ads', sonstiges: 'Other' },\n  },\n};\nconst esc = s => String(s == null ? '' : s).replace(/[*_~`]/g, '').replace(/\\s+/g, ' ').trim();\nconst euro = n => { const [a, b] = Math.abs(n).toFixed(2).split('.'); return (n < 0 ? '-' : '') + a.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.') + ',' + b + ' €'; };\nconst dmy = iso => iso ? iso.slice(8, 10) + '.' + iso.slice(5, 7) + '.' + iso.slice(0, 4) : '';\nconst todayISO = () => { try { return new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Berlin' }); } catch (e) { return new Date().toISOString().slice(0, 10); } };\nconst dayDiff = iso => Math.round((Date.UTC(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)) - Date.UTC(+todayISO().slice(0, 4), +todayISO().slice(5, 7) - 1, +todayISO().slice(8, 10))) / 864e5);\nconst light = d => d == null ? '⚪' : d <= 0 ? '🔴' : d <= 3 ? '🟠' : d <= 14 ? '🟡' : '🟢';\nconst when = (t, d) => d < 0 ? t.overdue(d) : d === 0 ? t.today : d === 1 ? t.tomorrow : t.inDays(d);\n\nconst ctx = $('Bild vorbereiten').first().json, cfg = ctx.cfg, t = L[cfg.sprache] || L.de;\nconst r = $input.first().json;\nlet text = ctx.isPdf ? String(r.text || '') : String((((r.choices || [])[0] || {}).message || {}).content || '');\ntext = text.replace(/```[a-z]*/g, '').replace(/[ \\t]+\\n/g, '\\n').replace(/\\n{3,}/g, '\\n\\n').trim().slice(0, 7000);\nif (text.length < 25) return [{ json: { ...ctx, route: 'reply', text: ctx.isPdf ? t.pdfScan : t.unread, code: 422 } }];\nconst langName = { de: 'Deutsch', it: 'Italiano', en: 'English' }[cfg.sprache] || 'Deutsch';\nconst system = `Du bist ein präziser Assistent für Briefe, Rechnungen und Behördenpost (Deutschland, Österreich, Schweiz, Italien). Heute ist ${new Date().toISOString().slice(0, 10)}. Lies den Brieftext und antworte NUR mit einem JSON-Objekt, ohne Erklärung, mit genau diesen Feldern:\n{\"absender\": \"Name der Firma/Behörde, kurz\",\n \"typ\": \"rechnung|mahnung|behoerde|steuer|versicherung|vertrag|bank|arzt|miete|schule|werbung|sonstiges\",\n \"betreff\": \"Worum geht es, max. 8 Wörter\",\n \"datum\": \"Briefdatum als YYYY-MM-DD oder null\",\n \"frist\": \"Zahlungs-/Antwort-/Widerspruchsfrist als YYYY-MM-DD oder null – nur wenn im Text ausdrücklich genannt\",\n \"betrag\": \"zu zahlender Betrag als Zahl (Punkt als Dezimaltrenner) oder null\",\n \"iban\": \"IBAN für die Zahlung oder null\",\n \"referenz\": \"Rechnungs-/Aktenzeichen/Kundennummer oder null\",\n \"zusammenfassung\": \"2 kurze Sätze in einfacher Sprache: was will der Absender?\",\n \"aktion\": \"1 Satz: was soll der Empfänger jetzt tun? Bei reiner Information: 'Nichts zu tun.'\",\n \"risiko\": \"Folge bei Nichtstun (z. B. Mahngebühren) oder null\"}\nErfinde nichts: Fehlt eine Angabe im Text, setze null. zusammenfassung, aktion und risiko schreibst du auf ${langName}.`;\nreturn [{ json: { ...ctx, ocrText: text, llmBody: { model: cfg.llmModel, temperature: 0, max_tokens: 900, response_format: { type: 'json_object' }, messages: [{ role: 'system', content: system }, { role: 'user', content: text }] } }, binary: $('Bild vorbereiten').first().binary }];\n"
   },
   "name": "Text sammeln",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2160,
    380
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "526a2d79-040f-49ff-af7b-4aa6275aa803",
       "leftValue": "={{ $json.route }}",
       "operator": {
        "type": "string",
        "operation": "equals"
       },
       "rightValue": "reply"
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Lesbar?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2400,
    380
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "method": "POST",
    "url": "={{ $json.cfg.apiBase }}/chat/completions",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($json.llmBody) }}",
    "options": {
     "timeout": 90000
    }
   },
   "name": "Brief analysieren (KI)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2640,
    440
   ],
   "credentials": {
    "httpHeaderAuth": {
     "name": "Papierkram · KI-API (Header Authorization = Bearer …)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const L = {\n  de: {\n    help: '📄 *Papierkram-Killer*\\nSchick mir ein *Foto* (oder PDF) von einem Brief – ich lese ihn, lege ihn ab und erinnere dich an die Frist.\\n\\n/offen – offene Fristen\\n/bezahlt 3 – Nr. 3 als erledigt markieren\\n/hilfe – diese Hilfe',\n    locked: '🔒 Dieser Bot ist privat.', unread: '😕 Ich konnte auf dem Bild keinen Text lesen. Bitte nochmal, gerade und gut beleuchtet.',\n    pdfScan: '😕 Das PDF ist ein Scan ohne Text. Bitte schick es als Foto.', tooBig: '😕 Datei zu groß (max. 8 MB).', unsupported: 'Bitte schick ein Foto oder PDF vom Brief.',\n    noneOpen: '🎉 Nichts offen. Papierkram-frei!', openHead: '📋 *Offene Fristen*', paidOk: '✅ Erledigt: ', paidBad: 'Diese Nummer kenne ich nicht.',\n    overdue: n => `${-n} Tag${n === -1 ? '' : 'e'} überfällig`, today: 'heute', tomorrow: 'morgen', inDays: n => `in ${n} Tagen`,\n    due: 'fällig', deadline: 'Frist', noDeadline: 'keine Frist erkannt', todo: 'Was tun', risk: 'Risiko', saved: '🗂 Abgelegt', noSave: 'Nicht abgelegt (Nextcloud nicht eingerichtet)', saveFail: '⚠️ Ablegen in Nextcloud fehlgeschlagen',\n    remind: d => `⏰ Erinnerung ${d} Tage vorher angelegt`, remindFail: '⚠️ Erinnerung konnte nicht angelegt werden', est: 'geschätzt, bitte prüfen', ref: 'Referenz', nr: 'Nr.', markPaid: 'Erledigt:',\n    remHead: '⏰ *Bald fällig*', weekHead: '🗓 *Wochenübersicht*',\n    typ: { rechnung: 'Rechnungen', mahnung: 'Mahnungen', behoerde: 'Behörden', steuer: 'Steuer', versicherung: 'Versicherung', vertrag: 'Verträge', bank: 'Bank', arzt: 'Gesundheit', miete: 'Wohnen', schule: 'Schule', werbung: 'Werbung', sonstiges: 'Sonstiges' },\n  },\n  it: {\n    help: '📄 *Papierkram-Killer*\\nMandami una *foto* (o un PDF) di una lettera: la leggo, la archivio e ti ricordo la scadenza.\\n\\n/offen – scadenze aperte\\n/bezahlt 3 – segna n. 3 come fatto\\n/hilfe – questo aiuto',\n    locked: '🔒 Questo bot è privato.', unread: '😕 Non riesco a leggere testo nell’immagine. Riprova, dritta e ben illuminata.',\n    pdfScan: '😕 Il PDF è una scansione senza testo. Mandalo come foto.', tooBig: '😕 File troppo grande (max 8 MB).', unsupported: 'Mandami una foto o un PDF della lettera.',\n    noneOpen: '🎉 Niente di aperto. Zero carte!', openHead: '📋 *Scadenze aperte*', paidOk: '✅ Fatto: ', paidBad: 'Numero sconosciuto.',\n    overdue: n => `scaduta da ${-n} giorn${n === -1 ? 'o' : 'i'}`, today: 'oggi', tomorrow: 'domani', inDays: n => `tra ${n} giorni`,\n    due: 'scade', deadline: 'Scadenza', noDeadline: 'nessuna scadenza trovata', todo: 'Cosa fare', risk: 'Rischio', saved: '🗂 Archiviata', noSave: 'Non archiviata (Nextcloud non configurato)', saveFail: '⚠️ Archiviazione su Nextcloud fallita',\n    remind: d => `⏰ Promemoria creato ${d} giorni prima`, remindFail: '⚠️ Promemoria non creato', est: 'stimata, da verificare', ref: 'Riferimento', nr: 'N.', markPaid: 'Fatto:',\n    remHead: '⏰ *In scadenza*', weekHead: '🗓 *Panoramica settimanale*',\n    typ: { rechnung: 'Fatture', mahnung: 'Solleciti', behoerde: 'Enti', steuer: 'Tasse', versicherung: 'Assicurazioni', vertrag: 'Contratti', bank: 'Banca', arzt: 'Salute', miete: 'Casa', schule: 'Scuola', werbung: 'Pubblicità', sonstiges: 'Altro' },\n  },\n  en: {\n    help: '📄 *Papierkram-Killer*\\nSend me a *photo* (or PDF) of a letter – I read it, file it and remind you of the deadline.\\n\\n/offen – open deadlines\\n/bezahlt 3 – mark no. 3 as done\\n/hilfe – this help',\n    locked: '🔒 This bot is private.', unread: '😕 I could not read any text in the image. Please retry, straight and well lit.',\n    pdfScan: '😕 The PDF is a scan without text. Please send it as a photo.', tooBig: '😕 File too large (max 8 MB).', unsupported: 'Please send a photo or PDF of the letter.',\n    noneOpen: '🎉 Nothing open. Paper-free!', openHead: '📋 *Open deadlines*', paidOk: '✅ Done: ', paidBad: 'I do not know that number.',\n    overdue: n => `${-n} day${n === -1 ? '' : 's'} overdue`, today: 'today', tomorrow: 'tomorrow', inDays: n => `in ${n} days`,\n    due: 'due', deadline: 'Deadline', noDeadline: 'no deadline found', todo: 'To do', risk: 'Risk', saved: '🗂 Filed', noSave: 'Not filed (Nextcloud not set up)', saveFail: '⚠️ Filing to Nextcloud failed',\n    remind: d => `⏰ Reminder set ${d} days before`, remindFail: '⚠️ Reminder could not be created', est: 'estimated, please check', ref: 'Reference', nr: 'No.', markPaid: 'Done:',\n    remHead: '⏰ *Due soon*', weekHead: '🗓 *Weekly overview*',\n    typ: { rechnung: 'Invoices', mahnung: 'Reminders', behoerde: 'Authorities', steuer: 'Tax', versicherung: 'Insurance', vertrag: 'Contracts', bank: 'Bank', arzt: 'Health', miete: 'Housing', schule: 'School', werbung: 'Ads', sonstiges: 'Other' },\n  },\n};\nconst esc = s => String(s == null ? '' : s).replace(/[*_~`]/g, '').replace(/\\s+/g, ' ').trim();\nconst euro = n => { const [a, b] = Math.abs(n).toFixed(2).split('.'); return (n < 0 ? '-' : '') + a.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.') + ',' + b + ' €'; };\nconst dmy = iso => iso ? iso.slice(8, 10) + '.' + iso.slice(5, 7) + '.' + iso.slice(0, 4) : '';\nconst todayISO = () => { try { return new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Berlin' }); } catch (e) { return new Date().toISOString().slice(0, 10); } };\nconst dayDiff = iso => Math.round((Date.UTC(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)) - Date.UTC(+todayISO().slice(0, 4), +todayISO().slice(5, 7) - 1, +todayISO().slice(8, 10))) / 864e5);\nconst light = d => d == null ? '⚪' : d <= 0 ? '🔴' : d <= 3 ? '🟠' : d <= 14 ? '🟡' : '🟢';\nconst when = (t, d) => d < 0 ? t.overdue(d) : d === 0 ? t.today : d === 1 ? t.tomorrow : t.inDays(d);\n\nconst ctx = $('Text sammeln').first().json, cfg = ctx.cfg, t = L[cfg.sprache] || L.de, text = ctx.ocrText;\nconst sd = $getWorkflowStaticData('global'); sd.docs = sd.docs || []; sd.n = sd.n || 0;\nconst raw = String((((($input.first().json.choices || [])[0]) || {}).message || {}).content || '');\nlet a = {}; try { a = JSON.parse(raw.slice(raw.indexOf('{'), raw.lastIndexOf('}') + 1)); } catch (e) { a = {}; }\nconst TYPES = Object.keys(t.typ), str = (v, n) => (v == null || v === 'null' ? '' : String(v)).replace(/\\s+/g, ' ').trim().slice(0, n);\nconst isoOK = s => /^\\d{4}-\\d{2}-\\d{2}$/.test(s || '') && !isNaN(Date.parse(s));\nconst fromDMY = (d, m, y) => { y = +y < 100 ? 2000 + +y : +y; const s = `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`; return isoOK(s) ? s : ''; };\nconst inText = iso => { const [y, m, d] = iso.split('-'); return [`${+d}.${+m}.${y}`, `${d}.${m}.${y}`, `${+d}.${+m}.${y.slice(2)}`, `${d}.${m}.${y.slice(2)}`, iso, `${+d}/${+m}/${y}`, `${d}/${m}/${y}`].some(x => text.includes(x)) || new RegExp(`${+d}\\\\.?\\\\s*(Januar|Februar|März|April|Mai|Juni|Juli|August|September|Oktober|November|Dezember|gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre)\\\\s+${y}`, 'i').test(text); };\nconst addDays = (iso, n) => new Date(Date.parse(iso) + n * 864e5).toISOString().slice(0, 10);\n\n// Typ\nlet typ = TYPES.includes(a.typ) ? a.typ : 'sonstiges';\nif (/(?<!keine\\s)(?<!Mahngebühr\\w*\\s)\\bMahnung|Zahlungserinnerung|Inkasso|Zwangsvollstreckung|Vollstreckungs(?:bescheid|ankündigung)|sollecito di pagamento|diffida ad adempiere|ingiunzione di pagamento/i.test(text) && ['rechnung', 'sonstiges', 'vertrag'].includes(typ)) typ = 'mahnung';\n\n// Datum + Frist: Modell, aber nur wenn im Text belegt – sonst Regeln\nlet datum = isoOK(a.datum) && inText(a.datum) ? a.datum : '';\nif (!datum) { const m = text.match(/(\\d{1,2})\\.(\\d{1,2})\\.(\\d{4})/); if (m) datum = fromDMY(m[1], m[2], m[3]); }\nlet frist = isoOK(a.frist) && inText(a.frist) ? a.frist : '', fristQuelle = frist ? 'text' : '';\nif (!frist) {\n  const re = /(?:bis(?:\\s+(?:sp[äa]testens|zum|einschlie(?:ß|ss)lich))*|sp[äa]testens(?:\\s+bis)?|f[äa]llig(?:\\s+am)?|zahlbar\\s+bis|Zahlungsziel:?|Frist:?|Zahlungsfrist:?|entro(?:\\s+il)?|scadenza:?|due(?:\\s+date)?)\\s*(?:am\\s*)?(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})/ig;\n  const m = re.exec(text); if (m) { frist = fromDMY(m[1], m[2], m[3]); if (frist) fristQuelle = 'text'; }\n}\nif (!frist && datum) {\n  const m = text.match(/innerhalb\\s+von\\s+(\\d{1,3})\\s*(Tagen|Wochen)/i) || text.match(/binnen\\s+(\\d{1,3})\\s*(giorni|settimane)/i);\n  if (m) { frist = addDays(datum, +m[1] * (/woch|settim/i.test(m[2]) ? 7 : 1)); fristQuelle = 'regel'; }\n  else if (['behoerde', 'steuer'].includes(typ) && /Rechtsbehelfsbelehrung|Einspruch|Widerspruch/i.test(text)) { frist = addDays(datum, 33); fristQuelle = 'schaetzung'; }\n}\nif (frist && (frist < addDays(todayISO(), -120) || frist > addDays(todayISO(), 800))) { frist = ''; fristQuelle = ''; }\n\n// Betrag: nur wenn im Text zu finden\nlet betrag = typeof a.betrag === 'number' ? a.betrag : parseFloat(String(a.betrag || '').replace(/[^0-9.,-]/g, '').replace(/\\.(?=\\d{3}\\b)/g, '').replace(',', '.'));\nif (!(betrag > 0 && betrag < 1e7)) betrag = 0;\nif (betrag) { const flat = text.replace(/\\s/g, ''), de = betrag.toFixed(2).replace('.', ','), de2 = de.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.'), en = betrag.toFixed(2); if (!(flat.includes(de) || flat.includes(de2) || flat.includes(en))) betrag = 0; }\n\n// IBAN prüfen (Modulo 97)\nlet iban = str(a.iban, 40).replace(/\\s/g, '').toUpperCase();\nconst ibanOK = s => /^[A-Z]{2}\\d{2}[A-Z0-9]{10,30}$/.test(s) && Number(BigInt([...(s.slice(4) + s.slice(0, 4))].map(c => /\\d/.test(c) ? c : c.charCodeAt(0) - 55).join('')) % 97n) === 1;\nif (!ibanOK(iban)) { const m = text.replace(/[ \\u00a0]/g, '').match(/[A-Z]{2}\\d{2}[A-Z0-9]{10,30}/g); iban = (m || []).find(ibanOK) || ''; }\nconst ibanFmt = iban ? iban.replace(/(.{4})/g, '$1 ').trim() : '';\n\nconst absender = str(a.absender, 60) || '?', betreff = str(a.betreff, 80), referenz = str(a.referenz, 40);\nconst days = frist ? dayDiff(frist) : null;\nconst werbung = typ === 'werbung';\nconst credit = betrag > 0 && /Guthaben|Erstattung|Gutschrift|rimborso|accredito|credit note/i.test(text) && !/Nachzahlung|Nachforderung|Restbetrag/i.test(text);\nconst sum = str(a.zusammenfassung, 300), aktion = str(a.aktion, 200), risiko = str(a.risiko, 160);\n\n// Dateiname + Ordner\nconst fold = s => s.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/Ä/g, 'Ae').replace(/Ö/g, 'Oe').replace(/Ü/g, 'Ue').replace(/ß/g, 'ss').normalize('NFD').replace(/[\\u0300-\\u036f]/g, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '');\nconst docDate = datum || todayISO(), year = docDate.slice(0, 4);\nconst base = [docDate, fold(absender).slice(0, 30) || 'Brief', fold(t.typ[typ]).slice(0, 14), betrag ? betrag.toFixed(2).replace('.', ',') + 'EUR' : ''].filter(Boolean).join('_');\nconst root = String(cfg.ordner || 'Papierkram').replace(/^\\/+|\\/+$/g, '');\nconst dirs = [root, `${root}/${year}`, `${root}/${year}/${t.typ[typ]}`];\nconst fileName = `${base}.${ctx.ext}`, txtName = `${base}.txt`;\nconst nc = cfg.nextcloudUrl.replace(/\\/$/, ''), dav = `${nc}/remote.php/dav/files/${encodeURIComponent(cfg.nextcloudUser)}/`;\nconst enc = p => p.split('/').map(encodeURIComponent).join('/');\n\n// Nextcloud-Aufgabe (VTODO) mit Erinnerung\nsd.n += 1; const n = sd.n, uid = `papierkram-${Date.now()}-${n}@n8n`;\nlet ics = '';\nif (frist && !werbung) {\n  const ev = s => s.replace(/\\\\/g, '\\\\\\\\').replace(/;/g, '\\;').replace(/,/g, '\\\\,').replace(/\\n/g, '\\\\n');\n  const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\\.\\d+/, '');\n  const desc = [sum, aktion && ('→ ' + aktion), ibanFmt && 'IBAN: ' + ibanFmt, referenz && (t.ref + ': ' + referenz), `${nc}/apps/files/?dir=/${enc(dirs[2])}`].filter(Boolean).join('\\n');\n  const head = (betrag && !credit ? '💶 ' : '📄 ') + absender + ': ' + (betrag ? euro(betrag) : betreff);\n  ics = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Papierkram-Killer//n8n//DE', 'BEGIN:VTODO', 'UID:' + uid, 'DTSTAMP:' + stamp, 'SUMMARY:' + ev(head), 'DUE;VALUE=DATE:' + frist.replace(/-/g, ''), 'DESCRIPTION:' + ev(desc), 'PRIORITY:' + (days <= 3 ? 1 : 5), 'STATUS:NEEDS-ACTION',\n    'BEGIN:VALARM', 'ACTION:DISPLAY', 'DESCRIPTION:' + ev(head), `TRIGGER;RELATED=END:-P${Math.max(0, +cfg.erinnerungTage || 0)}D`, 'END:VALARM', 'END:VTODO', 'END:VCALENDAR'].join('\\r\\n');\n}\nsd.docs.push({ n, absender, typ, betrag, frist: werbung ? '' : frist, datei: fileName, bezahlt: false, datum }); sd.docs = sd.docs.slice(-300);\n\n// Nachricht\nconst lines = [];\nlines.push(`${werbung ? '🗑' : light(days)} *${esc(absender)}* · ${esc(t.typ[typ])} · _#${n}_`);\nif (betrag || frist) lines.push([betrag ? (credit ? '💰 +' : '💶 ') + euro(betrag) : '', frist ? `📅 ${t.due} *${dmy(frist)}* (${when(t, days)})${fristQuelle === 'schaetzung' ? ' – ' + t.est : fristQuelle === 'regel' ? ' – ' + t.est : ''}` : ''].filter(Boolean).join('  ·  '));\nelse if (!werbung) lines.push('📅 ' + t.noDeadline);\nif (sum) lines.push('📝 ' + esc(sum));\nif (aktion) lines.push(`👉 *${t.todo}:* ${esc(aktion)}`);\nif (risiko) lines.push(`⚠️ ${esc(risiko)}`);\nif (ibanFmt) lines.push('🏦 ```' + ibanFmt + '```');\nif (referenz) lines.push(`🔖 ${t.ref}: ${esc(referenz)}`);\nconst message = lines.join('\\n');\nreturn [{ json: { ...ctx, parsed: { absender, typ, betreff, datum, frist, fristQuelle, betrag, iban: ibanFmt, referenz, zusammenfassung: sum, aktion, risiko, ampel: werbung ? 'grau' : days == null ? 'grau' : days <= 0 ? 'rot' : days <= 3 ? 'orange' : days <= 14 ? 'gelb' : 'gruen', tageBisFrist: days, nr: n },\n  message, nc: { on: !!(nc && cfg.nextcloudUser), dav, dirs: dirs.map(d => dav + enc(d)), fileUrl: dav + enc(dirs[2] + '/' + fileName), txtUrl: dav + enc(dirs[2] + '/' + txtName), icsUrl: ics ? `${nc}/remote.php/dav/calendars/${encodeURIComponent(cfg.nextcloudUser)}/${encodeURIComponent(cfg.kalender)}/${encodeURIComponent(uid)}.ics` : '', ics, path: dirs[2] + '/' + fileName } }, binary: $('Text sammeln').first().binary }];\n"
   },
   "name": "Auswerten",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2880,
    440
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "97a649f2-3b66-42fb-8ef4-1893ff2268b1",
       "leftValue": "={{ $json.nc.on }}",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Nextcloud?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    3120,
    440
   ]
  },
  {
   "parameters": {
    "jsCode": "// Ordner (MKCOL), dann Datei, dann Zusatz (Volltext + Aufgabe)\nconst m = $('Auswerten').first().json;\nreturn m.nc.dirs.map(url => ({ json: { url } }));\n"
   },
   "name": "Ordner planen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3360,
    380
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "method": "={{ 'MKCOL' }}",
    "url": "={{ $json.url }}",
    "options": {
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     },
     "timeout": 30000
    }
   },
   "name": "Ordner anlegen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    3600,
    380
   ],
   "credentials": {
    "httpBasicAuth": {
     "name": "Papierkram · Nextcloud (App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const m = $('Auswerten').first();\nreturn [{ json: { url: m.json.nc.fileUrl }, binary: m.binary }];\n"
   },
   "name": "Datei vorbereiten",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3840,
    380
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "method": "PUT",
    "url": "={{ $json.url }}",
    "sendBody": true,
    "contentType": "binaryData",
    "inputDataFieldName": "data",
    "options": {
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     },
     "timeout": 30000
    }
   },
   "name": "Datei ablegen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    4080,
    380
   ],
   "credentials": {
    "httpBasicAuth": {
     "name": "Papierkram · Nextcloud (App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const m = $('Auswerten').first().json;\nconst out = [{ json: { url: m.nc.txtUrl, ct: 'text/plain; charset=utf-8', body: m.ocrText, kind: 'txt' } }];\nif (m.nc.ics) out.push({ json: { url: m.nc.icsUrl, ct: 'text/calendar; charset=utf-8', body: m.nc.ics, kind: 'ics' } });\nreturn out;\n"
   },
   "name": "Zusatz planen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    4320,
    380
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "method": "PUT",
    "url": "={{ $json.url }}",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "={{ $json.ct }}",
    "body": "={{ $json.body }}",
    "options": {
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     },
     "timeout": 30000
    }
   },
   "name": "Zusatz ablegen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    4560,
    380
   ],
   "credentials": {
    "httpBasicAuth": {
     "name": "Papierkram · Nextcloud (App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "jsCode": "const L = {\n  de: {\n    help: '📄 *Papierkram-Killer*\\nSchick mir ein *Foto* (oder PDF) von einem Brief – ich lese ihn, lege ihn ab und erinnere dich an die Frist.\\n\\n/offen – offene Fristen\\n/bezahlt 3 – Nr. 3 als erledigt markieren\\n/hilfe – diese Hilfe',\n    locked: '🔒 Dieser Bot ist privat.', unread: '😕 Ich konnte auf dem Bild keinen Text lesen. Bitte nochmal, gerade und gut beleuchtet.',\n    pdfScan: '😕 Das PDF ist ein Scan ohne Text. Bitte schick es als Foto.', tooBig: '😕 Datei zu groß (max. 8 MB).', unsupported: 'Bitte schick ein Foto oder PDF vom Brief.',\n    noneOpen: '🎉 Nichts offen. Papierkram-frei!', openHead: '📋 *Offene Fristen*', paidOk: '✅ Erledigt: ', paidBad: 'Diese Nummer kenne ich nicht.',\n    overdue: n => `${-n} Tag${n === -1 ? '' : 'e'} überfällig`, today: 'heute', tomorrow: 'morgen', inDays: n => `in ${n} Tagen`,\n    due: 'fällig', deadline: 'Frist', noDeadline: 'keine Frist erkannt', todo: 'Was tun', risk: 'Risiko', saved: '🗂 Abgelegt', noSave: 'Nicht abgelegt (Nextcloud nicht eingerichtet)', saveFail: '⚠️ Ablegen in Nextcloud fehlgeschlagen',\n    remind: d => `⏰ Erinnerung ${d} Tage vorher angelegt`, remindFail: '⚠️ Erinnerung konnte nicht angelegt werden', est: 'geschätzt, bitte prüfen', ref: 'Referenz', nr: 'Nr.', markPaid: 'Erledigt:',\n    remHead: '⏰ *Bald fällig*', weekHead: '🗓 *Wochenübersicht*',\n    typ: { rechnung: 'Rechnungen', mahnung: 'Mahnungen', behoerde: 'Behörden', steuer: 'Steuer', versicherung: 'Versicherung', vertrag: 'Verträge', bank: 'Bank', arzt: 'Gesundheit', miete: 'Wohnen', schule: 'Schule', werbung: 'Werbung', sonstiges: 'Sonstiges' },\n  },\n  it: {\n    help: '📄 *Papierkram-Killer*\\nMandami una *foto* (o un PDF) di una lettera: la leggo, la archivio e ti ricordo la scadenza.\\n\\n/offen – scadenze aperte\\n/bezahlt 3 – segna n. 3 come fatto\\n/hilfe – questo aiuto',\n    locked: '🔒 Questo bot è privato.', unread: '😕 Non riesco a leggere testo nell’immagine. Riprova, dritta e ben illuminata.',\n    pdfScan: '😕 Il PDF è una scansione senza testo. Mandalo come foto.', tooBig: '😕 File troppo grande (max 8 MB).', unsupported: 'Mandami una foto o un PDF della lettera.',\n    noneOpen: '🎉 Niente di aperto. Zero carte!', openHead: '📋 *Scadenze aperte*', paidOk: '✅ Fatto: ', paidBad: 'Numero sconosciuto.',\n    overdue: n => `scaduta da ${-n} giorn${n === -1 ? 'o' : 'i'}`, today: 'oggi', tomorrow: 'domani', inDays: n => `tra ${n} giorni`,\n    due: 'scade', deadline: 'Scadenza', noDeadline: 'nessuna scadenza trovata', todo: 'Cosa fare', risk: 'Rischio', saved: '🗂 Archiviata', noSave: 'Non archiviata (Nextcloud non configurato)', saveFail: '⚠️ Archiviazione su Nextcloud fallita',\n    remind: d => `⏰ Promemoria creato ${d} giorni prima`, remindFail: '⚠️ Promemoria non creato', est: 'stimata, da verificare', ref: 'Riferimento', nr: 'N.', markPaid: 'Fatto:',\n    remHead: '⏰ *In scadenza*', weekHead: '🗓 *Panoramica settimanale*',\n    typ: { rechnung: 'Fatture', mahnung: 'Solleciti', behoerde: 'Enti', steuer: 'Tasse', versicherung: 'Assicurazioni', vertrag: 'Contratti', bank: 'Banca', arzt: 'Salute', miete: 'Casa', schule: 'Scuola', werbung: 'Pubblicità', sonstiges: 'Altro' },\n  },\n  en: {\n    help: '📄 *Papierkram-Killer*\\nSend me a *photo* (or PDF) of a letter – I read it, file it and remind you of the deadline.\\n\\n/offen – open deadlines\\n/bezahlt 3 – mark no. 3 as done\\n/hilfe – this help',\n    locked: '🔒 This bot is private.', unread: '😕 I could not read any text in the image. Please retry, straight and well lit.',\n    pdfScan: '😕 The PDF is a scan without text. Please send it as a photo.', tooBig: '😕 File too large (max 8 MB).', unsupported: 'Please send a photo or PDF of the letter.',\n    noneOpen: '🎉 Nothing open. Paper-free!', openHead: '📋 *Open deadlines*', paidOk: '✅ Done: ', paidBad: 'I do not know that number.',\n    overdue: n => `${-n} day${n === -1 ? '' : 's'} overdue`, today: 'today', tomorrow: 'tomorrow', inDays: n => `in ${n} days`,\n    due: 'due', deadline: 'Deadline', noDeadline: 'no deadline found', todo: 'To do', risk: 'Risk', saved: '🗂 Filed', noSave: 'Not filed (Nextcloud not set up)', saveFail: '⚠️ Filing to Nextcloud failed',\n    remind: d => `⏰ Reminder set ${d} days before`, remindFail: '⚠️ Reminder could not be created', est: 'estimated, please check', ref: 'Reference', nr: 'No.', markPaid: 'Done:',\n    remHead: '⏰ *Due soon*', weekHead: '🗓 *Weekly overview*',\n    typ: { rechnung: 'Invoices', mahnung: 'Reminders', behoerde: 'Authorities', steuer: 'Tax', versicherung: 'Insurance', vertrag: 'Contracts', bank: 'Bank', arzt: 'Health', miete: 'Housing', schule: 'School', werbung: 'Ads', sonstiges: 'Other' },\n  },\n};\nconst esc = s => String(s == null ? '' : s).replace(/[*_~`]/g, '').replace(/\\s+/g, ' ').trim();\nconst euro = n => { const [a, b] = Math.abs(n).toFixed(2).split('.'); return (n < 0 ? '-' : '') + a.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.') + ',' + b + ' €'; };\nconst dmy = iso => iso ? iso.slice(8, 10) + '.' + iso.slice(5, 7) + '.' + iso.slice(0, 4) : '';\nconst todayISO = () => { try { return new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Berlin' }); } catch (e) { return new Date().toISOString().slice(0, 10); } };\nconst dayDiff = iso => Math.round((Date.UTC(+iso.slice(0, 4), +iso.slice(5, 7) - 1, +iso.slice(8, 10)) - Date.UTC(+todayISO().slice(0, 4), +todayISO().slice(5, 7) - 1, +todayISO().slice(8, 10))) / 864e5);\nconst light = d => d == null ? '⚪' : d <= 0 ? '🔴' : d <= 3 ? '🟠' : d <= 14 ? '🟡' : '🟢';\nconst when = (t, d) => d < 0 ? t.overdue(d) : d === 0 ? t.today : d === 1 ? t.tomorrow : t.inDays(d);\n\nconst m = $('Auswerten').first().json, cfg = m.cfg, t = L[cfg.sprache] || L.de;\nconst ok = r => r && r.json && r.json.statusCode >= 200 && r.json.statusCode < 300;\nlet extra = [], nc = { aktiv: m.nc.on };\nif (!m.nc.on) extra.push('📭 ' + t.noSave);\nelse {\n  const f = $('Datei ablegen').first(), z = $('Zusatz ablegen').all();\n  const fileOK = ok(f), icsRes = m.nc.ics ? z[1] : null;\n  nc.datei = fileOK; nc.aufgabe = m.nc.ics ? ok(icsRes) : null;\n  extra.push(fileOK ? `${t.saved}: ` + '```' + m.nc.path + '```' : t.saveFail);\n  if (m.nc.ics) extra.push(ok(icsRes) ? t.remind(+cfg.erinnerungTage) : t.remindFail);\n}\nconst hint = m.parsed.frist && m.parsed.ampel !== 'grau' ? `\\n${t.markPaid} /bezahlt ${m.parsed.nr}` : '';\nreturn [{ json: { cfg, route: 'result', src: m.src, chatId: m.chatId, text: m.message + '\\n\\n' + extra.join('\\n') + hint, data: { ...m.parsed, nextcloud: nc, datei: m.nc.path } } }];\n"
   },
   "name": "Ergebnis",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    4800,
    440
   ]
  },
  {
   "parameters": {
    "jsCode": "const j = $input.first().json;\nconst cfg = j.cfg || $('Konfiguration').first().json.cfg;\nreturn [{ json: { cfg, src: j.src || 'web', chatId: j.chatId, text: j.text || j.reply || '', data: j.data || null, code: j.code || 200 } }];\n"
   },
   "name": "Ausliefern",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    5040,
    200
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose",
      "version": 2
     },
     "conditions": [
      {
       "id": "cdd6f58f-8f5b-4538-91e7-b6698542dcc5",
       "leftValue": "={{ $json.src }}",
       "operator": {
        "type": "string",
        "operation": "equals"
       },
       "rightValue": "waha"
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "name": "Per WhatsApp?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    5280,
    200
   ]
  },
  {
   "parameters": {
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "method": "POST",
    "url": "={{ $json.cfg.wahaUrl }}/api/sendText",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify({ session: $json.cfg.wahaSession, chatId: $json.chatId, text: $json.text }) }}",
    "options": {
     "timeout": 20000
    }
   },
   "name": "WhatsApp senden",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    5520,
    120
   ],
   "credentials": {
    "httpHeaderAuth": {
     "name": "Papierkram · WAHA (Header X-Api-Key)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "respondWith": "json",
    "responseBody": "={{ JSON.stringify({ ok: $json.code < 400, text: $json.text, data: $json.data }) }}",
    "options": {
     "responseCode": "={{ $json.code }}"
    }
   },
   "name": "Upload beantworten",
   "type": "n8n-nodes-base.respondToWebhook",
   "typeVersion": 1.1,
   "position": [
    5520,
    300
   ]
  },
  {
   "parameters": {
    "content": "## 📄 Papierkram-Killer\nBrief fotografieren → WhatsApp senden → fertig.\n\nDer Workflow **liest** den Brief (OCR), **versteht** ihn (KI), **legt ihn ab** (Nextcloud, nach Jahr/Typ benannt), **setzt die Frist als Aufgabe mit Erinnerung** und antwortet mit Ampel, Betrag, IBAN und \"Was tun\". Jeden Morgen um 8 Uhr: Erinnerung an bald fällige Briefe.\n\nBefehle in WhatsApp: `/offen` · `/bezahlt 3` · `/hilfe`\n\n_Fotos und PDFs mit Text. Keine Rechts- oder Steuerberatung._",
    "height": 380,
    "width": 480,
    "color": 6
   },
   "name": "Info",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    -20,
    -520
   ]
  },
  {
   "parameters": {
    "content": "### 🚀 Einrichten (10 Minuten)\n1. Workflow **importieren**, die 3 Zugangsdaten anlegen (siehe unten)\n2. Node **Konfiguration**: `wahaUrl`, `nextcloudUrl`, `nextcloudUser` eintragen\n3. Workflow **aktivieren**\n4. In **WAHA** den Webhook setzen: URL `…/webhook/papierkram`, Event `message`, und `WHATSAPP_DOWNLOAD_MEDIA=true`\n5. Foto eines Briefs an die WAHA-Nummer schicken\n\n### 🔑 Zugangsdaten (Header Auth / Basic Auth)\n- **KI-API**: Header `Authorization` = `Bearer <Key>` (IONOS AI Model Hub oder jede OpenAI-kompatible API)\n- **WAHA**: Header `X-Api-Key` = dein WAHA-Key\n- **Nextcloud**: Benutzer + App-Passwort (Einstellungen → Sicherheit)",
    "height": 400,
    "width": 560,
    "color": 5
   },
   "name": "Einrichten",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    240,
    -560
   ]
  },
  {
   "parameters": {
    "content": "### 🔒 Datenschutz\nDer Text jedes Briefs geht an die KI-API, die du in `apiBase` einstellst. Mit IONOS AI Model Hub bleibt alles in deutschen Rechenzentren. Wer es ganz lokal will, trägt eine eigene OpenAI-kompatible API (z. B. Ollama/vLLM) ein.\n\nDer Bot ist **privat**: der erste Chat, der schreibt, wird Besitzer (oder `erlaubteChats` setzen). Der Upload-Webhook ist ohne `webToken` gesperrt.\n\n_Fristen aus Regeln (z. B. Widerspruch = 1 Monat) sind **geschätzt** und markiert._",
    "height": 300,
    "width": 440,
    "color": 4
   },
   "name": "Datenschutz",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    840,
    -420
   ]
  }
 ],
 "connections": {
  "WhatsApp (WAHA-Webhook)": {
   "main": [
    [
     {
      "node": "Sofort 200 (WAHA)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Sofort 200 (WAHA)": {
   "main": [
    [
     {
      "node": "Konfiguration",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Upload-Webhook": {
   "main": [
    [
     {
      "node": "Konfiguration",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Täglich 8 Uhr": {
   "main": [
    [
     {
      "node": "Konfiguration",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Konfiguration": {
   "main": [
    [
     {
      "node": "Eingang prüfen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Eingang prüfen": {
   "main": [
    [
     {
      "node": "Was ist es?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Was ist es?": {
   "main": [
    [
     {
      "node": "Ausliefern",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "WAHA Datei laden",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Bild vorbereiten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "WAHA Datei laden": {
   "main": [
    [
     {
      "node": "Bild vorbereiten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Bild vorbereiten": {
   "main": [
    [
     {
      "node": "Fehler?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Fehler?": {
   "main": [
    [
     {
      "node": "Ausliefern",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "PDF?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "PDF?": {
   "main": [
    [
     {
      "node": "PDF lesen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Texterkennung (OCR)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "PDF lesen": {
   "main": [
    [
     {
      "node": "Text sammeln",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Texterkennung (OCR)": {
   "main": [
    [
     {
      "node": "Text sammeln",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Text sammeln": {
   "main": [
    [
     {
      "node": "Lesbar?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Lesbar?": {
   "main": [
    [
     {
      "node": "Ausliefern",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Brief analysieren (KI)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Brief analysieren (KI)": {
   "main": [
    [
     {
      "node": "Auswerten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Auswerten": {
   "main": [
    [
     {
      "node": "Nextcloud?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Nextcloud?": {
   "main": [
    [
     {
      "node": "Ordner planen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Ergebnis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ordner planen": {
   "main": [
    [
     {
      "node": "Ordner anlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ordner anlegen": {
   "main": [
    [
     {
      "node": "Datei vorbereiten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Datei vorbereiten": {
   "main": [
    [
     {
      "node": "Datei ablegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Datei ablegen": {
   "main": [
    [
     {
      "node": "Zusatz planen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Zusatz planen": {
   "main": [
    [
     {
      "node": "Zusatz ablegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Zusatz ablegen": {
   "main": [
    [
     {
      "node": "Ergebnis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ergebnis": {
   "main": [
    [
     {
      "node": "Ausliefern",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ausliefern": {
   "main": [
    [
     {
      "node": "Per WhatsApp?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Per WhatsApp?": {
   "main": [
    [
     {
      "node": "WhatsApp senden",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Upload beantworten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "active": false,
 "settings": {
  "executionOrder": "v1",
  "saveDataSuccessExecution": "none",
  "saveManualExecutions": false
 },
 "pinData": {},
 "tags": [],
 "meta": {
  "templateCredsSetupCompleted": true
 }
}