{
 "name": "Timesheet Guardian: working-time check with n8n Forms and Nextcloud",
 "nodes": [
  {
   "parameters": {
    "formTitle": "Zeit buchen · Book time · Registra ore",
    "formDescription": "Demo mit fiktiven Personen (Musterbüro GmbH). Die Prüfung nach ArbZG läuft sofort, Ergebnis und Wochen-Diagramm sehen Sie danach. · Demo with fictional people. The ArbZG check runs at once, you see the result and your week chart. · Demo con persone fittizie. Il controllo ArbZG parte subito.",
    "formFields": {
     "values": [
      {
       "fieldLabel": "Sprache",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Deutsch"
         },
         {
          "option": "English"
         },
         {
          "option": "Italiano"
         }
        ]
       }
      },
      {
       "fieldLabel": "Mitarbeiter",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Anna Weber"
         },
         {
          "option": "Ben Keller"
         },
         {
          "option": "Chiara Rossi"
         },
         {
          "option": "Dario Fischer"
         }
        ]
       }
      },
      {
       "fieldLabel": "Datum",
       "fieldType": "date",
       "requiredField": true
      },
      {
       "fieldLabel": "Beginn",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "05:00"
         },
         {
          "option": "05:15"
         },
         {
          "option": "05:30"
         },
         {
          "option": "05:45"
         },
         {
          "option": "06:00"
         },
         {
          "option": "06:15"
         },
         {
          "option": "06:30"
         },
         {
          "option": "06:45"
         },
         {
          "option": "07:00"
         },
         {
          "option": "07:15"
         },
         {
          "option": "07:30"
         },
         {
          "option": "07:45"
         },
         {
          "option": "08:00"
         },
         {
          "option": "08:15"
         },
         {
          "option": "08:30"
         },
         {
          "option": "08:45"
         },
         {
          "option": "09:00"
         },
         {
          "option": "09:15"
         },
         {
          "option": "09:30"
         },
         {
          "option": "09:45"
         },
         {
          "option": "10:00"
         },
         {
          "option": "10:15"
         },
         {
          "option": "10:30"
         },
         {
          "option": "10:45"
         },
         {
          "option": "11:00"
         },
         {
          "option": "11:15"
         },
         {
          "option": "11:30"
         },
         {
          "option": "11:45"
         },
         {
          "option": "12:00"
         },
         {
          "option": "12:15"
         },
         {
          "option": "12:30"
         },
         {
          "option": "12:45"
         },
         {
          "option": "13:00"
         },
         {
          "option": "13:15"
         },
         {
          "option": "13:30"
         },
         {
          "option": "13:45"
         },
         {
          "option": "14:00"
         },
         {
          "option": "14:15"
         },
         {
          "option": "14:30"
         },
         {
          "option": "14:45"
         },
         {
          "option": "15:00"
         },
         {
          "option": "15:15"
         },
         {
          "option": "15:30"
         },
         {
          "option": "15:45"
         },
         {
          "option": "16:00"
         },
         {
          "option": "16:15"
         },
         {
          "option": "16:30"
         },
         {
          "option": "16:45"
         },
         {
          "option": "17:00"
         },
         {
          "option": "17:15"
         },
         {
          "option": "17:30"
         },
         {
          "option": "17:45"
         },
         {
          "option": "18:00"
         },
         {
          "option": "18:15"
         },
         {
          "option": "18:30"
         },
         {
          "option": "18:45"
         },
         {
          "option": "19:00"
         },
         {
          "option": "19:15"
         },
         {
          "option": "19:30"
         },
         {
          "option": "19:45"
         },
         {
          "option": "20:00"
         },
         {
          "option": "20:15"
         },
         {
          "option": "20:30"
         },
         {
          "option": "20:45"
         },
         {
          "option": "21:00"
         },
         {
          "option": "21:15"
         },
         {
          "option": "21:30"
         },
         {
          "option": "21:45"
         },
         {
          "option": "22:00"
         },
         {
          "option": "22:15"
         },
         {
          "option": "22:30"
         },
         {
          "option": "22:45"
         },
         {
          "option": "23:00"
         },
         {
          "option": "23:15"
         },
         {
          "option": "23:30"
         },
         {
          "option": "23:45"
         }
        ]
       }
      },
      {
       "fieldLabel": "Ende",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "05:00"
         },
         {
          "option": "05:15"
         },
         {
          "option": "05:30"
         },
         {
          "option": "05:45"
         },
         {
          "option": "06:00"
         },
         {
          "option": "06:15"
         },
         {
          "option": "06:30"
         },
         {
          "option": "06:45"
         },
         {
          "option": "07:00"
         },
         {
          "option": "07:15"
         },
         {
          "option": "07:30"
         },
         {
          "option": "07:45"
         },
         {
          "option": "08:00"
         },
         {
          "option": "08:15"
         },
         {
          "option": "08:30"
         },
         {
          "option": "08:45"
         },
         {
          "option": "09:00"
         },
         {
          "option": "09:15"
         },
         {
          "option": "09:30"
         },
         {
          "option": "09:45"
         },
         {
          "option": "10:00"
         },
         {
          "option": "10:15"
         },
         {
          "option": "10:30"
         },
         {
          "option": "10:45"
         },
         {
          "option": "11:00"
         },
         {
          "option": "11:15"
         },
         {
          "option": "11:30"
         },
         {
          "option": "11:45"
         },
         {
          "option": "12:00"
         },
         {
          "option": "12:15"
         },
         {
          "option": "12:30"
         },
         {
          "option": "12:45"
         },
         {
          "option": "13:00"
         },
         {
          "option": "13:15"
         },
         {
          "option": "13:30"
         },
         {
          "option": "13:45"
         },
         {
          "option": "14:00"
         },
         {
          "option": "14:15"
         },
         {
          "option": "14:30"
         },
         {
          "option": "14:45"
         },
         {
          "option": "15:00"
         },
         {
          "option": "15:15"
         },
         {
          "option": "15:30"
         },
         {
          "option": "15:45"
         },
         {
          "option": "16:00"
         },
         {
          "option": "16:15"
         },
         {
          "option": "16:30"
         },
         {
          "option": "16:45"
         },
         {
          "option": "17:00"
         },
         {
          "option": "17:15"
         },
         {
          "option": "17:30"
         },
         {
          "option": "17:45"
         },
         {
          "option": "18:00"
         },
         {
          "option": "18:15"
         },
         {
          "option": "18:30"
         },
         {
          "option": "18:45"
         },
         {
          "option": "19:00"
         },
         {
          "option": "19:15"
         },
         {
          "option": "19:30"
         },
         {
          "option": "19:45"
         },
         {
          "option": "20:00"
         },
         {
          "option": "20:15"
         },
         {
          "option": "20:30"
         },
         {
          "option": "20:45"
         },
         {
          "option": "21:00"
         },
         {
          "option": "21:15"
         },
         {
          "option": "21:30"
         },
         {
          "option": "21:45"
         },
         {
          "option": "22:00"
         },
         {
          "option": "22:15"
         },
         {
          "option": "22:30"
         },
         {
          "option": "22:45"
         },
         {
          "option": "23:00"
         },
         {
          "option": "23:15"
         },
         {
          "option": "23:30"
         },
         {
          "option": "23:45"
         }
        ]
       }
      },
      {
       "fieldLabel": "Pause (Min.)",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "0"
         },
         {
          "option": "15"
         },
         {
          "option": "30"
         },
         {
          "option": "45"
         },
         {
          "option": "60"
         },
         {
          "option": "75"
         },
         {
          "option": "90"
         },
         {
          "option": "120"
         }
        ]
       }
      },
      {
       "fieldLabel": "Projekt",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Website-Relaunch"
         },
         {
          "option": "Support"
         },
         {
          "option": "Angebote"
         },
         {
          "option": "Interna"
         }
        ]
       }
      },
      {
       "fieldLabel": "Tätigkeit (optional)",
       "fieldType": "text",
       "requiredField": false,
       "placeholder": "z. B. Angebot Müller"
      }
     ]
    },
    "options": {
     "path": "zeitwaechter",
     "appendAttribution": false,
     "buttonLabel": "Buchen · Book · Registra"
    }
   },
   "id": "t1",
   "name": "Zeit buchen (Formular)",
   "type": "n8n-nodes-base.formTrigger",
   "typeVersion": 2.5,
   "position": [
    0,
    0
   ],
   "webhookId": "7d1e4a52-0c3b-4f6a-9d21-6c0000000301",
   "notes": "Öffentliches n8n-Formular. Alle Werte werden im Code-Knoten «Eingabe prüfen» erneut geprüft: Dropdowns sind nur Komfort, kein Schutz."
  },
  {
   "parameters": {
    "formTitle": "Abwesenheit melden · Report absence · Segnala assenza",
    "formDescription": "Trägt einen Ganztagstermin in den Kalender ein. Bucht die Person an so einem Tag Zeit, gibt es einen Hinweis. · Adds an all-day event. Booking time on such a day raises a hint.",
    "formFields": {
     "values": [
      {
       "fieldLabel": "Sprache",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Deutsch"
         },
         {
          "option": "English"
         },
         {
          "option": "Italiano"
         }
        ]
       }
      },
      {
       "fieldLabel": "Mitarbeiter",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Anna Weber"
         },
         {
          "option": "Ben Keller"
         },
         {
          "option": "Chiara Rossi"
         },
         {
          "option": "Dario Fischer"
         }
        ]
       }
      },
      {
       "fieldLabel": "Art",
       "fieldType": "dropdown",
       "requiredField": true,
       "fieldOptions": {
        "values": [
         {
          "option": "Urlaub"
         },
         {
          "option": "Krankheit"
         },
         {
          "option": "Gleitzeitausgleich"
         }
        ]
       }
      },
      {
       "fieldLabel": "Von",
       "fieldType": "date",
       "requiredField": true
      },
      {
       "fieldLabel": "Bis",
       "fieldType": "date",
       "requiredField": true
      }
     ]
    },
    "options": {
     "path": "zeitwaechter-abwesenheit",
     "appendAttribution": false,
     "buttonLabel": "Eintragen · Add · Aggiungi"
    }
   },
   "id": "t2",
   "name": "Abwesenheit melden (Formular)",
   "type": "n8n-nodes-base.formTrigger",
   "typeVersion": 2.5,
   "position": [
    0,
    1000
   ],
   "webhookId": "7d1e4a52-0c3b-4f6a-9d21-6c0000000302",
   "notes": "Zweites Formular: Abwesenheit → CalDAV."
  },
  {
   "parameters": {
    "httpMethod": "GET",
    "path": "zeitwaechter-bericht-CHANGE-ME",
    "responseMode": "lastNode",
    "options": {}
   },
   "id": "t3",
   "name": "Bericht per Webhook",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    1500
   ],
   "webhookId": "7d1e4a52-0c3b-4f6a-9d21-6c0000000303",
   "notes": "GET ?mode=report (Bericht jetzt) oder ?mode=seed (Demo-Daten neu). Der Pfad ist das Geheimnis: nicht veröffentlichen."
  },
  {
   "parameters": {
    "rule": {
     "interval": [
      {
       "field": "cronExpression",
       "expression": "0 15 * * 5"
      }
     ]
    }
   },
   "id": "t4",
   "name": "Freitag 15:00",
   "type": "n8n-nodes-base.scheduleTrigger",
   "typeVersion": 1.2,
   "position": [
    0,
    1700
   ],
   "notes": "Freitag 15:00: Wochenbericht."
  },
  {
   "parameters": {
    "rule": {
     "interval": [
      {
       "field": "cronExpression",
       "expression": "0 6 * * 1"
      }
     ]
    }
   },
   "id": "t5",
   "name": "Montag 06:00 (Demo zurücksetzen)",
   "type": "n8n-nodes-base.scheduleTrigger",
   "typeVersion": 1.2,
   "position": [
    0,
    1900
   ],
   "notes": "Montag 06:00: nur für die Demo gedacht. In Produktion deaktivieren."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\n// ============================================================================================================================\n//  ARBEITSBEREICH (fest verdrahtet): the only places this workflow reads or writes. Replace the placeholders in this node with your Nextcloud host, user, calendar, Talk token, Deck board and stack.\n//  Every URL of the HTTP nodes comes from here; the guard stops the run if one points anywhere else.\n// ============================================================================================================================\nconst NC = 'https://cloud.example.com';\nconst USER = 'your-user';\nconst CAL = `${NC}/remote.php/dav/calendars/${USER}/personal/`;\nconst FILES = `${NC}/remote.php/dav/files/${USER}/Zeit/`;\nconst DECK = `${NC}/index.php/apps/deck/api/v1.0/boards/1`;\nconst TALK = `${NC}/ocs/v2.php/apps/spreed/api/v1/chat/YOUR-TALK-TOKEN`;\nconst urls = { files: FILES, reports: FILES + 'Berichte/', csv: FILES + 'zeiten.csv', devices: FILES + 'geraete.json', punches: FILES + 'stempel.csv', cal: CAL, cal_new: CAL + 'zw-', deck_stacks: `${DECK}/stacks`, deck_cards: `${DECK}/stacks/1/cards`, deck_card: `${DECK}/stacks/1/cards/`, talk: TALK };\nconst ALLOWED = [CAL, FILES, DECK + '/', TALK];\nfor (const [k, u] of Object.entries(urls)) if (!ALLOWED.some(p => u.startsWith(p))) throw new Error('URL outside the work area: ' + k);\n\n// Berlin date without libraries\nconst TZ = 'Europe/Berlin';\nconst o = {}; for (const p of new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }).formatToParts(new Date())) o[p.type] = p.value;\nconst today = `${o.year}-${o.month}-${o.day}`;\nconst nowLocal = `${today}T${o.hour}:${o.minute}:${o.second}`;\n\nconst ran = n => { try { return $(n).isExecuted === true; } catch (e) { return false; } };\nlet route = 'book';\nif (ran('Stempel-Webhook (QR)')) route = 'punch';\nelse if (ran('Bericht per Webhook')) { const q = $('Bericht per Webhook').first().json.query || {}; route = q.mode === 'seed' ? 'seed' : 'report'; }\nelse if (ran('Freitag 15:00')) route = 'report';\nelse if (ran('Montag 06:00 (Demo zurücksetzen)')) route = 'seed';\nelse if (ran('Abwesenheit melden (Formular)')) route = 'absence';\nreturn [{ json: { route, today, nowLocal, nowIso: new Date().toISOString(), urls } }];"
   },
   "id": "c0",
   "name": "Demo-Bereich festlegen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    260,
    700
   ],
   "notes": "Feste URLs + Wächter + Route. Alle fünf Eingänge laufen hier durch."
  },
  {
   "parameters": {
    "rules": {
     "values": [
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "sw_book",
          "leftValue": "={{ $json.route }}",
          "rightValue": "book",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "book"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "sw_absence",
          "leftValue": "={{ $json.route }}",
          "rightValue": "absence",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "absence"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "sw_report",
          "leftValue": "={{ $json.route }}",
          "rightValue": "report",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "report"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "sw_seed",
          "leftValue": "={{ $json.route }}",
          "rightValue": "seed",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "seed"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "sw_punch",
          "leftValue": "={{ $json.route }}",
          "rightValue": "punch",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "punch"
      }
     ]
    },
    "options": {}
   },
   "id": "sw",
   "name": "Welcher Weg?",
   "type": "n8n-nodes-base.switch",
   "typeVersion": 3.2,
   "position": [
    500,
    700
   ]
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nlet lang = 'de', inp;\nif (cfg.route === 'punch') inp = $('Stempel: Zustand').last().json.book;                 // QR punch 'end': the finished day as ONE booking row\nelse { const f = $('Zeit buchen (Formular)').first().json; lang = { 'Deutsch': 'de', 'English': 'en', 'Italiano': 'it' }[f['Sprache']] || 'de';\n  inp = { person: f['Mitarbeiter'], date: f['Datum'], start: f['Beginn'], end: f['Ende'], pause: f['Pause (Min.)'], project: f['Projekt'], note: f['Tätigkeit (optional)'] }; }\nconst v = zwValidate(inp, cfg.today);\nconst d = v.entry.date;\nconst day = (v.ok ? d : cfg.today);\nconst t0 = day.replace(/-/g, ''), t1 = zwAdd(day, 1).replace(/-/g, '');\nconst report = '<?xml version=\"1.0\" encoding=\"utf-8\"?><c:calendar-query xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\"><d:prop><c:calendar-data/></d:prop>'\n  + `<c:filter><c:comp-filter name=\"VCALENDAR\"><c:comp-filter name=\"VEVENT\"><c:time-range start=\"${t0}T000000Z\" end=\"${t1}T000000Z\"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>`;\nreturn [{ json: { ok: v.ok, errors: v.errors, entry: v.entry, lang, report, html: v.ok ? '' : zwErrPage(v.errors, lang) } }];"
   },
   "id": "b1",
   "name": "Eingabe prüfen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    780,
    0
   ],
   "notes": "Validiert alles erneut (Person, Datum, Zeiten, Pause, Projekt), säubert die Notiz, baut die Kalender-Abfrage."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "b2",
       "leftValue": "={{ $json.ok === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "b2",
   "name": "Eingabe ok?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1020,
    0
   ]
  },
  {
   "parameters": {
    "method": "REPORT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.cal }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Depth",
       "value": "1"
      }
     ]
    },
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "application/xml",
    "body": "={{ $('Eingabe prüfen').first().json.report }}"
   },
   "id": "b3",
   "name": "Kalender: Abwesenheit am Tag?",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1260,
    -80
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "CalDAV REPORT: Gibt es für diesen Tag einen Abwesenheitstermin?"
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.csv }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Accept-Encoding",
       "value": "identity"
      }
     ]
    }
   },
   "id": "b4",
   "name": "CSV lesen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1500,
    0
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "Liest zeiten.csv samt ETag (404 = noch leer)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst inp = $('Eingabe prüfen').first().json;\nconst lang = inp.lang, U = ZW_UI[lang];\nconst res = $('CSV lesen').last().json;\nconst status = Number(res.statusCode);\nconst stop = (codes) => [{ json: { state: 'stop', errors: codes, html: zwErrPage(codes, lang) } }];\nlet rows = [], etag = '';\nif (status === 200) { const txt = zwBody(res); rows = zwCsvParse(txt); etag = String((res.headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); if (!rows.length && txt.replace(/\\s/g, '').length > ZW_CSV_HEAD.length + 2) return stop(['down']); }\nelse if (status !== 404) return stop(['down']);\nrows = zwRetention(rows, cfg.today, 70);\nconst e = inp.entry;\nif (rows.filter(r => String(r.created || '').slice(0, 10) === cfg.today && r.id[0] !== 'S').length >= 150) return stop(['cap']);\nif (zwOverlap(rows, e)) return stop(['overlap']);\nconst before = zwEvaluate(rows);\nconst entry = Object.assign({ id: 'W' + Date.now().toString(36) + Math.floor(Math.random() * 1296).toString(36), created: cfg.nowLocal }, e);\nconst all = rows.concat([entry]);\nconst after = zwEvaluate(all);\n// cross-check with the calendar: booked time on a day the person is entered as absent\nlet absent = [];\ntry { absent = zwAbsentFrom(zwBody($('Kalender: Abwesenheit am Tag?').first().json), e.date).filter(a => a.person === e.person); } catch (x) { absent = []; }\nif (absent.length) after.push({ key: e.person + '|' + e.date + '|ABSENT', person: e.person, date: e.date, rule: 'ABSENT', level: 'hinweis', v: 0 });\nconst newV = zwNewViolations(before, after);\nreturn [{ json: { state: 'ok', lang, entry, csv: zwCsvStringify(all), putHeaders: etag ? { 'If-Match': etag } : { 'If-None-Match': '*' }, rows: all, after, newV } }];"
   },
   "id": "b5",
   "name": "Buchen & prüfen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1740,
    0
   ],
   "notes": "Überschneidung, Tageslimit, Regeln VOR und NACH der Buchung, nur Neues zählt."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "b6",
       "leftValue": "={{ $json.state === 'ok' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "b6",
   "name": "Buchung ok?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1980,
    0
   ]
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.csv }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "specifyHeaders": "json",
    "jsonHeaders": "={{ JSON.stringify($json.putHeaders) }}",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/csv; charset=utf-8",
    "body": "={{ $json.csv }}"
   },
   "id": "b7",
   "name": "CSV speichern",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2220,
    -80
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "If-Match mit dem ETag von vorhin: Hat jemand dazwischen gespeichert, antwortet Nextcloud mit 412 und nichts geht verloren."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "b8",
       "leftValue": "={{ [200, 201, 204].includes($json.statusCode) }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "b8",
   "name": "Gespeichert?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2460,
    -80
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "b9",
       "leftValue": "={{ $runIndex < 3 }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "b9",
   "name": "Nochmal versuchen?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2460,
    160
   ],
   "notes": "Bis zu drei neue Versuche bei 412 (gleichzeitige Änderung)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\nreturn [{ json: { errors: ['conflict'], html: zwErrPage(['conflict'], $('Eingabe prüfen').first().json.lang) } }];"
   },
   "id": "b10",
   "name": "Konflikt-Seite",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2700,
    200
   ]
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.deck_stacks }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    }
   },
   "id": "b11",
   "name": "Deck: Stapel lesen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2700,
    -80
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst b = $('Buchen & prüfen').last().json;\nconst lang = b.lang, U = ZW_UI[lang], e = b.entry;\nlet cards = [];\ntry { const st = JSON.parse(zwBody($('Deck: Stapel lesen').first().json)); const s1 = (Array.isArray(st) ? st : []).find(s => s.cards && s.cards.some(c => /^⚠ ArbZG/.test(c.title)) ) || {}; cards = (s1.cards || []).filter(c => /^⚠ ArbZG/.test(c.title)); } catch (x) { cards = []; }\nconst canCard = cards.length < 8;\nconst net = zwDayMap([e])[e.person + '|' + e.date].net;\nconst mine = b.newV.filter(v => v.person === e.person && v.date === e.date);\nconst dm = e.date.slice(8) + '.' + e.date.slice(5, 7) + '.';\nconst lines = mine.slice(0, 4).map(v => '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' ' + zwMsg(v, 'de'));\nconst deckBody = { title: '⚠ ArbZG: ' + e.person + ' ' + dm, type: 'plain', order: 0, description: e.person + ' · ' + e.date + ' · ' + e.start + '–' + e.end + ' (Pause ' + e.pause + ' min, netto ' + zwFmtH(net, 'de') + ')\\n\\n' + lines.join('\\n') + '\\n\\nAutomatisch vom Zeit-Wächter. Entscheiden tut ein Mensch.' };\nconst talkBody = { message: '⚠ Zeit-Wächter · ' + e.person + ' · ' + dm + ' ' + e.start + '–' + e.end + '\\n' + lines.join('\\n') + '\\nKarte im Deck-Board, Daten in zeiten.csv.' };\n// the page the person sees\nconst wk = zwMon(e.date);\nlet inner = '<p><strong>' + zwEsc(e.person) + '</strong> · ' + zwEsc(e.date) + ' · ' + zwEsc(e.start) + '–' + zwEsc(e.end) + ' · ' + zwEsc(U.pause) + ' ' + e.pause + ' min · ' + zwEsc(zwFmtH(net, lang)) + ' ' + zwEsc(U.net) + ' · ' + zwEsc(e.project) + '</p>';\ninner += mine.length ? '<ul>' + mine.map(v => '<li class=\"' + (v.level === 'verstoss' ? 'r' : 'a') + '\">' + zwEsc(zwMsg(v, lang)) + '</li>').join('') + '</ul>' : '<ul><li>' + zwEsc(U.clean) + '</li></ul>';\ninner += zwPersonChart(b.rows, e.person, wk, b.after, lang);\ninner += '<p class=\"m\">' + zwEsc(U.saved) + ': n8n-Demo/Zeit/zeiten.csv' + (mine.length && canCard ? ' · Talk + Deck' : '') + '</p>';\nconst html = zwPage(lang, U.ok, inner, mine.some(v => v.level === 'verstoss') ? 'bad' : mine.length ? 'warn' : 'ok');\nconst idx = n => ZW_PEOPLE.indexOf(n), pj = n => ZW_PROJECTS.indexOf(n);\nconst ingest = { source: 'booking', generated: cfg.nowIso, rows: b.rows.filter(r => r.date >= zwAdd(cfg.today, -27)).map(r => ({ p: idx(r.person), d: r.date, s: r.start, e: r.end, b: Number(r.pause) || 0, j: pj(r.project) })) };\nreturn [{ json: { alert: mine.length > 0 && canCard, html, deckBody, talkBody, ingest, mine: mine.map(v => ({ rule: v.rule, level: v.level, v: v.v })) } }];"
   },
   "id": "b12",
   "name": "Folgen planen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2940,
    -80
   ],
   "notes": "Baut Seite, Deck-Karte, Talk-Text und die Daten für die Live-Seite. Deck: höchstens 8 Karten gleichzeitig."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "b13",
       "leftValue": "={{ $json.alert === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "b13",
   "name": "Verstoß melden?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    3180,
    -80
   ]
  },
  {
   "parameters": {
    "method": "POST",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.deck_cards }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($('Folgen planen').first().json.deckBody) }}"
   },
   "id": "b14",
   "name": "Deck: Karte anlegen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    3420,
    -160
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "method": "POST",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.talk }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($('Folgen planen').first().json.talkBody) }}"
   },
   "id": "b15",
   "name": "Talk: Hinweis",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    3660,
    -160
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "operation": "completion",
    "respondWith": "showText",
    "responseText": "={{ $('Folgen planen').first().json.html }}",
    "options": {}
   },
   "id": "b17",
   "name": "Seite: Ergebnis",
   "type": "n8n-nodes-base.form",
   "typeVersion": 2.5,
   "position": [
    4140,
    -80
   ],
   "notes": "Form-Knoten «Show Text»: eine komplette HTML-Seite als Antwort, mit SVG-Diagramm."
  },
  {
   "parameters": {
    "operation": "completion",
    "respondWith": "showText",
    "responseText": "={{ $json.html }}",
    "options": {}
   },
   "id": "b18",
   "name": "Seite: Hinweis",
   "type": "n8n-nodes-base.form",
   "typeVersion": 2.5,
   "position": [
    1260,
    440
   ],
   "notes": "Eine Fehlerseite für alle Abbrüche (ungültig, Überschneidung, Limit, Konflikt)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst f = $('Abwesenheit melden (Formular)').first().json;\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst lang = { 'Deutsch': 'de', 'English': 'en', 'Italiano': 'it' }[f['Sprache']] || 'de';\nconst v = zwValidateAbs({ person: f['Mitarbeiter'], kind: f['Art'], from: f['Von'], to: f['Bis'] }, cfg.today);\nreturn [{ json: { ok: v.ok, entry: v.entry, lang, html: v.ok ? '' : zwErrPage(v.errors, lang) } }];"
   },
   "id": "a1",
   "name": "Abwesenheit prüfen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    780,
    1000
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "a2",
       "leftValue": "={{ $json.ok === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "a2",
   "name": "Abwesenheit ok?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1020,
    1000
   ]
  },
  {
   "parameters": {
    "method": "PROPFIND",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.cal }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Depth",
       "value": "1"
      }
     ]
    },
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "application/xml",
    "body": "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\"><d:prop><d:getetag/></d:prop></d:propfind>"
   },
   "id": "a3",
   "name": "Kalender: Liste (Limit)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1260,
    1000
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst a = $('Abwesenheit prüfen').first().json, lang = a.lang, U = ZW_UI[lang], e = a.entry;\nconst body = zwBody($('Kalender: Liste (Limit)').first().json);\nconst count = (body.match(/zw-[a-z0-9]+\\.ics/gi) || []).length;\nif (count >= 25) return [{ json: { ok: false, html: zwErrPage(['abs_cap'], lang) } }];\nconst id = Date.now().toString(36) + Math.floor(Math.random() * 1296).toString(36);\nconst ics = zwIcs(id, e, cfg.nowIso);\nconst dm = s => s.slice(8) + '.' + s.slice(5, 7) + '.';\nconst talk = { message: '🗓 Zeit-Wächter · ' + e.person + ': ' + e.kind + ' ' + dm(e.from) + (e.to !== e.from ? '–' + dm(e.to) : '') + ' (Kalender n8n-demo)' };\nconst inner = '<p><strong>' + zwEsc(e.person) + '</strong> · ' + zwEsc(e.kind) + ' · ' + zwEsc(e.from) + (e.to !== e.from ? ' → ' + zwEsc(e.to) : '') + '</p><ul><li>' + zwEsc(U.abs_note) + '</li></ul>';\nreturn [{ json: { ok: true, ics, url: cfg.urls.cal_new + id + '.ics', talk, html: zwPage(lang, U.abs, inner, 'ok') } }];"
   },
   "id": "a4",
   "name": "Limit prüfen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1500,
    1000
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "a5",
       "leftValue": "={{ $json.ok === true }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "a5",
   "name": "Limit frei?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1740,
    1000
   ]
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $json.url }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "If-None-Match",
       "value": "*"
      }
     ]
    },
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/calendar",
    "body": "={{ $json.ics }}"
   },
   "id": "a6",
   "name": "Kalender: Abwesenheit eintragen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1980,
    940
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "POST",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.talk }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($('Limit prüfen').first().json.talk) }}"
   },
   "id": "a7",
   "name": "Talk: Abwesenheit",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2220,
    940
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "operation": "completion",
    "respondWith": "showText",
    "responseText": "={{ $('Limit prüfen').first().json.html }}",
    "options": {}
   },
   "id": "a8",
   "name": "Seite: Bestätigung",
   "type": "n8n-nodes-base.form",
   "typeVersion": 2.5,
   "position": [
    2460,
    940
   ],
   "notes": null
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.csv }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "r1",
   "name": "CSV lesen (Bericht)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    780,
    1500
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst res = $('CSV lesen (Bericht)').first().json;\nif (Number(res.statusCode) !== 200) throw new Error('zeiten.csv nicht lesbar (HTTP ' + res.statusCode + ')');\nconst rows = zwRetention(zwCsvParse(zwBody(res)), cfg.today, 70);\nconst st = zwStats(rows, cfg.today);\nconst svg = zwDashboard(st, 'de');\nconst byRule = {}; st.violations.forEach(v => { byRule[v.rule] = (byRule[v.rule] || 0) + 1; });\n// the AI gets numbers only: no names, no notes, no times of day\nconst facts = { kalenderwoche: st.kw, stunden_gesamt: Math.round(st.totalNet / 6) / 10, buchungen: st.entries, personen_ueber_48h: st.people.filter(p => p.net > 2880).length, verstoesse: st.counts.verstoss, hinweise: st.counts.hinweis, nach_regel: byRule };\nconst aiBody = { model: 'gpt-4o-mini', temperature: 0.3, max_tokens: 400, messages: [{ role: 'system', content: 'Du schreibst für ein kleines Büro drei kurze, sachliche Sätze zum Wochenbericht der Arbeitszeiterfassung. Nenne nur Zahlen aus den Fakten, erfinde nichts, nenne keine Personen, gib keine Rechtsberatung. Regeln: DAY10 mehr als 10 Stunden, BREAK30/BREAK45 Pause zu kurz, REST11 Ruhezeit unter 11 Stunden, SUN Sonntagsarbeit, WEEK48 Woche über 48 Stunden, DAY8 über 8 Stunden. Ein Satz pro Zeile, ohne Aufzählungszeichen.' }, { role: 'user', content: JSON.stringify(facts) }] };\nreturn [{ json: { today: cfg.today, st, svg, aiBody, facts } }];"
   },
   "id": "r2",
   "name": "Auswerten & Diagramme",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1020,
    1500
   ],
   "notes": "Statistik, Dashboard-SVG und die Zahlen für die KI. Die KI sieht keine Namen."
  },
  {
   "parameters": {
    "method": "POST",
    "url": "https://api.openai.com/v1/chat/completions",
    "authentication": "genericCredentialType",
    "genericAuthType": "httpHeaderAuth",
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($json.aiBody) }}",
    "options": {
     "timeout": 60000
    }
   },
   "id": "r3",
   "name": "Kommentar (KI)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1260,
    1500
   ],
   "onError": "continueRegularOutput",
   "credentials": {
    "httpHeaderAuth": {
     "id": "",
     "name": "YOUR OpenAI-compatible API key (Header Auth: Authorization = Bearer sk-...)"
    }
   },
   "notes": "Optional: eigene OpenAI-kompatible Credential eintragen. Fällt der Aufruf aus, schreibt der Code-Knoten den Satz selbst."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst d = $('Auswerten & Diagramme').first().json, st = d.st;\nlet ai = '';\ntry { const raw = String($json.choices[0].message.content || '').replace(/[*_#`>]/g, '').split(/\\n+/).map(x => x.replace(/^\\s*[-\\d.)]+\\s*/, '').trim()).filter(x => x.length > 12).slice(0, 3); if (raw.length >= 2) ai = raw.join(' ').slice(0, 520); } catch (x) { ai = ''; }\nif (!ai) ai = `Diese Woche wurden ${zwFmtH(st.totalNet, 'de')} in ${st.entries} Buchungen erfasst. Die Regeln schlugen ${st.counts.verstoss}-mal als Verstoß und ${st.counts.hinweis}-mal als Hinweis an.`;\nconst md = zwReportMd(st, 'de', ai);\nconst names = { svg: 'KW' + st.kw + '-dashboard.svg', md: 'KW' + st.kw + '-Wochenbericht.md' };\nconst top = st.violations.slice(0, 3).map(v => '- ' + (v.level === 'verstoss' ? '🔴 ' : '🟡 ') + v.person + ' ' + v.date.slice(8) + '.' + v.date.slice(5, 7) + '.: ' + zwMsg(v, 'de'));\nconst talkBody = { message: '📊 Zeit-Wächter · KW ' + st.kw + ': ' + zwFmtH(st.totalNet, 'de') + ' gebucht, ' + st.counts.verstoss + ' Verstöße, ' + st.counts.hinweis + ' Hinweise.\\n' + (top.length ? top.join('\\n') + '\\n' : '') + 'Bericht: Zeit/Berichte/' + names.md + ' (Dashboard als SVG daneben).' };\nconst idx = n => ZW_PEOPLE.indexOf(n), pj = n => ZW_PROJECTS.indexOf(n);\nconst ingest = { source: 'report', generated: cfg.nowIso, rows: zwRetention(st.rows, cfg.today, 27).map(r => ({ p: idx(r.person), d: r.date, s: r.start, e: r.end, b: Number(r.pause) || 0, j: pj(r.project) })) };\nreturn [{ json: { md, svg: d.svg, svgUrl: cfg.urls.reports + names.svg, mdUrl: cfg.urls.reports + names.md, talkBody, ingest, ai, kw: st.kw, names } }];"
   },
   "id": "r4",
   "name": "Bericht bauen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1500,
    1500
   ]
  },
  {
   "parameters": {
    "method": "MKCOL",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.reports }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "r5",
   "name": "Ordner anlegen (Berichte)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1740,
    1500
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "405 = gibt es schon. Ist gewollt."
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Bericht bauen').first().json.svgUrl }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "image/svg+xml",
    "body": "={{ $('Bericht bauen').first().json.svg }}"
   },
   "id": "r6",
   "name": "Dashboard speichern (SVG)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1980,
    1500
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Bericht bauen').first().json.mdUrl }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/markdown",
    "body": "={{ $('Bericht bauen').first().json.md }}"
   },
   "id": "r7",
   "name": "Bericht speichern (Markdown)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2220,
    1500
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "POST",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.talk }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    },
    "sendBody": true,
    "specifyBody": "json",
    "jsonBody": "={{ JSON.stringify($('Bericht bauen').first().json.talkBody) }}"
   },
   "id": "r8",
   "name": "Talk: Wochenbericht",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2460,
    1500
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst b = $('Bericht bauen').first().json;\nreturn [{ json: { ok: true, kw: b.kw, files: [b.names.md, b.names.svg], comment: b.ai } }];"
   },
   "id": "r10",
   "name": "Antwort (Bericht)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2940,
    1500
   ]
  },
  {
   "parameters": {
    "method": "MKCOL",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.files }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "s1",
   "name": "Ordner anlegen (Zeit)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    780,
    1900
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "MKCOL",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.reports }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "s2",
   "name": "Ordner anlegen (Berichte, Start)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1020,
    1900
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst rows = zwSeed(cfg.today);\nreturn [{ json: { csv: zwCsvStringify(rows), rows, n: rows.length } }];"
   },
   "id": "s3",
   "name": "Demo-Daten erzeugen",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1260,
    1900
   ],
   "notes": "Drei Wochen fiktive Buchungen, vier Probleme absichtlich eingebaut (Ruhezeit, 10 h, Pause, Sonntag)."
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.csv }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/csv; charset=utf-8",
    "body": "={{ $json.csv }}"
   },
   "id": "s4",
   "name": "Demo-Daten schreiben",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1500,
    1900
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "PROPFIND",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.cal }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Depth",
       "value": "1"
      }
     ]
    },
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "application/xml",
    "body": "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\"><d:prop><d:getetag/></d:prop></d:propfind>"
   },
   "id": "s5",
   "name": "Kalender: Liste (aufräumen)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1740,
    1900
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst body = String(($('Kalender: Liste (aufräumen)').first().json.data !== undefined ? $('Kalender: Liste (aufräumen)').first().json.data : $('Kalender: Liste (aufräumen)').first().json.body) || '');\nconst out = []; const re = /<[A-Za-z]*:?href>([^<]*\\/zw-[a-z0-9]+\\.ics)<\\/[A-Za-z]*:?href>/gi; let m;\nwhile ((m = re.exec(body)) && out.length < 60) { const u = cfg.urls.cal.slice(0, cfg.urls.cal.indexOf('/remote.php')) + m[1]; if (u.startsWith(cfg.urls.cal)) out.push({ json: { url: u } }); }\nreturn out.length ? out : [{ json: { url: '' } }];"
   },
   "id": "s6",
   "name": "Aufräumen: Kalender-Liste",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1980,
    1900
   ],
   "notes": "Nur Termine mit der Kennung zw-… aus diesem Workflow."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "s7",
       "leftValue": "={{ !!$json.url }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "s7",
   "name": "Kalender: etwas zu löschen?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2220,
    1900
   ]
  },
  {
   "parameters": {
    "method": "DELETE",
    "url": "={{ $json.url }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth"
   },
   "id": "s8d",
   "name": "Kalender: Abwesenheit löschen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2460,
    1840
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.deck_stacks }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      },
      {
       "name": "Accept",
       "value": "application/json"
      }
     ]
    }
   },
   "id": "s8",
   "name": "Deck: Stapel lesen (aufräumen)",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2700,
    1900
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "executeOnce": true,
   "onError": "continueRegularOutput"
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst cfg = $('Demo-Bereich festlegen').first().json;\nconst out = [];\ntry { const st = JSON.parse(($('Deck: Stapel lesen (aufräumen)').first().json.data !== undefined ? $('Deck: Stapel lesen (aufräumen)').first().json.data : $('Deck: Stapel lesen (aufräumen)').first().json.body)); (Array.isArray(st) ? st : []).forEach(s => (s.cards || []).forEach(c => { if (/^⚠ ArbZG/.test(c.title) && out.length < 40) out.push({ json: { url: cfg.urls.deck_card + c.id } }); })); } catch (x) { }\nreturn out.length ? out : [{ json: { url: '' } }];"
   },
   "id": "s9",
   "name": "Aufräumen: Deck-Liste",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2940,
    1900
   ],
   "notes": "Nur Karten, deren Titel mit «⚠ ArbZG» beginnt."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "s10",
       "leftValue": "={{ !!$json.url }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "s10",
   "name": "Deck: etwas zu löschen?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    3180,
    1900
   ]
  },
  {
   "parameters": {
    "method": "DELETE",
    "url": "={{ $json.url }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "OCS-APIRequest",
       "value": "true"
      }
     ]
    }
   },
   "id": "s11",
   "name": "Deck: Karte löschen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    3420,
    1840
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   }
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst s = $('Demo-Daten erzeugen').first().json;\nreturn [{ json: { ok: true, seeded: s.n } }];"
   },
   "id": "s13",
   "name": "Antwort (Demo)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3900,
    1900
   ]
  },
  {
   "parameters": {
    "httpMethod": "POST",
    "path": "zeitwaechter-stempel-CHANGE-ME",
    "responseMode": "lastNode",
    "options": {}
   },
   "id": "t6",
   "name": "Stempel-Webhook (QR)",
   "type": "n8n-nodes-base.webhook",
   "typeVersion": 2,
   "position": [
    0,
    2300
   ],
   "webhookId": "7d1e4a52-0c3b-4f6a-9d21-6c0000000304",
   "notes": "POST JSON {action: register|qr|punch|me, ...}. Der Pfad ist das Geheimnis. Antwort: JSON vom letzten Knoten (Stempel: Antwort)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst ZW_SECRET = 'CHANGE-ME-LONG-RANDOM-SECRET';\nconst cfg = $('Demo-Bereich festlegen').first().json;\nlet b = $('Stempel-Webhook (QR)').first().json.body; if (typeof b === 'string') { try { b = JSON.parse(b); } catch (x) { b = {}; } } b = (b && typeof b === 'object') ? b : {};\nconst action = String(b.action || '');\nconst fin = r => [{ json: { mode: 'resp', resp: r } }];\nconst err = c => fin({ ok: false, error: c });\nif (action === 'qr') return fin({ ok: true, date: cfg.today, codes: zwPunchCodes(ZW_SECRET, cfg.today) });\nif (action === 'register') { const person = String(b.person || '').trim(); if (ZW_PEOPLE.indexOf(person) < 0) return err('bad_person'); return [{ json: { mode: 'dev', action, person } }]; }\nif (action === 'punch' || action === 'me') {\n  const device = String(b.device || '').trim().toLowerCase();\n  if (!/^[0-9a-f]{32}$/.test(device)) return err('bad_device');\n  if (action === 'me') return [{ json: { mode: 'dev', action, device } }];\n  const kind = String(b.kind || '');\n  if (ZW_KINDS.indexOf(kind) < 0) return err('bad_kind');\n  const code = String(b.code || '').trim().toLowerCase();\n  if (!/^[0-9a-f]{8}$/.test(code)) return err('bad_code');\n  return [{ json: { mode: 'dev', action, device, kind, code, note: String(b.note == null ? '' : b.note).slice(0, 400) } }];\n}\nreturn err('bad_action');"
   },
   "id": "q1",
   "name": "Stempel: Anfrage",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    780,
    2300
   ],
   "notes": "Prüft die Anfrage. «qr» antwortet sofort mit den vier Tagescodes (HMAC-SHA256, erste 8 Hex von Datum|Art). Das Geheimnis steht nur in zwei Code-Knoten."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q2",
       "leftValue": "={{ $json.mode === 'resp' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q2",
   "name": "Stempel: Sofort antworten?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1020,
    2300
   ]
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.devices }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Accept-Encoding",
       "value": "identity"
      }
     ]
    }
   },
   "id": "q3",
   "name": "Geräte lesen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1260,
    2380
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "geraete.json samt ETag (404 = noch leer). Gespeichert wird nur sha256(Gerät) → Person."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst ZW_SECRET = 'CHANGE-ME-LONG-RANDOM-SECRET';\nconst cfg = $('Demo-Bereich festlegen').first().json, q = $('Stempel: Anfrage').first().json;\nconst res = $('Geräte lesen').last().json, st = Number(res.statusCode);\nconst fin = r => [{ json: { mode: 'resp', resp: r } }];\nconst down = { ok: false, error: 'down' };\nlet map = {};\nif (st === 200) { try { map = JSON.parse(zwBody(res) || '{}'); } catch (x) { return fin(down); } if (!map || typeof map !== 'object' || Array.isArray(map)) return fin(down); }\nelse if (st !== 404) return fin(down);\nconst etag = zwEtag(res);\nif (q.action === 'register') {\n  if (Object.keys(map).length >= 40) return fin({ ok: false, error: 'cap' });                 // demo: at most 40 devices\n  const device = zwDeviceId(ZW_SECRET, q.person);\n  map[zwSha256(device)] = { person: q.person, created: cfg.nowLocal };                         // only the hash is stored\n  return [{ json: { mode: 'write', putBody: JSON.stringify(map), putHeaders: etag ? { 'If-Match': etag } : { 'If-None-Match': '*' }, done: { ok: true, device, person: q.person } } }];\n}\nconst dv = map[zwSha256(q.device)];\nif (!dv || ZW_PEOPLE.indexOf(dv.person) < 0) return fin({ ok: false, error: 'bad_device' });\nif (q.action === 'punch' && q.code !== zwPunchCode(ZW_SECRET, cfg.today, q.kind)) return fin({ ok: false, error: 'bad_code' });   // only TODAY's code for exactly this kind\nreturn [{ json: { mode: 'next', person: dv.person } }];"
   },
   "id": "q4",
   "name": "Stempel: Geräte",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1500,
    2380
   ],
   "notes": "register: neues Gerät (max. 40). punch/me: Gerät bekannt? Code von HEUTE für genau diese Art?"
  },
  {
   "parameters": {
    "rules": {
     "values": [
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "q5_resp",
          "leftValue": "={{ $json.mode }}",
          "rightValue": "resp",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "resp"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "q5_write",
          "leftValue": "={{ $json.mode }}",
          "rightValue": "write",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "write"
      },
      {
       "conditions": {
        "options": {
         "caseSensitive": true,
         "leftValue": "",
         "typeValidation": "strict"
        },
        "conditions": [
         {
          "id": "q5_next",
          "leftValue": "={{ $json.mode }}",
          "rightValue": "next",
          "operator": {
           "type": "string",
           "operation": "equals"
          }
         }
        ],
        "combinator": "and"
       },
       "renameOutput": true,
       "outputKey": "next"
      }
     ]
    },
    "options": {}
   },
   "id": "q5",
   "name": "Stempel: Weiterleiten",
   "type": "n8n-nodes-base.switch",
   "typeVersion": 3.2,
   "position": [
    1740,
    2380
   ]
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.devices }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "specifyHeaders": "json",
    "jsonHeaders": "={{ JSON.stringify($json.putHeaders) }}",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "application/json",
    "body": "={{ $json.putBody }}"
   },
   "id": "q6",
   "name": "Geräte speichern",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1980,
    2380
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "If-Match / If-None-Match wie bei der CSV: gleichzeitige Registrierung → 412 → neu lesen."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q7",
       "leftValue": "={{ [200, 201, 204].includes($json.statusCode) }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q7",
   "name": "Geräte gespeichert?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2220,
    2380
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q8",
       "leftValue": "={{ $runIndex < 3 }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q8",
   "name": "Geräte nochmal?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2220,
    2560
   ]
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "return [{ json: { resp: $('Stempel: Geräte').last().json.done } }];"
   },
   "id": "q9",
   "name": "Stempel: Antwort (Gerät)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2460,
    2380
   ]
  },
  {
   "parameters": {
    "method": "GET",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.punches }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "headerParameters": {
     "parameters": [
      {
       "name": "Accept-Encoding",
       "value": "identity"
      }
     ]
    }
   },
   "id": "q10",
   "name": "Stempel lesen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1980,
    2700
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "stempel.csv samt ETag (404 = noch leer)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "// =====================================================================================================================\n//  Zeit-Wächter core: ArbZG rules, CSV, statistics, SVG charts. Pure functions, no I/O, no dependencies.\n//  ONE source of truth: pasted into the n8n Code nodes (build_workflow.py), loaded by the website (assets/zeitwaechter-core.js)\n//  and by the test (test_core.js). Everything is deterministic: the AI never decides what counts as a violation.\n//  Not legal advice. Rules follow ArbZG §3 (10 h/day, 8 h average), §4 (breaks 30/45 min), §5 (11 h rest), §9 (Sundays).\n// =====================================================================================================================\nconst ZW_PEOPLE = ['Anna Weber', 'Ben Keller', 'Chiara Rossi', 'Dario Fischer'];           // fictional Musterbüro GmbH\nconst ZW_PROJECTS = ['Website-Relaunch', 'Support', 'Angebote', 'Interna'];\nconst ZW_COLORS = ['#2f6fed', '#16a085', '#8e5bd6', '#7a8794'];\nconst ZW_CSV_HEAD = 'id,person,date,start,end,pause,project,note,created';\n\nconst ZW_T = {\n  de: { day: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'], kw: 'KW', hours: 'Stunden', entries: 'Buchungen', viol: 'Verstöße', hints: 'Hinweise', team: 'Stunden pro Person', proj: 'Stunden pro Projekt',\n    blocks: 'Arbeitsblöcke je Tag (Beginn bis Ende)', none: 'Keine Verstöße. Sauber.', title: 'Zeit-Wächter', demo: 'Musterbüro GmbH (Demo-Daten)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Mehr als 10 Stunden gearbeitet ({h}) · § 3 ArbZG', DAY8: 'Über 8 Stunden ({h}): braucht Ausgleich (Ø 8 h in 6 Monaten / 24 Wochen)', BREAK30: 'Pause zu kurz: {p} min, nötig sind 30 min bei mehr als 6 h · § 4 ArbZG',\n      BREAK45: 'Pause zu kurz: {p} min, nötig sind 45 min bei mehr als 9 h · § 4 ArbZG', REST11: 'Ruhezeit nur {h} (nötig: 11 h) · § 5 ArbZG', SUN: 'Sonntagsarbeit ({h}): nur mit Ausnahme · § 9 ArbZG', WEEK48: 'Woche mit {h}: über 48 h (6 × 8 h)', ABSENT: 'Im Kalender ist die Person an diesem Tag als abwesend eingetragen' } },\n  en: { day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], kw: 'CW', hours: 'hours', entries: 'entries', viol: 'violations', hints: 'hints', team: 'Hours per person', proj: 'Hours per project',\n    blocks: 'Work blocks per day (start to end)', none: 'No violations. Clean.', title: 'Timesheet Guardian', demo: 'Musterbüro GmbH (demo data)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'More than 10 hours worked ({h}) · § 3 ArbZG', DAY8: 'Over 8 hours ({h}): needs compensation (8 h average in 6 months / 24 weeks)', BREAK30: 'Break too short: {p} min, 30 min needed above 6 h · § 4 ArbZG',\n      BREAK45: 'Break too short: {p} min, 45 min needed above 9 h · § 4 ArbZG', REST11: 'Rest only {h} (11 h needed) · § 5 ArbZG', SUN: 'Sunday work ({h}): only with an exception · § 9 ArbZG', WEEK48: 'Week with {h}: above 48 h (6 × 8 h)', ABSENT: 'The calendar lists this person as absent on that day' } },\n  it: { day: ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'], kw: 'Sett.', hours: 'ore', entries: 'registrazioni', viol: 'violazioni', hints: 'avvisi', team: 'Ore per persona', proj: 'Ore per progetto',\n    blocks: 'Blocchi di lavoro per giorno (inizio-fine)', none: 'Nessuna violazione. Tutto pulito.', title: 'Il Guardiano delle ore', demo: 'Musterbüro GmbH (dati demo)', limit8: '8 h', limit10: '10 h',\n    r: { DAY10: 'Più di 10 ore lavorate ({h}) · § 3 ArbZG', DAY8: 'Oltre 8 ore ({h}): serve compensazione (media 8 h in 6 mesi / 24 settimane)', BREAK30: 'Pausa troppo corta: {p} min, ne servono 30 oltre 6 h · § 4 ArbZG',\n      BREAK45: 'Pausa troppo corta: {p} min, ne servono 45 oltre 9 h · § 4 ArbZG', REST11: 'Riposo di soli {h} (servono 11 h) · § 5 ArbZG', SUN: 'Lavoro domenicale ({h}): solo con eccezione · § 9 ArbZG', WEEK48: 'Settimana con {h}: oltre 48 h (6 × 8 h)', ABSENT: 'Il calendario segna la persona come assente quel giorno' } },\n};\n\nfunction zwMin(s) { const m = /^([01]?\\d|2[0-3]):([0-5]\\d)$/.exec(String(s == null ? '' : s).trim()); return m ? +m[1] * 60 + +m[2] : null; }\nfunction zwHM(m) { m = Math.round(m); return String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); }\nfunction zwFmtH(min, lang) { const h = Math.round(min / 6) / 10; const t = h.toFixed(1); return (lang === 'en' ? t : t.replace('.', ',')) + ' h'; }\nfunction zwFmtHM(min) { min = Math.round(min); return Math.floor(min / 60) + ' h ' + String(min % 60).padStart(2, '0') + ' min'; }\nfunction zwTime(s) {\n  const m = /^(\\d{4})-(\\d\\d)-(\\d\\d)$/.exec(String(s || '')); if (!m) return null;\n  const t = Date.UTC(+m[1], +m[2] - 1, +m[3]); const d = new Date(t);\n  return (d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3]) ? t : null;\n}\nfunction zwStr(t) { return new Date(t).toISOString().slice(0, 10); }\nfunction zwAdd(s, n) { return zwStr(zwTime(s) + n * 86400000); }\nfunction zwDow(s) { return (new Date(zwTime(s)).getUTCDay() + 6) % 7; }          // Monday = 0\nfunction zwMon(s) { return zwAdd(s, -zwDow(s)); }\nfunction zwKW(s) {\n  const t = new Date(zwTime(s)); t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);\n  const y = t.getUTCFullYear(); const f = new Date(Date.UTC(y, 0, 4));\n  return { year: y, week: 1 + Math.round(((t - f) / 86400000 - 3 + ((f.getUTCDay() + 6) % 7)) / 7) };\n}\nfunction zwEsc(s) { return String(s == null ? '' : s).replace(/[&<>\"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]; }); }\n\n// HTTP Request node (full response, text): the body lives in .data in n8n 2.x (.body in older ones)\nfunction zwBody(r) { r = r || {}; const b = r.data !== undefined ? r.data : r.body; return typeof b === 'string' ? b : (b == null ? '' : String(b)); }\n\n// ---- CSV (RFC 4180) with spreadsheet-formula protection -------------------------------------------------------------\nfunction zwCsvCell(v) {\n  let s = String(v == null ? '' : v).replace(/[\\r\\n\\t]+/g, ' ');\n  if (/^[=+\\-@]/.test(s)) s = \"'\" + s;                                 // CSV injection: Excel/Calc would run =HYPERLINK(...)\n  return /[\",]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s;\n}\nfunction zwCsvParse(text) {\n  const rows = []; let row = [], cell = '', q = false; const s = String(text || '').replace(/^﻿/, '');\n  for (let i = 0; i < s.length; i++) {\n    const c = s[i];\n    if (q) { if (c === '\"') { if (s[i + 1] === '\"') { cell += '\"'; i++; } else q = false; } else cell += c; }\n    else if (c === '\"') q = true;\n    else if (c === ',') { row.push(cell); cell = ''; }\n    else if (c === '\\n') { row.push(cell); rows.push(row); row = []; cell = ''; }\n    else if (c !== '\\r') cell += c;\n  }\n  if (cell !== '' || row.length) { row.push(cell); rows.push(row); }\n  const head = (rows.shift() || []).map(function (h) { return h.trim(); });\n  return rows.filter(function (r) { return r.length > 1; }).map(function (r) { const o = {}; head.forEach(function (h, i) { o[h] = r[i] == null ? '' : r[i]; }); return o; });\n}\nfunction zwCsvStringify(rows) {\n  const cols = ZW_CSV_HEAD.split(',');\n  return ZW_CSV_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n\nfunction zwNote(s) { return String(s == null ? '' : s).replace(/<[^>]*>/g, ' ').replace(/[\\u0000-\\u001f\\u007f@<>]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 80); }\n// ---- input validation (the form is public: everything is checked here, not in the browser) -----------------------------\nfunction zwValidate(inp, today) {\n  const err = []; const o = {};\n  o.person = String(inp.person || inp.Mitarbeiter || '').trim();\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person');\n  o.date = String(inp.date || inp.Datum || '').trim();\n  if (zwTime(o.date) == null) err.push('date');\n  else if (o.date > today) err.push('date_future');\n  else if (o.date < zwAdd(today, -60)) err.push('date_old');\n  const s = zwMin(inp.start || inp.Beginn), e = zwMin(inp.end || inp.Ende);\n  if (s == null) err.push('start'); if (e == null) err.push('end');\n  o.start = s == null ? '' : zwHM(s); o.end = e == null ? '' : zwHM(e);\n  if (s != null && e != null && e <= s) err.push('order');\n  const pr = inp.pause != null ? inp.pause : inp.Pause;\n  const p = Number(String(pr == null || pr === '' ? 0 : pr).replace(',', '.'));\n  if (!isFinite(p) || p < 0 || p > 240 || Math.round(p) !== p) err.push('pause'); else if (s != null && e != null && p >= e - s) err.push('pause_long');\n  o.pause = isFinite(p) ? Math.round(p) : 0;\n  o.project = String(inp.project || inp.Projekt || '').trim();\n  if (ZW_PROJECTS.indexOf(o.project) < 0) err.push('project');\n  o.note = zwNote(inp.note || inp.Tätigkeit);\n  return { ok: err.length === 0, errors: err, entry: o };\n}\n\n// ---- days + rules ---------------------------------------------------------------------------------------------------\nfunction zwDayMap(rows) {\n  const m = {};\n  rows.forEach(function (r) {\n    const s = zwMin(r.start), e = zwMin(r.end), p = Number(r.pause) || 0;\n    if (s == null || e == null || e <= s || zwTime(r.date) == null) return;\n    const k = r.person + '|' + r.date;\n    const d = m[k] || (m[k] = { person: r.person, date: r.date, first: s, last: e, net: 0, pause: 0, n: 0, proj: {} });\n    d.first = Math.min(d.first, s); d.last = Math.max(d.last, e);\n    const net = Math.max(0, e - s - p); d.net += net; d.pause += p; d.n++; d.proj[r.project] = (d.proj[r.project] || 0) + net;\n  });\n  return m;\n}\nfunction zwEvaluate(rows) {\n  const dm = zwDayMap(rows); const out = []; const wk = {};\n  Object.keys(dm).sort().forEach(function (k) {\n    const d = dm[k];\n    const add = function (rule, level, v) { out.push({ key: d.person + '|' + d.date + '|' + rule, person: d.person, date: d.date, rule: rule, level: level, v: v }); };\n    if (d.net > 600) add('DAY10', 'verstoss', d.net); else if (d.net > 480) add('DAY8', 'hinweis', d.net);\n    if (d.net > 540 && d.pause < 45) add('BREAK45', 'verstoss', d.pause); else if (d.net > 360 && d.pause < 30) add('BREAK30', 'verstoss', d.pause);\n    const prev = dm[d.person + '|' + zwAdd(d.date, -1)];\n    if (prev) { const rest = 1440 - prev.last + d.first; if (rest < 660) add('REST11', 'verstoss', rest); }\n    if (zwDow(d.date) === 6) add('SUN', 'hinweis', d.net);\n    const w = d.person + '|' + zwMon(d.date); const x = wk[w] || (wk[w] = { person: d.person, net: 0, last: d.date });\n    x.net += d.net; if (d.date > x.last) x.last = d.date;\n  });\n  Object.keys(wk).forEach(function (k) { const x = wk[k]; if (x.net > 2880) out.push({ key: x.person + '|' + x.last + '|WEEK48', person: x.person, date: x.last, rule: 'WEEK48', level: 'hinweis', v: x.net }); });\n  return out.sort(function (a, b) { return a.date < b.date ? 1 : a.date > b.date ? -1 : a.key < b.key ? -1 : 1; });\n}\nfunction zwNewViolations(before, after) { const seen = {}; before.forEach(function (v) { seen[v.key] = 1; }); return after.filter(function (v) { return !seen[v.key]; }); }\nfunction zwMsg(v, lang) {\n  const T = ZW_T[lang] || ZW_T.de;\n  const val = (v.rule === 'BREAK30' || v.rule === 'BREAK45') ? v.v : v.v;\n  if (v.rule === 'ABSENT') return T.r.ABSENT;\n  return T.r[v.rule].replace('{h}', v.rule === 'REST11' ? zwFmtHM(val) : zwFmtH(val, lang)).replace('{p}', String(val));\n}\n\n// ---- statistics -----------------------------------------------------------------------------------------------------\nfunction zwRetention(rows, today, days) { const lim = zwAdd(today, -(days || 70)); return rows.filter(function (r) { return r.date >= lim; }); }\nfunction zwStats(rows, today) {\n  const wk = zwMon(today), we = zwAdd(wk, 6); const dm = zwDayMap(rows);\n  const inWeek = Object.keys(dm).map(function (k) { return dm[k]; }).filter(function (d) { return d.date >= wk && d.date <= we; });\n  const people = ZW_PEOPLE.map(function (n) {\n    const ds = inWeek.filter(function (d) { return d.person === n; });\n    return { name: n, net: ds.reduce(function (a, d) { return a + d.net; }, 0), days: ds.length };\n  });\n  const projects = ZW_PROJECTS.map(function (n) { return { name: n, net: inWeek.reduce(function (a, d) { return a + (d.proj[n] || 0); }, 0) }; });\n  const viol = zwEvaluate(rows).filter(function (v) { return v.date >= zwAdd(today, -13); });\n  const hist = [3, 2, 1, 0].map(function (k) {\n    const s = zwAdd(wk, -7 * k), e = zwAdd(s, 6);\n    return { week: zwKW(s).week, net: Object.keys(dm).map(function (x) { return dm[x]; }).filter(function (d) { return d.date >= s && d.date <= e; }).reduce(function (a, d) { return a + d.net; }, 0) };\n  });\n  const kw = zwKW(wk);\n  const rows14 = rows.filter(function (r) { return r.date >= zwAdd(today, -13); });\n  return { today: today, week: wk, kw: kw.week, year: kw.year, people: people, projects: projects, violations: viol,\n    counts: { verstoss: viol.filter(function (v) { return v.level === 'verstoss'; }).length, hinweis: viol.filter(function (v) { return v.level === 'hinweis'; }).length },\n    totalNet: people.reduce(function (a, p) { return a + p.net; }, 0), entries: rows.length, hist: hist, rows: rows14 };\n}\n\n// ---- charts (self-contained SVG on a light panel, readable in Nextcloud, in a form page and on the website) ----------------\nconst ZW_INK = '#1b2430', ZW_MUTED = '#6b7787', ZW_GRID = '#dde3ea', ZW_BG = '#ffffff', ZW_PANEL = '#f4f7fb', ZW_RED = '#d64545', ZW_AMBER = '#e0a02b', ZW_OK = '#16a085', ZW_BLUE = '#2f6fed';\nfunction zwTxt(x, y, s, o) {\n  o = o || {};\n  return '<text x=\"' + x + '\" y=\"' + y + '\" font-size=\"' + (o.size || 13) + '\" fill=\"' + (o.fill || ZW_INK) + '\"' + (o.anchor ? ' text-anchor=\"' + o.anchor + '\"' : '') + (o.weight ? ' font-weight=\"' + o.weight + '\"' : '') + '>' + zwEsc(s) + '</text>';\n}\n// floating bars: one column per weekday, bar from first start to last end (time of day), red outline on violation days\nfunction zwBlocks(rows, person, wk, X, Y, W, H, lang, viol) {\n  const T = ZW_T[lang] || ZW_T.de; const dm = zwDayMap(rows); let g = '';\n  const t0 = 5 * 60, t1 = 24 * 60, ty = function (m) { return Y + (m - t0) / (t1 - t0) * H; };\n  [6, 12, 18, 24].forEach(function (h) { const y = ty(h * 60); g += '<line x1=\"' + X + '\" x2=\"' + (X + W) + '\" y1=\"' + y + '\" y2=\"' + y + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(X - 6, y + 4, String(h), { size: 10, fill: ZW_MUTED, anchor: 'end' }); });\n  const cw = W / 7;\n  for (let i = 0; i < 7; i++) {\n    const date = zwAdd(wk, i), d = dm[person + '|' + date]; const cx = X + i * cw + cw / 2;\n    g += zwTxt(cx, Y + H + 15, T.day[i], { size: 11, fill: i > 4 ? ZW_AMBER : ZW_MUTED, anchor: 'middle' });\n    if (!d) continue;\n    const bad = viol.filter(function (v) { return v.person === person && v.date === date && v.level === 'verstoss'; }).length > 0;\n    const hint = viol.filter(function (v) { return v.person === person && v.date === date; }).length > 0;\n    const y0 = ty(d.first), y1 = ty(d.last), bw = Math.min(26, cw - 10);\n    g += '<rect x=\"' + (cx - bw / 2) + '\" y=\"' + y0 + '\" width=\"' + bw + '\" height=\"' + Math.max(3, y1 - y0) + '\" rx=\"4\" fill=\"' + (bad ? '#f3b3b3' : '#a9c4fb') + '\" stroke=\"' + (bad ? ZW_RED : hint ? ZW_AMBER : ZW_BLUE) + '\" stroke-width=\"1.5\"/>';\n    g += zwTxt(cx, y0 - 4, zwFmtH(d.net, lang).replace(' h', ''), { size: 10, fill: bad ? ZW_RED : ZW_INK, anchor: 'middle', weight: 600 });\n  }\n  return g;\n}\nfunction zwBarsH(items, X, Y, W, rowH, max, lang, lines) {\n  let g = ''; const mx = max || Math.max.apply(null, items.map(function (i) { return i.net; }).concat([2400]));\n  lines.forEach(function (l) { const x = X + 120 + (W - 160) * l.min / mx; g += '<line x1=\"' + x + '\" x2=\"' + x + '\" y1=\"' + (Y - 6) + '\" y2=\"' + (Y + items.length * rowH) + '\" stroke=\"' + l.color + '\" stroke-dasharray=\"4 3\"/>' + zwTxt(x, Y - 10, l.label, { size: 10, fill: l.color, anchor: 'middle' }); });\n  items.forEach(function (it, i) {\n    const y = Y + i * rowH, w = (W - 160) * it.net / mx;\n    g += zwTxt(X, y + rowH / 2 + 3, it.name, { size: 12 }) + '<rect x=\"' + (X + 120) + '\" y=\"' + (y + 4) + '\" width=\"' + Math.max(2, w) + '\" height=\"' + (rowH - 10) + '\" rx=\"4\" fill=\"' + (it.color || ZW_BLUE) + '\"/>' + zwTxt(X + 126 + w, y + rowH / 2 + 3, zwFmtH(it.net, lang), { size: 11, fill: ZW_MUTED });\n  });\n  return g;\n}\nfunction zwPanel(x, y, w, h, title) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"' + h + '\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, title, { size: 13, weight: 700 }); }\nfunction zwKpi(x, y, w, label, val, color) { return '<rect x=\"' + x + '\" y=\"' + y + '\" width=\"' + w + '\" height=\"64\" rx=\"12\" fill=\"' + ZW_PANEL + '\"/>' + zwTxt(x + 16, y + 26, val, { size: 24, weight: 700, fill: color }) + zwTxt(x + 16, y + 48, label, { size: 12, fill: ZW_MUTED }); }\n\nfunction zwDashboard(st, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const rows = st.rows; const W = 1200; let g = '';\n  g += '<rect width=\"' + W + '\" height=\"900\" fill=\"' + ZW_BG + '\"/>';\n  g += zwTxt(32, 48, T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year, { size: 26, weight: 800 }) + zwTxt(32, 70, T.demo, { size: 13, fill: ZW_MUTED });\n  const kx = 560, kw = 140;\n  g += zwKpi(kx, 24, kw, T.hours, zwFmtH(st.totalNet, lang).replace(' h', ''), ZW_INK) + zwKpi(kx + 150, 24, kw, T.entries, String(st.entries), ZW_INK);\n  g += zwKpi(kx + 300, 24, kw, T.viol, String(st.counts.verstoss), st.counts.verstoss ? ZW_RED : ZW_OK) + zwKpi(kx + 450, 24, kw, T.hints, String(st.counts.hinweis), st.counts.hinweis ? ZW_AMBER : ZW_OK);\n  g += zwPanel(24, 110, 576, 230, T.team);\n  g += zwBarsH(st.people.map(function (p, i) { return { name: p.name, net: p.net, color: p.net > 2880 ? ZW_AMBER : ZW_BLUE }; }), 40, 150, 544, 40, 3600, lang, [{ min: 2400, color: ZW_MUTED, label: '40 h' }, { min: 2880, color: ZW_AMBER, label: '48 h' }]);\n  g += zwPanel(612, 110, 564, 230, T.proj);\n  g += zwBarsH(st.projects.map(function (p, i) { return { name: p.name, net: p.net, color: ZW_COLORS[i] }; }), 628, 150, 532, 40, Math.max.apply(null, st.projects.map(function (p) { return p.net; }).concat([1200])), lang, []);\n  g += zwPanel(24, 356, 1152, 330, T.blocks);\n  st.people.forEach(function (p, i) { const x = 52 + i * 286; g += zwTxt(x, 396, p.name, { size: 12, weight: 700 }) + zwBlocks(rows, p.name, st.week, x + 14, 408, 238, 240, lang, st.violations); });\n  g += zwPanel(24, 702, 1152, 180, (T.viol + ' & ' + T.hints));\n  const top = st.violations.slice(0, 5);\n  if (!top.length) g += zwTxt(44, 760, T.none, { size: 14, fill: ZW_OK });\n  top.forEach(function (v, i) { const y = 754 + i * 25; g += '<circle cx=\"46\" cy=\"' + (y - 4) + '\" r=\"5\" fill=\"' + (v.level === 'verstoss' ? ZW_RED : ZW_AMBER) + '\"/>' + zwTxt(60, y, v.person + ' · ' + v.date.slice(5).replace('-', '.') + '. · ' + zwMsg(v, lang), { size: 13 }); });\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1200 900\" width=\"1200\" height=\"900\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\" role=\"img\" aria-label=\"' + zwEsc(T.title) + '\">' + g + '</svg>';\n}\n// the page a person sees right after booking: own week, verdict\nfunction zwPersonChart(rows, person, wk, viol, lang) {\n  const T = ZW_T[lang] || ZW_T.de; const mine = viol.filter(function (v) { return v.person === person && v.date >= wk && v.date <= zwAdd(wk, 6); });\n  const net = Object.values(zwDayMap(rows)).filter(function (d) { return d.person === person && d.date >= wk && d.date <= zwAdd(wk, 6); }).reduce(function (a, d) { return a + d.net; }, 0);\n  let g = '<rect width=\"720\" height=\"330\" rx=\"14\" fill=\"' + ZW_BG + '\" stroke=\"' + ZW_GRID + '\"/>' + zwTxt(24, 36, person + ' · ' + T.kw + ' ' + zwKW(wk).week, { size: 18, weight: 800 }) + zwTxt(696, 36, zwFmtH(net, lang), { size: 18, weight: 800, anchor: 'end', fill: net > 2880 ? ZW_AMBER : ZW_INK });\n  g += zwBlocks(rows, person, wk, 56, 60, 640, 220, lang, mine);\n  return '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 720 330\" width=\"720\" height=\"330\" font-family=\"system-ui, -apple-system, Segoe UI, Roboto, sans-serif\">' + g + '</svg>';\n}\nfunction zwReportMd(st, lang, ai) {\n  const T = ZW_T[lang] || ZW_T.de; const fmt = function (m) { return zwFmtH(m, lang); };\n  let md = '# ' + T.title + ' · ' + T.kw + ' ' + st.kw + '/' + st.year + '\\n\\n*' + T.demo + '*\\n\\n';\n  if (ai) md += '> ' + ai + '\\n\\n';\n  md += '![](KW' + st.kw + '-dashboard.svg)\\n\\n| | ' + T.hours + ' |\\n|---|---|\\n' + st.people.map(function (p) { return '| ' + p.name + ' | ' + fmt(p.net) + ' |'; }).join('\\n') + '\\n\\n';\n  md += '## ' + T.viol + ' & ' + T.hints + '\\n\\n' + (st.violations.length ? st.violations.slice(0, 12).map(function (v) { return '- ' + (v.level === 'verstoss' ? '🔴' : '🟡') + ' **' + v.person + '** ' + v.date + ': ' + zwMsg(v, lang); }).join('\\n') : T.none) + '\\n';\n  return md;\n}\n\n// ---- demo data (fictional Musterbüro GmbH): three weeks of plausible bookings with a few planted problems ----------------\nfunction zwSeed(today) {\n  let x = 20261117; const rnd = function () { x = (x * 1664525 + 1013904223) % 4294967296; return x / 4294967296; };\n  const rows = []; let n = 0;\n  const add = function (person, date, s, e, pause, project, note) { n++; rows.push({ id: 'S' + String(n).padStart(3, '0'), person: person, date: date, start: s, end: e, pause: String(pause), project: project, note: note || '', created: date + 'T18:00:00' }); };\n  const pick = function () { const r = rnd(); return r < 0.4 ? ZW_PROJECTS[0] : r < 0.65 ? ZW_PROJECTS[1] : r < 0.85 ? ZW_PROJECTS[2] : ZW_PROJECTS[3]; };\n  const sh = function (m, k) { return zwHM(m + Math.round((rnd() - 0.5) * k / 15) * 15); };\n  const pat = { 'Anna Weber': { days: [0, 1, 2, 3, 4], s: 480, e: 990, p: 30 }, 'Ben Keller': { days: [0, 1, 2, 3, 4], s: 510, e: 1020, p: 45 },\n    'Chiara Rossi': { days: [0, 1, 2, 3], s: 450, e: 960, p: 30 }, 'Dario Fischer': { days: [0, 1, 2], s: 540, e: 1020, p: 30 } };\n  const mon = zwMon(today), lastMon = zwAdd(mon, -7), skip = {};\n  skip['Ben Keller|' + lastMon] = 1; skip['Ben Keller|' + zwAdd(lastMon, 1)] = 1; skip['Chiara Rossi|' + zwAdd(lastMon, 3)] = 1;\n  for (let d = zwAdd(today, -20); d < today; d = zwAdd(d, 1)) {\n    Object.keys(pat).forEach(function (name) {\n      const q = pat[name]; if (q.days.indexOf(zwDow(d)) < 0 || skip[name + '|' + d]) return;\n      const s = zwMin(sh(q.s, 30)), e = zwMin(sh(q.e, 30));\n      if (rnd() < 0.5) { const mid = s + Math.round((e - s) / 2 / 15) * 15; add(name, d, zwHM(s), zwHM(mid), 0, pick()); add(name, d, zwHM(mid), zwHM(e), q.p, pick()); }\n      else add(name, d, zwHM(s), zwHM(e), q.p, pick());\n    });\n  }\n  add('Ben Keller', lastMon, '10:00', '22:45', 45, ZW_PROJECTS[0], 'Release-Abend');\n  add('Ben Keller', zwAdd(lastMon, 1), '07:30', '16:00', 30, ZW_PROJECTS[1], 'Early shift after release');\n  add('Chiara Rossi', zwAdd(lastMon, 3), '07:30', '18:30', 30, ZW_PROJECTS[2], 'Angebotsfrist');\n  add('Dario Fischer', zwAdd(lastMon, 6), '11:00', '16:30', 30, ZW_PROJECTS[1], 'Wochenend-Support');\n  return rows;\n}\n\n// ---- overlap, absences, pages ---------------------------------------------------------------------------------------\nconst ZW_ABS = ['Urlaub', 'Krankheit', 'Gleitzeitausgleich'];\nfunction zwOverlap(rows, e) { const s = zwMin(e.start), t = zwMin(e.end); return rows.some(function (r) { return r.person === e.person && r.date === e.date && zwMin(r.start) < t && zwMin(r.end) > s; }); }\nfunction zwValidateAbs(inp, today) {\n  const err = []; const o = { person: String(inp.person || '').trim(), kind: String(inp.kind || '').trim(), from: String(inp.from || '').trim(), to: String(inp.to || '').trim() };\n  if (ZW_PEOPLE.indexOf(o.person) < 0) err.push('person'); if (ZW_ABS.indexOf(o.kind) < 0) err.push('kind');\n  if (zwTime(o.from) == null) err.push('date'); else if (zwTime(o.to) == null) err.push('date');\n  else if (o.to < o.from) err.push('order'); else if (o.from < zwAdd(today, -7) || o.to > zwAdd(today, 365)) err.push('range'); else if ((zwTime(o.to) - zwTime(o.from)) / 86400000 > 30) err.push('long');\n  return { ok: err.length === 0, errors: err, entry: o };\n}\nfunction zwIcs(id, e, nowIso) {\n  const d = function (s) { return s.replace(/-/g, ''); }; const st = nowIso.replace(/[-:]/g, '').replace(/\\.\\d+/, '').replace(/Z?$/, 'Z');\n  return ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//daniele-michelin.com//Zeit-Waechter//DE', 'BEGIN:VEVENT', 'UID:zw-' + id + '@daniele-michelin.com', 'DTSTAMP:' + st,\n    'DTSTART;VALUE=DATE:' + d(e.from), 'DTEND;VALUE=DATE:' + d(zwAdd(e.to, 1)), 'SUMMARY:' + e.person + ' · ' + e.kind, 'TRANSP:TRANSPARENT', 'CATEGORIES:Zeit-Waechter', 'END:VEVENT', 'END:VCALENDAR', ''].join('\\r\\n');\n}\n// who is absent on a day? reads the CalDAV REPORT answer (xml text with escaped ics)\nfunction zwAbsentFrom(xml, date) {\n  const t = String(xml || '').replace(/&#13;/g, '').replace(/&amp;/g, '&'); const out = [];\n  t.split('BEGIN:VEVENT').slice(1).forEach(function (ev) {\n    const m = /SUMMARY:([^\\r\\n<]+)/.exec(ev); const a = /DTSTART;VALUE=DATE:(\\d{8})/.exec(ev); const b = /DTEND;VALUE=DATE:(\\d{8})/.exec(ev);\n    if (!m || !a || !b) return; const f = a[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3'), e = b[1].replace(/(\\d{4})(\\d\\d)(\\d\\d)/, '$1-$2-$3');\n    const p = m[1].split(' · '); if (ZW_PEOPLE.indexOf(p[0]) >= 0 && ZW_ABS.indexOf(p[1]) >= 0 && date >= f && date < e) out.push({ person: p[0], kind: p[1] });\n  });\n  return out;\n}\nconst ZW_UI = {\n  de: { ok: 'Gebucht', hdr: 'Zeit-Wächter', bad: 'Das hat nicht geklappt', clean: 'Keine Regelverletzung. Sauber gebucht.', saved: 'In Nextcloud gespeichert', back: 'Zur Seite mit dem Live-Diagramm', net: 'netto', pause: 'Pause', again: 'Noch eine Buchung',\n    path: '/arbeitszeit-waechter/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Mitarbeiter unbekannt.', date: 'Datum ungültig.', date_future: 'Zeiten in der Zukunft kann man nicht buchen.', date_old: 'Älter als 60 Tage: bitte nicht im Demo-Formular nachbuchen.', start: 'Beginn ungültig.', end: 'Ende ungültig.', order: 'Das Ende muss nach dem Beginn liegen.', pause: 'Pause: ganze Minuten, 0 bis 240.', pause_long: 'Die Pause ist länger als der Arbeitsblock.', project: 'Projekt unbekannt.', kind: 'Art unbekannt.', range: 'Zeitraum außerhalb des erlaubten Bereichs.', long: 'Maximal 30 Tage am Stück.',\n      overlap: 'Für diese Zeit gibt es schon eine Buchung dieser Person.', cap: 'Demo-Limit für heute erreicht (150 Buchungen). Morgen wieder.', conflict: 'Zu viel los: Die Datei wurde gleichzeitig geändert. Bitte noch einmal absenden.', abs_cap: 'Demo-Limit: Es sind schon genug Abwesenheiten eingetragen. Montag wird alles zurückgesetzt.', down: 'Nextcloud antwortet gerade nicht. Bitte später noch einmal.' }, abs: 'Abwesenheit eingetragen', abs_note: 'Im Kalender «n8n-demo» steht jetzt ein Ganztagstermin. Bucht diese Person an einem dieser Tage Zeit, gibt der Zeit-Wächter einen Hinweis.' },\n  en: { ok: 'Booked', hdr: 'Timesheet Guardian', bad: 'That did not work', clean: 'No rule broken. Booked cleanly.', saved: 'Saved in Nextcloud', back: 'Back to the page with the live chart', net: 'net', pause: 'break', again: 'Book another entry',\n    path: '/en/timesheet-guardian/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Unknown employee.', date: 'Invalid date.', date_future: 'You cannot book time in the future.', date_old: 'Older than 60 days: please do not back-book in the demo form.', start: 'Invalid start.', end: 'Invalid end.', order: 'The end must be after the start.', pause: 'Break: whole minutes, 0 to 240.', pause_long: 'The break is longer than the work block.', project: 'Unknown project.', kind: 'Unknown type.', range: 'Period outside the allowed range.', long: 'At most 30 days in a row.',\n      overlap: 'This person already has a booking for that time.', cap: 'Demo limit for today reached (150 entries). Back tomorrow.', conflict: 'Busy: the file was changed at the same moment. Please submit again.', abs_cap: 'Demo limit: enough absences are listed already. Everything resets on Monday.', down: 'Nextcloud is not answering right now. Please try again later.' }, abs: 'Absence entered', abs_note: 'The calendar «n8n-demo» now holds an all-day event. If this person books time on one of those days, the Timesheet Guardian raises a hint.' },\n  it: { ok: 'Registrato', hdr: 'Il Guardiano delle ore', bad: 'Non ha funzionato', clean: 'Nessuna regola violata. Registrazione pulita.', saved: 'Salvato in Nextcloud', back: 'Torna alla pagina con il grafico live', net: 'nette', pause: 'pausa', again: 'Registra un\\'altra voce',\n    path: '/it/guardiano-delle-ore/', form: 'https://mikweb.eu/form/zeitwaechter',\n    e: { person: 'Dipendente sconosciuto.', date: 'Data non valida.', date_future: 'Non si possono registrare ore nel futuro.', date_old: 'Più vecchio di 60 giorni: nel modulo demo non registrare a ritroso.', start: 'Inizio non valido.', end: 'Fine non valida.', order: 'La fine deve essere dopo l\\'inizio.', pause: 'Pausa: minuti interi, da 0 a 240.', pause_long: 'La pausa è più lunga del blocco di lavoro.', project: 'Progetto sconosciuto.', kind: 'Tipo sconosciuto.', range: 'Periodo fuori dall\\'intervallo consentito.', long: 'Al massimo 30 giorni consecutivi.',\n      overlap: 'Per quell\\'orario questa persona ha già una registrazione.', cap: 'Limite demo di oggi raggiunto (150 voci). Si riprende domani.', conflict: 'Troppo traffico: il file è stato modificato nello stesso momento. Invia di nuovo.', abs_cap: 'Limite demo: ci sono già abbastanza assenze. Lunedì si azzera tutto.', down: 'Nextcloud non risponde ora. Riprova più tardi.' }, abs: 'Assenza registrata', abs_note: 'Nel calendario «n8n-demo» c\\'è ora un evento di un giorno intero. Se la persona registra ore in uno di quei giorni, il Guardiano segnala un avviso.' },\n};\nfunction zwPage(lang, title, inner, kind) {\n  const U = ZW_UI[lang] || ZW_UI.de; const col = kind === 'bad' ? '#d64545' : kind === 'warn' ? '#e0a02b' : '#16a085';\n  const css = ':root{color-scheme:light dark;--bg:#f4f7fb;--card:#fff;--ink:#1b2430;--mut:#6b7787;--line:#dde3ea}@media(prefers-color-scheme:dark){:root{--bg:#10151c;--card:#18202a;--ink:#e8edf3;--mut:#9aa7b6;--line:#2a3441}}'\n    + 'body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}main{max-width:760px;margin:0 auto;padding:28px 18px 48px}'\n    + '.c{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:22px 24px;margin:0 0 16px;border-top:5px solid ' + col + '}h1{font-size:26px;margin:0 0 6px}.m{color:var(--mut);font-size:14px}'\n    + 'ul{padding-left:0;list-style:none;margin:10px 0}li{padding:8px 12px;border-radius:10px;margin:6px 0;background:var(--bg)}li.r{border-left:4px solid #d64545}li.a{border-left:4px solid #e0a02b}svg{max-width:100%;height:auto}a{color:#2f6fed;font-weight:600}.f{margin-top:18px;font-size:14px}';\n  return '<!doctype html><html lang=\"' + lang + '\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>' + zwEsc(title) + '</title><style>' + css + '</style></head><body><main>'\n    + '<div class=\"c\"><div class=\"m\">' + zwEsc(U.hdr) + '</div><h1>' + zwEsc(title) + '</h1>' + inner + '</div>'\n    + '<p class=\"f\"><a href=\"https://daniele-michelin.com' + U.path + '\">' + zwEsc(U.back) + '</a> · <a href=\"' + U.form + '\">' + zwEsc(U.again) + '</a></p></main></body></html>';\n}\nfunction zwErrPage(codes, lang) { const U = ZW_UI[lang] || ZW_UI.de; return zwPage(lang, U.bad, '<ul>' + codes.map(function (c) { return '<li class=\"r\">' + zwEsc((U.e[c] || c)) + '</li>'; }).join('') + '</ul>', 'bad'); }\n// ---- QR punching: SHA-256 / HMAC in plain JS (the n8n Code sandbox has no require/crypto), codes, devices, state machine -------------\nconst ZW_SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\nfunction zwUtf8(s) {\n  const out = []; s = String(s == null ? '' : s);\n  for (let i = 0; i < s.length; i++) {\n    let c = s.charCodeAt(i);\n    if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) { const d = s.charCodeAt(i + 1); if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; } }\n    if (c < 0x80) out.push(c);\n    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));\n    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n    else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));\n  }\n  return out;\n}\nfunction zwSha256Bytes(msg) {\n  const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n  const b = msg.slice(), bits = msg.length * 8; b.push(0x80); while (b.length % 64 !== 56) b.push(0);\n  [Math.floor(bits / 4294967296), bits >>> 0].forEach(function (x) { b.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); });\n  const w = new Array(64), rr = function (x, n) { return (x >>> n) | (x << (32 - n)); };\n  for (let o = 0; o < b.length; o += 64) {\n    for (let i = 0; i < 16; i++) w[i] = ((b[o + 4 * i] << 24) | (b[o + 4 * i + 1] << 16) | (b[o + 4 * i + 2] << 8) | b[o + 4 * i + 3]) | 0;\n    for (let i = 16; i < 64; i++) { const s0 = rr(w[i - 15], 7) ^ rr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rr(w[i - 2], 17) ^ rr(w[i - 2], 19) ^ (w[i - 2] >>> 10); w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0; }\n    let a = H[0], bb = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];\n    for (let i = 0; i < 64; i++) {\n      const t1 = (h + (rr(e, 6) ^ rr(e, 11) ^ rr(e, 25)) + ((e & f) ^ (~e & g)) + ZW_SHA_K[i] + w[i]) | 0, t2 = ((rr(a, 2) ^ rr(a, 13) ^ rr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;\n      h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;\n    }\n    H[0] = (H[0] + a) | 0; H[1] = (H[1] + bb) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0;\n  }\n  const out = []; H.forEach(function (x) { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); }); return out;\n}\nfunction zwHex(bytes) { return bytes.map(function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join(''); }\nfunction zwSha256(s) { return zwHex(zwSha256Bytes(typeof s === 'string' ? zwUtf8(s) : s)); }\nfunction zwHmac(key, msg) {                                                // strings (UTF-8) or byte arrays\n  let k = typeof key === 'string' ? zwUtf8(key) : key.slice(); const m = typeof msg === 'string' ? zwUtf8(msg) : msg;\n  if (k.length > 64) k = zwSha256Bytes(k); while (k.length < 64) k.push(0);\n  return zwHex(zwSha256Bytes(k.map(function (x) { return x ^ 0x5c; }).concat(zwSha256Bytes(k.map(function (x) { return x ^ 0x36; }).concat(m)))));\n}\nconst ZW_KINDS = ['start', 'pause', 'resume', 'end'];\nconst ZW_PUNCH_HEAD = 'id,person,date,time,kind,note,created';\nconst ZW_PUNCH_PROJECT = 'Interna';                                        // QR punches carry no project: they are booked here\nfunction zwPunchCode(secret, date, kind) { return zwHmac(secret, date + '|' + kind).slice(0, 8); }\nfunction zwPunchCodes(secret, date) { const o = {}; ZW_KINDS.forEach(function (k) { o[k] = zwPunchCode(secret, date, k); }); return o; }\nfunction zwDeviceId(secret, salt) {                                        // 128 bit: HMAC(secret, clock + Math.random + crypto.getRandomValues when present)\n  let r = ''; for (let i = 0; i < 4; i++) r += Math.random().toString(36).slice(2) + '|';\n  try { if (typeof crypto !== 'undefined' && crypto.getRandomValues) { const a = new Uint32Array(4); crypto.getRandomValues(a); r += Array.prototype.join.call(a, '.'); } } catch (e) { }\n  return zwHmac(secret, 'dev|' + Date.now() + '|' + String(salt || '') + '|' + r).slice(0, 32);\n}\nfunction zwEtag(res) { return String(((res || {}).headers || {}).etag || '').replace(/-(gzip|br|deflate)(?=\"$)/, ''); }\nfunction zwPunchStringify(rows) {\n  const cols = ZW_PUNCH_HEAD.split(',');\n  return ZW_PUNCH_HEAD + '\\n' + rows.map(function (r) { return cols.map(function (c) { return zwCsvCell(r[c]); }).join(','); }).join('\\n') + (rows.length ? '\\n' : '');\n}\n// day state of ONE person from his punches in file order: none -> working -> (pause -> working)* -> done. net = minutes worked without pauses\nfunction zwPunchDay(rows, nowMin) {\n  let state = 'none', start = null, end = null, last = null, pAt = null, pause = 0, work = 0; const notes = [];\n  rows.forEach(function (r) {\n    const t = zwMin(r.time); if (t == null || !zwPunchOk(state, r.kind)) return;\n    if (r.note) notes.push(r.note);\n    if (r.kind === 'start') { state = 'working'; start = t; last = t; }\n    else if (r.kind === 'pause') { work += Math.max(0, t - last); state = 'pause'; pAt = t; }\n    else if (r.kind === 'resume') { pause += Math.max(0, t - pAt); state = 'working'; last = t; }\n    else if (r.kind === 'end') { work += Math.max(0, t - last); state = 'done'; end = t; }\n  });\n  const net = work + (state === 'working' && nowMin != null ? Math.max(0, nowMin - last) : 0);\n  return { state: state, start: start, end: end, pause: pause, net: net, notes: notes };\n}\nfunction zwPunchOk(state, kind) { return (state === 'none' && kind === 'start') || (state === 'working' && (kind === 'pause' || kind === 'end')) || (state === 'pause' && kind === 'resume'); }\n// the booking row of a finished day: one block start..end, pause = sum of pause..resume (same net and break logic as the form booking)\nfunction zwPunchBook(day, person, date) { return { person: person, date: date, start: zwHM(day.start), end: zwHM(day.end), pause: String(day.pause), project: ZW_PUNCH_PROJECT, note: day.notes.join(' · ') }; }\nif (typeof module !== 'undefined' && module.exports) module.exports = { ZW_PEOPLE, ZW_PROJECTS, ZW_T, zwMin, zwHM, zwFmtH, zwTime, zwAdd, zwDow, zwMon, zwKW, zwCsvParse, zwCsvStringify, zwValidate, zwDayMap, zwEvaluate, zwNewViolations, zwMsg, zwRetention, zwStats, zwDashboard, zwPersonChart, zwReportMd, zwCsvCell, zwSeed, zwBody, zwOverlap, zwValidateAbs, zwIcs, zwAbsentFrom, zwPage, zwErrPage, ZW_UI, ZW_ABS, zwNote, zwUtf8, zwSha256Bytes, zwSha256, zwHmac, zwHex, ZW_KINDS, ZW_PUNCH_HEAD, ZW_PUNCH_PROJECT, zwPunchCode, zwPunchCodes, zwDeviceId, zwEtag, zwPunchStringify, zwPunchDay, zwPunchOk, zwPunchBook };\n\nconst cfg = $('Demo-Bereich festlegen').first().json, q = $('Stempel: Anfrage').first().json, person = $('Stempel: Geräte').last().json.person;\nconst res = $('Stempel lesen').last().json, st = Number(res.statusCode);\nconst fin = r => [{ json: { mode: 'resp', resp: r } }];\nif (st !== 200 && st !== 404) return fin({ ok: false, error: 'down' });\nlet rows = [], etag = '';\nif (st === 200) { const txt = zwBody(res); rows = zwCsvParse(txt); etag = zwEtag(res); if (!rows.length && txt.replace(/\\s/g, '').length > ZW_PUNCH_HEAD.length + 2) return fin({ ok: false, error: 'down' }); }\nrows = rows.filter(r => r.date >= zwAdd(cfg.today, -7));\nconst nowHM = cfg.nowLocal.slice(11, 16), nowMin = zwMin(nowHM);                               // server clock, Berlin: never from the client\nconst mine = rows.filter(r => r.person === person && r.date === cfg.today);\nconst day = zwPunchDay(mine, nowMin);\nif (q.action === 'me') return fin({ ok: true, person, state: day.state, start: day.start == null ? null : zwHM(day.start), netMin: day.net });\nif (!zwPunchOk(day.state, q.kind)) return fin({ ok: false, error: 'wrong_state' });\nif (rows.filter(r => String(r.created || '').slice(0, 10) === cfg.today).length >= 300) return fin({ ok: false, error: 'cap' });\nconst row = { id: 'P' + Date.now().toString(36) + Math.floor(Math.random() * 1296).toString(36), person, date: cfg.today, time: nowHM, kind: q.kind, note: zwNote(q.note), created: cfg.nowLocal };\nconst d2 = zwPunchDay(mine.concat([row]), nowMin);\nconst out = { mode: 'write', csv: zwPunchStringify(rows.concat([row])), putHeaders: etag ? { 'If-Match': etag } : { 'If-None-Match': '*' },\n  resp: { ok: true, person, kind: q.kind, time: nowHM, state: d2.state, netMin: d2.net, violations: [], booked: false } };\nif (q.kind === 'end') out.book = zwPunchBook(d2, person, cfg.today);\nreturn [{ json: out }];"
   },
   "id": "q11",
   "name": "Stempel: Zustand",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    2220,
    2700
   ],
   "notes": "Zustandsautomat je Person und Tag: start → (pause → resume)* → end. Zeit = Serveruhr Berlin. Bei «end» entsteht die Buchungszeile für den bestehenden Buchungsweg."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q12",
       "leftValue": "={{ $json.mode === 'resp' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q12",
   "name": "Stempel: Fertig?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2460,
    2700
   ]
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.punches }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendHeaders": true,
    "specifyHeaders": "json",
    "jsonHeaders": "={{ JSON.stringify($json.putHeaders) }}",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/csv; charset=utf-8",
    "body": "={{ $json.csv }}"
   },
   "id": "q13",
   "name": "Stempel speichern",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    2700,
    2760
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "Gleiches Locking wie die Buchung: If-Match mit dem ETag von vorhin; 412 → neu lesen, Zustand neu prüfen."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q14",
       "leftValue": "={{ [200, 201, 204].includes($json.statusCode) }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q14",
   "name": "Stempel gespeichert?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2940,
    2760
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q15",
       "leftValue": "={{ $runIndex < 3 }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q15",
   "name": "Stempel nochmal?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    2940,
    2940
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q16",
       "leftValue": "={{ !!$('Stempel: Zustand').last().json.book }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q16",
   "name": "Stempel: Ende?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    3180,
    2760
   ],
   "notes": "Nur «end» läuft weiter in den normalen Buchungsweg (Eingabe prüfen → … → Folgen planen)."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "return [{ json: { resp: $('Stempel: Zustand').last().json.resp } }];"
   },
   "id": "q17",
   "name": "Stempel: Antwort (Stempel)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3420,
    2820
   ]
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "return [{ json: { resp: { ok: false, error: 'down' } } }];"
   },
   "id": "q18",
   "name": "Stempel: Fehler",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3180,
    2940
   ]
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q19",
       "leftValue": "={{ $('Demo-Bereich festlegen').first().json.route === 'punch' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q19",
   "name": "Fehler: Stempel?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    1260,
    640
   ],
   "notes": "Abbruch im Buchungsweg: bei QR-Stempel JSON statt Formularseite."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst base = $('Stempel: Zustand').last().json.resp;\nconst code = (($json.errors || [])[0]) || 'invalid';\nreturn [{ json: { resp: Object.assign({}, base, { violations: [], booked: false, book_error: String(code) }) } }];"
   },
   "id": "q20",
   "name": "Stempel: Antwort (nicht gebucht)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    1500,
    640
   ],
   "notes": "Der Stempel ist gespeichert, die Buchung nicht (Überschneidung, Limit, Konflikt, 0 Minuten). booked:false + book_error."
  },
  {
   "parameters": {
    "conditions": {
     "options": {
      "caseSensitive": true,
      "leftValue": "",
      "typeValidation": "loose"
     },
     "conditions": [
      {
       "id": "q21",
       "leftValue": "={{ $('Demo-Bereich festlegen').first().json.route === 'punch' }}",
       "rightValue": "",
       "operator": {
        "type": "boolean",
        "operation": "true",
        "singleValue": true
       }
      }
     ],
     "combinator": "and"
    },
    "options": {}
   },
   "id": "q21",
   "name": "Ergebnis: Stempel?",
   "type": "n8n-nodes-base.if",
   "typeVersion": 2.2,
   "position": [
    4380,
    -80
   ],
   "notes": "Buchung durch: bei QR-Stempel JSON (neue Verstöße, booked:true) statt Formularseite."
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "\nconst base = $('Stempel: Zustand').last().json.resp, f = $('Folgen planen').first().json;\nreturn [{ json: { resp: Object.assign({}, base, { violations: f.mine || [], booked: true }) } }];"
   },
   "id": "q22",
   "name": "Stempel: Antwort (Buchung)",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    4620,
    -160
   ]
  },
  {
   "parameters": {
    "mode": "runOnceForAllItems",
    "jsCode": "return [{ json: $json.resp }];"
   },
   "id": "q23",
   "name": "Stempel: Antwort",
   "type": "n8n-nodes-base.code",
   "typeVersion": 2,
   "position": [
    3660,
    2300
   ],
   "notes": "Einziges Ende aller QR-Wege: gibt das fertige JSON zurück."
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.devices }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "application/json",
    "body": "{}"
   },
   "id": "s4a",
   "name": "Geräte zurücksetzen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1620,
    1960
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "Montag: alle Demo-Geräte weg (die Demo registriert sich neu)."
  },
  {
   "parameters": {
    "method": "PUT",
    "url": "={{ $('Demo-Bereich festlegen').first().json.urls.punches }}",
    "options": {
     "webdavMethods": true,
     "timeout": 20000,
     "response": {
      "response": {
       "fullResponse": true,
       "neverError": true,
       "responseFormat": "text"
      }
     }
    },
    "authentication": "genericCredentialType",
    "genericAuthType": "httpBasicAuth",
    "sendBody": true,
    "contentType": "raw",
    "rawContentType": "text/csv; charset=utf-8",
    "body": "id,person,date,time,kind,note,created\n"
   },
   "id": "s4b",
   "name": "Stempel zurücksetzen",
   "type": "n8n-nodes-base.httpRequest",
   "typeVersion": 4.2,
   "position": [
    1680,
    1960
   ],
   "credentials": {
    "httpBasicAuth": {
     "id": "",
     "name": "Nextcloud (Basic Auth: Benutzer + App-Passwort)"
    }
   },
   "notes": "Montag: alle Stempel weg."
  },
  {
   "parameters": {
    "content": "## Timesheet Guardian (Arbeitszeit-Wächter)\nTwo **n8n Forms** (book time, report absence) → checks against the German Working Hours Act (§3 10 h/day, §4 breaks 30/45 min, §5 11 h rest, §9 Sundays) → `zeiten.csv` in **Nextcloud** (WebDAV, optimistic locking with ETag/If-Match) → Deck card + Talk message on a new violation → weekly report (Markdown + SVG dashboard) every Friday.\n\n**Set up:** 1) credential *Basic Auth* (Nextcloud user + app password) on every Nextcloud HTTP node, 2) edit the node *Demo-Bereich festlegen* (host, user, calendar, Talk token, Deck board/stack), 3) replace the fictional names/projects in the form fields **and** at the top of the Code nodes (`ZW_PEOPLE`, `ZW_PROJECTS`), 4) activate. Forms live at `/form/zeitwaechter` and `/form/zeitwaechter-abwesenheit`.\n\n**QR punching (extra):** POST webhook `zeitwaechter-stempel-CHANGE-ME` (change the path, it is the secret) with JSON `register` (person → device id), `qr` (today's four codes), `punch` (device, kind start/pause/resume/end, code, note) and `me`. Codes = first 8 hex of HMAC-SHA256(secret, date|kind); replace `CHANGE-ME-LONG-RANDOM-SECRET` in the Code nodes *Stempel: Anfrage* and *Stempel: Geräte*. Devices are stored as sha256 only (`geraete.json`, max 40), punches in `stempel.csv`, the time is always the server clock. On `end` the day goes through the same booking and rule check as the form. Needs no other backend.\n\n**Know:** not legal advice. The rules are deterministic Code; the AI only words the weekly summary and never sees names. Deactivate the Monday demo reset in production.",
    "height": 560,
    "width": 640,
    "color": 5
   },
   "id": "note1",
   "name": "Hinweis",
   "type": "n8n-nodes-base.stickyNote",
   "typeVersion": 1,
   "position": [
    -40,
    -260
   ]
  }
 ],
 "connections": {
  "Zeit buchen (Formular)": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Abwesenheit melden (Formular)": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Bericht per Webhook": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel-Webhook (QR)": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Freitag 15:00": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Montag 06:00 (Demo zurücksetzen)": {
   "main": [
    [
     {
      "node": "Demo-Bereich festlegen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Demo-Bereich festlegen": {
   "main": [
    [
     {
      "node": "Welcher Weg?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Welcher Weg?": {
   "main": [
    [
     {
      "node": "Eingabe prüfen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Abwesenheit prüfen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "CSV lesen (Bericht)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Ordner anlegen (Zeit)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel: Anfrage",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Eingabe prüfen": {
   "main": [
    [
     {
      "node": "Eingabe ok?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Eingabe ok?": {
   "main": [
    [
     {
      "node": "Kalender: Abwesenheit am Tag?",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Fehler: Stempel?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: Abwesenheit am Tag?": {
   "main": [
    [
     {
      "node": "CSV lesen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "CSV lesen": {
   "main": [
    [
     {
      "node": "Buchen & prüfen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Buchen & prüfen": {
   "main": [
    [
     {
      "node": "Buchung ok?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Buchung ok?": {
   "main": [
    [
     {
      "node": "CSV speichern",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Fehler: Stempel?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "CSV speichern": {
   "main": [
    [
     {
      "node": "Gespeichert?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Gespeichert?": {
   "main": [
    [
     {
      "node": "Deck: Stapel lesen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Nochmal versuchen?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Nochmal versuchen?": {
   "main": [
    [
     {
      "node": "CSV lesen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Konflikt-Seite",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Konflikt-Seite": {
   "main": [
    [
     {
      "node": "Fehler: Stempel?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Deck: Stapel lesen": {
   "main": [
    [
     {
      "node": "Folgen planen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Folgen planen": {
   "main": [
    [
     {
      "node": "Verstoß melden?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Verstoß melden?": {
   "main": [
    [
     {
      "node": "Deck: Karte anlegen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Ergebnis: Stempel?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Deck: Karte anlegen": {
   "main": [
    [
     {
      "node": "Talk: Hinweis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Talk: Hinweis": {
   "main": [
    [
     {
      "node": "Ergebnis: Stempel?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Abwesenheit prüfen": {
   "main": [
    [
     {
      "node": "Abwesenheit ok?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Abwesenheit ok?": {
   "main": [
    [
     {
      "node": "Kalender: Liste (Limit)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Seite: Hinweis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: Liste (Limit)": {
   "main": [
    [
     {
      "node": "Limit prüfen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Limit prüfen": {
   "main": [
    [
     {
      "node": "Limit frei?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Limit frei?": {
   "main": [
    [
     {
      "node": "Kalender: Abwesenheit eintragen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Seite: Hinweis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: Abwesenheit eintragen": {
   "main": [
    [
     {
      "node": "Talk: Abwesenheit",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Talk: Abwesenheit": {
   "main": [
    [
     {
      "node": "Seite: Bestätigung",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "CSV lesen (Bericht)": {
   "main": [
    [
     {
      "node": "Auswerten & Diagramme",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Auswerten & Diagramme": {
   "main": [
    [
     {
      "node": "Kommentar (KI)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kommentar (KI)": {
   "main": [
    [
     {
      "node": "Bericht bauen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Bericht bauen": {
   "main": [
    [
     {
      "node": "Ordner anlegen (Berichte)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ordner anlegen (Berichte)": {
   "main": [
    [
     {
      "node": "Dashboard speichern (SVG)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Dashboard speichern (SVG)": {
   "main": [
    [
     {
      "node": "Bericht speichern (Markdown)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Bericht speichern (Markdown)": {
   "main": [
    [
     {
      "node": "Talk: Wochenbericht",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Talk: Wochenbericht": {
   "main": [
    [
     {
      "node": "Antwort (Bericht)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ordner anlegen (Zeit)": {
   "main": [
    [
     {
      "node": "Ordner anlegen (Berichte, Start)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ordner anlegen (Berichte, Start)": {
   "main": [
    [
     {
      "node": "Demo-Daten erzeugen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Demo-Daten erzeugen": {
   "main": [
    [
     {
      "node": "Demo-Daten schreiben",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Demo-Daten schreiben": {
   "main": [
    [
     {
      "node": "Geräte zurücksetzen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Geräte zurücksetzen": {
   "main": [
    [
     {
      "node": "Stempel zurücksetzen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel zurücksetzen": {
   "main": [
    [
     {
      "node": "Kalender: Liste (aufräumen)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: Liste (aufräumen)": {
   "main": [
    [
     {
      "node": "Aufräumen: Kalender-Liste",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Aufräumen: Kalender-Liste": {
   "main": [
    [
     {
      "node": "Kalender: etwas zu löschen?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: etwas zu löschen?": {
   "main": [
    [
     {
      "node": "Kalender: Abwesenheit löschen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Deck: Stapel lesen (aufräumen)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Kalender: Abwesenheit löschen": {
   "main": [
    [
     {
      "node": "Deck: Stapel lesen (aufräumen)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Deck: Stapel lesen (aufräumen)": {
   "main": [
    [
     {
      "node": "Aufräumen: Deck-Liste",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Aufräumen: Deck-Liste": {
   "main": [
    [
     {
      "node": "Deck: etwas zu löschen?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Deck: etwas zu löschen?": {
   "main": [
    [
     {
      "node": "Deck: Karte löschen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Antwort (Demo)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Deck: Karte löschen": {
   "main": [
    [
     {
      "node": "Antwort (Demo)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Fehler: Stempel?": {
   "main": [
    [
     {
      "node": "Stempel: Antwort (nicht gebucht)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Seite: Hinweis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Antwort (nicht gebucht)": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Ergebnis: Stempel?": {
   "main": [
    [
     {
      "node": "Stempel: Antwort (Buchung)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Seite: Ergebnis",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Antwort (Buchung)": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Anfrage": {
   "main": [
    [
     {
      "node": "Stempel: Sofort antworten?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Sofort antworten?": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Geräte lesen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Geräte lesen": {
   "main": [
    [
     {
      "node": "Stempel: Geräte",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Geräte": {
   "main": [
    [
     {
      "node": "Stempel: Weiterleiten",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Weiterleiten": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Geräte speichern",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel lesen",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Geräte speichern": {
   "main": [
    [
     {
      "node": "Geräte gespeichert?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Geräte gespeichert?": {
   "main": [
    [
     {
      "node": "Stempel: Antwort (Gerät)",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Geräte nochmal?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Geräte nochmal?": {
   "main": [
    [
     {
      "node": "Geräte lesen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel: Fehler",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Antwort (Gerät)": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel lesen": {
   "main": [
    [
     {
      "node": "Stempel: Zustand",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Zustand": {
   "main": [
    [
     {
      "node": "Stempel: Fertig?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Fertig?": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel speichern",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel speichern": {
   "main": [
    [
     {
      "node": "Stempel gespeichert?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel gespeichert?": {
   "main": [
    [
     {
      "node": "Stempel: Ende?",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel nochmal?",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel nochmal?": {
   "main": [
    [
     {
      "node": "Stempel lesen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel: Fehler",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Ende?": {
   "main": [
    [
     {
      "node": "Eingabe prüfen",
      "type": "main",
      "index": 0
     }
    ],
    [
     {
      "node": "Stempel: Antwort (Stempel)",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Antwort (Stempel)": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ]
   ]
  },
  "Stempel: Fehler": {
   "main": [
    [
     {
      "node": "Stempel: Antwort",
      "type": "main",
      "index": 0
     }
    ]
   ]
  }
 },
 "active": false,
 "settings": {
  "executionOrder": "v1",
  "timezone": "Europe/Berlin",
  "saveDataSuccessExecution": "none",
  "saveDataErrorExecution": "all",
  "saveManualExecutions": false
 },
 "pinData": {}
}