Speiseplan, Übersetzungen, Statistik, Überwachung, Tests und CI (0.2.0)
- Speiseplan: Wochenansicht mit Linien, Standorten, Kennzeichnung und Allergenen (LMIV), „Heute gibt es“ auf der Startseite, Pflege in der Redaktion mit „Vorwoche übernehmen“ - Übersetzungen per KI in acht Sprachen für Meldungen und Seiten – gekennzeichnet, mit Original-Ansicht, lang/dir für Screenreader und Rechts-nach-links-Satz, Vorlesen in der jeweiligen Sprache; Ausgabe wird wie bisher bereinigt - Statistik: anonyme Aufrufzahlen je Tag/Seite/Web-App/Sprachfassung, ohne Cookies und IP-Adressen; Datenschutzvorlage ergänzt und automatisch nummeriert - Betrieb: /health, Fehlermeldungen an ALERT_EMAIL (gedrosselt), Version in der Redaktion, deploy/uebersicht.sh, aktualisieren.sh holt Images aus der Registry und prüft jede Einrichtung nach dem Start - Tests: Vitest (Logik und Server mit Test-Datenbank) und Playwright (Leser mobil, Redaktion desktop, KI über Testdienst, axe hell/dunkel) - Forgejo Actions: Prüfung bei jedem Push, Release-Image bei Versions-Tags - Barrierefreiheit: Schalter mit role=switch, Logo-Link und Kalender-Einträge nennen den sichtbaren Text zuerst (WCAG 2.5.3) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
21a54da2e3
commit
07fa837807
84 changed files with 4771 additions and 93 deletions
|
|
@ -6,3 +6,7 @@ data
|
|||
.env
|
||||
.claude
|
||||
mobile
|
||||
tests
|
||||
playwright-report
|
||||
test-results
|
||||
.forgejo
|
||||
|
|
|
|||
49
.forgejo/workflows/ci.yml
Normal file
49
.forgejo/workflows/ci.yml
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# Prüft jeden Push und jeden Pull Request: Typen, Unit-Tests, Build, Ende-zu-Ende-Tests mit Barrierefreiheit.
|
||||
name: Prüfen
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pruefen:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.63.0-noble
|
||||
env:
|
||||
CI: 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Abhängigkeiten
|
||||
run: npm ci
|
||||
|
||||
- name: Typen prüfen
|
||||
run: npm run check
|
||||
|
||||
- name: Unit-Tests
|
||||
run: npm run test:unit
|
||||
|
||||
- name: Bauen
|
||||
run: npm run build
|
||||
env:
|
||||
APP_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || format('{0}-{1}', 'dev', github.sha) }}
|
||||
|
||||
- name: Ende-zu-Ende-Tests (inkl. axe, WCAG 2.2 AA)
|
||||
run: npm run test:e2e
|
||||
|
||||
- name: Bericht bei Fehlern
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: playwright-bericht
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
retention-days: 14
|
||||
36
.forgejo/workflows/release.yml
Normal file
36
.forgejo/workflows/release.yml
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# Veröffentlicht ein Docker-Image in der Forgejo-Registry, sobald ein Versions-Tag gepusht wird:
|
||||
# git tag v1.2.0 && git push origin v1.2.0
|
||||
# → git.loheide.cloud/friloo/werkstaetten-app:1.2.0 und :latest
|
||||
#
|
||||
# Voraussetzungen: ein Runner mit Docker (Label „docker“, Zugriff auf den Docker-Socket)
|
||||
# und das Repository-Secret REGISTRY_TOKEN (Zugangs-Token mit Berechtigung „package: write“).
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*.*.*']
|
||||
|
||||
jobs:
|
||||
image:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: docker:27-cli
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
steps:
|
||||
- name: Code holen
|
||||
run: |
|
||||
apk add --no-cache git
|
||||
git clone --depth 1 --branch "${GITHUB_REF_NAME}" "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" .
|
||||
|
||||
- name: Image bauen und hochladen
|
||||
env:
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
REGISTRY="${GITHUB_SERVER_URL#https://}"
|
||||
IMAGE="${REGISTRY}/$(echo "$GITHUB_REPOSITORY" | tr '[:upper:]' '[:lower:]')"
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$GITHUB_ACTOR" --password-stdin
|
||||
docker build --build-arg APP_VERSION="$VERSION" -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
|
||||
docker push "$IMAGE:$VERSION"
|
||||
docker push "$IMAGE:latest"
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -9,3 +9,5 @@ node_modules
|
|||
!/data/.gitkeep
|
||||
.DS_Store
|
||||
vite.config.*.timestamp-*
|
||||
/playwright-report
|
||||
/test-results
|
||||
|
|
|
|||
30
CHANGELOG.md
Normal file
30
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Änderungen
|
||||
|
||||
Versionsnummern nach [Semantic Versioning](https://semver.org/lang/de/). Eine neue Version entsteht
|
||||
mit einem Git-Tag (`v1.2.0`); daraus baut Forgejo das Docker-Image.
|
||||
|
||||
## 0.2.0 – 2026-10-09
|
||||
|
||||
### Neu
|
||||
- **Speiseplan** mit Wochenansicht, Linien, Standorten, Kennzeichnung und Allergenen (LMIV);
|
||||
„Heute gibt es“ auf der Startseite; Pflege in der Redaktion inkl. „Vorwoche übernehmen“
|
||||
- **Übersetzungen per KI** in acht Sprachen für Meldungen und Seiten – gekennzeichnet, mit Original-Ansicht,
|
||||
Rechts-nach-links-Satz und Vorlesen in der jeweiligen Sprache
|
||||
- **Statistik** mit anonymen Aufrufzahlen (ohne Cookies, ohne IP-Adressen)
|
||||
- **Erscheinungsbild je Einrichtung:** Vorlagen Kreis, Klar und Kacheln, vier Schriften, drei Eckenformen,
|
||||
Farbprüfung auf Lesbarkeit; Checkliste „Erste Schritte“
|
||||
- **Betrieb:** `/health`, Fehlermeldungen per E-Mail (`ALERT_EMAIL`), Version in der Redaktion,
|
||||
Skripte für mehrere Einrichtungen (`deploy/`), Apps je Einrichtung (`mobile/kunden/`)
|
||||
- **Tests und CI:** Vitest und Playwright (inkl. axe), Forgejo-Workflows für Prüfung und Release
|
||||
|
||||
### Verbessert
|
||||
- Markenfarben greifen zuverlässig; die dunkle Darstellung leitet sich aus der Hauptfarbe ab
|
||||
- Schalter in der Redaktion werden als Schalter angesagt; Logo-Link und Kalender-Einträge nennen den
|
||||
sichtbaren Text zuerst (WCAG 2.5.3)
|
||||
- Datenschutzerklärung nummeriert ihre Abschnitte automatisch
|
||||
|
||||
## 0.1.0 – 2026-10-03
|
||||
|
||||
Erste Version: App für Leser (Meldungen, Seiten, Termine, Ansprechpartner, Suche, Merkliste, Vorlesen,
|
||||
Leichte Sprache, Push), Redaktion mit Redaktionskalender, Sicherheit (2FA, Sperren, CSP),
|
||||
rechtliche Vorlagen, native Apps für iOS und Android.
|
||||
|
|
@ -4,6 +4,9 @@ WORKDIR /app
|
|||
COPY package.json package-lock.json .npmrc ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
# Version für /health und die Redaktion (aus dem Git-Tag, siehe .forgejo/workflows/release.yml)
|
||||
ARG APP_VERSION
|
||||
ENV APP_VERSION=${APP_VERSION}
|
||||
RUN npm run build && npm prune --omit=dev
|
||||
|
||||
# ── Laufzeit ─────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
38
README.md
38
README.md
|
|
@ -13,6 +13,11 @@ Tablet und Desktop.
|
|||
- Meldungen mit Titelbild, Galerie, Video (datensparsam erst nach Klick), Dateien und Ansprechpartnern
|
||||
- Infoseiten in beliebiger Tiefe (z. B. „Dienste → Sozialer Dienst“)
|
||||
- Termine & Schließzeiten, gruppiert nach Monat, mit Kalender-Abo (`/termine.ics`)
|
||||
- **Speiseplan** pro Woche mit Linien (z. B. „Menü 1“), Standorten, Kennzeichnung (vegan, vegetarisch,
|
||||
Fisch …) und den 14 Allergenen nach LMIV; „Heute gibt es“ auf der Startseite
|
||||
- **Andere Sprachen per KI:** Meldungen und Seiten auf Englisch, Türkisch, Arabisch, Ukrainisch, Russisch,
|
||||
Polnisch, Rumänisch oder Persisch – für Angehörige; gekennzeichnet, mit „Original anzeigen“,
|
||||
Arabisch/Persisch von rechts nach links, Vorlesen in der jeweiligen Sprache
|
||||
- Ansprechpartner-Verzeichnis, Kontaktformular, Volltextsuche
|
||||
- **Barrierearm:** klare Schrift (selbst gehostet, wählbar), 3 Schriftgrößen, Hell/Dunkel,
|
||||
**Leichte Sprache** pro Seite/Meldung – geprüfte Fassung (auch als KI-Entwurf erstellt) oder, wenn so
|
||||
|
|
@ -39,6 +44,9 @@ Tablet und Desktop.
|
|||
Modell wählbar, Schlüssel verschlüsselt gespeichert, Verbindungstest, Tageslimit. Arbeitsweise
|
||||
**„Mit Prüfung“** (Knopf „Mit KI erstellen“ → Entwurf prüfen → speichern) oder **„Automatisch für Leser“**
|
||||
- Bilder werden automatisch gedreht, verkleinert und als WebP gespeichert
|
||||
- **Speiseplan** pflegen: Wochenansicht, Gericht per Dialog, „Vorwoche übernehmen“, Linien und Standorte
|
||||
- **Statistik:** anonyme Aufrufzahlen (ohne Cookies und IP-Adressen) – Verlauf, meistgelesene Inhalte,
|
||||
Anteil App/Web, Nutzung von Leichter Sprache und Übersetzungen
|
||||
- **Benachrichtigungen:** beim Erscheinen einer Meldung (auch zeitgesteuert), automatisch am Vortag einer
|
||||
Schließzeit, oder von Hand – mit Vorschau und Verlauf
|
||||
- **Rechtliches:** Impressum und Datenschutzerklärung aus Vorlagen, die genau beschreiben, was die App
|
||||
|
|
@ -68,6 +76,24 @@ sichtbarer Tastaturfokus, beschriftete Bedienelemente, Ansagen für Screenreader
|
|||
Tastatur-Alternativen zu Ziehen & Ablegen, `prefers-reduced-motion`, Kontrast ≥ 4,5 : 1.
|
||||
Schriftgröße und Farbschema lassen sich auch in der Redaktion einstellen (Mein Konto).
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
npm run test:unit # Vitest: Logik und Server-Funktionen mit eigener Test-Datenbank
|
||||
npm run build
|
||||
npm run test:e2e # Playwright: Leser (Handy) und Redaktion (Desktop) inkl. axe-Prüfung, hell und dunkel
|
||||
```
|
||||
|
||||
Die Ende-zu-Ende-Tests starten die gebaute App mit frischer Demo-Datenbank und einem nachgebauten
|
||||
KI-Dienst (`tests/e2e/`). Einmalig `npx playwright install chromium` – oder mit `PW_CHROMIUM=/pfad/zu/chrome`
|
||||
ein vorhandenes Chromium nutzen.
|
||||
|
||||
**Forgejo Actions:** `.forgejo/workflows/ci.yml` prüft jeden Push (Typen, Unit-Tests, Build, Ende-zu-Ende).
|
||||
`.forgejo/workflows/release.yml` baut bei einem Tag `v1.2.0` das Docker-Image und legt es als
|
||||
`git.loheide.cloud/friloo/werkstaetten-app:1.2.0` (und `:latest`) in die Registry. Dafür braucht es einen
|
||||
Forgejo-Runner mit dem Label `docker` (für den Release-Job mit Zugriff auf den Docker-Socket) und das
|
||||
Repository-Secret `REGISTRY_TOKEN` (Token mit „package: write“). Änderungen stehen in [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
## Technik
|
||||
|
||||
SvelteKit 2 (Svelte 5) · Tailwind CSS 4 · SQLite (better-sqlite3) mit Drizzle ORM · sharp · Tiptap.
|
||||
|
|
@ -95,6 +121,10 @@ Alle Daten (Datenbank + Uploads) liegen in `./data` – das ist das Einzige, was
|
|||
Der Container lauscht auf `127.0.0.1:3000`; davor einen Reverse-Proxy mit HTTPS (z. B. Caddy) setzen.
|
||||
Ohne Docker: `npm ci && npm run build && ORIGIN=https://… BODY_SIZE_LIMIT=30M node build`.
|
||||
|
||||
**Überwachung:** `GET /health` antwortet mit Status, Version und Datenbank-Zustand (HTTP 503 bei
|
||||
Problemen) – geeignet für Uptime-Kuma, Healthchecks o. ä. Unerwartete Fehler landen im Log und, mit
|
||||
`ALERT_EMAIL`, im Postfach der Betreuung. Die Version steht unten in der Seitenleiste der Redaktion.
|
||||
|
||||
| Variable | Bedeutung |
|
||||
| --------------------------------- | --------------------------------------------------------------- |
|
||||
| `ORIGIN` | Öffentliche URL (Pflicht in Produktion, sonst schlagen Formulare fehl) |
|
||||
|
|
@ -102,6 +132,8 @@ Ohne Docker: `npm ci && npm run build && ORIGIN=https://… BODY_SIZE_LIMIT=30M
|
|||
| `ADMIN_EMAIL` / `ADMIN_PASSWORD` | Erster Admin, wird angelegt, solange es noch keinen Benutzer gibt |
|
||||
| `APP_NAME`, `ORG_NAME`, `BRAND_COLOR`, `ACCENT_COLOR` | Optionale Startwerte beim allerersten Start |
|
||||
| `BODY_SIZE_LIMIT` | Max. Upload-Größe (im Docker-Image auf 30M gesetzt) |
|
||||
| `ALERT_EMAIL` | Bekommt unerwartete Fehler per E-Mail (gleiche Fehler höchstens stündlich, max. 20/Tag; braucht SMTP) |
|
||||
| `APP_VERSION` | Beim Bauen: Versionsnummer für `/health` und die Redaktion (Standard: aus `package.json`) |
|
||||
| `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM` | E-Mail-Versand für „Passwort vergessen“. Ohne SMTP steht der Link im Server-Log |
|
||||
| `GOOGLE_TOKEN_URL`, `FCM_API_URL` | Nur für Tests: andere Adressen für Firebase |
|
||||
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | Optional – sonst werden die Push-Schlüssel automatisch erzeugt und gespeichert |
|
||||
|
|
@ -128,7 +160,8 @@ werden automatisch abgedunkelt); danach zählt, was in den Einstellungen steht.
|
|||
| Skript | Zweck |
|
||||
| ------ | ----- |
|
||||
| `deploy/neue-einrichtung.sh <kurzname> <domain> [admin-mail]` | Einrichtung anlegen |
|
||||
| `deploy/aktualisieren.sh [kurzname …]` | Image neu bauen, alle (oder die genannten) Einrichtungen nacheinander neu starten – Migrationen laufen automatisch |
|
||||
| `VERSION=1.2.0 deploy/aktualisieren.sh [kurzname …]` | Image aus der Registry holen (ohne `VERSION`: lokal bauen), Einrichtungen nacheinander neu starten und per `/health` prüfen – Migrationen laufen automatisch |
|
||||
| `deploy/uebersicht.sh` | Tabelle aller Einrichtungen: Container, App-Zustand, Version, letzte Sicherung (Rückgabewert 1, wenn eine ausfällt – für cron) |
|
||||
| `deploy/sichern.sh [kurzname …]` | Datenbank (konsistente Kopie im laufenden Container) und Uploads sichern, 14 Tage aufbewahren |
|
||||
|
||||
Jede Einrichtung braucht etwa 100–150 MB RAM (Limit 384 MB). Für eigene Apps im Store je
|
||||
|
|
@ -149,5 +182,4 @@ Einrichtung siehe [`mobile/README.md`](mobile/README.md#mehrere-einrichtungen).
|
|||
|
||||
## Ideen für später
|
||||
|
||||
Push-Benachrichtigungen (Web Push), E-Mail-Weiterleitung des Kontaktformulars, Umfragen,
|
||||
Mehrsprachigkeit, Standort-Filter für Speisepläne.
|
||||
E-Mail-Weiterleitung des Kontaktformulars, Umfragen, Bedienoberfläche in weiteren Sprachen.
|
||||
|
|
|
|||
|
|
@ -1,27 +1,44 @@
|
|||
#!/usr/bin/env bash
|
||||
# Baut das Image neu und startet alle Einrichtungen mit der neuen Version.
|
||||
# Die Datenbank wird beim Start jeder Einrichtung automatisch migriert.
|
||||
# Bringt alle Einrichtungen auf eine neue Version. Die Datenbank wird beim Start
|
||||
# jeder Einrichtung automatisch migriert.
|
||||
#
|
||||
# deploy/aktualisieren.sh alle Einrichtungen
|
||||
# deploy/aktualisieren.sh lindenhof nur diese
|
||||
# deploy/aktualisieren.sh lokal bauen, alle Einrichtungen
|
||||
# deploy/aktualisieren.sh lindenhof nur diese
|
||||
# VERSION=1.2.0 deploy/aktualisieren.sh fertiges Image aus der Registry holen (empfohlen)
|
||||
#
|
||||
# REGISTRY_IMAGE: Image ohne Version (Standard: git.loheide.cloud/friloo/werkstaetten-app)
|
||||
# Vorher sichern: deploy/sichern.sh
|
||||
set -euo pipefail
|
||||
|
||||
BASIS="${BASIS:-/srv/werkstatt-apps}"
|
||||
REPO="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
REGISTRY_IMAGE="${REGISTRY_IMAGE:-git.loheide.cloud/friloo/werkstaetten-app}"
|
||||
|
||||
echo "→ Image bauen"
|
||||
docker build -t werkstatt-app:latest "$REPO"
|
||||
if [[ -n "${VERSION:-}" ]]; then
|
||||
export IMAGE="$REGISTRY_IMAGE:${VERSION#v}"
|
||||
echo "→ Image holen: $IMAGE"
|
||||
docker pull "$IMAGE"
|
||||
else
|
||||
export IMAGE="werkstatt-app:latest"
|
||||
echo "→ Image lokal bauen"
|
||||
docker build --build-arg APP_VERSION="$(git -C "$REPO" describe --tags --always 2>/dev/null | sed "s/^v//" || echo dev)" -t "$IMAGE" "$REPO"
|
||||
fi
|
||||
|
||||
ordner=("$BASIS"/*/)
|
||||
[[ $# -gt 0 ]] && ordner=("${@/#/$BASIS/}")
|
||||
|
||||
# Nacheinander, damit der Speicher reicht
|
||||
# Nacheinander, damit der Speicher reicht – und nach jedem Start prüfen, ob die App antwortet
|
||||
for d in "${ordner[@]}"; do
|
||||
[[ -f "$d/compose.yml" ]] || continue
|
||||
echo "→ $(basename "$d")"
|
||||
docker compose --project-directory "$d" up -d
|
||||
k=$(basename "$d")
|
||||
echo "→ $k"
|
||||
docker compose -f "$d/compose.yml" --project-directory "$d" up -d
|
||||
port=$(sed -n 's/^PORT=//p' "$d/.env")
|
||||
for _ in $(seq 1 30); do
|
||||
curl -sf -m 2 "http://127.0.0.1:$port/health" >/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
curl -sf -m 2 "http://127.0.0.1:$port/health" >/dev/null && echo " läuft ($(curl -s "http://127.0.0.1:$port/health" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'))" || { echo " ✘ antwortet nicht – Logs: docker logs werkstatt-$k" >&2; exit 1; }
|
||||
done
|
||||
docker image prune -f >/dev/null
|
||||
echo "Fertig."
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
# APP_NAME Name der App beim ersten Start
|
||||
# ORG_NAME Name der Einrichtung beim ersten Start
|
||||
# BRAND_COLOR Hauptfarbe (#rrggbb), ACCENT_COLOR Akzentfarbe
|
||||
# ALERT_EMAIL Adresse für Fehlermeldungen (Betreuung)
|
||||
set -euo pipefail
|
||||
|
||||
KUNDE="${1:-}"
|
||||
|
|
@ -61,7 +62,10 @@ ORG_NAME="${ORG_NAME:-}"
|
|||
BRAND_COLOR=${BRAND_COLOR:-}
|
||||
ACCENT_COLOR=${ACCENT_COLOR:-}
|
||||
|
||||
# E-Mail-Versand (für „Passwort vergessen“)
|
||||
# Betreuer der Installation: bekommt Fehlermeldungen per E-Mail (braucht SMTP)
|
||||
ALERT_EMAIL=${ALERT_EMAIL:-}
|
||||
|
||||
# E-Mail-Versand (für „Passwort vergessen“ und Fehlermeldungen)
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
|
|
|
|||
27
deploy/uebersicht.sh
Executable file
27
deploy/uebersicht.sh
Executable file
|
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/env bash
|
||||
# Übersicht aller Einrichtungen: läuft der Container, antwortet die App, welche Version.
|
||||
#
|
||||
# deploy/uebersicht.sh
|
||||
#
|
||||
# Rückgabewert 1, wenn eine Einrichtung nicht läuft – geeignet für cron oder Monitoring.
|
||||
set -uo pipefail
|
||||
|
||||
BASIS="${BASIS:-/srv/werkstatt-apps}"
|
||||
SICHERUNG="${SICHERUNG:-/srv/werkstatt-apps-sicherung}"
|
||||
fehler=0
|
||||
|
||||
printf '%-18s %-34s %-10s %-10s %-9s %s\n' EINRICHTUNG ADRESSE CONTAINER APP VERSION 'LETZTE SICHERUNG'
|
||||
for d in "$BASIS"/*/; do
|
||||
[[ -f "$d/.env" ]] || continue
|
||||
k=$(basename "$d")
|
||||
port=$(sed -n 's/^PORT=//p' "$d/.env")
|
||||
origin=$(sed -n 's/^ORIGIN=//p' "$d/.env")
|
||||
container=$(docker inspect -f '{{.State.Status}}' "werkstatt-$k" 2>/dev/null || echo fehlt)
|
||||
health=$(curl -s -m 5 "http://127.0.0.1:$port/health" 2>/dev/null)
|
||||
app=$(sed -n 's/.*"status":"\([^"]*\)".*/\1/p' <<<"$health")
|
||||
version=$(sed -n 's/.*"version":"\([^"]*\)".*/\1/p' <<<"$health")
|
||||
sicherung=$(ls -t "$SICHERUNG/$k"-*.tar.gz 2>/dev/null | head -1 | sed 's/.*-\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\)-\([0-9]\{2\}\)\([0-9]\{2\}\).*/\1 \2:\3/')
|
||||
[[ "$container" == running && "$app" == ok ]] || fehler=1
|
||||
printf '%-18s %-34s %-10s %-10s %-9s %s\n' "$k" "${origin#https://}" "$container" "${app:-keine Antwort}" "${version:--}" "${sicherung:-–}"
|
||||
done
|
||||
exit $fehler
|
||||
40
drizzle/0005_speiseplan_uebersetzung_statistik.sql
Normal file
40
drizzle/0005_speiseplan_uebersetzung_statistik.sql
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
CREATE TABLE `meals` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`date` text NOT NULL,
|
||||
`location` text DEFAULT '' NOT NULL,
|
||||
`line` text DEFAULT '' NOT NULL,
|
||||
`title` text NOT NULL,
|
||||
`description` text DEFAULT '' NOT NULL,
|
||||
`allergens` text DEFAULT '[]' NOT NULL,
|
||||
`labels` text DEFAULT '[]' NOT NULL,
|
||||
`price` text DEFAULT '' NOT NULL,
|
||||
`position` integer DEFAULT 0 NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
`updated_at` integer DEFAULT (unixepoch()) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX `meals_date_idx` ON `meals` (`date`);--> statement-breakpoint
|
||||
CREATE TABLE `page_views` (
|
||||
`day` text NOT NULL,
|
||||
`path` text NOT NULL,
|
||||
`client` text DEFAULT 'web' NOT NULL,
|
||||
`variant` text DEFAULT 'normal' NOT NULL,
|
||||
`views` integer DEFAULT 0 NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `page_views_key_idx` ON `page_views` (`day`,`path`,`client`,`variant`);--> statement-breakpoint
|
||||
CREATE INDEX `page_views_day_idx` ON `page_views` (`day`);--> statement-breakpoint
|
||||
CREATE TABLE `translations` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`kind` text NOT NULL,
|
||||
`ref_id` integer NOT NULL,
|
||||
`lang` text NOT NULL,
|
||||
`hash` text NOT NULL,
|
||||
`title` text NOT NULL,
|
||||
`teaser` text DEFAULT '' NOT NULL,
|
||||
`html` text NOT NULL,
|
||||
`model` text DEFAULT '' NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch()) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `translations_ref_lang_idx` ON `translations` (`kind`,`ref_id`,`lang`);
|
||||
1922
drizzle/meta/0005_snapshot.json
Normal file
1922
drizzle/meta/0005_snapshot.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -36,6 +36,13 @@
|
|||
"when": 1791010254817,
|
||||
"tag": "0004_native_apps",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "6",
|
||||
"when": 1791570610795,
|
||||
"tag": "0005_speiseplan_uebersetzung_statistik",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
310
package-lock.json
generated
310
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "werkstaetten-app",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "werkstaetten-app",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.131.0",
|
||||
"better-sqlite3": "^13.0.3",
|
||||
|
|
@ -25,6 +25,7 @@
|
|||
"@fontsource-variable/montserrat": "^5.3.0",
|
||||
"@fontsource-variable/source-sans-3": "^5.3.0",
|
||||
"@lucide/svelte": "^1.48.0",
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@sveltejs/adapter-node": "^5.5.7",
|
||||
"@sveltejs/kit": "^2.70.3",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
||||
|
|
@ -40,12 +41,14 @@
|
|||
"@types/qrcode": "^1.5.6",
|
||||
"@types/sanitize-html": "^2.16.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"axe-core": "^4.14.0",
|
||||
"drizzle-kit": "^0.31.11",
|
||||
"svelte": "^5.57.1",
|
||||
"svelte-check": "^4.7.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.0",
|
||||
"vite": "^8.3.1"
|
||||
"vite": "^8.3.1",
|
||||
"vitest": "^5.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
|
|
@ -1664,6 +1667,22 @@
|
|||
"url": "https://github.com/sponsors/oxc-project"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
||||
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@polka/url": {
|
||||
"version": "1.0.0-next.29",
|
||||
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
|
||||
|
|
@ -3295,6 +3314,17 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/chai": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
|
||||
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/deep-eql": "*",
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/cookie": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
|
||||
|
|
@ -3302,6 +3332,13 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/estree": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
||||
|
|
@ -3366,6 +3403,64 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
|
||||
"integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "0.3.31",
|
||||
"@vitest/spy": "5.0.3",
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^1.2.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker/node_modules/estree-walker": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker/node_modules/magic-string": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz",
|
||||
"integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/spy": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
|
||||
"integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.18.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
|
||||
|
|
@ -3434,6 +3529,26 @@
|
|||
"safer-buffer": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/axe-core": {
|
||||
"version": "4.14.0",
|
||||
"resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz",
|
||||
"integrity": "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/axobject-query": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||
|
|
@ -3484,6 +3599,16 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/chai": {
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
|
||||
"integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
|
||||
|
|
@ -4379,6 +4504,13 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-lexer": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
|
||||
"integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
|
||||
|
|
@ -4465,6 +4597,16 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/expect-type": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-sha256": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||
|
|
@ -5254,6 +5396,35 @@
|
|||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
|
|
@ -5808,6 +5979,13 @@
|
|||
"fast-sha256": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/std-env": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
|
||||
"integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
|
|
@ -5930,6 +6108,26 @@
|
|||
"url": "https://opencollective.com/webpack"
|
||||
}
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.1.tgz",
|
||||
"integrity": "sha512-IAbQaPJIIdhVxi0mqy9lez1wEwje0UQf9F1vwtbelEG5Nbgn0nPOxCvU+mNeNS9gyJTAhrHp74CbUaSynQpZcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyexec": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
|
||||
"integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
|
|
@ -6388,6 +6586,99 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
|
||||
"integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/chai": "^5.2.2",
|
||||
"@vitest/mocker": "5.0.3",
|
||||
"chai": "^6.2.2",
|
||||
"es-module-lexer": "^2.3.2",
|
||||
"expect-type": "^1.4.0",
|
||||
"magic-string": "^1.2.3",
|
||||
"obug": "^2.1.4",
|
||||
"picomatch": "^4.0.7",
|
||||
"std-env": "^4.2.0",
|
||||
"tinybench": "^6.1.4",
|
||||
"tinyexec": "^1.3.0",
|
||||
"tinyglobby": "^0.2.17",
|
||||
"why-is-node-running": "3.2.1"
|
||||
},
|
||||
"bin": {
|
||||
"vitest": "vitest.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@edge-runtime/vm": "*",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@types/node": "^22.0.0 || >=24.0.0",
|
||||
"@vitest/browser-playwright": "5.0.3",
|
||||
"@vitest/browser-preview": "5.0.3",
|
||||
"@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
|
||||
"@vitest/coverage-istanbul": "5.0.3",
|
||||
"@vitest/coverage-v8": "5.0.3",
|
||||
"@vitest/ui": "5.0.3",
|
||||
"happy-dom": "*",
|
||||
"jsdom": "*",
|
||||
"vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@edge-runtime/vm": {
|
||||
"optional": true
|
||||
},
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-playwright": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-preview": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser-webdriverio": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-istanbul": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/coverage-v8": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/ui": {
|
||||
"optional": true
|
||||
},
|
||||
"happy-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"jsdom": {
|
||||
"optional": true
|
||||
},
|
||||
"vite": {
|
||||
"optional": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vitest/node_modules/magic-string": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz",
|
||||
"integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-keyname": {
|
||||
"version": "2.2.8",
|
||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||
|
|
@ -6420,6 +6711,19 @@
|
|||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
|
||||
"integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"why-is-node-running": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11"
|
||||
}
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
|
|
|
|||
18
package.json
18
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "werkstaetten-app",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Moderne, werbefreie Info-App für Werkstätten für Menschen mit Behinderung – mit einfachem Redaktions-Backend.",
|
||||
|
|
@ -12,7 +12,10 @@
|
|||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:seed": "node --experimental-strip-types scripts/seed.ts",
|
||||
"user:create": "node --experimental-strip-types scripts/create-user.ts"
|
||||
"user:create": "node --experimental-strip-types scripts/create-user.ts",
|
||||
"test": "npm run test:unit && npm run test:e2e",
|
||||
"test:unit": "vitest run",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
|
|
@ -35,6 +38,7 @@
|
|||
"@fontsource-variable/montserrat": "^5.3.0",
|
||||
"@fontsource-variable/source-sans-3": "^5.3.0",
|
||||
"@lucide/svelte": "^1.48.0",
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@sveltejs/adapter-node": "^5.5.7",
|
||||
"@sveltejs/kit": "^2.70.3",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
||||
|
|
@ -50,11 +54,19 @@
|
|||
"@types/qrcode": "^1.5.6",
|
||||
"@types/sanitize-html": "^2.16.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"axe-core": "^4.14.0",
|
||||
"drizzle-kit": "^0.31.11",
|
||||
"svelte": "^5.57.1",
|
||||
"svelte-check": "^4.7.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^6.0.0",
|
||||
"vite": "^8.3.1"
|
||||
"vite": "^8.3.1",
|
||||
"vitest": "^5.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"better-sqlite3@13.0.3": true,
|
||||
"esbuild@0.18.20": true,
|
||||
"esbuild@0.25.12": true,
|
||||
"esbuild@0.28.2": true
|
||||
}
|
||||
}
|
||||
|
|
|
|||
38
playwright.config.ts
Normal file
38
playwright.config.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Ende-zu-Ende-Tests gegen den Produktions-Build (vorher `npm run build`).
|
||||
* Die Tests teilen sich eine Datenbank und laufen deshalb nacheinander.
|
||||
* PW_CHROMIUM: Pfad zu einem vorhandenen Chromium (sonst `npx playwright install chromium`).
|
||||
*/
|
||||
const port = 4173;
|
||||
const executablePath = process.env.PW_CHROMIUM || undefined;
|
||||
|
||||
export default defineConfig({
|
||||
testDir: 'tests/e2e',
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: process.env.CI ? 1 : 0,
|
||||
reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list',
|
||||
timeout: 60_000,
|
||||
use: {
|
||||
baseURL: `http://localhost:${port}`,
|
||||
// kein „Headless“ im Kennzeichen, damit die anonyme Zählung greift (Bots werden verworfen)
|
||||
userAgent: 'Mozilla/5.0 (X11; Linux x86_64) WerkstattTest/1.0',
|
||||
launchOptions: { executablePath },
|
||||
// axe wird für die Prüfung in die Seite eingebunden – die Content-Security-Policy würde das verhindern
|
||||
bypassCSP: true,
|
||||
trace: 'retain-on-failure'
|
||||
},
|
||||
projects: [
|
||||
{ name: 'mobil', use: { ...devices['Pixel 7'], userAgent: 'Mozilla/5.0 (Linux; Android 14) WerkstattTest/1.0 Mobile', launchOptions: { executablePath }, bypassCSP: true }, testMatch: /leser\..*spec/ },
|
||||
{ name: 'desktop', use: { viewport: { width: 1360, height: 900 } }, testIgnore: /leser\..*spec/ }
|
||||
],
|
||||
webServer: {
|
||||
command: 'node tests/e2e/server.mjs',
|
||||
url: `http://localhost:${port}/health`,
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
env: { PORT: String(port), FAKE_AI_PORT: '9599' }
|
||||
}
|
||||
});
|
||||
|
|
@ -27,7 +27,7 @@ if (db.select().from(s.pages).all().length && !force) {
|
|||
process.exit(0);
|
||||
}
|
||||
if (force) {
|
||||
for (const t of [s.editorialComments, s.editorialItems, s.tiles, s.posts, s.pages, s.events, s.contacts, s.messages, s.media, s.settings]) db.delete(t).run();
|
||||
for (const t of [s.translations, s.pageViews, s.meals, s.editorialComments, s.editorialItems, s.tiles, s.posts, s.pages, s.events, s.contacts, s.messages, s.media, s.settings]) db.delete(t).run();
|
||||
// alte Upload-Dateien mit entfernen
|
||||
for (const f of fs.readdirSync(UPLOAD_DIR)) fs.rmSync(path.join(UPLOAD_DIR, f), { force: true });
|
||||
}
|
||||
|
|
@ -95,7 +95,9 @@ db.insert(s.settings)
|
|||
privacy:
|
||||
'<h2>Kurz gesagt</h2><p>Diese App kommt ohne Werbung und ohne Tracking aus. Es werden keine Daten an Dritte weitergegeben.</p><h2>Was wird gespeichert?</h2><ul><li>Deine Anzeige-Einstellungen (Schriftgröße, Farbschema, Leichte Sprache) als Cookie auf deinem Gerät.</li><li>Deine Merkliste – nur auf deinem Gerät.</li><li>Nachrichten aus dem Kontaktformular, bis sie bearbeitet sind.</li></ul><h2>Videos</h2><p>Eingebettete Videos werden erst geladen, wenn du auf „Abspielen“ tippst.</p>',
|
||||
homeNewsCount: 4,
|
||||
homeEventsCount: 4
|
||||
homeEventsCount: 4,
|
||||
mealLocations: ['Lindenhof', 'Werkstatt am Kanal'],
|
||||
mealLines: ['Menü 1', 'Menü 2', 'Vegetarisch']
|
||||
}
|
||||
})
|
||||
.run();
|
||||
|
|
@ -159,7 +161,6 @@ page({
|
|||
contentEasy: '<p>Der Werkstatt·rat hilft allen Beschäftigten.</p><p>Der Werkstatt·rat spricht mit der Leitung.</p><p>Die Frauen·beauftragte hilft Frauen.</p><p>Du kannst immer zu uns kommen.</p>',
|
||||
contactIds: [contactIds[3], contactIds[4]]
|
||||
});
|
||||
page({ title: 'Speisepläne', slug: 'speiseplaene', icon: 'utensils', color: 'coral', teaser: 'Was gibt es diese Woche zu essen?', content: '<p>Die Speisepläne werden jeden Freitag für die nächste Woche aktualisiert.</p><h3>Diese Woche in der Werkstatt Lindenhof</h3><ul><li><strong>Montag:</strong> Gemüselasagne</li><li><strong>Dienstag:</strong> Hähnchen mit Reis</li><li><strong>Mittwoch:</strong> Kartoffelsuppe mit Würstchen</li><li><strong>Donnerstag:</strong> Spaghetti Bolognese</li><li><strong>Freitag:</strong> Fisch mit Kartoffelsalat</li></ul>' });
|
||||
page({ title: 'Wichtige Infos', slug: 'infos', icon: 'info', color: 'slate', teaser: 'Werkstattordnung, Infobriefe und mehr.', content: '<p>Hier findest du die Werkstattordnung, aktuelle Informationsbriefe und das Kursheft zum Herunterladen.</p>' });
|
||||
page({ title: 'Produkte & Verkauf', slug: 'produkte', icon: 'store', color: 'amber', teaser: 'Hofladen, Café und Online-Shop.', content: '<p>In unserem Hofladen und im Café Linde verkaufen wir, was in den Werkstätten entsteht: Holzspielzeug, Kerzen, Honig, Apfelsaft und vieles mehr.</p>', contactIds: [contactIds[2]] });
|
||||
|
||||
|
|
@ -168,7 +169,7 @@ page({ title: 'Produkte & Verkauf', slug: 'produkte', icon: 'store', color: 'amb
|
|||
const tileDefs = [
|
||||
['Meldungen', 'newspaper', 'sky', '/meldungen'],
|
||||
['Termine', 'calendar-days', 'amber', '/termine'],
|
||||
['Speiseplan', 'utensils', 'coral', '/s/speiseplaene'],
|
||||
['Speiseplan', 'utensils', 'coral', '/speiseplan'],
|
||||
['Dienste & Angebote', 'hand-heart', 'rose', '/s/dienste'],
|
||||
['Mitarbeiten', 'briefcase', 'indigo', '/s/mitarbeiten'],
|
||||
['Werkstattrat', 'scale', 'violet', '/s/gremien'],
|
||||
|
|
@ -180,6 +181,47 @@ const tileDefs = [
|
|||
] as const;
|
||||
tileDefs.forEach(([label, icon, color, href], i) => db.insert(s.tiles).values({ label, icon, color, href, sortOrder: i }).run());
|
||||
|
||||
// ─── Speiseplan (letzte, diese und nächste Woche) ────────────────────────────
|
||||
|
||||
const dishes: [string, string, string[], string[]][] = [
|
||||
['Gemüselasagne', 'mit Tomatensoße und Salat', ['A', 'C', 'G'], ['vegetarisch']],
|
||||
['Hähnchenbrust mit Reis', 'und Paprikagemüse', [], ['gefluegel']],
|
||||
['Kartoffelsuppe mit Würstchen', 'dazu Brot', ['A', 'L'], ['schwein']],
|
||||
['Spaghetti Bolognese', 'mit geriebenem Käse', ['A', 'G', 'L'], ['rind']],
|
||||
['Fischfilet mit Kartoffelsalat', 'Seelachs, paniert', ['A', 'C', 'D', 'M'], ['fisch']],
|
||||
['Linsen-Dal', 'mit Reis und Joghurt-Dip', ['G'], ['vegetarisch']],
|
||||
['Gemüse-Curry', 'mit Kokosmilch und Reis', [], ['vegan']],
|
||||
['Käsespätzle', 'mit Röstzwiebeln', ['A', 'C', 'G'], ['vegetarisch']],
|
||||
['Schnitzel mit Pommes', 'und Erbsen und Möhren', ['A', 'C'], ['schwein']],
|
||||
['Chili sin Carne', 'mit Brot', ['A'], ['vegan']],
|
||||
['Rindergulasch', 'mit Nudeln', ['A', 'C', 'L'], ['rind']],
|
||||
['Ofenkartoffel', 'mit Kräuterquark', ['G'], ['vegetarisch']],
|
||||
['Hähnchen-Wrap', 'mit Salat und Joghurtsoße', ['A', 'G'], ['gefluegel']],
|
||||
['Tomatensuppe', 'mit Grießklößchen', ['A', 'C', 'G', 'L'], ['vegetarisch']],
|
||||
['Milchreis', 'mit Zimt und Apfelmus', ['G'], ['vegetarisch']]
|
||||
];
|
||||
{
|
||||
const today0 = new Date(iso(0) + 'T12:00:00Z');
|
||||
const monday = (today0.getUTCDay() + 6) % 7;
|
||||
let n = 0;
|
||||
for (let week = -1; week <= 1; week++) {
|
||||
for (let d = 0; d < 5; d++) {
|
||||
const date = iso(week * 7 + d - monday);
|
||||
const pick = (k: number) => dishes[(n + k) % dishes.length];
|
||||
const lines: [string, string, ReturnType<typeof pick>][] = [
|
||||
['Menü 1', '', pick(0)],
|
||||
['Menü 2', 'Lindenhof', pick(5)],
|
||||
['Menü 2', 'Werkstatt am Kanal', pick(9)],
|
||||
['Vegetarisch', '', dishes.filter((x) => x[3].includes('vegetarisch') || x[3].includes('vegan'))[n % 7]]
|
||||
];
|
||||
lines.forEach(([line, location, [title, description, allergens, labels]], position) =>
|
||||
db.insert(s.meals).values({ date, line, location, title, description, allergens, labels, price: '3,20 €', position }).run()
|
||||
);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Meldungen ───────────────────────────────────────────────────────────────
|
||||
|
||||
const postDefs = [
|
||||
|
|
|
|||
2
src/app.d.ts
vendored
2
src/app.d.ts
vendored
|
|
@ -2,6 +2,8 @@ import type { SessionUser } from '$lib/server/auth';
|
|||
import type { Prefs } from '$lib/prefs';
|
||||
|
||||
declare global {
|
||||
const __APP_VERSION__: string;
|
||||
|
||||
namespace App {
|
||||
interface Locals {
|
||||
user: SessionUser | null;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
import type { Handle, ServerInit } from '@sveltejs/kit';
|
||||
import type { Handle, HandleServerError, ServerInit } from '@sveltejs/kit';
|
||||
import { reportError } from '$lib/server/monitor';
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import { SESSION_COOKIE, ensureInitialAdmin, purgeExpiredSessions, validateSession } from '$lib/server/auth';
|
||||
import { purgeRateLimits } from '$lib/server/ratelimit';
|
||||
import { purgeOrphanTranslations } from '$lib/server/translate';
|
||||
import { purgeOldPageViews } from '$lib/server/stats';
|
||||
import { startPushScheduler } from '$lib/server/push';
|
||||
import { applyInitialSettings, getSettings } from '$lib/server/settings';
|
||||
import { PREFS_COOKIE, parsePrefs } from '$lib/prefs';
|
||||
|
|
@ -12,6 +15,8 @@ export const init: ServerInit = async () => {
|
|||
const cleanup = () => {
|
||||
purgeExpiredSessions();
|
||||
purgeRateLimits();
|
||||
purgeOrphanTranslations();
|
||||
purgeOldPageViews();
|
||||
};
|
||||
cleanup();
|
||||
setInterval(cleanup, 6 * 3600e3).unref();
|
||||
|
|
@ -91,3 +96,9 @@ export const handle: Handle = async ({ event, resolve }) => {
|
|||
response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');
|
||||
return response;
|
||||
};
|
||||
|
||||
/** Unerwartete Fehler: ins Log und an ALERT_EMAIL; Leser sehen nur eine allgemeine Meldung */
|
||||
export const handleError: HandleServerError = ({ error, event, status }) => {
|
||||
if (status !== 404) reportError(`${event.request.method} ${event.route.id ?? event.url.pathname}`, error);
|
||||
return { message: 'Da ist etwas schiefgelaufen.' };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
<script lang="ts">
|
||||
import { LANGUAGES, langCodes } from '$lib/languages';
|
||||
import { untrack } from 'svelte';
|
||||
import Download from '@lucide/svelte/icons/download';
|
||||
import PlugZap from '@lucide/svelte/icons/plug-zap';
|
||||
|
|
@ -58,7 +59,7 @@
|
|||
</script>
|
||||
|
||||
<div class="space-y-5">
|
||||
<Switch name="aiEnabled" checked={s.aiEnabled} label="Leichte Sprache mit KI einschalten" />
|
||||
<Switch name="aiEnabled" checked={s.aiEnabled} label="KI für Leichte Sprache und Übersetzungen einschalten" />
|
||||
|
||||
<fieldset>
|
||||
<legend class="label">Arbeitsweise</legend>
|
||||
|
|
@ -147,6 +148,18 @@
|
|||
<p class="hint">Heute verwendet: {ai.usedToday}. Schützt vor unerwarteten Kosten.</p>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend class="label">Übersetzungen für Leser</legend>
|
||||
<p class="hint mt-0 mb-2">Leser können Meldungen und Seiten in diese Sprachen übersetzen lassen – z. B. für Angehörige. Übersetzt wird automatisch beim ersten Aufruf, gekennzeichnet und ohne Prüfung vorab. Jede Übersetzung zählt zum Tageslimit.</p>
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
{#each langCodes as l (l)}
|
||||
<label class="flex items-center gap-2 rounded-xl border border-line px-3 py-2 cursor-pointer has-[:checked]:border-brand has-[:checked]:bg-brand-soft">
|
||||
<input type="checkbox" name="aiLanguages" value={l} checked={s.aiLanguages.includes(l)} class="size-4 accent-[var(--brand)]" />
|
||||
<span class="text-sm font-semibold">{LANGUAGES[l].german}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
<p class="text-sm text-ink-2">
|
||||
Status: {#if ai.ready}<strong>eingerichtet und aktiv</strong>{:else}<strong>nicht aktiv</strong> – einschalten, Modell wählen{p.needsKey ? ' und Schlüssel eintragen' : ''}, dann speichern.{/if}
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<script lang="ts">
|
||||
import Check from '@lucide/svelte/icons/check';
|
||||
import TriangleAlert from '@lucide/svelte/icons/triangle-alert';
|
||||
import { FONTS, PRESETS, RADII, type FontKey, type Preset, type RadiusKey, type Theme } from '$lib/theme';
|
||||
import { COLOR_PAIRS, FONTS, PRESETS, RADII, type FontKey, type Preset, type RadiusKey, type Theme } from '$lib/theme';
|
||||
import { contrast, darkenForContrast, isHex, MIN_CONTRAST } from '$lib/color';
|
||||
|
||||
/**
|
||||
|
|
@ -33,18 +33,7 @@
|
|||
radius = PRESETS[p].radius;
|
||||
}
|
||||
|
||||
// Farbpaare aus Hauptfarbe (Schrift, Buttons) und Akzent (Kreis, Hervorhebungen) –
|
||||
// alle mit mindestens 4,5:1 zu Weiß
|
||||
const pairs = [
|
||||
['#2e2672', '#85357c'],
|
||||
['#0f4c5c', '#b3470f'],
|
||||
['#1d3557', '#c0262f'],
|
||||
['#264027', '#8a5a14'],
|
||||
['#3a2e39', '#13705f'],
|
||||
['#12355b', '#8f6400'],
|
||||
['#4a1d5c', '#b0306e'],
|
||||
['#1f2a44', '#2f6f4f']
|
||||
] as const;
|
||||
const pairs = COLOR_PAIRS;
|
||||
|
||||
const ratio = (c: string) => (isHex(c) ? contrast(c, '#ffffff') : 0);
|
||||
const fmt = (r: number) => r.toFixed(1).replace('.', ',');
|
||||
|
|
|
|||
132
src/lib/admin/MealDialog.svelte
Normal file
132
src/lib/admin/MealDialog.svelte
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import X from '@lucide/svelte/icons/x';
|
||||
import Save from '@lucide/svelte/icons/save';
|
||||
import Trash2 from '@lucide/svelte/icons/trash-2';
|
||||
import { toasts } from './toast.svelte';
|
||||
import { ALLERGENS, MEAL_LABELS, allergenCodes, mealLabelKeys, type MealDraft } from '$lib/meals';
|
||||
import { formatLong } from '$lib/dates';
|
||||
|
||||
|
||||
let {
|
||||
meal = $bindable(null),
|
||||
lines,
|
||||
locations
|
||||
}: { meal: MealDraft | null; lines: string[]; locations: string[] } = $props();
|
||||
|
||||
let dialog: HTMLDialogElement;
|
||||
let busy = $state(false);
|
||||
let confirmDelete = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (meal && !dialog.open) dialog.showModal();
|
||||
if (!meal && dialog.open) dialog.close();
|
||||
});
|
||||
|
||||
const submit = () => {
|
||||
busy = true;
|
||||
return async ({ result }: { result: { type: string; data?: Record<string, unknown> } }) => {
|
||||
busy = false;
|
||||
if (result.type === 'failure') toasts.show(String(result.data?.error ?? 'Bitte Eingaben prüfen.'), 'error');
|
||||
else if (result.type === 'success') {
|
||||
toasts.show(result.data?.deleted ? 'Gelöscht' : 'Gespeichert');
|
||||
await invalidateAll();
|
||||
meal = null;
|
||||
}
|
||||
};
|
||||
};
|
||||
</script>
|
||||
|
||||
<dialog
|
||||
bind:this={dialog}
|
||||
onclose={() => {
|
||||
meal = null;
|
||||
confirmDelete = false;
|
||||
}}
|
||||
aria-labelledby="meal-title"
|
||||
class="m-0 ml-auto h-dvh max-h-dvh w-full max-w-xl bg-surface text-ink p-0 shadow-float backdrop:bg-black/40"
|
||||
>
|
||||
{#if meal}
|
||||
<div class="flex flex-col h-full">
|
||||
<header class="flex items-center gap-3 px-5 h-16 border-b border-line shrink-0">
|
||||
<h2 id="meal-title" class="font-bold text-lg flex-1 truncate">{meal.id ? 'Gericht bearbeiten' : 'Gericht hinzufügen'}</h2>
|
||||
<button type="button" class="btn btn-ghost btn-icon" aria-label="Schließen" onclick={() => (meal = null)}><X class="size-5" /></button>
|
||||
</header>
|
||||
|
||||
<form id="meal-form" method="POST" action="?/save" class="flex-1 overflow-y-auto p-5 space-y-5" use:enhance={submit}>
|
||||
<input type="hidden" name="id" value={meal.id || ''} />
|
||||
<div class="grid sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="label" for="m-date">Tag</label>
|
||||
<input id="m-date" name="date" type="date" class="field" required value={meal.date} />
|
||||
<p class="hint">{formatLong(meal.date)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="m-line">Linie</label>
|
||||
<input id="m-line" name="line" class="field" list="m-lines" value={meal.line} placeholder="z. B. Menü 1" />
|
||||
<datalist id="m-lines">{#each lines as l (l)}<option value={l}></option>{/each}</datalist>
|
||||
</div>
|
||||
</div>
|
||||
{#if locations.length}
|
||||
<div>
|
||||
<label class="label" for="m-location">Standort</label>
|
||||
<select id="m-location" name="location" class="field">
|
||||
<option value="">Alle Standorte</option>
|
||||
{#each locations as l (l)}<option value={l} selected={meal.location === l}>{l}</option>{/each}
|
||||
</select>
|
||||
</div>
|
||||
{/if}
|
||||
<div>
|
||||
<label class="label" for="m-title">Gericht</label>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input id="m-title" name="title" class="field font-semibold" required maxlength="200" value={meal.title} autofocus={!meal.id} placeholder="z. B. Gemüselasagne" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="m-desc">Beilagen / Beschreibung (optional)</label>
|
||||
<input id="m-desc" name="description" class="field" maxlength="300" value={meal.description} placeholder="z. B. mit Salat" />
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend class="label">Kennzeichnung</legend>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each mealLabelKeys as k (k)}
|
||||
<label class="inline-flex items-center gap-2 rounded-pill border border-line px-3 py-1.5 cursor-pointer has-[:checked]:border-brand has-[:checked]:bg-brand-soft">
|
||||
<input type="checkbox" name="labels" value={k} checked={meal.labels.includes(k)} class="size-4 accent-[var(--brand)]" />
|
||||
<span class="font-semibold text-sm">{MEAL_LABELS[k].label}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend class="label">Allergene</legend>
|
||||
<div class="grid sm:grid-cols-2 gap-x-4 gap-y-1.5">
|
||||
{#each allergenCodes as a (a)}
|
||||
<label class="flex items-start gap-2 cursor-pointer text-sm">
|
||||
<input type="checkbox" name="allergens" value={a} checked={meal.allergens.includes(a)} class="mt-0.5 size-4 accent-[var(--brand)]" />
|
||||
<span><strong>{a}</strong> {ALLERGENS[a]}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="max-w-48">
|
||||
<label class="label" for="m-price">Preis (optional)</label>
|
||||
<input id="m-price" name="price" class="field" maxlength="30" value={meal.price} placeholder="z. B. 3,20 €" />
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<footer class="flex items-center gap-2 px-5 py-3 border-t border-line shrink-0">
|
||||
<button form="meal-form" class="btn btn-primary" disabled={busy}><Save class="size-4" />Speichern</button>
|
||||
{#if meal.id}
|
||||
<form method="POST" action="?/delete" class="ml-auto" use:enhance={submit}>
|
||||
<input type="hidden" name="id" value={meal.id} />
|
||||
{#if confirmDelete}
|
||||
<button class="btn btn-danger" disabled={busy}><Trash2 class="size-4" />Wirklich löschen</button>
|
||||
{:else}
|
||||
<button type="button" class="btn btn-ghost" onclick={() => (confirmDelete = true)}><Trash2 class="size-4" />Löschen</button>
|
||||
{/if}
|
||||
</form>
|
||||
{/if}
|
||||
</footer>
|
||||
</div>
|
||||
{/if}
|
||||
</dialog>
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
</script>
|
||||
|
||||
<label class="flex items-start gap-3 cursor-pointer">
|
||||
<input type="checkbox" {name} {checked} class="switch mt-0.5" />
|
||||
<input type="checkbox" role="switch" {name} {checked} class="switch mt-0.5" />
|
||||
<span>
|
||||
<span class="block font-semibold">{label}</span>
|
||||
{#if hint}<span class="block text-sm text-ink-3">{hint}</span>{/if}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@
|
|||
const label = $derived.by(() => {
|
||||
if (entry.type === 'plan')
|
||||
return [
|
||||
`Planung: ${entry.title}`,
|
||||
'Planung',
|
||||
EDITORIAL_KINDS[entry.kind],
|
||||
`Status ${EDITORIAL_STATUS[entry.status]}`,
|
||||
assignee ? `zuständig ${assignee.name}` : 'niemand zuständig',
|
||||
|
|
@ -34,7 +34,8 @@
|
|||
.filter(Boolean)
|
||||
.join(', ');
|
||||
if (entry.type === 'post')
|
||||
return `Meldung: ${entry.title}, ${entry.live ? 'veröffentlicht' : entry.published ? `geplant um ${entry.time} Uhr` : 'Entwurf'}`;
|
||||
// gleiche Wörter wie sichtbar (WCAG 2.5.3 „Label in Name“)
|
||||
return `Meldung: ${entry.title}, ${entry.live ? 'Online' : entry.published ? `Geplant · ${entry.time} Uhr` : 'Entwurf'}`;
|
||||
return `${entry.closure ? 'Schließzeit' : 'Termin'}: ${entry.title}`;
|
||||
});
|
||||
|
||||
|
|
@ -50,11 +51,10 @@
|
|||
{draggable}
|
||||
ondragstart={dragstart}
|
||||
onclick={() => onopen(entry)}
|
||||
aria-label={label}
|
||||
class="tone-{STATUS_TONE[entry.status]} group w-full text-left rounded-lg bg-surface border border-line border-l-4 border-l-tone px-2 py-1.5 hover:border-brand/40 hover:shadow-card transition cursor-grab active:cursor-grabbing {entry.status === 'done' ? 'bg-surface-2' : ''}"
|
||||
>
|
||||
<span class="flex items-start gap-1.5">
|
||||
<span class="flex-1 min-w-0 text-[0.8rem] font-semibold leading-snug {compact ? 'line-clamp-2' : ''} {entry.status === 'done' ? 'line-through text-ink-2' : ''}">{entry.title}</span>
|
||||
<span class="flex-1 min-w-0 text-[0.8rem] font-semibold leading-snug {compact ? 'line-clamp-2' : ''} {entry.status === 'done' ? 'line-through text-ink-2' : ''}">{entry.title}<span class="sr-only">, {label}</span></span>
|
||||
{#if assignee}
|
||||
<span class="grid place-items-center size-5 rounded-full bg-brand text-on-brand text-[0.6rem] font-bold shrink-0" aria-hidden="true" title={assignee.name}>{assignee.initials}</span>
|
||||
{/if}
|
||||
|
|
|
|||
29
src/lib/components/LanguagePicker.svelte
Normal file
29
src/lib/components/LanguagePicker.svelte
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<script lang="ts">
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import Languages from '@lucide/svelte/icons/languages';
|
||||
import { prefs } from '$lib/prefs.svelte';
|
||||
import { LANGUAGES, type LangCode } from '$lib/languages';
|
||||
|
||||
/** Auswahl der Sprache für Texte (KI-Übersetzung) – Sprachnamen in der jeweiligen Sprache */
|
||||
let { languages }: { languages: LangCode[] } = $props();
|
||||
|
||||
async function choose(lang: string) {
|
||||
prefs.set({ lang });
|
||||
await invalidateAll();
|
||||
}
|
||||
</script>
|
||||
|
||||
<details class="group">
|
||||
<summary class="inline-flex items-center gap-2 cursor-pointer rounded-pill bg-surface-2 hover:bg-brand-soft px-3.5 py-1.5 text-sm font-semibold text-brand-ink list-none [&::-webkit-details-marker]:hidden">
|
||||
<Languages class="size-4" aria-hidden="true" />Andere Sprache <span lang="en" class="text-ink-2 font-medium">· Language</span>
|
||||
</summary>
|
||||
<ul class="mt-2 flex flex-wrap gap-2" aria-label="Sprache wählen">
|
||||
{#each languages as l (l)}
|
||||
<li>
|
||||
<button type="button" class="btn btn-soft btn-sm" lang={l} dir={LANGUAGES[l].dir} onclick={() => choose(l)}>
|
||||
{LANGUAGES[l].name}<span class="sr-only" lang="de"> ({LANGUAGES[l].german})</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</details>
|
||||
39
src/lib/components/MealCard.svelte
Normal file
39
src/lib/components/MealCard.svelte
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<script lang="ts">
|
||||
import Sprout from '@lucide/svelte/icons/sprout';
|
||||
import Leaf from '@lucide/svelte/icons/leaf';
|
||||
import Fish from '@lucide/svelte/icons/fish';
|
||||
import Drumstick from '@lucide/svelte/icons/drumstick';
|
||||
import Beef from '@lucide/svelte/icons/beef';
|
||||
import Ham from '@lucide/svelte/icons/ham';
|
||||
import { ALLERGENS, MEAL_LABELS, type AllergenCode, type MealLabel } from '$lib/meals';
|
||||
|
||||
type MealItem = { line: string; title: string; description: string; allergens: string[]; labels: string[]; price: string; location?: string };
|
||||
let { meal, showLocation = false }: { meal: MealItem; showLocation?: boolean } = $props();
|
||||
|
||||
const icons = { vegan: Sprout, vegetarisch: Leaf, fisch: Fish, gefluegel: Drumstick, rind: Beef, schwein: Ham };
|
||||
</script>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
{#if meal.line || (showLocation && meal.location)}
|
||||
<p class="eyebrow !text-accent-ink">{[meal.line, showLocation ? meal.location : ''].filter(Boolean).join(' · ')}</p>
|
||||
{/if}
|
||||
<p class="font-bold text-lg leading-snug">{meal.title}</p>
|
||||
{#if meal.description}<p class="text-ink-2">{meal.description}</p>{/if}
|
||||
<div class="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-sm">
|
||||
{#each meal.labels as l (l)}
|
||||
{@const L = icons[l as MealLabel]}
|
||||
{#if L}
|
||||
<span class="inline-flex items-center gap-1 rounded-pill bg-brand-soft text-brand-ink px-2.5 py-0.5 font-semibold">
|
||||
<L class="size-4" aria-hidden="true" />{MEAL_LABELS[l as MealLabel].label}
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
{#if meal.allergens.length}
|
||||
<span class="text-ink-2">
|
||||
Allergene:
|
||||
{#each meal.allergens as a, i (a)}<abbr title={ALLERGENS[a as AllergenCode]} class="no-underline font-semibold">{a}</abbr><span class="sr-only"> ({ALLERGENS[a as AllergenCode]})</span>{i < meal.allergens.length - 1 ? ', ' : ''}{/each}
|
||||
</span>
|
||||
{/if}
|
||||
{#if meal.price}<span class="font-semibold ml-auto">{meal.price}</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -3,10 +3,17 @@
|
|||
import Moon from '@lucide/svelte/icons/moon';
|
||||
import Monitor from '@lucide/svelte/icons/monitor';
|
||||
import BookHeart from '@lucide/svelte/icons/book-heart';
|
||||
import Languages from '@lucide/svelte/icons/languages';
|
||||
import { page } from '$app/state';
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import { prefs } from '$lib/prefs.svelte';
|
||||
import { LANGUAGES, isLang } from '$lib/languages';
|
||||
|
||||
let { compact = false, easy = true }: { compact?: boolean; easy?: boolean } = $props();
|
||||
|
||||
// Sprachen für KI-Übersetzungen (nur im Leserbereich, wenn eingeschaltet)
|
||||
const languages = $derived(easy ? ((page.data.languages ?? []) as string[]).filter(isLang) : []);
|
||||
|
||||
const themes = [
|
||||
{ value: 'light', label: 'Hell', icon: Sun },
|
||||
{ value: 'dark', label: 'Dunkel', icon: Moon },
|
||||
|
|
@ -43,6 +50,30 @@
|
|||
</label>
|
||||
{/if}
|
||||
|
||||
{#if languages.length}
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="grid place-items-center size-10 rounded-xl bg-brand-soft text-brand-ink shrink-0" aria-hidden="true">
|
||||
<Languages class="size-5" />
|
||||
</span>
|
||||
<label for="pref-lang" class="flex-1">
|
||||
<span class="block font-semibold">Sprache der Texte <span lang="en" class="font-medium text-ink-2">· Language</span></span>
|
||||
{#if !compact}<span class="block text-sm text-ink-3">Meldungen und Seiten werden automatisch übersetzt.</span>{/if}
|
||||
</label>
|
||||
<select
|
||||
id="pref-lang"
|
||||
class="field w-auto min-h-10 py-1"
|
||||
value={prefs.current.lang}
|
||||
onchange={async (e) => {
|
||||
prefs.set({ lang: e.currentTarget.value });
|
||||
await invalidateAll();
|
||||
}}
|
||||
>
|
||||
<option value="de" lang="de">Deutsch</option>
|
||||
{#each languages as l (l)}<option value={l} lang={l}>{LANGUAGES[l].name}</option>{/each}
|
||||
</select>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<fieldset>
|
||||
<legend class="font-semibold mb-2">Schriftgröße</legend>
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@
|
|||
import { page } from '$app/state';
|
||||
import { prefs } from '$lib/prefs.svelte';
|
||||
import { STREAM_ERROR } from '$lib/easy-language';
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import Languages from '@lucide/svelte/icons/languages';
|
||||
import LanguagePicker from './LanguagePicker.svelte';
|
||||
import { LANGUAGES, isLang } from '$lib/languages';
|
||||
|
||||
/**
|
||||
* Zeigt den Text – bei „Leichte Sprache“ die eigene Fassung der Redaktion,
|
||||
|
|
@ -18,7 +22,8 @@
|
|||
easyAutoPending = false,
|
||||
kind = 'post',
|
||||
slug = '',
|
||||
id = 'vorlesen'
|
||||
id = 'vorlesen',
|
||||
translation = null
|
||||
}: {
|
||||
content: string;
|
||||
contentEasy: string;
|
||||
|
|
@ -27,8 +32,44 @@
|
|||
kind?: 'post' | 'page';
|
||||
slug?: string;
|
||||
id?: string;
|
||||
/** KI-Übersetzung: liegt vor (Text ist schon übersetzt) oder wird gerade erstellt */
|
||||
translation?: { lang: string; status: 'ready' | 'pending' } | null;
|
||||
} = $props();
|
||||
|
||||
const languages = $derived(((page.data.languages ?? []) as string[]).filter(isLang));
|
||||
const tr = $derived(translation && isLang(translation.lang) ? { ...translation, info: LANGUAGES[translation.lang] } : null);
|
||||
let trStatus = $state<'idle' | 'loading' | 'error'>('idle');
|
||||
let trError = $state('');
|
||||
|
||||
// Übersetzung fehlt noch → anstoßen, danach Seite neu laden
|
||||
$effect(() => {
|
||||
if (tr?.status === 'pending' && untrack(() => trStatus) === 'idle') untrack(translateNow);
|
||||
});
|
||||
|
||||
async function translateNow() {
|
||||
if (!tr) return;
|
||||
trStatus = 'loading';
|
||||
try {
|
||||
const res = await fetch('/api/uebersetzung', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ typ: kind, slug, lang: tr.lang })
|
||||
});
|
||||
if (!res.ok) throw new Error((await res.json().catch(() => null))?.message ?? 'Die Übersetzung ist gerade nicht möglich.');
|
||||
await invalidateAll();
|
||||
trStatus = 'idle';
|
||||
} catch (e) {
|
||||
trError = (e as Error).message;
|
||||
trStatus = 'error';
|
||||
}
|
||||
}
|
||||
|
||||
async function showGerman() {
|
||||
prefs.set({ lang: 'de' });
|
||||
trStatus = 'idle';
|
||||
await invalidateAll();
|
||||
}
|
||||
|
||||
let auto = $state(untrack(() => contentEasyAuto));
|
||||
let live = $state('');
|
||||
let status = $state<'idle' | 'loading' | 'error'>('idle');
|
||||
|
|
@ -41,11 +82,12 @@
|
|||
untrack(() => {
|
||||
live = '';
|
||||
status = 'idle';
|
||||
trStatus = 'idle';
|
||||
});
|
||||
});
|
||||
|
||||
const available = $derived(!!contentEasy || !!auto || easyAutoPending);
|
||||
const mode = $derived(!prefs.current.easy ? 'normal' : contentEasy ? 'manual' : auto ? 'auto' : easyAutoPending ? 'pending' : 'normal');
|
||||
const mode = $derived(!prefs.current.easy || translation ? 'normal' : contentEasy ? 'manual' : auto ? 'auto' : easyAutoPending ? 'pending' : 'normal');
|
||||
|
||||
// Leichte Sprache gewünscht, aber noch keine Fassung → jetzt übertragen
|
||||
$effect(() => {
|
||||
|
|
@ -104,7 +146,22 @@
|
|||
const reportHref = $derived(`/barrierefreiheit?seite=${encodeURIComponent(page.url.pathname)}#message`);
|
||||
</script>
|
||||
|
||||
{#if available}
|
||||
{#if tr}
|
||||
<div class="bg-accent-soft text-accent-ink rounded-3xl pl-4 pr-5 py-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm font-semibold" lang={tr.lang} dir={tr.info.dir}>
|
||||
<Languages class="size-5 shrink-0" aria-hidden="true" />
|
||||
<span class="flex-1 min-w-48" role="status">
|
||||
{#if tr.status === 'ready'}
|
||||
{tr.info.note}
|
||||
{:else if trStatus === 'error'}
|
||||
<span lang="de" dir="ltr">{trError} Du siehst den deutschen Text.</span>
|
||||
{:else}
|
||||
{tr.info.loading}
|
||||
{/if}
|
||||
</span>
|
||||
{#if tr.status === 'ready'}<a href={reportHref} class="underline underline-offset-2" lang="de" dir="ltr">Fehler melden</a>{/if}
|
||||
<button class="font-bold underline underline-offset-2 min-h-8" onclick={showGerman}>{tr.info.original}<span class="sr-only" lang="de"> (Deutsch)</span></button>
|
||||
</div>
|
||||
{:else if available}
|
||||
<div class="bg-accent-soft text-accent-ink rounded-3xl pl-4 pr-5 py-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm font-semibold">
|
||||
{#if mode === 'auto' || mode === 'pending'}<Sparkles class="size-5 shrink-0" aria-hidden="true" />{:else}<BookHeart class="size-5 shrink-0" aria-hidden="true" />{/if}
|
||||
<span class="flex-1 min-w-48">
|
||||
|
|
@ -127,6 +184,16 @@
|
|||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !tr && languages.length}
|
||||
<LanguagePicker {languages} />
|
||||
{/if}
|
||||
|
||||
{#if tr?.status === 'pending' && trStatus === 'loading'}
|
||||
<p class="flex items-center gap-2 text-sm font-semibold text-accent-ink" lang={tr.lang} dir={tr.info.dir}>
|
||||
<LoaderCircle class="size-4 animate-spin" aria-hidden="true" />{tr.info.loading}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if mode === 'pending' && status === 'loading'}
|
||||
<div class="rounded-3xl border-2 border-dashed border-accent/40 p-5" aria-busy="true">
|
||||
<p class="flex items-center gap-2 text-sm font-semibold text-accent-ink"><LoaderCircle class="size-4 animate-spin" aria-hidden="true" />Bitte kurz warten.</p>
|
||||
|
|
@ -135,7 +202,7 @@
|
|||
{:else}
|
||||
{@const html = mode === 'manual' ? contentEasy : mode === 'auto' ? auto : content}
|
||||
{#if html}
|
||||
<div {id} class="rich {mode === 'manual' || mode === 'auto' ? 'easy' : ''}">
|
||||
<div {id} class="rich {mode === 'manual' || mode === 'auto' ? 'easy' : ''}" lang={tr?.status === 'ready' ? tr.lang : undefined} dir={tr?.status === 'ready' ? tr.info.dir : undefined} data-uebersetzt={tr?.status === 'ready' ? '' : undefined}>
|
||||
{@html html}
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
|||
18
src/lib/languages.ts
Normal file
18
src/lib/languages.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
/**
|
||||
* Sprachen für automatische Übersetzungen (KI). Die kurzen Hinweise stehen in der
|
||||
* jeweiligen Sprache, damit Leser sie verstehen, auch wenn die App sonst deutsch ist.
|
||||
*/
|
||||
export const LANGUAGES = {
|
||||
en: { name: 'English', german: 'Englisch', english: 'English', dir: 'ltr', note: 'Automatically translated from German. It may contain mistakes.', original: 'Show German original', loading: 'Translating …' },
|
||||
tr: { name: 'Türkçe', german: 'Türkisch', english: 'Turkish', dir: 'ltr', note: 'Almancadan otomatik olarak çevrildi. Hatalar içerebilir.', original: 'Almanca aslını göster', loading: 'Çevriliyor …' },
|
||||
ar: { name: 'العربية', german: 'Arabisch', english: 'Arabic (Modern Standard Arabic)', dir: 'rtl', note: 'تمت الترجمة تلقائيًا من الألمانية. قد تحتوي على أخطاء.', original: 'عرض النص الألماني الأصلي', loading: 'جارٍ الترجمة …' },
|
||||
uk: { name: 'Українська', german: 'Ukrainisch', english: 'Ukrainian', dir: 'ltr', note: 'Автоматично перекладено з німецької. Можливі помилки.', original: 'Показати німецький оригінал', loading: 'Перекладається …' },
|
||||
ru: { name: 'Русский', german: 'Russisch', english: 'Russian', dir: 'ltr', note: 'Автоматически переведено с немецкого. Возможны ошибки.', original: 'Показать немецкий оригинал', loading: 'Идёт перевод …' },
|
||||
pl: { name: 'Polski', german: 'Polnisch', english: 'Polish', dir: 'ltr', note: 'Przetłumaczono automatycznie z języka niemieckiego. Mogą wystąpić błędy.', original: 'Pokaż oryginał po niemiecku', loading: 'Tłumaczenie …' },
|
||||
ro: { name: 'Română', german: 'Rumänisch', english: 'Romanian', dir: 'ltr', note: 'Tradus automat din germană. Poate conține greșeli.', original: 'Arată originalul în germană', loading: 'Se traduce …' },
|
||||
fa: { name: 'فارسی', german: 'Persisch (Farsi)', english: 'Persian (Farsi)', dir: 'rtl', note: 'بهطور خودکار از آلمانی ترجمه شده است. ممکن است اشتباه داشته باشد.', original: 'نمایش متن اصلی آلمانی', loading: 'در حال ترجمه …' }
|
||||
} as const;
|
||||
|
||||
export type LangCode = keyof typeof LANGUAGES;
|
||||
export const langCodes = Object.keys(LANGUAGES) as LangCode[];
|
||||
export const isLang = (v: unknown): v is LangCode => typeof v === 'string' && v in LANGUAGES;
|
||||
29
src/lib/meals.test.ts
Normal file
29
src/lib/meals.test.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { cleanAllergens, cleanLabels, isoWeek, mondayOf, weekDays } from './meals';
|
||||
|
||||
describe('Kalenderwochen', () => {
|
||||
it.each([
|
||||
['2026-10-09', '2026-10-05', 41],
|
||||
['2026-01-01', '2025-12-29', 1],
|
||||
['2027-01-01', '2026-12-28', 53],
|
||||
['2024-12-30', '2024-12-30', 1],
|
||||
['2021-01-03', '2020-12-28', 53],
|
||||
['2026-10-12', '2026-10-12', 42]
|
||||
])('%s liegt in der Woche ab %s (KW %i)', (day, monday, week) => {
|
||||
expect(mondayOf(day)).toBe(monday);
|
||||
expect(isoWeek(day)).toBe(week);
|
||||
});
|
||||
|
||||
it('liefert Mo–Fr bzw. Mo–So', () => {
|
||||
expect(weekDays('2026-10-05')).toEqual(['2026-10-05', '2026-10-06', '2026-10-07', '2026-10-08', '2026-10-09']);
|
||||
expect(weekDays('2026-10-05', 7).at(-1)).toBe('2026-10-11');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Eingaben bereinigen', () => {
|
||||
it('lässt nur bekannte Allergene und Kennzeichen durch – in fester Reihenfolge', () => {
|
||||
expect(cleanAllergens(['G', 'A', 'X', '<b>'])).toEqual(['A', 'G']);
|
||||
expect(cleanAllergens('A')).toEqual([]);
|
||||
expect(cleanLabels(['vegan', 'lecker'])).toEqual(['vegan']);
|
||||
});
|
||||
});
|
||||
68
src/lib/meals.ts
Normal file
68
src/lib/meals.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { addDays } from './dates';
|
||||
|
||||
/** Die 14 Hauptallergene nach LMIV mit den in Kantinen üblichen Kennbuchstaben */
|
||||
export const ALLERGENS = {
|
||||
A: 'Gluten (Weizen, Roggen, Gerste, Hafer)',
|
||||
B: 'Krebstiere',
|
||||
C: 'Eier',
|
||||
D: 'Fisch',
|
||||
E: 'Erdnüsse',
|
||||
F: 'Soja',
|
||||
G: 'Milch und Laktose',
|
||||
H: 'Schalenfrüchte (Nüsse)',
|
||||
L: 'Sellerie',
|
||||
M: 'Senf',
|
||||
N: 'Sesam',
|
||||
O: 'Schwefeldioxid und Sulfite',
|
||||
P: 'Lupinen',
|
||||
R: 'Weichtiere'
|
||||
} as const;
|
||||
export type AllergenCode = keyof typeof ALLERGENS;
|
||||
export const allergenCodes = Object.keys(ALLERGENS) as AllergenCode[];
|
||||
|
||||
/** Kennzeichen für Gerichte – mit Symbol und kurzer Bezeichnung */
|
||||
export const MEAL_LABELS = {
|
||||
vegan: { label: 'vegan', icon: 'sprout' },
|
||||
vegetarisch: { label: 'vegetarisch', icon: 'leaf' },
|
||||
fisch: { label: 'mit Fisch', icon: 'fish' },
|
||||
gefluegel: { label: 'mit Geflügel', icon: 'drumstick' },
|
||||
rind: { label: 'mit Rind', icon: 'beef' },
|
||||
schwein: { label: 'mit Schwein', icon: 'ham' }
|
||||
} as const;
|
||||
export type MealLabel = keyof typeof MEAL_LABELS;
|
||||
export const mealLabelKeys = Object.keys(MEAL_LABELS) as MealLabel[];
|
||||
|
||||
export const cleanAllergens = (v: unknown): AllergenCode[] =>
|
||||
Array.isArray(v) ? allergenCodes.filter((c) => v.includes(c)) : [];
|
||||
export const cleanLabels = (v: unknown): MealLabel[] =>
|
||||
Array.isArray(v) ? mealLabelKeys.filter((c) => v.includes(c)) : [];
|
||||
|
||||
/** Montag der Woche, in der `iso` liegt */
|
||||
export function mondayOf(iso: string): string {
|
||||
const d = new Date(`${iso}T12:00:00Z`);
|
||||
const dow = (d.getUTCDay() + 6) % 7; // Mo = 0
|
||||
return addDays(iso, -dow);
|
||||
}
|
||||
|
||||
/** Kalenderwoche nach ISO 8601 */
|
||||
export function isoWeek(iso: string): number {
|
||||
const thursday = new Date(`${addDays(mondayOf(iso), 3)}T12:00:00Z`);
|
||||
const firstThursday = new Date(`${addDays(mondayOf(`${thursday.getUTCFullYear()}-01-04`), 3)}T12:00:00Z`);
|
||||
return 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 864e5));
|
||||
}
|
||||
|
||||
/** Tage einer Woche ab Montag (5 = Mo–Fr, 7 = mit Wochenende) */
|
||||
export const weekDays = (monday: string, count = 5) => Array.from({ length: count }, (_, i) => addDays(monday, i));
|
||||
|
||||
/** Gericht im Bearbeiten-Dialog der Redaktion (id 0 = neu) */
|
||||
export type MealDraft = {
|
||||
id: number;
|
||||
date: string;
|
||||
line: string;
|
||||
location: string;
|
||||
title: string;
|
||||
description: string;
|
||||
allergens: string[];
|
||||
labels: string[];
|
||||
price: string;
|
||||
};
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { PREFS_COOKIE, type Prefs } from './prefs';
|
||||
import { DEFAULT_PREFS, PREFS_COOKIE, type Prefs } from './prefs';
|
||||
import { syncStatusBar } from './native';
|
||||
|
||||
/** Reaktive Anzeige-Einstellungen im Browser. */
|
||||
class PrefsState {
|
||||
current = $state<Prefs>({ theme: 'system', size: 'm', easy: false });
|
||||
current = $state<Prefs>({ ...DEFAULT_PREFS });
|
||||
|
||||
init(p: Prefs) {
|
||||
this.current = { ...p };
|
||||
|
|
|
|||
16
src/lib/prefs.test.ts
Normal file
16
src/lib/prefs.test.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { DEFAULT_PREFS, parsePrefs } from './prefs';
|
||||
|
||||
describe('Anzeige-Einstellungen aus dem Cookie', () => {
|
||||
it('liest gültige Werte', () => {
|
||||
const raw = encodeURIComponent(JSON.stringify({ theme: 'dark', size: 'xl', easy: true, lang: 'tr' }));
|
||||
expect(parsePrefs(raw)).toEqual({ theme: 'dark', size: 'xl', easy: true, lang: 'tr' });
|
||||
});
|
||||
|
||||
it('fällt bei Unsinn auf Standardwerte zurück', () => {
|
||||
expect(parsePrefs(undefined)).toEqual(DEFAULT_PREFS);
|
||||
expect(parsePrefs('%%%kaputt')).toEqual(DEFAULT_PREFS);
|
||||
const raw = encodeURIComponent(JSON.stringify({ theme: 'pink', size: 'xxl', easy: 'ja', lang: '../etc' }));
|
||||
expect(parsePrefs(raw)).toEqual(DEFAULT_PREFS);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,10 +3,12 @@ export type Prefs = {
|
|||
theme: 'system' | 'light' | 'dark';
|
||||
size: 'm' | 'l' | 'xl';
|
||||
easy: boolean;
|
||||
/** Sprache für Texte: de oder Code einer KI-Übersetzung */
|
||||
lang: string;
|
||||
};
|
||||
|
||||
export const PREFS_COOKIE = 'wa_prefs';
|
||||
export const DEFAULT_PREFS: Prefs = { theme: 'system', size: 'm', easy: false };
|
||||
export const DEFAULT_PREFS: Prefs = { theme: 'system', size: 'm', easy: false, lang: 'de' };
|
||||
|
||||
export function parsePrefs(raw: string | undefined): Prefs {
|
||||
if (!raw) return DEFAULT_PREFS;
|
||||
|
|
@ -15,7 +17,8 @@ export function parsePrefs(raw: string | undefined): Prefs {
|
|||
return {
|
||||
theme: ['system', 'light', 'dark'].includes(p.theme) ? p.theme : 'system',
|
||||
size: ['m', 'l', 'xl'].includes(p.size) ? p.size : 'm',
|
||||
easy: p.easy === true
|
||||
easy: p.easy === true,
|
||||
lang: typeof p.lang === 'string' && /^[a-z]{2}$/.test(p.lang) ? p.lang : 'de'
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_PREFS;
|
||||
|
|
|
|||
|
|
@ -305,6 +305,73 @@ export const editorialComments = sqliteTable(
|
|||
(t) => [index('editorial_comments_item_idx').on(t.itemId)]
|
||||
);
|
||||
|
||||
// ─── Speiseplan ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Ein Gericht an einem Tag (optional je Standort und Linie, z. B. „Menü 1“) */
|
||||
export const meals = sqliteTable(
|
||||
'meals',
|
||||
{
|
||||
id: integer('id').primaryKey({ autoIncrement: true }),
|
||||
/** YYYY-MM-DD */
|
||||
date: text('date').notNull(),
|
||||
/** Standort/Kantine, leer = alle */
|
||||
location: text('location').notNull().default(''),
|
||||
line: text('line').notNull().default(''),
|
||||
title: text('title').notNull(),
|
||||
description: text('description').notNull().default(''),
|
||||
/** Allergen-Kennbuchstaben nach LMIV, z. B. ["A","G"] */
|
||||
allergens: text('allergens', { mode: 'json' }).$type<string[]>().notNull().default([]),
|
||||
/** Kennzeichen wie vegetarisch, vegan, schwein … */
|
||||
labels: text('labels', { mode: 'json' }).$type<string[]>().notNull().default([]),
|
||||
price: text('price').notNull().default(''),
|
||||
position: integer('position').notNull().default(0),
|
||||
...timestamps
|
||||
},
|
||||
(t) => [index('meals_date_idx').on(t.date)]
|
||||
);
|
||||
|
||||
// ─── Übersetzungen (KI) ────────────────────────────────────────────────────────
|
||||
|
||||
/** Automatische Übersetzung einer Meldung oder Seite in eine andere Sprache */
|
||||
export const translations = sqliteTable(
|
||||
'translations',
|
||||
{
|
||||
id: integer('id').primaryKey({ autoIncrement: true }),
|
||||
kind: text('kind', { enum: ['post', 'page'] }).notNull(),
|
||||
refId: integer('ref_id').notNull(),
|
||||
lang: text('lang').notNull(),
|
||||
/** Prüfsumme des Originals – ändert sich der Text, wird neu übersetzt */
|
||||
hash: text('hash').notNull(),
|
||||
title: text('title').notNull(),
|
||||
teaser: text('teaser').notNull().default(''),
|
||||
html: text('html').notNull(),
|
||||
model: text('model').notNull().default(''),
|
||||
createdAt: integer('created_at', { mode: 'timestamp' })
|
||||
.notNull()
|
||||
.default(sql`(unixepoch())`)
|
||||
},
|
||||
(t) => [uniqueIndex('translations_ref_lang_idx').on(t.kind, t.refId, t.lang)]
|
||||
);
|
||||
|
||||
// ─── Lesezahlen (anonym) ───────────────────────────────────────────────────────
|
||||
|
||||
/** Aufrufe je Tag und Seite – ohne Cookies, ohne IP, ohne Geräte-Kennung */
|
||||
export const pageViews = sqliteTable(
|
||||
'page_views',
|
||||
{
|
||||
day: text('day').notNull(),
|
||||
path: text('path').notNull(),
|
||||
/** web oder app */
|
||||
client: text('client').notNull().default('web'),
|
||||
/** normal, leicht oder Sprachcode einer Übersetzung */
|
||||
variant: text('variant').notNull().default('normal'),
|
||||
views: integer('views').notNull().default(0)
|
||||
},
|
||||
(t) => [uniqueIndex('page_views_key_idx').on(t.day, t.path, t.client, t.variant), index('page_views_day_idx').on(t.day)]
|
||||
);
|
||||
|
||||
export type Meal = typeof meals.$inferSelect;
|
||||
export type Translation = typeof translations.$inferSelect;
|
||||
export type User = typeof users.$inferSelect;
|
||||
export type Media = typeof media.$inferSelect;
|
||||
export type Contact = typeof contacts.$inferSelect;
|
||||
|
|
|
|||
22
src/lib/server/legal.test.ts
Normal file
22
src/lib/server/legal.test.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { DEFAULT_SETTINGS } from '$lib/settings';
|
||||
import { privacyTemplate } from './legal';
|
||||
|
||||
const numbers = (html: string) => [...html.matchAll(/<h2>(\d+)\. /g)].map((m) => Number(m[1]));
|
||||
|
||||
describe('Datenschutzerklärung', () => {
|
||||
it.each([
|
||||
['ohne KI', { aiEnabled: false, aiLanguages: [] }],
|
||||
['mit KI', { aiEnabled: true, aiLanguages: [] }],
|
||||
['mit Übersetzungen', { aiEnabled: true, aiLanguages: ['tr'] }]
|
||||
])('nummeriert lückenlos (%s)', (_, patch) => {
|
||||
const n = numbers(privacyTemplate({ ...DEFAULT_SETTINGS, ...patch }));
|
||||
expect(n).toEqual(n.map((_, i) => i + 1));
|
||||
});
|
||||
|
||||
it('erwähnt anonyme Aufrufzahlen und – falls aktiv – Übersetzungen', () => {
|
||||
const html = privacyTemplate({ ...DEFAULT_SETTINGS, aiEnabled: true, aiLanguages: ['tr'] });
|
||||
expect(html).toContain('Anonyme Aufrufzahlen');
|
||||
expect(html).toContain('Übersetzungen mit KI');
|
||||
});
|
||||
});
|
||||
|
|
@ -35,36 +35,40 @@ export function imprintTemplate(s: AppSettings): string {
|
|||
export function privacyTemplate(s: AppSettings): string {
|
||||
const l = s.legal;
|
||||
const days = Math.max(1, l.logRetentionDays || 7);
|
||||
let n = 0;
|
||||
const h = (title: string) => `<h2>${++n}. ${title}</h2>`;
|
||||
const translations = s.aiEnabled && s.aiLanguages.length > 0;
|
||||
return [
|
||||
'<p><strong>Kurz gesagt:</strong> Diese App kommt ohne Werbung, ohne Tracking und ohne Analyse-Werkzeuge aus. Wir verarbeiten nur die Daten, die für den Betrieb nötig sind oder die du uns selbst gibst.</p>',
|
||||
'<p><strong>Kurz gesagt:</strong> Diese App kommt ohne Werbung, ohne Tracking und ohne Analyse-Werkzeuge von Drittanbietern aus. Wir verarbeiten nur die Daten, die für den Betrieb nötig sind oder die du uns selbst gibst.</p>',
|
||||
|
||||
'<h2>1. Verantwortlich</h2>',
|
||||
h('Verantwortlich'),
|
||||
`<p>${val(l.name, 'Name der Einrichtung')}<br>${l.street || l.city ? lines(l.street, l.city) : todo('Anschrift')}<br>E-Mail: ${val(l.email, 'E-Mail-Adresse')}${l.phone ? `<br>Telefon: ${esc(l.phone)}` : ''}</p>`,
|
||||
l.dpo ? `<p><strong>Datenschutzbeauftragte/r:</strong><br>${esc(l.dpo)}</p>` : '',
|
||||
|
||||
'<h2>2. Betrieb der App</h2>',
|
||||
h('Betrieb der App'),
|
||||
'<p>Die App wird auf einem eigenen Server des Verantwortlichen betrieben. Es werden keine Daten an Dritte weitergegeben, außer in den unten beschriebenen Fällen, die du selbst auslöst.</p>',
|
||||
`<p>Beim Aufruf verarbeitet der Server technisch notwendige Daten: IP-Adresse, Datum und Uhrzeit, aufgerufene Adresse sowie Angaben zu Browser und Betriebssystem. Das ist nötig, um die Seiten auszuliefern und den Betrieb abzusichern (Art. 6 Abs. 1 lit. f DSGVO). Protokolldateien werden nach spätestens ${days} Tagen gelöscht.</p>`,
|
||||
'<p><strong>Anonyme Aufrufzahlen:</strong> Damit die Redaktion sieht, welche Inhalte gelesen werden, zählt die App, wie oft eine Seite pro Tag aufgerufen wurde – getrennt nach Web und App sowie nach Sprachfassung. Dabei werden weder Cookies gesetzt noch IP-Adressen, Geräte-Kennungen oder andere Angaben zu dir gespeichert; ein Rückschluss auf einzelne Personen ist nicht möglich. Die Zahlen werden nach 13 Monaten gelöscht.</p>',
|
||||
|
||||
'<h2>3. Cookies und Speicher auf deinem Gerät</h2>',
|
||||
h('Cookies und Speicher auf deinem Gerät'),
|
||||
'<ul>',
|
||||
'<li><strong>Anzeige-Einstellungen</strong> (Schriftgröße, Farbschema, Leichte Sprache) speichern wir in einem Cookie auf deinem Gerät, damit die App so aussieht, wie du es eingestellt hast.</li>',
|
||||
'<li><strong>Anzeige-Einstellungen</strong> (Schriftgröße, Farbschema, Leichte Sprache, Sprache der Texte) speichern wir in einem Cookie auf deinem Gerät, damit die App so aussieht, wie du es eingestellt hast.</li>',
|
||||
'<li><strong>Merkliste</strong>, gewähltes <strong>Vorlese-Tempo</strong> und die Themen für <strong>Benachrichtigungen</strong> liegen nur im Speicher deines Browsers und werden nicht an uns übertragen.</li>',
|
||||
'<li>Für die <strong>Redaktion</strong> setzen wir nach der Anmeldung ein Sitzungs-Cookie.</li>',
|
||||
'</ul>',
|
||||
'<p>Diese Speicherungen sind für die von dir gewünschten Funktionen unbedingt erforderlich (§ 25 Abs. 2 Nr. 2 TDDDG). Eine Einwilligung ist dafür nicht nötig, deshalb gibt es auch kein Cookie-Banner.</p>',
|
||||
|
||||
'<h2>4. Kontaktformular und Meldung von Barrieren</h2>',
|
||||
h('Kontaktformular und Meldung von Barrieren'),
|
||||
'<p>Wenn du uns schreibst, speichern wir deinen Namen, deine Nachricht und – falls angegeben – deine E-Mail-Adresse, um dein Anliegen zu bearbeiten (Art. 6 Abs. 1 lit. f DSGVO). Die Nachricht wird gelöscht, sobald sie erledigt ist und keine Aufbewahrungspflicht besteht.</p>',
|
||||
|
||||
'<h2>5. Benachrichtigungen (Push)</h2>',
|
||||
h('Benachrichtigungen (Push)'),
|
||||
'<p>Benachrichtigungen erhältst du nur, wenn du sie selbst einschaltest (Einwilligung, Art. 6 Abs. 1 lit. a DSGVO). Dann speichern wir die Push-Adresse deines Browsers, die zugehörigen Schlüssel und die gewählten Themen. Zugestellt werden die Nachrichten über den Push-Dienst des Browser-Herstellers (z. B. Google, Apple, Mozilla oder Microsoft); dabei kann eine Übermittlung in Länder außerhalb der EU stattfinden. Der Inhalt der Nachricht ist verschlüsselt. In den Apps für iPhone und Android werden die Nachrichten über Firebase Cloud Messaging von Google zugestellt (auf dem iPhone zusätzlich über den Push-Dienst von Apple); gespeichert wird dafür eine Gerätekennung der App. Du kannst die Einwilligung jederzeit unter „Einstellungen → Benachrichtigungen“ widerrufen; die Daten werden dann gelöscht.</p>',
|
||||
|
||||
'<h2>6. Vorlesen</h2>',
|
||||
h('Vorlesen'),
|
||||
'<p>Die Vorlesefunktion nutzt die Sprachausgabe deines Geräts. Wir bevorzugen Stimmen, die direkt auf dem Gerät arbeiten. Steht nur eine Online-Stimme des Browsers zur Verfügung, kann der vorgelesene Text vom Browser-Anbieter verarbeitet werden. Wir selbst erhalten dabei keine Daten.</p>',
|
||||
|
||||
s.aiEnabled
|
||||
? `<h2>7. Leichte Sprache mit KI</h2><p>${s.aiMode === 'auto' ? 'Texte, die es noch nicht in Leichter Sprache gibt, überträgt eine KI automatisch. Dafür werden die veröffentlichten Texte der App' : 'Fassungen in Leichter Sprache entstehen mit Hilfe einer KI und werden vor der Veröffentlichung von der Redaktion geprüft. Dafür werden die Texte der App'} an ${
|
||||
? `${h(translations ? 'Leichte Sprache und Übersetzungen mit KI' : 'Leichte Sprache mit KI')}<p>${s.aiMode === 'auto' ? 'Texte, die es noch nicht in Leichter Sprache gibt, überträgt eine KI automatisch. Dafür werden die veröffentlichten Texte der App' : 'Fassungen in Leichter Sprache entstehen mit Hilfe einer KI und werden vor der Veröffentlichung von der Redaktion geprüft. Dafür werden die Texte der App'} an ${
|
||||
AI_PROVIDERS[s.aiProvider].region === 'own'
|
||||
? 'einen KI-Dienst auf einem eigenen Server des Verantwortlichen'
|
||||
: `den Anbieter ${esc(AI_PROVIDERS[s.aiProvider].label)} (${
|
||||
|
|
@ -72,12 +76,12 @@ export function privacyTemplate(s: AppSettings): string {
|
|||
? 'Sitz und Verarbeitung in der EU'
|
||||
: 'Verarbeitung außerhalb der EU'
|
||||
}, auf Grundlage eines Auftragsverarbeitungsvertrags)`
|
||||
} übermittelt. Von dir als Leserin oder Leser werden dabei keine Daten übermittelt.${s.aiMode === 'auto' ? ' Automatisch übertragene Texte sind in der App gekennzeichnet.' : ''}</p>`
|
||||
} übermittelt. Von dir als Leserin oder Leser werden dabei keine Daten übermittelt.${s.aiMode === 'auto' ? ' Automatisch übertragene Texte sind in der App gekennzeichnet.' : ''}${translations ? ' Wählst du eine andere Sprache, werden Meldungen und Seiten auf dieselbe Weise automatisch übersetzt und als Übersetzung gekennzeichnet; übermittelt wird auch dabei nur der veröffentlichte Text.' : ''}</p>`
|
||||
: '',
|
||||
`<h2>${s.aiEnabled ? 8 : 7}. Eingebettete Videos</h2>`,
|
||||
h('Eingebettete Videos'),
|
||||
'<p>Videos von YouTube (im erweiterten Datenschutzmodus, youtube-nocookie.com) oder Vimeo werden erst geladen, wenn du auf „Video abspielen“ tippst. Erst dann wird eine Verbindung zum jeweiligen Anbieter hergestellt, der dabei u. a. deine IP-Adresse erhält und Daten auch in den USA verarbeiten kann (Einwilligung, Art. 6 Abs. 1 lit. a DSGVO).</p>',
|
||||
|
||||
`<h2>${s.aiEnabled ? 9 : 8}. Deine Rechte</h2>`,
|
||||
h('Deine Rechte'),
|
||||
'<p>Du hast das Recht auf Auskunft, Berichtigung, Löschung und Einschränkung der Verarbeitung, auf Datenübertragbarkeit sowie auf Widerspruch gegen Verarbeitungen, die auf berechtigtem Interesse beruhen. Eine Einwilligung kannst du jederzeit mit Wirkung für die Zukunft widerrufen. Schreib uns dazu einfach über die oben genannten Kontaktdaten.</p>',
|
||||
`<p>Außerdem kannst du dich bei einer Datenschutz-Aufsichtsbehörde beschweren${l.supervisory ? `, zum Beispiel bei der für uns zuständigen: ${esc(l.supervisory)}` : ''}.</p>`,
|
||||
|
||||
|
|
|
|||
38
src/lib/server/meals.test.ts
Normal file
38
src/lib/server/meals.test.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { db } from './db';
|
||||
import { meals } from './db/schema';
|
||||
import { copyWeek, mealsBetween, nextMealDay } from './meals';
|
||||
|
||||
const add = (date: string, title: string, location = '') => db.insert(meals).values({ date, title, location }).run();
|
||||
|
||||
describe('Speiseplan', () => {
|
||||
beforeEach(() => {
|
||||
db.delete(meals).run();
|
||||
});
|
||||
|
||||
it('gruppiert nach Tag und filtert nach Standort (allgemeine Gerichte gelten überall)', () => {
|
||||
add('2026-10-05', 'Suppe');
|
||||
add('2026-10-05', 'Schnitzel', 'Nord');
|
||||
add('2026-10-06', 'Curry', 'Süd');
|
||||
expect(Object.keys(mealsBetween('2026-10-05', '2026-10-09'))).toEqual(['2026-10-05', '2026-10-06']);
|
||||
const nord = mealsBetween('2026-10-05', '2026-10-09', 'Nord');
|
||||
expect(nord['2026-10-05'].map((m) => m.title)).toEqual(['Suppe', 'Schnitzel']);
|
||||
expect(nord['2026-10-06']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('findet den nächsten Tag mit Essen', () => {
|
||||
add('2026-10-12', 'Montagsessen');
|
||||
expect(nextMealDay('2026-10-10')?.date).toBe('2026-10-12');
|
||||
expect(nextMealDay('2026-10-13')).toBeNull();
|
||||
});
|
||||
|
||||
it('übernimmt die Vorwoche nur in leere Tage', () => {
|
||||
add('2026-10-05', 'Mo alt');
|
||||
add('2026-10-06', 'Di alt');
|
||||
add('2026-10-13', 'Di schon geplant');
|
||||
expect(copyWeek('2026-10-05', '2026-10-12')).toBe(1);
|
||||
const next = mealsBetween('2026-10-12', '2026-10-18');
|
||||
expect(next['2026-10-12'].map((m) => m.title)).toEqual(['Mo alt']);
|
||||
expect(next['2026-10-13'].map((m) => m.title)).toEqual(['Di schon geplant']);
|
||||
});
|
||||
});
|
||||
53
src/lib/server/meals.ts
Normal file
53
src/lib/server/meals.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { and, asc, between, eq, inArray, or } from 'drizzle-orm';
|
||||
import { db } from './db';
|
||||
import { meals, type Meal } from './db/schema';
|
||||
import { addDays } from '$lib/dates';
|
||||
|
||||
/** Gerichte eines Zeitraums, nach Tag gruppiert. `location` leer = alle Standorte. */
|
||||
export function mealsBetween(from: string, to: string, location = ''): Record<string, Meal[]> {
|
||||
const rows = db
|
||||
.select()
|
||||
.from(meals)
|
||||
.where(and(between(meals.date, from, to), location ? or(eq(meals.location, location), eq(meals.location, '')) : undefined))
|
||||
.orderBy(asc(meals.date), asc(meals.position), asc(meals.id))
|
||||
.all();
|
||||
const out: Record<string, Meal[]> = {};
|
||||
for (const m of rows) (out[m.date] ??= []).push(m);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const mealsOn = (date: string, location = '') => mealsBetween(date, date, location)[date] ?? [];
|
||||
|
||||
/** Nächster Tag ab `from` (höchstens 7 Tage voraus), an dem es Essen gibt */
|
||||
export function nextMealDay(from: string, location = ''): { date: string; meals: Meal[] } | null {
|
||||
const days = mealsBetween(from, addDays(from, 7), location);
|
||||
const first = Object.keys(days).sort()[0];
|
||||
return first ? { date: first, meals: days[first] } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kopiert alle Gerichte einer Woche in eine andere (Mo–So, gleicher Wochentag).
|
||||
* Tage, die in der Zielwoche schon Gerichte haben, bleiben unverändert.
|
||||
*/
|
||||
export function copyWeek(fromMonday: string, toMonday: string): number {
|
||||
const source = mealsBetween(fromMonday, addDays(fromMonday, 6));
|
||||
const target = mealsBetween(toMonday, addDays(toMonday, 6));
|
||||
let copied = 0;
|
||||
db.transaction((tx) => {
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const from = addDays(fromMonday, i);
|
||||
const to = addDays(toMonday, i);
|
||||
if (target[to]?.length || !source[from]) continue;
|
||||
for (const m of source[from]) {
|
||||
const { id: _id, createdAt: _c, updatedAt: _u, ...rest } = m;
|
||||
tx.insert(meals).values({ ...rest, date: to }).run();
|
||||
copied++;
|
||||
}
|
||||
}
|
||||
});
|
||||
return copied;
|
||||
}
|
||||
|
||||
export function deleteMeals(ids: number[]) {
|
||||
if (ids.length) db.delete(meals).where(inArray(meals.id, ids)).run();
|
||||
}
|
||||
41
src/lib/server/monitor.test.ts
Normal file
41
src/lib/server/monitor.test.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const sent: { to: string; subject: string; text: string }[] = [];
|
||||
vi.mock('./mail', () => ({
|
||||
mailConfigured: () => true,
|
||||
sendMail: async (m: { to: string; subject: string; text: string }) => {
|
||||
sent.push(m);
|
||||
return true;
|
||||
}
|
||||
}));
|
||||
|
||||
const { reportError } = await import('./monitor');
|
||||
|
||||
describe('Fehlermeldungen per E-Mail', () => {
|
||||
beforeEach(() => {
|
||||
sent.length = 0;
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
it('schickt ohne ALERT_EMAIL nichts', () => {
|
||||
delete process.env.ALERT_EMAIL;
|
||||
reportError('Test', new Error('kaputt'));
|
||||
expect(sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('meldet gleiche Fehler höchstens einmal pro Stunde', () => {
|
||||
process.env.ALERT_EMAIL = 'betreuung@example.org';
|
||||
reportError('GET /x', new Error('Datenbank weg'));
|
||||
reportError('GET /x', new Error('Datenbank weg'));
|
||||
reportError('GET /y', new Error('Anderer Fehler'));
|
||||
expect(sent.map((m) => m.subject)).toEqual([expect.stringContaining('Datenbank weg'), expect.stringContaining('Anderer Fehler')]);
|
||||
expect(sent[0].to).toBe('betreuung@example.org');
|
||||
expect(sent[0].text).toContain('Version:');
|
||||
});
|
||||
|
||||
it('begrenzt auf 20 Mails am Tag', () => {
|
||||
process.env.ALERT_EMAIL = 'betreuung@example.org';
|
||||
for (let i = 0; i < 40; i++) reportError('Schleife', new Error(`Fehler ${i}`));
|
||||
expect(sent.length).toBeLessThanOrEqual(20);
|
||||
});
|
||||
});
|
||||
53
src/lib/server/monitor.ts
Normal file
53
src/lib/server/monitor.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { getSettings } from './settings';
|
||||
import { mailConfigured, sendMail } from './mail';
|
||||
import { VERSION } from '$lib/version';
|
||||
|
||||
/**
|
||||
* Fehler melden: immer ins Log, zusätzlich per E-Mail an ALERT_EMAIL (Betreuer der
|
||||
* Installation). Gleiche Fehler höchstens einmal pro Stunde, insgesamt höchstens
|
||||
* 20 Mails am Tag – ein Fehler in einer Schleife darf kein Postfach fluten.
|
||||
*/
|
||||
|
||||
const HOUR = 3600e3;
|
||||
const MAX_PER_DAY = 20;
|
||||
const lastSent = new Map<string, number>();
|
||||
let day = '';
|
||||
let sentToday = 0;
|
||||
|
||||
export const startedAt = Date.now();
|
||||
|
||||
export function reportError(where: string, error: unknown) {
|
||||
const err = error instanceof Error ? error : new Error(String(error));
|
||||
console.error(`[fehler] ${where}:`, err);
|
||||
|
||||
const to = process.env.ALERT_EMAIL;
|
||||
if (!to || !mailConfigured()) return;
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
if (today !== day) {
|
||||
day = today;
|
||||
sentToday = 0;
|
||||
}
|
||||
const key = `${where}|${err.message.split('\n')[0].slice(0, 200)}`;
|
||||
const now = Date.now();
|
||||
if ((lastSent.get(key) ?? 0) > now - HOUR || sentToday >= MAX_PER_DAY) return;
|
||||
lastSent.set(key, now);
|
||||
sentToday++;
|
||||
|
||||
const s = getSettings();
|
||||
const origin = process.env.ORIGIN ?? '(ORIGIN nicht gesetzt)';
|
||||
sendMail({
|
||||
to,
|
||||
subject: `[${s.appName}] Fehler: ${err.message.slice(0, 80)}`,
|
||||
text: [
|
||||
`Installation: ${s.orgName} – ${origin}`,
|
||||
`Version: ${VERSION}`,
|
||||
`Zeit: ${new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' })}`,
|
||||
`Wo: ${where}`,
|
||||
'',
|
||||
(err.stack ?? err.message).split('\n').slice(0, 15).join('\n'),
|
||||
'',
|
||||
sentToday >= MAX_PER_DAY ? 'Tageslimit erreicht – weitere Fehler heute nur noch im Server-Log.' : 'Gleiche Fehler werden höchstens einmal pro Stunde gemeldet.'
|
||||
].join('\n')
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { reportError } from './monitor';
|
||||
import webpush from 'web-push';
|
||||
import { and, asc, eq, isNull, lte } from 'drizzle-orm';
|
||||
import { db } from './db';
|
||||
|
|
@ -189,7 +190,7 @@ export async function sendClosureReminders() {
|
|||
|
||||
export function startPushScheduler() {
|
||||
const run = () =>
|
||||
Promise.all([sendDuePosts(), sendClosureReminders()]).catch((e) => console.error('[push] Fehler im Zeitplan:', e));
|
||||
Promise.all([sendDuePosts(), sendClosureReminders()]).catch((e) => reportError('Push-Zeitplan', e));
|
||||
run();
|
||||
setInterval(run, 5 * 60e3).unref();
|
||||
}
|
||||
|
|
|
|||
18
src/lib/server/sanitize.test.ts
Normal file
18
src/lib/server/sanitize.test.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { cleanHtml } from './sanitize';
|
||||
|
||||
describe('HTML bereinigen', () => {
|
||||
it('entfernt Skripte, Ereignis-Attribute und gefährliche Links', () => {
|
||||
const out = cleanHtml('<p onclick="x()">Hi</p><script>alert(1)</script><img src=x onerror="alert(1)"><a href="javascript:alert(1)">a</a>');
|
||||
expect(out).not.toMatch(/script|onclick|onerror|javascript:/i);
|
||||
expect(out).toContain('<p>Hi</p>');
|
||||
});
|
||||
|
||||
it('behält leeres alt für dekorative Bilder', () => {
|
||||
expect(cleanHtml('<img alt="" src="/uploads/a.webp">')).toContain('alt=""');
|
||||
});
|
||||
|
||||
it('öffnet externe Links sicher in neuem Tab', () => {
|
||||
expect(cleanHtml('<a href="https://example.org">x</a>')).toContain('rel="noopener noreferrer"');
|
||||
});
|
||||
});
|
||||
|
|
@ -90,7 +90,7 @@ export function setupSteps(user: { totpEnabled: boolean }): SetupStep[] {
|
|||
},
|
||||
{
|
||||
key: 'ai',
|
||||
label: 'Leichte Sprache per KI',
|
||||
label: 'Leichte Sprache und Übersetzungen per KI',
|
||||
hint: 'Anbieter wählen und Schlüssel eintragen.',
|
||||
href: '/admin/einstellungen#ki',
|
||||
done: s.aiEnabled,
|
||||
|
|
|
|||
30
src/lib/server/stats.test.ts
Normal file
30
src/lib/server/stats.test.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { db } from './db';
|
||||
import { posts } from './db/schema';
|
||||
import { countView, normalizePath, statsReport } from './stats';
|
||||
|
||||
describe('Anonyme Aufrufzahlen', () => {
|
||||
it('zählt nur echte Seiten der App', () => {
|
||||
db.insert(posts).values({ title: 'Sommerfest', slug: 'sommerfest', content: '' }).run();
|
||||
expect(normalizePath('/')).toBe('/');
|
||||
expect(normalizePath('/speiseplan?woche=2026-10-05')).toBe('/speiseplan');
|
||||
expect(normalizePath('/meldungen/sommerfest/')).toBe('/meldungen/sommerfest');
|
||||
expect(normalizePath('/meldungen/gibt-es-nicht')).toBeNull();
|
||||
expect(normalizePath('/admin')).toBeNull();
|
||||
expect(normalizePath('/<script>')).toBeNull();
|
||||
});
|
||||
|
||||
it('fasst Aufrufe pro Tag zusammen und wertet aus', () => {
|
||||
countView('/meldungen/sommerfest', 'web', 'normal');
|
||||
countView('/meldungen/sommerfest', 'web', 'normal');
|
||||
countView('/meldungen/sommerfest', 'app', 'tr');
|
||||
countView('/', 'web', 'leicht');
|
||||
countView('/', 'web', 'unsinn!');
|
||||
const r = statsReport(7);
|
||||
expect(r.total).toBe(5);
|
||||
expect(r.app).toBe(1);
|
||||
expect(r.top[0]).toMatchObject({ path: '/meldungen/sommerfest', title: 'Sommerfest', n: 3 });
|
||||
expect(r.variants.map((v) => v.k).sort()).toEqual(['leicht', 'tr']);
|
||||
expect(r.series).toHaveLength(7);
|
||||
});
|
||||
});
|
||||
108
src/lib/server/stats.ts
Normal file
108
src/lib/server/stats.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { and, desc, eq, gte, lt, sql } from 'drizzle-orm';
|
||||
import { db } from './db';
|
||||
import { pageViews, pages, posts } from './db/schema';
|
||||
import { addDays, today } from '$lib/dates';
|
||||
|
||||
/**
|
||||
* Anonyme Aufrufzahlen: nur Tag, Seite, Web/App und Sprachfassung werden gezählt.
|
||||
* Keine Cookies, keine IP-Adressen, keine Geräte-Kennungen.
|
||||
*/
|
||||
|
||||
const KEEP_DAYS = 400;
|
||||
|
||||
/** Feste Bereiche der App mit Namen für die Auswertung */
|
||||
const FIXED: Record<string, string> = {
|
||||
'/': 'Startseite',
|
||||
'/meldungen': 'Alle Meldungen',
|
||||
'/termine': 'Termine',
|
||||
'/speiseplan': 'Speiseplan',
|
||||
'/kontakte': 'Ansprechpartner',
|
||||
'/kontakt': 'Kontakt',
|
||||
'/suche': 'Suche',
|
||||
'/merkliste': 'Merkliste',
|
||||
'/einstellungen': 'Einstellungen',
|
||||
'/barrierefreiheit': 'Barrierefreiheit',
|
||||
'/impressum': 'Impressum',
|
||||
'/datenschutz': 'Datenschutz'
|
||||
};
|
||||
|
||||
const VARIANT = /^(normal|leicht|[a-z]{2})$/;
|
||||
|
||||
/** Nur echte Seiten der App zählen – alles andere wird verworfen */
|
||||
export function normalizePath(raw: string): string | null {
|
||||
const path = raw.split(/[?#]/)[0].replace(/\/+$/, '') || '/';
|
||||
if (path in FIXED) return path;
|
||||
const m = path.match(/^\/(meldungen|s)\/([a-z0-9-]{1,100})$/);
|
||||
if (!m) return null;
|
||||
const table = m[1] === 'meldungen' ? posts : pages;
|
||||
return db.select({ id: table.id }).from(table).where(eq(table.slug, m[2])).get() ? path : null;
|
||||
}
|
||||
|
||||
export function countView(path: string, client: 'web' | 'app', variant: string) {
|
||||
const v = VARIANT.test(variant) ? variant : 'normal';
|
||||
db.insert(pageViews)
|
||||
.values({ day: today(), path, client, variant: v, views: 1 })
|
||||
.onConflictDoUpdate({
|
||||
target: [pageViews.day, pageViews.path, pageViews.client, pageViews.variant],
|
||||
set: { views: sql`${pageViews.views} + 1` }
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
export function purgeOldPageViews() {
|
||||
db.delete(pageViews).where(lt(pageViews.day, addDays(today(), -KEEP_DAYS))).run();
|
||||
}
|
||||
|
||||
/** Auswertung für die Redaktion */
|
||||
export function statsReport(days: number) {
|
||||
const from = addDays(today(), -(days - 1));
|
||||
const since = gte(pageViews.day, from);
|
||||
const sum = sql<number>`sum(${pageViews.views})`;
|
||||
|
||||
const daily = new Map(
|
||||
db.select({ day: pageViews.day, n: sum }).from(pageViews).where(since).groupBy(pageViews.day).all().map((r) => [r.day, r.n])
|
||||
);
|
||||
const series = Array.from({ length: days }, (_, i) => {
|
||||
const day = addDays(from, i);
|
||||
return { day, views: daily.get(day) ?? 0 };
|
||||
});
|
||||
|
||||
const byClient = Object.fromEntries(
|
||||
db.select({ k: pageViews.client, n: sum }).from(pageViews).where(since).groupBy(pageViews.client).all().map((r) => [r.k, r.n])
|
||||
) as Record<string, number>;
|
||||
const byVariant = db
|
||||
.select({ k: pageViews.variant, n: sum })
|
||||
.from(pageViews)
|
||||
.where(and(since, sql`${pageViews.variant} <> 'normal'`))
|
||||
.groupBy(pageViews.variant)
|
||||
.orderBy(desc(sum))
|
||||
.all();
|
||||
|
||||
const top = db
|
||||
.select({ path: pageViews.path, n: sum })
|
||||
.from(pageViews)
|
||||
.where(since)
|
||||
.groupBy(pageViews.path)
|
||||
.orderBy(desc(sum))
|
||||
.limit(15)
|
||||
.all()
|
||||
.map((r) => ({ ...r, title: titleOf(r.path) }));
|
||||
|
||||
return {
|
||||
from,
|
||||
total: series.reduce((a, d) => a + d.views, 0),
|
||||
series,
|
||||
app: byClient.app ?? 0,
|
||||
web: byClient.web ?? 0,
|
||||
variants: byVariant,
|
||||
top
|
||||
};
|
||||
}
|
||||
|
||||
function titleOf(path: string): string {
|
||||
if (path in FIXED) return FIXED[path];
|
||||
const [, kind, slug] = path.split('/');
|
||||
const table = kind === 'meldungen' ? posts : pages;
|
||||
const row = db.select({ title: table.title }).from(table).where(eq(table.slug, slug)).get();
|
||||
return row ? row.title : path;
|
||||
}
|
||||
34
src/lib/server/totp.test.ts
Normal file
34
src/lib/server/totp.test.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { verifyTotp } from './totp';
|
||||
|
||||
// Testvektoren aus RFC 6238 (SHA-1, Schlüssel „12345678901234567890“)
|
||||
const SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
|
||||
|
||||
describe('Zwei-Faktor-Codes (RFC 6238)', () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it.each([
|
||||
[59, '287082'],
|
||||
[1111111109, '081804'],
|
||||
[1234567890, '005924'],
|
||||
[2000000000, '279037']
|
||||
])('Zeit %i → Code %s', (t, codeStr) => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(t * 1000);
|
||||
expect(verifyTotp(SECRET, codeStr, t)).toBe(true);
|
||||
});
|
||||
|
||||
it('akzeptiert jeden Code nur einmal', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(59_000);
|
||||
expect(verifyTotp(SECRET, '287082', 4711)).toBe(true);
|
||||
expect(verifyTotp(SECRET, '287082', 4711)).toBe(false);
|
||||
});
|
||||
|
||||
it('lehnt falsche und kaputte Eingaben ab', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(59_000);
|
||||
expect(verifyTotp(SECRET, '000000', 1)).toBe(false);
|
||||
expect(verifyTotp(SECRET, 'abc', 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
34
src/lib/server/translate.test.ts
Normal file
34
src/lib/server/translate.test.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { db } from './db';
|
||||
import { translations } from './db/schema';
|
||||
import { saveSettings } from './settings';
|
||||
import { applyTranslation, hashOf } from './translate';
|
||||
|
||||
const post = { id: 1, title: 'Sommerfest', teaser: 'Danke!', content: '<p>Es war schön.</p>', contentEasy: '<p>Leicht</p>', contentEasyAuto: '', easyAutoPending: false };
|
||||
|
||||
describe('Übersetzungen für Leser', () => {
|
||||
it('bleibt deutsch, solange die Sprache nicht eingeschaltet ist', () => {
|
||||
expect(applyTranslation('post', post, 'tr')).toEqual({ item: post, translation: null });
|
||||
saveSettings({ aiEnabled: true, aiProvider: 'ollama', aiModel: 'llama3.2', aiLanguages: ['tr'] });
|
||||
expect(applyTranslation('post', post, 'de').translation).toBeNull();
|
||||
expect(applyTranslation('post', post, 'ar').translation).toBeNull();
|
||||
});
|
||||
|
||||
it('meldet „wird übersetzt“ und zeigt danach die gespeicherte Übersetzung', () => {
|
||||
saveSettings({ aiEnabled: true, aiProvider: 'ollama', aiModel: 'llama3.2', aiLanguages: ['tr'] });
|
||||
expect(applyTranslation('post', post, 'tr').translation).toEqual({ lang: 'tr', status: 'pending' });
|
||||
|
||||
// so speichert translate() das Ergebnis der KI
|
||||
const hash = hashOf(post, 'tr');
|
||||
db.insert(translations).values({ kind: 'post', refId: 1, lang: 'tr', hash, title: 'Yaz şenliği', teaser: '', html: '<p>Güzeldi.</p>' }).run();
|
||||
|
||||
const { item, translation } = applyTranslation('post', post, 'tr');
|
||||
expect(translation).toEqual({ lang: 'tr', status: 'ready' });
|
||||
expect(item).toMatchObject({ title: 'Yaz şenliği', teaser: 'Danke!', content: '<p>Güzeldi.</p>', contentEasy: '' });
|
||||
});
|
||||
|
||||
it('übersetzt neu, wenn sich der deutsche Text ändert', () => {
|
||||
const changed = { ...post, content: '<p>Es war sehr schön.</p>' };
|
||||
expect(applyTranslation('post', changed, 'tr').translation?.status).toBe('pending');
|
||||
});
|
||||
});
|
||||
138
src/lib/server/translate.ts
Normal file
138
src/lib/server/translate.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { and, eq, notInArray } from 'drizzle-orm';
|
||||
import { db } from './db';
|
||||
import { pages, posts, translations } from './db/schema';
|
||||
import { AiError, aiReady, currentConfig, streamText } from './ai';
|
||||
import { record } from './ratelimit';
|
||||
import { dailyUsage } from './easy-auto';
|
||||
import { cleanHtml } from './sanitize';
|
||||
import { getSettings } from './settings';
|
||||
import { LANGUAGES, isLang, type LangCode } from '$lib/languages';
|
||||
|
||||
/**
|
||||
* Automatische Übersetzung von Meldungen und Seiten in andere Sprachen (KI).
|
||||
* Übersetzt wird beim ersten Abruf; das Ergebnis gilt für alle weiteren Leser,
|
||||
* bis sich der deutsche Text ändert.
|
||||
*/
|
||||
|
||||
export type TranslateKind = 'post' | 'page';
|
||||
type Source = { id: number; title: string; teaser?: string; content: string };
|
||||
|
||||
/** Bei Änderungen an den Anweisungen erhöhen → wird nach und nach neu übersetzt */
|
||||
const PROMPT_VERSION = 1;
|
||||
const MAX_INPUT_CHARS = 60_000;
|
||||
|
||||
/** Ist die Sprache eingeschaltet und die KI bereit? */
|
||||
export const translationEnabled = (lang: string): lang is LangCode =>
|
||||
isLang(lang) && aiReady() && getSettings().aiLanguages.includes(lang);
|
||||
|
||||
/** Sprachen, die Leser wählen können */
|
||||
export const readerLanguages = () => (aiReady() ? getSettings().aiLanguages.filter(isLang) : []);
|
||||
|
||||
export const hashOf = (src: Source, lang: string) =>
|
||||
createHash('sha256').update(JSON.stringify([PROMPT_VERSION, lang, src.title, src.teaser ?? '', src.content])).digest('hex');
|
||||
|
||||
function stored(kind: TranslateKind, id: number, lang: string) {
|
||||
return db
|
||||
.select()
|
||||
.from(translations)
|
||||
.where(and(eq(translations.kind, kind), eq(translations.refId, id), eq(translations.lang, lang)))
|
||||
.get();
|
||||
}
|
||||
|
||||
export type TranslationState =
|
||||
| { status: 'ready'; lang: LangCode; title: string; teaser: string; html: string }
|
||||
| { status: 'pending'; lang: LangCode };
|
||||
|
||||
/** Zustand der Übersetzung für einen Leser (null = auf Deutsch zeigen) */
|
||||
export function translationFor(kind: TranslateKind, src: Source, lang: string): TranslationState | null {
|
||||
if (!translationEnabled(lang)) return null;
|
||||
const row = stored(kind, src.id, lang);
|
||||
if (row && row.hash === hashOf(src, lang)) return { status: 'ready', lang, title: row.title, teaser: row.teaser, html: row.html };
|
||||
return { status: 'pending', lang };
|
||||
}
|
||||
|
||||
function systemPrompt(lang: LangCode) {
|
||||
return `You translate texts from the information app of a German sheltered workshop (Werkstatt für Menschen mit Behinderung) from German into ${LANGUAGES[lang].english}.
|
||||
Readers are employees with disabilities and their relatives, many of whom have limited German.
|
||||
|
||||
Rules:
|
||||
- Translate faithfully and completely. Do not add, explain or leave out information.
|
||||
- Use clear, simple, friendly language. Short sentences are welcome.
|
||||
- Keep names of people, places, organisations, dates, times, phone numbers, e-mail addresses and URLs exactly as they are.
|
||||
- German terms without a good equivalent (for example "Werkstattrat", "Frauenbeauftragte"): translate the meaning and add the German term once in parentheses.
|
||||
- The body is HTML. Keep every tag and attribute exactly as it is and translate only the visible text. Never translate attribute values such as href or src.
|
||||
|
||||
Answer only in this exact format, without any other text and without a code block:
|
||||
<title>translated title</title>
|
||||
<teaser>translated teaser (empty if there is none)</teaser>
|
||||
<body>translated HTML</body>`;
|
||||
}
|
||||
|
||||
const inFlight = new Map<string, Promise<void>>();
|
||||
|
||||
/** Übersetzt und speichert. Läuft schon dieselbe Übersetzung, wird darauf gewartet. */
|
||||
export function translate(kind: TranslateKind, src: Source, lang: LangCode): Promise<void> {
|
||||
const key = `${kind}:${src.id}:${lang}`;
|
||||
const running = inFlight.get(key);
|
||||
if (running) return running;
|
||||
|
||||
const job = (async () => {
|
||||
if (!translationEnabled(lang)) throw new AiError('Diese Sprache ist nicht eingeschaltet.');
|
||||
const hash = hashOf(src, lang);
|
||||
if (stored(kind, src.id, lang)?.hash === hash) return;
|
||||
if (src.content.length > MAX_INPUT_CHARS) throw new AiError('Der Text ist zu lang für eine automatische Übersetzung.');
|
||||
if (dailyUsage() >= getSettings().aiDailyLimit) throw new AiError('Das Tageslimit für KI-Übertragungen ist erreicht.');
|
||||
record('ki-tag');
|
||||
|
||||
const config = currentConfig();
|
||||
let out = '';
|
||||
for await (const chunk of streamText(
|
||||
config,
|
||||
systemPrompt(lang),
|
||||
`<title>${src.title}</title>\n<teaser>${src.teaser ?? ''}</teaser>\n<body>\n${src.content}\n</body>`
|
||||
))
|
||||
out += chunk;
|
||||
|
||||
const part = (tag: string) => out.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, 'i'))?.[1].trim() ?? '';
|
||||
const plain = (s: string) => s.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
|
||||
const title = plain(part('title'));
|
||||
const html = cleanHtml(part('body'));
|
||||
if (!title || !html) throw new AiError('Die KI hat keine vollständige Übersetzung geliefert.');
|
||||
|
||||
const values = { kind, refId: src.id, lang, hash, title, teaser: plain(part('teaser')), html, model: `${config.provider}/${config.model}`, createdAt: new Date() };
|
||||
db.insert(translations)
|
||||
.values(values)
|
||||
.onConflictDoUpdate({ target: [translations.kind, translations.refId, translations.lang], set: values })
|
||||
.run();
|
||||
})().finally(() => inFlight.delete(key));
|
||||
|
||||
inFlight.set(key, job);
|
||||
return job;
|
||||
}
|
||||
|
||||
/** Übersetzungen gelöschter Meldungen und Seiten entfernen */
|
||||
export function purgeOrphanTranslations() {
|
||||
for (const [kind, table] of [['post', posts], ['page', pages]] as const) {
|
||||
const ids = db.select({ id: table.id }).from(table).all().map((r) => r.id);
|
||||
db.delete(translations)
|
||||
.where(and(eq(translations.kind, kind), ids.length ? notInArray(translations.refId, ids) : undefined))
|
||||
.run();
|
||||
}
|
||||
}
|
||||
|
||||
type Translatable = { id: number; title: string; teaser: string; content: string; contentEasy: string; contentEasyAuto: string; easyAutoPending: boolean };
|
||||
|
||||
/**
|
||||
* Für die Anzeige: ersetzt Titel, Teaser und Text durch die Übersetzung, wenn der
|
||||
* Leser eine andere Sprache gewählt hat und sie schon vorliegt.
|
||||
*/
|
||||
export function applyTranslation<T extends Translatable>(kind: TranslateKind, item: T, lang: string) {
|
||||
const state = translationFor(kind, item, lang);
|
||||
if (!state) return { item, translation: null };
|
||||
if (state.status === 'pending') return { item, translation: { lang: state.lang, status: state.status } };
|
||||
return {
|
||||
item: { ...item, title: state.title, teaser: state.teaser || item.teaser, content: state.html, contentEasy: '', contentEasyAuto: '', easyAutoPending: false },
|
||||
translation: { lang: state.lang, status: state.status }
|
||||
};
|
||||
}
|
||||
|
|
@ -96,6 +96,13 @@ export type AppSettings = {
|
|||
homeEventsCount: number;
|
||||
/** Checkliste „Erste Schritte“ im Dashboard ausgeblendet */
|
||||
setupHidden: boolean;
|
||||
/** Speiseplan: Standorte (leer = nur einer), übliche Linien, Wochenende zeigen, Hinweis */
|
||||
mealLocations: string[];
|
||||
mealLines: string[];
|
||||
mealWeekend: boolean;
|
||||
mealNote: string;
|
||||
/** Sprachen, in die Meldungen und Seiten per KI übersetzt werden (leer = aus) */
|
||||
aiLanguages: string[];
|
||||
};
|
||||
|
||||
export const DEFAULT_SETTINGS: AppSettings = {
|
||||
|
|
@ -139,6 +146,11 @@ export const DEFAULT_SETTINGS: AppSettings = {
|
|||
},
|
||||
require2faAdmins: false,
|
||||
setupHidden: false,
|
||||
mealLocations: [],
|
||||
mealLines: ['Menü 1', 'Menü 2', 'Vegetarisch'],
|
||||
mealWeekend: false,
|
||||
mealNote: 'Allergene und Zusatzstoffe: Bitte frag in der Küche nach, wenn du unsicher bist.',
|
||||
aiLanguages: [],
|
||||
aiEnabled: false,
|
||||
aiMode: 'review',
|
||||
aiProvider: 'anthropic',
|
||||
|
|
|
|||
|
|
@ -94,6 +94,8 @@ class Speech {
|
|||
#sentences: Sentence[] = [];
|
||||
#native = false;
|
||||
#run = 0;
|
||||
/** Sprache des vorgelesenen Bereichs (übersetzte Texte tragen ihr lang-Attribut) */
|
||||
#lang = 'de';
|
||||
|
||||
init() {
|
||||
this.#native = isNative();
|
||||
|
|
@ -111,6 +113,7 @@ class Speech {
|
|||
const root = document.getElementById(targetId);
|
||||
if (!root || !this.supported) return;
|
||||
this.stop();
|
||||
this.#lang = (root.querySelector('[data-uebersetzt][lang]') ?? root.closest('[lang]'))?.getAttribute('lang') || 'de';
|
||||
this.#sentences = sentencesOf(root);
|
||||
if (!this.#sentences.length) return;
|
||||
this.label = label;
|
||||
|
|
@ -128,7 +131,7 @@ class Speech {
|
|||
this.index = k;
|
||||
this.#highlight(k);
|
||||
try {
|
||||
await TextToSpeech.speak({ text: this.#sentences[k].text, lang: 'de-DE', rate: this.slow ? 0.8 : 1.0, category: 'playback' });
|
||||
await TextToSpeech.speak({ text: this.#sentences[k].text, lang: this.#bcp47(), rate: this.slow ? 0.8 : 1.0, category: 'playback' });
|
||||
} catch {
|
||||
if (run === this.#run) this.stop();
|
||||
return;
|
||||
|
|
@ -145,11 +148,11 @@ class Speech {
|
|||
}
|
||||
speechSynthesis.cancel();
|
||||
// Stimmen bevorzugen, die auf dem Gerät arbeiten – Online-Stimmen schicken den Text an den Browser-Anbieter
|
||||
const german = speechSynthesis.getVoices().filter((v) => v.lang.startsWith('de'));
|
||||
const voice = german.find((v) => v.localService) ?? german[0];
|
||||
const matching = speechSynthesis.getVoices().filter((v) => v.lang.toLowerCase().startsWith(this.#lang));
|
||||
const voice = matching.find((v) => v.localService) ?? matching[0];
|
||||
for (let k = i; k < this.#sentences.length; k++) {
|
||||
const u = new SpeechSynthesisUtterance(this.#sentences[k].text);
|
||||
u.lang = 'de-DE';
|
||||
u.lang = this.#bcp47();
|
||||
u.rate = this.slow ? 0.75 : 0.95;
|
||||
if (voice) u.voice = voice;
|
||||
u.onstart = () => {
|
||||
|
|
@ -162,6 +165,10 @@ class Speech {
|
|||
}
|
||||
}
|
||||
|
||||
#bcp47() {
|
||||
return this.#lang === 'de' ? 'de-DE' : this.#lang;
|
||||
}
|
||||
|
||||
#highlight(k: number) {
|
||||
const range = this.#sentences[k]?.range;
|
||||
if (!range) return;
|
||||
|
|
|
|||
31
src/lib/theme.test.ts
Normal file
31
src/lib/theme.test.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { COLOR_PAIRS, DEFAULT_THEME, cleanTheme } from './theme';
|
||||
import { checkBrandColors, contrast, darkenForContrast, MIN_CONTRAST } from './color';
|
||||
|
||||
describe('Farben', () => {
|
||||
it('berechnet Kontraste nach WCAG', () => {
|
||||
expect(contrast('#000000', '#ffffff')).toBeCloseTo(21, 1);
|
||||
expect(contrast('#777777', '#ffffff')).toBeCloseTo(4.48, 1);
|
||||
});
|
||||
|
||||
it.each(COLOR_PAIRS)('Farbpaar %s / %s ist mit weißer Schrift lesbar', (brand, accent) => {
|
||||
expect(checkBrandColors(brand, accent)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(['#f4a261', '#ffff00', '#9be7ff', '#e63946'])('„Farbe anpassen“ macht %s lesbar und behält den Farbton', (hex) => {
|
||||
const fixed = darkenForContrast(hex);
|
||||
expect(contrast(fixed, '#ffffff')).toBeGreaterThanOrEqual(MIN_CONTRAST);
|
||||
expect(fixed).not.toBe(hex);
|
||||
});
|
||||
|
||||
it('lässt gute Farben unverändert', () => {
|
||||
expect(darkenForContrast('#2e2672')).toBe('#2e2672');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Erscheinungsbild', () => {
|
||||
it('verwirft unbekannte Werte', () => {
|
||||
expect(cleanTheme(undefined)).toEqual(DEFAULT_THEME);
|
||||
expect(cleanTheme({ preset: 'klar', font: 'comic-sans', radius: 'eckig' })).toEqual({ preset: 'klar', font: DEFAULT_THEME.font, radius: 'eckig' });
|
||||
});
|
||||
});
|
||||
|
|
@ -59,3 +59,18 @@ export const TILE_GRID: Record<Preset, string> = {
|
|||
klar: 'grid sm:grid-cols-2 lg:grid-cols-3 gap-3',
|
||||
kacheln: 'grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3'
|
||||
};
|
||||
|
||||
/**
|
||||
* Fertige Farbpaare aus Hauptfarbe (Schrift, Buttons) und Akzent (Kreis, Hervorhebungen).
|
||||
* Alle erreichen mit weißer Schrift mindestens 4,5:1 (wird in theme.test.ts geprüft).
|
||||
*/
|
||||
export const COLOR_PAIRS = [
|
||||
['#2e2672', '#85357c'],
|
||||
['#0f4c5c', '#b3470f'],
|
||||
['#1d3557', '#c0262f'],
|
||||
['#264027', '#8a5a14'],
|
||||
['#3a2e39', '#13705f'],
|
||||
['#12355b', '#8f6400'],
|
||||
['#4a1d5c', '#b0306e'],
|
||||
['#1f2a44', '#2f6f4f']
|
||||
] as const;
|
||||
|
|
|
|||
2
src/lib/version.ts
Normal file
2
src/lib/version.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/** Version dieser Installation (aus package.json oder APP_VERSION beim Bauen) */
|
||||
export const VERSION: string = __APP_VERSION__;
|
||||
|
|
@ -1,10 +1,13 @@
|
|||
import { childPages } from '$lib/server/content';
|
||||
import { getSettings } from '$lib/server/settings';
|
||||
import { readerLanguages } from '$lib/server/translate';
|
||||
|
||||
export const load = () => {
|
||||
const s = getSettings();
|
||||
return {
|
||||
menuPages: childPages(null),
|
||||
website: s.website
|
||||
website: s.website,
|
||||
/** Sprachen, in die Leser Meldungen und Seiten übersetzen lassen können */
|
||||
languages: readerLanguages()
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -12,12 +12,25 @@
|
|||
import { speech } from '$lib/speech.svelte';
|
||||
import MenuSheet from '$lib/components/MenuSheet.svelte';
|
||||
import { favorites } from '$lib/favorites.svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { afterNavigate, goto } from '$app/navigation';
|
||||
import { prefs } from '$lib/prefs.svelte';
|
||||
import { initNative } from '$lib/native';
|
||||
|
||||
let { data, children } = $props();
|
||||
let menuOpen = $state(false);
|
||||
|
||||
// Anonyme Aufrufzahl (ohne Cookies und Kennungen) – nur Seite und Sprachfassung
|
||||
afterNavigate(({ to }) => {
|
||||
if (!to) return;
|
||||
const variant = prefs.current.lang !== 'de' ? prefs.current.lang : prefs.current.easy ? 'leicht' : 'normal';
|
||||
fetch('/api/gelesen', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ path: to.url.pathname, variant }),
|
||||
keepalive: true
|
||||
}).catch(() => {});
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
favorites.load();
|
||||
initNative((path) => goto(path));
|
||||
|
|
@ -47,17 +60,17 @@
|
|||
<div class="min-h-dvh flex flex-col">
|
||||
<header class="sticky top-0 z-30 safe-top bg-bg/95 backdrop-blur-md border-b border-line">
|
||||
<div class="mx-auto max-w-6xl px-4 h-16 lg:h-20 flex items-center gap-2">
|
||||
<a href="/" class="flex items-center gap-3 min-w-0 mr-auto" aria-label="{data.brand.appName} – Startseite">
|
||||
<a href="/" class="flex items-center gap-3 min-w-0 mr-auto">
|
||||
{#if data.brand.logo}
|
||||
<img src={data.brand.logo.thumb} alt="" class="h-10 lg:h-12 w-auto max-w-40 object-contain" />
|
||||
{:else}
|
||||
<span class="grid place-items-center size-10 rounded-full bg-brand text-on-brand font-bold text-lg">
|
||||
<span class="grid place-items-center size-10 rounded-full bg-brand text-on-brand font-bold text-lg" aria-hidden="true">
|
||||
{data.brand.appName.slice(0, 1)}
|
||||
</span>
|
||||
{/if}
|
||||
<span class="min-w-0 leading-tight">
|
||||
<span class="block font-bold text-[1.05rem] text-brand-ink truncate">{data.brand.appName}</span>
|
||||
<span class="block text-xs text-ink-3 truncate">{data.brand.orgName}</span>
|
||||
<span class="block text-xs text-ink-3 truncate">{data.brand.orgName}<span class="sr-only"> – zur Startseite</span></span>
|
||||
</span>
|
||||
</a>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { db } from '$lib/server/db';
|
|||
import { posts, tiles } from '$lib/server/db/schema';
|
||||
import { getMedia, listPosts, upcomingEvents } from '$lib/server/content';
|
||||
import { getSettings } from '$lib/server/settings';
|
||||
import { nextMealDay } from '$lib/server/meals';
|
||||
import { addDays, eventWhen, formatLong, today } from '$lib/dates';
|
||||
|
||||
/** Hinweis-Fahne auf dem Titelbild: anstehende Schließzeit hat Vorrang, sonst die angeheftete Meldung. */
|
||||
|
|
@ -33,6 +34,11 @@ export const load = () => {
|
|||
highlight: highlight(),
|
||||
tiles: db.select().from(tiles).orderBy(asc(tiles.sortOrder), asc(tiles.id)).all(),
|
||||
posts: listPosts({ limit: s.homeNewsCount }).items,
|
||||
events: upcomingEvents({ limit: s.homeEventsCount })
|
||||
events: upcomingEvents({ limit: s.homeEventsCount }),
|
||||
// Essen heute oder am nächsten Tag mit Speiseplan (höchstens 3 Gerichte)
|
||||
meals: (() => {
|
||||
const next = nextMealDay(today());
|
||||
return next ? { date: next.date, isToday: next.date === today(), items: next.meals.slice(0, 3), more: Math.max(0, next.meals.length - 3) } : null;
|
||||
})()
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@
|
|||
import { TILE_GRID } from '$lib/theme';
|
||||
import Tile from '$lib/components/Tile.svelte';
|
||||
import PostCard from '$lib/components/PostCard.svelte';
|
||||
import { dayOfMonth, eventWhen, monthAbbr, weekday } from '$lib/dates';
|
||||
import MealCard from '$lib/components/MealCard.svelte';
|
||||
import Utensils from '@lucide/svelte/icons/utensils';
|
||||
import { dayOfMonth, eventWhen, formatLong, monthAbbr, weekday } from '$lib/dates';
|
||||
|
||||
let { data } = $props();
|
||||
const preset = $derived(data.brand.theme.preset);
|
||||
|
|
@ -64,6 +66,26 @@
|
|||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- Essen -->
|
||||
{#if data.meals}
|
||||
<section aria-labelledby="essen" class="space-y-5">
|
||||
<div class="flex items-end justify-between gap-4">
|
||||
<div class="space-y-2">
|
||||
<p class="eyebrow eyebrow-rule">Speiseplan</p>
|
||||
<h2 id="essen" class="text-2xl sm:text-3xl text-brand-ink">{data.meals.isToday ? 'Heute gibt es' : `Am ${formatLong(data.meals.date).split(',')[0]} gibt es`}</h2>
|
||||
</div>
|
||||
<a href="/speiseplan" class="btn btn-soft btn-sm shrink-0">Ganze Woche <ArrowRight class="size-4" /></a>
|
||||
</div>
|
||||
<div class="card p-5 sm:p-6 flex gap-5">
|
||||
<span class="hidden sm:grid place-items-center size-12 rounded-full bg-brand-soft text-brand-ink shrink-0" aria-hidden="true"><Utensils class="size-6" /></span>
|
||||
<ul class="flex-1 grid md:grid-cols-3 gap-5">
|
||||
{#each data.meals.items as m (m.id)}<li><MealCard meal={m} /></li>{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{#if data.meals.more}<p class="hint">und {data.meals.more} weitere – siehe Speiseplan.</p>{/if}
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- Neuigkeiten -->
|
||||
<section aria-labelledby="neu" class="space-y-5">
|
||||
<div class="flex items-end justify-between gap-4">
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { error } from '@sveltejs/kit';
|
||||
import { getPost } from '$lib/server/content';
|
||||
import { applyTranslation } from '$lib/server/translate';
|
||||
|
||||
export const load = ({ params }) => {
|
||||
const post = getPost(params.slug);
|
||||
if (!post) error(404, 'Diese Meldung gibt es nicht (mehr).');
|
||||
return { post };
|
||||
export const load = ({ params, locals }) => {
|
||||
const found = getPost(params.slug);
|
||||
if (!found) error(404, 'Diese Meldung gibt es nicht (mehr).');
|
||||
const { item: post, translation } = applyTranslation('post', found, locals.prefs.lang);
|
||||
return { post, translation };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
<script lang="ts">
|
||||
import { LANGUAGES, isLang } from '$lib/languages';
|
||||
import BackLink from '$lib/components/BackLink.svelte';
|
||||
import ArticleActions from '$lib/components/ArticleActions.svelte';
|
||||
import RichContent from '$lib/components/RichContent.svelte';
|
||||
|
|
@ -9,6 +10,8 @@
|
|||
import { formatLong } from '$lib/dates';
|
||||
|
||||
let { data } = $props();
|
||||
// Übersetzte Texte tragen ihre Sprache – für Screenreader, Vorlesen und Schreibrichtung
|
||||
const translated = $derived(data.translation?.status === 'ready' && isLang(data.translation.lang) ? { lang: data.translation.lang } : null);
|
||||
const post = $derived(data.post);
|
||||
</script>
|
||||
|
||||
|
|
@ -23,8 +26,8 @@
|
|||
|
||||
<header class="space-y-3 mb-6">
|
||||
<p class="eyebrow eyebrow-rule !text-accent-ink">{formatLong(post.publishedAt)}</p>
|
||||
<h1 class="text-3xl sm:text-4xl text-brand-ink">{post.title}</h1>
|
||||
{#if post.teaser}<p class="text-lg text-ink-2">{post.teaser}</p>{/if}
|
||||
<h1 class="text-3xl sm:text-4xl text-brand-ink" lang={translated?.lang} dir={translated ? LANGUAGES[translated.lang].dir : undefined}>{post.title}</h1>
|
||||
{#if post.teaser}<p class="text-lg text-ink-2" lang={translated?.lang} dir={translated ? LANGUAGES[translated.lang].dir : undefined}>{post.teaser}</p>{/if}
|
||||
<ArticleActions target="vorlesen" favorite={{ href: `/meldungen/${post.slug}`, title: post.title, kind: 'post' }} />
|
||||
</header>
|
||||
|
||||
|
|
@ -39,7 +42,7 @@
|
|||
{/if}
|
||||
|
||||
<div class="space-y-8">
|
||||
<RichContent content={post.content} contentEasy={post.contentEasy} contentEasyAuto={post.contentEasyAuto} easyAutoPending={post.easyAutoPending} kind="post" slug={post.slug} />
|
||||
<RichContent content={post.content} contentEasy={post.contentEasy} contentEasyAuto={post.contentEasyAuto} easyAutoPending={post.easyAutoPending} kind="post" slug={post.slug} translation={data.translation} />
|
||||
{#if post.videoUrl}<VideoEmbed url={post.videoUrl} />{/if}
|
||||
<Gallery images={post.gallery} />
|
||||
<Attachments items={post.attachments} />
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { error } from '@sveltejs/kit';
|
||||
import { getPage } from '$lib/server/content';
|
||||
import { applyTranslation } from '$lib/server/translate';
|
||||
|
||||
export const load = ({ params }) => {
|
||||
const page = getPage(params.slug);
|
||||
if (!page) error(404, 'Diese Seite gibt es nicht (mehr).');
|
||||
return { page };
|
||||
export const load = ({ params, locals }) => {
|
||||
const found = getPage(params.slug);
|
||||
if (!found) error(404, 'Diese Seite gibt es nicht (mehr).');
|
||||
const { item: page, translation } = applyTranslation('page', found, locals.prefs.lang);
|
||||
return { page, translation };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
<script lang="ts">
|
||||
import { LANGUAGES, isLang } from '$lib/languages';
|
||||
import Tile from '$lib/components/Tile.svelte';
|
||||
import { TILE_GRID } from '$lib/theme';
|
||||
import ArticleActions from '$lib/components/ArticleActions.svelte';
|
||||
|
|
@ -7,6 +8,8 @@
|
|||
import ContactCard from '$lib/components/ContactCard.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
// Übersetzte Texte tragen ihre Sprache – für Screenreader, Vorlesen und Schreibrichtung
|
||||
const translated = $derived(data.translation?.status === 'ready' && isLang(data.translation.lang) ? { lang: data.translation.lang } : null);
|
||||
const p = $derived(data.page);
|
||||
const hasText = $derived(!!(p.content || p.contentEasy));
|
||||
</script>
|
||||
|
|
@ -27,8 +30,8 @@
|
|||
{/each}
|
||||
</span>
|
||||
</nav>
|
||||
<h1 class="text-3xl sm:text-4xl text-brand-ink">{p.title}</h1>
|
||||
{#if p.teaser}<p class="text-lg text-ink-2">{p.teaser}</p>{/if}
|
||||
<h1 class="text-3xl sm:text-4xl text-brand-ink" lang={translated?.lang} dir={translated ? LANGUAGES[translated.lang].dir : undefined}>{p.title}</h1>
|
||||
{#if p.teaser}<p class="text-lg text-ink-2" lang={translated?.lang} dir={translated ? LANGUAGES[translated.lang].dir : undefined}>{p.teaser}</p>{/if}
|
||||
{#if hasText}
|
||||
<div class="pt-2">
|
||||
<ArticleActions target="vorlesen" favorite={{ href: `/s/${p.slug}`, title: p.title, kind: 'page' }} />
|
||||
|
|
@ -41,7 +44,7 @@
|
|||
{/if}
|
||||
|
||||
<div class="space-y-8">
|
||||
<RichContent content={p.content} contentEasy={p.contentEasy} contentEasyAuto={p.contentEasyAuto} easyAutoPending={p.easyAutoPending} kind="page" slug={p.slug} />
|
||||
<RichContent content={p.content} contentEasy={p.contentEasy} contentEasyAuto={p.contentEasyAuto} easyAutoPending={p.easyAutoPending} kind="page" slug={p.slug} translation={data.translation} />
|
||||
|
||||
{#if p.children.length}
|
||||
<section class="space-y-3">
|
||||
|
|
|
|||
27
src/routes/(app)/speiseplan/+page.server.ts
Normal file
27
src/routes/(app)/speiseplan/+page.server.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { addDays, today } from '$lib/dates';
|
||||
import { isoWeek, mondayOf, weekDays } from '$lib/meals';
|
||||
import { mealsBetween } from '$lib/server/meals';
|
||||
import { getSettings } from '$lib/server/settings';
|
||||
|
||||
export const load = ({ url }) => {
|
||||
const s = getSettings();
|
||||
const now = today();
|
||||
const wanted = url.searchParams.get('woche') ?? '';
|
||||
// Am Wochenende ohne Wochenend-Essen gleich die nächste Woche zeigen
|
||||
const dow = (new Date(`${now}T12:00:00Z`).getUTCDay() + 6) % 7;
|
||||
const fallback = !s.mealWeekend && dow >= 5 ? addDays(mondayOf(now), 7) : mondayOf(now);
|
||||
const monday = /^\d{4}-\d{2}-\d{2}$/.test(wanted) ? mondayOf(wanted) : fallback;
|
||||
const location = s.mealLocations.includes(url.searchParams.get('standort') ?? '') ? url.searchParams.get('standort')! : '';
|
||||
const days = weekDays(monday, s.mealWeekend ? 7 : 5);
|
||||
const byDay = mealsBetween(days[0], days.at(-1)!, location);
|
||||
return {
|
||||
today: now,
|
||||
monday,
|
||||
week: isoWeek(monday),
|
||||
thisMonday: fallback,
|
||||
days: days.map((date) => ({ date, meals: byDay[date] ?? [] })),
|
||||
locations: s.mealLocations,
|
||||
location,
|
||||
note: s.mealNote
|
||||
};
|
||||
};
|
||||
95
src/routes/(app)/speiseplan/+page.svelte
Normal file
95
src/routes/(app)/speiseplan/+page.svelte
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
|
||||
import ChevronRight from '@lucide/svelte/icons/chevron-right';
|
||||
import Utensils from '@lucide/svelte/icons/utensils';
|
||||
import MealCard from '$lib/components/MealCard.svelte';
|
||||
import ArticleActions from '$lib/components/ArticleActions.svelte';
|
||||
import { addDays, formatDate, formatLong } from '$lib/dates';
|
||||
import { ALLERGENS } from '$lib/meals';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
const query = (monday: string) => {
|
||||
const q = new URLSearchParams();
|
||||
if (monday !== data.thisMonday) q.set('woche', monday);
|
||||
if (data.location) q.set('standort', data.location);
|
||||
return q.size ? `?${q}` : '/speiseplan';
|
||||
};
|
||||
const range = $derived(`${formatDate(data.days[0].date).replace(/ \d{4}$/, '')} bis ${formatDate(data.days.at(-1)!.date)}`);
|
||||
const empty = $derived(data.days.every((d) => !d.meals.length));
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Speiseplan · {data.brand.appName}</title></svelte:head>
|
||||
|
||||
<div class="max-w-4xl mx-auto">
|
||||
<div class="flex flex-wrap items-end justify-between gap-3 mb-2">
|
||||
<h1 class="text-3xl sm:text-4xl text-brand-ink">Speiseplan</h1>
|
||||
{#if data.locations.length}
|
||||
<form method="GET" class="flex items-center gap-2">
|
||||
{#if data.monday !== data.thisMonday}<input type="hidden" name="woche" value={data.monday} />{/if}
|
||||
<label for="standort" class="font-semibold text-sm">Standort</label>
|
||||
<select
|
||||
id="standort"
|
||||
name="standort"
|
||||
class="field min-h-10 py-1 w-auto"
|
||||
value={data.location}
|
||||
onchange={(e) => goto(`?${new URLSearchParams({ ...(data.monday !== data.thisMonday ? { woche: data.monday } : {}), ...(e.currentTarget.value ? { standort: e.currentTarget.value } : {}) })}`, { keepFocus: true, noScroll: true })}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
{#each data.locations as l (l)}<option value={l}>{l}</option>{/each}
|
||||
</select>
|
||||
<noscript><button class="btn btn-soft btn-sm">Zeigen</button></noscript>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1 mb-3">
|
||||
<a href={query(addDays(data.monday, -7))} class="btn btn-ghost btn-icon btn-sm shrink-0" aria-label="Vorherige Woche" data-sveltekit-noscroll><ChevronLeft class="size-5" /></a>
|
||||
<h2 class="flex-1 text-center font-bold text-lg leading-tight" aria-live="polite">KW {data.week} <span class="block sm:inline font-semibold text-ink-2 text-base">{range}</span></h2>
|
||||
<a href={query(addDays(data.monday, 7))} class="btn btn-ghost btn-icon btn-sm shrink-0" aria-label="Nächste Woche" data-sveltekit-noscroll><ChevronRight class="size-5" /></a>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 mb-6">
|
||||
{#if data.monday !== data.thisMonday}<a href={query(data.thisMonday)} class="btn btn-soft btn-sm" data-sveltekit-noscroll>Diese Woche</a>{:else}<span></span>{/if}
|
||||
<ArticleActions target="speiseplan" />
|
||||
</div>
|
||||
|
||||
<div id="speiseplan">
|
||||
{#if empty}
|
||||
<div class="card p-8 text-center space-y-2">
|
||||
<Utensils class="size-8 mx-auto text-ink-3" aria-hidden="true" />
|
||||
<p class="font-bold">Für diese Woche gibt es noch keinen Speiseplan.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<ol class="space-y-4">
|
||||
{#each data.days as d (d.date)}
|
||||
{@const isToday = d.date === data.today}
|
||||
<li class="card p-5 sm:p-6 grid sm:grid-cols-[11rem_1fr] gap-x-6 gap-y-3 {isToday ? 'ring-2 ring-brand' : ''}" aria-current={isToday ? 'date' : undefined}>
|
||||
<h3 class="leading-tight">
|
||||
<span class="block font-bold text-lg text-brand-ink">{formatLong(d.date).split(',')[0]}</span>
|
||||
<span class="text-sm text-ink-2">{formatDate(d.date)}</span>
|
||||
{#if isToday}<span class="mt-1.5 inline-block rounded-pill bg-brand text-on-brand px-2.5 py-0.5 text-xs font-bold">Heute</span>{/if}
|
||||
</h3>
|
||||
{#if d.meals.length}
|
||||
<ul class="grid md:grid-cols-2 gap-5">
|
||||
{#each d.meals as m (m.id)}<li><MealCard meal={m} showLocation={!data.location && data.locations.length > 0} /></li>{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="text-ink-2 self-center">Kein Essen eingetragen.</p>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<details class="card p-5 mt-6">
|
||||
<summary class="font-bold cursor-pointer">Was bedeuten die Buchstaben?</summary>
|
||||
<dl class="mt-3 grid sm:grid-cols-2 gap-x-6 gap-y-1">
|
||||
{#each Object.entries(ALLERGENS) as [code, name] (code)}
|
||||
<div class="flex gap-2"><dt class="font-bold w-5">{code}</dt><dd>{name}</dd></div>
|
||||
{/each}
|
||||
</dl>
|
||||
</details>
|
||||
{#if data.note}<p class="hint mt-4">{data.note}</p>{/if}
|
||||
</div>
|
||||
|
|
@ -1,15 +1,18 @@
|
|||
<script lang="ts">
|
||||
import { VERSION } from '$lib/version';
|
||||
import { page } from '$app/state';
|
||||
import LayoutDashboard from '@lucide/svelte/icons/layout-dashboard';
|
||||
import CalendarRange from '@lucide/svelte/icons/calendar-range';
|
||||
import Newspaper from '@lucide/svelte/icons/newspaper';
|
||||
import FolderTree from '@lucide/svelte/icons/folder-tree';
|
||||
import CalendarDays from '@lucide/svelte/icons/calendar-days';
|
||||
import Utensils from '@lucide/svelte/icons/utensils';
|
||||
import LayoutGrid from '@lucide/svelte/icons/layout-grid';
|
||||
import Users from '@lucide/svelte/icons/users';
|
||||
import Image from '@lucide/svelte/icons/image';
|
||||
import Inbox from '@lucide/svelte/icons/inbox';
|
||||
import BellRing from '@lucide/svelte/icons/bell-ring';
|
||||
import ChartColumn from '@lucide/svelte/icons/chart-column';
|
||||
import UserCog from '@lucide/svelte/icons/user-cog';
|
||||
import Settings from '@lucide/svelte/icons/settings';
|
||||
import LogOut from '@lucide/svelte/icons/log-out';
|
||||
|
|
@ -37,6 +40,7 @@
|
|||
{ href: '/admin/meldungen', label: 'Meldungen', icon: Newspaper },
|
||||
{ href: '/admin/seiten', label: 'Seiten', icon: FolderTree },
|
||||
{ href: '/admin/termine', label: 'Termine', icon: CalendarDays },
|
||||
{ href: '/admin/speiseplan', label: 'Speiseplan', icon: Utensils },
|
||||
{ href: '/admin/kacheln', label: 'Startseite', icon: LayoutGrid },
|
||||
{ href: '/admin/ansprechpartner', label: 'Ansprechpartner', icon: Users },
|
||||
{ href: '/admin/medien', label: 'Mediathek', icon: Image }
|
||||
|
|
@ -47,6 +51,7 @@
|
|||
items: [
|
||||
{ href: '/admin/postfach', label: 'Postfach', icon: Inbox, badge: data.unread },
|
||||
{ href: '/admin/benachrichtigungen', label: 'Benachrichtigungen', icon: BellRing },
|
||||
{ href: '/admin/statistik', label: 'Statistik', icon: ChartColumn },
|
||||
...(data.user.role === 'admin'
|
||||
? [
|
||||
{ href: '/admin/benutzer', label: 'Benutzer', icon: UserCog },
|
||||
|
|
@ -136,6 +141,7 @@
|
|||
<LogOut class="size-4" /> Abmelden
|
||||
</button>
|
||||
</form>
|
||||
<p class="px-3 pt-1 text-xs text-ink-3">Version {VERSION}</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@
|
|||
<div>
|
||||
<label class="label" for="p-url">Öffnet beim Antippen</label>
|
||||
<input id="p-url" name="url" class="field" value="/" placeholder="/meldungen/…" />
|
||||
<p class="hint">Pfad innerhalb der App, z. B. <code>/termine</code> oder <code>/s/speiseplaene</code>.</p>
|
||||
<p class="hint">Pfad innerhalb der App, z. B. <code>/termine</code> oder <code>/speiseplan</code>.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" disabled={busy}><Send class="size-4" />Jetzt senden</button>
|
||||
{#if form?.error}<p class="text-sm text-danger font-semibold" role="alert">{form.error}</p>{/if}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { dailyUsage } from '$lib/server/easy-auto';
|
|||
import { FcmConfigError, saveServiceAccount, serviceAccountInfo } from '$lib/server/fcm';
|
||||
import { AI_PROVIDERS, type AiProvider } from '$lib/settings';
|
||||
import { cleanTheme } from '$lib/theme';
|
||||
import { isLang } from '$lib/languages';
|
||||
import { checkBrandColors, darkenForContrast } from '$lib/color';
|
||||
|
||||
export const load = ({ locals }) => {
|
||||
|
|
@ -61,6 +62,7 @@ function read(form: FormData): Partial<AppSettings> | string {
|
|||
aiProvider: (f.str('aiProvider') in AI_PROVIDERS ? f.str('aiProvider') : 'anthropic') as AiProvider,
|
||||
aiModel: f.str('aiModel', 120),
|
||||
aiBaseUrl: f.str('aiBaseUrl', 300),
|
||||
aiLanguages: form.getAll('aiLanguages').filter(isLang),
|
||||
aiDailyLimit: Math.min(5000, Math.max(0, f.int('aiDailyLimit') ?? 100)),
|
||||
homeNewsCount: Math.min(12, Math.max(0, f.int('homeNewsCount') ?? 4)),
|
||||
homeEventsCount: Math.min(12, Math.max(0, f.int('homeEventsCount') ?? 4)),
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@
|
|||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel id="ki" title="Leichte Sprache mit KI" description="Überträgt Texte ohne eigene Fassung automatisch für Leser in Leichte Sprache. Eigene Fassungen aus der Redaktion haben immer Vorrang.">
|
||||
<Panel id="ki" title="Leichte Sprache & Übersetzungen mit KI" description="Leichte Sprache als Entwurf für die Redaktion oder automatisch für Leser – und Übersetzungen in andere Sprachen. Eigene Fassungen aus der Redaktion haben immer Vorrang.">
|
||||
<AiSettings {s} ai={data.ai} />
|
||||
</Panel>
|
||||
|
||||
|
|
|
|||
85
src/routes/admin/(panel)/speiseplan/+page.server.ts
Normal file
85
src/routes/admin/(panel)/speiseplan/+page.server.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import { fail } from '@sveltejs/kit';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db } from '$lib/server/db';
|
||||
import { meals } from '$lib/server/db/schema';
|
||||
import { fields } from '$lib/server/forms';
|
||||
import { copyWeek, mealsBetween } from '$lib/server/meals';
|
||||
import { getSettings, saveSettings } from '$lib/server/settings';
|
||||
import { addDays, today } from '$lib/dates';
|
||||
import { cleanAllergens, cleanLabels, isoWeek, mondayOf, weekDays } from '$lib/meals';
|
||||
|
||||
const isDate = (v: string) => /^\d{4}-\d{2}-\d{2}$/.test(v);
|
||||
|
||||
export const load = ({ url }) => {
|
||||
const s = getSettings();
|
||||
const wanted = url.searchParams.get('woche') ?? '';
|
||||
const monday = mondayOf(isDate(wanted) ? wanted : today());
|
||||
const days = weekDays(monday, s.mealWeekend ? 7 : 5);
|
||||
const byDay = mealsBetween(days[0], days.at(-1)!);
|
||||
const prev = mealsBetween(addDays(monday, -7), addDays(monday, -1));
|
||||
return {
|
||||
monday,
|
||||
week: isoWeek(monday),
|
||||
today: today(),
|
||||
days: days.map((date) => ({ date, meals: byDay[date] ?? [] })),
|
||||
previousWeekHasMeals: Object.keys(prev).length > 0,
|
||||
options: { locations: s.mealLocations, lines: s.mealLines, weekend: s.mealWeekend, note: s.mealNote }
|
||||
};
|
||||
};
|
||||
|
||||
const lines = (v: string, max: number) =>
|
||||
[...new Set(v.split('\n').map((l) => l.trim().slice(0, 60)).filter(Boolean))].slice(0, max);
|
||||
|
||||
export const actions = {
|
||||
save: async ({ request }) => {
|
||||
const form = await request.formData();
|
||||
const f = fields(form);
|
||||
const id = f.int('id');
|
||||
const date = f.str('date', 10);
|
||||
const title = f.str('title', 200);
|
||||
if (!isDate(date)) return fail(400, { error: 'Bitte ein Datum wählen.' });
|
||||
if (!title) return fail(400, { error: 'Bitte angeben, was es gibt.' });
|
||||
const s = getSettings();
|
||||
const line = f.str('line', 60);
|
||||
const location = f.str('location', 60);
|
||||
const pos = s.mealLines.indexOf(line);
|
||||
const values = {
|
||||
date,
|
||||
title,
|
||||
line,
|
||||
location: s.mealLocations.includes(location) ? location : '',
|
||||
description: f.str('description', 300),
|
||||
allergens: cleanAllergens(form.getAll('allergens')),
|
||||
labels: cleanLabels(form.getAll('labels')),
|
||||
price: f.str('price', 30),
|
||||
position: pos >= 0 ? pos : 99
|
||||
};
|
||||
if (id) db.update(meals).set(values).where(eq(meals.id, id)).run();
|
||||
else db.insert(meals).values(values).run();
|
||||
return { saved: true };
|
||||
},
|
||||
|
||||
delete: async ({ request }) => {
|
||||
const id = fields(await request.formData()).int('id');
|
||||
if (id) db.delete(meals).where(eq(meals.id, id)).run();
|
||||
return { deleted: true };
|
||||
},
|
||||
|
||||
copyPrevious: async ({ request }) => {
|
||||
const monday = fields(await request.formData()).str('monday', 10);
|
||||
if (!isDate(monday)) return fail(400, { error: 'Ungültige Woche.' });
|
||||
const n = copyWeek(addDays(mondayOf(monday), -7), mondayOf(monday));
|
||||
return { copied: n };
|
||||
},
|
||||
|
||||
options: async ({ request }) => {
|
||||
const f = fields(await request.formData());
|
||||
saveSettings({
|
||||
mealLocations: lines(f.str('locations', 2000), 20),
|
||||
mealLines: lines(f.str('lines', 2000), 20),
|
||||
mealWeekend: f.bool('weekend'),
|
||||
mealNote: f.str('note', 300)
|
||||
});
|
||||
return { saved: true };
|
||||
}
|
||||
};
|
||||
128
src/routes/admin/(panel)/speiseplan/+page.svelte
Normal file
128
src/routes/admin/(panel)/speiseplan/+page.svelte
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import Plus from '@lucide/svelte/icons/plus';
|
||||
import Copy from '@lucide/svelte/icons/copy';
|
||||
import Pencil from '@lucide/svelte/icons/pencil';
|
||||
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
|
||||
import ChevronRight from '@lucide/svelte/icons/chevron-right';
|
||||
import ExternalLink from '@lucide/svelte/icons/external-link';
|
||||
import PageHeader from '$lib/admin/PageHeader.svelte';
|
||||
import Panel from '$lib/admin/Panel.svelte';
|
||||
import Switch from '$lib/admin/Switch.svelte';
|
||||
import MealDialog from '$lib/admin/MealDialog.svelte';
|
||||
import { toasts } from '$lib/admin/toast.svelte';
|
||||
import { addDays, formatDate, formatLong } from '$lib/dates';
|
||||
import { MEAL_LABELS, type MealDraft, type MealLabel } from '$lib/meals';
|
||||
|
||||
let { data } = $props();
|
||||
let editing = $state<MealDraft | null>(null);
|
||||
|
||||
const add = (date: string) =>
|
||||
(editing = { id: 0, date, line: '', location: '', title: '', description: '', allergens: [], labels: [], price: '' });
|
||||
const edit = (m: MealDraft) => (editing = { ...m, allergens: [...m.allergens], labels: [...m.labels] });
|
||||
|
||||
const range = $derived(`${formatDate(data.days[0].date).replace(/ \d{4}$/, '')} bis ${formatDate(data.days.at(-1)!.date)}`);
|
||||
const weekHasMeals = $derived(data.days.some((d) => d.meals.length));
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Speiseplan · {data.brand.appName}</title></svelte:head>
|
||||
|
||||
<PageHeader title="Speiseplan" description="Gerichte pro Tag eintragen – mit Allergenen und Kennzeichnung. Erscheint in der App unter „Speiseplan“ und auf der Startseite.">
|
||||
{#snippet actions()}
|
||||
<a href="/speiseplan?woche={data.monday}" class="btn btn-soft" target="_blank" rel="noopener"><ExternalLink class="size-4" />In der App ansehen</a>
|
||||
{/snippet}
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 mb-6">
|
||||
<a href="?woche={addDays(data.monday, -7)}" class="btn btn-ghost btn-icon btn-sm" aria-label="Vorherige Woche" data-sveltekit-noscroll><ChevronLeft class="size-5" /></a>
|
||||
<h2 class="font-bold text-lg" aria-live="polite">KW {data.week} <span class="font-semibold text-ink-2">· {range}</span></h2>
|
||||
<a href="?woche={addDays(data.monday, 7)}" class="btn btn-ghost btn-icon btn-sm" aria-label="Nächste Woche" data-sveltekit-noscroll><ChevronRight class="size-5" /></a>
|
||||
{#if data.today < data.monday || data.today > addDays(data.monday, 6)}<a href="?" class="btn btn-soft btn-sm" data-sveltekit-noscroll>Diese Woche</a>{/if}
|
||||
{#if data.previousWeekHasMeals}
|
||||
<form
|
||||
method="POST"
|
||||
action="?/copyPrevious"
|
||||
class="ml-auto"
|
||||
use:enhance={() =>
|
||||
async ({ result, update }) => {
|
||||
await update();
|
||||
if (result.type === 'success') toasts.show(result.data?.copied ? `${result.data.copied} Gerichte übernommen` : 'Alle Tage dieser Woche haben schon Gerichte.');
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="monday" value={data.monday} />
|
||||
<button class="btn btn-soft btn-sm" title="Füllt nur Tage, an denen noch nichts eingetragen ist"><Copy class="size-4" />Vorwoche übernehmen</button>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="grid xl:grid-cols-[1fr_20rem] gap-6 items-start">
|
||||
<ol class="space-y-3">
|
||||
{#each data.days as d (d.date)}
|
||||
<li class="card p-4 sm:p-5">
|
||||
<div class="flex items-center justify-between gap-3 mb-2">
|
||||
<h3 class="font-bold">
|
||||
{formatLong(d.date).split(',')[0]} <span class="font-semibold text-ink-2">{formatDate(d.date)}</span>
|
||||
{#if d.date === data.today}<span class="ml-1 rounded-pill bg-brand text-on-brand px-2 py-0.5 text-xs">Heute</span>{/if}
|
||||
</h3>
|
||||
<button type="button" class="btn btn-soft btn-sm" onclick={() => add(d.date)}>
|
||||
<Plus class="size-4" />Gericht<span class="sr-only"> am {formatLong(d.date)} hinzufügen</span>
|
||||
</button>
|
||||
</div>
|
||||
{#if d.meals.length}
|
||||
<ul class="divide-y divide-line">
|
||||
{#each d.meals as m (m.id)}
|
||||
<li>
|
||||
<button type="button" class="group w-full flex items-center gap-3 py-2.5 text-left hover:text-brand-ink" onclick={() => edit(m)}>
|
||||
<span class="w-28 shrink-0 text-sm font-semibold text-ink-2">{m.line || '–'}{#if m.location}<span class="block text-xs font-medium">{m.location}</span>{/if}</span>
|
||||
<span class="flex-1 min-w-0">
|
||||
<span class="block font-semibold">{m.title}</span>
|
||||
<span class="block text-sm text-ink-2">
|
||||
{[...m.labels.map((l) => MEAL_LABELS[l as MealLabel]?.label), m.allergens.length ? `Allergene ${m.allergens.join(', ')}` : ''].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</span>
|
||||
<Pencil class="size-4 text-ink-3 shrink-0" aria-hidden="true" /><span class="sr-only">bearbeiten</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="text-sm text-ink-3">Noch nichts eingetragen.</p>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
{#if !weekHasMeals && !data.previousWeekHasMeals}
|
||||
<p class="hint">Tipp: Ist eine Woche fertig, lässt sie sich mit „Vorwoche übernehmen“ als Vorlage für die nächste nutzen.</p>
|
||||
{/if}
|
||||
</ol>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="?/options"
|
||||
use:enhance={() =>
|
||||
async ({ result, update }) => {
|
||||
await update({ reset: false });
|
||||
if (result.type === 'success') toasts.show('Gespeichert');
|
||||
}}
|
||||
>
|
||||
<Panel title="Einstellungen">
|
||||
<div>
|
||||
<label class="label" for="o-lines">Linien</label>
|
||||
<textarea id="o-lines" name="lines" rows="3" class="field" aria-describedby="o-lines-hint">{data.options.lines.join('\n')}</textarea>
|
||||
<p id="o-lines-hint" class="hint">Eine pro Zeile, z. B. „Menü 1“. Bestimmt auch die Reihenfolge.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label" for="o-locations">Standorte (optional)</label>
|
||||
<textarea id="o-locations" name="locations" rows="3" class="field" aria-describedby="o-loc-hint">{data.options.locations.join('\n')}</textarea>
|
||||
<p id="o-loc-hint" class="hint">Eine pro Zeile. Gibt es mehrere, können Leser ihren Standort wählen.</p>
|
||||
</div>
|
||||
<Switch name="weekend" checked={data.options.weekend} label="Samstag und Sonntag zeigen" />
|
||||
<div>
|
||||
<label class="label" for="o-note">Hinweis unter dem Speiseplan</label>
|
||||
<textarea id="o-note" name="note" rows="3" class="field">{data.options.note}</textarea>
|
||||
</div>
|
||||
<button class="btn btn-primary">Speichern</button>
|
||||
</Panel>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<MealDialog bind:meal={editing} lines={data.options.lines} locations={data.options.locations} />
|
||||
10
src/routes/admin/(panel)/statistik/+page.server.ts
Normal file
10
src/routes/admin/(panel)/statistik/+page.server.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { statsReport } from '$lib/server/stats';
|
||||
import { subscriberCounts } from '$lib/server/push';
|
||||
|
||||
const PERIODS = [7, 30, 90, 365];
|
||||
|
||||
export const load = ({ url }) => {
|
||||
const wanted = Number(url.searchParams.get('tage'));
|
||||
const days = PERIODS.includes(wanted) ? wanted : 30;
|
||||
return { days, periods: PERIODS, report: statsReport(days), push: subscriberCounts() };
|
||||
};
|
||||
107
src/routes/admin/(panel)/statistik/+page.svelte
Normal file
107
src/routes/admin/(panel)/statistik/+page.svelte
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
<script lang="ts">
|
||||
import PageHeader from '$lib/admin/PageHeader.svelte';
|
||||
import { formatShort } from '$lib/dates';
|
||||
import { LANGUAGES, isLang } from '$lib/languages';
|
||||
|
||||
let { data } = $props();
|
||||
const r = $derived(data.report);
|
||||
const max = $derived(Math.max(1, ...r.series.map((d) => d.views)));
|
||||
const pct = (n: number) => (r.total ? Math.round((n / r.total) * 100) : 0);
|
||||
const nf = new Intl.NumberFormat('de-DE');
|
||||
const variantLabel = (v: string) => (v === 'leicht' ? 'Leichte Sprache' : isLang(v) ? `Übersetzung: ${LANGUAGES[v].german}` : v);
|
||||
// Bei langen Zeiträumen Wochen statt Tage zeigen, damit die Balken lesbar bleiben
|
||||
const bars = $derived.by(() => {
|
||||
if (data.days <= 31) return r.series.map((d) => ({ label: formatShort(d.day).slice(0, 6), from: d.day, views: d.views }));
|
||||
const out: { label: string; from: string; views: number }[] = [];
|
||||
for (let i = 0; i < r.series.length; i += 7) {
|
||||
const chunk = r.series.slice(i, i + 7);
|
||||
out.push({ label: formatShort(chunk[0].day).slice(0, 6), from: chunk[0].day, views: chunk.reduce((a, d) => a + d.views, 0) });
|
||||
}
|
||||
return out;
|
||||
});
|
||||
const barMax = $derived(Math.max(1, ...bars.map((b) => b.views)));
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Statistik · {data.brand.appName}</title></svelte:head>
|
||||
|
||||
<PageHeader title="Statistik" description="Wie oft wird was gelesen? Anonym gezählt – ohne Cookies, ohne IP-Adressen, ohne Rückschluss auf Personen." />
|
||||
|
||||
<nav aria-label="Zeitraum" class="inline-flex rounded-pill bg-surface-2 p-1 mb-6">
|
||||
{#each data.periods as p (p)}
|
||||
<a
|
||||
href="?tage={p}"
|
||||
class="rounded-pill px-3.5 py-1.5 text-sm font-bold transition {data.days === p ? 'bg-surface text-brand-ink shadow-card' : 'text-ink-2 hover:text-ink'}"
|
||||
aria-current={data.days === p ? 'page' : undefined}
|
||||
data-sveltekit-noscroll>{p === 365 ? '1 Jahr' : `${p} Tage`}</a
|
||||
>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
|
||||
<div class="card p-4"><p class="font-display text-3xl font-extrabold">{nf.format(r.total)}</p><p class="text-sm text-ink-3">Aufrufe</p></div>
|
||||
<div class="card p-4"><p class="font-display text-3xl font-extrabold">{pct(r.app)} %</p><p class="text-sm text-ink-3">in den Apps ({nf.format(r.app)})</p></div>
|
||||
<div class="card p-4"><p class="font-display text-3xl font-extrabold">{new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 }).format(r.total / data.days)}</p><p class="text-sm text-ink-3">Aufrufe pro Tag</p></div>
|
||||
<div class="card p-4"><p class="font-display text-3xl font-extrabold">{nf.format(data.push.total)}</p><p class="text-sm text-ink-3">Geräte mit Benachrichtigungen</p></div>
|
||||
</div>
|
||||
|
||||
<section class="card p-5 mb-6" aria-labelledby="verlauf">
|
||||
<h2 id="verlauf" class="font-bold text-lg mb-4">Verlauf {data.days > 31 ? '(pro Woche)' : '(pro Tag)'}</h2>
|
||||
<div class="flex items-end gap-[2px] h-48" aria-hidden="true">
|
||||
{#each bars as b (b.from)}
|
||||
<div class="flex-1 min-w-0 rounded-t-sm bg-brand/80 hover:bg-brand" style="height:{Math.max(1, (b.views / barMax) * 100)}%" title="{b.label}: {b.views}"></div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="flex justify-between text-xs text-ink-3 mt-2" aria-hidden="true">
|
||||
<span>{bars[0]?.label}</span><span>{bars.at(-1)?.label}</span>
|
||||
</div>
|
||||
<details class="mt-3">
|
||||
<summary class="text-sm font-semibold text-brand-ink cursor-pointer">Als Tabelle anzeigen</summary>
|
||||
<table class="mt-2 text-sm">
|
||||
<thead><tr><th class="text-left pr-6">{data.days > 31 ? 'Woche ab' : 'Tag'}</th><th class="text-right">Aufrufe</th></tr></thead>
|
||||
<tbody>{#each bars as b (b.from)}<tr><td class="pr-6">{formatShort(b.from)}</td><td class="text-right tabular-nums">{b.views}</td></tr>{/each}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
{#if max === 1 && r.total === 0}<p class="hint">Noch keine Aufrufe in diesem Zeitraum.</p>{/if}
|
||||
</section>
|
||||
|
||||
<div class="grid lg:grid-cols-[1.5fr_1fr] gap-6">
|
||||
<section class="card p-5" aria-labelledby="meistgelesen">
|
||||
<h2 id="meistgelesen" class="font-bold text-lg mb-3">Meistgelesen</h2>
|
||||
{#if r.top.length}
|
||||
<ol class="divide-y divide-line">
|
||||
{#each r.top as t, i (t.path)}
|
||||
<li class="flex items-center gap-3 py-2.5">
|
||||
<span class="w-6 text-sm font-bold text-ink-3 tabular-nums">{i + 1}.</span>
|
||||
<a href={t.path} target="_blank" rel="noopener" class="flex-1 min-w-0 font-semibold truncate hover:text-brand-ink">{t.title}</a>
|
||||
<span class="text-sm tabular-nums text-ink-2">{nf.format(t.n)}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
{:else}
|
||||
<p class="text-ink-3">Noch keine Daten.</p>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<div class="space-y-6">
|
||||
<section class="card p-5" aria-labelledby="fassungen">
|
||||
<h2 id="fassungen" class="font-bold text-lg mb-3">Leichte Sprache & Übersetzungen</h2>
|
||||
{#if r.variants.length}
|
||||
<ul class="space-y-2">
|
||||
{#each r.variants as v (v.k)}
|
||||
<li class="flex justify-between gap-3"><span>{variantLabel(v.k)}</span><span class="tabular-nums font-semibold">{nf.format(v.n)}</span></li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="text-ink-3 text-sm">Bisher hat niemand Leichte Sprache oder eine andere Sprache eingestellt.</p>
|
||||
{/if}
|
||||
</section>
|
||||
<section class="card p-5" aria-labelledby="push">
|
||||
<h2 id="push" class="font-bold text-lg mb-3">Benachrichtigungen</h2>
|
||||
<ul class="space-y-2">
|
||||
<li class="flex justify-between"><span>Im Browser</span><span class="tabular-nums font-semibold">{data.push.web}</span></li>
|
||||
<li class="flex justify-between"><span>In den Apps</span><span class="tabular-nums font-semibold">{data.push.app}</span></li>
|
||||
</ul>
|
||||
<a href="/admin/benachrichtigungen" class="text-sm font-semibold text-brand-ink mt-3 inline-block">Details und Versand</a>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
22
src/routes/api/gelesen/+server.ts
Normal file
22
src/routes/api/gelesen/+server.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { countView, normalizePath } from '$lib/server/stats';
|
||||
|
||||
/** Höchstens 300 Zählungen pro Adresse und Stunde – nur im Speicher, nichts wird über Leser gespeichert */
|
||||
const recent = new Map<string, { n: number; until: number }>();
|
||||
|
||||
/** Zählt einen Seitenaufruf (anonym, siehe $lib/server/stats.ts) */
|
||||
export const POST = async ({ request, getClientAddress }) => {
|
||||
const now = Date.now();
|
||||
const ip = getClientAddress();
|
||||
const bucket = recent.get(ip);
|
||||
if (bucket && bucket.until > now && bucket.n >= 300) return new Response(null, { status: 204 });
|
||||
if (!bucket || bucket.until <= now) recent.set(ip, { n: 1, until: now + 3600e3 });
|
||||
else bucket.n++;
|
||||
if (recent.size > 10_000) for (const [k, v] of recent) if (v.until <= now) recent.delete(k);
|
||||
|
||||
const ua = request.headers.get('user-agent') ?? '';
|
||||
if (/bot|crawl|spider|slurp|preview|headless/i.test(ua)) return new Response(null, { status: 204 });
|
||||
const body = await request.json().catch(() => null);
|
||||
const path = typeof body?.path === 'string' ? normalizePath(body.path.slice(0, 200)) : null;
|
||||
if (path) countView(path, ua.includes('WerkstattApp/') ? 'app' : 'web', typeof body?.variant === 'string' ? body.variant : 'normal');
|
||||
return new Response(null, { status: 204 });
|
||||
};
|
||||
32
src/routes/api/uebersetzung/+server.ts
Normal file
32
src/routes/api/uebersetzung/+server.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { error, json } from '@sveltejs/kit';
|
||||
import { and, eq, lte } from 'drizzle-orm';
|
||||
import { db } from '$lib/server/db';
|
||||
import { pages, posts } from '$lib/server/db/schema';
|
||||
import { AiError } from '$lib/server/ai';
|
||||
import { translate, translationEnabled, type TranslateKind } from '$lib/server/translate';
|
||||
import { allow } from '$lib/server/ratelimit';
|
||||
|
||||
/** Übersetzt eine veröffentlichte Meldung oder Seite – die Seite lädt danach neu */
|
||||
export const POST = async ({ request, getClientAddress }) => {
|
||||
const body = await request.json().catch(() => null);
|
||||
const kind: TranslateKind = body?.typ === 'page' ? 'page' : 'post';
|
||||
const slug = typeof body?.slug === 'string' ? body.slug.slice(0, 200) : '';
|
||||
const lang = typeof body?.lang === 'string' ? body.lang : '';
|
||||
if (!translationEnabled(lang)) error(404, 'Diese Sprache gibt es nicht.');
|
||||
|
||||
const row =
|
||||
kind === 'post'
|
||||
? db.select().from(posts).where(and(eq(posts.slug, slug), eq(posts.published, true), lte(posts.publishedAt, new Date()))).get()
|
||||
: db.select().from(pages).where(and(eq(pages.slug, slug), eq(pages.published, true))).get();
|
||||
if (!row) error(404, 'Text nicht gefunden.');
|
||||
|
||||
// Kostenschutz: pro Gerät höchstens 20 Übersetzungen pro Stunde
|
||||
if (!allow(`ki-ip:${getClientAddress()}`, 20, 3600e3)) error(429, 'Bitte versuche es etwas später noch einmal.');
|
||||
try {
|
||||
await translate(kind, { id: row.id, title: row.title, teaser: 'teaser' in row ? row.teaser : '', content: row.content }, lang);
|
||||
} catch (e) {
|
||||
if (e instanceof AiError) error(503, e.message);
|
||||
throw e;
|
||||
}
|
||||
return json({ ok: true });
|
||||
};
|
||||
19
src/routes/health/+server.ts
Normal file
19
src/routes/health/+server.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { json } from '@sveltejs/kit';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { db } from '$lib/server/db';
|
||||
import { startedAt } from '$lib/server/monitor';
|
||||
import { VERSION } from '$lib/version';
|
||||
|
||||
/** Zustand für Überwachung und deploy/uebersicht.sh – ohne Inhalte oder Personendaten */
|
||||
export const GET = () => {
|
||||
let dbOk = false;
|
||||
try {
|
||||
dbOk = db.get<{ ok: number }>(sql`select 1 as ok`)?.ok === 1;
|
||||
} catch {
|
||||
/* unten gemeldet */
|
||||
}
|
||||
return json(
|
||||
{ status: dbOk ? 'ok' : 'fehler', version: VERSION, database: dbOk ? 'ok' : 'fehler', uptime: Math.round((Date.now() - startedAt) / 1000) },
|
||||
{ status: dbOk ? 200 : 503, headers: { 'cache-control': 'no-store' } }
|
||||
);
|
||||
};
|
||||
7
src/test-setup.ts
Normal file
7
src/test-setup.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
// Jede Testdatei bekommt einen eigenen Datenordner – die Datenbank wird beim ersten Import angelegt und migriert
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'werkstatt-test-'));
|
||||
delete process.env.DATABASE_PATH;
|
||||
24
tests/e2e/betrieb.spec.ts
Normal file
24
tests/e2e/betrieb.spec.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test('Health-Check meldet Version und Datenbank', async ({ request }) => {
|
||||
const res = await request.get('/health');
|
||||
expect(res.status()).toBe(200);
|
||||
expect(res.headers()['cache-control']).toBe('no-store');
|
||||
const body = await res.json();
|
||||
expect(body).toMatchObject({ status: 'ok', database: 'ok' });
|
||||
expect(body.version).toMatch(/\d+\.\d+\.\d+/);
|
||||
});
|
||||
|
||||
test('Sicherheits-Header und kein Zugriff auf die Redaktion ohne Anmeldung', async ({ request }) => {
|
||||
const res = await request.get('/');
|
||||
expect(res.headers()['x-content-type-options']).toBe('nosniff');
|
||||
expect(res.headers()['content-security-policy']).toContain("object-src 'none'");
|
||||
const admin = await request.get('/admin/einstellungen', { maxRedirects: 0 });
|
||||
expect([302, 303]).toContain(admin.status());
|
||||
expect(admin.headers()['location']).toContain('/admin/login');
|
||||
});
|
||||
|
||||
test('Aufrufzählung nimmt nur echte Seiten an', async ({ request }) => {
|
||||
expect((await request.post('/api/gelesen', { data: { path: '/etc/passwd' } })).status()).toBe(204);
|
||||
expect((await request.post('/api/gelesen', { data: { path: '/speiseplan', variant: 'normal' } })).status()).toBe(204);
|
||||
});
|
||||
35
tests/e2e/fake-ai.mjs
Normal file
35
tests/e2e/fake-ai.mjs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// Nachgebauter OpenAI-kompatibler KI-Dienst (wie Ollama) für die Tests – antwortet sofort und vorhersagbar
|
||||
import http from 'node:http';
|
||||
|
||||
export function startFakeAi(port) {
|
||||
const server = http.createServer((req, res) => {
|
||||
let body = '';
|
||||
req.on('data', (c) => (body += c));
|
||||
req.on('end', () => {
|
||||
if (req.url === '/v1/models') {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ object: 'list', data: [{ id: 'test-modell', object: 'model' }] }));
|
||||
return;
|
||||
}
|
||||
if (req.url !== '/v1/chat/completions') {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
const [system, user] = JSON.parse(body).messages.map((m) => m.content);
|
||||
let text = '<p>Das ist ein Text in Leichter Sprache.</p><p>Er hat kurze Sätze.</p>';
|
||||
if (system.startsWith('You translate')) {
|
||||
const lang = system.match(/into (\w+)/)?.[1];
|
||||
const title = user.match(/<title>([\s\S]*?)<\/title>/)?.[1];
|
||||
// enthält absichtlich gefährliches HTML – muss beim Speichern entfernt werden
|
||||
text = `<title>[${lang}] ${title}</title>\n<teaser></teaser>\n<body><p>Translated into ${lang}.</p><img alt="" src="x" onerror="window.__xss=1"></body>`;
|
||||
}
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
||||
const chunk = (delta, finish = null) =>
|
||||
res.write(`data: ${JSON.stringify({ id: 't', object: 'chat.completion.chunk', created: 0, model: 'test-modell', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`);
|
||||
for (let i = 0; i < text.length; i += 40) chunk({ content: text.slice(i, i + 40) });
|
||||
chunk({}, 'stop');
|
||||
res.end('data: [DONE]\n\n');
|
||||
});
|
||||
});
|
||||
return new Promise((resolve) => server.listen(port, () => resolve(server)));
|
||||
}
|
||||
32
tests/e2e/helpers.ts
Normal file
32
tests/e2e/helpers.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { expect, type Page } from '@playwright/test';
|
||||
|
||||
const axeSource = fs.readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.min.js'), 'utf8');
|
||||
|
||||
/** Prüft die Seite mit axe auf WCAG 2.2 AA – erwartet 0 Verstöße */
|
||||
export async function expectAccessible(page: Page) {
|
||||
await page.addScriptTag({ content: axeSource });
|
||||
const violations = await page.evaluate(async () => {
|
||||
// @ts-expect-error axe wird oben eingebunden
|
||||
const r = await window.axe.run(document, { runOnly: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa', 'best-practice'] });
|
||||
return r.violations.map((v: { id: string; nodes: { target: string[] }[] }) => `${v.id}: ${v.nodes.map((n) => n.target.join(' ')).slice(0, 3).join(' | ')}`);
|
||||
});
|
||||
expect(violations, `axe auf ${page.url()}`).toEqual([]);
|
||||
}
|
||||
|
||||
export async function login(page: Page, email = 'admin@example.org') {
|
||||
await page.goto('/admin/login');
|
||||
await page.fill('#email', email);
|
||||
await page.fill('#password', 'demo-passwort');
|
||||
await page.getByRole('button', { name: 'Anmelden' }).click();
|
||||
await page.waitForURL((u) => !u.pathname.includes('login'));
|
||||
}
|
||||
|
||||
/** Einstellungen speichern und warten, bis die Antwort da ist */
|
||||
export async function saveSettings(page: Page) {
|
||||
await Promise.all([
|
||||
page.waitForResponse((r) => r.url().includes('/admin/einstellungen') && r.request().method() === 'POST'),
|
||||
page.getByRole('button', { name: 'Speichern' }).first().click()
|
||||
]);
|
||||
}
|
||||
54
tests/e2e/ki.spec.ts
Normal file
54
tests/e2e/ki.spec.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import { expectAccessible, login, saveSettings } from './helpers';
|
||||
|
||||
// KI über den Testdienst aus tests/e2e/fake-ai.mjs (OpenAI-kompatibel, wie Ollama)
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
test('KI einrichten: Leichte Sprache als Entwurf und Übersetzungen', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/admin/einstellungen');
|
||||
await page.getByRole('switch', { name: /KI für Leichte Sprache/ }).check();
|
||||
await page.selectOption('#aiProvider', 'ollama');
|
||||
await page.fill('#aiBaseUrl', 'http://localhost:9599/v1');
|
||||
await page.fill('#aiModel', 'test-modell');
|
||||
await page.getByLabel('Türkisch').check();
|
||||
await page.getByLabel('Arabisch').check();
|
||||
await saveSettings(page);
|
||||
await page.reload();
|
||||
await expect(page.getByText('eingerichtet und aktiv')).toBeVisible();
|
||||
|
||||
// „Mit KI erstellen“ in einer Meldung
|
||||
await page.goto('/admin/meldungen');
|
||||
await page.getByRole('link', { name: /Sommerfest/ }).first().click();
|
||||
await page.getByRole('button', { name: /Mit KI erstellen|Vorhandene Fassung ersetzen/ }).click();
|
||||
if (await page.getByRole('button', { name: 'Vorhandene Fassung ersetzen?' }).isVisible()) await page.getByRole('button', { name: 'Vorhandene Fassung ersetzen?' }).click();
|
||||
await expect(page.getByText('Das ist ein Text in Leichter Sprache.')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Leser lässt eine Meldung übersetzen', async ({ page }) => {
|
||||
await page.goto('/meldungen/sommerfest-2026');
|
||||
await page.getByText('Andere Sprache').click();
|
||||
await page.getByRole('button', { name: /Türkçe/ }).click();
|
||||
const h1 = page.getByRole('heading', { level: 1 });
|
||||
await expect(h1).toContainText('[Turkish]');
|
||||
await expect(h1).toHaveAttribute('lang', 'tr');
|
||||
await expect(page.locator('#vorlesen')).toHaveAttribute('lang', 'tr');
|
||||
await expect(page.getByText('Almancadan otomatik olarak çevrildi')).toBeVisible();
|
||||
// gefährliches HTML aus der KI-Antwort wurde entfernt
|
||||
expect(await page.evaluate(() => (window as unknown as { __xss?: number }).__xss)).toBeUndefined();
|
||||
await expect(page.locator('#vorlesen img[onerror]')).toHaveCount(0);
|
||||
await expectAccessible(page);
|
||||
|
||||
await page.getByRole('button', { name: /Almanca aslını göster/ }).click();
|
||||
await expect(h1).not.toContainText('[Turkish]');
|
||||
});
|
||||
|
||||
test('Arabisch wird von rechts nach links gesetzt', async ({ page }) => {
|
||||
await page.goto('/einstellungen');
|
||||
await page.selectOption('#pref-lang', 'ar');
|
||||
await page.goto('/s/dienste');
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveAttribute('dir', 'rtl');
|
||||
await expectAccessible(page);
|
||||
await page.goto('/einstellungen');
|
||||
await page.selectOption('#pref-lang', 'de');
|
||||
});
|
||||
67
tests/e2e/leser.spec.ts
Normal file
67
tests/e2e/leser.spec.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import { expectAccessible } from './helpers';
|
||||
|
||||
// Die App für Leser – ohne Anmeldung, auf dem Handy
|
||||
|
||||
test('Startseite zeigt Bereiche, Essen, Neuigkeiten und Termine', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('heading', { level: 1 })).toContainText('Willkommen');
|
||||
await expect(page.getByRole('heading', { name: 'Was möchtest du wissen?' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Neuigkeiten' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Was steht an?' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('Meldung lesen, merken und in Leichter Sprache anzeigen', async ({ page }) => {
|
||||
await page.goto('/meldungen/sommerfest-2026');
|
||||
await expect(page.getByRole('heading', { level: 1 })).toContainText('Sommerfest');
|
||||
await page.getByRole('button', { name: 'Leichte Sprache' }).click();
|
||||
await expect(page.getByText('Du liest diesen Text in Leichter Sprache.')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Normale Sprache' }).click();
|
||||
await page.getByRole('button', { name: /Merken/ }).click();
|
||||
await page.goto('/merkliste');
|
||||
await expect(page.getByText('Sommerfest')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Speiseplan mit Woche, Standort und Allergenen', async ({ page }) => {
|
||||
await page.goto('/speiseplan');
|
||||
await expect(page.getByRole('heading', { name: 'Speiseplan' })).toBeVisible();
|
||||
await expect(page.getByText(/^KW \d+/)).toBeVisible();
|
||||
await expect(page.locator('li.card').first()).toBeVisible();
|
||||
await page.selectOption('#standort', 'Werkstatt am Kanal');
|
||||
await expect(page).toHaveURL(/standort=Werkstatt/);
|
||||
await expect(page.getByText('Lindenhof', { exact: false }).filter({ hasText: 'Menü 2 · Lindenhof' })).toHaveCount(0);
|
||||
await page.getByRole('link', { name: 'Nächste Woche' }).click();
|
||||
await expect(page.getByRole('link', { name: 'Diese Woche' })).toBeVisible();
|
||||
await page.getByText('Was bedeuten die Buchstaben?').click();
|
||||
await expect(page.getByRole('definition').filter({ hasText: 'Gluten (Weizen, Roggen, Gerste, Hafer)' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('Termine, Suche und Kontaktformular', async ({ page }) => {
|
||||
await page.goto('/termine');
|
||||
await expect(page.getByRole('heading', { name: 'Termine' })).toBeVisible();
|
||||
await page.goto('/suche?q=sommerfest');
|
||||
await expect(page.getByText('Sommerfest 2026')).toBeVisible();
|
||||
await page.goto('/kontakt');
|
||||
await page.getByLabel('Dein Name').fill('Test Person');
|
||||
await page.getByLabel('Nachricht').fill('Das ist eine Testnachricht aus den automatischen Tests.');
|
||||
await page.getByRole('button', { name: 'Nachricht senden' }).click();
|
||||
await expect(page.getByText('Danke für deine Nachricht!')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Anzeige-Einstellungen wirken sofort', async ({ page }) => {
|
||||
await page.goto('/einstellungen');
|
||||
await page.getByRole('button', { name: /Sehr groß/ }).click();
|
||||
await expect(page.locator('html')).toHaveAttribute('data-size', 'xl');
|
||||
await page.getByRole('button', { name: /Dunkel/ }).click();
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
|
||||
});
|
||||
|
||||
for (const scheme of ['light', 'dark'] as const) {
|
||||
test(`Barrierefreiheit (${scheme === 'light' ? 'hell' : 'dunkel'})`, async ({ page }) => {
|
||||
await page.emulateMedia({ colorScheme: scheme });
|
||||
for (const path of ['/', '/meldungen', '/meldungen/sommerfest-2026', '/termine', '/speiseplan', '/s/dienste', '/kontakte', '/suche?q=werkstatt', '/kontakt', '/merkliste', '/einstellungen', '/impressum', '/datenschutz', '/barrierefreiheit']) {
|
||||
await page.goto(path);
|
||||
await expectAccessible(page);
|
||||
}
|
||||
});
|
||||
}
|
||||
109
tests/e2e/redaktion.spec.ts
Normal file
109
tests/e2e/redaktion.spec.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import { expectAccessible, login, saveSettings } from './helpers';
|
||||
|
||||
test.describe.configure({ mode: 'serial' });
|
||||
|
||||
test('Meldung schreiben und veröffentlichen', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/admin/meldungen/neu');
|
||||
await page.fill('#title', 'Testmeldung aus der Redaktion');
|
||||
await page.fill('#teaser', 'Kurz und knapp.');
|
||||
await page.getByRole('textbox', { name: 'Text' }).fill('Heute gibt es eine Testmeldung.');
|
||||
await page.getByRole('switch', { name: 'Veröffentlicht' }).check();
|
||||
await page.getByRole('button', { name: 'Speichern' }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/meldungen\/\d+/);
|
||||
await page.goto('/meldungen');
|
||||
await expect(page.getByText('Testmeldung aus der Redaktion')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Speiseplan pflegen', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/admin/speiseplan');
|
||||
await page.locator('li.card').first().getByRole('button', { name: /Gericht/ }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await dialog.getByLabel('Gericht', { exact: true }).fill('Kürbissuppe Test');
|
||||
await dialog.getByRole('checkbox', { name: 'vegan' }).check();
|
||||
await dialog.getByRole('checkbox', { name: 'L Sellerie' }).check();
|
||||
await dialog.getByRole('button', { name: 'Speichern' }).click();
|
||||
await expect(page.getByText('Kürbissuppe Test')).toBeVisible();
|
||||
|
||||
const appLink = await page.getByRole('link', { name: 'In der App ansehen' }).getAttribute('href');
|
||||
await page.goto(appLink!);
|
||||
await expect(page.getByText('Kürbissuppe Test')).toBeVisible();
|
||||
|
||||
// Zwei Wochen voraus ist noch nichts geplant → Vorwoche übernehmen
|
||||
await page.goto('/admin/speiseplan');
|
||||
await page.getByRole('link', { name: 'Nächste Woche' }).click();
|
||||
await page.getByRole('link', { name: 'Nächste Woche' }).click();
|
||||
await expect(page.getByText('Noch nichts eingetragen.').first()).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Vorwoche übernehmen' }).click();
|
||||
await expect(page.getByText('Noch nichts eingetragen.')).toHaveCount(0);
|
||||
|
||||
// Gericht löschen
|
||||
await page.locator('li.card li button').first().click();
|
||||
await dialog.getByRole('button', { name: 'Löschen' }).click();
|
||||
await dialog.getByRole('button', { name: 'Wirklich löschen' }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expectAccessible(page);
|
||||
});
|
||||
|
||||
test('Erscheinungsbild: Vorlage wechseln, zu helle Farbe wird abgelehnt', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/admin/einstellungen');
|
||||
await page.fill('#accentColor', '#f4a261');
|
||||
await expect(page.getByText(/Kontrast nur/)).toBeVisible();
|
||||
await saveSettings(page);
|
||||
await expect(page.getByText(/ist zu hell/)).toBeVisible();
|
||||
await page.getByRole('button', { name: /Farbe anpassen/ }).click();
|
||||
|
||||
await page.locator('label:has(input[name=themePreset][value=klar])').click();
|
||||
await page.getByRole('button', { name: 'Farbpaar #0f4c5c und #b3470f' }).click();
|
||||
await saveSettings(page);
|
||||
await page.goto('/');
|
||||
await expect(page.locator('html')).toHaveAttribute('data-preset', 'klar');
|
||||
await expect(page.locator('html')).toHaveAttribute('data-radius', 'eckig');
|
||||
expect(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--brand').trim())).toBe('#0f4c5c');
|
||||
await expectAccessible(page);
|
||||
|
||||
// zurück zur Standard-Vorlage für die übrigen Tests
|
||||
await page.goto('/admin/einstellungen');
|
||||
await page.locator('label:has(input[name=themePreset][value=kreis])').click();
|
||||
await page.getByRole('button', { name: 'Farbpaar #2e2672 und #85357c' }).click();
|
||||
await saveSettings(page);
|
||||
});
|
||||
|
||||
test('Checkliste „Erste Schritte“ lässt sich ausblenden', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/admin');
|
||||
await expect(page.getByRole('heading', { name: /Erste Schritte|Alles eingerichtet/ })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Ausblenden' }).click();
|
||||
await expect(page.getByRole('heading', { name: /Erste Schritte|Alles eingerichtet/ })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('Statistik zeigt anonyme Aufrufe', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await page.getByRole('link', { name: 'Ganze Woche' }).click();
|
||||
await expect(page).toHaveURL(/speiseplan/);
|
||||
await login(page);
|
||||
await page.goto('/admin/statistik?tage=7');
|
||||
await expect(page.getByRole('heading', { name: 'Meistgelesen' })).toBeVisible();
|
||||
await expect(page.getByRole('main').getByRole('link', { name: 'Speiseplan' })).toBeVisible();
|
||||
await expectAccessible(page);
|
||||
});
|
||||
|
||||
test('Redakteure kommen nicht an die Einstellungen', async ({ page }) => {
|
||||
await login(page, 'redaktion@example.org');
|
||||
const res = await page.goto('/admin/einstellungen');
|
||||
expect(res?.status()).toBe(403);
|
||||
});
|
||||
|
||||
for (const scheme of ['light', 'dark'] as const) {
|
||||
test(`Barrierefreiheit der Redaktion (${scheme === 'light' ? 'hell' : 'dunkel'})`, async ({ page }) => {
|
||||
await page.emulateMedia({ colorScheme: scheme });
|
||||
await login(page);
|
||||
for (const path of ['/admin', '/admin/redaktion', '/admin/redaktion?ansicht=board', '/admin/meldungen', '/admin/meldungen/neu', '/admin/seiten', '/admin/termine', '/admin/speiseplan', '/admin/kacheln', '/admin/ansprechpartner', '/admin/medien', '/admin/postfach', '/admin/benachrichtigungen', '/admin/statistik', '/admin/benutzer', '/admin/einstellungen', '/admin/konto']) {
|
||||
await page.goto(path);
|
||||
await expectAccessible(page);
|
||||
}
|
||||
});
|
||||
}
|
||||
27
tests/e2e/server.mjs
Normal file
27
tests/e2e/server.mjs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// Startet die gebaute App mit frischer Demo-Datenbank und dem KI-Testdienst (für playwright.config.ts)
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { startFakeAi } from './fake-ai.mjs';
|
||||
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'werkstatt-e2e-'));
|
||||
const env = { ...process.env, DATA_DIR: dataDir };
|
||||
const run = (script, ...args) => execFileSync(process.execPath, ['--experimental-strip-types', '--no-warnings', script, ...args], { env, stdio: 'inherit' });
|
||||
|
||||
run('scripts/seed.ts', '--force');
|
||||
run('scripts/create-user.ts', 'admin@example.org', 'demo-passwort', 'admin', 'Anna Admin');
|
||||
run('scripts/create-user.ts', 'redaktion@example.org', 'demo-passwort', 'editor', 'Ben Redakteur');
|
||||
await startFakeAi(Number(process.env.FAKE_AI_PORT ?? 9599));
|
||||
|
||||
Object.assign(process.env, {
|
||||
DATA_DIR: dataDir,
|
||||
PORT: process.env.PORT ?? '4173',
|
||||
ORIGIN: `http://localhost:${process.env.PORT ?? '4173'}`,
|
||||
ADMIN_EMAIL: 'admin@example.org',
|
||||
ADMIN_PASSWORD: 'demo-passwort',
|
||||
BODY_SIZE_LIMIT: '30M'
|
||||
});
|
||||
process.on('exit', () => fs.rmSync(dataDir, { recursive: true, force: true }));
|
||||
for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(0));
|
||||
await import(path.resolve('build/index.js'));
|
||||
|
|
@ -1,9 +1,21 @@
|
|||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// Version: APP_VERSION beim Bauen (z. B. Git-Tag in der CI), sonst aus package.json
|
||||
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
|
||||
const version = process.env.APP_VERSION || pkg.version;
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
define: { __APP_VERSION__: JSON.stringify(version) },
|
||||
test: {
|
||||
include: ['src/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
// eigene, leere Datenbank je Testdatei
|
||||
setupFiles: ['src/test-setup.ts']
|
||||
},
|
||||
ssr: {
|
||||
external: ['better-sqlite3', 'sharp']
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue