# Zeit-Wächter nella tua istanza Nextcloud / in your own Nextcloud

Italiano sotto, English further down. File: `setup.sh` (prepara Nextcloud), `uninstall.sh` (rimuove), `../../assets/n8n/zeitwaechter.json` (workflow n8n).

---

## Italiano

### Requisiti

- Nextcloud 28 o più recente, con le app **Calendar**, **Deck**, **Talk** (spreed) e **Files** attive.
- **n8n 2.x** raggiungibile da Nextcloud e viceversa (il workflow chiama WebDAV, CalDAV, le API Deck e Talk).
- **HTTPS** su Nextcloud e su n8n (i QR-code e la PWA funzionano solo in contesto sicuro).
- Accesso a `occ` (shell sul server o `docker exec`) con un utente admin.

### Passi

**1. Prepara Nextcloud con `setup.sh`** (idempotente: si può rilanciare, non tocca impostazioni globali tranne l'esclusione dalla condivisione di `zeit-demo`).

Variabili: `OCC` (come lanciare occ), `DEMO` (1 = crea 4 dipendenti fittizi + capo demo, 0 = no), `CHEF_UID` / `CHEF_NAME` / `CHEF_MAIL` (il tuo vero capo: account normale, non admin, invito per mail), `SECRETS_DIR` (dove finisce `bot.pass`, chmod 600).

```bash
# Docker AIO (predefinito dello script)
CHEF_UID=mario CHEF_NAME="Mario Rossi" CHEF_MAIL=mario@azienda.it DEMO=0 ./setup.sh

# Docker Compose (nome servizio "app")
OCC="docker compose exec -T -u www-data -e OC_PASS app php occ" DEMO=0 CHEF_UID=mario CHEF_MAIL=mario@azienda.it ./setup.sh

# Bare metal (Apache/nginx + PHP-FPM); sudo deve passare OC_PASS
OCC="sudo -u www-data --preserve-env=OC_PASS php /var/www/nextcloud/occ" DEMO=0 SECRETS_DIR=/root/zeit-secrets ./setup.sh
```

Controllo dello stato senza modificare nulla: `./setup.sh --check`. Disattivare i conti demo: `./setup.sh --demo-off` (con `--purge` li cancella, solo se sono in `zeit-demo`).

**2. Credenziale in n8n.** Credentials, Create, **Basic Auth**: utente `zeitwaechter`, password dal file `bot.pass`. Meglio: accedi come `zeitwaechter`, Impostazioni, Sicurezza, crea una **password per app** e usa quella (revocabile senza cambiare la password del conto). Assegna la credenziale a tutti i nodi HTTP Nextcloud del workflow.

**3. Importa il workflow.** n8n, Workflows, Import from File: `assets/n8n/zeitwaechter.json` (o dal sito: `/assets/n8n/zeitwaechter.json`). Apri il nodo **«Demo-Bereich festlegen»** e sostituisci i segnaposto:

| Costante | Valore |
|---|---|
| `NC` | `https://cloud.tuodominio.it` |
| `USER` | `zeitwaechter` (l'utente del bot: calendario e cartella `Zeit/` stanno nel suo spazio) |
| `CAL` | slug del calendario (di norma `personal`) |
| `DECK` / stack | id della board Deck e dello stack (di norma `1`) |
| `TALK` | token della stanza Talk (nell'URL della conversazione) |

Crea prima nel conto del bot: un calendario, una board Deck con almeno uno stack, una conversazione Talk. Condividili con `zeit-team` / `zeit-chef` come serve (vedi «Dove finiscono i dati»).

**4. Segreti.** Cambia (a) il percorso dei due webhook `zeitwaechter-bericht-CHANGE-ME` e `zeitwaechter-stempel-CHANGE-ME` (il percorso è il segreto: usa 24+ caratteri casuali) e (b) il segreto HMAC `CHANGE-ME-LONG-RANDOM-SECRET`, **identico in tutti i nodi Code** che lo contengono (cerca la stringa con la ricerca di n8n; `openssl rand -hex 32`). Se cambia il segreto, i QR del giorno cambiano e i telefoni già registrati restano da registrare di nuovo.

**5. Attiva** il workflow (interruttore in alto a destra). Prova il modulo `https://TUO-N8N/form/zeitwaechter`: deve comparire un evento nel calendario, una scheda Deck e un messaggio in Talk.

**6. App sul telefono (PWA, facoltativa).** Le pagine `/zeit/`, `/zeit/anmelden/`, `/zeit/s/`, `/zeit-qr/` sono statiche (cartelle `zeit/`, `zeit-qr/` e `assets/zeitwaechter-app.*`, `assets/zeitwaechter-core.js`, `assets/zeit-*.png` del sito). Il PHP `zeit-punch.php` è un proxy same-origin verso il webhook di stampa di n8n: legge il percorso del webhook dal file `private/zeit-punch-hook` (una riga, fuori dalla document root) e si aspetta n8n su `http://127.0.0.1:5678` (variabile d'ambiente `ZP_N8N`, cartella privata `ZP_PRIV`). Modifica in `zeit-punch.php` l'elenco `ZP_PEOPLE` con i nomi del tuo team. Esempio nginx:

```nginx
location = /zeit-punch.php { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/zeit-punch.php; fastcgi_pass unix:/run/php/php-fpm.sock; }
location ^~ /private/ { deny all; }          # meglio: la cartella private fuori dalla root
```

Senza PWA: usa solo i due moduli n8n (`/form/zeitwaechter`, `/form/zeitwaechter-abwesenheit`) e stampa i QR dal webhook `qr`.

### Login Flow v2

È il flusso ufficiale con cui Nextcloud rilascia una **password per app** senza che l'utente digiti la password nel software terzo: il client chiama `POST /index.php/login/v2`, l'utente apre l'indirizzo restituito nel browser e approva, il client ottiene `loginName` e `appPassword` (revocabili in Impostazioni, Sicurezza). Se la versione del workflow che importi lo usa, serve solo per ottenere la password per app del bot al punto 2; in alternativa creala a mano come descritto.

### Ruoli

| Gruppo | Chi | Può |
|---|---|---|
| `zeit-team` | dipendenti | vedono solo i propri dati (cartella/calendario condivisi per utente) |
| `zeit-chef` | capo | vede tutto il team |
| `zeit-demo` | conti fittizi | non possono condividere, quota 20 MB, nessun dato reale |

### Dove finiscono i dati

| Dove | Cosa | Chi lo vede |
|---|---|---|
| Calendario del bot | un evento per giornata lavorata o assenza | condiviso per utente/gruppo |
| Deck (board del bot) | una scheda per segnalazione o violazione ArbZG | `zeit-chef`, il diretto interessato |
| Talk (stanza del bot) | avvisi e riepilogo del venerdì | membri della stanza |
| Files del bot, `Zeit/` | `zeiten.csv`, `stempel.csv`, `geraete.json`, `Berichte/` | condivisione per utente/gruppo, nessuna pubblica |
| n8n | solo esecuzioni transitorie | amministratore n8n; riduci la conservazione delle esecuzioni |

### Privacy

Sono dati personali di lavoratori. Base giuridica tipica: obbligo di registrare l'orario (in Germania § 16 ArbZG, in Italia D.Lgs. 66/2003) e, per l'uso del sistema, art. 6.1(b)/(c) GDPR; in Italia l'art. 4 dello Statuto dei lavoratori richiede accordo sindacale o autorizzazione per strumenti da cui può derivare controllo a distanza; in Germania serve il consiglio aziendale (§ 87 BetrVG) se esiste. Consegna ai dipendenti un'informativa (art. 13 GDPR) che indichi finalità, destinatari (capo), tempi e diritti. **Conservazione: 70 giorni** nei file di lavoro (il workflow applica `zwRetention(..., 70)`); prevedi un'archiviazione separata solo se la legge lo richiede (la normativa tedesca esige conservazione di 2 anni delle ore oltre 8 al giorno). Questo non è consulenza legale: chiedi al tuo DPO o consulente.

### Rimozione

```bash
./uninstall.sh --dry-run            # mostra cosa farebbe
./uninstall.sh                      # chiede conferma a ogni passo: disattiva (non cancella) i conti, toglie gruppi e esclusione dalla condivisione
./uninstall.sh --delete-data        # permette di CANCELLARE bot e conti demo con i dati (conferma scritta LOESCHEN)
```

Gli utenti veri (es. `CHEF_UID`) non vengono mai cancellati. Poi: disattiva il workflow in n8n, elimina la credenziale, rimuovi dal web server le pagine PWA e il file `private/zeit-punch-hook`.

---

## English

### Requirements

- Nextcloud 28 or newer with **Calendar**, **Deck**, **Talk** (spreed) and **Files** enabled.
- **n8n 2.x** reachable from Nextcloud and the other way round.
- **HTTPS** on both (QR codes and the PWA need a secure context).
- `occ` access (server shell or `docker exec`) as an admin.

### Steps

1. **Run `setup.sh`** (idempotent). Variables: `OCC`, `DEMO` (1 = 4 fictitious staff + demo boss, 0 = none), `CHEF_UID`/`CHEF_NAME`/`CHEF_MAIL`, `SECRETS_DIR` (where `bot.pass` is written, chmod 600). Examples are in the Italian section (Docker AIO, Docker Compose, bare metal `sudo -u www-data php occ`). `./setup.sh --check` prints the state without changing anything; `./setup.sh --demo-off [--purge]` disables or deletes the demo accounts.
2. **n8n credential**: Basic Auth, user `zeitwaechter`, password from `bot.pass`. Better: log in as `zeitwaechter`, Settings, Security, create an **app password** and use it instead (revocable on its own). Attach it to every Nextcloud HTTP node.
3. **Import** `assets/n8n/zeitwaechter.json`. In the node **"Demo-Bereich festlegen"** replace `NC`, `USER`, calendar slug, Deck board/stack ids and the Talk room token. Create the calendar, Deck board and Talk room under the bot account first.
4. **Secrets**: change both webhook paths (`...-CHANGE-ME`, treat the path as a secret) and the HMAC secret `CHANGE-ME-LONG-RANDOM-SECRET`, identical in every Code node that holds it. Changing it invalidates daily QR codes and registered phones.
5. **Activate** the workflow and test `https://YOUR-N8N/form/zeitwaechter`: one calendar event, one Deck card and one Talk message should appear.
6. **PWA (optional)**: serve `zeit/`, `zeit-qr/` and the `assets/zeitwaechter-app.*`, `assets/zeitwaechter-core.js` files statically, and `zeit-punch.php` as a same-origin proxy to the n8n stamp webhook (webhook path in `private/zeit-punch-hook`, outside the web root; env `ZP_N8N`, `ZP_PRIV`; edit `ZP_PEOPLE`). Without the PWA use only the two n8n forms and print the QR codes from the `qr` webhook.

**Login Flow v2** is Nextcloud's official way to issue an app password without typing the account password into third-party software: the client POSTs `/index.php/login/v2`, the user approves in the browser, the client receives `loginName` and `appPassword`. Creating the bot's app password by hand (step 2) is equivalent.

**Roles**: `zeit-team` (staff, own data only), `zeit-chef` (sees everything), `zeit-demo` (fictitious, cannot share, 20 MB).

**Where data goes**: bot's calendar (one event per day/absence), Deck (one card per notice/violation), Talk (alerts and Friday summary), bot's Files `Zeit/` (`zeiten.csv`, `stempel.csv`, `geraete.json`, `Berichte/`), shared per user/group, never publicly.

**Privacy**: this is employee personal data. Check your legal basis (time-recording duty, GDPR Art. 6), involve the works council / unions where required (DE: § 87 BetrVG, IT: Art. 4 Statuto dei lavoratori), and give staff a privacy notice (Art. 13). Retention in the working files is **70 days**. Not legal advice.

**Removal**: `./uninstall.sh --dry-run`, then `./uninstall.sh` (disables accounts, removes groups and the share exclusion; asks at each step). `--delete-data` additionally allows deleting the bot and demo accounts with all their data (typed confirmation `LOESCHEN`). Real users are never deleted. Finally deactivate the n8n workflow, delete the credential and remove the PWA files from the web server.
