Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b915857951 | ||
|
|
add96fb40b | ||
|
|
4c99662f6e | ||
|
|
a9f57acf70 | ||
|
|
656ada80bd | ||
|
|
4702bf5abb | ||
|
|
979f795341 | ||
|
|
2d3b82eb80 | ||
|
|
8b32e4a832 | ||
|
|
a96ba0fd84 | ||
|
|
90b8843cda | ||
|
|
043fed2e46 | ||
|
|
ec3f4f933d | ||
|
|
3ce5638449 | ||
|
|
4cd16773c1 | ||
|
|
74dc2d6b57 | ||
|
|
27c5a6940a | ||
|
|
f28956194c | ||
|
|
7eaa198a29 | ||
|
|
5dca7c76f8 |
+12
-7
@@ -1,4 +1,4 @@
|
||||
FROM node:22-alpine AS base
|
||||
FROM node:22-alpine@sha256:0a7108bf6c7bf5de370ffb1a3ed6be93d405b43ff159f681a8d18c0e2bc2e402 AS base
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -28,6 +28,10 @@ COPY . .
|
||||
|
||||
RUN npm run build:prod
|
||||
|
||||
# Separate administrative image; never ship the migration CLI in the app runner.
|
||||
FROM builder AS migrator
|
||||
CMD ["npm", "run", "db:migrate:deploy"]
|
||||
|
||||
FROM base AS runner
|
||||
|
||||
ENV NODE_ENV=production
|
||||
@@ -35,10 +39,11 @@ ENV PORT=3000
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
ENV UPLOAD_DIR=/app/uploads/announcements
|
||||
|
||||
COPY --from=builder /app ./
|
||||
|
||||
RUN mkdir -p /app/uploads/announcements && chmod +x /app/scripts/start-production.sh
|
||||
|
||||
RUN addgroup -S -g 1001 app && adduser -S -u 1001 -G app app
|
||||
COPY --from=builder --chown=app:app /app/.next/standalone ./
|
||||
COPY --from=builder --chown=app:app /app/.next/static ./.next/static
|
||||
COPY --from=builder --chown=app:app /app/public ./public
|
||||
RUN mkdir -p /app/uploads/announcements/announcements /app/.next/cache && chown -R app:app /app/uploads /app/.next/cache
|
||||
USER app
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["./scripts/start-production.sh"]
|
||||
CMD ["sh", "scripts/start-production.sh"]
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Deployment und Mailversand
|
||||
|
||||
Die aktuelle Anleitung steht in [README.md](README.md), die Konfigurationsvorlage in [production.env.example](production.env.example).
|
||||
|
||||
Der Compose-Dienst `migrate` initialisiert das Schema über versionierte Migrationen und stellt den separaten Runtime-Zugang bereit. Die App startet erst nach erfolgreicher Initialisierung. `prisma db push`, Demo-Seeding und historische SQL-Upgrades sind im Produktionsstart nicht vorgesehen.
|
||||
|
||||
Für Resend müssen Versanddomain, `RESEND_API_KEY` und `EMAIL_FROM` gültig konfiguriert sein. `ADMIN_EMAIL` ist das Ziel für das Kontaktformular. Die drei öffentlichen Basis-URLs müssen übereinstimmen, damit Einladungs- und Bestätigungslinks auf die richtige Anwendung zeigen. Der Notdienst-Worker startet im App-Container mit `NOTDIENST_JOB_SECRET`; kein zusätzlicher Cron-Dienst ist erforderlich.
|
||||
+54
-39
@@ -1,55 +1,70 @@
|
||||
# Kita-Planer Deployment
|
||||
# Sicherer Betrieb und Rollout
|
||||
|
||||
Dieses Verzeichnis enthaelt die ausfuellbaren Vorlagen fuer das Production-Deployment.
|
||||
Die Anwendung startet ohne Schemaänderungen und ohne Demo-Seeding. Datenbankmigrationen laufen separat mit einer administrativen Rolle. Der App-Container verwendet ausschließlich `kita_runtime`, läuft als UID/GID 1001 und hat ein schreibgeschütztes Dateisystem mit persistenten Upload- und Cache-Volumes.
|
||||
|
||||
## Dateien
|
||||
## Konfiguration
|
||||
|
||||
- `production.env.example`: Vorlage fuer alle benoetigten Environment Variables.
|
||||
- `production-checklist.md`: Checkliste fuer Domain, Datenbank, Auth, Mail, Uploads und Rechtliches.
|
||||
- `../Dockerfile`: Container-Build fuer Coolify oder andere Docker-Hosts.
|
||||
- `../docker-compose.coolify.yml`: Compose-Vorlage fuer Coolify mit required Environment Variables.
|
||||
Werte aus `production.env.example` als Hosting-Secrets hinterlegen. Im Compose-Stack erzeugt der Dienst `migrate` automatisch ein separates Runtime-Passwort im privaten Secret-Volume, wendet die Migrationen an, vergibt die eingeschränkten DB-Rechte und bereitet die Upload-/Cache-Volumes vor. Danach startet `app` mit UID/GID 1001. Administrative Zugangsdaten werden im App-Service ausdrücklich mit dem harmlosen Platzhalter `unavailable-in-app` überschrieben (leere Werte entfernt Coolify bei der Verarbeitung), damit eine zusätzliche globale `env_file`-Weitergabe durch das Hosting sie nicht in den App-Container einschleust. Der Start entfernt diese Variablen zusätzlich vor dem App- und Worker-Prozess. Das Eigentümerpasswort steht nur PostgreSQL und dem Initialisierungsdienst zur Verfügung. Für manuelle CLI-Befehle außerhalb von Compose bleibt `DATABASE_URL` die jeweilige administrative oder eingeschränkte URL. Keine echten Secrets im Repository speichern.
|
||||
|
||||
## Empfohlener Ablauf mit Coolify und Gitea
|
||||
`AUTH_URL`, `NEXTAUTH_URL` und `NEXT_PUBLIC_SITE_URL` müssen dieselbe kanonische HTTPS-Origin verwenden. Der Reverse Proxy terminiert TLS, routet intern auf App-Port 3000 und überschreibt weitergeleitete Host-/IP-Header. `TRUSTED_CLIENT_IP_HEADER` nur setzen, wenn der Proxy den gewählten Header (`x-real-ip` oder `cf-connecting-ip`) zuverlässig überschreibt. Ohne diese Einstellung gelten weiterhin gemeinsame globale und identitätsbezogene Datenbanklimits. Proxyseitig Body-Limit von höchstens 26 MiB, Timeouts und zusätzliche Request-Limits setzen.
|
||||
|
||||
1. Repository in deine Gitea-Instanz pushen.
|
||||
2. In Coolify eine neue Application aus diesem Gitea-Repository anlegen.
|
||||
3. Als Build Pack `Docker Compose` waehlen.
|
||||
4. Als Compose-Datei `docker-compose.coolify.yml` eintragen.
|
||||
5. Die bestehende Coolify-Postgres-Datenbank ueber ihre interne `DATABASE_URL` verbinden.
|
||||
6. Environment Variables aus `production.env.example` in Coolify eintragen.
|
||||
7. Domain auf den `app`-Service mit internem Port `3000` zeigen lassen.
|
||||
8. Deploy starten.
|
||||
Compose startet PostgreSQL standardmäßig intern. Bei einer bereits extern verwalteten Coolify-Datenbank den Stack entsprechend anpassen und deren interne URL verwenden; niemals versehentlich einen neuen leeren Datenbankdienst als Ersatz anschließen. pgAdmin ist nur im Profil `maintenance` und nur auf Loopback verfügbar; Zugriff über SSH-Tunnel.
|
||||
|
||||
Beim Container-Start fuehrt `scripts/start-production.sh` automatisch aus:
|
||||
## Neustart mit leerer Datenbank
|
||||
|
||||
```bash
|
||||
npx prisma db push
|
||||
Wenn vorhandene Daten ausdrücklich löschbare Testdaten sind: ausschließlich die zu dieser Installation gehörenden Datenbank- und Upload-Volumes zurücksetzen. Danach genügt ein normales Deployment mit `docker compose -f docker-compose.coolify.yml up -d --build app`. Es sind weder eine Baseline-Markierung noch manuelle Schema-Upgrades oder Demo-Seeding erforderlich. Der Initialisierungsdienst läuft vor der App; ein Fehler verhindert deren Start. Bestehende produktive Daten erfordern dagegen die unten beschriebene Vorbereitung.
|
||||
|
||||
Im Normalbetrieb bleiben Datenbank, Uploads, Cache und Runtime-Secret-Volume bei Deployments bestehen. Das Runtime-Passwort wird bei einem normalen Neustart wiederverwendet. Niemals die Datenbank als Startnebenwirkung löschen.
|
||||
|
||||
## Bestehende Installation aktualisieren
|
||||
|
||||
1. Datenbank **und** Upload-Volume sichern und Wiederherstellung überprüfen. Wartungsfenster ankündigen und alte App stoppen: das neue Schema und der neue Code gehören zusammen.
|
||||
2. Den Zustand der bestehenden Datenbank mit `prisma/migrations/20261009000000_baseline/migration.sql` vergleichen. Die Baseline bildet das bisherige Schema ab. Bei Abweichungen zuerst die Unterschiede gezielt klären; eine Baseline-Markierung prüft das Schema nicht automatisch.
|
||||
3. `scripts/check-tenant-integrity.sql` mit `psql "$MIGRATION_DATABASE_URL" -v ON_ERROR_STOP=1 -f scripts/check-tenant-integrity.sql` ausführen. **Keine Ergebniszeilen** bedeutet, dass keine der geprüften widersprüchlichen Tenant-Verknüpfungen vorliegt. Ergebnisse vor der Migration fachlich korrigieren; keine Daten automatisch einem anderen Mandanten zuweisen.
|
||||
4. **Nur für eine bestehende, zur Baseline passende Datenbank** einmal die Baseline als bereits angewendet markieren. Bei einer leeren neuen Datenbank diesen Schritt auslassen.
|
||||
5. Alle weiteren Migrationen anwenden, Runtime-Rolle bereitstellen und Größenmetadaten vorhandener Anhänge nachtragen.
|
||||
6. Eigentümer bestehender Upload-/Cache-Volumes auf UID/GID 1001 vorbereiten, dann die neue App starten. Stichproben mit zwei verschiedenen Kitas und den echten E-Mail-Flows prüfen.
|
||||
|
||||
Compose-Beispiele (Environment-Secrets vorher bereitstellen):
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.coolify.yml build app migrate
|
||||
# NUR bei bestehender, zuvor geprüfter Baseline-Datenbank:
|
||||
docker compose -f docker-compose.coolify.yml run --rm migrate npx prisma migrate resolve --applied 20261009000000_baseline
|
||||
# Initialisierung läuft automatisch vor der App:
|
||||
docker compose -f docker-compose.coolify.yml up -d app
|
||||
```
|
||||
|
||||
Coolify erkennt Variablen aus `docker-compose.coolify.yml` und zeigt required Variablen
|
||||
wie `DATABASE_URL`, `AUTH_SECRET`, `AUTH_URL`, `NEXTAUTH_URL`, `NEXT_PUBLIC_SITE_URL`,
|
||||
`RESEND_API_KEY`, `EMAIL_FROM` und `ADMIN_EMAIL` in der UI an.
|
||||
Die Baseline-Markierung benötigt bei einem manuellen Aufruf eine administrative `DATABASE_URL`; für eine leere Datenbank entfällt sie vollständig. Vorhandene Uploads müssen vor dem Start kontrolliert und ihre Größen unter administrativem Zugang nachgetragen werden. Für bestehende root-eigene Unterverzeichnisse ist eine gezielte Eigentümerkorrektur nötig; die Initialisierung bereitet die Basisverzeichnisse vor.
|
||||
|
||||
## Welche Coolify-Postgres-URL?
|
||||
Bei einem Rollback nach Migration zuerst Kompatibilität prüfen; das alte Image allein zurückzusetzen reicht wegen neuer Pflichtfelder nicht aus. Im Zweifel das geprüfte Backup von Datenbank und Dateien gemeinsam wiederherstellen.
|
||||
|
||||
Wenn die App und die Postgres-DB im selben Coolify-Projekt/Netzwerk laufen, nimm
|
||||
die interne Datenbank-URL aus Coolify, nicht die oeffentliche externe URL. Das ist
|
||||
stabiler und vermeidet unnoetigen Traffic ueber den Host.
|
||||
## Auswirkungen auf bestehende Konten
|
||||
|
||||
Das Format bleibt:
|
||||
Alle JWT-Sitzungen vor diesem Release werden ungültig; erneute Anmeldung ist erforderlich. Administrative Sperren entwerten auch bei späterer Entsperrung dauerhaft die alten Sitzungen. Gründerkonten ohne Kita und ohne echte E-Mail-Prüfung registrieren sich mit derselben Adresse erneut und bestätigen den Link. Bereits bestehende Kita-Gründer behalten ihre bisherige Verifizierung; deren historische Adressen werden dadurch nicht nachträglich als echte Mailbox-Bestätigung nachgewiesen.
|
||||
|
||||
```txt
|
||||
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
|
||||
Neue Registrierungen bestätigen zuerst die E-Mail-Adresse, wählen anschließend ihr Passwort und erstellen erst danach eine Kita. Beim Ändern einer Elternadresse werden Passwort und bisherige Sitzungen entwertet; die neue Adresse erhält eine Einladung zum Festlegen eines neuen Passworts. Kita-Admins können die Einladung erneut senden. Neue Registrierungslinks gelten 30 Minuten, Einladungen sieben Tage und Notdienst-Rückmeldelinks bis zum Ende des jeweiligen Einsatzes; eine gemeinsame Haushaltsantwort kann nur einmal gespeichert werden. Sperren entwerten vorhandene Rückmeldelinks dauerhaft. Die öffentlichen Token-Antworten zeigen nur die benötigten Einsatzangaben. Bestehende UUID-Links bleiben innerhalb ihrer Laufzeit kompatibel. Zwei-Faktor-Anmeldung ist auf ausdrücklichen Wunsch vorerst nicht eingeführt.
|
||||
|
||||
## Dateien und Wartung
|
||||
|
||||
`UPLOAD_DIR` bezeichnet die bisherige Basis; die Anwendung ergänzt `announcements`. Compose verwendet unverändert `/app/uploads/announcements/announcements`. Backfill muss genau dieselben Dateien sehen. Fehlende Dateien werden mit Größe 0 erfasst und als Anzahl gemeldet: Ursache und Datenverlust prüfen. Solange Größenwerte `NULL` sind, blockiert die Anwendung neue Anhänge, damit das Gesamtlimit nicht umgangen werden kann.
|
||||
|
||||
Grenzen: 10 MiB pro Datei, fünf Dateien und 25 MiB pro Nachricht; standardmäßig 256 MiB pro Kita und 10 GiB insgesamt, konfigurierbar über die beiden Quota-Variablen. Erlaubt sind PDF, PNG und JPEG mit passenden Dateisignaturen und Endungen. Das ist keine Virenprüfung oder vollständige PDF-Bereinigung. Downloads erfordern Sitzung, Consent und die passende Kita; sie werden als Anhang ausgeliefert.
|
||||
|
||||
`npm run uploads:cleanup` zeigt zunächst nur verwaiste Dateien mit mindestens 24 Stunden Alter. Nach Prüfung entfernt `npm run uploads:cleanup -- --delete` diese Dateien. Backups, Speicherüberwachung und eine Aufbewahrungs-/Löschstrategie für Backups separat einrichten. Dateien gelöschter Datensätze werden auch unmittelbar bestmöglich entfernt.
|
||||
|
||||
Die SQL-Migrationen ergänzen **41 zusammengesetzte Tenant-Fremdschlüssel**, die Prisma wegen der vorhandenen optionalen Cascade-/SetNull-Beziehungen nicht vollständig abbildet. Zukünftige generierte Migrationen auf unbeabsichtigtes Entfernen dieser Constraints prüfen. Kein `prisma db push` auf verwalteten Datenbanken einsetzen. Runtime-Grants nach zukünftigen Migrationen erneut bereitstellen.
|
||||
|
||||
## Verifikation und Updates
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run build:prod
|
||||
npx tsc --noEmit
|
||||
npm run lint -- --quiet
|
||||
npm audit --omit=dev
|
||||
```
|
||||
|
||||
## Wichtige Hinweise
|
||||
Die Integrationstests setzen eine ausdrücklich isolierte lokale PostgreSQL-Datenbank namens `kita_security_test` voraus; `SECURITY_TEST_DATABASE_URL` darf keine Anwendungsdaten enthalten. `npm run test:security` prüft Aktionen und echte DB-Transaktionen. `npm run test:security:http` benötigt den Production-Server auf localhost:3057 mit derselben Testdatenbank, `UPLOAD_DIR` und dem im Test dokumentierten Test-Secret. Niemals dieses Test-Secret in Produktion verwenden.
|
||||
|
||||
- Das aktuelle Projekt nutzt noch `prisma db push` statt versionierter Prisma-Migrationen.
|
||||
Fuer den ersten MVP-Deploy ist das praktikabel, fuer laengerfristigen Betrieb sollten
|
||||
Migrationen eingefuehrt werden.
|
||||
- `UPLOAD_DIR` muss persistent sein. Die Coolify-Compose-Datei mountet dafuer ein
|
||||
Docker-Volume nach `/app/uploads`.
|
||||
- `NEXT_PUBLIC_SITE_URL` muss die echte Domain enthalten, damit OpenGraph-Bilder in
|
||||
WhatsApp, LinkedIn und Co. korrekt als absolute URL aufgeloest werden.
|
||||
- `NEXT_PUBLIC_SITE_URL` wird auch als Build-Arg an Docker uebergeben. In Coolify sollte
|
||||
diese Variable deshalb fuer Build und Runtime verfuegbar sein.
|
||||
Docker-Images sind auf Digests fixiert. Neue Sicherheitsreleases regelmäßig prüfen und die Digests bewusst aktualisieren. Zum Prüfzeitpunkt verbleibt eine ungepatchte `braces`-Schwachstelle in der Entwicklungs-Lint-Kette; `npm audit --force` löst sie nicht sinnvoll. Der Runtime-Audit ist ohne bekannte Findings. NextAuth bleibt eine Beta-Abhängigkeit und benötigt weiterhin Update-Beobachtung.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Use with docker-compose.coolify.yml for a local production-like installation.
|
||||
# Both services are reachable only from this computer.
|
||||
services:
|
||||
app:
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
postgres:
|
||||
ports:
|
||||
- "127.0.0.1:5433:5432"
|
||||
@@ -1,60 +1,39 @@
|
||||
# Production Checklist
|
||||
# Production-Checkliste
|
||||
|
||||
## 1. Domain & Basis-URLs
|
||||
## Vor dem Rollout mit bestehenden Daten
|
||||
|
||||
- [ ] Produktionsdomain festlegen: `https://[deine-domain.de]`
|
||||
- [ ] `NEXT_PUBLIC_SITE_URL` auf die Produktionsdomain setzen
|
||||
- [ ] `AUTH_URL` und `NEXTAUTH_URL` auf die Produktionsdomain setzen
|
||||
- [ ] Nach Deployment die WhatsApp-/LinkedIn-Vorschau mit der finalen URL testen
|
||||
Bei einem ausdrücklich genehmigten Reset löschbarer Testdaten entfallen Backup-Übernahme, Baseline-Markierung und Upload-Backfill. Nach dem gezielten Reset initialisiert das normale Deployment den leeren Stand.
|
||||
|
||||
## 2. Datenbank
|
||||
- [ ] Datenbank und Uploads gesichert; Wiederherstellung geprüft.
|
||||
- [ ] Alte App gestoppt; Wartungsfenster und erneute Anmeldung angekündigt.
|
||||
- [ ] Bestehendes Schema mit Baseline verglichen; Tenant-Preflight ohne Befunde.
|
||||
- [ ] Baseline nur bei bestehender passender DB markiert; anschließend alle Migrationen angewendet.
|
||||
- [ ] Initialisierungsdienst erfolgreich; App verwendet automatisch die eingeschränkte Runtime-Rolle.
|
||||
- [ ] Upload-Größen nachgetragen; gemeldete fehlende Dateien geprüft.
|
||||
- [ ] Upload- und Cache-Volumes für UID/GID 1001 beschreibbar; Upload-Pfad unverändert.
|
||||
|
||||
- [ ] Interne `DATABASE_URL` der bestehenden Coolify-Postgres-DB kopieren
|
||||
- [ ] `DATABASE_URL` in der Coolify-App eintragen
|
||||
- [ ] Beim ersten App-Start wird das Schema automatisch mit `npx prisma db push --skip-generate` angewendet
|
||||
- [ ] Fuer spaetere Releases idealerweise Prisma-Migrationen einfuehren
|
||||
## Hosting und Konfiguration
|
||||
|
||||
## 3. Auth & Sicherheit
|
||||
- [ ] Drei öffentliche Basis-URLs auf dieselbe kanonische HTTPS-Origin gesetzt.
|
||||
- [ ] Starkes `AUTH_SECRET`; echte Secrets nur in Hosting-Konfiguration.
|
||||
- [ ] TLS und Proxy-Header korrekt; kein öffentlicher DB-/App-/pgAdmin-Port.
|
||||
- [ ] Request-Limits, Timeouts und Upload-Body-Limit am Proxy eingerichtet.
|
||||
- [ ] Trusted-IP-Header nur bei garantierter Überschreibung aktiviert.
|
||||
- [ ] Maildomain bei Resend verifiziert; Produktionsabsender gesetzt.
|
||||
- [ ] Optionale Analytics nur auf öffentlichen Marketingseiten; keine Token-/Login-/Dashboard-Daten.
|
||||
- [ ] Upload-Speicher und Backups überwacht; Löschfristen festgelegt.
|
||||
- [ ] Impressum und Datenschutztexte an tatsächliche Betreiber/Anbieter angepasst.
|
||||
|
||||
- [ ] `AUTH_SECRET` neu generieren: `openssl rand -base64 32`
|
||||
- [ ] Keine `.env`-Dateien mit echten Secrets committen
|
||||
- [ ] Dashboard ist per Metadata auf `noindex,nofollow` gesetzt
|
||||
- [ ] Produktionsdomain auf HTTPS betreiben
|
||||
## Nach dem Rollout
|
||||
|
||||
## 4. Mail
|
||||
- [ ] Anmeldung und Registrierung mit Mailbox-Bestätigung getestet.
|
||||
- [ ] Einladungen, Adressänderung und erneutes Senden getestet.
|
||||
- [ ] Administrative Sperre entwertet bestehende Sitzung; Entsperrung verlangt neue Anmeldung.
|
||||
- [ ] Zwei getrennte Kitas: Anhänge, Kalender und Mutationen bleiben isoliert.
|
||||
- [ ] Anhänge heruntergeladen; Quotas und persistentes Volume geprüft.
|
||||
- [ ] Privates Dashboard ohne Analytics und ohne Cache; CSP ohne Browserfehler.
|
||||
- [ ] Kontakt-/Notdienst-Mailfluss und Fehlerbehandlung geprüft.
|
||||
- [ ] Build, Lint, Typprüfung, Sicherheitstests und Runtime-Audit erfolgreich.
|
||||
- [ ] Offenes Entwicklungs-Advisory und fixierte Image-Digests weiter beobachten.
|
||||
|
||||
- [ ] Eigene Versanddomain bei Resend verifizieren
|
||||
- [ ] `RESEND_API_KEY` fuer Produktion setzen
|
||||
- [ ] `EMAIL_FROM` auf eine verifizierte Absenderadresse setzen
|
||||
- [ ] `ADMIN_EMAIL` fuer Kontaktformular setzen
|
||||
- [ ] Kontaktformular und Einladung/E-Mail-Flows einmal in Produktion testen
|
||||
|
||||
## 5. Uploads
|
||||
|
||||
- [ ] Coolify-Volume `kita_planer_uploads` fuer `/app/uploads` verwenden
|
||||
- [ ] Sicherstellen, dass Uploads nicht aus Versehen oeffentlich ausgeliefert werden
|
||||
- [ ] Backup-Strategie fuer Uploads klaeren
|
||||
|
||||
## 6. Rechtliches
|
||||
|
||||
- [ ] Platzhalter im Impressum ersetzen
|
||||
- [ ] Platzhalter in der Datenschutzerklaerung ersetzen
|
||||
- [ ] Hosting-Anbieter und Mail-Anbieter in Datenschutztext eintragen
|
||||
- [ ] Rechtliche Texte vor Livegang pruefen lassen
|
||||
|
||||
## 7. Build & Smoke Test
|
||||
|
||||
- [ ] Dependencies installieren: `npm ci`
|
||||
- [ ] Production Build erstellen: `npm run build:prod`
|
||||
- [ ] App starten: `npm run start:prod`
|
||||
- [ ] Startseite, Login, Dashboard und Kontaktformular testen
|
||||
|
||||
## 8. Coolify
|
||||
|
||||
- [ ] Code nach Gitea pushen
|
||||
- [ ] In Coolify eine Application aus dem Gitea-Repository anlegen
|
||||
- [ ] Build Pack `Docker Compose` waehlen
|
||||
- [ ] Compose-Datei `docker-compose.coolify.yml` verwenden
|
||||
- [ ] Environment Variables in Coolify eintragen, nicht ins Repo committen
|
||||
- [ ] Domain auf den `app`-Service und Container-Port `3000` routen
|
||||
- [ ] Upload-Volume `kita_planer_uploads` bleibt zwischen Deployments erhalten
|
||||
Details und Befehle stehen in [README.md](README.md). Lokale Tests ersetzen nicht die Kontrolle der produktiven TLS-, Proxy-, Backup-, Mail- und Container-Konfiguration.
|
||||
|
||||
@@ -11,6 +11,10 @@ POSTGRES_DB="kita_planer"
|
||||
POSTGRES_USER="kita_planer"
|
||||
POSTGRES_PASSWORD="[GENERATE_ME]"
|
||||
|
||||
# Der Initialisierungsdienst erzeugt automatisch einen separaten Runtime-Zugang.
|
||||
# Keine zusätzlichen APP_DATABASE_URL-/Passwort-Secrets nötig.
|
||||
# Passwort wird nur im privaten kita_planer_runtime_secrets-Volume gespeichert.
|
||||
|
||||
# pgAdmin im Coolify-Compose-Stack
|
||||
PGADMIN_DEFAULT_EMAIL="[admin@deine-domain.de]"
|
||||
PGADMIN_DEFAULT_PASSWORD="[GENERATE_ME]"
|
||||
@@ -36,9 +40,22 @@ RESEND_API_KEY="re_[PRODUCTION_API_KEY]"
|
||||
EMAIL_FROM="Kita-Planer <[absender@deine-domain.de]>"
|
||||
ADMIN_EMAIL="[kontakt@deine-domain.de]"
|
||||
|
||||
# Automatische Notdienst-Fristpruefung im App-Container.
|
||||
# Eigenes Secret, mindestens 32 Zeichen; generieren mit: openssl rand -hex 32
|
||||
NOTDIENST_JOB_SECRET="[GENERATE_ME]"
|
||||
|
||||
# Persistenter Upload-Speicher fuer Anhaenge vom Schwarzen Brett.
|
||||
# Muss auf dem Server dauerhaft erhalten bleiben und darf nicht im Repo liegen.
|
||||
UPLOAD_DIR="/var/lib/kita-planer/uploads/announcements"
|
||||
|
||||
# Optional: Nur bewusst fuer initiales Demo-Seeding in Produktion setzen.
|
||||
# ALLOW_DATABASE_SEED="true"
|
||||
# Standard: 256 MiB je Kita, 10 GiB insgesamt. Compose verwendet diese Werte.
|
||||
UPLOAD_TENANT_QUOTA_BYTES="268435456"
|
||||
UPLOAD_GLOBAL_QUOTA_BYTES="10737418240"
|
||||
|
||||
# Compose setzt UPLOAD_DIR fest auf /app/uploads/announcements.
|
||||
# Die Anwendung ergänzt /announcements: bestehende Dateien liegen dort unter
|
||||
# /app/uploads/announcements/announcements. Diesen Pfad beim Backfill beibehalten.
|
||||
|
||||
# Demo-Seeding ist in Produktion deaktiviert.
|
||||
# Nur hinter einem Proxy setzen, der diesen Header überschreibt:
|
||||
# TRUSTED_CLIENT_IP_HEADER="x-real-ip"
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
-- Additives Upgrade für einen Personalbereich einschließlich vorhandener Mail-Erweiterung.
|
||||
-- Einmalig vor dem Start der neuen Anwendung ausführen, sofern nicht prisma db push verwendet wird.
|
||||
BEGIN;
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotdienstAlarmStatus" AS ENUM ('PENDING', 'CONFIRMED', 'DECLINED', 'LATE_CONFIRMATION', 'REVIEW_REQUIRED', 'CANCELLED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "notdienst_alerts" ADD COLUMN "alarmId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarms" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"assignmentId" TEXT,
|
||||
"activeAssignmentId" TEXT,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"familyName" TEXT NOT NULL,
|
||||
"childName" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"wholeDay" BOOLEAN NOT NULL DEFAULT true,
|
||||
"startMinute" INTEGER,
|
||||
"endMinute" INTEGER,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"deadline" TIMESTAMP(3) NOT NULL,
|
||||
"status" "NotdienstAlarmStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"triggeredById" TEXT,
|
||||
"triggeredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"respondedById" TEXT,
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
"responseSource" TEXT,
|
||||
"escalatedAt" TIMESTAMP(3),
|
||||
"educatorId" TEXT,
|
||||
"notes" TEXT,
|
||||
"cancelledAt" TIMESTAMP(3),
|
||||
"cancelReason" TEXT,
|
||||
|
||||
CONSTRAINT "notdienst_alarms_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_recipients" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"token" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_recipients_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_notifications" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventKey" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"readAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "notdienst_alarm_notifications_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_emails" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventKey" TEXT NOT NULL,
|
||||
"kind" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"skippedAt" TIMESTAMP(3),
|
||||
"leaseUntil" TIMESTAMP(3),
|
||||
"failed" BOOLEAN NOT NULL DEFAULT false,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_emails_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_history" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"action" TEXT NOT NULL,
|
||||
"details" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_history_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarms_activeAssignmentId_key" ON "notdienst_alarms"("activeAssignmentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarms_kitaId_date_idx" ON "notdienst_alarms"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarms_status_deadline_idx" ON "notdienst_alarms"("status", "deadline");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_recipients_token_key" ON "notdienst_alarm_recipients"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_recipients_alarmId_userId_key" ON "notdienst_alarm_recipients"("alarmId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_notifications_userId_readAt_idx" ON "notdienst_alarm_notifications"("userId", "readAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_notifications_alarmId_userId_eventKey_key" ON "notdienst_alarm_notifications"("alarmId", "userId", "eventKey");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_emails_sentAt_skippedAt_createdAt_idx" ON "notdienst_alarm_emails"("sentAt", "skippedAt", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_emails_alarmId_userId_eventKey_key" ON "notdienst_alarm_emails"("alarmId", "userId", "eventKey");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_history_alarmId_createdAt_idx" ON "notdienst_alarm_history"("alarmId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_assignmentId_fkey" FOREIGN KEY ("assignmentId") REFERENCES "notdienst_assignments"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_recipients" ADD CONSTRAINT "notdienst_alarm_recipients_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_recipients" ADD CONSTRAINT "notdienst_alarm_recipients_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_notifications" ADD CONSTRAINT "notdienst_alarm_notifications_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_notifications" ADD CONSTRAINT "notdienst_alarm_notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_emails" ADD CONSTRAINT "notdienst_alarm_emails_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_emails" ADD CONSTRAINT "notdienst_alarm_emails_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_history" ADD CONSTRAINT "notdienst_alarm_history_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,37 @@
|
||||
-- Nur E-Mail-Erweiterung für einen bereits mit 043fed2 eingeführten Personalbereich.
|
||||
-- Alternative zu prisma db push, nicht zusätzlich oder mehrfach ausführen.
|
||||
BEGIN;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "staffDecisionEmails" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_emails" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"toAdmins" BOOLEAN NOT NULL DEFAULT false,
|
||||
"subject" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"inviteToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"skippedAt" TIMESTAMP(3),
|
||||
"leaseUntil" TIMESTAMP(3),
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"failed" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "staff_emails_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_emails_profileId_sentAt_skippedAt_idx" ON "staff_emails"("profileId", "sentAt", "skippedAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,286 @@
|
||||
-- Einmalige Einführung des vollständigen Personalbereichs inklusive E-Mails ab ec3f4f9.
|
||||
-- Alternative zu prisma db push, nicht zusätzlich oder mehrfach ausführen.
|
||||
BEGIN;
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffRequestStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'CANCEL_REQUESTED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffLeaveKind" AS ENUM ('VACATION', 'TIME_OFF', 'SICKNESS');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffWeekStatus" AS ENUM ('DRAFT', 'SUBMITTED', 'APPROVED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "staffDecisionEmails" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_profiles" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"educatorId" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"employmentStart" DATE NOT NULL,
|
||||
"employmentEnd" DATE,
|
||||
"trackingStart" DATE NOT NULL,
|
||||
"openingMinutes" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_profiles_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_emails" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"toAdmins" BOOLEAN NOT NULL DEFAULT false,
|
||||
"subject" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"inviteToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"skippedAt" TIMESTAMP(3),
|
||||
"leaseUntil" TIMESTAMP(3),
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"failed" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "staff_emails_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_work_patterns" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"effectiveFrom" DATE NOT NULL,
|
||||
"dailyMinutes" INTEGER[],
|
||||
|
||||
CONSTRAINT "staff_work_patterns_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_day_overrides" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"minutes" INTEGER NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_day_overrides_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_holidays" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_holidays_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leave_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"year" INTEGER NOT NULL,
|
||||
"entitlementUnits" INTEGER NOT NULL,
|
||||
"carryUnits" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "staff_leave_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leaves" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"kind" "StaffLeaveKind" NOT NULL,
|
||||
"status" "StaffRequestStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"startDate" DATE NOT NULL,
|
||||
"endDate" DATE NOT NULL,
|
||||
"halfDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"minutes" INTEGER,
|
||||
"note" TEXT,
|
||||
"decisionNote" TEXT,
|
||||
"requestedById" TEXT NOT NULL,
|
||||
"reviewedById" TEXT,
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_leaves_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leave_days" (
|
||||
"id" TEXT NOT NULL,
|
||||
"leaveId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"vacationUnits" INTEGER NOT NULL DEFAULT 0,
|
||||
"creditMinutes" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_leave_days_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_time_entries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"startMinute" INTEGER NOT NULL,
|
||||
"endMinute" INTEGER NOT NULL,
|
||||
"breakMinutes" INTEGER NOT NULL DEFAULT 0,
|
||||
"note" TEXT,
|
||||
|
||||
CONSTRAINT "staff_time_entries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_weeks" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"weekStart" DATE NOT NULL,
|
||||
"status" "StaffWeekStatus" NOT NULL DEFAULT 'DRAFT',
|
||||
"submittedAt" TIMESTAMP(3),
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"reviewedById" TEXT,
|
||||
"decisionNote" TEXT,
|
||||
"dailySnapshot" JSONB,
|
||||
|
||||
CONSTRAINT "staff_weeks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_adjustments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"minutes" INTEGER NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_adjustments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_history" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"details" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_history_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_notifications" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"readAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_notifications_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_profiles_educatorId_key" ON "staff_profiles"("educatorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_profiles_userId_key" ON "staff_profiles"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_profiles_kitaId_idx" ON "staff_profiles"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_emails_profileId_sentAt_skippedAt_idx" ON "staff_emails"("profileId", "sentAt", "skippedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_work_patterns_profileId_effectiveFrom_key" ON "staff_work_patterns"("profileId", "effectiveFrom");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_day_overrides_profileId_date_key" ON "staff_day_overrides"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_holidays_kitaId_date_key" ON "staff_holidays"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_leave_accounts_profileId_year_key" ON "staff_leave_accounts"("profileId", "year");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_leaves_profileId_status_startDate_idx" ON "staff_leaves"("profileId", "status", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_leave_days_leaveId_date_key" ON "staff_leave_days"("leaveId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_time_entries_profileId_date_idx" ON "staff_time_entries"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_weeks_profileId_weekStart_key" ON "staff_weeks"("profileId", "weekStart");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_adjustments_profileId_date_idx" ON "staff_adjustments"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_history_profileId_createdAt_idx" ON "staff_history"("profileId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_notifications_userId_readAt_createdAt_idx" ON "staff_notifications"("userId", "readAt", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_educatorId_fkey" FOREIGN KEY ("educatorId") REFERENCES "educators"("id") ON DELETE NO ACTION ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_work_patterns" ADD CONSTRAINT "staff_work_patterns_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_day_overrides" ADD CONSTRAINT "staff_day_overrides_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_holidays" ADD CONSTRAINT "staff_holidays_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leave_accounts" ADD CONSTRAINT "staff_leave_accounts_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leaves" ADD CONSTRAINT "staff_leaves_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leave_days" ADD CONSTRAINT "staff_leave_days_leaveId_fkey" FOREIGN KEY ("leaveId") REFERENCES "staff_leaves"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_time_entries" ADD CONSTRAINT "staff_time_entries_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_weeks" ADD CONSTRAINT "staff_weeks_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_adjustments" ADD CONSTRAINT "staff_adjustments_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_history" ADD CONSTRAINT "staff_history_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_notifications" ADD CONSTRAINT "staff_notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_notifications" ADD CONSTRAINT "staff_notifications_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
COMMIT;
|
||||
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
image: postgres:16-alpine@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-kita_planer}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-kita_planer}
|
||||
@@ -27,7 +27,14 @@ services:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
HOSTNAME: 0.0.0.0
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-kita_planer}:${POSTGRES_PASSWORD:?}@postgres:5432/${POSTGRES_DB:-kita_planer}?schema=public
|
||||
# A nonempty sentinel survives hosting Compose parsers and blocks global env_file credentials.
|
||||
DATABASE_URL: "unavailable-in-app"
|
||||
MIGRATION_DATABASE_URL: "unavailable-in-app"
|
||||
APP_DATABASE_PASSWORD: "unavailable-in-app"
|
||||
POSTGRES_PASSWORD: "unavailable-in-app"
|
||||
PGADMIN_DEFAULT_PASSWORD: "unavailable-in-app"
|
||||
APP_DATABASE_PASSWORD_FILE: /app/runtime-secrets/database-password
|
||||
APP_DATABASE_NAME: ${POSTGRES_DB:-kita_planer}
|
||||
AUTH_SECRET: ${AUTH_SECRET:?}
|
||||
AUTH_URL: ${AUTH_URL:?}
|
||||
NEXTAUTH_URL: ${NEXTAUTH_URL:?}
|
||||
@@ -38,18 +45,61 @@ services:
|
||||
RESEND_API_KEY: ${RESEND_API_KEY:?}
|
||||
EMAIL_FROM: ${EMAIL_FROM:?}
|
||||
ADMIN_EMAIL: ${ADMIN_EMAIL:?}
|
||||
NOTDIENST_JOB_SECRET: ${NOTDIENST_JOB_SECRET:?}
|
||||
UPLOAD_DIR: /app/uploads/announcements
|
||||
UPLOAD_TENANT_QUOTA_BYTES: ${UPLOAD_TENANT_QUOTA_BYTES:-268435456}
|
||||
UPLOAD_GLOBAL_QUOTA_BYTES: ${UPLOAD_GLOBAL_QUOTA_BYTES:-10737418240}
|
||||
TRUSTED_CLIENT_IP_HEADER: ${TRUSTED_CLIENT_IP_HEADER:-}
|
||||
volumes:
|
||||
- kita_planer_uploads:/app/uploads
|
||||
- kita_planer_next_cache:/app/.next/cache
|
||||
- kita_planer_runtime_secrets:/app/runtime-secrets:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
expose:
|
||||
- "3000"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
pids_limit: 256
|
||||
mem_limit: 1g
|
||||
cpus: "1.0"
|
||||
restart: unless-stopped
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: migrator
|
||||
args:
|
||||
NEXT_PUBLIC_SITE_URL: ${NEXT_PUBLIC_SITE_URL:?}
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
POSTGRES_DB: ${POSTGRES_DB:-kita_planer}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-kita_planer}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?}
|
||||
APP_DATABASE_PASSWORD_FILE: /app/runtime-secrets/database-password
|
||||
UPLOAD_DIR: /app/uploads/announcements
|
||||
command: ["node", "scripts/initialize-production.mjs"]
|
||||
volumes:
|
||||
- kita_planer_uploads:/app/uploads
|
||||
- kita_planer_next_cache:/app/runtime-cache
|
||||
- kita_planer_runtime_secrets:/app/runtime-secrets
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
|
||||
pgadmin:
|
||||
image: dpage/pgadmin4:latest
|
||||
profiles: ["maintenance"]
|
||||
image: dpage/pgadmin4@sha256:c332c5f6dfba995d9ebc4af261d93506d6876085d712eaaa3defc8dd1a3f26de
|
||||
environment:
|
||||
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:?}
|
||||
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:?}
|
||||
@@ -61,10 +111,12 @@ services:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "80"
|
||||
- "127.0.0.1:5050:80"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
kita_planer_postgres_data:
|
||||
kita_planer_uploads:
|
||||
kita_planer_next_cache:
|
||||
kita_planer_runtime_secrets:
|
||||
kita_planer_pgadmin_data:
|
||||
|
||||
+2
-2
@@ -2,14 +2,14 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
image: postgres:16-alpine@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||
container_name: kita_planer_db
|
||||
environment:
|
||||
POSTGRES_USER: kita
|
||||
POSTGRES_PASSWORD: kita
|
||||
POSTGRES_DB: kita_planer
|
||||
ports:
|
||||
- "5433:5432"
|
||||
- "127.0.0.1:5433:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
# Kita-Planer – Funktionsübersicht und aktueller Stand
|
||||
|
||||
## Ergänzung vom 09.10.2026: Notdienstalarm
|
||||
|
||||
Der Notdienstalarm ist inzwischen umgesetzt. Admins und Koordination alarmieren die eingeteilte Familie für einen ganzen Tag oder ein Zeitfenster. Persönliche Rückmeldelinks erzeugen eine gemeinsame Haushaltsantwort; Dashboard-Hinweise, eine 30-Minuten-Frist, Klärungsbedarf, verspätete Freigabe, telefonische Korrektur, Stornierung, Versandstatus und Hintergrundprüfung sind angebunden. Aktive Alarme sperren Planumzuordnung und Diensttausche. Siehe [NOTDIENSTALARM.md](NOTDIENSTALARM.md) für Bedienung und benötigte Hosting-Konfiguration.
|
||||
|
||||
Die folgende ursprüngliche Bestandsaufnahme bleibt als historischer Stand erhalten; darin als offen bezeichnete Alarmfunktionen sind durch diese Ergänzung überholt.
|
||||
|
||||
Stand: **07.10.2026**
|
||||
|
||||
Geprüfter Ausgangsbranch: `codex/notdienst-swaps`
|
||||
|
||||
Geprüfter Commit: `ec3f4f933d42068c9d8446dc95de9815d5779238`
|
||||
|
||||
Dokumentationsbranch: `codex/funktionsinventar`
|
||||
|
||||
**Ergänzung vom 07.10.2026:** Auf `codex/personalbereich` wurde anschließend der Personalbereich für Arbeitszeit, Urlaub und Freizeitausgleich umgesetzt. Diese Bestandsaufnahme bleibt als Beschreibung des Ausgangsstands erhalten; der neue Umfang, Berechnungsregeln, Einrichtung und aktuelle Prüfungen stehen in [PERSONALBEREICH.md](PERSONALBEREICH.md). Die Aussagen unten zu fehlender Zeiterfassung, Accountverknüpfung und Tests beziehen sich auf den Ausgangscommit.
|
||||
|
||||
**Ergänzung vom 08.10.2026:** Der Personalbereich enthält jetzt auch Aktivierungsmails, Antrags- und Entscheidungshinweise sowie eine Abschalteinstellung im Fachkraftprofil. Der aktuelle Umfang und die Versandkonfiguration stehen ebenfalls in [PERSONALBEREICH.md](PERSONALBEREICH.md).
|
||||
|
||||
## 1. Grundlage der Prüfung
|
||||
|
||||
Diese Bestandsaufnahme beschreibt die im Repository vorhandenen Produktfunktionen. Geprüft wurden Seiten und Navigation, Formulare und Dialoge, Server Actions, API-Routen, Datenmodell, E-Mail-Anbindung und Betriebsdateien. Die Planung in `planung.md`, die UI-Liste in `UI-TODO.md` und der frühere Live-Testplan wurden mit dem aktuellen Code abgeglichen.
|
||||
|
||||
**„Vorhanden“ bedeutet hier: Oberfläche und zugehörige Verarbeitung sind im Code angebunden. Es bedeutet keine Bestätigung durch einen aktuellen Live-Test.** Es wurden keine Produktionsdaten verändert, keine E-Mails verschickt und keine Datenbankänderungen ausgeführt. Die tatsächliche Zustellung von E-Mails, das Verhalten im Browser und die produktive Konfiguration bleiben gesondert zu prüfen.
|
||||
|
||||
Status:
|
||||
|
||||
| Kennzeichnung | Bedeutung |
|
||||
| --- | --- |
|
||||
| Vorhanden | Im aktuellen Code als erreichbarer Ablauf umgesetzt. |
|
||||
| Teilweise | Funktion vorhanden, aber mit konkreten Einschränkungen oder fehlender Anbindung. |
|
||||
| Vorbereitet | Datenmodell, Komponente oder Aktion vorhanden; vollständiger Nutzerablauf fehlt. |
|
||||
| Offen | In der Planung vorgesehen, im geprüften Code nicht umgesetzt. |
|
||||
|
||||
## 2. Gesamtüberblick
|
||||
|
||||
Die Anwendung besitzt bereits eine breite MVP-Grundlage für mehrere unabhängige Kitas: Registrierung, Einrichtung, Familien und Kinder, Notdienst-Verfügbarkeiten und Planung, Diensttausch, Kalender, Mitbringlisten, Abwesenheiten, Kontaktdaten und Superadmin-Support. Einige beworbene Abläufe sind jedoch noch nicht vollständig nutzbar, insbesondere Alarmierung, Eltern-Rückmeldungen zu Events und die Anzeige des Schwarzen Bretts für Eltern.
|
||||
|
||||
| Bereich | Stand | Wichtigste Einschränkung |
|
||||
| --- | --- | --- |
|
||||
| Öffentliche Website und Kontakt | Vorhanden | Impressum und Datenschutz enthalten Platzhalter. |
|
||||
| Registrierung, Login, Kita-Einrichtung | Vorhanden | Kein selbstständiger Passwort-Reset; Modulschalter wirken nur teilweise. |
|
||||
| Dashboard | Vorhanden | News-, RSVP- und Alarm-Komponenten sind nicht eingebunden. |
|
||||
| Profil und eigene Kinder | Vorhanden | Persönlicher Name, E-Mail und Rolle sind im Profil nur lesbar. |
|
||||
| Familienverwaltung und feste Ämter | Vorhanden | Kein vollständiger Einladungs-Support mit erneutem Versand/Widerruf. |
|
||||
| Notdienst-Verfügbarkeiten | Vorhanden | Wochenenden und Schließtage werden nur in der Oberfläche ausgeschlossen. |
|
||||
| Notdienst-Planung | Vorhanden | Keine automatische Erinnerung und keine E-Mail bei Erstveröffentlichung. |
|
||||
| Notdienst-Tausch | Vorhanden | Nur Elternrolle kann neue Tauschanfragen starten. |
|
||||
| Notdienst-Alarmierung | Vorbereitet | Auslösebutton ist auf keiner Seite eingebunden. |
|
||||
| Kalender und Mitbringlisten | Vorhanden | Keine Kollisionsprüfung für Raumbuchungen; Mitbringsel nicht direkt bearbeitbar. |
|
||||
| Event-Teilnahme/RSVP | Teilweise | Verwaltung vorhanden, Eltern-Eingabe nicht in eine Seite eingebunden. |
|
||||
| Abwesenheiten | Vorhanden | Gruppenfilter verwendet eine künstliche Zuordnung. |
|
||||
| Schwarzes Brett | Teilweise | Veröffentlichung vorhanden, Elternanzeige und Lesestatus fehlen im aktuellen Dashboard. |
|
||||
| Adressbuch | Vorhanden | Opt-in gilt für Kontaktdaten; weitere Haushaltsdaten bleiben sichtbar. |
|
||||
| ErzieherInnen-Stammdaten | Vorhanden | Stammdatensatz und Benutzerrolle `ERZIEHER` sind getrennte Konzepte. |
|
||||
| Superadmin-Verwaltung | Vorhanden | Einladungszähler verwenden ein anderes Modell als der reale Einladungsablauf. |
|
||||
| Betrieb und Qualität | Teilweise | TypeScript erfolgreich, ESLint mit Fehlern; keine automatisierte Testsuite gefunden. |
|
||||
|
||||
## 3. Rollen und Zugriffsbereiche
|
||||
|
||||
| Rolle | Aktuelle Möglichkeiten |
|
||||
| --- | --- |
|
||||
| `SUPERADMIN` | Systemweite Kita-Übersicht, Kita-Diagnosen, Support-Aktionen und Audit-Protokoll. Standardmäßig ohne Kita-Zuordnung und mit eigener Oberfläche unter `/admin`. |
|
||||
| `ADMIN` | Verwaltung der eigenen Kita: Familien, Ämter, ErzieherInnen, Dienste, Meldungen, Kalender und Notdienst. Mit eigenem Haushalt auch Elternfunktionen nutzbar. |
|
||||
| `KOORDINATOR` | Notdienstplanung, Kalenderverwaltung, Event-Anmeldungen und Abwesenheitsübersicht. Mit eigenem Haushalt auch Verfügbarkeiten eintragbar. |
|
||||
| `ERZIEHER` | Dashboard, Kalender, Adressbuch, Profil und Abwesenheitsübersicht. Kein Zugriff auf die Notdienst-Eingabeseite. |
|
||||
| `ELTERN` | Eigener Haushalt/Kinder, Verfügbarkeiten, Kalender, Terminanfragen, Mitbringsel, Diensttausch, Abwesenheitsmeldungen und Adressbuch. |
|
||||
|
||||
Navigation und serverseitige Rollenprüfungen sind vorhanden. Die Rolle `ERZIEHER` existiert im Datenmodell und wird in Berechtigungen verwendet. Die ErzieherInnen-Verwaltung erstellt jedoch nur Namen als Stammdaten und keine Benutzerkonten. Ein regulärer Dialog zur Einladung von Erzieher-Accounts oder zur Vergabe von Admin-/Koordinatorrollen wurde nicht gefunden.
|
||||
|
||||
Quellen: [Navigation](../src/components/dashboard/sidebar-nav.tsx), [Zugriffsprüfungen](../src/lib/auth-utils.ts), [Datenmodell](../prisma/schema.prisma).
|
||||
|
||||
## 4. Funktionsinventar nach Bereich
|
||||
|
||||
### 4.1 Öffentliche Website und Kontakt
|
||||
|
||||
- Startseite mit Produktbeschreibung, Funktionsvorschauen, Rollenbeschreibung, Einstieg in Registrierung und Login sowie Kontaktbereich.
|
||||
- Fünf öffentliche Detailseiten: Notdienst-Planer, Kita-Kalender, Eltern-Adressbuch, Krankmeldung und Schwarzes Brett.
|
||||
- Kontaktformular für allgemeine Fragen, Demo-Anfragen und individuelles Setup.
|
||||
- Eingaben: Name, optionale Kita, E-Mail-Adresse, Anfrageart und Nachricht.
|
||||
- Versand einer Anfrage an den konfigurierten Kontakt-Empfänger und einer Bestätigung an die anfragende Person; passende Antwortadressen werden gesetzt.
|
||||
- Bot-Schutz durch ein unsichtbares Zusatzfeld und ein Limit von fünf Kontaktanfragen je IP-Adresse pro Stunde. Das Limit liegt im Arbeitsspeicher des jeweiligen Prozesses.
|
||||
- Sitemap, Robots-Datei und Metadaten für öffentliche Seiten.
|
||||
- Optionales Umami-Tracking über Umgebungsvariablen, auf eine Liste öffentlicher Seiten beschränkt. Suchparameter und URL-Fragmente werden ausgeschlossen; Do-Not-Track wird berücksichtigt.
|
||||
- Impressum und Datenschutzerklärung sind als Seiten vorhanden, enthalten aber noch Betreiber-, Hosting- und weitere Platzhalter.
|
||||
|
||||
Quellen: [Startseite](../src/app/page.tsx), [Feature-Inhalte](../src/lib/marketing/features.ts), [Kontaktaktion](../src/actions/contact.ts), [Analytics](../src/components/analytics/umami-analytics.tsx), [Impressum](../src/app/impressum/page.tsx), [Datenschutz](../src/app/datenschutz/page.tsx).
|
||||
|
||||
### 4.2 Registrierung, Anmeldung und Einrichtung
|
||||
|
||||
- Gründerregistrierung mit Vorname, Nachname, E-Mail-Adresse, Passwort und verpflichtender Datenschutzannahme.
|
||||
- Prüfung auf bereits verwendete E-Mail-Adressen und Passwort-Hashing mit bcrypt.
|
||||
- Gründer erhält zunächst die Adminrolle ohne Kita-Zuordnung und wird direkt angemeldet.
|
||||
- Kita-Einrichtung mit Name, eindeutigem Slug, Aktivierung von Notdienst/Kalender/Adressbuch und Mindestzahl an Verfügbarkeiten pro Kind.
|
||||
- Bei aktivem Notdienstmodul ist mindestens ein Verfügbarkeitstag erforderlich; die Einrichtung erlaubt höchstens 31.
|
||||
- Kita-Anlage und Zuordnung des Gründers erfolgen in einer Datenbanktransaktion; erneute Einrichtung desselben Kontos wird abgefangen.
|
||||
- Login mit E-Mail und Passwort, Rückleitung zu einer internen Zielseite und allgemeine Fehlermeldung bei falschen Zugangsdaten.
|
||||
- Abmeldung über Desktop-Navigation und mobiles Menü.
|
||||
- Nach zehn Fehlversuchen wird das betreffende Konto für 15 Minuten gesperrt; erfolgreicher Login setzt den Zähler zurück.
|
||||
- JWT-basierte Sessions mit Benutzer-, Kita-, Familien- und Rolleninformationen. Rolle und Zuordnungen werden bei weiteren Session-Aufrufen mit der Datenbank abgeglichen.
|
||||
- Geschützte Seiten leiten nicht angemeldete Personen zum Login und Gründer ohne Kita zur Einrichtung weiter.
|
||||
- Datenschutzannahme wird mit Zeitpunkt und Versionskennung gespeichert. Die Sonderseite für fehlende Zustimmung verweist auf Support; sie enthält kein Formular zum Nachholen der Zustimmung.
|
||||
|
||||
**Einschränkungen:** Kein Passwort-vergessen-/Passwort-ändern-Ablauf. Die Gründerregistrierung setzt `emailVerifiedAt` unmittelbar, ohne Bestätigungsmail. Ein allgemeines IP-Limit für Login oder Registrierung ist nicht angebunden; das Kontaktformular hat sein eigenes Limit.
|
||||
|
||||
Quellen: [Registrierung](../src/app/register/actions.ts), [Einrichtung](../src/app/onboarding/actions.ts), [Login](../src/app/login/actions.ts), [Authentifizierung](../src/auth.ts), [Proxy](../src/proxy.ts), [Consent-Seite](../src/app/onboarding/consent/page.tsx).
|
||||
|
||||
### 4.3 Dashboard und Navigation
|
||||
|
||||
- Begrüßung mit Kita-Namen, Benutzernamen und aktuellem Datum.
|
||||
- Kennzahlen zu Familien, aktiven Kindern, eingetragenen Notdienst-Verfügbarkeiten des Folgemonats und rechnerisch heute anwesenden Kindern.
|
||||
- Direktes Melden einer Kinderabwesenheit und Übersicht der laufenden/bevorstehenden eigenen Abwesenheiten.
|
||||
- Schnellzugriffe auf Familienverwaltung, Kalender, Notdienstplanung und Adressbuch. Die drei letztgenannten berücksichtigen die Modulschalter bei der Anzeige.
|
||||
- Hinweisdialog bei unvollständigem Profil: Telefon, Adresse sowie gegebenenfalls Haushalt und Kinder. Fortschritt wird angezeigt; der Hinweis kann im lokalen Browser dauerhaft ausgeblendet werden.
|
||||
- Rollenabhängige Seitenleiste und ein auf kleinen Bildschirmen aufklappbares Menü.
|
||||
|
||||
**Einschränkungen:** Die Notdienstkennzahl zählt Verfügbarkeitseinträge, keine tatsächlich besetzten Plantage. Schnellzugriffe auf Verwaltung werden nicht vollständig nach Rolle ausgeblendet; die Zielseiten besitzen Rollenprüfungen. Die Notdienst-Badge `4` in der Seitenleiste ist fest hinterlegt.
|
||||
|
||||
Quellen: [Dashboard](../src/app/dashboard/page.tsx), [Profilhinweis](../src/components/OnboardingDialog.tsx), [Dashboard-Rahmen](../src/components/dashboard/dashboard-shell.tsx).
|
||||
|
||||
### 4.4 Profil, Haushalt und eigene Kinder
|
||||
|
||||
- Anzeige von Name, E-Mail-Adresse, Rolle, Kita, Haushalt, angelegtem Konto und zugewiesenen festen Ämtern.
|
||||
- Bearbeiten von Telefonnummer, Straße, Postleitzahl und Ort.
|
||||
- Adressbuchfreigabe erteilen oder zurückziehen; Zeitpunkt der Freigabe wird gespeichert.
|
||||
- Eigenen Haushalt anlegen, wenn noch keiner zugeordnet ist.
|
||||
- Eigene Kinder anlegen, bearbeiten und löschen; Vor-/Nachname sowie optionales Geburtsdatum.
|
||||
- Bei Eingabe eines Geburtsdatums: gültiges Datum, nicht in der Zukunft, höchstens sieben Jahre zurück.
|
||||
- Datenänderungen an Kindern werden auf den eigenen Haushalt und die eigene Kita begrenzt.
|
||||
- Eigenes Konto nach Bestätigung löschen. Bestehen aktuelle oder zukünftige veröffentlichte Notdienstpflichten des Haushalts, wird die Selbstlöschung abgelehnt.
|
||||
- Beim letzten Benutzer eines Haushalts wird die Familie samt abhängigen Kindern gelöscht; bei weiteren Benutzern bleibt der Haushalt bestehen.
|
||||
|
||||
**Einschränkungen:** Name, E-Mail und Rolle lassen sich im persönlichen Profil nicht ändern. Eine Sperre der Kinderlöschung bei bestehenden Notdienstpflichten ist in `deleteMyChild` nicht vorhanden, obwohl die Kontolöschung diese Pflichten prüft.
|
||||
|
||||
Quellen: [Profilseite](../src/app/dashboard/profil/page.tsx), [Profilaktionen](../src/app/dashboard/profil/actions.ts).
|
||||
|
||||
### 4.5 Familienverwaltung, Eltern-Einladungen und feste Ämter
|
||||
|
||||
- Adminübersicht aller Familien mit Eltern und Kindern; Suche nach Familie, Eltern, E-Mail und Kindern.
|
||||
- Umschalten zwischen Tabelle und Karten.
|
||||
- Neue Familie mit einem oder zwei Elternteilen sowie einem bis zehn Kindern anlegen.
|
||||
- Familienname, Namen/E-Mail-Adressen der Eltern und Kindernamen bearbeiten.
|
||||
- Zweiten Elternteil ergänzen, neue Kinder hinzufügen und Kinder entfernen. Der Bearbeitungsablauf verlangt mindestens ein verbleibendes Kind und höchstens zwei Elternteile.
|
||||
- Neue Elternkonten erhalten die Rolle `ELTERN` und einen Einladungslink zur Passwortvergabe mit sieben Tagen Gültigkeit.
|
||||
- Aktivierung prüft Link, Ablaufdatum, Passwortlänge, Passwortbestätigung und Datenschutzannahme; optionales Adressbuch-Opt-in.
|
||||
- Nach Aktivierung werden Passwort und Zustimmungen gespeichert, der Token gelöscht und die Person direkt angemeldet.
|
||||
- Die Familienliste zeigt anhand der Kontoverifikation, ob eine Einladung noch offen ist.
|
||||
- Feste Ämter mit Name und optionaler Beschreibung anlegen und löschen.
|
||||
- Ein oder mehrere Ämter an einzelne Benutzer vergeben und Zuordnungen entfernen; doppelte identische Zuordnungen werden verhindert.
|
||||
- Ämter sind im Profil und Adressbuch sichtbar.
|
||||
|
||||
**Einschränkungen:** Kein regulärer Dialog zum erneuten Versand oder Widerruf einer Einladung. Einladungen werden im tatsächlichen Ablauf in `VerificationToken` gespeichert. Das separate Modell `Invitation` ist dafür nicht angebunden. Scheitert der Mailversand nach der Datenanlage, bleibt die Familie angelegt und eine Fehlermeldung wird zurückgegeben. Eine vollständige Familienlöschung durch Kita-Admins ist nicht angeboten.
|
||||
|
||||
Quellen: [Familienaktionen](../src/app/dashboard/families/actions.ts), [Familienliste](../src/app/dashboard/families/_components/families-list-client.tsx), [Einladungsaktivierung](../src/app/invite/%5Btoken%5D/actions.ts), [Ämter](../src/app/dashboard/families/duty-actions.ts).
|
||||
|
||||
### 4.6 Notdienst-Verfügbarkeiten für Eltern
|
||||
|
||||
- Eingabe für den Folgemonat, bezogen auf aktive Kinder des eigenen Haushalts.
|
||||
- Mindestzahl an ausgewählten Tagen entspricht Anzahl der Kinder × Kita-Einstellung.
|
||||
- Bereits gespeicherte Haushaltseinträge werden geladen und können erneut gespeichert werden.
|
||||
- Monatskalender mit Terminen, Kategorien, Veranstaltungsdetails und auswählbaren Verfügbarkeitstagen.
|
||||
- Die Oberfläche lässt Montag bis Freitag zu und sperrt bestätigte Schließtage.
|
||||
- Auswahlfortschritt und Rückmeldung bei zu wenigen Tagen.
|
||||
- Die ausgewählten verschiedenen Tage werden beim Speichern reihum auf die angegebenen Kinder verteilt; bestehende Einträge dieser Kinder im Zielmonat werden ersetzt.
|
||||
- Eingabefrist ist im Code fest: bis einschließlich 26. des aktuellen Monats, gesperrt ab dem 27.
|
||||
- Ohne aktive eigene Kinder erscheint ein Hinweis mit Verweis zum Profil.
|
||||
|
||||
**Einschränkungen:** Die Server Action prüft Datumsformat, Zielmonat, Mindestzahl und Haushaltszugehörigkeit, aber keine Wochenenden oder Schließtage. Die Frist ist nicht im Einstellungsdialog konfigurierbar. Abwesenheitsmeldungen werden bei den Verfügbarkeiten nicht automatisch berücksichtigt.
|
||||
|
||||
Quellen: [Elternseite](../src/app/dashboard/notdienst/page.tsx), [Kalendereingabe](../src/app/dashboard/notdienst/notdienst-form.tsx), [Speichern](../src/app/dashboard/notdienst/actions.ts), [Fristregel](../src/lib/date-utils.ts).
|
||||
|
||||
### 4.7 Notdienst-Planungszentrale
|
||||
|
||||
- Admins und Koordinatoren können über Monat/Jahr navigieren; Vorgabe ist der Folgemonat.
|
||||
- Übersicht von Haushalten, Kindern, Verfügbarkeitstagen, Haushalten mit/ohne Rückmeldung und Planstatus.
|
||||
- Automatische Erzeugung eines monatlichen Entwurfs; ein bestehender Monatsplan verhindert erneute Generierung.
|
||||
- Für jeden Montag bis Freitag wird aus verfügbaren Kindern ein Haushalt ausgewählt, der im bisherigen Monatsdurchlauf möglichst selten eingeteilt wurde. Bei Gleichstand kommt Zufall zum Einsatz; der Zähler startet jeden Monat neu.
|
||||
- Tage ohne Verfügbarkeiten bleiben unbesetzt.
|
||||
- Vorschau und manuelle Zuordnung zu einem aktiven Kind der Kita; Tage können auch geleert werden.
|
||||
- Entwurf veröffentlichen; veröffentlichte Einteilungen erscheinen im Kalender.
|
||||
- Veröffentlichte Pläne nachbearbeiten, solange der betreffende Tag nicht vergangen ist.
|
||||
- Nach manuellen Änderungen eines veröffentlichten Plans werden E-Mails an betroffene Elternkonten der Rolle `ELTERN` angestoßen; betroffene offene Tauschanfragen werden ungültig.
|
||||
- Entwurfsplan mit Bestätigungsdialog zurücksetzen und löschen. Veröffentlichte Pläne werden serverseitig vom Reset ausgeschlossen.
|
||||
- Kita-Einstellungen für Mindestverfügbarkeiten und Erinnerungs-Vorlauf speichern.
|
||||
- Manuell Erinnerungen an Haushalte versenden, die im ausgewählten Monat gar keinen Verfügbarkeitseintrag haben.
|
||||
- „Als PDF exportieren“ öffnet den Browser-Druckdialog (`window.print()`); die PDF-Datei entsteht über die Druckfunktion des Browsers.
|
||||
|
||||
**Einschränkungen:** Keine garantierte optimale oder über mehrere Monate ausgeglichene Verteilung. Die Generierung berücksichtigt keine Feiertage, Schließtage, Teamtage oder Kinderabwesenheiten. Ein Erinnerungs-Vorlauf wird gespeichert, aber kein zeitgesteuerter Job verwendet ihn. Haushalte mit zu wenigen Einträgen erhalten über diese Erinnerungsaktion keine Erinnerung, sobald wenigstens ein Eintrag vorliegt. Beim erstmaligen Veröffentlichen wird keine Zuteilungsmail versendet; die entsprechende E-Mail-Vorlage allein ist kein angebundener Versand.
|
||||
|
||||
Quellen: [Planungsseite](../src/app/dashboard/notdienst/plan/page.tsx), [Planaktionen](../src/app/dashboard/notdienst/plan/actions.ts), [Planoberfläche](../src/app/dashboard/notdienst/plan/plan-view.tsx).
|
||||
|
||||
### 4.8 Notdienst-Tausch zwischen Familien
|
||||
|
||||
- Eltern können im Kalender einen fremden Notdienst anfragen und einen eigenen veröffentlichten Dienst zum Tausch anbieten; optionale Nachricht bis 500 Zeichen.
|
||||
- Beide Dienste müssen derselben Kita angehören, veröffentlicht und heute oder zukünftig sein. Ein Tausch im eigenen Haushalt wird abgewiesen.
|
||||
- Dienste mit wartender oder bestätigter Alarmierung sind vom Tausch ausgeschlossen.
|
||||
- Bereits beteiligte Dienste mit offenen Tauschanfragen können keine weitere offene Anfrage erhalten.
|
||||
- Der angefragte Haushalt erhält eine E-Mail und sieht die offene Anfrage im Kalender.
|
||||
- Angefragter Haushalt kann annehmen oder ablehnen; anfragender Haushalt kann zurückziehen.
|
||||
- Annahme vertauscht beide Kinder-Zuordnungen in einer Transaktion, speichert die Entscheidung und storniert weitere betroffene offene Anfragen.
|
||||
- Annahme und Ablehnung lösen Benachrichtigungen an beide Familien aus; Rücknahme speichert den Status ohne eigenen Mailversand.
|
||||
- Kalender und Notdienstansichten werden nach Änderungen neu validiert.
|
||||
|
||||
**Einschränkungen:** Neue Anfragen sind auf die exakte Rolle `ELTERN` beschränkt; Eltern mit Admin-/Koordinatorrolle können sie nicht starten. Die Oberfläche zeigt offene Anfragen, keine vollständige abgeschlossene Tauschhistorie. Eine erneute Verfügbarkeitsprüfung für die getauschten Tage erfolgt nicht.
|
||||
|
||||
Quellen: [Tauschaktionen](../src/app/dashboard/kalender/actions.ts), [Kalender und Anfragen](../src/app/dashboard/kalender/_components/calendar-overview-client.tsx), [Tauschdialog](../src/app/dashboard/kalender/_components/termin-list.tsx).
|
||||
|
||||
### 4.9 Notdienst-Alarmierung
|
||||
|
||||
Die am 09.10.2026 abgestimmte Erweiterung ist in [NOTDIENSTALARM_PLAN.md](NOTDIENSTALARM_PLAN.md) beschrieben. Sie ist zunächst geplant; der folgende Abschnitt beschreibt den vorhandenen Code.
|
||||
|
||||
Vorbereitet sind:
|
||||
|
||||
- Server Action zum Auslösen eines Alarms durch Admin/Koordinator für eine Einteilung.
|
||||
- Kita-Prüfung und Abweisung einer bereits alarmierten Einteilung.
|
||||
- Eigene Alarmdatensätze und E-Mails für die Elternkonten der eingeteilten Familie mit Rolle `ELTERN`.
|
||||
- Bestätigungsseite unter `/alert/[token]`; der Link erlaubt die Bestätigung ohne Login.
|
||||
- Statuswechsel von `PENDING` auf `CONFIRMED` mit Zeitstempel; erneute Bestätigung wird abgewiesen.
|
||||
- Vorbereitete Button-Komponente für das Auslösen.
|
||||
|
||||
**Aktueller Stand:** `AlertButton` wird von keiner Seite eingebunden. Ein erreichbarer Auslöseablauf und eine laufende Statusübersicht für die Koordination fehlen damit in der aktuellen Oberfläche. Das Datenmodell kann eine erkrankte Fachkraft und Notizen speichern, aber die Aktion nimmt nur die Einteilungs-ID entgegen. Eine Auswahl der Fachkraft, Alarmstornierung, Eskalation oder zeitliche Token-Gültigkeit ist nicht angebunden.
|
||||
|
||||
Quellen: [Alarmaktion](../src/app/dashboard/actions.ts), [ungebundener Alarmbutton](../src/app/dashboard/alert-button.tsx), [Bestätigung](../src/app/alert/%5Btoken%5D/actions.ts).
|
||||
|
||||
### 4.10 Kalender, Terminanfragen und Mitbringlisten
|
||||
|
||||
- Gemeinsamer Kalender für bestätigte Termine, eigene ausstehende Terminanfragen, geplante Elterndienste und veröffentlichte Notdienste.
|
||||
- Listen-, Monats- und Agendaansicht; Monatsnavigation und Sprung zu heute.
|
||||
- Tagesdialog mit Termindetails, Diensten und Mitbringlisten.
|
||||
- Suche nach Titel/Beschreibung und bei Diensten nach Familie beziehungsweise Kind.
|
||||
- Kategorienfilter und Umschaltung zwischen eigenen und allen Diensten; reguläre Kita-Termine bleiben auch im eigenen Filter sichtbar.
|
||||
- Kategorien: Kita-Fest, Schließtag, Teamtag, Mitmach-Tag, Elternabend, Mitgliederversammlung, Elterncafé, interner/externer Geburtstag und Sonstiges.
|
||||
- Terminanfrage mit Titel, Beschreibung, Kategorie, Anfang/Ende und Ganztagsangabe.
|
||||
- Eigene Anfragen werden als ausstehend angezeigt; Admins/Koordinatoren können ausstehende Anfragen bestätigen oder mit Begründung ablehnen.
|
||||
- Admins/Koordinatoren können bestätigte Termine direkt anlegen, bearbeiten und endgültig löschen.
|
||||
- Datumsprüfung: Beginn nicht in der Vergangenheit, Ende nicht vor Beginn.
|
||||
- Mitbringliste je Termin aktivieren/deaktivieren; Textbeiträge hinzufügen.
|
||||
- Eigene Beiträge löschen; Admins/Koordinatoren können auch fremde Beiträge löschen.
|
||||
- Verweise aus Dienst-/Notdienstterminen in die entsprechenden Verwaltungsseiten; Diensttausch über den Kalender.
|
||||
|
||||
**Einschränkungen:** Ausstehende Anfragen blockieren keinen Zeitraum durch eine serverseitige Kollisionsprüfung. Eine Anfrage ist für andere Eltern nicht allgemein als reservierter Slot sichtbar. Mitbringbeiträge lassen sich nicht direkt bearbeiten, sondern nur löschen und neu anlegen. Es wurde kein Kalenderabo, ICS-Export oder Serientermin-Ablauf gefunden.
|
||||
|
||||
Quellen: [Kalenderseite](../src/app/dashboard/kalender/page.tsx), [Kalenderansichten](../src/app/dashboard/kalender/_components/calendar-overview-client.tsx), [Terminaktionen](../src/app/dashboard/kalender/actions.ts), [Mitbringliste](../src/app/dashboard/kalender/_components/mitbringsel-list.tsx).
|
||||
|
||||
### 4.11 Event-Anmeldungen und RSVP
|
||||
|
||||
- Admins/Koordinatoren können Termine mit Teilnahmeabfrage, optionaler Rückmeldefrist und Hinweisen für Teilnehmende anlegen/bearbeiten.
|
||||
- Verwaltungsseite listet Termine samt Status und zeigt pro Event Zusagen, Absagen und ausstehende Antworten.
|
||||
- Kindbezogene Teilnehmerliste über alle aktiven Kinder der Kita.
|
||||
- Server Action für Zu-/Absage eines eigenen aktiven Kindes, inklusive Prüfung von Kita, Haushalt, bestätigtem Termin und Frist.
|
||||
- Fehlt eine eigene Frist, gilt der Eventbeginn als Rückmeldeschluss. Eine bestehende Antwort kann bis dahin überschrieben werden.
|
||||
- Teilnehmerhinweise werden im Kalender bei Admin/Koordinator und bei einem Haushalt mit mindestens einer Zusage angezeigt.
|
||||
|
||||
**Aktueller Stand:** Die Eltern-Eingabekomponente `RsvpActionCard` existiert, wird aber von keiner Seite verwendet. Eltern besitzen deshalb im aktuellen Seitenaufbau keinen eingebundenen Zu-/Absagedialog. Außerdem wird `participantInfo` bereits an den Kalender-Client übertragen und nur bei der Darstellung ausgeblendet; die Anzeigeprüfung ist keine serverseitige Zugriffsbeschränkung für diese Information.
|
||||
|
||||
Quellen: [RSVP-Aktionen](../src/actions/rsvp.ts), [Event-Verwaltung](../src/app/dashboard/admin/kalender/admin-calendar-manager.tsx), [ungebundene Elternkomponente](../src/app/dashboard/rsvp-action-card.tsx), [Kalenderdaten](../src/app/dashboard/kalender/page.tsx).
|
||||
|
||||
### 4.12 Krank- und Abwesenheitsmeldungen
|
||||
|
||||
- Eigenes aktives Kind aus dem Haushalt auswählen und für einen Tag oder Zeitraum abmelden.
|
||||
- Gründe: Krankheit, Urlaub und Sonstiges; optionale Notiz bis 500 Zeichen.
|
||||
- Ende darf nicht vor dem Beginn liegen; sich überschneidende Meldungen desselben Kindes werden abgewiesen.
|
||||
- Eigene laufende/bevorstehende Meldungen anzeigen und löschen.
|
||||
- Tagesübersicht für Admin, Koordinator und Erzieherrolle mit Kind, Familie, Grund, Zeitraum und Notiz.
|
||||
- Tagesnavigation zurück/vor/heute und freie Datumswahl.
|
||||
- Grundfilter, Kennzahlen und Hinweise zu Wochenende, Schließtag/Teamtag sowie Tagen mehr als 30 Tage in der Zukunft.
|
||||
- Abwesenheiten sind nicht als echte Anwesenheitserfassung mit Check-in/Check-out implementiert; „anwesend“ ist aus Kinderzahl minus Meldungen abgeleitet.
|
||||
|
||||
**Einschränkungen:** Gruppen „Krippe“ und „Elementar“ werden aus dem ersten Zeichen des Kindernamens künstlich abgeleitet (`mockGroup`). Das Datenmodell hat keine echte Gruppenzuordnung. Die Anwesenheitszahl dieser Ansicht verwendet die gefilterten Fehlmeldungen bei weiterhin gesamter Kinderzahl und kann deshalb bei aktivem Filter irreführend sein. Eine bestehende Abwesenheit kann nur gelöscht und neu gemeldet, nicht direkt bearbeitet werden.
|
||||
|
||||
Quellen: [Abwesenheitsaktionen](../src/actions/absences.ts), [Elternformular](../src/app/dashboard/absence-card.tsx), [Tagesübersicht](../src/app/dashboard/admin/abwesenheiten/page.tsx), [Filter](../src/app/dashboard/admin/abwesenheiten/_components/absences-client.tsx).
|
||||
|
||||
### 4.13 Wöchentlicher Dienstplan
|
||||
|
||||
- Separater Dienstplan für Haushalte, unabhängig von festen personenbezogenen Ämtern und Notdienst.
|
||||
- Diensttypen mit Name/Beschreibung anlegen und löschen.
|
||||
- Wochenraster mit wählbarem Beginn und Zeitraum; Standard zwölf Wochen, maximal 104 Wochen.
|
||||
- Haushalt je Diensttyp/Kalenderwoche auswählen oder Zuordnung entfernen; Änderungen werden direkt gespeichert.
|
||||
- Kita-Zugehörigkeit von Diensttyp und Familie wird geprüft.
|
||||
- Einteilungen erscheinen im gemeinsamen Kalender.
|
||||
- Manuelle Erinnerungsaktion für noch nicht erinnerte geplante Dienste, deren Beginn in der aktuellen Woche liegt.
|
||||
- Versand an verifizierte Benutzer der Familie; erfolgreicher Versand wird mit `reminderSentAt` gespeichert. Erneute Zuordnung setzt diesen Wert zurück.
|
||||
|
||||
**Einschränkungen:** Kein automatisch laufender Erinnerungsjob. Status `DONE` und `CANCELLED` existieren im Datenmodell, aber ein regulärer Abschluss-/Stornoablauf ist nicht eingebunden. Eine Änderung setzt den Dienst wieder auf `PLANNED`. Das Löschen eines Diensttyps löscht durch die Datenrelationen auch dessen Einteilungen.
|
||||
|
||||
Quellen: [Dienstplanseite](../src/app/dashboard/admin/dienste/page.tsx), [Raster](../src/app/dashboard/admin/dienste/duty-planner.tsx), [Dienstaktionen](../src/app/dashboard/admin/dienste/actions.ts).
|
||||
|
||||
### 4.14 Schwarzes Brett, E-Mail und Anhänge
|
||||
|
||||
- Admins können eine Ankündigung mit Titel und Markdown-Inhalt erstellen; Vorschau ist im Formular vorhanden.
|
||||
- PDF-, JPG- und PNG-Anhänge bis zehn MB je Datei.
|
||||
- Speicherung der Anhangdateien auf dem Server und der Metadaten in der Datenbank.
|
||||
- Abruf über geschützte API mit Prüfung auf angemeldeten Benutzer und dieselbe Kita; keine Auslieferung über ein öffentliches Uploadverzeichnis.
|
||||
- Optionaler E-Mail-Versand an verifizierte Haushaltskonten, Erzieherkonten oder beide Gruppen. Die Auswahl betrifft E-Mail-Empfänger und wird nicht als Sichtbarkeitsgruppe der Meldung gespeichert.
|
||||
- Adminseite zeigt die letzten acht veröffentlichten Meldungen mit Autor, Zeitpunkt und Anhanganzahl.
|
||||
- Bei Dateischreibfehlern werden die neue Meldung und angefangene Dateien zurückgenommen; bei Mailfehlern bleibt die Meldung gespeichert und eine Warnung wird zurückgegeben.
|
||||
- Lesestatusmodell und Aktion zum Markieren als gelesen sind vorhanden; `NewsTicker` enthält einen vorbereiteten Meldungsdialog.
|
||||
|
||||
**Aktueller Stand:** `NewsTicker` ist nicht in das Dashboard oder eine andere Seite eingebunden. Eltern können neue Meldungen daher derzeit über den optionalen Mailversand erhalten, besitzen aber keine eingebundene Meldungsliste in der App. Eine Adminauswertung der Lesebestätigungen sowie Bearbeiten/Löschen von Meldungen sind nicht umgesetzt.
|
||||
|
||||
Quellen: [Meldungsaktionen](../src/actions/announcements.ts), [Adminseite](../src/app/dashboard/admin/news/page.tsx), [Formular](../src/app/dashboard/admin/news/news-form.tsx), [ungebundener Ticker](../src/app/dashboard/news-ticker.tsx), [Anhang-API](../src/app/api/announcements/attachments/%5Bid%5D/route.ts).
|
||||
|
||||
### 4.15 Adressbuch
|
||||
|
||||
- Interne Übersicht der Haushalte, bei denen mindestens ein Benutzer der Kontaktfreigabe zugestimmt hat.
|
||||
- Anzeige von Haushaltsname, Kindern, Elternnamen und festen Ämtern; alphabetische Gruppierung nach Haushaltsnamen.
|
||||
- E-Mail, Telefon und Adresse werden nur für den jeweiligen Benutzer mit Opt-in geladen.
|
||||
- Suche nach Familienname, Eltern-/Kindernamen oder sichtbarer E-Mail.
|
||||
- Filter für Telefonnummer, Ämter und Haushalte mit Opt-in aller zugeordneten Benutzer.
|
||||
- Detaildialog je Familie; E-Mail- und Telefonlinks starten den jeweiligen Mail-/Telefonhandler.
|
||||
- Sichtbarkeitsdialog erklärt die Freigabe und führt zum eigenen Profil.
|
||||
- Optionales Geburtsdatum eines Kindes ist im Detaildialog sichtbar.
|
||||
|
||||
**Einschränkung:** Namen und Ämter eines zweiten Elternteils ohne Kontaktfreigabe sowie Kinderinformationen sind innerhalb eines sichtbaren Haushalts weiterhin sichtbar. Die Freigabe ist technisch kein Opt-in für sämtliche Haushaltsinformationen.
|
||||
|
||||
Quellen: [Adressbuchdaten](../src/app/dashboard/adressbuch/page.tsx), [Adressbuchoberfläche](../src/app/dashboard/adressbuch/_components/directory-client.tsx).
|
||||
|
||||
### 4.16 ErzieherInnen-Stammdaten
|
||||
|
||||
- Admins können Fachkräfte mit Vor- und Nachname anlegen, bearbeiten und löschen.
|
||||
- Aktivstatus wird gepflegt und dargestellt.
|
||||
- Diese Datensätze sind keine Login-Konten; die separate Benutzerrolle `ERZIEHER` ist hiervon unabhängig.
|
||||
- Referenz für Notdienstalarme im Datenmodell vorhanden, aber derzeit keine Fachkraftauswahl im Alarmauslöser.
|
||||
|
||||
Quellen: [Erzieheraktionen](../src/app/dashboard/erzieher/actions.ts), [Erzieheroberfläche](../src/app/dashboard/erzieher/_components/erzieher-list.tsx).
|
||||
|
||||
### 4.17 Systemweite Superadmin-Verwaltung
|
||||
|
||||
- Übersicht aller Kitas mit Slug, Modulstatus, Benutzer-/Familien-/Kinderzahlen, Terminen, Abwesenheiten, Meldungen, offenen Einladungen und letztem Login.
|
||||
- Hinweise auf Benutzer ohne Kita, Kontosperren, fehlende Datenschutzzustimmung und Familien ohne Benutzer.
|
||||
- Kita-Diagnose mit Benutzerliste, Rollen, Familien, Verifikationsstatus, Consent, Fehlversuchen und Sperren; zusätzlich Zähler für Konten ohne Passwort und abgelaufene Einladungen.
|
||||
- Diagnoseaufrufe werden im Audit-Protokoll gespeichert.
|
||||
- Kita endgültig löschen nach exakter Namensbestätigung, mit kaskadierender Löschung abhängiger Datenbankdatensätze.
|
||||
- Kita-gebundene Benutzer löschen nach Bestätigung ihrer E-Mail-Adresse; dabei zugehörige Verifikationstokens entfernen.
|
||||
- Benutzer für weitere Logins sperren, entsperren oder Fehlversuche zurücksetzen. Sperrung setzt `lockedUntil` weit in die Zukunft; Entsperren löscht die Sperre und setzt den Zähler zurück.
|
||||
- Eigene und andere Superadmin-Konten sowie Konten ohne Kita werden durch diese Support-Aktionen nicht verändert.
|
||||
- Auditansicht zeigt die neuesten 200 Einträge samt Akteur, Ziel, Zeitpunkt, Aktion und Metadaten. Protokolle können auch nach Löschung der Zielobjekte bestehen bleiben.
|
||||
|
||||
**Einschränkungen:** Offene und abgelaufene Einladungen werden über `Invitation` gezählt, während die tatsächlichen Familien-Einladungen `VerificationToken` nutzen. Eine Superadmin-Benutzerlöschung entfernt nicht automatisch einen nun leeren Haushalt. Eine Sperre wird bei der Anmeldung geprüft; das sofortige Beenden bereits bestehender Sessions ist nicht umgesetzt.
|
||||
|
||||
Quellen: [Adminübersicht und Diagnose-Daten](../src/app/admin/_lib/data.ts), [Support-Aktionen](../src/app/admin/actions.ts), [Auditseite](../src/app/admin/audit/page.tsx).
|
||||
|
||||
## 5. Datenmodell und technische Querschnittsfunktionen
|
||||
|
||||
- PostgreSQL mit Prisma. Eine Kita ist ein Mandant; fachliche Daten sind über `kitaId` zugeordnet.
|
||||
- Datenmodelle für Kitas, Benutzer, Haushalte, Kinder, Fachkräfte, feste Ämter, Diensttypen/-einteilungen, Abwesenheiten, Meldungen, Anhänge, Lesestatus, Termine, Teilnahme, Mitbringsel, Notdienstpläne/-verfügbarkeiten/-einteilungen/-alarme/-tausche sowie Auditprotokolle und Tokens.
|
||||
- Eindeutigkeitsregeln unter anderem für E-Mail, Kita-Slug, Monatsplan, Einteilung je Plantag, Verfügbarkeit je Kind/Tag, Teilnahme je Event/Kind und Amt je Benutzer.
|
||||
- Eingabeprüfung überwiegend mit Zod, Schreibabläufe teilweise als Datenbanktransaktionen, Aktualisierung von Seiten nach Änderungen.
|
||||
- Gemeinsamer E-Mail-Versand über Resend mit Fehlerbehandlung. Ohne API-Key werden E-Mails nur in der Entwicklungsumgebung simuliert; diese Simulation bestätigt keine Zustellung.
|
||||
- Vorlagen für Einladung, Alarm, Verfügbarkeitserinnerung, Einteilungsänderung, Diensttausch, Wochen-Diensterinnerung, News und Kontakt. Eine weitere Vorlage für erstmalige Notdienst-Zuteilung ist vorhanden, aber nicht an die Veröffentlichung angebunden.
|
||||
- Rollen-, Kita- und Consent-Prüfungen über gemeinsame Helfer. Geschützte Dashboard-/Adminlayouts, Seiten und Aktionen setzen Zugriffsprüfungen ein; nicht jede Aktion verwendet denselben Consent-Helfer.
|
||||
- Viele Datenbankrelationen löschen abhängige Datensätze mit. Das ist nicht gleichbedeutend mit vollständiger Bereinigung von Dateien, allgemeinen Verifikationstokens oder Audit-Snapshots.
|
||||
- Der Hilfsmodus `TEST_MODE=true` liefert in `requireRole` und `requireKitaSession` künstliche Sessions und umgeht dort die regulären Prüfungen. Er ist nicht auf die Entwicklungsumgebung begrenzt.
|
||||
|
||||
Quelle: [Schema](../prisma/schema.prisma), [Mail](../src/lib/mail.ts), [Auth-Helfer](../src/lib/auth-utils.ts).
|
||||
|
||||
## 6. Seiten- und Schnittstellenverzeichnis
|
||||
|
||||
| Route | Zweck/Zugriff |
|
||||
| --- | --- |
|
||||
| `/` | Öffentliche Startseite und Kontakt. |
|
||||
| `/features/notdienst-planer` | Öffentliche Notdienst-Beschreibung. |
|
||||
| `/features/kita-kalender` | Öffentliche Kalender-Beschreibung. |
|
||||
| `/features/eltern-adressbuch` | Öffentliche Adressbuch-Beschreibung. |
|
||||
| `/features/krankmeldung` | Öffentliche Abwesenheits-Beschreibung. |
|
||||
| `/features/schwarzes-brett` | Öffentliche Meldungs-Beschreibung. |
|
||||
| `/impressum`, `/datenschutz` | Öffentliche Informationsseiten mit noch offenen Platzhaltern. |
|
||||
| `/register`, `/login` | Gründerregistrierung und Anmeldung. |
|
||||
| `/onboarding` | Kita einrichten nach Anmeldung. |
|
||||
| `/onboarding/consent` | Hinweis bei fehlender Datenschutzannahme. |
|
||||
| `/invite/[token]` | Elternkonto über Einladungslink aktivieren. |
|
||||
| `/alert/[token]` | Notdienstalarm über Link bestätigen. |
|
||||
| `/forbidden` | Hinweis bei verweigertem Zugriff. |
|
||||
| `/dashboard` | Kita-Übersicht und eigene Abwesenheiten. |
|
||||
| `/dashboard/profil` | Eigener Haushalt, Kinder, Kontakte und Kontolöschung. |
|
||||
| `/dashboard/notdienst` | Verfügbarkeiten; Eltern, Admin, Koordinator. |
|
||||
| `/dashboard/notdienst/plan` | Planung; Admin, Koordinator. |
|
||||
| `/dashboard/kalender` | Kita-Kalender und Diensttausch. |
|
||||
| `/dashboard/adressbuch` | Internes Adressbuch. |
|
||||
| `/dashboard/families` | Familien und feste Ämter; Admin. |
|
||||
| `/dashboard/erzieher` | Fachkraft-Stammdaten; Admin. |
|
||||
| `/dashboard/admin/dienste` | Wochen-Dienstplan; Kita-Admin. Die Aktion erlaubt zusätzlich Superadmin mit Kita-Kontext. |
|
||||
| `/dashboard/admin/news` | Meldungen veröffentlichen; Admin. |
|
||||
| `/dashboard/admin/kalender` | Termine und Event-Anmeldungen; Admin, Koordinator. |
|
||||
| `/dashboard/admin/abwesenheiten` | Tagesübersicht; Admin, Koordinator, Erzieherrolle. |
|
||||
| `/admin` | Systemweite Kita-Übersicht; Superadmin. |
|
||||
| `/admin/kitas/[kitaId]` | Kita-Diagnose und Benutzersupport; Superadmin. |
|
||||
| `/admin/audit` | Systemweites Audit-Protokoll; Superadmin. |
|
||||
| `/api/auth/[...nextauth]` | Auth.js-Endpunkte. |
|
||||
| `/api/announcements/attachments/[id]` | Geschützter Anhangdownload. |
|
||||
| `/sitemap.xml`, `/robots.txt` | Suchmaschinensteuerung. |
|
||||
|
||||
## 7. Betrieb, Entwicklung und Prüfstand
|
||||
|
||||
- Stack laut `package.json`: Next.js 16.2.4, React 19.2.4, TypeScript, Prisma 6, Auth.js/NextAuth v5 beta, PostgreSQL, Tailwind CSS und Resend.
|
||||
- Lokaler Entwicklungsstart führt vor Next.js automatisch `prisma db push` und den Seed aus.
|
||||
- Seed legt Demonstrationsdaten mit mehreren Rollen und fachlichen Beispielen an; regulärer Seed ist bei bereits befüllter Datenbank zurückhaltend. Ein separater Reset-Modus existiert.
|
||||
- Docker-Build und Produktionsstart sind vorhanden; Produktionsstart wendet das Schema über `prisma db push --skip-generate` an. Versionierte Prisma-Migrationen liegen nicht im geprüften Dateibestand.
|
||||
- Lokale Compose-Datei stellt PostgreSQL bereit; Coolify-Compose enthält App, PostgreSQL, pgAdmin und persistente Datenbank-/Uploadvolumes.
|
||||
- Umgebungsvariablen-Vorlage und Produktionscheckliste sind vorhanden; ihre tatsächliche Erfüllung wurde nicht auf einem Server geprüft.
|
||||
- `UPLOAD_DIR` ist persistent vorgesehen. Die Dateihilfsfunktionen hängen noch `announcements` an diesen Pfad an; bei der aktuellen Compose-Konfiguration ergibt sich `/app/uploads/announcements/announcements`.
|
||||
- Kein Testskript und keine automatisierte Testdateisuite im geprüften Repository gefunden. Demo-Seed und manueller Live-Testplan ersetzen keine automatisierten Tests.
|
||||
|
||||
### Ausgeführte technische Prüfungen
|
||||
|
||||
Die Prüfungen liefen auf dem unveränderten Ausgangscheckout mit den dort bereits installierten Abhängigkeiten. Es wurden keine Bibliotheken installiert und keine Builds oder Datenbankoperationen ausgeführt.
|
||||
|
||||
| Prüfung | Ergebnis |
|
||||
| --- | --- |
|
||||
| `./node_modules/.bin/tsc --noEmit --incremental false` | Erfolgreich, Exit-Code 0. |
|
||||
| `npm run lint` | Fehlgeschlagen, Exit-Code 1: zwei Fehler und neun Warnungen. |
|
||||
| Quellenprüfung von Seiten, Aktionen, Komponenten und Schema | Durchführung für die oben beschriebenen Funktionsbereiche. |
|
||||
| Aktueller Browser-/End-to-End-Test | Nicht durchgeführt. |
|
||||
| Mailzustellung und produktives Deployment | Nicht geprüft. |
|
||||
|
||||
Beide ESLint-Fehler betreffen `as any` im Testmodus von `src/lib/auth-utils.ts` (Zeilen 57 und 91). Die Warnungen betreffen ungenutzte Variablen/Imports im Seed, Kalender, Adressbuch und Abwesenheiten. Diese Bestandsaufnahme ändert keinen Anwendungscode.
|
||||
|
||||
Der vorhandene [Live-Testplan](live-testplan.md) vom 17.05.2026 dokumentiert erfolgreiche Tests von Landingpage/Kontakt, Gründerregistrierung, Einrichtung, Dashboard, Familienanlage und Teilen des Login-Ablaufs. Eltern-Einladungsaktivierung und anschließende Bereinigung sind dort noch offen. Dies sind historische Einträge, keine aktuellen Testnachweise für den geprüften Commit. Die abgehakten Punkte in [UI-TODO.md](../UI-TODO.md) sind ebenfalls historische Angaben; viele der dort ehemals fehlenden Handler sind inzwischen im Code vorhanden.
|
||||
|
||||
Quellen: [Paket und Skripte](../package.json), [Deployment](../deploy/README.md), [Produktionscheckliste](../deploy/production-checklist.md), [Seed](../prisma/seed.ts), [Coolify-Compose](../docker-compose.coolify.yml).
|
||||
|
||||
## 8. Konkrete offene Punkte für die weitere Arbeit
|
||||
|
||||
Die Reihenfolge ist ein Vorschlag aus der Bestandsaufnahme; es wurde nichts davon umgesetzt.
|
||||
|
||||
| Reihenfolge | Thema | Konkreter nächster Schritt |
|
||||
| --- | --- | --- |
|
||||
| 1 | Fehlende Elternabläufe | NewsTicker und RSVP-Eingabe an eine erreichbare Seite anbinden; Daten dafür laden. |
|
||||
| 2 | Notdienstalarm | Auslösebutton, Fachkraftauswahl und Statusanzeige in den aktuellen Seitenaufbau integrieren. |
|
||||
| 3 | Moduldeaktivierung | Modulschalter in Navigation, Seiten und Server Actions einheitlich prüfen; spätere Einstellungen anbieten. |
|
||||
| 4 | Notdienstregeln | Wochenenden/Schließtage serverseitig ausschließen und Generierung um Schließtage ergänzen; Abwesenheitsregel festlegen. |
|
||||
| 5 | Erinnerungen | Automatische Ausführung ergänzen und unterscheiden, ob gar keine oder zu wenige Verfügbarkeiten vorliegen. |
|
||||
| 6 | Erstveröffentlichung | Zuteilungsmails beim Veröffentlichen anbinden und Mailfehler sichtbar behandeln. |
|
||||
| 7 | Einladungssupport | Tokenmodell und Superadmin-Zähler vereinheitlichen; erneuten Versand, Ablauf und Widerruf erreichbar machen. |
|
||||
| 8 | Rechtevergabe | Regulären Ablauf für Koordinator-/Erzieherkonten und Rollenänderungen ergänzen. |
|
||||
| 9 | Abwesenheitsgruppen | Echte Gruppenzuordnung einführen oder den künstlichen Gruppenfilter entfernen; Kennzahlen konsistent berechnen. |
|
||||
| 10 | Buchungskonflikte | Fachliche Reservierungsregeln definieren und Überschneidungen serverseitig prüfen. |
|
||||
| 11 | Selbstverwaltung | Passwort-Reset/-Änderung und direkte Bearbeitung von Abwesenheiten/Mitbringbeiträgen ergänzen. |
|
||||
| 12 | Löschabläufe | Kinderlöschung bei bestehenden Verpflichtungen prüfen; Anhangdateien und Tokens bei Kita-/Kontolöschungen bereinigen; Audit-Aufbewahrung gesondert definieren. |
|
||||
| 13 | Zugriffsprüfungen | Testmodus an Entwicklungsumgebung binden; Consent-/Session-Prüfungen und Teilnehmerhinweise serverseitig vereinheitlichen. |
|
||||
| 14 | Technischer Zustand | Zwei ESLint-Fehler beheben, Migrationsablauf einführen und aussagekräftige Tests für die zentralen Abläufe ergänzen. |
|
||||
| 15 | Aktuelle Abnahme | Rollenbasierte Browserprüfung, Mailzustellung, Elternaktivierung und Bereinigung anhand eines aktualisierten Testplans durchführen. |
|
||||
| 16 | Öffentliche Texte | Platzhalter in Impressum/Datenschutz mit den tatsächlichen Betriebsangaben vervollständigen und Marketingversprechen mit dem implementierten Verhalten abgleichen. |
|
||||
|
||||
## 9. Nicht als fertige Produktfunktion vorhanden
|
||||
|
||||
Im geprüften Code wurden kein Abonnement-/Zahlungsablauf, keine Import-/Exportverwaltung für Familien, kein externer Kalenderabgleich, keine Push-/SMS-Alarmierung, keine echte Kita-Gruppenverwaltung und keine Zeiterfassung/Check-in-Funktion gefunden. Vorhandene Planungs- oder Marketingtexte sind dafür kein Umsetzungsnachweis.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Notdienstalarm
|
||||
|
||||
Stand: 09.10.2026 · Umsetzung auf `codex/notdienstalarm`
|
||||
|
||||
## Bedienung
|
||||
|
||||
Kita-Admins und Notdienst-Koordination finden den Alarm in der Navigation und bei eingeteilten Tagen eines veröffentlichten Notdienstplans. Der Dialog zeigt die betroffene Familie und ihre Elternadressen vor dem Auslösen. Er umfasst einen ganzen Kita-Tag oder ein Zeitfenster, eine Antwortfrist (standardmäßig 30 Minuten), eine optionale interne Fachkraftzuordnung und eine interne Notiz.
|
||||
|
||||
Nur die eingeteilte Familie wird angefragt. Jedes Elternkonto erhält einen eigenen persönlichen Rückmeldelink und einen Hinweis in der App. Die Antwort „Wir übernehmen“ oder „Wir können nicht“ muss ausdrücklich gespeichert werden und gilt für den gesamten Haushalt. Das Öffnen des Links speichert keine Antwort. Die erste gespeicherte Antwort entscheidet auch bei gleichzeitigen Antworten; Änderungen dokumentiert die Koordination.
|
||||
|
||||
| Anzeige | Bedeutung / nächster Schritt |
|
||||
| --- | --- |
|
||||
| Antwort ausstehend | Haushalt hat noch nicht geantwortet. |
|
||||
| Übernahme bestätigt | Rechtzeitige Zusage oder dokumentierte Freigabe durch Koordination. |
|
||||
| Absage – Klärung erforderlich | Alle Admins und KoordinatorInnen der Kita erhalten sofort einen Hinweis. Ersatz manuell organisieren. |
|
||||
| Klärung erforderlich – Frist abgelaufen | Nach Ablauf informiert der Hintergrundjob einmalig die Admins und KoordinatorInnen. |
|
||||
| Verspätete Zusage | Muss durch Koordination freigegeben werden; keine automatische sichere Besetzung. |
|
||||
| Klärung erforderlich | Uneindeutige frühere Einzelantworten wurden übernommen. Haushalt kontaktieren. |
|
||||
| Storniert | Haushalt wird informiert; der Link kann keine Antwort mehr speichern. |
|
||||
|
||||
Telefonische Rückmeldungen, Korrekturen, verspätete Freigaben und Stornierungen benötigen eine interne Begründung. Interne Fachkraftdaten, Notizen und Verlauf erscheinen ausschließlich in der Verwaltungsansicht und werden nicht per E-Mail übermittelt. Eltern sehen ihre eigenen Alarme; andere Haushalte und Fachkräfte haben keinen Zugriff.
|
||||
|
||||
Aktive Alarme sperren manuelle Umzuordnung und Diensttausche. Für einen Ersatz zuerst den Alarm stornieren, dann die Einteilung ändern und neu alarmieren. Ein ausstehender E-Mail-Versand lässt sich erneut versuchen, ohne die Antwortfrist neu zu starten. Die Anzeige „vom Maildienst angenommen“ bestätigt die Annahme durch den Versanddienst, nicht die Zustellung im Postfach.
|
||||
|
||||
## Zeiten und Grenzen
|
||||
|
||||
- Kita-Zeitzone: `Europe/Berlin`, einschließlich Sommer-/Winterzeit. Nicht existierende Uhrzeiten bei der Zeitumstellung werden abgelehnt.
|
||||
- Ganze Tage enden um Mitternacht zum Folgetag. Zeitfenster müssen am selben Tag liegen; Ende nach Beginn.
|
||||
- Die Antwortfrist startet beim Auslösen, beträgt 1–1440 Minuten und endet spätestens mit dem Einsatz. Alarme sind für heute und zukünftige veröffentlichte Einteilungen möglich.
|
||||
- Nach Einsatzende können Rückmeldelinks keine Antwort mehr speichern. Der letzte Status bleibt lesbar.
|
||||
- Die Übersicht zeigt bis zu 100 Alarme seit 30 Tagen vor heute. Direkte Detail-Links öffnen auch ältere Vorgänge. Im Dialog stehen Einteilungen der nächsten 93 Tage zur Wahl; das Dashboard zeigt bis zu zehn aktuelle Alarme.
|
||||
- Kein SMS-/Push-Versand und keine automatische Alarmierung anderer Familien. Notdienstmails gehören zum Alarmablauf und verwenden nicht die persönliche Einstellung für Personal-Antragsmails.
|
||||
|
||||
## Betrieb und Hintergrundjob
|
||||
|
||||
Benötigt werden die vorhandene Resend-Konfiguration (`RESEND_API_KEY`, `EMAIL_FROM`), die korrekte öffentliche App-Adresse (`NEXT_PUBLIC_SITE_URL`, alternativ `AUTH_URL`/`NEXTAUTH_URL`) und neu `NOTDIENST_JOB_SECRET` mit mindestens 32 Zeichen. Ein zufälliges Secret kann beispielsweise mit `openssl rand -hex 32` erzeugt und in der Hosting-Konfiguration gespeichert werden. Das Secret gehört nicht in Git oder ins Browser-Frontend.
|
||||
|
||||
Der bestehende Docker-Produktionsstart startet `scripts/notdienst-alarm-worker.mjs`. Dieser ruft nach fünf Sekunden und danach ungefähr jede Minute lokal `POST /api/jobs/notdienstalarme` auf. Fristmeldungen entstehen dadurch auch ohne geöffneten Browser, normalerweise innerhalb einer Minute nach Fristende, zuzüglich Laufzeit und möglicher Ausfälle. Bei fehlendem Secret startet der allgemeine Produktionsstart ohne Fristjob und die Verwaltungsseite zeigt einen Hinweis; die Coolify-Vorlage verlangt das Secret. Ein zu kurzes gesetztes Secret stoppt den Produktionsstart.
|
||||
|
||||
Bei einem anderen Hosting-Verfahren muss der Worker als eigener dauerhaft überwachter Prozess gestartet werden oder ein externer Scheduler die Route mindestens einmal pro Minute per POST und `Authorization: Bearer <NOTDIENST_JOB_SECRET>` aufrufen. Nur `npm run start` startet den Worker nicht. Der Scheduler/Host muss auch nach Neustarts laufen; ein gesetztes Secret allein belegt keine laufende Fristprüfung.
|
||||
|
||||
Der Job bearbeitet bis zu 100 Fristfälle und 100 E-Mail-Aufträge je Lauf. Wiederholte und gleichzeitige Aufrufe werden abgefangen: Fristmeldungen besitzen einen eindeutigen Ereignisschlüssel, Mailaufträge eine Versandreservierung und einen stabilen Idempotenzschlüssel. Versandfehler bleiben gespeichert und werden bei späteren Läufen erneut versucht; bereits angenommene Aufträge werden nicht erneut angefragt. Rollen- und Haushaltszuordnungen werden vor dem Versand erneut geprüft. Überholte Anfragen werden übersprungen. Provider-Garantien zur Idempotenz und tatsächliche Postfachzustellung bleiben Grenzen außerhalb der Anwendung.
|
||||
|
||||
HTTP 401 bedeutet fehlende/falsche Berechtigung, 503 fehlendes/zu kurzes Job-Secret, 500 einen fehlgeschlagenen Lauf. HTTP 200 enthält die Bearbeitungszahlen einschließlich fehlgeschlagener E-Mails; die Versandübersicht und Server-/Worker-Logs sind für die Betriebsprüfung heranzuziehen. Bei Ausfall wird die Fristüberschreitung schon anhand der Uhrzeit in der Oberfläche angezeigt; E-Mail-Eskalation und Reservierungsfreigabe benötigen den nächsten erfolgreichen Joblauf.
|
||||
|
||||
## Datenbank und vorhandene Alarme
|
||||
|
||||
Das Schema ergänzt einen gemeinsamen Alarmvorgang, einzelne Empfänger und Tokens, Hinweise, Mailaufträge und einen Verlauf. Die bisherigen `NotdienstAlert`-Datensätze bleiben erhalten. Ein aktiver Alarm reserviert seine Einteilung eindeutig; Transaktionen schützen konkurrierende Antworten und Planänderungen.
|
||||
|
||||
Der bestehende Docker-Start nutzt `prisma db push --skip-generate`. Für kontrollierte SQL-Upgrades liegt alternativ [deploy/sql/notdienstalarm.sql](../deploy/sql/notdienstalarm.sql) vor. Es setzt den vollständigen Personalbereich einschließlich seiner Mail-Erweiterung voraus, ist einmalig auszuführen und enthält keine Datenlöschung. Nicht zusätzlich ausführen, wenn `db push` diese Änderungen bereits angewandt hat. Datenbanksicherung und Prüfung des Ausgangsschemas gehören zum Deployment. Die Auswahl der SQL-Alternativen erklärt die [zentrale Deployment- und Mailanleitung](../deploy/DEPLOYMENT_UND_MAILVERSAND.md).
|
||||
|
||||
Bisherige Einzelalarme werden beim Verwaltungsaufruf, Joblauf oder Aufruf eines alten Links in Gruppen pro Einteilung übernommen. Alte gültige Tokens bleiben nutzbar; Originalantworten bleiben gespeichert. Nur vollständig übereinstimmende gültige Antworten ergeben eine sichere gemeinsame Zusage. Widersprüche, fehlende/ungeklärte Empfänger oder doppelte Einzelalarme führen zu Klärungsbedarf. Bei doppelten Datensätzen eines Elternkontos wird ein Rückmeldetoken übernommen; die übrigen Originaldatensätze bleiben erhalten. Die Übernahme verschickt keine erneute Alarmanfrage.
|
||||
|
||||
## Prüfung
|
||||
|
||||
Abschließender Prüfstand: 20 Alarmtests, 17 Personal-Service-Tests und neun Berechnungstests erfolgreich; TypeScript, ESLint der betroffenen Dateien und Produktionsbuild erfolgreich. Das additive SQL-Upgrade wurde auf einem separaten Schema der isolierten Datenbank angewandt und per Prisma mit dem Zielmodell verglichen: keine Abweichungen. Worker und Jobroute wurden lokal geprüft (401 ohne Secret, 200 mit Secret, Fristmeldung je zuständigem Konto einmalig). Die vorhandenen globalen ESLint-Fehler in `auth-utils.ts` liegen außerhalb dieser Änderung.
|
||||
|
||||
Automatisierte Alarmtests prüfen Rollen und Mandanten, gemeinsame und konkurrierende Antworten, Fristprüfung, Absagen, verspätete Freigaben, Stornierung, Tokens, Versandfehler/erneuten Versand, Altbestände sowie die Sperre vorhandener Plan- und Diensttausch-Aktionen. Sie benötigen ausdrücklich die isolierte lokale Testdatenbank `127.0.0.1:55439/kita_staff_test` und bereinigen nur ihre eigenen Test-Kitas.
|
||||
|
||||
```sh
|
||||
DATABASE_URL='postgresql://USER@127.0.0.1:55439/kita_staff_test' npm run test:alarms
|
||||
npm run test:staff
|
||||
```
|
||||
|
||||
Die Browserprüfung verwendet ausschließlich Demo-Daten und deaktivierten tatsächlichen E-Mail-Versand. Geprüft wurden Auslösen aus der Einteilung, Zeitfenster, Eltern-Dashboard-Hinweis, persönliche Rückmeldeseite mit expliziter Bestätigung und eine mobile Ansicht ohne horizontalen Überlauf. Produktive Zustellung und Deployment sind separat durchzuführen.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Notdienstalarm – abgestimmter Funktionsplan
|
||||
|
||||
Stand: 09.10.2026 · Branch `codex/notdienstalarm`
|
||||
|
||||
Status: Umgesetzt. Dieser Plan hält die abgestimmten Entscheidungen fest. Bedienung, Betriebsanforderungen und Prüfungen stehen in [NOTDIENSTALARM.md](NOTDIENSTALARM.md).
|
||||
|
||||
## Festgelegter Umfang
|
||||
|
||||
| Thema | Entscheidung |
|
||||
| --- | --- |
|
||||
| Zuständigkeit | Nur Kita-Admins und Notdienst-Koordination (`ADMIN`, `KOORDINATOR`) lösen Alarme aus und verwalten sie. |
|
||||
| Erste Empfänger | Ausschließlich die für das Datum im veröffentlichten Notdienstplan eingeteilte Familie. Alle Elternkonten dieses Haushalts werden einzeln angeschrieben. |
|
||||
| Rückmeldung | „Wir übernehmen“ oder „Wir können nicht“. Eine Antwort gilt für den gesamten Haushalt. |
|
||||
| Kanäle | E-Mail und ein deutlich sichtbarer Hinweis in der App. |
|
||||
| Antwortfrist | Standardmäßig 30 Minuten ab Auslösung; beim Auslösen anpassbar. |
|
||||
| Einsatzdauer | Wahl zwischen „Ganzer Kita-Tag“ und „Bestimmte Uhrzeiten“ mit Beginn und Ende. |
|
||||
| Fehlende Übernahme | Absage sofort, ausbleibende Antwort nach Fristablauf: „Klärung erforderlich“. Koordination informieren; Ersatz manuell organisieren. |
|
||||
|
||||
## Ablauf in der Oberfläche
|
||||
|
||||
### 1. Alarm auslösen
|
||||
|
||||
Im veröffentlichten Notdienstplan erhält die Einteilung eine Aktion **Notdienstalarm auslösen**. Eine aktuelle Alarmübersicht ist zusätzlich über das Dashboard erreichbar.
|
||||
|
||||
Der Dialog zeigt Datum, eingeteilte Familie und deren Empfängeradressen. Die auslösende Person wählt die Einsatzdauer, prüft die Antwortfrist und bestätigt den Versand. Bei **Bestimmte Uhrzeiten** sind Beginn und Ende Pflicht; Ende liegt nach Beginn. Bei **Ganzer Kita-Tag** sind keine künstlichen Uhrzeitangaben nötig. Die gewählte Dauer erscheint in der E-Mail und auf der Rückmeldeseite.
|
||||
|
||||
Ein Alarm ist nur für heutige oder zukünftige Einteilungen eines veröffentlichten Plans der eigenen Kita möglich. Notdienst muss für die Kita aktiviert sein. Fehlende Elternkonten werden vor der Auslösung deutlich angezeigt. Eine aktive Alarmierung verhindert einen zweiten Alarm für dieselbe Einteilung.
|
||||
|
||||
Optional kann die ausgefallene Fachkraft intern zugeordnet werden. Dies dient der Zuordnung und erzeugt keine automatische Krankheitsbuchung im Personalbereich. Private interne Notizen und Namen ausgefallener Fachkräfte gehören nicht in die Eltern-E-Mail.
|
||||
|
||||
### 2. Familie informieren und Antwort erfassen
|
||||
|
||||
Jedes Elternkonto erhält eine eigene E-Mail mit Kita, Datum, Einsatzdauer, Antwortfrist und persönlichem Rückmeldelink. Die Nachricht fragt eindeutig nach einer Übernahme. Alle Elternkonten des Haushalts sehen in der App denselben aktiven Alarm.
|
||||
|
||||
Die Rückmeldeseite funktioniert wie bisher ohne Login über einen persönlichen Token. Das Öffnen des Links löst keine Zusage aus. Erst die ausdrückliche Auswahl von **Wir übernehmen** oder **Wir können nicht** mit Bestätigung schreibt die Antwort.
|
||||
|
||||
Die Antwort wird am gemeinsamen Haushaltseinsatz gespeichert, einschließlich Zeitpunkt und antwortendem Elternkonto. Alle anderen Links zeigen anschließend die gemeinsame Antwort. Gleichzeitige gegensätzliche Antworten dürfen nicht beide wirksam werden. Eine bereits gespeicherte Antwort lässt sich nicht versehentlich durch einen zweiten Klick überschreiben.
|
||||
|
||||
### 3. Stand verfolgen und Ersatz klären
|
||||
|
||||
Die Alarmübersicht zeigt Datum, Dauer, Familie, Antwortfrist, gemeinsamen Rückmeldestatus und den Versandstand je Empfänger. Offene Alarme für heute werden besonders hervorgehoben.
|
||||
|
||||
| Anzeige | Bedeutung und nächste Aktion |
|
||||
| --- | --- |
|
||||
| Antwort ausstehend | Familie wurde angefragt; die Antwortfrist läuft. |
|
||||
| Übernahme bestätigt | Der Haushalt hat rechtzeitig zugesagt. Koordination und Admins sehen die Zusage. |
|
||||
| Klärung erforderlich – Absage | Der Haushalt kann nicht übernehmen. Koordination organisiert Ersatz. |
|
||||
| Klärung erforderlich – Frist abgelaufen | Es liegt keine Antwort vor. Koordination fasst nach oder organisiert Ersatz. |
|
||||
| Storniert | Einsatz entfällt; Rückmeldelinks erlauben keine weitere Antwort. |
|
||||
|
||||
Versandfehler sind ein eigener Zustand und dürfen nicht als Absage der Familie erscheinen. Eine fehlgeschlagene E-Mail wird deutlich angezeigt und kann erneut versendet werden; andere Empfänger werden trotzdem bedient.
|
||||
|
||||
Bei Absage oder Fristablauf erhalten zuständige Koordinations- und Admin-Konten derselben Kita einen Hinweis in der App und eine E-Mail. Die Fristmeldung wird je Alarm einmal erzeugt. Die Koordination organisiert Ersatz in dieser Version manuell; weitere Familien werden nicht automatisch alarmiert.
|
||||
|
||||
## Vorgeschlagene Ausgestaltung für Sonderfälle
|
||||
|
||||
Diese Details ergänzen die Nutzerentscheidungen als Umsetzungsvorschlag:
|
||||
|
||||
- **Verspätete Zusage:** Nach Fristablauf bleibt eine Rückmeldung möglich, solange der Einsatz läuft und der Alarm nicht storniert ist. Eine verspätete Zusage wird als solche angezeigt und muss von der Koordination bestätigt werden, damit sie nicht mit bereits organisiertem Ersatz kollidiert.
|
||||
- **Telefonische Rückmeldung:** Admin oder Koordination kann eine Zusage bzw. Absage für den Haushalt dokumentieren. Herkunft, handelndes Konto und Zeitpunkt bleiben nachvollziehbar.
|
||||
- **Antwort ändern:** Eine bereits dokumentierte Antwort wird nur durch Admin oder Koordination korrigiert. Eltern erhalten auf der Rückmeldeseite einen Hinweis, die Kita bei Änderungen zu kontaktieren.
|
||||
- **Stornieren:** Admin oder Koordination storniert mit einer internen Begründung. Alle angeschriebenen Elternkonten werden informiert; offene Links werden unwirksam. Eine neue Alarmierung derselben Einteilung ist danach als neuer Vorgang möglich.
|
||||
- **Token-Ende:** Für einen ganzen Kita-Tag endet die Rückmeldemöglichkeit spätestens mit dem Datum in Europe/Berlin; bei bestimmten Uhrzeiten mit dem Einsatzende. Die 30-Minuten-Frist für Eskalation ist davon unabhängig.
|
||||
- **Planänderungen und Tausch:** Aktive Alarme schützen die zugehörige Einteilung vor einem unbemerkten Familienwechsel oder Diensttausch. Ersatz darf nicht durch Änderung eines noch aktiven Alarms auf eine andere Familie übertragen werden.
|
||||
- **Erinnerung und erneuter Versand:** Eine Wiederholung startet die Antwortfrist nicht automatisch neu. E-Mail-Annahme durch den Versanddienst, Rückmeldung und tatsächliche Anwesenheit bleiben getrennte Informationen.
|
||||
|
||||
## Technische Umsetzung
|
||||
|
||||
Der bestehende `NotdienstAlert` speichert pro Elternkonto einen unabhängigen Status. Für die gemeinsame Haushaltsantwort wird ein übergeordneter Alarmvorgang benötigt; Empfänger, Tokens und Versandversuche sind untergeordnet. Bestehende Datensätze müssen bei der Schemaumstellung berücksichtigt werden, ohne widersprüchliche Einzelantworten als sichere Haushaltszusage zu übernehmen.
|
||||
|
||||
Am Vorgang werden Einteilung und Haushalt, auslösendes Konto, Zeitpunkt, Einsatzart, gegebenenfalls Uhrzeiten, Antwortfrist, gemeinsame Antwort, interne Zuordnung und Stornierungsdaten festgehalten. Empfängerdatensätze führen persönliche Tokens und deren Gültigkeit. Historie und Versandaufträge erlauben Wiederholung und nachvollziehbare Änderungen.
|
||||
|
||||
Alle Aktionen prüfen aktuelle Datenbankrolle, Kita-Zugehörigkeit und Zugriff serverseitig. Auslösung und gemeinsame Rückmeldung laufen transaktional. Eine Datenbanksicherung verhindert mehrere aktive Alarme für dieselbe Einteilung sowie widersprüchliche parallele Antworten.
|
||||
|
||||
Der Versand verwendet die vorhandene Resend-Anbindung mit persistenten Versandaufträgen. Elternmails enthalten ausschließlich notwendige Einsatzdaten. Interne Begründungen, Krankheitsdetails und Daten aus Personalzeitkonten werden nicht übernommen. Alarm-E-Mails sind unabhängig von der Abschalteinstellung für Personal-Entscheidungsmails.
|
||||
|
||||
Die Fristüberwachung braucht eine regelmäßig aufgerufene serverseitige Prüfung, auch wenn niemand die App geöffnet hat. Vorgesehen ist ein geschützter, einmal pro Minute aufgerufener Serverjob. Die Anzeige berechnet Fristablauf zusätzlich direkt aus der gespeicherten Antwortfrist. Die Benachrichtigung kann durch das Prüfintervall und den Mailtransport etwas nach Ablauf eintreffen. Für die Einführung muss der Job in der Hosting-Umgebung eingerichtet werden.
|
||||
|
||||
## Umsetzungsschritte
|
||||
|
||||
1. Gemeinsamen Alarmvorgang, Empfänger, Tokens, Verlauf und Schemaumstellung ergänzen.
|
||||
2. Auslösung, Haushaltsantwort, Korrektur, Stornierung und erneuten Versand absichern.
|
||||
3. E-Mail-Vorlagen, Versandaufträge und Benachrichtigung der Koordination anbinden.
|
||||
4. Alarmdialog, Rückmeldeseite, Dashboard-Hinweise und Statusübersicht umsetzen.
|
||||
5. Fristprüfung, Hosting-Konfiguration und Einführungsdokumentation ergänzen.
|
||||
6. Gemeinsame Haushaltsantworten, Fristen, Rollen, Versandfehler und Browserabläufe prüfen.
|
||||
|
||||
## Abnahmefälle
|
||||
|
||||
- Admin und Koordination dürfen auslösen; Eltern, Fachkräfte und Konten anderer Kitas dürfen es nicht.
|
||||
- Nur die im veröffentlichten Plan eingeteilte Familie wird zunächst angeschrieben.
|
||||
- Ganzer Kita-Tag und bestimmte Uhrzeiten erscheinen in E-Mail, App und Rückmeldeseite konsistent.
|
||||
- Eine Zusage oder Absage wirkt auf den gesamten Haushalt; weitere persönliche Links zeigen denselben Stand.
|
||||
- Zwei gleichzeitige Antworten, doppelte Auslösung und Fristprüfung erzeugen keine doppelten Vorgänge oder widersprüchlichen Zusagen.
|
||||
- Absage erzeugt sofort Klärungsbedarf; Fristablauf nach 30 Minuten erzeugt ihn auch bei geschlossener App.
|
||||
- Versandfehler verhindern keine Speicherung, unterbrechen nicht den Versand an weitere Empfänger und lassen sich gezielt wiederholen.
|
||||
- Verspätete Antwort, telefonisch dokumentierte Antwort und Stornierung bleiben nachvollziehbar.
|
||||
- Stornierte und zeitlich abgelaufene Links können keinen aktiven Einsatz zusagen.
|
||||
- Aktive Alarme schützen Einteilungen vor unbemerktem Tausch oder Familienwechsel.
|
||||
|
||||
## Vorhandene Grundlage
|
||||
|
||||
- `src/app/dashboard/actions.ts`: Auslösung und E-Mail-Versand, bisher ein separater Alarm pro Elternkonto.
|
||||
- `src/app/dashboard/alert-button.tsx`: Vorbereiteter, noch nicht eingebundener Auslösebutton.
|
||||
- `src/app/alert/[token]/`: Rückmeldeseite und Bestätigung, bisher nur Zusage und ohne zeitliche Token-Gültigkeit.
|
||||
- `src/app/dashboard/kalender/actions.ts`: Bestehender Tauschausschluss für aktive Alarmierungen.
|
||||
- `src/lib/mail.ts` und `src/lib/staff/email.ts`: Mailtransport sowie Vorlage für persistente, wiederholbare Versandaufträge.
|
||||
|
||||
Die Planung löst keine Alarme aus und versendet keine E-Mails.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Personalbereich: Arbeitszeit, Urlaub und Zeitkonto
|
||||
|
||||
Stand: 09.10.2026
|
||||
|
||||
## Einstieg und Zuständigkeiten
|
||||
|
||||
Der Bereich liegt unter `/dashboard/personal`. Kita-Admins (einschließlich Vorstand mit Rolle `ADMIN`) verwalten alle Personalprofile ihrer Kita. ErzieherInnen bearbeiten eigene Zeiten und Anträge. Eltern und Koordination haben keinen Zugriff. Der interne Teamkalender ist nur für Admins und ErzieherInnen zugänglich.
|
||||
|
||||
Neue Fachkräfte werden unter **ErzieherInnen → ErzieherIn anlegen** in einem Formular eingerichtet:
|
||||
|
||||
1. Vorname, Nachname und E-Mail-Adresse (Pflichtfelder).
|
||||
2. Tatsächlicher Beschäftigungsbeginn und separat der Start der Zeiterfassung (vorbelegt mit heute, änderbar). Die Erfassung darf nicht vor der Beschäftigung beginnen.
|
||||
3. **Fachkraft anlegen und einladen** speichert Stammdaten, Personalprofil, Accountverknüpfung und Mailauftrag gemeinsam in einer Transaktion. Unpassende oder schon verknüpfte E-Mail-Adressen verhindern die gesamte Anlage.
|
||||
4. Anschließend öffnet sich das Personalprofil. Dort werden datierte Netto-Sollstunden für Montag bis Sonntag, Jahresurlaub und ausdrücklich festgelegter Übertrag sowie vorhandene Überstunden eingerichtet. Der Anfangssaldo startet mit 0 Minuten und muss bei vorhandenen Überstunden vor der ersten Zeiterfassung angepasst werden.
|
||||
5. Die örtlichen Feiertage werden unter **Teamkalender** hinterlegt. Sie gelten separat von den Schließtagen des allgemeinen Kalenders.
|
||||
|
||||
Vorhandene Fachkräfte können ihre fehlende E-Mail und gegebenenfalls die beiden Startdaten direkt über **Bearbeiten** erhalten. Bereits eingerichtete Beschäftigungsdaten, Wochenmodelle und Konten bleiben dabei erhalten. Die E-Mail eines verknüpften Accounts wird angezeigt und kann im Stammdatendialog nicht geändert werden; Namensänderungen werden auch im verknüpften Fachkraft-Account übernommen.
|
||||
|
||||
Die Teamübersicht zeigt E-Mail und Zugangszustand: **Zugang fehlt**, **Einladung ausstehend**, **Account aktiviert** oder **Mailversand fehlgeschlagen**. Für offene Einladungen steht **Einladung erneut senden** zur Verfügung. Ein neuer Link ersetzt den alten. Ein Mailfehler entfernt keine Fachkraft: Er bleibt sichtbar, der Versand kann erneut angestoßen werden. Im Personalbereich kann außerdem der bestehende Mailauftrag erneut versucht werden.
|
||||
|
||||
Der Aktivierungsablauf verwendet die bestehende Passwort- und Consent-Einrichtung unter `/invite/[token]`. Neue Accounts erhalten einen persönlichen, einmal verwendbaren Aktivierungslink mit sieben Tagen Gültigkeit per E-Mail; im Personalprofil kann der Admin zusätzlich einen Link zum Kopieren erzeugen. Ein vorhandener verifizierter Fachkraft-Account derselben Kita ohne andere Profilverknüpfung wird verbunden, ohne eine Aktivierungsmail zu verschicken. Accounts anderer Kitas oder Rollen werden nicht übernommen.
|
||||
|
||||
Die gemeinsame Anlage benötigt keine zusätzlichen Datenbankfelder oder Umgebungsvariablen. Sie verwendet die bestehende Resend-Anbindung; siehe [Deployment und Mailversand](../deploy/DEPLOYMENT_UND_MAILVERSAND.md).
|
||||
|
||||
## Arbeitszeit und Überstunden
|
||||
|
||||
Pro Tag sind mehrere Arbeitsblöcke mit Beginn, Ende und Pause möglich. Zeitblöcke dürfen nicht überlappen. Die Pause wird in Minuten vom Block abgezogen. Zeiten werden für heutige oder vergangene Tage innerhalb der Beschäftigung und ab Erfassungsbeginn erfasst. Blöcke über Mitternacht werden auf zwei Tage aufgeteilt.
|
||||
|
||||
Die Tagesbilanz ist **Istzeit + Urlaub/Krankheit − Sollzeit**. Arbeit an einem freien Tag oder Feiertag zählt als zusätzliche Istzeit. Die Wochenansicht zeigt alle sieben Tage; in einer laufenden Woche fehlen zukünftige Arbeitszeiten noch, deshalb ist ihre Differenz vorläufig.
|
||||
|
||||
Die Fachkraft reicht ihre Woche nach dem letzten vorgesehenen Arbeitstag ein. Offene Abwesenheiten im Zeitraum müssen zuerst geklärt sein. Der Admin prüft die einzelnen Zeiten, genehmigt die Woche oder gibt sie mit Rückmeldung zurück. Eingereichte und genehmigte Wochen sperren Zeitänderungen. Eigene Wochen und eigene Anträge können nicht selbst freigegeben werden.
|
||||
|
||||
Beim Genehmigen wird die Tagesberechnung gespeichert. Nur genehmigte Wochen, der Anfangssaldo und wirksame manuelle Korrekturen zählen zum bestätigten Zeitkonto. Offene oder eingereichte Wochen wirken noch nicht auf dieses Konto. Eine Rückgabe entfernt die Wochenbuchung bis zur erneuten Freigabe. Fehler in manuellen Korrekturen werden durch eine begründete Gegenbuchung behoben.
|
||||
|
||||
## Feste Wochentage und seltene Wechsel
|
||||
|
||||
Wochenmodelle gelten ab ihrem Datum. Eine spätere Änderung überschreibt kein früheres Modell. Seltene Tausche werden über zwei Tagesausnahmen erfasst: der bisherige Arbeitstag erhält 0 Sollstunden, der Ersatztermin die vorgesehenen Stunden.
|
||||
|
||||
Genehmigte Abwesenheiten sowie eingereichte oder genehmigte Wochen schützen ihren Zeitraum auch vor Änderungen an Modellen, Ausnahmen und Feiertagen. Betroffene Freigaben müssen vor einer solchen Änderung zurückgegeben bzw. storniert werden. Grunddaten und Anfangssaldo werden nach der ersten Erfassung geschützt; das Beschäftigungsende bleibt über einen eigenen Ablauf verwaltbar, sofern bestehende Zeiten und Anträge nicht verletzt werden.
|
||||
|
||||
## Urlaub
|
||||
|
||||
Urlaub ist ganztägig oder für einen einzelnen halben Tag möglich. Nur vorgesehene Arbeitstage verbrauchen Urlaub. Wochenenden sind nicht pauschal frei: Entscheidend sind Wochenmodell und Tagesausnahmen. Feiertage verbrauchen keinen Urlaub und erzeugen keine Sollzeit. Ein halber Urlaubstag schreibt die Hälfte der Tages-Sollzeit gut; bei ungerader Minutenzahl wird auf eine ganze Minute gerundet.
|
||||
|
||||
Ein Jahreskonto führt Anspruch plus Übertrag, genommenen Urlaub, genehmigten geplanten Urlaub, offene Anträge und verfügbaren Rest. Offene Anträge werden bei weiteren Anträgen berücksichtigt. Abgelehnte und stornierte Anträge verbrauchen nichts. Zeiträume über den Jahreswechsel werden auf die jeweiligen Jahreskonten verteilt. Anspruch und Übertrag werden nicht automatisch anteilig berechnet oder zum Jahreswechsel übertragen.
|
||||
|
||||
Offene Anträge können geändert oder zurückgezogen werden. Bei genehmigten Anträgen wird eine Stornierung beantragt. Bis zur Entscheidung bleibt die Abwesenheit gebucht. Krankheit hinterlegt der Admin; sie entlastet die Sollzeit, ohne Urlaub zu verbrauchen. KollegInnen sehen Krankheit im Teamkalender nur als **Abwesend**, ohne persönliche Notizen oder Kontodaten.
|
||||
|
||||
## Freizeitausgleich
|
||||
|
||||
Freizeitausgleich wird für einen einzelnen vorgesehenen Arbeitstag in Stunden beantragt. Das bestätigte verfügbare Guthaben muss ausreichen; weitere offene Anträge werden dabei berücksichtigt.
|
||||
|
||||
Nach Genehmigung wird die Zeit reserviert. Freizeitausgleich erzeugt keine zusätzliche Istzeit oder Urlaubsgutschrift. Beispiel: 6 Stunden Soll, 5 Stunden Arbeit und 1 Stunde Freizeitausgleich ergeben eine Tagesbilanz von −1 Stunde. Mit der Wochenfreigabe wird diese Stunde im Zeitkonto gebucht und die Reservierung entfällt. Dadurch wird die Stunde genau einmal abgezogen. Bei offenen Stornierungen bleibt die Reservierung erhalten.
|
||||
|
||||
## Hinweise und Nachvollziehbarkeit
|
||||
|
||||
Neue Anträge und eingereichte Wochen erzeugen interne Hinweise für Kita-Admins. Entscheidungen und Rückgaben erzeugen Hinweise für die betroffene Fachkraft. Hinweise lassen sich als gelesen markieren; jede Person kann ausschließlich eigene Hinweise quittieren. Das Personalprofil zeigt die letzten 30 Änderungen. Im Datenmodell werden sämtliche Änderungen mit Zeitpunkt und handelnder User-ID gespeichert.
|
||||
|
||||
Parallele Änderungen laufen in serialisierbaren Datenbanktransaktionen mit Wiederholung bei Schreibkonflikten. Rollen, Accountstatus, Eigentümer und Kita-Zugehörigkeit werden serverseitig geprüft. Das Löschen von Fachkräften mit Personalprofil wird verhindert; sie können auf inaktiv gesetzt werden. Bei Accountlöschung bleiben Personalaufzeichnungen ohne Accountverknüpfung erhalten. Die Löschung einer Kita entfernt auch ihren Personalbereich.
|
||||
|
||||
## Einführung und Schema
|
||||
|
||||
Das Projekt verwendet weiterhin seinen vorhandenen Ablauf mit `prisma db push`. Es gibt keine vollständige versionierte Prisma-Migrationshistorie. Die neuen Tabellen sind additiv; vorhandene Personen erhalten noch kein automatisch befülltes Beschäftigungsprofil.
|
||||
|
||||
- Lokal: Abhängigkeiten installieren, Prisma-Client generieren, Schema gegen eine dafür vorgesehene Datenbank anwenden, App starten und Profile einrichten.
|
||||
- Im vorhandenen Docker-Ablauf erzeugt `npm run build:prod` den Client; `scripts/start-production.sh` wendet das Schema vor App-Start an.
|
||||
- [Prüfbares SQL](../deploy/sql/personalbereich.sql) beschreibt dieselbe additive Änderung gegen den dokumentierten Ausgangsstand. Es ist einmalig und nicht idempotent. Entweder den vorhandenen Schemaabgleich **oder** dieses SQL verwenden; das SQL nicht nach bereits erfolgtem Schemaabgleich erneut ausführen.
|
||||
- Ist der Personalbereich bereits auf Stand `043fed2` eingeführt, beschreibt [Personalbereich-E-Mail-SQL](../deploy/sql/personalbereich-email.sql) ausschließlich die zusätzlichen Mail-Tabellen und die Profileinstellung. Auch dieses Skript ist eine einmalige Alternative zum Schemaabgleich.
|
||||
|
||||
Die reale Projekt- und Produktionsdatenbank wurde bei dieser Umsetzung nicht verändert. Alle DB- und Browserprüfungen liefen mit synthetischen Daten in einer separaten lokalen PostgreSQL-Datenbank.
|
||||
|
||||
## Prüfungen
|
||||
|
||||
- `npm run test:staff`: Berechnungstests für Teilzeit, halbe Tage, Feiertage, Jahreswechsel, Statuswechsel, Pausen, Snapshots und Freizeitausgleich.
|
||||
- `npm run test:staff:integration`: echte Datenbankabläufe für Mandantentrennung, Rollen und Eigentümer, Anträge, Freigaben, parallele Änderungen, Sperren, Rückgaben, Aktivierungslinks und Beschäftigungsende.
|
||||
- Integrationstests akzeptieren ausschließlich `127.0.0.1:55439/kita_staff_test`. Beispiel: `DATABASE_URL=postgresql://USER@127.0.0.1:55439/kita_staff_test npm run test:staff:integration`. Die leere Testdatenbank vorher mit dem aktuellen Schema einrichten. Tests bereinigen nur ihre eigens erzeugten Testkitas.
|
||||
- Browserprüfung: Admin richtet Profil, 18-Stunden-Woche und 18 Urlaubstage ein; Erzieherin erfasst drei Blöcke mit Pausen, reicht eine 19-Stunden-Woche ein und beantragt einen Urlaubstag. Nach Adminfreigabe zeigt das Zeitkonto 11 Stunden (10 Stunden Anfangssaldo + 1 Stunde Wochenplus) und das Urlaubskonto 17 Tage. Der Urlaub erscheint im Teamkalender.
|
||||
|
||||
Ergebnisse der abschließenden Prüfung:
|
||||
|
||||
| Prüfung | Ergebnis |
|
||||
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Berechnungstests | 9 bestanden. |
|
||||
| Integrationstests | 25 bestanden; einschließlich gemeinsamer Anlage, vollständigem Rollback bei E-Mail-Konflikten, Bearbeitung bestehender Fachkräfte, Kontenschutz, Rollenprüfung und Empfänger, Opt-out, Versandfehler, Token-Erneuerung und paralleler Versandversuche. Testkitas danach bereinigt. |
|
||||
| TypeScript | Erfolgreich. |
|
||||
| ESLint für sämtliche geänderten Anwendungsteile und neue Tests | Erfolgreich, ohne Warnungen. |
|
||||
| Projektweites ESLint | Die bereits vorhandenen zwei `as any`-Fehler in `src/lib/auth-utils.ts` und neun Warnungen bestehen weiterhin. |
|
||||
| Endgültiger Produktionsbuild | Erfolgreich, einschließlich `/dashboard/personal`. |
|
||||
| Vollständiges und inkrementelles SQL-Skript | Erfolgreich in isolierten Prüfschemata; anschließend jeweils kein Unterschied zum Prisma-Schema. |
|
||||
| Browser | Admin- und ErzieherInnen-Ablauf einschließlich Freigaben erfolgreich. Mobile Ansicht und Arbeitszeitdialog ohne Seitenüberlauf geprüft. Abschalten der E-Mail-Hinweise im Demo-Profil gespeichert und nach Neuladen verifiziert; anschließend wieder eingeschaltet. |
|
||||
|
||||
Die vom bestehenden Build gemeldete Warnung zu mehreren Lockfiles bzw. dem Turbopack-Arbeitsverzeichnis und die bestehende Prisma-Konfigurationswarnung sind unabhängig vom Personalbereich. Eine produktive Bereitstellung oder Mailzustellung wurde nicht durchgeführt.
|
||||
|
||||
## Prüfung der gemeinsamen Fachkraft-Anlage (09.10.2026)
|
||||
|
||||
- 25 Personal-Integrationstests, TypeScript, ESLint der geänderten Anwendungsteile und Produktionsbuild erfolgreich.
|
||||
- Lokale Browserprüfung mit synthetischen Daten: Datum vor Beschäftigungsbeginn abgewiesen, Eingaben erhalten, korrigierte Anlage erfolgreich und unmittelbar zum Personalprofil weitergeleitet.
|
||||
- Resend im lokalen Produktionsbuild bewusst deaktiviert: gespeicherte Fachkraft und wiederholbarer Mailfehler in Personalbereich und Teamliste sichtbar; erneute Einladung aus der Teamliste erfolgreich ausgelöst.
|
||||
- Bestehende Fachkraft ohne Zugang zeigt E-Mail und fehlende Startdaten direkt im Bearbeitungsdialog. Mobilprüfung bei 390 × 844 Pixeln: Dialog ohne horizontalen Überlauf, längerer Inhalt innerhalb des Dialogs scrollbar.
|
||||
- Keine echten Aktivierungsmails versendet; keine Änderung an Produktionsdaten vorgenommen.
|
||||
|
||||
## E-Mail-Hinweise
|
||||
|
||||
Die E-Mail-Erweiterung wurde am 08.10.2026 ausdrücklich beauftragt. Sie verwendet die vorhandene Resend-Anbindung:
|
||||
|
||||
| Nachricht | Empfänger | Inhalt |
|
||||
| ------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| Accountaktivierung | Vom Kita-Admin eingetragene E-Mail-Adresse der Fachkraft | Kita, Name, persönlicher Aktivierungslink mit sieben Tagen Gültigkeit. |
|
||||
| Antrag / Änderung / Stornierung oder Arbeitswoche eingereicht | Alle Kita-Admins derselben Kita, einzeln angeschrieben | Name, Zeitraum und Hinweis auf Prüfung im geschützten Personalbereich. |
|
||||
| Entscheidung / Rückgabe | Account-Adresse der betroffenen Fachkraft | Art, Zeitraum und Status mit Link in den geschützten Personalbereich. |
|
||||
|
||||
Fachkräfte können Entscheidungsmails unter **Mein Profil → E-Mail-Hinweise** abschalten. Aktivierungslinks und interne App-Hinweise bleiben davon unabhängig. Krankheitsbuchungen erzeugen keine E-Mail. Private Notizen, Entscheidungsbegründungen und Zeit- oder Urlaubskontostände werden nicht per E-Mail übertragen.
|
||||
|
||||
Versandaufträge werden innerhalb derselben Datenbanktransaktion wie die Personalaktion gespeichert. Der Versand erfolgt anschließend; ein Fehler macht den gespeicherten Antrag nicht rückgängig. Ausstehende Mails erscheinen im Personalbereich mit **Versand erneut versuchen**. Admins dürfen die Aufträge ihrer Kita wiederholen, Fachkräfte nur eigene. Pro Aktion werden bis zu 50 ausstehende Aufträge verarbeitet. Es gibt keinen zusätzlichen Hintergrundjob.
|
||||
|
||||
Vor jedem Versand werden Kita-Zugehörigkeit, aktuelle Rolle, Accountverknüpfung und gegebenenfalls die Abschalteinstellung geprüft. Ersetzte, abgelaufene oder bereits verwendete Aktivierungslinks werden übersprungen. Eine fünfminütige Versandsperre verhindert parallele Versuche für denselben Auftrag; ein stabiler Resend-Idempotenzschlüssel vermindert doppelte Zustellungen bei Wiederholungen. Eine Zustellbestätigung des Empfängerpostfachs wird nicht erfasst.
|
||||
|
||||
Benötigt werden `RESEND_API_KEY`, `EMAIL_FROM` und eine öffentliche App-Adresse über `NEXT_PUBLIC_SITE_URL`, alternativ `AUTH_URL` oder `NEXTAUTH_URL`. Ohne Konfiguration bleibt ein Produktionsversand ausstehend und wird als Warnung angezeigt. Im Entwicklungsmodus ohne Resend-Schlüssel wird der bestehende lokale Mailtransport simuliert. Die Tests verwenden ausschließlich einen eingesetzten Testtransport; es wurden keine echten E-Mails verschickt.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Elternabläufe: Mitteilungen und Teilnahmeantworten
|
||||
|
||||
## Verhalten
|
||||
|
||||
- Die Übersicht zeigt offene Rückmeldungen und drei aktuelle Mitteilungen. Das Archiv unter `/dashboard/mitteilungen` enthält alle für das eigene Konto sichtbaren Meldungen, zwölf pro Seite.
|
||||
- Termine können eine Antwort pro Kind oder pro Familie verlangen. Familienzusagen brauchen mindestens einen teilnehmenden Erwachsenen; Absagen speichern 0 Erwachsene. Beide Elternkonten bearbeiten dieselbe Antwort.
|
||||
- Die Terminart schlägt bei neuen Terminen eine Antwortart vor. Die Verwaltung kann sie ändern, solange keine Antworten vorliegen. Danach verhindert auch die Server Action einen Wechsel. Normale Terminänderungen erhalten die bisherigen Teilnahmefelder.
|
||||
- Kinderantworten werden für alle eigenen aktiven Kinder gemeinsam in einer Transaktion gespeichert. Eigene und fremde Kinder dürfen nicht gemischt werden. Frist, Terminstatus, Haushalt, Kita und aktiviertes Terminmodul werden serverseitig geprüft.
|
||||
- Ohne eigene Rückmeldefrist gilt der Terminbeginn. Nach Fristablauf bleiben die Antworten im Kalender lesbar. Die Eingabe ist in Monatsansicht, Liste und Agenda erreichbar.
|
||||
- Empfängergruppen sind Eltern, ErzieherInnen oder beide. Die Gruppe steuert App-Anzeige, Lesestatus-Aktion, Anhänge und optionalen E-Mail-Versand. Admins können sämtliche Meldungen der eigenen Kita zur Verwaltung sehen. Eltern mit Koordinationsrolle gehören mit ihrem Haushalt zur Elterngruppe; Erzieherkonten gehören zur Erziehergruppe.
|
||||
- Teilnehmerhinweise werden nur bei einer Zusage des Haushalts oder für Admin/Koordination an den Kalender-Client übertragen.
|
||||
|
||||
## Bestehende Daten und Schemaaktualisierung
|
||||
|
||||
Das Projekt verwendet weiterhin `prisma db push`; es besitzt keine Prisma-Migrationshistorie. Der vorhandene Produktionsstart aktualisiert das Schema automatisch. Die neuen Pflichtfelder haben kompatible Defaults: bisherige Termine bleiben `CHILD`, bisherige Meldungen erhalten `ALLE`. Bestehende Kinderantworten werden nicht verändert.
|
||||
|
||||
Für eine kontrollierte, einmalige Aktualisierung einer Datenbank mit dem bisherigen Schema liegt zusätzlich die additive SQL-Datei `prisma/updates/20261007_parent_flows.sql` vor. Sie ist eine Alternative zum ersten `db push`, kein nachträglich anzuwendender zweiter Schritt. Beispiel:
|
||||
|
||||
```sh
|
||||
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 --single-transaction -f prisma/updates/20261007_parent_flows.sql
|
||||
npm run prisma:generate
|
||||
```
|
||||
|
||||
Die Datei gehört bewusst nicht in `prisma/migrations`: Eine Einführung von `prisma migrate deploy` würde zuerst eine Baseline für bereits existierende Datenbanken verlangen.
|
||||
|
||||
## Verifikation
|
||||
|
||||
```sh
|
||||
npm run test:parent-flows
|
||||
TEST_DATABASE_URL=postgresql://USER@127.0.0.1:PORT/TESTDB npm run test:parent-flows:integration
|
||||
npx tsc --noEmit
|
||||
npm run build
|
||||
```
|
||||
|
||||
Die Integrationstests benötigen eine Node.js-Version mit experimentellem Modul-Mocking (hier geprüft mit Node.js 26), eine ausdrücklich über `TEST_DATABASE_URL` gesetzte lokale PostgreSQL-Testdatenbank und das aktuelle Schema. Sie legen eigene Kitas mit zufälligen IDs an und entfernen ausschließlich diese Testkitas wieder. Kein automatischer Zugriff auf `DATABASE_URL` ohne Testfreigabe.
|
||||
|
||||
Die Tests prüfen Erwachsenenanzahl, gemischte Kinderantworten, gemeinsame Familienantworten, Fristablauf, Terminabsage, Moduldeaktivierung, Kita-/Haushaltsgrenzen, gesperrte Antwortart einschließlich paralleler erster Rückmeldung, erhaltene Terminoptionen sowie verweigerte Team-Meldungen und Anhänge für Eltern. E-Mail-Empfänger werden anhand derselben Gruppenregeln geprüft; es werden keine echten E-Mails verschickt.
|
||||
|
||||
Zusätzlich im Browser geprüft: Familienzusage, unterschiedliche Antworten für zwei Kinder, verschwundene offene Hinweise, Lesen/Ändern der gemeinsamen Antwort aus einem zweiten Elternkonto, abgelaufene Eingabe, Kalender-Monats- und Agendaansicht, Lesestatus, Archivnavigation, Verwaltungsauswertung, gesperrte Antwortart und Eltern-/Erzieher-Empfängertrennung. Die Rückmeldeformulare und Übersicht wurden auch bei 390 Pixeln Breite visuell geprüft.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Live-Testplan mein-kitaplaner.de
|
||||
|
||||
## Kopfbereich
|
||||
|
||||
- Zielsystem: `https://mein-kitaplaner.de`
|
||||
- Testdatum: `2026-05-17`
|
||||
- Strategie: echte Testdaten auf Produktion verwenden und anschließend bereinigen
|
||||
- Testkennzeichnung: alle Testnamen und Test-E-Mails mit `Codex Live-Test` kennzeichnen
|
||||
- Statuslegende:
|
||||
- `[ ]` offen
|
||||
- `[x]` erledigt
|
||||
- `[!]` Blocker / Beobachtung
|
||||
|
||||
## Testdaten
|
||||
|
||||
- Gründer/Admin: `hanivan790@acanok.com`
|
||||
- Test-Kita: `Codex Live-Test Kita-Verein 20260517-2343`
|
||||
- Elternteil: `kitatester1233@mailaddress.de`
|
||||
- Passwort: `<TEST_PASSWORD>`
|
||||
|
||||
Keine echten Passwörter, Secrets, Session-Werte, Tokens oder Invite-Links in diese Datei schreiben.
|
||||
|
||||
## Core Journey
|
||||
|
||||
- [x] Landingpage erreichbar.
|
||||
- Erwartung: `https://mein-kitaplaner.de` lädt mit aktuellem Landingpage-Content.
|
||||
- [x] Demo-CTA führt zum Kontaktformular.
|
||||
- Erwartung: CTA öffnet `/#kontakt` und das Formular ist sichtbar.
|
||||
- [x] Kontaktformular versendet Bestätigungsmail.
|
||||
- Bestätigt: Testmail an `nolip18234@acanok.com` ist angekommen.
|
||||
- [x] Registrierung: neuer Gründer/Admin kann Account erstellen.
|
||||
- Testdaten: eindeutige Admin-Testmail und `<TEST_PASSWORD>`.
|
||||
- Erwartung: Account wird erstellt, keine Fehlermeldung.
|
||||
- [x] Redirect nach Registrierung führt zu `/onboarding`.
|
||||
- Erwartung: Gründer landet nach Registrierung direkt im Onboarding.
|
||||
- [x] Onboarding: Kita wird mit Standardmodulen angelegt.
|
||||
- Testdaten: `Codex Live-Test Kita-Verein YYYYMMDD-HHMM`.
|
||||
- Erwartung: Notdienst, Kalender und Adressbuch bleiben standardmäßig aktiv.
|
||||
- [x] Redirect nach Onboarding führt zu `/dashboard`.
|
||||
- Erwartung: Dashboard lädt ohne erneute Anmeldung.
|
||||
- [x] Dashboard zeigt Kita-Namen und Admin-Navigation.
|
||||
- Erwartung: Sidebar zeigt Test-Kita sowie Admin-Menüpunkte wie Familienverwaltung, Dienstplan, Schwarzes Brett und ErzieherInnen.
|
||||
- [x] Familienverwaltung: Familie mit Kind und Elternteil anlegen.
|
||||
- Testdaten: Familie, Elternteil und Kind mit `Codex Live-Test` kennzeichnen.
|
||||
- Erwartung: Familie erscheint in der Liste.
|
||||
- [ ] Einladung wird per E-Mail versendet.
|
||||
- Erwartung: Eltern-Testadresse erhält eine Einladung.
|
||||
- Erst als erledigt markieren, wenn die Mail im Postfach bestätigt wurde.
|
||||
- [ ] Invite-Link öffnet Aktivierungsseite.
|
||||
- Erwartung: Seite `/invite/[token]` zeigt personalisierte Einladung und Kita-Namen.
|
||||
- Invite-Link nicht in diese Datei schreiben.
|
||||
- [ ] Invite-Validierung: Passwort-Pflicht, Passwort-Mismatch, Datenschutz-Pflicht.
|
||||
- Erwartung: fehlende oder unterschiedliche Passwörter und fehlende Datenschutzerklärung erzeugen sichtbare Fehler.
|
||||
- [ ] Elternteil kann Einladung annehmen und wird eingeloggt.
|
||||
- Erwartung: Passwort setzen, Datenschutzerklärung akzeptieren, optional Adressbuch-Opt-in wählen, danach Redirect zu `/dashboard`.
|
||||
- [ ] Elternrolle sieht nur erlaubte Navigation.
|
||||
- Erwartung: Eltern sehen keine Admin-only Punkte wie Familienverwaltung, Dienstplan, Schwarzes Brett-Admin, ErzieherInnen.
|
||||
- [ ] Logout/Login für Admin und Elternteil funktionieren.
|
||||
- Erwartung: beide Testaccounts können sich abmelden und mit `<TEST_PASSWORD>` erneut anmelden.
|
||||
- [x] Zugriffsschutz: `/dashboard` ohne Session leitet zu `/login`.
|
||||
- Erwartung: ausgeloggter Aufruf von `/dashboard` führt zu `/login?callbackUrl=%2Fdashboard` oder entsprechender Login-Route.
|
||||
- [ ] Cleanup: Test-Kita/User/Familie über Superadmin löschen.
|
||||
- Erwartung: Test-Kita wird über Superadmin-Diagnose mit exakter Namensbestätigung gelöscht.
|
||||
- Erst als erledigt markieren, wenn Superadmin-Ansicht keine Test-Kita/Test-User mehr zeigt.
|
||||
- [ ] Nach Cleanup: Test-Login funktioniert nicht mehr / Daten nicht sichtbar.
|
||||
- Erwartung: Admin- und Eltern-Testlogin schlagen fehl; Test-Kita erscheint nicht mehr.
|
||||
|
||||
## Beobachtungen
|
||||
|
||||
- [x] `2026-05-17`: Kontaktformular auf Produktion getestet. Bestätigungsmail an `nolip18234@acanok.com` ist angekommen.
|
||||
- [x] `2026-05-17`: Registrierung mit `hanivan790@acanok.com`, Redirect nach `/onboarding`, Onboarding mit `Codex Live-Test Kita-Verein 20260517-2343` und Dashboard/Admin-Navigation erfolgreich geprüft.
|
||||
- [!] `2026-05-17`: Familienanlage mit Elternadresse `nolip18234@acanok.com` blockiert, weil die E-Mail-Adresse bereits existiert. Mit `kitatester1233@mailaddress.de` erfolgreich fortgesetzt.
|
||||
- [x] `2026-05-17`: Admin-Logout, Zugriffsschutz für `/dashboard` ohne Session und Admin-Login mit temporärem Passwort erfolgreich geprüft. Kombinierter Login-Check bleibt offen, bis ein Elternaccount aktiviert werden kann.
|
||||
- [x] `2026-05-17`: Familie `Codex Live-Test Familie 20260517-2343` mit Kind und Elternteil `kitatester1233@mailaddress.de` erfolgreich angelegt; Status in der Familienverwaltung: `Einladung offen`.
|
||||
- [ ] `2026-05-17`: Im Familien-Details-Dialog ist kein Invite-Link sichtbar; Fortsetzung der Invite-Tests benötigt Mailbestätigung und Invite-Link aus dem Postfach.
|
||||
- [ ] Mailzeit Einladung Elternteil: offen.
|
||||
- [ ] Cleanup-Ergebnis: offen.
|
||||
|
||||
## Pflege-Regeln
|
||||
|
||||
- Erledigte Schritte während des Tests direkt von `[ ]` auf `[x]` setzen.
|
||||
- Blocker mit `[!]` markieren und kurz im Abschnitt Beobachtungen beschreiben.
|
||||
- Mailversand nur als erledigt markieren, wenn die Mail im jeweiligen Postfach bestätigt wurde.
|
||||
- Keine echten Passwörter, Secrets, Tokens oder vollständigen Invite-Links dokumentieren.
|
||||
- Cleanup erst als erledigt markieren, wenn die Testdaten in der Superadmin-Ansicht nicht mehr sichtbar sind.
|
||||
+22
-1
@@ -1,12 +1,33 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
experimental: { serverActions: { bodySizeLimit: "26mb" } },
|
||||
async headers() {
|
||||
return [{ source: "/:path*", headers: [
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
{ key: "Referrer-Policy", value: "no-referrer" },
|
||||
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
|
||||
...(process.env.NODE_ENV === "production" ? [{ key: "Strict-Transport-Security", value: "max-age=31536000" }] : []),
|
||||
] }];
|
||||
},
|
||||
images: {
|
||||
localPatterns: [
|
||||
{ pathname: "/landing/**", search: "" },
|
||||
{ pathname: "/og-image.png", search: "" },
|
||||
{ pathname: "/_next/static/media/**", search: "" },
|
||||
],
|
||||
maximumDiskCacheSize: 128 * 1024 * 1024,
|
||||
maximumResponseBody: 10 * 1024 * 1024,
|
||||
maximumRedirects: 0,
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "images.unsplash.com",
|
||||
pathname: "/**",
|
||||
port: "",
|
||||
pathname: "/photo-1503454537195-1dcabb73ffb9",
|
||||
search: "?auto=format&fit=crop&w=2400&q=86",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
Generated
+572
-520
File diff suppressed because it is too large
Load Diff
+28
-10
@@ -3,23 +3,33 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "NODE_ENV=development prisma db push && NODE_ENV=development prisma db seed && next dev",
|
||||
"build": "next build",
|
||||
"build:prod": "prisma generate && next build",
|
||||
"dev": "next dev",
|
||||
"build": "next build && node scripts/prepare-standalone.mjs",
|
||||
"build:prod": "prisma generate && next build && node scripts/prepare-standalone.mjs",
|
||||
"start": "next start",
|
||||
"start:prod": "next start",
|
||||
"start:prod": "sh .next/standalone/scripts/start-production.sh",
|
||||
"lint": "eslint",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:studio": "prisma studio",
|
||||
"db:seed": "NODE_ENV=development prisma db seed",
|
||||
"db:seed:reset": "NODE_ENV=development prisma db seed -- --reset"
|
||||
"db:seed": "prisma db seed",
|
||||
"db:seed:reset": "prisma db seed -- --reset",
|
||||
"db:migrate:deploy": "prisma migrate deploy",
|
||||
"test:security": "node --test tests/security.test.cjs",
|
||||
"db:provision-runtime": "node scripts/provision-runtime-role.mjs",
|
||||
"uploads:backfill": "tsx scripts/backfill-attachment-sizes.ts",
|
||||
"uploads:cleanup": "tsx scripts/cleanup-attachments.ts",
|
||||
"test:security:http": "node tests/security-http.cjs",
|
||||
"test:staff": "tsx --test tests/staff-calculations.test.ts",
|
||||
"test:staff:integration": "tsx --test tests/staff-service.test.ts",
|
||||
"test:alarms": "tsx --experimental-test-module-mocks --test tests/notdienst-alarm.test.ts",
|
||||
"test:parent-flows": "tsx --test tests/parent-flows.test.ts",
|
||||
"test:parent-flows:integration": "tsx --experimental-test-module-mocks --test tests/parent-flows.integration.test.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.2",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@prisma/client": "^6.19.3",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
@@ -36,8 +46,8 @@
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"lucide-react": "^1.14.0",
|
||||
"next": "16.2.4",
|
||||
"next-auth": "^5.0.0-beta.31",
|
||||
"next": "^16.4.0",
|
||||
"next-auth": "^5.0.0-beta.32",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
@@ -57,10 +67,18 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.4",
|
||||
"eslint-config-next": "^16.4.0",
|
||||
"prisma": "^6.19.3",
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"overrides": {
|
||||
"@prisma/config": {
|
||||
"deepmerge-ts": "8.0.0"
|
||||
},
|
||||
"tsx": {
|
||||
"esbuild": "^0.28.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,713 @@
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "UserRole" AS ENUM ('SUPERADMIN', 'ADMIN', 'KOORDINATOR', 'ERZIEHER', 'ELTERN');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "InvitationStatus" AS ENUM ('PENDING', 'ACCEPTED', 'EXPIRED', 'REVOKED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "TerminType" AS ENUM ('KITA_FEST', 'SCHLIESSTAG', 'TEAMTAG', 'MITMACH_TAG', 'ELTERNABEND', 'MITGLIEDERVERSAMMLUNG', 'ELTERNCAFE', 'GEBURTSTAG_INTERN', 'GEBURTSTAG_EXTERN', 'SONSTIGES');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "TerminStatus" AS ENUM ('PENDING', 'CONFIRMED', 'REJECTED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "EventParticipationStatus" AS ENUM ('ATTENDING', 'NOT_ATTENDING');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AuditTargetType" AS ENUM ('KITA', 'USER');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotdienstPlanStatus" AS ENUM ('DRAFT', 'PUBLISHED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotdienstAlertStatus" AS ENUM ('PENDING', 'CONFIRMED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotdienstSwapStatus" AS ENUM ('PENDING', 'ACCEPTED', 'DECLINED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "DutyAssignmentStatus" AS ENUM ('PLANNED', 'DONE', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AbsenceReason" AS ENUM ('ILLNESS', 'VACATION', 'OTHER');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "kitas" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"notdienstModuleEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"terminModuleEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"adressbuchModuleEnabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"notdienstMinPerChildPerMonth" INTEGER NOT NULL DEFAULT 2,
|
||||
"notdienstReminderDaysBefore" INTEGER NOT NULL DEFAULT 7,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "kitas_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "families" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "families_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "users" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT,
|
||||
"familyId" TEXT,
|
||||
"email" TEXT NOT NULL,
|
||||
"passwordHash" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"role" "UserRole" NOT NULL DEFAULT 'ELTERN',
|
||||
"phone" TEXT,
|
||||
"street" TEXT,
|
||||
"postalCode" TEXT,
|
||||
"city" TEXT,
|
||||
"privacyPolicyAcceptedAt" TIMESTAMP(3),
|
||||
"privacyPolicyVersion" TEXT,
|
||||
"directoryOptInAt" TIMESTAMP(3),
|
||||
"emailVerifiedAt" TIMESTAMP(3),
|
||||
"lastLoginAt" TIMESTAMP(3),
|
||||
"failedLoginAttempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"lockedUntil" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "children" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"dateOfBirth" TIMESTAMP(3),
|
||||
"notes" TEXT,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "children_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "educators" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "educators_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "parent_duties" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "parent_duties_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "parent_duty_assignments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"dutyId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "parent_duty_assignments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "duty_types" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "duty_types_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "duty_assignments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"dutyTypeId" TEXT NOT NULL,
|
||||
"startDate" DATE NOT NULL,
|
||||
"endDate" DATE NOT NULL,
|
||||
"status" "DutyAssignmentStatus" NOT NULL DEFAULT 'PLANNED',
|
||||
"reminderSentAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "duty_assignments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "absences" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"childId" TEXT NOT NULL,
|
||||
"startDate" DATE NOT NULL,
|
||||
"endDate" DATE NOT NULL,
|
||||
"reason" "AbsenceReason" NOT NULL,
|
||||
"note" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "absences_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "announcements" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"authorId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "announcements_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "attachments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"announcementId" TEXT NOT NULL,
|
||||
"fileName" TEXT NOT NULL,
|
||||
"fileUrl" TEXT NOT NULL,
|
||||
"fileType" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "attachments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "announcement_reads" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"announcementId" TEXT NOT NULL,
|
||||
"readAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "announcement_reads_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "invitations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"role" "UserRole" NOT NULL DEFAULT 'ELTERN',
|
||||
"token" TEXT NOT NULL,
|
||||
"status" "InvitationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"acceptedAt" TIMESTAMP(3),
|
||||
"invitedById" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "invitations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "termine" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"type" "TerminType" NOT NULL,
|
||||
"status" "TerminStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"startDate" TIMESTAMP(3) NOT NULL,
|
||||
"endDate" TIMESTAMP(3) NOT NULL,
|
||||
"allDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"mitbringselListEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"requiresRsvp" BOOLEAN NOT NULL DEFAULT false,
|
||||
"rsvpDeadline" TIMESTAMP(3),
|
||||
"participantInfo" TEXT,
|
||||
"createdById" TEXT,
|
||||
"approvedById" TEXT,
|
||||
"approvedAt" TIMESTAMP(3),
|
||||
"rejectionReason" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "termine_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "event_participations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"childId" TEXT NOT NULL,
|
||||
"status" "EventParticipationStatus" NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "event_participations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mitbringsel_items" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"terminId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "mitbringsel_items_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_plans" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"year" INTEGER NOT NULL,
|
||||
"month" INTEGER NOT NULL,
|
||||
"status" "NotdienstPlanStatus" NOT NULL DEFAULT 'DRAFT',
|
||||
"createdById" TEXT,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "notdienst_plans_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_availabilities" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"childId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "notdienst_availabilities_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_assignments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"planId" TEXT NOT NULL,
|
||||
"childId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "notdienst_assignments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_swap_requests" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"requesterUserId" TEXT NOT NULL,
|
||||
"requesterFamilyId" TEXT NOT NULL,
|
||||
"targetAssignmentId" TEXT NOT NULL,
|
||||
"offeredAssignmentId" TEXT NOT NULL,
|
||||
"status" "NotdienstSwapStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"message" TEXT,
|
||||
"respondedById" TEXT,
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "notdienst_swap_requests_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alerts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"assignmentId" TEXT NOT NULL,
|
||||
"parentUserId" TEXT NOT NULL,
|
||||
"triggeredById" TEXT,
|
||||
"educatorId" TEXT,
|
||||
"status" "NotdienstAlertStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"confirmationToken" TEXT NOT NULL,
|
||||
"triggeredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"confirmedAt" TIMESTAMP(3),
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "notdienst_alerts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "audit_logs" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorUserId" TEXT,
|
||||
"actorEmail" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" "AuditTargetType" NOT NULL,
|
||||
"targetId" TEXT NOT NULL,
|
||||
"targetLabel" TEXT NOT NULL,
|
||||
"targetKitaId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "verification_tokens" (
|
||||
"identifier" TEXT NOT NULL,
|
||||
"token" TEXT NOT NULL,
|
||||
"expires" TIMESTAMP(3) NOT NULL
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "kitas_slug_key" ON "kitas"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "families_kitaId_idx" ON "families"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "users_kitaId_idx" ON "users"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "users_familyId_idx" ON "users"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "users_kitaId_role_idx" ON "users"("kitaId", "role");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "children_kitaId_idx" ON "children"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "children_familyId_idx" ON "children"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "educators_kitaId_idx" ON "educators"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "parent_duties_kitaId_idx" ON "parent_duties"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "parent_duties_kitaId_name_key" ON "parent_duties"("kitaId", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "parent_duty_assignments_kitaId_idx" ON "parent_duty_assignments"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "parent_duty_assignments_userId_idx" ON "parent_duty_assignments"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "parent_duty_assignments_dutyId_userId_key" ON "parent_duty_assignments"("dutyId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "duty_types_kitaId_idx" ON "duty_types"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "duty_types_kitaId_name_key" ON "duty_types"("kitaId", "name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "duty_assignments_kitaId_startDate_idx" ON "duty_assignments"("kitaId", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "duty_assignments_familyId_startDate_idx" ON "duty_assignments"("familyId", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "duty_assignments_kitaId_dutyTypeId_startDate_key" ON "duty_assignments"("kitaId", "dutyTypeId", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "absences_kitaId_startDate_endDate_idx" ON "absences"("kitaId", "startDate", "endDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "absences_childId_startDate_idx" ON "absences"("childId", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "announcements_kitaId_createdAt_idx" ON "announcements"("kitaId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "announcements_authorId_idx" ON "announcements"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "attachments_announcementId_idx" ON "attachments"("announcementId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "announcement_reads_announcementId_idx" ON "announcement_reads"("announcementId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "announcement_reads_userId_announcementId_key" ON "announcement_reads"("userId", "announcementId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "invitations_token_key" ON "invitations"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "invitations_kitaId_idx" ON "invitations"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "invitations_kitaId_email_key" ON "invitations"("kitaId", "email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "termine_kitaId_startDate_idx" ON "termine"("kitaId", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "termine_kitaId_status_idx" ON "termine"("kitaId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "event_participations_kitaId_idx" ON "event_participations"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "event_participations_childId_idx" ON "event_participations"("childId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "event_participations_eventId_childId_key" ON "event_participations"("eventId", "childId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mitbringsel_items_kitaId_idx" ON "mitbringsel_items"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mitbringsel_items_terminId_idx" ON "mitbringsel_items"("terminId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_plans_kitaId_idx" ON "notdienst_plans"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_plans_kitaId_year_month_key" ON "notdienst_plans"("kitaId", "year", "month");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_availabilities_kitaId_date_idx" ON "notdienst_availabilities"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_availabilities_userId_idx" ON "notdienst_availabilities"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_availabilities_childId_date_key" ON "notdienst_availabilities"("childId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_assignments_kitaId_date_idx" ON "notdienst_assignments"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_assignments_planId_date_key" ON "notdienst_assignments"("planId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_swap_requests_kitaId_status_idx" ON "notdienst_swap_requests"("kitaId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_swap_requests_requesterFamilyId_status_idx" ON "notdienst_swap_requests"("requesterFamilyId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_swap_requests_targetAssignmentId_status_idx" ON "notdienst_swap_requests"("targetAssignmentId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_swap_requests_offeredAssignmentId_status_idx" ON "notdienst_swap_requests"("offeredAssignmentId", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alerts_confirmationToken_key" ON "notdienst_alerts"("confirmationToken");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alerts_kitaId_idx" ON "notdienst_alerts"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alerts_assignmentId_idx" ON "notdienst_alerts"("assignmentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alerts_parentUserId_idx" ON "notdienst_alerts"("parentUserId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_logs_actorUserId_idx" ON "audit_logs"("actorUserId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_logs_targetType_targetId_idx" ON "audit_logs"("targetType", "targetId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_logs_targetKitaId_idx" ON "audit_logs"("targetKitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "audit_logs_createdAt_idx" ON "audit_logs"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "verification_tokens_token_key" ON "verification_tokens"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "verification_tokens_identifier_token_key" ON "verification_tokens"("identifier", "token");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "families" ADD CONSTRAINT "families_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "users" ADD CONSTRAINT "users_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "users" ADD CONSTRAINT "users_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "children" ADD CONSTRAINT "children_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "children" ADD CONSTRAINT "children_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "educators" ADD CONSTRAINT "educators_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "parent_duties" ADD CONSTRAINT "parent_duties_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "parent_duty_assignments" ADD CONSTRAINT "parent_duty_assignments_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "parent_duty_assignments" ADD CONSTRAINT "parent_duty_assignments_dutyId_fkey" FOREIGN KEY ("dutyId") REFERENCES "parent_duties"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "parent_duty_assignments" ADD CONSTRAINT "parent_duty_assignments_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "duty_types" ADD CONSTRAINT "duty_types_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "duty_assignments" ADD CONSTRAINT "duty_assignments_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "duty_assignments" ADD CONSTRAINT "duty_assignments_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "duty_assignments" ADD CONSTRAINT "duty_assignments_dutyTypeId_fkey" FOREIGN KEY ("dutyTypeId") REFERENCES "duty_types"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "absences" ADD CONSTRAINT "absences_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "absences" ADD CONSTRAINT "absences_childId_fkey" FOREIGN KEY ("childId") REFERENCES "children"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "announcements" ADD CONSTRAINT "announcements_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "announcements" ADD CONSTRAINT "announcements_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "attachments" ADD CONSTRAINT "attachments_announcementId_fkey" FOREIGN KEY ("announcementId") REFERENCES "announcements"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "announcement_reads" ADD CONSTRAINT "announcement_reads_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "announcement_reads" ADD CONSTRAINT "announcement_reads_announcementId_fkey" FOREIGN KEY ("announcementId") REFERENCES "announcements"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "invitations" ADD CONSTRAINT "invitations_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "invitations" ADD CONSTRAINT "invitations_invitedById_fkey" FOREIGN KEY ("invitedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "termine" ADD CONSTRAINT "termine_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "termine" ADD CONSTRAINT "termine_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "termine" ADD CONSTRAINT "termine_approvedById_fkey" FOREIGN KEY ("approvedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "event_participations" ADD CONSTRAINT "event_participations_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "event_participations" ADD CONSTRAINT "event_participations_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "termine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "event_participations" ADD CONSTRAINT "event_participations_childId_fkey" FOREIGN KEY ("childId") REFERENCES "children"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mitbringsel_items" ADD CONSTRAINT "mitbringsel_items_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mitbringsel_items" ADD CONSTRAINT "mitbringsel_items_terminId_fkey" FOREIGN KEY ("terminId") REFERENCES "termine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mitbringsel_items" ADD CONSTRAINT "mitbringsel_items_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_plans" ADD CONSTRAINT "notdienst_plans_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_plans" ADD CONSTRAINT "notdienst_plans_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_availabilities" ADD CONSTRAINT "notdienst_availabilities_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_availabilities" ADD CONSTRAINT "notdienst_availabilities_childId_fkey" FOREIGN KEY ("childId") REFERENCES "children"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_availabilities" ADD CONSTRAINT "notdienst_availabilities_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_assignments" ADD CONSTRAINT "notdienst_assignments_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_assignments" ADD CONSTRAINT "notdienst_assignments_planId_fkey" FOREIGN KEY ("planId") REFERENCES "notdienst_plans"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_assignments" ADD CONSTRAINT "notdienst_assignments_childId_fkey" FOREIGN KEY ("childId") REFERENCES "children"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_requesterUserId_fkey" FOREIGN KEY ("requesterUserId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_requesterFamilyId_fkey" FOREIGN KEY ("requesterFamilyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_targetAssignmentId_fkey" FOREIGN KEY ("targetAssignmentId") REFERENCES "notdienst_assignments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_offeredAssignmentId_fkey" FOREIGN KEY ("offeredAssignmentId") REFERENCES "notdienst_assignments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_respondedById_fkey" FOREIGN KEY ("respondedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_assignmentId_fkey" FOREIGN KEY ("assignmentId") REFERENCES "notdienst_assignments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_parentUserId_fkey" FOREIGN KEY ("parentUserId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_triggeredById_fkey" FOREIGN KEY ("triggeredById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_educatorId_fkey" FOREIGN KEY ("educatorId") REFERENCES "educators"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_actorUserId_fkey" FOREIGN KEY ("actorUserId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,102 @@
|
||||
BEGIN;
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "disabledAt" TIMESTAMP(3),
|
||||
ADD COLUMN "sessionVersion" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "rate_limit_buckets" (
|
||||
"key" TEXT NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
"resetAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "rate_limit_buckets_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "pending_registrations" (
|
||||
"email" TEXT NOT NULL,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "pending_registrations_pkey" PRIMARY KEY ("email")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "rate_limit_buckets_resetAt_idx" ON "rate_limit_buckets"("resetAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "pending_registrations_tokenHash_key" ON "pending_registrations"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "pending_registrations_expiresAt_idx" ON "pending_registrations"("expiresAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "families_id_kitaId_key" ON "families"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_id_kitaId_key" ON "users"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "children_id_kitaId_key" ON "children"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "educators_id_kitaId_key" ON "educators"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "parent_duties_id_kitaId_key" ON "parent_duties"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "duty_types_id_kitaId_key" ON "duty_types"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "termine_id_kitaId_key" ON "termine"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_plans_id_kitaId_key" ON "notdienst_plans"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_assignments_id_kitaId_key" ON "notdienst_assignments"("id", "kitaId");
|
||||
|
||||
|
||||
-- Additional composite tenant foreign keys deliberately supplement the Prisma single-ID relations.
|
||||
-- NO ACTION preserves their existing Cascade/SetNull behavior; validation rejects inconsistent legacy rows.
|
||||
ALTER TABLE "users" ADD CONSTRAINT "users_familyId_tenant_fkey" FOREIGN KEY ("familyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "children" ADD CONSTRAINT "children_familyId_tenant_fkey" FOREIGN KEY ("familyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "parent_duty_assignments" ADD CONSTRAINT "parent_duty_assignments_dutyId_tenant_fkey" FOREIGN KEY ("dutyId", "kitaId") REFERENCES "parent_duties"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "parent_duty_assignments" ADD CONSTRAINT "parent_duty_assignments_userId_tenant_fkey" FOREIGN KEY ("userId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "duty_assignments" ADD CONSTRAINT "duty_assignments_familyId_tenant_fkey" FOREIGN KEY ("familyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "duty_assignments" ADD CONSTRAINT "duty_assignments_dutyTypeId_tenant_fkey" FOREIGN KEY ("dutyTypeId", "kitaId") REFERENCES "duty_types"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "absences" ADD CONSTRAINT "absences_childId_tenant_fkey" FOREIGN KEY ("childId", "kitaId") REFERENCES "children"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "announcements" ADD CONSTRAINT "announcements_authorId_tenant_fkey" FOREIGN KEY ("authorId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "invitations" ADD CONSTRAINT "invitations_invitedById_tenant_fkey" FOREIGN KEY ("invitedById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "termine" ADD CONSTRAINT "termine_createdById_tenant_fkey" FOREIGN KEY ("createdById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "termine" ADD CONSTRAINT "termine_approvedById_tenant_fkey" FOREIGN KEY ("approvedById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "event_participations" ADD CONSTRAINT "event_participations_eventId_tenant_fkey" FOREIGN KEY ("eventId", "kitaId") REFERENCES "termine"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "event_participations" ADD CONSTRAINT "event_participations_childId_tenant_fkey" FOREIGN KEY ("childId", "kitaId") REFERENCES "children"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "mitbringsel_items" ADD CONSTRAINT "mitbringsel_items_terminId_tenant_fkey" FOREIGN KEY ("terminId", "kitaId") REFERENCES "termine"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "mitbringsel_items" ADD CONSTRAINT "mitbringsel_items_userId_tenant_fkey" FOREIGN KEY ("userId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_plans" ADD CONSTRAINT "notdienst_plans_createdById_tenant_fkey" FOREIGN KEY ("createdById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_availabilities" ADD CONSTRAINT "notdienst_availabilities_childId_tenant_fkey" FOREIGN KEY ("childId", "kitaId") REFERENCES "children"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_availabilities" ADD CONSTRAINT "notdienst_availabilities_userId_tenant_fkey" FOREIGN KEY ("userId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_assignments" ADD CONSTRAINT "notdienst_assignments_planId_tenant_fkey" FOREIGN KEY ("planId", "kitaId") REFERENCES "notdienst_plans"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_assignments" ADD CONSTRAINT "notdienst_assignments_childId_tenant_fkey" FOREIGN KEY ("childId", "kitaId") REFERENCES "children"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_requesterUserId_tenant_fkey" FOREIGN KEY ("requesterUserId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_requesterFamilyId_tenant_fkey" FOREIGN KEY ("requesterFamilyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_targetAssignmentId_tenant_fkey" FOREIGN KEY ("targetAssignmentId", "kitaId") REFERENCES "notdienst_assignments"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_offeredAssignmentId_tenant_fkey" FOREIGN KEY ("offeredAssignmentId", "kitaId") REFERENCES "notdienst_assignments"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_swap_requests" ADD CONSTRAINT "notdienst_swap_requests_respondedById_tenant_fkey" FOREIGN KEY ("respondedById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_assignmentId_tenant_fkey" FOREIGN KEY ("assignmentId", "kitaId") REFERENCES "notdienst_assignments"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_parentUserId_tenant_fkey" FOREIGN KEY ("parentUserId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_triggeredById_tenant_fkey" FOREIGN KEY ("triggeredById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_educatorId_tenant_fkey" FOREIGN KEY ("educatorId", "kitaId") REFERENCES "educators"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
|
||||
-- Existing founder registrations previously set this timestamp without verification.
|
||||
UPDATE users SET "emailVerifiedAt" = NULL, "sessionVersion" = "sessionVersion" + 1
|
||||
WHERE role = 'ADMIN' AND "kitaId" IS NULL;
|
||||
-- Preserve existing administrative account locks separately from temporary brute-force lockouts.
|
||||
UPDATE users SET "disabledAt" = NOW(), "sessionVersion" = "sessionVersion" + 1
|
||||
WHERE "lockedUntil" >= TIMESTAMP '2099-01-01';
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,20 @@
|
||||
BEGIN;
|
||||
-- AlterTable
|
||||
ALTER TABLE "announcement_reads" ADD COLUMN "kitaId" TEXT;
|
||||
UPDATE announcement_reads AS r SET "kitaId" = a."kitaId" FROM announcements AS a WHERE a.id = r."announcementId";
|
||||
ALTER TABLE announcement_reads ALTER COLUMN "kitaId" SET NOT NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "announcements_id_kitaId_key" ON "announcements"("id", "kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "announcement_reads_kitaId_idx" ON "announcement_reads"("kitaId");
|
||||
|
||||
|
||||
ALTER TABLE users ADD CONSTRAINT users_family_requires_tenant CHECK ("familyId" IS NULL OR "kitaId" IS NOT NULL);
|
||||
ALTER TABLE announcement_reads ADD CONSTRAINT announcement_reads_user_tenant_fkey
|
||||
FOREIGN KEY ("userId", "kitaId") REFERENCES users(id, "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE announcement_reads ADD CONSTRAINT announcement_reads_announcement_tenant_fkey
|
||||
FOREIGN KEY ("announcementId", "kitaId") REFERENCES announcements(id, "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "attachments" ADD COLUMN "sizeBytes" INTEGER;
|
||||
@@ -0,0 +1,483 @@
|
||||
BEGIN;
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RsvpMode" AS ENUM ('CHILD', 'FAMILY');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AnnouncementAudience" AS ENUM ('ELTERN', 'ERZIEHER', 'ALLE');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "NotdienstAlarmStatus" AS ENUM ('PENDING', 'CONFIRMED', 'DECLINED', 'LATE_CONFIRMATION', 'REVIEW_REQUIRED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffRequestStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'CANCEL_REQUESTED', 'CANCELLED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffLeaveKind" AS ENUM ('VACATION', 'TIME_OFF', 'SICKNESS');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StaffWeekStatus" AS ENUM ('DRAFT', 'SUBMITTED', 'APPROVED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "staffDecisionEmails" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "announcements" ADD COLUMN "audience" "AnnouncementAudience" NOT NULL DEFAULT 'ALLE';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "termine" ADD COLUMN "rsvpMode" "RsvpMode" NOT NULL DEFAULT 'CHILD';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "notdienst_alerts" ADD COLUMN "alarmId" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_profiles" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"educatorId" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"employmentStart" DATE NOT NULL,
|
||||
"employmentEnd" DATE,
|
||||
"trackingStart" DATE NOT NULL,
|
||||
"openingMinutes" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_profiles_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_emails" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"toAdmins" BOOLEAN NOT NULL DEFAULT false,
|
||||
"subject" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"inviteToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"skippedAt" TIMESTAMP(3),
|
||||
"leaseUntil" TIMESTAMP(3),
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"failed" BOOLEAN NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT "staff_emails_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_work_patterns" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"effectiveFrom" DATE NOT NULL,
|
||||
"dailyMinutes" INTEGER[],
|
||||
|
||||
CONSTRAINT "staff_work_patterns_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_day_overrides" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"minutes" INTEGER NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_day_overrides_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_holidays" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_holidays_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leave_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"year" INTEGER NOT NULL,
|
||||
"entitlementUnits" INTEGER NOT NULL,
|
||||
"carryUnits" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "staff_leave_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leaves" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"kind" "StaffLeaveKind" NOT NULL,
|
||||
"status" "StaffRequestStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"startDate" DATE NOT NULL,
|
||||
"endDate" DATE NOT NULL,
|
||||
"halfDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"minutes" INTEGER,
|
||||
"note" TEXT,
|
||||
"decisionNote" TEXT,
|
||||
"requestedById" TEXT NOT NULL,
|
||||
"reviewedById" TEXT,
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_leaves_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_leave_days" (
|
||||
"id" TEXT NOT NULL,
|
||||
"leaveId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"vacationUnits" INTEGER NOT NULL DEFAULT 0,
|
||||
"creditMinutes" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "staff_leave_days_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_time_entries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"startMinute" INTEGER NOT NULL,
|
||||
"endMinute" INTEGER NOT NULL,
|
||||
"breakMinutes" INTEGER NOT NULL DEFAULT 0,
|
||||
"note" TEXT,
|
||||
|
||||
CONSTRAINT "staff_time_entries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_weeks" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"weekStart" DATE NOT NULL,
|
||||
"status" "StaffWeekStatus" NOT NULL DEFAULT 'DRAFT',
|
||||
"submittedAt" TIMESTAMP(3),
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"reviewedById" TEXT,
|
||||
"decisionNote" TEXT,
|
||||
"dailySnapshot" JSONB,
|
||||
|
||||
CONSTRAINT "staff_weeks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_adjustments" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"minutes" INTEGER NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_adjustments_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_history" (
|
||||
"id" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"details" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_history_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "staff_notifications" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"profileId" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"readAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "staff_notifications_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "family_event_participations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"status" "EventParticipationStatus" NOT NULL,
|
||||
"adultCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "family_event_participations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarms" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"assignmentId" TEXT,
|
||||
"activeAssignmentId" TEXT,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"familyName" TEXT NOT NULL,
|
||||
"childName" TEXT NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"wholeDay" BOOLEAN NOT NULL DEFAULT true,
|
||||
"startMinute" INTEGER,
|
||||
"endMinute" INTEGER,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"deadline" TIMESTAMP(3) NOT NULL,
|
||||
"status" "NotdienstAlarmStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"triggeredById" TEXT,
|
||||
"triggeredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"respondedById" TEXT,
|
||||
"respondedAt" TIMESTAMP(3),
|
||||
"responseSource" TEXT,
|
||||
"escalatedAt" TIMESTAMP(3),
|
||||
"educatorId" TEXT,
|
||||
"notes" TEXT,
|
||||
"cancelledAt" TIMESTAMP(3),
|
||||
"cancelReason" TEXT,
|
||||
|
||||
CONSTRAINT "notdienst_alarms_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_recipients" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"token" TEXT NOT NULL,
|
||||
"sessionVersion" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_recipients_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_notifications" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventKey" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"readAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "notdienst_alarm_notifications_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_emails" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"eventKey" TEXT NOT NULL,
|
||||
"kind" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"message" TEXT NOT NULL,
|
||||
"path" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"sentAt" TIMESTAMP(3),
|
||||
"skippedAt" TIMESTAMP(3),
|
||||
"leaseUntil" TIMESTAMP(3),
|
||||
"failed" BOOLEAN NOT NULL DEFAULT false,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_emails_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "notdienst_alarm_history" (
|
||||
"id" TEXT NOT NULL,
|
||||
"alarmId" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"action" TEXT NOT NULL,
|
||||
"details" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "notdienst_alarm_history_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_profiles_educatorId_key" ON "staff_profiles"("educatorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_profiles_userId_key" ON "staff_profiles"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_profiles_kitaId_idx" ON "staff_profiles"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_emails_profileId_sentAt_skippedAt_idx" ON "staff_emails"("profileId", "sentAt", "skippedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_work_patterns_profileId_effectiveFrom_key" ON "staff_work_patterns"("profileId", "effectiveFrom");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_day_overrides_profileId_date_key" ON "staff_day_overrides"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_holidays_kitaId_date_key" ON "staff_holidays"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_leave_accounts_profileId_year_key" ON "staff_leave_accounts"("profileId", "year");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_leaves_profileId_status_startDate_idx" ON "staff_leaves"("profileId", "status", "startDate");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_leave_days_leaveId_date_key" ON "staff_leave_days"("leaveId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_time_entries_profileId_date_idx" ON "staff_time_entries"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "staff_weeks_profileId_weekStart_key" ON "staff_weeks"("profileId", "weekStart");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_adjustments_profileId_date_idx" ON "staff_adjustments"("profileId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_history_profileId_createdAt_idx" ON "staff_history"("profileId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "staff_notifications_userId_readAt_createdAt_idx" ON "staff_notifications"("userId", "readAt", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "family_event_participations_kitaId_idx" ON "family_event_participations"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "family_event_participations_familyId_idx" ON "family_event_participations"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "family_event_participations_eventId_familyId_key" ON "family_event_participations"("eventId", "familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarms_activeAssignmentId_key" ON "notdienst_alarms"("activeAssignmentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarms_kitaId_date_idx" ON "notdienst_alarms"("kitaId", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarms_status_deadline_idx" ON "notdienst_alarms"("status", "deadline");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_recipients_token_key" ON "notdienst_alarm_recipients"("token");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_recipients_alarmId_userId_key" ON "notdienst_alarm_recipients"("alarmId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_notifications_userId_readAt_idx" ON "notdienst_alarm_notifications"("userId", "readAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_notifications_alarmId_userId_eventKey_key" ON "notdienst_alarm_notifications"("alarmId", "userId", "eventKey");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_emails_sentAt_skippedAt_createdAt_idx" ON "notdienst_alarm_emails"("sentAt", "skippedAt", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "notdienst_alarm_emails_alarmId_userId_eventKey_key" ON "notdienst_alarm_emails"("alarmId", "userId", "eventKey");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "notdienst_alarm_history_alarmId_createdAt_idx" ON "notdienst_alarm_history"("alarmId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_educatorId_fkey" FOREIGN KEY ("educatorId") REFERENCES "educators"("id") ON DELETE NO ACTION ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_emails" ADD CONSTRAINT "staff_emails_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_work_patterns" ADD CONSTRAINT "staff_work_patterns_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_day_overrides" ADD CONSTRAINT "staff_day_overrides_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_holidays" ADD CONSTRAINT "staff_holidays_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leave_accounts" ADD CONSTRAINT "staff_leave_accounts_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leaves" ADD CONSTRAINT "staff_leaves_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_leave_days" ADD CONSTRAINT "staff_leave_days_leaveId_fkey" FOREIGN KEY ("leaveId") REFERENCES "staff_leaves"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_time_entries" ADD CONSTRAINT "staff_time_entries_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_weeks" ADD CONSTRAINT "staff_weeks_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_adjustments" ADD CONSTRAINT "staff_adjustments_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_history" ADD CONSTRAINT "staff_history_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_notifications" ADD CONSTRAINT "staff_notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "staff_notifications" ADD CONSTRAINT "staff_notifications_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "staff_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "termine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_assignmentId_fkey" FOREIGN KEY ("assignmentId") REFERENCES "notdienst_assignments"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_recipients" ADD CONSTRAINT "notdienst_alarm_recipients_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_recipients" ADD CONSTRAINT "notdienst_alarm_recipients_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_notifications" ADD CONSTRAINT "notdienst_alarm_notifications_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_notifications" ADD CONSTRAINT "notdienst_alarm_notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_emails" ADD CONSTRAINT "notdienst_alarm_emails_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_emails" ADD CONSTRAINT "notdienst_alarm_emails_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alarm_history" ADD CONSTRAINT "notdienst_alarm_history_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "notdienst_alerts" ADD CONSTRAINT "notdienst_alerts_alarmId_fkey" FOREIGN KEY ("alarmId") REFERENCES "notdienst_alarms"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,13 @@
|
||||
BEGIN;
|
||||
-- Additional tenant invariants intentionally supplement Prisma relations.
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_educatorId_tenant_fkey" FOREIGN KEY ("educatorId", "kitaId") REFERENCES "educators"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "staff_profiles" ADD CONSTRAINT "staff_profiles_userId_tenant_fkey" FOREIGN KEY ("userId", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_eventId_tenant_fkey" FOREIGN KEY ("eventId", "kitaId") REFERENCES "termine"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_familyId_tenant_fkey" FOREIGN KEY ("familyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_familyId_tenant_fkey" FOREIGN KEY ("familyId", "kitaId") REFERENCES "families"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_assignmentId_tenant_fkey" FOREIGN KEY ("assignmentId", "kitaId") REFERENCES "notdienst_assignments"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_activeAssignmentId_tenant_fkey" FOREIGN KEY ("activeAssignmentId", "kitaId") REFERENCES "notdienst_assignments"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_triggeredById_tenant_fkey" FOREIGN KEY ("triggeredById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_respondedById_tenant_fkey" FOREIGN KEY ("respondedById", "kitaId") REFERENCES "users"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
ALTER TABLE "notdienst_alarms" ADD CONSTRAINT "notdienst_alarms_educatorId_tenant_fkey" FOREIGN KEY ("educatorId", "kitaId") REFERENCES "educators"("id", "kitaId") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
COMMIT;
|
||||
@@ -0,0 +1 @@
|
||||
provider = "postgresql"
|
||||
@@ -63,6 +63,17 @@ enum TerminStatus {
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum RsvpMode {
|
||||
CHILD
|
||||
FAMILY
|
||||
}
|
||||
|
||||
enum AnnouncementAudience {
|
||||
ELTERN
|
||||
ERZIEHER
|
||||
ALLE
|
||||
}
|
||||
|
||||
enum EventParticipationStatus {
|
||||
ATTENDING
|
||||
NOT_ATTENDING
|
||||
@@ -84,6 +95,22 @@ enum NotdienstAlertStatus {
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum NotdienstAlarmStatus {
|
||||
PENDING
|
||||
CONFIRMED
|
||||
DECLINED
|
||||
LATE_CONFIRMATION
|
||||
REVIEW_REQUIRED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum NotdienstSwapStatus {
|
||||
PENDING
|
||||
ACCEPTED
|
||||
DECLINED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum DutyAssignmentStatus {
|
||||
PLANNED
|
||||
DONE
|
||||
@@ -136,6 +163,11 @@ model Kita {
|
||||
notdienstAvailabilities NotdienstAvailability[]
|
||||
notdienstAssignments NotdienstAssignment[]
|
||||
notdienstAlerts NotdienstAlert[]
|
||||
notdienstAlarms NotdienstAlarm[]
|
||||
notdienstSwapRequests NotdienstSwapRequest[]
|
||||
staffProfiles StaffProfile[]
|
||||
staffHolidays StaffHoliday[]
|
||||
familyEventParticipations FamilyEventParticipation[]
|
||||
|
||||
@@map("kitas")
|
||||
}
|
||||
@@ -151,6 +183,7 @@ model Family {
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
|
||||
name String
|
||||
notdienstAlarms NotdienstAlarm[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -158,9 +191,12 @@ model Family {
|
||||
users User[]
|
||||
children Child[]
|
||||
dutyAssignments DutyAssignment[]
|
||||
notdienstSwapRequestsStarted NotdienstSwapRequest[] @relation("NotdienstSwapRequesterFamily")
|
||||
familyEventParticipations FamilyEventParticipation[]
|
||||
|
||||
@@index([kitaId])
|
||||
@@map("families")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
@@ -202,12 +238,15 @@ model User {
|
||||
privacyPolicyVersion String?
|
||||
/// Zeitstempel des Opt-Ins für das interne Kita-Adressbuch (Modul 3).
|
||||
directoryOptInAt DateTime?
|
||||
staffDecisionEmails Boolean @default(true)
|
||||
|
||||
// Auth-Bookkeeping
|
||||
emailVerifiedAt DateTime?
|
||||
lastLoginAt DateTime?
|
||||
failedLoginAttempts Int @default(0)
|
||||
lockedUntil DateTime?
|
||||
disabledAt DateTime?
|
||||
sessionVersion Int @default(0)
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -219,6 +258,8 @@ model User {
|
||||
notdienstAlertsAssigned NotdienstAlert[] @relation("NotdienstAlertParent")
|
||||
notdienstAlertsTriggered NotdienstAlert[] @relation("NotdienstAlertTrigger")
|
||||
notdienstPlansCreated NotdienstPlan[] @relation("NotdienstPlanCreator")
|
||||
notdienstSwapRequestsStarted NotdienstSwapRequest[] @relation("NotdienstSwapRequester")
|
||||
notdienstSwapRequestsResponded NotdienstSwapRequest[] @relation("NotdienstSwapResponder")
|
||||
announcementsAuthored Announcement[] @relation("AnnouncementAuthor")
|
||||
announcementReads AnnouncementRead[]
|
||||
|
||||
@@ -228,11 +269,18 @@ model User {
|
||||
mitbringselItems MitbringselItem[]
|
||||
invitationsCreated Invitation[] @relation("InvitationCreator")
|
||||
auditLogsAuthored AuditLog[] @relation("AuditLogActor")
|
||||
staffProfile StaffProfile?
|
||||
staffNotifications StaffNotification[]
|
||||
staffEmails StaffEmail[]
|
||||
alarmRecipients NotdienstAlarmRecipient[]
|
||||
alarmNotifications NotdienstAlarmNotification[]
|
||||
alarmEmails NotdienstAlarmEmail[]
|
||||
|
||||
@@index([kitaId])
|
||||
@@index([familyId])
|
||||
@@index([kitaId, role])
|
||||
@@map("users")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
@@ -265,6 +313,7 @@ model Child {
|
||||
@@index([kitaId])
|
||||
@@index([familyId])
|
||||
@@map("children")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
@@ -284,9 +333,236 @@ model Educator {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
notdienstAlerts NotdienstAlert[]
|
||||
staffProfile StaffProfile?
|
||||
|
||||
@@index([kitaId])
|
||||
@@map("educators")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
// Personalbereich: Tage als UTC-Datum, Zeiten als Minuten, Anspruch in halben Tagen.
|
||||
enum StaffRequestStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
CANCEL_REQUESTED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum StaffLeaveKind {
|
||||
VACATION
|
||||
TIME_OFF
|
||||
SICKNESS
|
||||
}
|
||||
|
||||
enum StaffWeekStatus {
|
||||
DRAFT
|
||||
SUBMITTED
|
||||
APPROVED
|
||||
}
|
||||
|
||||
model StaffProfile {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
educatorId String @unique
|
||||
educator Educator @relation(fields: [educatorId], references: [id], onDelete: NoAction)
|
||||
userId String? @unique
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
employmentStart DateTime @db.Date
|
||||
employmentEnd DateTime? @db.Date
|
||||
trackingStart DateTime @db.Date
|
||||
openingMinutes Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
workPatterns StaffWorkPattern[]
|
||||
dayOverrides StaffDayOverride[]
|
||||
leaveAccounts StaffLeaveAccount[]
|
||||
leaves StaffLeave[]
|
||||
timeEntries StaffTimeEntry[]
|
||||
weeks StaffWeek[]
|
||||
adjustments StaffAdjustment[]
|
||||
history StaffHistory[]
|
||||
notifications StaffNotification[]
|
||||
emails StaffEmail[]
|
||||
|
||||
@@index([kitaId])
|
||||
@@map("staff_profiles")
|
||||
}
|
||||
|
||||
// Persisted in the same transaction as the staff action; delivered after commit.
|
||||
model StaffEmail {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
toAdmins Boolean @default(false)
|
||||
subject String
|
||||
message String
|
||||
path String
|
||||
inviteToken String?
|
||||
createdAt DateTime @default(now())
|
||||
sentAt DateTime?
|
||||
skippedAt DateTime?
|
||||
leaseUntil DateTime?
|
||||
attempts Int @default(0)
|
||||
failed Boolean @default(false)
|
||||
|
||||
@@index([profileId, sentAt, skippedAt])
|
||||
@@map("staff_emails")
|
||||
}
|
||||
|
||||
model StaffWorkPattern {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
effectiveFrom DateTime @db.Date
|
||||
// Montag bis Sonntag; 0 bedeutet arbeitsfrei.
|
||||
dailyMinutes Int[]
|
||||
|
||||
@@unique([profileId, effectiveFrom])
|
||||
@@map("staff_work_patterns")
|
||||
}
|
||||
|
||||
model StaffDayOverride {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
date DateTime @db.Date
|
||||
minutes Int
|
||||
reason String
|
||||
|
||||
@@unique([profileId, date])
|
||||
@@map("staff_day_overrides")
|
||||
}
|
||||
|
||||
model StaffHoliday {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
date DateTime @db.Date
|
||||
name String
|
||||
|
||||
@@unique([kitaId, date])
|
||||
@@map("staff_holidays")
|
||||
}
|
||||
|
||||
model StaffLeaveAccount {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
year Int
|
||||
entitlementUnits Int
|
||||
carryUnits Int @default(0)
|
||||
|
||||
@@unique([profileId, year])
|
||||
@@map("staff_leave_accounts")
|
||||
}
|
||||
|
||||
model StaffLeave {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
kind StaffLeaveKind
|
||||
status StaffRequestStatus @default(PENDING)
|
||||
startDate DateTime @db.Date
|
||||
endDate DateTime @db.Date
|
||||
halfDay Boolean @default(false)
|
||||
minutes Int?
|
||||
note String?
|
||||
decisionNote String?
|
||||
requestedById String
|
||||
reviewedById String?
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
days StaffLeaveDay[]
|
||||
|
||||
@@index([profileId, status, startDate])
|
||||
@@map("staff_leaves")
|
||||
}
|
||||
|
||||
model StaffLeaveDay {
|
||||
id String @id @default(cuid())
|
||||
leaveId String
|
||||
leave StaffLeave @relation(fields: [leaveId], references: [id], onDelete: Cascade)
|
||||
date DateTime @db.Date
|
||||
vacationUnits Int @default(0)
|
||||
creditMinutes Int
|
||||
|
||||
@@unique([leaveId, date])
|
||||
@@map("staff_leave_days")
|
||||
}
|
||||
|
||||
model StaffTimeEntry {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
date DateTime @db.Date
|
||||
startMinute Int
|
||||
endMinute Int
|
||||
breakMinutes Int @default(0)
|
||||
note String?
|
||||
|
||||
@@index([profileId, date])
|
||||
@@map("staff_time_entries")
|
||||
}
|
||||
|
||||
model StaffWeek {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
weekStart DateTime @db.Date
|
||||
status StaffWeekStatus @default(DRAFT)
|
||||
submittedAt DateTime?
|
||||
reviewedAt DateTime?
|
||||
reviewedById String?
|
||||
decisionNote String?
|
||||
// Snapshot von Soll-, Ist- und Abwesenheitsminuten bei Genehmigung.
|
||||
dailySnapshot Json?
|
||||
|
||||
@@unique([profileId, weekStart])
|
||||
@@map("staff_weeks")
|
||||
}
|
||||
|
||||
model StaffAdjustment {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
date DateTime @db.Date
|
||||
minutes Int
|
||||
reason String
|
||||
actorId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([profileId, date])
|
||||
@@map("staff_adjustments")
|
||||
}
|
||||
|
||||
model StaffHistory {
|
||||
id String @id @default(cuid())
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
actorId String
|
||||
action String
|
||||
details String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([profileId, createdAt])
|
||||
@@map("staff_history")
|
||||
}
|
||||
|
||||
model StaffNotification {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
profileId String
|
||||
profile StaffProfile @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
message String
|
||||
readAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId, readAt, createdAt])
|
||||
@@map("staff_notifications")
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
@@ -310,6 +586,7 @@ model ParentDuty {
|
||||
@@unique([kitaId, name])
|
||||
@@index([kitaId])
|
||||
@@map("parent_duties")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
model ParentDutyAssignment {
|
||||
@@ -349,6 +626,7 @@ model DutyType {
|
||||
@@unique([kitaId, name])
|
||||
@@index([kitaId])
|
||||
@@map("duty_types")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
model DutyAssignment {
|
||||
@@ -413,6 +691,7 @@ model Announcement {
|
||||
|
||||
title String
|
||||
content String
|
||||
audience AnnouncementAudience @default(ALLE)
|
||||
|
||||
authorId String
|
||||
author User @relation("AnnouncementAuthor", fields: [authorId], references: [id], onDelete: Cascade)
|
||||
@@ -424,6 +703,7 @@ model Announcement {
|
||||
|
||||
@@index([kitaId, createdAt])
|
||||
@@index([authorId])
|
||||
@@unique([id, kitaId])
|
||||
@@map("announcements")
|
||||
}
|
||||
|
||||
@@ -435,12 +715,14 @@ model Attachment {
|
||||
fileName String
|
||||
fileUrl String
|
||||
fileType String
|
||||
sizeBytes Int?
|
||||
|
||||
@@index([announcementId])
|
||||
@@map("attachments")
|
||||
}
|
||||
|
||||
model AnnouncementRead {
|
||||
kitaId String
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
@@ -451,6 +733,7 @@ model AnnouncementRead {
|
||||
|
||||
@@unique([userId, announcementId])
|
||||
@@index([announcementId])
|
||||
@@index([kitaId])
|
||||
@@map("announcement_reads")
|
||||
}
|
||||
|
||||
@@ -505,6 +788,7 @@ model Termin {
|
||||
|
||||
/// Teilnahme-Abfrage für Ausflüge und besondere Events.
|
||||
requiresRsvp Boolean @default(false)
|
||||
rsvpMode RsvpMode @default(CHILD)
|
||||
rsvpDeadline DateTime?
|
||||
participantInfo String?
|
||||
|
||||
@@ -521,10 +805,12 @@ model Termin {
|
||||
|
||||
mitbringselItems MitbringselItem[]
|
||||
participations EventParticipation[]
|
||||
familyParticipations FamilyEventParticipation[]
|
||||
|
||||
@@index([kitaId, startDate])
|
||||
@@index([kitaId, status])
|
||||
@@map("termine")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
model EventParticipation {
|
||||
@@ -549,6 +835,25 @@ model EventParticipation {
|
||||
@@map("event_participations")
|
||||
}
|
||||
|
||||
model FamilyEventParticipation {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
eventId String
|
||||
event Termin @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
familyId String
|
||||
family Family @relation(fields: [familyId], references: [id], onDelete: Cascade)
|
||||
status EventParticipationStatus
|
||||
adultCount Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([eventId, familyId])
|
||||
@@index([kitaId])
|
||||
@@index([familyId])
|
||||
@@map("family_event_participations")
|
||||
}
|
||||
|
||||
model MitbringselItem {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
@@ -601,6 +906,7 @@ model NotdienstPlan {
|
||||
@@unique([kitaId, year, month])
|
||||
@@index([kitaId])
|
||||
@@map("notdienst_plans")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
/// Verfügbarkeits-Eintrag eines Elternteils für ein Kind an einem Tag.
|
||||
@@ -647,16 +953,163 @@ model NotdienstAssignment {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
alerts NotdienstAlert[]
|
||||
alarms NotdienstAlarm[]
|
||||
swapRequestsAsTarget NotdienstSwapRequest[] @relation("NotdienstSwapTargetAssignment")
|
||||
swapRequestsAsOffered NotdienstSwapRequest[] @relation("NotdienstSwapOfferedAssignment")
|
||||
|
||||
@@unique([planId, date])
|
||||
@@index([kitaId, date])
|
||||
@@map("notdienst_assignments")
|
||||
@@unique([id, kitaId])
|
||||
}
|
||||
|
||||
/// Tauschanfrage zwischen Eltern fuer zwei bereits veroeffentlichte
|
||||
/// zukuenftige Notdienst-Zuteilungen.
|
||||
model NotdienstSwapRequest {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
|
||||
requesterUserId String
|
||||
requesterUser User @relation("NotdienstSwapRequester", fields: [requesterUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
requesterFamilyId String
|
||||
requesterFamily Family @relation("NotdienstSwapRequesterFamily", fields: [requesterFamilyId], references: [id], onDelete: Cascade)
|
||||
|
||||
targetAssignmentId String
|
||||
targetAssignment NotdienstAssignment @relation("NotdienstSwapTargetAssignment", fields: [targetAssignmentId], references: [id], onDelete: Cascade)
|
||||
|
||||
offeredAssignmentId String
|
||||
offeredAssignment NotdienstAssignment @relation("NotdienstSwapOfferedAssignment", fields: [offeredAssignmentId], references: [id], onDelete: Cascade)
|
||||
|
||||
status NotdienstSwapStatus @default(PENDING)
|
||||
message String?
|
||||
|
||||
respondedById String?
|
||||
respondedBy User? @relation("NotdienstSwapResponder", fields: [respondedById], references: [id], onDelete: SetNull)
|
||||
respondedAt DateTime?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([kitaId, status])
|
||||
@@index([requesterFamilyId, status])
|
||||
@@index([targetAssignmentId, status])
|
||||
@@index([offeredAssignmentId, status])
|
||||
@@map("notdienst_swap_requests")
|
||||
}
|
||||
|
||||
/// Aktive Alarmierung — wird bei Krankmeldung einer Fachkraft
|
||||
/// vom Koordinator ausgelöst. Bestätigung via Magic-Link (Token).
|
||||
model NotdienstAlarm {
|
||||
id String @id @default(cuid())
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
assignmentId String?
|
||||
assignment NotdienstAssignment? @relation(fields: [assignmentId], references: [id], onDelete: SetNull)
|
||||
// Nullable unique reservation: cancelled or ended alarms release the assignment.
|
||||
activeAssignmentId String? @unique
|
||||
familyId String
|
||||
family Family @relation(fields: [familyId], references: [id], onDelete: Cascade)
|
||||
familyName String
|
||||
childName String
|
||||
date DateTime @db.Date
|
||||
wholeDay Boolean @default(true)
|
||||
startMinute Int?
|
||||
endMinute Int?
|
||||
expiresAt DateTime
|
||||
deadline DateTime
|
||||
status NotdienstAlarmStatus @default(PENDING)
|
||||
triggeredById String?
|
||||
triggeredAt DateTime @default(now())
|
||||
respondedById String?
|
||||
respondedAt DateTime?
|
||||
responseSource String?
|
||||
escalatedAt DateTime?
|
||||
educatorId String?
|
||||
notes String?
|
||||
cancelledAt DateTime?
|
||||
cancelReason String?
|
||||
recipients NotdienstAlarmRecipient[]
|
||||
notifications NotdienstAlarmNotification[]
|
||||
emails NotdienstAlarmEmail[]
|
||||
history NotdienstAlarmHistory[]
|
||||
legacyAlerts NotdienstAlert[]
|
||||
|
||||
@@index([kitaId, date])
|
||||
@@index([status, deadline])
|
||||
@@map("notdienst_alarms")
|
||||
}
|
||||
|
||||
model NotdienstAlarmRecipient {
|
||||
id String @id @default(cuid())
|
||||
alarmId String
|
||||
alarm NotdienstAlarm @relation(fields: [alarmId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
token String @unique
|
||||
sessionVersion Int @default(0)
|
||||
|
||||
@@unique([alarmId, userId])
|
||||
@@map("notdienst_alarm_recipients")
|
||||
}
|
||||
|
||||
model NotdienstAlarmNotification {
|
||||
id String @id @default(cuid())
|
||||
alarmId String
|
||||
alarm NotdienstAlarm @relation(fields: [alarmId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
eventKey String
|
||||
message String
|
||||
createdAt DateTime @default(now())
|
||||
readAt DateTime?
|
||||
|
||||
@@unique([alarmId, userId, eventKey])
|
||||
@@index([userId, readAt])
|
||||
@@map("notdienst_alarm_notifications")
|
||||
}
|
||||
|
||||
model NotdienstAlarmEmail {
|
||||
id String @id @default(cuid())
|
||||
alarmId String
|
||||
alarm NotdienstAlarm @relation(fields: [alarmId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
eventKey String
|
||||
kind String
|
||||
subject String
|
||||
message String
|
||||
path String
|
||||
createdAt DateTime @default(now())
|
||||
sentAt DateTime?
|
||||
skippedAt DateTime?
|
||||
leaseUntil DateTime?
|
||||
failed Boolean @default(false)
|
||||
attempts Int @default(0)
|
||||
|
||||
@@unique([alarmId, userId, eventKey])
|
||||
@@index([sentAt, skippedAt, createdAt])
|
||||
@@map("notdienst_alarm_emails")
|
||||
}
|
||||
|
||||
model NotdienstAlarmHistory {
|
||||
id String @id @default(cuid())
|
||||
alarmId String
|
||||
alarm NotdienstAlarm @relation(fields: [alarmId], references: [id], onDelete: Cascade)
|
||||
actorId String?
|
||||
action String
|
||||
details String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([alarmId, createdAt])
|
||||
@@map("notdienst_alarm_history")
|
||||
}
|
||||
|
||||
model NotdienstAlert {
|
||||
id String @id @default(cuid())
|
||||
alarmId String?
|
||||
alarm NotdienstAlarm? @relation(fields: [alarmId], references: [id], onDelete: SetNull)
|
||||
kitaId String
|
||||
kita Kita @relation(fields: [kitaId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@ -737,3 +1190,21 @@ model VerificationToken {
|
||||
@@unique([identifier, token])
|
||||
@@map("verification_tokens")
|
||||
}
|
||||
|
||||
model RateLimitBucket {
|
||||
key String @id
|
||||
count Int
|
||||
resetAt DateTime
|
||||
@@index([resetAt])
|
||||
@@map("rate_limit_buckets")
|
||||
}
|
||||
|
||||
model PendingRegistration {
|
||||
email String @id
|
||||
firstName String
|
||||
lastName String
|
||||
tokenHash String @unique
|
||||
expiresAt DateTime
|
||||
@@index([expiresAt])
|
||||
@@map("pending_registrations")
|
||||
}
|
||||
|
||||
+60
-15
@@ -19,7 +19,7 @@ import { hash } from "bcryptjs";
|
||||
// noch keine Kita und keine User enthaelt.
|
||||
//
|
||||
// Reset: `npm run db:seed:reset` loescht gezielt die Demo-Daten und baut
|
||||
// sie neu auf. Production wird nur mit ALLOW_DATABASE_SEED=true erlaubt.
|
||||
// sie neu auf. Production-Seeding ist grundsätzlich deaktiviert.
|
||||
// =====================================================================
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
@@ -101,16 +101,8 @@ function getWorkingDays(year: number, month: number, limit?: number) {
|
||||
}
|
||||
|
||||
function isSeedAllowed() {
|
||||
if (
|
||||
process.env.NODE_ENV === "development" ||
|
||||
process.env.ALLOW_DATABASE_SEED === "true"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
console.log(
|
||||
"Seed uebersprungen: NODE_ENV ist nicht development. Setze ALLOW_DATABASE_SEED=true, wenn das bewusst gewuenscht ist.",
|
||||
);
|
||||
if (process.env.NODE_ENV !== "production" && process.env.ALLOW_DATABASE_SEED === "true") return true;
|
||||
console.log("Seed deaktiviert. Nur außerhalb der Produktion mit ALLOW_DATABASE_SEED=true erlaubt.");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -659,6 +651,24 @@ async function createAnnouncements(context: SeedContext) {
|
||||
},
|
||||
});
|
||||
|
||||
const longTitle = await prisma.announcement.create({
|
||||
data: {
|
||||
kitaId: kita.id,
|
||||
title: "Dies ist eine extrem lange Ankuendigung mit einem superlangen Titel um das Layout des Dashboards und des Schwarzen Bretts auf korrekten Textumbruch und Mobilfreundlichkeit zu testen",
|
||||
content: "Inhalt der superlangen Ankuendigung fuer Layout-Testing.",
|
||||
authorId: admin.id,
|
||||
},
|
||||
});
|
||||
|
||||
const xssTitle = await prisma.announcement.create({
|
||||
data: {
|
||||
kitaId: kita.id,
|
||||
title: "Boesartiger Titel mit <script>alert('XSS_NEWS_TITLE')</script> HTML Tags",
|
||||
content: "Dieser Beitrag testet, ob die Anwendung XSS-Angriffe im Titel oder im Inhalt filtert. <script>alert('XSS_NEWS_CONTENT')</script>",
|
||||
authorId: admin.id,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.attachment.create({
|
||||
data: {
|
||||
announcementId: sommerfest.id,
|
||||
@@ -670,10 +680,10 @@ async function createAnnouncements(context: SeedContext) {
|
||||
|
||||
await prisma.announcementRead.createMany({
|
||||
data: [
|
||||
{ userId: koordinator.id, announcementId: sommerfest.id },
|
||||
{ userId: elternSchmidt.id, announcementId: sommerfest.id },
|
||||
{ userId: elternYilmaz.id, announcementId: sommerfest.id },
|
||||
{ userId: elternFischer.id, announcementId: garderobe.id },
|
||||
{ kitaId: kita.id, userId: koordinator.id, announcementId: sommerfest.id },
|
||||
{ kitaId: kita.id, userId: elternSchmidt.id, announcementId: sommerfest.id },
|
||||
{ kitaId: kita.id, userId: elternYilmaz.id, announcementId: sommerfest.id },
|
||||
{ kitaId: kita.id, userId: elternFischer.id, announcementId: garderobe.id },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -808,6 +818,41 @@ async function createTermine(
|
||||
},
|
||||
});
|
||||
|
||||
const highDensityDay = addDays(now, 7);
|
||||
for (let i = 1; i <= 8; i++) {
|
||||
await prisma.termin.create({
|
||||
data: {
|
||||
kitaId: kita.id,
|
||||
title: `Parallel-Termin #${i}`,
|
||||
description: `Beschreibung fuer Parallel-Termin #${i}`,
|
||||
type: TerminType.SONSTIGES,
|
||||
status: TerminStatus.CONFIRMED,
|
||||
startDate: highDensityDay,
|
||||
endDate: highDensityDay,
|
||||
allDay: false,
|
||||
createdById: admin.id,
|
||||
approvedById: admin.id,
|
||||
approvedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.termin.create({
|
||||
data: {
|
||||
kitaId: kita.id,
|
||||
title: "Boesartiger Termin <script>alert('XSS_CAL_TITLE')</script>",
|
||||
description: "XSS Test im Terminkalender <script>alert('XSS_CAL_DESC')</script>",
|
||||
type: TerminType.SONSTIGES,
|
||||
status: TerminStatus.CONFIRMED,
|
||||
startDate: addDays(now, 5),
|
||||
endDate: addDays(now, 5),
|
||||
allDay: true,
|
||||
createdById: admin.id,
|
||||
approvedById: admin.id,
|
||||
approvedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.mitbringselItem.createMany({
|
||||
data: [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RsvpMode" AS ENUM ('CHILD', 'FAMILY');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AnnouncementAudience" AS ENUM ('ELTERN', 'ERZIEHER', 'ALLE');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "announcements" ADD COLUMN "audience" "AnnouncementAudience" NOT NULL DEFAULT 'ALLE';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "termine" ADD COLUMN "rsvpMode" "RsvpMode" NOT NULL DEFAULT 'CHILD';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "family_event_participations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kitaId" TEXT NOT NULL,
|
||||
"eventId" TEXT NOT NULL,
|
||||
"familyId" TEXT NOT NULL,
|
||||
"status" "EventParticipationStatus" NOT NULL,
|
||||
"adultCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "family_event_participations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "family_event_participations_kitaId_idx" ON "family_event_participations"("kitaId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "family_event_participations_familyId_idx" ON "family_event_participations"("familyId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "family_event_participations_eventId_familyId_key" ON "family_event_participations"("eventId", "familyId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_kitaId_fkey" FOREIGN KEY ("kitaId") REFERENCES "kitas"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "termine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "family_event_participations" ADD CONSTRAINT "family_event_participations_familyId_fkey" FOREIGN KEY ("familyId") REFERENCES "families"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { stat } from "node:fs/promises";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { attachmentPath } from "../src/lib/attachments";
|
||||
const prisma = new PrismaClient();
|
||||
async function main() {
|
||||
let count = 0, missing = 0;
|
||||
while (true) {
|
||||
const batch = await prisma.attachment.findMany({ where: { sizeBytes: null }, select: { id: true }, take: 100 });
|
||||
if (!batch.length) break;
|
||||
for (const item of batch) {
|
||||
let sizeBytes = 0;
|
||||
try { sizeBytes = (await stat(attachmentPath(item.id))).size; }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
missing++;
|
||||
}
|
||||
await prisma.attachment.update({ where: { id: item.id }, data: { sizeBytes } });
|
||||
count++;
|
||||
}
|
||||
}
|
||||
console.log(`Attachment sizes recorded: ${count}; missing files: ${missing}.`);
|
||||
}
|
||||
main().finally(() => prisma.$disconnect()).catch(() => { console.error("Attachment size backfill failed."); process.exitCode = 1; });
|
||||
@@ -0,0 +1,62 @@
|
||||
-- Read-only preflight for both legacy and upgraded schemas. Empty result means no violations.
|
||||
SELECT * FROM (
|
||||
SELECT 'users.familyId' AS relation, count(*) AS invalid_rows FROM "users" c JOIN "families" p ON c."familyId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'children.familyId' AS relation, count(*) AS invalid_rows FROM "children" c JOIN "families" p ON c."familyId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'parent_duty_assignments.dutyId' AS relation, count(*) AS invalid_rows FROM "parent_duty_assignments" c JOIN "parent_duties" p ON c."dutyId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'parent_duty_assignments.userId' AS relation, count(*) AS invalid_rows FROM "parent_duty_assignments" c JOIN "users" p ON c."userId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'duty_assignments.familyId' AS relation, count(*) AS invalid_rows FROM "duty_assignments" c JOIN "families" p ON c."familyId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'duty_assignments.dutyTypeId' AS relation, count(*) AS invalid_rows FROM "duty_assignments" c JOIN "duty_types" p ON c."dutyTypeId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'absences.childId' AS relation, count(*) AS invalid_rows FROM "absences" c JOIN "children" p ON c."childId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'announcements.authorId' AS relation, count(*) AS invalid_rows FROM "announcements" c JOIN "users" p ON c."authorId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'invitations.invitedById' AS relation, count(*) AS invalid_rows FROM "invitations" c JOIN "users" p ON c."invitedById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'termine.createdById' AS relation, count(*) AS invalid_rows FROM "termine" c JOIN "users" p ON c."createdById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'termine.approvedById' AS relation, count(*) AS invalid_rows FROM "termine" c JOIN "users" p ON c."approvedById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'event_participations.eventId' AS relation, count(*) AS invalid_rows FROM "event_participations" c JOIN "termine" p ON c."eventId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'event_participations.childId' AS relation, count(*) AS invalid_rows FROM "event_participations" c JOIN "children" p ON c."childId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'mitbringsel_items.terminId' AS relation, count(*) AS invalid_rows FROM "mitbringsel_items" c JOIN "termine" p ON c."terminId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'mitbringsel_items.userId' AS relation, count(*) AS invalid_rows FROM "mitbringsel_items" c JOIN "users" p ON c."userId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_plans.createdById' AS relation, count(*) AS invalid_rows FROM "notdienst_plans" c JOIN "users" p ON c."createdById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_availabilities.childId' AS relation, count(*) AS invalid_rows FROM "notdienst_availabilities" c JOIN "children" p ON c."childId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_availabilities.userId' AS relation, count(*) AS invalid_rows FROM "notdienst_availabilities" c JOIN "users" p ON c."userId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_assignments.planId' AS relation, count(*) AS invalid_rows FROM "notdienst_assignments" c JOIN "notdienst_plans" p ON c."planId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_assignments.childId' AS relation, count(*) AS invalid_rows FROM "notdienst_assignments" c JOIN "children" p ON c."childId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_swap_requests.requesterUserId' AS relation, count(*) AS invalid_rows FROM "notdienst_swap_requests" c JOIN "users" p ON c."requesterUserId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_swap_requests.requesterFamilyId' AS relation, count(*) AS invalid_rows FROM "notdienst_swap_requests" c JOIN "families" p ON c."requesterFamilyId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_swap_requests.targetAssignmentId' AS relation, count(*) AS invalid_rows FROM "notdienst_swap_requests" c JOIN "notdienst_assignments" p ON c."targetAssignmentId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_swap_requests.offeredAssignmentId' AS relation, count(*) AS invalid_rows FROM "notdienst_swap_requests" c JOIN "notdienst_assignments" p ON c."offeredAssignmentId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_swap_requests.respondedById' AS relation, count(*) AS invalid_rows FROM "notdienst_swap_requests" c JOIN "users" p ON c."respondedById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_alerts.assignmentId' AS relation, count(*) AS invalid_rows FROM "notdienst_alerts" c JOIN "notdienst_assignments" p ON c."assignmentId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_alerts.parentUserId' AS relation, count(*) AS invalid_rows FROM "notdienst_alerts" c JOIN "users" p ON c."parentUserId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_alerts.triggeredById' AS relation, count(*) AS invalid_rows FROM "notdienst_alerts" c JOIN "users" p ON c."triggeredById" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'notdienst_alerts.educatorId' AS relation, count(*) AS invalid_rows FROM "notdienst_alerts" c JOIN "educators" p ON c."educatorId" = p.id WHERE c."kitaId" IS DISTINCT FROM p."kitaId"
|
||||
UNION ALL
|
||||
SELECT 'announcement_reads.userId' AS relation, count(*) AS invalid_rows FROM announcement_reads r JOIN announcements a ON r."announcementId" = a.id JOIN users u ON r."userId" = u.id WHERE u."kitaId" IS DISTINCT FROM a."kitaId"
|
||||
) violations WHERE invalid_rows > 0;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readdir, stat, rm } from "node:fs/promises";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { attachmentDirectory, attachmentPath } from "../src/lib/attachments";
|
||||
|
||||
// Dry run by default. A 24-hour grace period protects concurrent uploads.
|
||||
const prisma = new PrismaClient();
|
||||
async function main() {
|
||||
const remove = process.argv.includes("--delete");
|
||||
let candidates = 0;
|
||||
for (const entry of await readdir(attachmentDirectory(), { withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
let file: string;
|
||||
try { file = attachmentPath(entry.name); } catch { continue; }
|
||||
if ((await stat(file)).mtimeMs > Date.now() - 24 * 60 * 60_000) continue;
|
||||
if (await prisma.attachment.findUnique({ where: { id: entry.name }, select: { id: true } })) continue;
|
||||
candidates++;
|
||||
if (remove) await rm(file, { force: true });
|
||||
}
|
||||
console.log(`${candidates} orphan attachments ${remove ? "removed" : "found (dry run)"}`);
|
||||
}
|
||||
main().finally(() => prisma.$disconnect()).catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,27 @@
|
||||
import { mkdirSync, existsSync, readFileSync, writeFileSync, chmodSync, chownSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
const passwordFile = process.env.APP_DATABASE_PASSWORD_FILE;
|
||||
if (!passwordFile) throw new Error('Runtime password file is required.');
|
||||
const directory = passwordFile.slice(0, passwordFile.lastIndexOf('/'));
|
||||
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
const password = existsSync(passwordFile) ? readFileSync(passwordFile, 'utf8').trim() : randomBytes(32).toString('hex');
|
||||
if (!/^[a-f0-9]{64}$/.test(password)) throw new Error('Invalid runtime password file.');
|
||||
if (!existsSync(passwordFile)) writeFileSync(passwordFile, password + '\n', { flag: 'wx', mode: 0o400 });
|
||||
chmodSync(passwordFile, 0o400);
|
||||
chownSync(passwordFile, 1001, 1001);
|
||||
chownSync(directory, 1001, 1001);
|
||||
const ownerUrl = new URL('postgresql://postgres:5432/' + encodeURIComponent(process.env.POSTGRES_DB || 'kita_planer'));
|
||||
ownerUrl.username = process.env.POSTGRES_USER || 'kita_planer';
|
||||
ownerUrl.password = process.env.POSTGRES_PASSWORD || '';
|
||||
if (!ownerUrl.password) throw new Error('Database owner password is required.');
|
||||
const environment = { ...process.env, DATABASE_URL: ownerUrl.toString(), APP_DATABASE_PASSWORD: password };
|
||||
for (const args of [['node_modules/prisma/build/index.js', 'migrate', 'deploy'], ['scripts/provision-runtime-role.mjs']]) {
|
||||
const result = spawnSync(process.execPath, args, { env: environment, stdio: 'inherit' });
|
||||
if (result.status !== 0) process.exit(result.status || 1);
|
||||
}
|
||||
for (const path of ['/app/uploads', '/app/uploads/announcements', '/app/uploads/announcements/announcements', '/app/runtime-cache']) {
|
||||
mkdirSync(path, { recursive: true, mode: 0o700 });
|
||||
chownSync(path, 1001, 1001);
|
||||
}
|
||||
console.log('Database initialized; restricted application access and volumes are ready.');
|
||||
@@ -0,0 +1,42 @@
|
||||
// Runs inside the application container. No external cron service or browser is required.
|
||||
const secret = process.env.NOTDIENST_JOB_SECRET;
|
||||
if (!secret || secret.length < 32) {
|
||||
console.error(
|
||||
"Notdienst-Fristprüfung deaktiviert: NOTDIENST_JOB_SECRET muss mindestens 32 Zeichen haben.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const port = Number(process.env.PORT || 3000);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) process.exit(1);
|
||||
let stopped = false;
|
||||
let timer;
|
||||
async function tick() {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const response = await fetch(
|
||||
`http://127.0.0.1:${port}/api/jobs/notdienstalarme`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${secret}` },
|
||||
signal: AbortSignal.timeout(50000),
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
console.error(
|
||||
`Notdienst-Fristprüfung: HTTP ${response.status}; erneuter Versuch in einer Minute.`,
|
||||
);
|
||||
} catch {
|
||||
console.error(
|
||||
"Notdienst-Fristprüfung momentan nicht erreichbar; erneuter Versuch in einer Minute.",
|
||||
);
|
||||
}
|
||||
if (!stopped)
|
||||
timer = setTimeout(tick, Math.max(1000, 60000 - (Date.now() - started)));
|
||||
}
|
||||
for (const signal of ["SIGINT", "SIGTERM"])
|
||||
process.on(signal, () => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
process.exit(0);
|
||||
});
|
||||
timer = setTimeout(tick, 5000);
|
||||
@@ -0,0 +1,8 @@
|
||||
import { cpSync, mkdirSync } from 'node:fs';
|
||||
cpSync('.next/static', '.next/standalone/.next/static', { recursive: true });
|
||||
cpSync('public', '.next/standalone/public', { recursive: true });
|
||||
mkdirSync('.next/standalone/scripts', { recursive: true });
|
||||
cpSync('scripts/start-production.sh', '.next/standalone/scripts/start-production.sh');
|
||||
cpSync('scripts/notdienst-alarm-worker.mjs', '.next/standalone/scripts/notdienst-alarm-worker.mjs');
|
||||
cpSync('scripts/runtime-database-url.mjs', '.next/standalone/scripts/runtime-database-url.mjs');
|
||||
cpSync('scripts/verify-runtime-isolation.mjs', '.next/standalone/scripts/verify-runtime-isolation.mjs');
|
||||
@@ -0,0 +1,34 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const password = process.env.APP_DATABASE_PASSWORD;
|
||||
if (!password || password.length < 24 || password.length > 256) {
|
||||
throw new Error('Set APP_DATABASE_PASSWORD to a dedicated password of 24–256 characters.');
|
||||
}
|
||||
const prisma = new PrismaClient();
|
||||
async function main() {
|
||||
const existing = await prisma.$queryRaw`SELECT 1 FROM pg_roles WHERE rolname = 'kita_runtime'`;
|
||||
if (!existing.length) await prisma.$executeRawUnsafe('CREATE ROLE kita_runtime LOGIN');
|
||||
const owned = await prisma.$queryRaw`SELECT 1 FROM pg_class c JOIN pg_roles r ON c.relowner = r.oid WHERE r.rolname = 'kita_runtime'
|
||||
UNION ALL SELECT 1 FROM pg_namespace n JOIN pg_roles r ON n.nspowner = r.oid WHERE r.rolname = 'kita_runtime'`;
|
||||
if (owned.length) throw new Error('Runtime role must not own tables or schemas.');
|
||||
const memberships = await prisma.$queryRaw`SELECT quote_ident(r.rolname) AS role FROM pg_auth_members m JOIN pg_roles r ON m.roleid = r.oid
|
||||
JOIN pg_roles member ON m.member = member.oid WHERE member.rolname = 'kita_runtime'`;
|
||||
for (const membership of memberships) await prisma.$executeRawUnsafe(`REVOKE ${membership.role} FROM kita_runtime`);
|
||||
// PostgreSQL quotes the secret. Only this server-produced SQL is executed.
|
||||
const [quoted] = await prisma.$queryRaw`SELECT format('ALTER ROLE kita_runtime PASSWORD %L LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS NOREPLICATION', ${password}) AS statement`;
|
||||
await prisma.$executeRawUnsafe(quoted.statement);
|
||||
for (const statement of [
|
||||
'REVOKE CREATE ON SCHEMA public FROM PUBLIC',
|
||||
'GRANT USAGE ON SCHEMA public TO kita_runtime',
|
||||
'GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO kita_runtime',
|
||||
'GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO kita_runtime',
|
||||
'REVOKE ALL ON TABLE _prisma_migrations FROM kita_runtime',
|
||||
'REVOKE UPDATE, DELETE, TRUNCATE ON TABLE audit_logs FROM kita_runtime',
|
||||
]) await prisma.$executeRawUnsafe(statement);
|
||||
console.log('Runtime database grants configured. Re-run after future migrations.');
|
||||
}
|
||||
main().finally(() => prisma.$disconnect()).catch(error => {
|
||||
// Avoid putting a statement containing credentials into deployment logs.
|
||||
console.error('Runtime role provisioning failed:', error?.code ?? error?.name ?? 'unknown');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
const file = process.env.APP_DATABASE_PASSWORD_FILE;
|
||||
if (!file) throw new Error('Runtime password file is required.');
|
||||
const password = readFileSync(file, 'utf8').trim();
|
||||
if (!/^[a-f0-9]{64}$/.test(password)) throw new Error('Invalid runtime password file.');
|
||||
const url = new URL('postgresql://kita_runtime@postgres:5432/' + encodeURIComponent(process.env.APP_DATABASE_NAME || 'kita_planer'));
|
||||
url.password = password;
|
||||
process.stdout.write(url.toString());
|
||||
@@ -1,8 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
echo "Applying Prisma schema..."
|
||||
npx prisma db push --skip-generate
|
||||
|
||||
echo "Starting Kita-Planer..."
|
||||
exec npm run start:prod
|
||||
cd "$(dirname "$0")/.."
|
||||
if [ -n "${APP_DATABASE_PASSWORD_FILE:-}" ]; then
|
||||
DATABASE_URL="$(node scripts/runtime-database-url.mjs)"
|
||||
export DATABASE_URL
|
||||
fi
|
||||
unset POSTGRES_PASSWORD PGADMIN_DEFAULT_PASSWORD APP_DATABASE_PASSWORD MIGRATION_DATABASE_URL
|
||||
# Schema changes are applied by the maintenance image before runtime startup.
|
||||
if [ -n "${NOTDIENST_JOB_SECRET:-}" ]; then
|
||||
node scripts/notdienst-alarm-worker.mjs &
|
||||
fi
|
||||
exec node server.js
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
let prisma;
|
||||
try {
|
||||
const main = Object.fromEntries(readFileSync('/proc/1/environ', 'utf8').split('\0').filter(Boolean).map(line => {
|
||||
const index = line.indexOf('='); return [line.slice(0, index), line.slice(index + 1)];
|
||||
}));
|
||||
for (const key of ['POSTGRES_PASSWORD', 'PGADMIN_DEFAULT_PASSWORD', 'APP_DATABASE_PASSWORD', 'MIGRATION_DATABASE_URL']) {
|
||||
if ((process.env[key] && process.env[key] !== 'unavailable-in-app') || main[key]) throw new Error('Administrative credential reached the app.');
|
||||
}
|
||||
// Configured global/legacy URLs must not expose an administrative login either.
|
||||
if (process.env.DATABASE_URL && process.env.DATABASE_URL !== 'unavailable-in-app') throw new Error('Hosting injected a legacy database URL.');
|
||||
if (new URL(main.DATABASE_URL).username !== 'kita_runtime') throw new Error('Wrong application database role.');
|
||||
prisma = new PrismaClient({ datasourceUrl: main.DATABASE_URL });
|
||||
const [row] = await prisma.$queryRawUnsafe('SELECT current_user');
|
||||
if (row.current_user !== 'kita_runtime') throw new Error('Wrong effective database role.');
|
||||
console.log('Runtime isolation verified: no administrative credentials in container/app environment; current_user=kita_runtime.');
|
||||
} catch {
|
||||
console.error('Runtime isolation verification failed. Credential values were not logged.');
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await prisma?.$disconnect();
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { AbsenceReason, UserRole } from "@prisma/client";
|
||||
import { dateOnlySchema } from "@/lib/date-schema";
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireKitaSession, requireRole } from "@/lib/auth-utils";
|
||||
@@ -9,14 +10,14 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
const reportAbsenceSchema = z.object({
|
||||
childId: z.string().min(1),
|
||||
startDate: z.string().min(1),
|
||||
endDate: z.string().min(1),
|
||||
startDate: dateOnlySchema,
|
||||
endDate: dateOnlySchema,
|
||||
reason: z.nativeEnum(AbsenceReason),
|
||||
note: z.string().trim().max(500).optional(),
|
||||
});
|
||||
|
||||
const dailyAbsenceSchema = z.object({
|
||||
date: z.string().min(1),
|
||||
date: dateOnlySchema,
|
||||
});
|
||||
|
||||
export type DailyAbsenceDto = {
|
||||
|
||||
@@ -2,25 +2,22 @@
|
||||
|
||||
import { randomUUID } from "crypto";
|
||||
import { mkdir, rm, writeFile } from "fs/promises";
|
||||
import path from "path";
|
||||
import { attachmentDirectory, attachmentPath, MAX_ATTACHMENT_SIZE, detectAttachmentType, attachmentExtensionMatches } from "@/lib/attachments";
|
||||
import { serializableTransaction } from "@/lib/transaction";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { createElement } from "react";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { Prisma, UserRole } from "@prisma/client";
|
||||
import { AnnouncementAudience, UserRole, type Prisma } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import { NewsEmail } from "@/emails/NewsEmail";
|
||||
import { requireKitaSession, requireRole } from "@/lib/auth-utils";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;
|
||||
const ALLOWED_TYPES = new Map([
|
||||
["application/pdf", ".pdf"],
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
]);
|
||||
|
||||
const ALLOWED_EXTENSIONS = new Set([".pdf", ".jpg", ".jpeg", ".png"]);
|
||||
import {
|
||||
announcementRecipientWhere,
|
||||
visibleAnnouncementAudiences,
|
||||
} from "@/lib/announcement-access";
|
||||
|
||||
const audienceSchema = z.enum(["ELTERN", "ERZIEHER", "ALLE"]);
|
||||
|
||||
@@ -31,52 +28,15 @@ const announcementSchema = z.object({
|
||||
audience: audienceSchema,
|
||||
});
|
||||
|
||||
function getUploadDir() {
|
||||
return path.resolve(process.env.UPLOAD_DIR ?? "uploads", "announcements");
|
||||
}
|
||||
|
||||
function getSafeFileName(name: string) {
|
||||
return name.replace(/[^\w.\- äöüÄÖÜß]/g, "_").slice(0, 160);
|
||||
}
|
||||
|
||||
function validateAttachment(file: File) {
|
||||
const extension = path.extname(file.name).toLowerCase();
|
||||
const typeAllowed = ALLOWED_TYPES.has(file.type);
|
||||
const extensionAllowed = ALLOWED_EXTENSIONS.has(extension);
|
||||
|
||||
if (!typeAllowed && !extensionAllowed) {
|
||||
return "Nur PDF, JPG und PNG sind erlaubt.";
|
||||
}
|
||||
|
||||
if (file.size > MAX_ATTACHMENT_SIZE) {
|
||||
return "Anhänge dürfen maximal 10 MB groß sein.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getRecipients(kitaId: string, audience: z.infer<typeof audienceSchema>) {
|
||||
const where: Prisma.UserWhereInput =
|
||||
audience === "ELTERN"
|
||||
? {
|
||||
kitaId,
|
||||
familyId: { not: null },
|
||||
emailVerifiedAt: { not: null },
|
||||
}
|
||||
: audience === "ERZIEHER"
|
||||
? {
|
||||
kitaId,
|
||||
role: UserRole.ERZIEHER,
|
||||
emailVerifiedAt: { not: null },
|
||||
}
|
||||
: {
|
||||
kitaId,
|
||||
emailVerifiedAt: { not: null },
|
||||
OR: [{ familyId: { not: null } }, { role: UserRole.ERZIEHER }],
|
||||
};
|
||||
const where: Prisma.UserWhereInput = { kitaId, emailVerifiedAt: { not: null }, ...announcementRecipientWhere(audience as AnnouncementAudience) };
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where,
|
||||
where: { ...where, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true },
|
||||
});
|
||||
|
||||
@@ -106,35 +66,53 @@ export async function createAnnouncement(formData: FormData) {
|
||||
.getAll("attachments")
|
||||
.filter((value): value is File => value instanceof File && value.size > 0);
|
||||
|
||||
if (attachmentFiles.length > 5 || attachmentFiles.some(file => file.size > MAX_ATTACHMENT_SIZE) ||
|
||||
attachmentFiles.reduce((total, file) => total + file.size, 0) > 25 * 1024 * 1024) {
|
||||
return { error: "Maximal 5 Anhänge, je 10 MB und insgesamt 25 MB sind erlaubt." };
|
||||
}
|
||||
if (!(await rateLimit(`announcements:${kitaId}:${session.user.id}`, 20, 3600)).allowed) {
|
||||
return { error: "Zu viele Ankündigungen. Bitte versuche es später erneut." };
|
||||
}
|
||||
const attachmentInputs: { id: string; bytes: Buffer; fileName: string; fileType: string; fileUrl: string }[] = [];
|
||||
for (const file of attachmentFiles) {
|
||||
const error = validateAttachment(file);
|
||||
if (error) {
|
||||
return { error };
|
||||
const bytes = Buffer.from(await file.arrayBuffer());
|
||||
const fileType = detectAttachmentType(bytes);
|
||||
if (!fileType || !attachmentExtensionMatches(file.name, fileType) || (file.type && file.type !== fileType)) {
|
||||
return { error: "Nur PDF-, JPG- und PNG-Dateien mit passenden Dateiinhalten sind erlaubt." };
|
||||
}
|
||||
}
|
||||
|
||||
const attachmentInputs = attachmentFiles.map((file) => {
|
||||
const id = randomUUID();
|
||||
return {
|
||||
id,
|
||||
file,
|
||||
fileName: getSafeFileName(file.name),
|
||||
fileType: file.type || "application/octet-stream",
|
||||
fileUrl: `/api/announcements/attachments/${id}`,
|
||||
};
|
||||
});
|
||||
attachmentInputs.push({ id, bytes, fileName: getSafeFileName(file.name), fileType,
|
||||
fileUrl: `/api/announcements/attachments/${id}` });
|
||||
}
|
||||
|
||||
const announcement = await prisma.announcement.create({
|
||||
const announcement = await serializableTransaction(async tx => {
|
||||
if (attachmentInputs.length) {
|
||||
const pending = await tx.attachment.count({ where: { sizeBytes: null } });
|
||||
if (pending) return null;
|
||||
const [tenantUsage, globalUsage] = await Promise.all([
|
||||
tx.attachment.aggregate({ where: { announcement: { kitaId } }, _sum: { sizeBytes: true } }),
|
||||
tx.attachment.aggregate({ _sum: { sizeBytes: true } }),
|
||||
]);
|
||||
const bytes = attachmentInputs.reduce((total, item) => total + item.bytes.length, 0);
|
||||
const quota = (value: string | undefined, fallback: number) => {
|
||||
const parsed = Number(value); return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
|
||||
};
|
||||
if ((tenantUsage._sum.sizeBytes ?? 0) + bytes > quota(process.env.UPLOAD_TENANT_QUOTA_BYTES, 256 * 1024 ** 2) ||
|
||||
(globalUsage._sum.sizeBytes ?? 0) + bytes > quota(process.env.UPLOAD_GLOBAL_QUOTA_BYTES, 10 * 1024 ** 3)) return null;
|
||||
}
|
||||
return tx.announcement.create({
|
||||
data: {
|
||||
kitaId,
|
||||
title: parsed.data.title,
|
||||
content: parsed.data.content,
|
||||
audience: parsed.data.audience,
|
||||
authorId: session.user.id,
|
||||
attachments: {
|
||||
create: attachmentInputs.map((attachment) => ({
|
||||
id: attachment.id,
|
||||
fileName: attachment.fileName,
|
||||
fileType: attachment.fileType,
|
||||
sizeBytes: attachment.bytes.length,
|
||||
fileUrl: attachment.fileUrl,
|
||||
})),
|
||||
},
|
||||
@@ -145,17 +123,19 @@ export async function createAnnouncement(formData: FormData) {
|
||||
content: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
if (!announcement) return { error: "Anhänge können momentan nicht gespeichert werden. Bitte wende dich an die Administration." };
|
||||
|
||||
if (attachmentInputs.length > 0) {
|
||||
const uploadDir = getUploadDir();
|
||||
const uploadDir = attachmentDirectory();
|
||||
try {
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
await Promise.all(
|
||||
attachmentInputs.map(async (attachment) => {
|
||||
const arrayBuffer = await attachment.file.arrayBuffer();
|
||||
await writeFile(
|
||||
path.join(uploadDir, attachment.id),
|
||||
Buffer.from(arrayBuffer),
|
||||
attachmentPath(attachment.id),
|
||||
attachment.bytes,
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -163,10 +143,13 @@ export async function createAnnouncement(formData: FormData) {
|
||||
await prisma.announcement.delete({ where: { id: announcement.id } });
|
||||
await Promise.all(
|
||||
attachmentInputs.map((attachment) =>
|
||||
rm(path.join(uploadDir, attachment.id), { force: true }),
|
||||
rm(attachmentPath(attachment.id), { force: true }),
|
||||
),
|
||||
);
|
||||
console.error("Ankündigungs-Anhang konnte nicht gespeichert werden:", error);
|
||||
console.error(
|
||||
"Ankündigungs-Anhang konnte nicht gespeichert werden:",
|
||||
error,
|
||||
);
|
||||
return { error: "Anhang konnte nicht gespeichert werden." };
|
||||
}
|
||||
}
|
||||
@@ -198,6 +181,7 @@ export async function createAnnouncement(formData: FormData) {
|
||||
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/dashboard/admin/news");
|
||||
revalidatePath("/dashboard/mitteilungen");
|
||||
|
||||
if (emailError) {
|
||||
return {
|
||||
@@ -216,6 +200,7 @@ export async function markAnnouncementRead(announcementId: string) {
|
||||
where: {
|
||||
id: announcementId,
|
||||
kitaId: session.user.kitaId,
|
||||
audience: { in: visibleAnnouncementAudiences(session.user) },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
@@ -232,6 +217,7 @@ export async function markAnnouncementRead(announcementId: string) {
|
||||
},
|
||||
},
|
||||
create: {
|
||||
kitaId: session.user.kitaId,
|
||||
userId: session.user.id,
|
||||
announcementId: announcement.id,
|
||||
},
|
||||
@@ -241,5 +227,6 @@ export async function markAnnouncementRead(announcementId: string) {
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/dashboard/mitteilungen");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
+5
-27
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { createElement } from "react";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
|
||||
import { ContactConfirmationEmail } from "@/emails/ContactConfirmationEmail";
|
||||
import { ContactRequestEmail } from "@/emails/ContactRequestEmail";
|
||||
@@ -11,39 +11,17 @@ import {
|
||||
type ContactSubmissionPayload,
|
||||
} from "@/lib/contact-schema";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
|
||||
const DEFAULT_ADMIN_EMAIL = "kontakt@kita-planer.local";
|
||||
const RATE_LIMIT_MAX = 5;
|
||||
const RATE_LIMIT_WINDOW_SECONDS = 60 * 60;
|
||||
|
||||
async function resolveClientIp(): Promise<string> {
|
||||
const h = await headers();
|
||||
const forwarded = h.get("x-forwarded-for");
|
||||
if (forwarded) {
|
||||
return forwarded.split(",")[0]?.trim() || "unknown";
|
||||
}
|
||||
return h.get("x-real-ip") ?? "unknown";
|
||||
}
|
||||
|
||||
export async function submitContactRequest(data: ContactSubmissionPayload) {
|
||||
// Honeypot: silently absorb bot submissions without informing them.
|
||||
if (data.website && data.website.trim().length > 0) {
|
||||
if (typeof data?.website === "string" && data.website.trim().length > 0) {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
const ip = await resolveClientIp();
|
||||
const limit = rateLimit(
|
||||
`contact:${ip}`,
|
||||
RATE_LIMIT_MAX,
|
||||
RATE_LIMIT_WINDOW_SECONDS,
|
||||
);
|
||||
if (!limit.allowed) {
|
||||
const minutes = Math.max(1, Math.ceil(limit.retryAfterSeconds / 60));
|
||||
return {
|
||||
success: false,
|
||||
error: `Zu viele Anfragen. Bitte versuche es in ${minutes} Minuten erneut.`,
|
||||
};
|
||||
if (!(await limitPublicAction("contact", String(data.email ?? "").trim().toLowerCase()))) {
|
||||
return { success: false, error: "Zu viele Anfragen. Bitte versuche es später erneut." };
|
||||
}
|
||||
|
||||
const parsed = contactRequestSchema.safeParse(data);
|
||||
|
||||
+95
-58
@@ -3,20 +3,16 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
import {
|
||||
EventParticipationStatus,
|
||||
RsvpMode,
|
||||
TerminStatus,
|
||||
UserRole,
|
||||
} from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { rsvpSubmissionSchema } from "@/lib/rsvp";
|
||||
import { lockEvent } from "@/lib/event-lock";
|
||||
|
||||
import { requireKitaSession, requireRole } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const submitRsvpSchema = z.object({
|
||||
eventId: z.string().min(1),
|
||||
childId: z.string().min(1),
|
||||
status: z.nativeEnum(EventParticipationStatus),
|
||||
});
|
||||
|
||||
export type EventParticipantDto = {
|
||||
childId: string;
|
||||
childName: string;
|
||||
@@ -24,79 +20,120 @@ export type EventParticipantDto = {
|
||||
status: EventParticipationStatus | null;
|
||||
};
|
||||
|
||||
export async function submitEventRsvp(rawPayload: unknown) {
|
||||
export async function submitEventRsvp(
|
||||
rawPayload: unknown,
|
||||
): Promise<{ error?: string; success?: boolean }> {
|
||||
const session = await requireKitaSession();
|
||||
const parsed = submitRsvpSchema.safeParse(rawPayload);
|
||||
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
const parsed = rsvpSubmissionSchema.safeParse(rawPayload);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
error:
|
||||
"Bitte alle Antworten und bei Familienzusagen die Anzahl Erwachsener angeben.",
|
||||
};
|
||||
if (!session.user.familyId || session.user.role === UserRole.ERZIEHER) {
|
||||
return {
|
||||
error: "Für Rückmeldungen ist ein Elternkonto mit Haushalt erforderlich.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!session.user.familyId) {
|
||||
return { error: "Dein Account ist noch keinem Haushalt zugeordnet." };
|
||||
}
|
||||
|
||||
const { eventId, childId, status } = parsed.data;
|
||||
|
||||
const event = await prisma.termin.findFirst({
|
||||
where: {
|
||||
id: eventId,
|
||||
kitaId: session.user.kitaId,
|
||||
},
|
||||
const kitaId = session.user.kitaId;
|
||||
const familyId = session.user.familyId;
|
||||
const payload = parsed.data;
|
||||
try {
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
await lockEvent(tx, payload.eventId, kitaId);
|
||||
const event = await tx.termin.findFirst({
|
||||
where: { id: payload.eventId, kitaId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
requiresRsvp: true,
|
||||
rsvpMode: true,
|
||||
rsvpDeadline: true,
|
||||
startDate: true,
|
||||
kita: { select: { terminModuleEnabled: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!event || !event.requiresRsvp || event.status !== TerminStatus.CONFIRMED) {
|
||||
if (
|
||||
!event?.kita.terminModuleEnabled ||
|
||||
!event.requiresRsvp ||
|
||||
event.status !== TerminStatus.CONFIRMED
|
||||
) {
|
||||
return { error: "Für diesen Termin ist keine Rückmeldung aktiv." };
|
||||
}
|
||||
|
||||
const deadline = event.rsvpDeadline ?? event.startDate;
|
||||
if (deadline < new Date()) {
|
||||
return { error: "Die Rückmeldefrist ist bereits abgelaufen." };
|
||||
}
|
||||
|
||||
const child = await prisma.child.findFirst({
|
||||
where: {
|
||||
id: childId,
|
||||
kitaId: session.user.kitaId,
|
||||
familyId: session.user.familyId,
|
||||
active: true,
|
||||
},
|
||||
if (event.rsvpMode !== payload.mode)
|
||||
return {
|
||||
error: "Die Antwortart wurde geändert. Bitte lade den Termin erneut.",
|
||||
};
|
||||
if (payload.mode === RsvpMode.FAMILY) {
|
||||
const family = await tx.family.findFirst({
|
||||
where: { id: familyId, kitaId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!child) {
|
||||
return { error: "Dieses Kind gehört nicht zu deinem Haushalt." };
|
||||
if (!family) return { error: "Haushalt wurde nicht gefunden." };
|
||||
if (
|
||||
(event.rsvpDeadline ?? event.startDate) <= new Date() ||
|
||||
event.startDate <= new Date()
|
||||
) {
|
||||
return { error: "Die Rückmeldefrist ist bereits abgelaufen." };
|
||||
}
|
||||
|
||||
await prisma.eventParticipation.upsert({
|
||||
await tx.familyEventParticipation.upsert({
|
||||
where: { eventId_familyId: { eventId: payload.eventId, familyId } },
|
||||
create: {
|
||||
kitaId,
|
||||
eventId: payload.eventId,
|
||||
familyId,
|
||||
status: payload.status,
|
||||
adultCount: payload.adultCount,
|
||||
},
|
||||
update: { status: payload.status, adultCount: payload.adultCount },
|
||||
});
|
||||
} else {
|
||||
const children = await tx.child.findMany({
|
||||
where: { kitaId, familyId, active: true },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = new Set(children.map((child) => child.id));
|
||||
if (
|
||||
payload.responses.length !== ids.size ||
|
||||
payload.responses.some((row) => !ids.has(row.childId))
|
||||
) {
|
||||
return {
|
||||
error:
|
||||
"Bitte antworte für alle eigenen aktiven Kinder. Lade den Termin bei Änderungen erneut.",
|
||||
};
|
||||
}
|
||||
if (
|
||||
(event.rsvpDeadline ?? event.startDate) <= new Date() ||
|
||||
event.startDate <= new Date()
|
||||
) {
|
||||
return { error: "Die Rückmeldefrist ist bereits abgelaufen." };
|
||||
}
|
||||
for (const response of payload.responses) {
|
||||
await tx.eventParticipation.upsert({
|
||||
where: {
|
||||
eventId_childId: {
|
||||
eventId,
|
||||
childId,
|
||||
eventId: payload.eventId,
|
||||
childId: response.childId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
kitaId: session.user.kitaId,
|
||||
eventId,
|
||||
childId,
|
||||
status,
|
||||
},
|
||||
update: {
|
||||
status,
|
||||
},
|
||||
create: { kitaId, eventId: payload.eventId, ...response },
|
||||
update: { status: response.status },
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
return { success: true };
|
||||
});
|
||||
if (result.error) return result;
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
return { success: true };
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("Rückmeldung konnte nicht gespeichert werden:", error);
|
||||
return {
|
||||
error:
|
||||
"Rückmeldung konnte nicht gespeichert werden. Bitte versuche es erneut.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEventParticipants(
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { removeAttachmentFiles } from "@/lib/attachments";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { AuditTargetType, UserRole } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
@@ -26,6 +28,7 @@ type ActionResult = {
|
||||
|
||||
async function requireSuperadminActor() {
|
||||
const session = await requireRole([UserRole.SUPERADMIN]);
|
||||
if (Date.now() - session.user.authenticatedAt > 15 * 60_000) redirect("/login?reauth=1&callbackUrl=/admin");
|
||||
return {
|
||||
id: session.user.id,
|
||||
email: session.user.email ?? session.user.name ?? "Unbekannter Superadmin",
|
||||
@@ -92,7 +95,8 @@ export async function deleteKita(
|
||||
|
||||
const counts = await getKitaDeleteCounts(kita.id);
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const attachmentIds = await prisma.$transaction(async (tx) => {
|
||||
const attachments = await tx.attachment.findMany({ where: { announcement: { kitaId: kita.id } }, select: { id: true } });
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
actorUserId: actor.id,
|
||||
@@ -107,8 +111,10 @@ export async function deleteKita(
|
||||
});
|
||||
|
||||
await tx.kita.delete({ where: { id: kita.id } });
|
||||
return attachments.map(item => item.id);
|
||||
});
|
||||
|
||||
await removeAttachmentFiles(attachmentIds);
|
||||
revalidatePath("/admin");
|
||||
revalidatePath("/admin/audit");
|
||||
return { ok: true, redirectTo: "/admin" };
|
||||
@@ -182,7 +188,8 @@ export async function deleteUser(rawPayload: unknown): Promise<ActionResult> {
|
||||
};
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const attachmentIds = await prisma.$transaction(async (tx) => {
|
||||
const attachments = await tx.attachment.findMany({ where: { announcement: { authorId: user.id } }, select: { id: true } });
|
||||
await tx.verificationToken.deleteMany({
|
||||
where: { identifier: user.id },
|
||||
});
|
||||
@@ -206,8 +213,10 @@ export async function deleteUser(rawPayload: unknown): Promise<ActionResult> {
|
||||
},
|
||||
});
|
||||
await tx.user.delete({ where: { id: user.id } });
|
||||
return attachments.map(item => item.id);
|
||||
});
|
||||
|
||||
await removeAttachmentFiles(attachmentIds);
|
||||
revalidatePath("/admin");
|
||||
revalidatePath(`/admin/kitas/${user.kitaId}`);
|
||||
revalidatePath("/admin/audit");
|
||||
@@ -219,6 +228,7 @@ async function updateUserSupportState(
|
||||
action: "USER_LOCK" | "USER_UNLOCK" | "USER_FAILED_LOGIN_RESET",
|
||||
data: {
|
||||
lockedUntil?: Date | null;
|
||||
disabledAt?: Date | null;
|
||||
failedLoginAttempts?: number;
|
||||
},
|
||||
): Promise<ActionResult> {
|
||||
@@ -238,7 +248,7 @@ async function updateUserSupportState(
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: user.id },
|
||||
data,
|
||||
data: { ...data, ...(action === "USER_LOCK" ? { sessionVersion: { increment: 1 } } : {}) },
|
||||
});
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
@@ -266,12 +276,14 @@ async function updateUserSupportState(
|
||||
|
||||
export async function lockUser(userId: string): Promise<ActionResult> {
|
||||
return updateUserSupportState(userId, "USER_LOCK", {
|
||||
disabledAt: new Date(),
|
||||
lockedUntil: new Date("2099-12-31T23:59:59.000Z"),
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlockUser(userId: string): Promise<ActionResult> {
|
||||
return updateUserSupportState(userId, "USER_UNLOCK", {
|
||||
disabledAt: null,
|
||||
lockedUntil: null,
|
||||
failedLoginAttempts: 0,
|
||||
});
|
||||
|
||||
@@ -1,34 +1,37 @@
|
||||
"use server";
|
||||
|
||||
import { publicActionError } from "@/lib/action-error";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { NotdienstAlertStatus } from "@prisma/client";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { respondToAlarm } from "@/lib/alarms/service";
|
||||
import { deliverAlarmEmails } from "@/lib/alarms/email";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
import { hashToken, isPublicToken } from "@/lib/tokens";
|
||||
|
||||
export async function confirmAlertAction(token: string) {
|
||||
export async function respondAlertAction(token: string, approve: boolean) {
|
||||
if (!isPublicToken(token) || typeof approve !== "boolean")
|
||||
return { error: "Ungültiger Rückmeldelink." };
|
||||
if (!(await limitPublicAction("alarm-response", hashToken(token), 12, 60)))
|
||||
return { error: "Bitte kurz warten und erneut versuchen." };
|
||||
try {
|
||||
const alert = await prisma.notdienstAlert.findUnique({
|
||||
where: { confirmationToken: token },
|
||||
});
|
||||
|
||||
if (!alert) {
|
||||
return { error: "Ungültiger Bestätigungs-Link." };
|
||||
}
|
||||
|
||||
if (alert.status !== NotdienstAlertStatus.PENDING) {
|
||||
return { error: "Dieser Alarm wurde bereits bestätigt oder abgebrochen." };
|
||||
}
|
||||
|
||||
await prisma.notdienstAlert.update({
|
||||
where: { id: alert.id },
|
||||
data: {
|
||||
status: NotdienstAlertStatus.CONFIRMED,
|
||||
confirmedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
const result = await respondToAlarm(token, approve);
|
||||
// The household response is already committed; transport failure must not undo it.
|
||||
try {
|
||||
await deliverAlarmEmails(result.emailIds);
|
||||
} catch {
|
||||
return { error: "Fehler bei der Bestätigung." };
|
||||
/* Persistent jobs will retry. */
|
||||
}
|
||||
revalidatePath("/alert/[token]", "page");
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/dashboard/notdienst/alarm");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
const message = publicActionError(error, "");
|
||||
if (message) return { error: message };
|
||||
return {
|
||||
error:
|
||||
"Die Rückmeldung konnte nicht gespeichert werden. Bitte den aktuellen Stand prüfen.",
|
||||
};
|
||||
}
|
||||
}
|
||||
export async function confirmAlertAction(token: string) {
|
||||
return respondAlertAction(token, true);
|
||||
}
|
||||
|
||||
@@ -1,37 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { confirmAlertAction } from "./actions";
|
||||
import { respondAlertAction } from "./actions";
|
||||
|
||||
export function AlertConfirmForm({ token }: { token: string }) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const handleConfirm = () => {
|
||||
startTransition(async () => {
|
||||
const result = await confirmAlertAction(token);
|
||||
if ("error" in result && result.error) {
|
||||
toast.error(result.error as string);
|
||||
} else {
|
||||
toast.success("Erfolgreich bestätigt!");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const [choice, setChoice] = useState<boolean | null>(null);
|
||||
const [pending, start] = useTransition();
|
||||
const [error, setError] = useState("");
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Button
|
||||
size="lg"
|
||||
className="w-full sm:w-auto font-semibold text-lg"
|
||||
onClick={handleConfirm}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
|
||||
) : null}
|
||||
Ich bestätige! (Bin auf dem Weg)
|
||||
<div className="grid gap-4">
|
||||
{choice === null ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Button onClick={() => setChoice(true)}>Wir übernehmen</Button>
|
||||
<Button variant="outline" onClick={() => setChoice(false)}>
|
||||
Wir können nicht
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3 rounded-xl border border-[var(--hairline)] bg-[var(--surface-2)] p-4">
|
||||
<p className="text-sm">
|
||||
{choice
|
||||
? "Wir sagen für unseren Haushalt zu."
|
||||
: "Unser Haushalt kann diesen Einsatz nicht übernehmen."}{" "}
|
||||
Diese Antwort gilt für alle Elternkonten des Haushalts.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
start(async () => {
|
||||
setError("");
|
||||
const result = await respondAlertAction(token, choice);
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
router.refresh();
|
||||
} else router.refresh();
|
||||
})
|
||||
}
|
||||
>
|
||||
{pending ? "Wird gespeichert …" : "Antwort verbindlich speichern"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
setChoice(null);
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
Zurück
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-[var(--danger)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+90
-103
@@ -1,127 +1,114 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { BellRing, ShieldCheck, XCircle } from "lucide-react";
|
||||
import { NotdienstAlertStatus } from "@prisma/client";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { BellRing, CheckCircle2 } from "lucide-react";
|
||||
import { getPublicAlarm } from "@/lib/alarms/service";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
alarmLabel,
|
||||
dateKey,
|
||||
durationLabel,
|
||||
instantLabel,
|
||||
} from "@/lib/alarms/format";
|
||||
import { AlertConfirmForm } from "./alert-confirm-form";
|
||||
|
||||
export const metadata = { title: "Notdienst Alarm · Kita-Planer" };
|
||||
|
||||
export const metadata = {
|
||||
title: "Notdienstalarm · Kita-Planer",
|
||||
robots: { index: false, follow: false },
|
||||
referrer: "no-referrer" as const,
|
||||
};
|
||||
export const dynamic = "force-dynamic";
|
||||
export default async function AlertPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ token: string }>;
|
||||
}) {
|
||||
const { token } = await params;
|
||||
|
||||
const alert = await prisma.notdienstAlert.findUnique({
|
||||
where: { confirmationToken: token },
|
||||
select: {
|
||||
status: true,
|
||||
parentUser: {
|
||||
select: {
|
||||
firstName: true,
|
||||
},
|
||||
},
|
||||
kita: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
assignment: {
|
||||
select: {
|
||||
date: true,
|
||||
child: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!alert) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const isPending = alert.status === NotdienstAlertStatus.PENDING;
|
||||
const isConfirmed = alert.status === NotdienstAlertStatus.CONFIRMED;
|
||||
|
||||
const alarm = await getPublicAlarm(token);
|
||||
if (!alarm) notFound();
|
||||
const now = new Date(),
|
||||
expired = alarm.expiresAt <= now;
|
||||
const canRespond = alarm.status === "PENDING" && !expired;
|
||||
const overdue = alarm.deadline <= now;
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-muted/30 px-4 py-12">
|
||||
<Card className="w-full max-w-md shadow-lg border-primary/20">
|
||||
<CardHeader className="text-center pb-2">
|
||||
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 text-primary">
|
||||
{isPending ? (
|
||||
<BellRing className="h-8 w-8 animate-pulse text-destructive" />
|
||||
) : isConfirmed ? (
|
||||
<ShieldCheck className="h-8 w-8 text-success" />
|
||||
<main className="flex min-h-screen items-center justify-center bg-[var(--bg)] px-5 py-12">
|
||||
<section className="w-full max-w-xl overflow-hidden rounded-2xl border border-[var(--hairline)] bg-[var(--surface)] shadow-sm">
|
||||
<header
|
||||
className={`border-b border-[var(--hairline)] p-6 sm:p-8 ${alarm.status === "CONFIRMED" ? "bg-[var(--accent-soft)]" : "bg-[var(--surface-2)]"}`}
|
||||
>
|
||||
<p className="text-xs font-semibold uppercase tracking-widest text-[var(--accent-deep)]">
|
||||
Kita-Planer · {alarm.kitaName}
|
||||
</p>
|
||||
{alarm.status === "CONFIRMED" ? (
|
||||
<CheckCircle2 className="mt-6 h-7 w-7 text-[var(--accent-deep)]" />
|
||||
) : (
|
||||
<XCircle className="h-8 w-8 text-muted-foreground" />
|
||||
<BellRing className="mt-6 h-7 w-7 text-[var(--danger)]" />
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-2xl">
|
||||
{isPending
|
||||
? "Notdienst Einsatz!"
|
||||
: isConfirmed
|
||||
? "Einsatz bestätigt"
|
||||
: "Alarm abgebrochen"}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base mt-2">
|
||||
Kita {alert.kita.name}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6 pt-4">
|
||||
<div className="rounded-lg bg-background border p-4 text-center space-y-1">
|
||||
<p className="text-sm text-muted-foreground">Datum</p>
|
||||
<p className="font-semibold text-lg">
|
||||
{format(alert.assignment.date, "EEEE, dd. MMMM yyyy", {
|
||||
locale: de,
|
||||
})}
|
||||
</p>
|
||||
<div className="h-2" />
|
||||
<p className="text-sm text-muted-foreground">Eingeteiltes Kind</p>
|
||||
<p className="font-medium">
|
||||
{alert.assignment.child.firstName}{" "}
|
||||
{alert.assignment.child.lastName}
|
||||
<h1 className="mt-3 text-3xl text-[var(--ink)]">
|
||||
{alarm.status === "PENDING"
|
||||
? "Könnt ihr den Notdienst übernehmen?"
|
||||
: alarmLabel(alarm)}
|
||||
</h1>
|
||||
<p className="mt-3 text-sm leading-6 text-[var(--ink-soft)]">
|
||||
Hallo {alarm.firstName}, diese Rückmeldung gilt für euren gesamten
|
||||
Haushalt.
|
||||
</p>
|
||||
</header>
|
||||
<div className="grid gap-6 p-6 sm:p-8">
|
||||
<dl className="grid grid-cols-2 gap-5 text-sm">
|
||||
<div>
|
||||
<dt className="text-[var(--ink-muted)]">Datum</dt>
|
||||
<dd className="mt-1 font-semibold">
|
||||
{dateKey(alarm.date).split("-").reverse().join(".")}
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
{isPending ? (
|
||||
<div>
|
||||
<dt className="text-[var(--ink-muted)]">Einsatz</dt>
|
||||
<dd className="mt-1 font-semibold">{durationLabel(alarm)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-[var(--ink-muted)]">Haushalt</dt>
|
||||
<dd className="mt-1 font-semibold">{alarm.familyName}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-[var(--ink-muted)]">Antwortfrist</dt>
|
||||
<dd className="mt-1 font-semibold">
|
||||
{instantLabel(alarm.deadline)} Uhr
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{canRespond ? (
|
||||
<>
|
||||
<p className="mb-6 text-sm text-muted-foreground">
|
||||
Hallo {alert.parentUser.firstName}, eine Fachkraft hat sich
|
||||
krankgemeldet und du bist heute für den Notdienst eingeteilt.
|
||||
Bitte bestätige deinen Einsatz schnellstmöglich!
|
||||
{overdue && (
|
||||
<p className="rounded-lg bg-[var(--surface-2)] p-4 text-sm leading-6">
|
||||
Die Antwortfrist ist abgelaufen. Ihr könnt noch antworten.
|
||||
Eine verspätete Zusage muss die Koordination freigeben, da
|
||||
möglicherweise bereits Ersatz organisiert wird.
|
||||
</p>
|
||||
)}
|
||||
<AlertConfirmForm token={token} />
|
||||
</>
|
||||
) : isConfirmed ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Danke, {alert.parentUser.firstName}! Dein Einsatz wurde
|
||||
erfolgreich bestätigt. Die Kita rechnet mit dir.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Dieser Einsatz wurde vom Koordinator abgebrochen. Du musst nicht
|
||||
einspringen.
|
||||
</p>
|
||||
<div
|
||||
role="status"
|
||||
className="rounded-xl border border-[var(--hairline)] p-4 text-sm leading-6"
|
||||
>
|
||||
{alarm.status === "CANCELLED"
|
||||
? "Der Einsatz wurde storniert. Ihr müsst für diesen Alarm nicht einspringen."
|
||||
: alarm.status === "CONFIRMED"
|
||||
? "Euer Haushalt hat zugesagt. Die Kita rechnet mit euch. Bei einer Änderung kontaktiert bitte die Koordination."
|
||||
: alarm.status === "LATE_CONFIRMATION"
|
||||
? "Eure verspätete Zusage ist gespeichert. Wartet bitte auf die Freigabe durch die Koordination."
|
||||
: alarm.status === "DECLINED"
|
||||
? "Die Absage eures Haushalts ist gespeichert. Die Koordination kümmert sich um Ersatz."
|
||||
: alarm.status === "REVIEW_REQUIRED"
|
||||
? "Die bisherigen Rückmeldungen müssen von der Koordination geprüft werden. Bitte kontaktiert die Kita."
|
||||
: "Der Einsatz ist beendet. Dieser Rückmeldelink ist abgelaufen."}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs leading-5 text-[var(--ink-muted)]">
|
||||
Den persönlichen Link bitte innerhalb eures Haushalts behalten.
|
||||
Änderungen einer gespeicherten Antwort klärt ihr mit der Kita.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,19 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import path from "path";
|
||||
import { open } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { attachmentPath, attachmentDisposition, detectAttachmentType, MAX_ATTACHMENT_SIZE } from "@/lib/attachments";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/auth";
|
||||
import { getKitaSession } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { visibleAnnouncementAudiences } from "@/lib/announcement-access";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
function getUploadPath(attachmentId: string) {
|
||||
const uploadDir = path.resolve(
|
||||
process.env.UPLOAD_DIR ?? "uploads",
|
||||
"announcements",
|
||||
);
|
||||
return path.join(uploadDir, attachmentId);
|
||||
}
|
||||
|
||||
function contentDisposition(fileName: string) {
|
||||
const fallback = fileName.replace(/[^\w.\-]/g, "_");
|
||||
return `inline; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const session = await auth();
|
||||
const session = await getKitaSession();
|
||||
const user = session?.user;
|
||||
|
||||
if (!user?.id || !user.kitaId) {
|
||||
@@ -32,11 +21,13 @@ export async function GET(
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
try { attachmentPath(id); } catch { return NextResponse.json({ error: "Not found" }, { status: 404 }); }
|
||||
const attachment = await prisma.attachment.findFirst({
|
||||
where: {
|
||||
id,
|
||||
announcement: {
|
||||
kitaId: user.kitaId,
|
||||
audience: { in: visibleAnnouncementAudiences(user) },
|
||||
},
|
||||
},
|
||||
select: {
|
||||
@@ -51,12 +42,22 @@ export async function GET(
|
||||
}
|
||||
|
||||
try {
|
||||
const file = await readFile(getUploadPath(attachment.id));
|
||||
const filePath = attachmentPath(attachment.id);
|
||||
const handle = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
let file: Buffer;
|
||||
try {
|
||||
const info = await handle.stat();
|
||||
if (!info.isFile() || info.size > MAX_ATTACHMENT_SIZE) throw new Error("Invalid attachment");
|
||||
file = await handle.readFile();
|
||||
} finally { await handle.close(); }
|
||||
return new Response(new Uint8Array(file), {
|
||||
headers: {
|
||||
"Content-Type": attachment.fileType,
|
||||
"Content-Disposition": contentDisposition(attachment.fileName),
|
||||
"Cache-Control": "private, max-age=300",
|
||||
"Content-Type": detectAttachmentType(file) ?? "application/octet-stream",
|
||||
"Content-Disposition": attachmentDisposition(attachment.fileName),
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { authorizeAlarmJob, runAlarmJob } from "@/lib/alarms/job";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const status = authorizeAlarmJob(request.headers.get("authorization"));
|
||||
if (status !== 200)
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
status === 503
|
||||
? "Fristprüfung ist nicht konfiguriert."
|
||||
: "Nicht autorisiert.",
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
try {
|
||||
const result = await runAlarmJob();
|
||||
revalidatePath("/dashboard");
|
||||
revalidatePath("/dashboard/notdienst/alarm");
|
||||
return Response.json(result);
|
||||
} catch {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
"Fristprüfung fehlgeschlagen; nächster Aufruf versucht es erneut.",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,123 +1,10 @@
|
||||
"use server";
|
||||
|
||||
import crypto from "crypto";
|
||||
import { createElement } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { NotdienstAlertStatus, UserRole } from "@prisma/client";
|
||||
|
||||
import { AlertEmail } from "@/emails/AlertEmail";
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const BASE_URL =
|
||||
process.env.NEXTAUTH_URL ?? process.env.AUTH_URL ?? "http://localhost:3000";
|
||||
|
||||
import { alarmAction } from "./notdienst/alarm/actions";
|
||||
// Existing callers use the shared household workflow and the same guards.
|
||||
export async function triggerAlertAction(assignmentId: string) {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId!;
|
||||
|
||||
try {
|
||||
const [existing, assignment] = await Promise.all([
|
||||
// Prüfen ob es schon einen aktiven Alert für dieses Assignment gibt
|
||||
prisma.notdienstAlert.findFirst({
|
||||
where: { assignmentId, kitaId },
|
||||
}),
|
||||
prisma.notdienstAssignment.findFirst({
|
||||
where: { id: assignmentId, kitaId },
|
||||
include: {
|
||||
child: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
family: {
|
||||
select: {
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (existing) {
|
||||
return { error: "Für diese Einteilung wurde bereits ein Alarm ausgelöst." };
|
||||
}
|
||||
|
||||
if (!assignment) {
|
||||
return { error: "Notdienst-Einteilung wurde nicht gefunden." };
|
||||
}
|
||||
|
||||
const parents = assignment.child.family.users;
|
||||
|
||||
if (parents.length === 0) {
|
||||
return { error: "Kein Elternteil für diesen Notdienst hinterlegt." };
|
||||
}
|
||||
|
||||
const mailConfigError = getAppEmailConfigError();
|
||||
if (mailConfigError) {
|
||||
return { error: mailConfigError };
|
||||
}
|
||||
|
||||
const dateLabel = format(assignment.date, "EEEE, dd. MMMM yyyy", {
|
||||
locale: de,
|
||||
});
|
||||
const childName = `${assignment.child.firstName} ${assignment.child.lastName}`;
|
||||
const alertJobs: { email: string; token: string }[] = [];
|
||||
|
||||
await prisma.$transaction(
|
||||
parents.map((parent) => {
|
||||
const token = crypto.randomUUID();
|
||||
alertJobs.push({ email: parent.email, token });
|
||||
return prisma.notdienstAlert.create({
|
||||
data: {
|
||||
kitaId,
|
||||
return alarmAction("create", {
|
||||
assignmentId,
|
||||
parentUserId: parent.id,
|
||||
triggeredById: session.user.id,
|
||||
status: NotdienstAlertStatus.PENDING,
|
||||
confirmationToken: token,
|
||||
},
|
||||
wholeDay: true,
|
||||
replyMinutes: 30,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
for (const job of alertJobs) {
|
||||
const emailResult = await sendAppEmail({
|
||||
to: job.email,
|
||||
subject: `Dringender Notdienst-Alarm für ${dateLabel}`,
|
||||
react: createElement(AlertEmail, {
|
||||
date: dateLabel,
|
||||
childName,
|
||||
confirmLink: `${BASE_URL}/alert/${job.token}`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!emailResult.success) {
|
||||
revalidatePath("/dashboard");
|
||||
return {
|
||||
error: `Alarm wurde angelegt, aber mindestens eine E-Mail konnte nicht versendet werden: ${emailResult.error}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/dashboard");
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return { error: "Fehler beim Auslösen des Alarms." };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,13 @@ import { revalidatePath } from "next/cache";
|
||||
import { DutyAssignmentStatus, UserRole } from "@prisma/client";
|
||||
import { endOfWeek, format, startOfDay, startOfWeek } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { dateOnlySchema } from "@/lib/date-schema";
|
||||
import { z } from "zod";
|
||||
|
||||
import { DutyReminderEmail } from "@/emails/DutyReminderEmail";
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const dutyTypeSchema = z.object({
|
||||
@@ -20,8 +22,8 @@ const dutyTypeSchema = z.object({
|
||||
const assignmentSchema = z.object({
|
||||
dutyTypeId: z.string().min(1),
|
||||
familyId: z.string().nullable(),
|
||||
startDate: z.string().min(1),
|
||||
endDate: z.string().min(1),
|
||||
startDate: dateOnlySchema,
|
||||
endDate: dateOnlySchema,
|
||||
});
|
||||
|
||||
async function requireDutyAdmin() {
|
||||
@@ -160,6 +162,7 @@ export async function upsertDutyAssignment(rawPayload: unknown) {
|
||||
|
||||
export async function checkAndSendDutyReminders() {
|
||||
const { kitaId } = await requireDutyAdmin();
|
||||
if (!(await rateLimit(`duty-reminders:${kitaId}`, 3, 3600)).allowed) return { error: "Bitte versuche es später erneut." };
|
||||
const configError = getAppEmailConfigError();
|
||||
|
||||
if (configError) {
|
||||
@@ -195,6 +198,8 @@ export async function checkAndSendDutyReminders() {
|
||||
users: {
|
||||
where: {
|
||||
emailVerifiedAt: { not: null },
|
||||
disabledAt: null,
|
||||
privacyPolicyAcceptedAt: { not: null },
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import {
|
||||
EventParticipationStatus,
|
||||
RsvpMode,
|
||||
TerminStatus,
|
||||
TerminType,
|
||||
} from "@prisma/client";
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { suggestedRsvpMode } from "@/lib/rsvp";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -48,10 +50,7 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
createTerminAdmin,
|
||||
updateTerminAdmin,
|
||||
} from "../../kalender/actions";
|
||||
import { createTerminAdmin, updateTerminAdmin } from "../../kalender/actions";
|
||||
|
||||
type AdminTerminDto = {
|
||||
id: string;
|
||||
@@ -64,6 +63,12 @@ type AdminTerminDto = {
|
||||
allDay: boolean;
|
||||
mitbringselListEnabled: boolean;
|
||||
requiresRsvp: boolean;
|
||||
rsvpMode: RsvpMode;
|
||||
familyParticipations: {
|
||||
familyId: string;
|
||||
status: EventParticipationStatus;
|
||||
adultCount: number;
|
||||
}[];
|
||||
rsvpDeadline: string | null;
|
||||
participantInfo: string | null;
|
||||
participations: {
|
||||
@@ -81,9 +86,11 @@ type ChildDto = {
|
||||
export function AdminCalendarManager({
|
||||
termine,
|
||||
childRows,
|
||||
familyRows,
|
||||
}: {
|
||||
termine: AdminTerminDto[];
|
||||
childRows: ChildDto[];
|
||||
familyRows: { id: string; name: string }[];
|
||||
}) {
|
||||
const rsvpCount = termine.filter((termin) => termin.requiresRsvp).length;
|
||||
const pendingCount = termine.filter(
|
||||
@@ -104,8 +111,8 @@ export function AdminCalendarManager({
|
||||
</em>
|
||||
</h1>
|
||||
<p className="mt-2 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
Termine verwalten, RSVP aktivieren und den Rücklauf pro Kind
|
||||
verfolgen.
|
||||
Termine verwalten, RSVP aktivieren und den Rücklauf pro Familie oder
|
||||
Kind verfolgen.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap gap-2">
|
||||
@@ -145,6 +152,7 @@ export function AdminCalendarManager({
|
||||
key={termin.id}
|
||||
termin={termin}
|
||||
childRows={childRows}
|
||||
familyRows={familyRows}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -156,11 +164,25 @@ export function AdminCalendarManager({
|
||||
function AdminTerminCard({
|
||||
termin,
|
||||
childRows,
|
||||
familyRows,
|
||||
}: {
|
||||
termin: AdminTerminDto;
|
||||
childRows: ChildDto[];
|
||||
familyRows: { id: string; name: string }[];
|
||||
}) {
|
||||
const stats = useMemo(() => getStats(termin, childRows), [termin, childRows]);
|
||||
const isFamily = termin.rsvpMode === RsvpMode.FAMILY;
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
isFamily
|
||||
? familyRows.map((family) => ({
|
||||
id: family.id,
|
||||
name: family.name,
|
||||
familyName: family.name,
|
||||
}))
|
||||
: childRows,
|
||||
[isFamily, familyRows, childRows],
|
||||
);
|
||||
const stats = useMemo(() => getStats(termin, rows), [termin, rows]);
|
||||
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
@@ -175,7 +197,9 @@ function AdminTerminCard({
|
||||
{getStatusLabel(termin.status)}
|
||||
</Badge>
|
||||
{termin.requiresRsvp && (
|
||||
<Badge variant="warning">RSVP aktiv</Badge>
|
||||
<Badge variant="warning">
|
||||
Antwort pro {isFamily ? "Familie" : "Kind"}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-lg">{termin.title}</CardTitle>
|
||||
@@ -217,14 +241,19 @@ function AdminTerminCard({
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{stats.attending} Zugesagt / {stats.notAttending} Abgesagt /{" "}
|
||||
{stats.pending} Ausstehend
|
||||
{stats.pending} Ausstehend{" "}
|
||||
{isFamily ? `· ${stats.adultCount} Erwachsene` : ""}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-[var(--ink-soft)]">
|
||||
Frist:{" "}
|
||||
{termin.rsvpDeadline
|
||||
? format(new Date(termin.rsvpDeadline), "dd.MM.yyyy HH:mm", {
|
||||
? format(
|
||||
new Date(termin.rsvpDeadline),
|
||||
"dd.MM.yyyy HH:mm",
|
||||
{
|
||||
locale: de,
|
||||
})
|
||||
},
|
||||
)
|
||||
: "bis Terminbeginn"}
|
||||
</p>
|
||||
</div>
|
||||
@@ -241,18 +270,24 @@ function AdminTerminCard({
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Kind</TableHead>
|
||||
<TableHead>Familie</TableHead>
|
||||
<TableHead>{isFamily ? "Familie" : "Kind"}</TableHead>
|
||||
<TableHead>{isFamily ? "Erwachsene" : "Familie"}</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{childRows.map((child) => {
|
||||
{rows.map((child) => {
|
||||
const status = stats.statusByChildId.get(child.id) ?? null;
|
||||
return (
|
||||
<TableRow key={child.id}>
|
||||
<TableCell className="font-medium">{child.name}</TableCell>
|
||||
<TableCell>{child.familyName}</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
{child.name}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{isFamily
|
||||
? (stats.adultCounts.get(child.id) ?? "–")
|
||||
: child.familyName}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<RsvpStatusBadge status={status} />
|
||||
</TableCell>
|
||||
@@ -283,6 +318,13 @@ function TerminFormDialog({
|
||||
const [requiresRsvp, setRequiresRsvp] = useState(
|
||||
termin?.requiresRsvp ?? false,
|
||||
);
|
||||
const [rsvpMode, setRsvpMode] = useState(
|
||||
termin?.rsvpMode ?? suggestedRsvpMode(TerminType.KITA_FEST),
|
||||
);
|
||||
const [modeTouched, setModeTouched] = useState(false);
|
||||
const modeLocked =
|
||||
!!termin &&
|
||||
termin.participations.length + termin.familyParticipations.length > 0;
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
function handleAction(formData: FormData) {
|
||||
@@ -300,6 +342,7 @@ function TerminFormDialog({
|
||||
allDay: formData.get("allDay") === "on",
|
||||
mitbringselListEnabled: formData.get("mitbringselListEnabled") === "on",
|
||||
requiresRsvp: hasRsvp,
|
||||
rsvpMode,
|
||||
rsvpDeadline:
|
||||
hasRsvp && deadlineRaw ? new Date(deadlineRaw).toISOString() : null,
|
||||
participantInfo: String(formData.get("participantInfo") ?? ""),
|
||||
@@ -330,6 +373,10 @@ function TerminFormDialog({
|
||||
setOpen(nextOpen);
|
||||
if (nextOpen) {
|
||||
setRequiresRsvp(termin?.requiresRsvp ?? false);
|
||||
setRsvpMode(
|
||||
termin?.rsvpMode ?? suggestedRsvpMode(TerminType.KITA_FEST),
|
||||
);
|
||||
setModeTouched(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -380,6 +427,12 @@ function TerminFormDialog({
|
||||
<select
|
||||
id={`${mode}-type`}
|
||||
name="type"
|
||||
onChange={(event) => {
|
||||
if (!termin && !modeLocked && !modeTouched)
|
||||
setRsvpMode(
|
||||
suggestedRsvpMode(event.target.value as TerminType),
|
||||
);
|
||||
}}
|
||||
defaultValue={termin?.type ?? TerminType.KITA_FEST}
|
||||
className="flex h-10 w-full rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-[13.5px] text-[var(--ink)] ring-offset-[var(--surface)] transition-colors hover:border-[var(--accent-mid)] focus-visible:border-[var(--accent)] focus-visible:bg-[oklch(0.99_0.005_75)] focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--focus-ring)]"
|
||||
required
|
||||
@@ -453,9 +506,33 @@ function TerminFormDialog({
|
||||
{requiresRsvp && (
|
||||
<div className="grid gap-4 rounded-lg border border-[var(--warn)] bg-[var(--warn-soft)] p-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${mode}-rsvpDeadline`}>
|
||||
Rückmeldefrist
|
||||
</Label>
|
||||
<Label htmlFor={`${mode}-rsvpMode`}>Antwortart</Label>
|
||||
<select
|
||||
id={`${mode}-rsvpMode`}
|
||||
value={rsvpMode}
|
||||
disabled={modeLocked}
|
||||
onChange={(e) => {
|
||||
setRsvpMode(e.target.value as RsvpMode);
|
||||
setModeTouched(true);
|
||||
}}
|
||||
className="h-10 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 text-sm disabled:opacity-60"
|
||||
>
|
||||
<option value="FAMILY">
|
||||
Pro Familie · mit Anzahl Erwachsener
|
||||
</option>
|
||||
<option value="CHILD">
|
||||
Pro Kind · einzelne Zu-/Absage
|
||||
</option>
|
||||
</select>
|
||||
{modeLocked ? (
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Die Antwortart ist gesperrt, da bereits Rückmeldungen
|
||||
vorliegen.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${mode}-rsvpDeadline`}>Rückmeldefrist</Label>
|
||||
<Input
|
||||
id={`${mode}-rsvpDeadline`}
|
||||
name="rsvpDeadline"
|
||||
@@ -532,28 +609,34 @@ function RsvpStatusBadge({
|
||||
);
|
||||
}
|
||||
|
||||
function getStats(termin: AdminTerminDto, children: ChildDto[]) {
|
||||
const statusByChildId = new Map(
|
||||
termin.participations.map((participation) => [
|
||||
participation.childId,
|
||||
participation.status,
|
||||
]),
|
||||
function getStats(termin: AdminTerminDto, rows: ChildDto[]) {
|
||||
const isFamily = termin.rsvpMode === RsvpMode.FAMILY;
|
||||
const statusByChildId = new Map<string, EventParticipationStatus>(
|
||||
isFamily
|
||||
? termin.familyParticipations.map((row) => [row.familyId, row.status])
|
||||
: termin.participations.map((row) => [row.childId, row.status]),
|
||||
);
|
||||
const adultCounts = new Map(
|
||||
termin.familyParticipations.map((row) => [row.familyId, row.adultCount]),
|
||||
);
|
||||
|
||||
let attending = 0;
|
||||
let notAttending = 0;
|
||||
|
||||
children.forEach((child) => {
|
||||
const status = statusByChildId.get(child.id);
|
||||
if (status === EventParticipationStatus.ATTENDING) attending += 1;
|
||||
let adultCount = 0;
|
||||
for (const row of rows) {
|
||||
const status = statusByChildId.get(row.id);
|
||||
if (status === EventParticipationStatus.ATTENDING) {
|
||||
attending += 1;
|
||||
adultCount += adultCounts.get(row.id) ?? 0;
|
||||
}
|
||||
if (status === EventParticipationStatus.NOT_ATTENDING) notAttending += 1;
|
||||
});
|
||||
|
||||
}
|
||||
return {
|
||||
attending,
|
||||
notAttending,
|
||||
pending: Math.max(children.length - attending - notAttending, 0),
|
||||
pending: rows.length - attending - notAttending,
|
||||
statusByChildId,
|
||||
adultCounts,
|
||||
adultCount,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export default async function AdminKalenderPage() {
|
||||
return <div className="p-8">Kein Mandant zugeordnet.</div>;
|
||||
}
|
||||
|
||||
const [termine, children] = await Promise.all([
|
||||
const [termine, children, families] = await Promise.all([
|
||||
prisma.termin.findMany({
|
||||
where: { kitaId },
|
||||
select: {
|
||||
@@ -28,6 +28,10 @@ export default async function AdminKalenderPage() {
|
||||
allDay: true,
|
||||
mitbringselListEnabled: true,
|
||||
requiresRsvp: true,
|
||||
rsvpMode: true,
|
||||
familyParticipations: {
|
||||
select: { familyId: true, status: true, adultCount: true },
|
||||
},
|
||||
rsvpDeadline: true,
|
||||
participantInfo: true,
|
||||
participations: {
|
||||
@@ -60,6 +64,11 @@ export default async function AdminKalenderPage() {
|
||||
{ firstName: "asc" },
|
||||
],
|
||||
}),
|
||||
prisma.family.findMany({
|
||||
where: { kitaId },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -70,6 +79,7 @@ export default async function AdminKalenderPage() {
|
||||
endDate: termin.endDate.toISOString(),
|
||||
rsvpDeadline: termin.rsvpDeadline?.toISOString() ?? null,
|
||||
}))}
|
||||
familyRows={families}
|
||||
childRows={children.map((child) => ({
|
||||
id: child.id,
|
||||
name: `${child.firstName} ${child.lastName}`,
|
||||
|
||||
@@ -64,7 +64,9 @@ export function NewsForm() {
|
||||
rows={10}
|
||||
value={content}
|
||||
onChange={(event) => setContent(event.target.value)}
|
||||
placeholder={"## Liebe Familien,\n\nhier stehen die offiziellen Informationen..."}
|
||||
placeholder={
|
||||
"## Liebe Familien,\n\nhier stehen die offiziellen Informationen..."
|
||||
}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-[var(--ink-muted)]">
|
||||
@@ -93,7 +95,7 @@ export function NewsForm() {
|
||||
/>
|
||||
<p className="mt-2 flex items-center gap-1 text-xs text-[var(--ink-muted)]">
|
||||
<UploadCloud className="h-3.5 w-3.5 [stroke-width:1.7]" />
|
||||
PDF, JPG und PNG bis 10 MB pro Datei.
|
||||
PDF, JPG und PNG: maximal 5 Dateien, je 10 MB und insgesamt 25 MB.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -110,21 +112,23 @@ export function NewsForm() {
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{sendEmail && (
|
||||
<div className="mt-4 grid gap-2">
|
||||
<Label>Empfänger</Label>
|
||||
<Label htmlFor="news-audience">Empfängergruppe</Label>
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Bestimmt, wer die Meldung und Anhänge in der App sehen darf und
|
||||
optional die E-Mail erhält.
|
||||
</p>
|
||||
<Select name="audience" defaultValue="ELTERN">
|
||||
<SelectTrigger>
|
||||
<SelectTrigger id="news-audience">
|
||||
<SelectValue placeholder="Empfänger auswählen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ELTERN">Eltern</SelectItem>
|
||||
<SelectItem value="ERZIEHER">ErzieherInnen</SelectItem>
|
||||
<SelectItem value="ALLE">Alle</SelectItem>
|
||||
<SelectItem value="ALLE">Eltern und ErzieherInnen</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { announcementAudienceLabels } from "@/lib/announcement-access";
|
||||
import { NewsForm } from "./news-form";
|
||||
|
||||
export const metadata = { title: "Schwarzes Brett · Kita-Planer" };
|
||||
@@ -30,6 +31,7 @@ export default async function AdminNewsPage() {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
audience: true,
|
||||
createdAt: true,
|
||||
attachments: {
|
||||
select: {
|
||||
@@ -63,8 +65,8 @@ export default async function AdminNewsPage() {
|
||||
</h1>
|
||||
<p className="mt-2 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
Veröffentliche verbindliche Ankündigungen für deine Kita. Anhänge
|
||||
werden geschützt gespeichert und nur für eingeloggte Nutzer
|
||||
derselben Kita ausgeliefert.
|
||||
werden geschützt gespeichert und nur an die gewählte Empfängergruppe
|
||||
deiner Kita ausgeliefert.
|
||||
</p>
|
||||
</div>
|
||||
<span className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--hairline)] bg-[var(--surface)] px-4 text-[13px] font-semibold text-[var(--ink-soft)] tabular-nums">
|
||||
@@ -127,6 +129,9 @@ export default async function AdminNewsPage() {
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="mb-2">
|
||||
{announcementAudienceLabels[announcement.audience]}
|
||||
</Badge>
|
||||
<p className="text-xs text-[var(--ink-muted)]">
|
||||
{format(announcement.createdAt, "dd.MM.yyyy HH:mm", {
|
||||
locale: de,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Plus, Pencil, Search, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -29,18 +31,112 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
|
||||
import { createEducator, updateEducator, deleteEducator } from "../actions";
|
||||
import {
|
||||
createEducator,
|
||||
updateEducator,
|
||||
deleteEducator,
|
||||
resendEducatorInvitation,
|
||||
} from "../actions";
|
||||
|
||||
type EducatorDto = {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
active: boolean;
|
||||
hasProfile: boolean;
|
||||
email: string | null;
|
||||
verified: boolean;
|
||||
inviteFailed: boolean;
|
||||
};
|
||||
|
||||
export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
function AccessFields({
|
||||
prefix,
|
||||
today,
|
||||
educator,
|
||||
}: {
|
||||
prefix: string;
|
||||
today: string;
|
||||
educator?: EducatorDto;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${prefix}-email`}>E-Mail-Adresse</Label>
|
||||
<Input
|
||||
id={`${prefix}-email`}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
defaultValue={educator?.email ?? ""}
|
||||
readOnly={!!educator?.email}
|
||||
required
|
||||
maxLength={254}
|
||||
/>
|
||||
<p className="text-xs leading-5 text-[var(--ink-soft)]">
|
||||
{educator?.email
|
||||
? "Diese Adresse gehört zum verknüpften Account."
|
||||
: "An diese Adresse senden wir den persönlichen Aktivierungslink."}
|
||||
</p>
|
||||
</div>
|
||||
{!educator?.hasProfile && (
|
||||
<div className="grid gap-4 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-4 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${prefix}-employmentStart`}>
|
||||
Beschäftigungsbeginn
|
||||
</Label>
|
||||
<Input
|
||||
id={`${prefix}-employmentStart`}
|
||||
name="employmentStart"
|
||||
type="date"
|
||||
required
|
||||
min="2000-01-01"
|
||||
max="2100-12-31"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${prefix}-trackingStart`}>
|
||||
Start der Zeiterfassung
|
||||
</Label>
|
||||
<Input
|
||||
id={`${prefix}-trackingStart`}
|
||||
name="trackingStart"
|
||||
type="date"
|
||||
defaultValue={today}
|
||||
required
|
||||
min="2000-01-01"
|
||||
max="2100-12-31"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs leading-5 text-[var(--ink-soft)] sm:col-span-2">
|
||||
Ab diesem Datum werden Arbeitszeiten im Kita-Planer erfasst.
|
||||
Arbeitstage, Urlaub und vorhandene Überstunden richtest du
|
||||
anschließend im Personalprofil ein.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErzieherList({
|
||||
educators,
|
||||
today,
|
||||
}: {
|
||||
educators: EducatorDto[];
|
||||
today: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [search, setSearch] = useState("");
|
||||
const [formError, setFormError] = useState("");
|
||||
const filtered = educators.filter((ed) =>
|
||||
`${ed.firstName} ${ed.lastName} ${ed.email ?? ""}`
|
||||
.toLocaleLowerCase("de")
|
||||
.includes(search.toLocaleLowerCase("de")),
|
||||
);
|
||||
const [openCreate, setOpenCreate] = useState(false);
|
||||
const [editingEducator, setEditingEducator] = useState<EducatorDto | null>(null);
|
||||
const [editingEducator, setEditingEducator] = useState<EducatorDto | null>(
|
||||
null,
|
||||
);
|
||||
const [educatorToDelete, setEducatorToDelete] = useState<EducatorDto | null>(
|
||||
null,
|
||||
);
|
||||
@@ -51,15 +147,24 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
firstName: formData.get("firstName") as string,
|
||||
lastName: formData.get("lastName") as string,
|
||||
active: formData.get("active") === "on",
|
||||
email: formData.get("email"),
|
||||
employmentStart: formData.get("employmentStart"),
|
||||
trackingStart: formData.get("trackingStart"),
|
||||
};
|
||||
|
||||
setFormError("");
|
||||
startTransition(async () => {
|
||||
const res = await createEducator(data);
|
||||
if (res.error) {
|
||||
toast.error(res.error);
|
||||
setFormError(res.error);
|
||||
} else {
|
||||
toast.success("ErzieherIn angelegt.");
|
||||
toast.success(res.message ?? "Fachkraft und Personalprofil angelegt.");
|
||||
if (res.warning) toast.warning(res.warning, { duration: 12000 });
|
||||
setOpenCreate(false);
|
||||
if (res.educatorId)
|
||||
router.push(
|
||||
`/dashboard/personal?tab=verwaltung&educator=${res.educatorId}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -70,19 +175,35 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
firstName: formData.get("firstName") as string,
|
||||
lastName: formData.get("lastName") as string,
|
||||
active: formData.get("active") === "on",
|
||||
email: formData.get("email"),
|
||||
employmentStart: formData.get("employmentStart"),
|
||||
trackingStart: formData.get("trackingStart"),
|
||||
};
|
||||
|
||||
setFormError("");
|
||||
startTransition(async () => {
|
||||
const res = await updateEducator(editingEducator.id, data);
|
||||
if (res.error) {
|
||||
toast.error(res.error);
|
||||
setFormError(res.error);
|
||||
} else {
|
||||
toast.success("Daten aktualisiert.");
|
||||
toast.success(res.message ?? "Daten aktualisiert.");
|
||||
if (res.warning) toast.warning(res.warning, { duration: 12000 });
|
||||
setEditingEducator(null);
|
||||
router.refresh();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleResend = (educator: EducatorDto) => {
|
||||
startTransition(async () => {
|
||||
const res = await resendEducatorInvitation(educator.id);
|
||||
if (res.error) toast.error(res.error);
|
||||
else if (res.warning) toast.warning(res.warning, { duration: 12000 });
|
||||
else toast.success(res.message ?? "Einladung erneuert.");
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = (educator: EducatorDto) => {
|
||||
startTransition(async () => {
|
||||
const res = await deleteEducator(educator.id);
|
||||
@@ -100,24 +221,44 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="relative min-w-72 max-[760px]:w-full max-[760px]:min-w-0">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--ink-muted)] [stroke-width:1.7]" />
|
||||
<Input placeholder="Name suchen" className="pl-9" />
|
||||
<Input
|
||||
placeholder="Name oder E-Mail suchen"
|
||||
aria-label="Team durchsuchen"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Dialog open={openCreate} onOpenChange={setOpenCreate}>
|
||||
<Dialog
|
||||
open={openCreate}
|
||||
onOpenChange={(open) => {
|
||||
if (!isPending) {
|
||||
setOpenCreate(open);
|
||||
setFormError("");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="gap-2">
|
||||
<Plus className="h-4 w-4 [stroke-width:1.7]" />
|
||||
ErzieherIn anlegen
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<form action={handleCreate}>
|
||||
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
handleCreate(new FormData(event.currentTarget));
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Neue(n) ErzieherIn anlegen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Erfasse die Stammdaten des Kita-Personals.
|
||||
Lege Stammdaten, Personalprofil und App-Zugang gemeinsam an.
|
||||
Die Fachkraft erhält ihren Aktivierungslink per E-Mail.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<fieldset disabled={isPending} className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="firstName">Vorname</Label>
|
||||
<Input id="firstName" name="firstName" required />
|
||||
@@ -126,14 +267,31 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
<Label htmlFor="lastName">Nachname</Label>
|
||||
<Input id="lastName" name="lastName" required />
|
||||
</div>
|
||||
<AccessFields prefix="create" today={today} />
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Switch id="active" name="active" defaultChecked />
|
||||
<Label htmlFor="active">Aktiv (Arbeitet aktuell hier)</Label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
{formError && (
|
||||
<p role="alert" className="mb-4 text-sm text-[var(--danger)]">
|
||||
{formError}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="ghost" onClick={() => setOpenCreate(false)}>Abbrechen</Button>
|
||||
<Button type="submit" disabled={isPending}>Speichern</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
disabled={isPending}
|
||||
onClick={() => setOpenCreate(false)}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending
|
||||
? "Wird angelegt …"
|
||||
: "Fachkraft anlegen und einladen"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
@@ -158,14 +316,15 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
<TableRow>
|
||||
<TableHead className="pl-6">Vorname</TableHead>
|
||||
<TableHead>Nachname</TableHead>
|
||||
<TableHead>E-Mail / App-Zugang</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="pr-6 text-right">Aktionen</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{educators.length === 0 ? (
|
||||
{filtered.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="h-32 text-center">
|
||||
<TableCell colSpan={5} className="h-32 text-center">
|
||||
<div className="flex max-h-[240px] min-h-[200px] flex-col items-center justify-center">
|
||||
<div className="mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--accent-soft)] text-[var(--accent-deep)]">
|
||||
<Plus className="h-6 w-6 [stroke-width:1.7]" />
|
||||
@@ -180,17 +339,66 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
educators.map((ed) => (
|
||||
filtered.map((ed) => (
|
||||
<TableRow key={ed.id}>
|
||||
<TableCell className="pl-6 font-medium">{ed.firstName}</TableCell>
|
||||
<TableCell className="pl-6 font-medium">
|
||||
{ed.firstName}
|
||||
</TableCell>
|
||||
<TableCell>{ed.lastName}</TableCell>
|
||||
<TableCell>
|
||||
<p className="mb-1 text-sm">
|
||||
{ed.email ?? "Noch keine E-Mail hinterlegt"}
|
||||
</p>
|
||||
<Badge variant={ed.verified ? "success" : "secondary"}>
|
||||
{ed.verified
|
||||
? "Account aktiviert"
|
||||
: ed.inviteFailed
|
||||
? "Mailversand fehlgeschlagen"
|
||||
: ed.email
|
||||
? "Einladung ausstehend"
|
||||
: "Zugang fehlt"}
|
||||
</Badge>
|
||||
{ed.email && !ed.verified && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={isPending}
|
||||
onClick={() => handleResend(ed)}
|
||||
aria-label={`Einladung für ${ed.firstName} ${ed.lastName} erneut senden`}
|
||||
className="mt-1 block"
|
||||
>
|
||||
Einladung erneut senden
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={ed.active ? "success" : "secondary"}>
|
||||
{ed.active ? "Aktiv" : "Inaktiv"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="pr-6 text-right">
|
||||
<Button variant="ghost" size="icon" onClick={() => setEditingEducator(ed)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
asChild
|
||||
className="mr-2"
|
||||
>
|
||||
<Link
|
||||
href={`/dashboard/personal?tab=verwaltung&educator=${ed.id}`}
|
||||
>
|
||||
Personalprofil
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setFormError("");
|
||||
setEditingEducator(ed);
|
||||
}}
|
||||
disabled={isPending}
|
||||
aria-label={`${ed.firstName} ${ed.lastName} bearbeiten`}
|
||||
>
|
||||
<Pencil className="h-4 w-4 [stroke-width:1.7]" />
|
||||
</Button>
|
||||
<Button
|
||||
@@ -213,31 +421,78 @@ export function ErzieherList({ educators }: { educators: EducatorDto[] }) {
|
||||
</Card>
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<Dialog open={!!editingEducator} onOpenChange={(open) => !open && setEditingEducator(null)}>
|
||||
<DialogContent>
|
||||
<form action={handleUpdate}>
|
||||
<Dialog
|
||||
open={!!editingEducator}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !isPending) setEditingEducator(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
handleUpdate(new FormData(event.currentTarget));
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>ErzieherIn bearbeiten</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editingEducator && (
|
||||
<div className="grid gap-4 py-4">
|
||||
<fieldset disabled={isPending} className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="edit-firstName">Vorname</Label>
|
||||
<Input id="edit-firstName" name="firstName" defaultValue={editingEducator.firstName} required />
|
||||
<Input
|
||||
id="edit-firstName"
|
||||
name="firstName"
|
||||
defaultValue={editingEducator.firstName}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="edit-lastName">Nachname</Label>
|
||||
<Input id="edit-lastName" name="lastName" defaultValue={editingEducator.lastName} required />
|
||||
<Input
|
||||
id="edit-lastName"
|
||||
name="lastName"
|
||||
defaultValue={editingEducator.lastName}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<AccessFields
|
||||
prefix="edit"
|
||||
today={today}
|
||||
educator={editingEducator}
|
||||
/>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Switch id="edit-active" name="active" defaultChecked={editingEducator.active} />
|
||||
<Switch
|
||||
id="edit-active"
|
||||
name="active"
|
||||
defaultChecked={editingEducator.active}
|
||||
/>
|
||||
<Label htmlFor="edit-active">Aktiv</Label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{formError && (
|
||||
<p role="alert" className="mb-4 text-sm text-[var(--danger)]">
|
||||
{formError}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="ghost" onClick={() => setEditingEducator(null)}>Abbrechen</Button>
|
||||
<Button type="submit" disabled={isPending}>Aktualisieren</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
disabled={isPending}
|
||||
onClick={() => setEditingEducator(null)}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending
|
||||
? "Wird gespeichert …"
|
||||
: editingEducator?.email
|
||||
? "Aktualisieren"
|
||||
: "Speichern und einladen"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
|
||||
@@ -6,74 +6,23 @@ import { z } from "zod";
|
||||
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { staffAction } from "../personal/actions";
|
||||
|
||||
const educatorSchema = z.object({
|
||||
firstName: z.string().min(1, "Vorname ist erforderlich").max(100).trim(),
|
||||
lastName: z.string().min(1, "Nachname ist erforderlich").max(100).trim(),
|
||||
active: z.boolean().default(true),
|
||||
});
|
||||
|
||||
// The staff service creates the person, profile, account and mail job in one transaction.
|
||||
export async function createEducator(rawPayload: unknown) {
|
||||
const session = await requireRole([UserRole.ADMIN]);
|
||||
const kitaId = session.user.kitaId;
|
||||
if (!kitaId) {
|
||||
return { error: "Kein Mandant zugeordnet." };
|
||||
}
|
||||
|
||||
const parsed = educatorSchema.safeParse(rawPayload);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.educator.create({
|
||||
data: {
|
||||
kitaId,
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
active: parsed.data.active,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/erzieher");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Anlegen:", error);
|
||||
return { error: "Ein Fehler ist aufgetreten." };
|
||||
}
|
||||
const parsed = z.record(z.string(), z.unknown()).safeParse(rawPayload);
|
||||
if (!parsed.success) return { error: "Ungültige Eingabedaten." };
|
||||
return staffAction("educatorCreate", parsed.data);
|
||||
}
|
||||
|
||||
export async function updateEducator(id: string, rawPayload: unknown) {
|
||||
const session = await requireRole([UserRole.ADMIN]);
|
||||
const kitaId = session.user.kitaId;
|
||||
if (!kitaId) {
|
||||
return { error: "Kein Mandant zugeordnet." };
|
||||
const parsed = z.record(z.string(), z.unknown()).safeParse(rawPayload);
|
||||
if (!parsed.success) return { error: "Ungültige Eingabedaten." };
|
||||
return staffAction("educatorUpdate", { ...parsed.data, educatorId: id });
|
||||
}
|
||||
|
||||
const parsed = educatorSchema.safeParse(rawPayload);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.educator.update({
|
||||
where: {
|
||||
id,
|
||||
kitaId,
|
||||
},
|
||||
data: {
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
active: parsed.data.active,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/erzieher");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Aktualisieren:", error);
|
||||
return { error: "Ein Fehler ist aufgetreten." };
|
||||
}
|
||||
export async function resendEducatorInvitation(educatorId: string) {
|
||||
return staffAction("educatorInvite", { educatorId });
|
||||
}
|
||||
|
||||
export async function deleteEducator(id: string) {
|
||||
@@ -84,6 +33,14 @@ export async function deleteEducator(id: string) {
|
||||
}
|
||||
|
||||
try {
|
||||
const profile = await prisma.staffProfile.findFirst({
|
||||
where: { educatorId: id, kitaId },
|
||||
});
|
||||
if (profile)
|
||||
return {
|
||||
error:
|
||||
"Diese Fachkraft hat ein Personalprofil. Bitte auf inaktiv setzen, damit Zeiten und Konten erhalten bleiben.",
|
||||
};
|
||||
await prisma.educator.delete({
|
||||
where: {
|
||||
id,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { UserRole } from "@prisma/client";
|
||||
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { todayKey } from "@/lib/staff/calculations";
|
||||
import { ErzieherList } from "./_components/erzieher-list";
|
||||
|
||||
export const metadata = { title: "ErzieherInnen · Kita-Planer" };
|
||||
@@ -17,6 +18,18 @@ export default async function ErzieherPage() {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
active: true,
|
||||
staffProfile: {
|
||||
select: {
|
||||
id: true,
|
||||
user: { select: { email: true, emailVerifiedAt: true } },
|
||||
emails: {
|
||||
where: { inviteToken: { not: null }, skippedAt: null },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1,
|
||||
select: { failed: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [{ lastName: "asc" }, { firstName: "asc" }],
|
||||
});
|
||||
@@ -36,8 +49,8 @@ export default async function ErzieherPage() {
|
||||
</em>
|
||||
</h1>
|
||||
<p className="mt-2 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
Stammdaten des Kita-Personals für interne Planung und spätere
|
||||
Notdienst-Alarmierung.
|
||||
Stammdaten des Teams und Zugang zu Beschäftigungsprofilen,
|
||||
Urlaubsansprüchen und Arbeitszeitmodellen.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap gap-2">
|
||||
@@ -51,7 +64,16 @@ export default async function ErzieherPage() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<ErzieherList educators={educators} />
|
||||
<ErzieherList
|
||||
today={todayKey()}
|
||||
educators={educators.map(({ staffProfile, ...educator }) => ({
|
||||
...educator,
|
||||
hasProfile: !!staffProfile,
|
||||
email: staffProfile?.user?.email ?? null,
|
||||
verified: !!staffProfile?.user?.emailVerifiedAt,
|
||||
inviteFailed: !!staffProfile?.emails[0]?.failed,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useTransition } from "react";
|
||||
import { LayoutGrid, Mail, Search, Table, Users } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { resendParentInvite } from "../actions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -245,6 +247,7 @@ export function FamiliesListClient({
|
||||
<Mail className="h-3 w-3 shrink-0 [stroke-width:1.7]" />
|
||||
<span className="break-words [overflow-wrap:anywhere]">
|
||||
{parent.email}
|
||||
{!parent.emailVerifiedAt && <ResendInviteButton userId={parent.id} />}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -351,6 +354,7 @@ export function FamiliesListClient({
|
||||
<Mail className="h-3.5 w-3.5 shrink-0 [stroke-width:1.7]" />
|
||||
<span className="break-words [overflow-wrap:anywhere]">
|
||||
{parent.email}
|
||||
{!parent.emailVerifiedAt && <ResendInviteButton userId={parent.id} />}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -416,3 +420,11 @@ export function FamiliesListClient({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResendInviteButton({ userId }: { userId: string }) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
return <Button type="button" size="sm" variant="ghost" disabled={pending} onClick={() => startTransition(async () => {
|
||||
const result = await resendParentInvite(userId);
|
||||
if (result.error) toast.error(result.error); else toast.success("Einladung erneut gesendet.");
|
||||
})}>{pending ? "Wird gesendet…" : "Einladung erneut senden"}</Button>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use server";
|
||||
|
||||
import crypto from "crypto";
|
||||
import { hashToken, newToken } from "@/lib/tokens";
|
||||
import { createElement } from "react";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { Prisma, UserRole } from "@prisma/client";
|
||||
@@ -9,6 +9,7 @@ import { z } from "zod";
|
||||
import { InviteEmail } from "@/emails/InviteEmail";
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const INVITE_TOKEN_TTL_DAYS = 7;
|
||||
@@ -115,7 +116,7 @@ function optionalParentFromForm(data: z.infer<typeof addFamilySchema>) {
|
||||
}
|
||||
|
||||
function createInviteToken() {
|
||||
const token = crypto.randomUUID();
|
||||
const token = newToken();
|
||||
const expires = new Date(
|
||||
Date.now() + INVITE_TOKEN_TTL_DAYS * 24 * 60 * 60_000,
|
||||
);
|
||||
@@ -153,6 +154,8 @@ export async function addFamilyAction(
|
||||
return { errors: { _form: ["Kein Mandant zugeordnet."] } };
|
||||
}
|
||||
|
||||
if (!(await rateLimit(`family-invites:${kitaId}`, 30, 3600)).allowed) return { errors: { _form: ["Zu viele Einladungen. Bitte versuche es später erneut."] } };
|
||||
|
||||
const parsedFamily = addFamilySchema.safeParse(Object.fromEntries(formData));
|
||||
if (!parsedFamily.success) {
|
||||
return { errors: parsedFamily.error.flatten().fieldErrors };
|
||||
@@ -245,7 +248,7 @@ export async function addFamilyAction(
|
||||
await tx.verificationToken.create({
|
||||
data: {
|
||||
identifier: createdParent.id,
|
||||
token: invite.token,
|
||||
token: hashToken(invite.token),
|
||||
expires: invite.expires,
|
||||
},
|
||||
});
|
||||
@@ -320,6 +323,7 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
|
||||
const removedChildIdSet = new Set(removedChildIds);
|
||||
const activeChildren = children.filter((child) => !removedChildIdSet.has(child.id));
|
||||
if (activeChildren.length + newChildren.length > 20) return { error: "Maximal 20 Kinder pro Familie." };
|
||||
if (activeChildren.length + newChildren.length === 0) {
|
||||
return { error: "Eine Familie benötigt mindestens ein Kind." };
|
||||
}
|
||||
@@ -347,7 +351,7 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
where: { id: familyId, kitaId },
|
||||
select: {
|
||||
id: true,
|
||||
users: { select: { id: true } },
|
||||
users: { select: { id: true, email: true } },
|
||||
children: { select: { id: true } },
|
||||
},
|
||||
});
|
||||
@@ -356,6 +360,13 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
return { error: "Familie wurde nicht gefunden." };
|
||||
}
|
||||
|
||||
const needsEmail = newParents.length > 0 || parents.some(parent => existingFamily.users.find(user => user.id === parent.id)?.email !== parent.email);
|
||||
if (needsEmail) {
|
||||
const configError = getAppEmailConfigError();
|
||||
if (configError) return { error: configError };
|
||||
if (!(await rateLimit(`family-invites:${kitaId}`, 30, 3600)).allowed) return { error: "Zu viele Einladungen. Bitte versuche es später erneut." };
|
||||
}
|
||||
|
||||
const existingParentIds = new Set(existingFamily.users.map((user) => user.id));
|
||||
const existingChildIds = new Set(existingFamily.children.map((child) => child.id));
|
||||
|
||||
@@ -382,14 +393,20 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
});
|
||||
|
||||
for (const parent of parents) {
|
||||
const current = await tx.user.findFirst({ where: { id: parent.id, kitaId, familyId }, select: { email: true } });
|
||||
if (!current) throw new Error("Parent assignment changed");
|
||||
const emailChanged = current.email !== parent.email;
|
||||
await tx.user.update({
|
||||
where: { id: parent.id },
|
||||
data: {
|
||||
firstName: parent.firstName,
|
||||
lastName: parent.lastName,
|
||||
email: parent.email,
|
||||
},
|
||||
where: { id: parent.id, kitaId, familyId },
|
||||
data: { firstName: parent.firstName, lastName: parent.lastName, email: parent.email,
|
||||
...(emailChanged ? { passwordHash: "", emailVerifiedAt: null, sessionVersion: { increment: 1 } } : {}) },
|
||||
});
|
||||
if (emailChanged) {
|
||||
const invite = createInviteToken();
|
||||
await tx.verificationToken.deleteMany({ where: { identifier: parent.id } });
|
||||
await tx.verificationToken.create({ data: { identifier: parent.id, token: hashToken(invite.token), expires: invite.expires } });
|
||||
inviteJobs.push({ to: parent.email, parentName: `${parent.firstName} ${parent.lastName}`, inviteUrl: invite.inviteUrl });
|
||||
}
|
||||
}
|
||||
|
||||
for (const parent of newParents) {
|
||||
@@ -413,7 +430,7 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
await tx.verificationToken.create({
|
||||
data: {
|
||||
identifier: createdParent.id,
|
||||
token: invite.token,
|
||||
token: hashToken(invite.token),
|
||||
expires: invite.expires,
|
||||
},
|
||||
});
|
||||
@@ -421,7 +438,7 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
|
||||
for (const child of activeChildren) {
|
||||
await tx.child.update({
|
||||
where: { id: child.id },
|
||||
where: { id: child.id, kitaId, familyId },
|
||||
data: {
|
||||
firstName: child.firstName,
|
||||
lastName: child.lastName,
|
||||
@@ -430,7 +447,7 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
}
|
||||
|
||||
for (const childId of removedChildIds) {
|
||||
await tx.child.delete({ where: { id: childId } });
|
||||
await tx.child.delete({ where: { id: childId, kitaId, familyId } });
|
||||
}
|
||||
|
||||
for (const child of newChildren) {
|
||||
@@ -469,3 +486,28 @@ export async function updateFamilyAction(rawPayload: unknown) {
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function resendParentInvite(userId: string) {
|
||||
const session = await requireRole([UserRole.ADMIN]);
|
||||
if (typeof userId !== "string" || !userId || userId.length > 64) return { error: "Ungültige Eingabedaten." };
|
||||
if (!(await rateLimit(`family-invites:${session.user.kitaId}`, 30, 3600)).allowed) return { error: "Bitte versuche es später erneut." };
|
||||
if (!(await rateLimit(`resend-invite:${session.user.kitaId}:${userId}`, 3, 3600)).allowed) return { error: "Bitte versuche es später erneut." };
|
||||
const user = await prisma.user.findFirst({ where: { id: userId, kitaId: session.user.kitaId, emailVerifiedAt: null, passwordHash: "", disabledAt: null },
|
||||
select: { id: true, email: true, firstName: true, lastName: true, kita: { select: { name: true } } } });
|
||||
if (!user?.kita) return { error: "Keine offene Einladung gefunden." };
|
||||
const configError = getAppEmailConfigError(); if (configError) return { error: configError };
|
||||
const invite = createInviteToken();
|
||||
const renewed = await prisma.$transaction(async tx => {
|
||||
// Lock and re-check the account before issuing a link for the selected mailbox.
|
||||
// A concurrent address change/activation must invalidate this resend.
|
||||
const eligible = await tx.user.updateMany({ where: { id: user.id, email: user.email, kitaId: session.user.kitaId,
|
||||
emailVerifiedAt: null, passwordHash: "", disabledAt: null }, data: { sessionVersion: { increment: 1 } } });
|
||||
if (eligible.count !== 1) return false;
|
||||
await tx.verificationToken.deleteMany({ where: { identifier: user.id } });
|
||||
await tx.verificationToken.create({ data: { identifier: user.id, token: hashToken(invite.token), expires: invite.expires } });
|
||||
return true;
|
||||
});
|
||||
if (!renewed) return { error: "Die Einladung hat sich geändert. Bitte lade die Seite neu." };
|
||||
const error = await sendInviteJobs(user.kita.name, [{ to: user.email, parentName: `${user.firstName} ${user.lastName}`, inviteUrl: invite.inviteUrl }]);
|
||||
return error ? { error } : { success: true };
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
const dutySchema = z.object({
|
||||
name: z.string().min(2, "Name muss mindestens 2 Zeichen lang sein").max(50),
|
||||
description: z.string().optional(),
|
||||
description: z.string().trim().max(2000).optional(),
|
||||
});
|
||||
|
||||
export async function createDuty(rawPayload: unknown) {
|
||||
|
||||
@@ -154,7 +154,7 @@ export function EditFamilyDialog({ family }: { family: EditableFamily }) {
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Familie aktualisiert.");
|
||||
toast.success("Familie aktualisiert. Geänderte E-Mail-Adressen müssen über einen neuen Einladungslink bestätigt werden.");
|
||||
setRemovedChildIds([]);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import type { ComponentProps, FormEvent } from "react";
|
||||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||
import { TerminType } from "@prisma/client";
|
||||
import { RsvpMode, TerminType } from "@prisma/client";
|
||||
import { Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { suggestedRsvpMode } from "@/lib/rsvp";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -28,6 +29,11 @@ type AdminTerminFormState = {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
allDay: boolean;
|
||||
requiresRsvp: boolean;
|
||||
rsvpMode: RsvpMode;
|
||||
rsvpDeadline: string;
|
||||
participantInfo: string;
|
||||
mitbringselListEnabled: boolean;
|
||||
};
|
||||
|
||||
const initialFormState: AdminTerminFormState = {
|
||||
@@ -37,6 +43,11 @@ const initialFormState: AdminTerminFormState = {
|
||||
startDate: "",
|
||||
endDate: "",
|
||||
allDay: false,
|
||||
requiresRsvp: false,
|
||||
rsvpMode: RsvpMode.FAMILY,
|
||||
rsvpDeadline: "",
|
||||
participantInfo: "",
|
||||
mitbringselListEnabled: false,
|
||||
};
|
||||
|
||||
type AdminTerminModalProps = {
|
||||
@@ -51,6 +62,12 @@ type AdminTerminModalProps = {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
allDay: boolean;
|
||||
requiresRsvp: boolean;
|
||||
rsvpMode: RsvpMode;
|
||||
rsvpDeadline: Date | null;
|
||||
participantInfo: string | null;
|
||||
mitbringselListEnabled: boolean;
|
||||
hasRsvpResponses: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -61,10 +78,12 @@ export function AdminTerminModal({
|
||||
existingTermin,
|
||||
}: AdminTerminModalProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [formState, setFormState] = useState<AdminTerminFormState>(initialFormState);
|
||||
const [formState, setFormState] =
|
||||
useState<AdminTerminFormState>(initialFormState);
|
||||
const [modeTouched, setModeTouched] = useState(false);
|
||||
const modeLocked = existingTermin?.hasRsvpResponses ?? false;
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const minDateTime = useMemo(() => getLocalDateTimeInputValue(new Date()), []);
|
||||
const minEndDateTime = formState.startDate || minDateTime;
|
||||
|
||||
// Initialize and reset form fields when modal opens
|
||||
useEffect(() => {
|
||||
@@ -78,10 +97,18 @@ export function AdminTerminModal({
|
||||
startDate: getLocalDateTimeInputValue(existingTermin.startDate),
|
||||
endDate: getLocalDateTimeInputValue(existingTermin.endDate),
|
||||
allDay: existingTermin.allDay,
|
||||
requiresRsvp: existingTermin.requiresRsvp,
|
||||
rsvpMode: existingTermin.rsvpMode,
|
||||
rsvpDeadline: existingTermin.rsvpDeadline
|
||||
? getLocalDateTimeInputValue(existingTermin.rsvpDeadline)
|
||||
: "",
|
||||
participantInfo: existingTermin.participantInfo ?? "",
|
||||
mitbringselListEnabled: existingTermin.mitbringselListEnabled,
|
||||
});
|
||||
} else {
|
||||
setFormState(initialFormState);
|
||||
}
|
||||
setModeTouched(false);
|
||||
}
|
||||
}, [open, existingTermin]);
|
||||
|
||||
@@ -91,7 +118,14 @@ export function AdminTerminModal({
|
||||
) => {
|
||||
setFormState((current) => {
|
||||
const next = { ...current, [key]: value };
|
||||
if (key === "startDate" && typeof value === "string" && next.endDate && next.endDate < value) {
|
||||
if (key === "type" && !existingTermin && !modeTouched && !modeLocked)
|
||||
next.rsvpMode = suggestedRsvpMode(value as TerminType);
|
||||
if (
|
||||
key === "startDate" &&
|
||||
typeof value === "string" &&
|
||||
next.endDate &&
|
||||
next.endDate < value
|
||||
) {
|
||||
next.endDate = value;
|
||||
}
|
||||
return next;
|
||||
@@ -122,6 +156,13 @@ export function AdminTerminModal({
|
||||
startDate: new Date(formState.startDate).toISOString(),
|
||||
endDate: new Date(formState.endDate).toISOString(),
|
||||
allDay: formState.allDay,
|
||||
requiresRsvp: formState.requiresRsvp,
|
||||
rsvpMode: formState.rsvpMode,
|
||||
rsvpDeadline: formState.rsvpDeadline
|
||||
? new Date(formState.rsvpDeadline).toISOString()
|
||||
: null,
|
||||
participantInfo: formState.participantInfo,
|
||||
mitbringselListEnabled: formState.mitbringselListEnabled,
|
||||
};
|
||||
|
||||
startTransition(async () => {
|
||||
@@ -138,7 +179,7 @@ export function AdminTerminModal({
|
||||
toast.success(
|
||||
existingTermin
|
||||
? "Termin wurde erfolgreich aktualisiert!"
|
||||
: "Termin wurde direkt angelegt!"
|
||||
: "Termin wurde direkt angelegt!",
|
||||
);
|
||||
if (!existingTermin) {
|
||||
setFormState(initialFormState);
|
||||
@@ -156,11 +197,13 @@ export function AdminTerminModal({
|
||||
{triggerLabel}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogContent className="max-h-[85vh] overflow-y-auto">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{existingTermin ? "Termin bearbeiten (Admin)" : "Termin anlegen (Admin)"}
|
||||
{existingTermin
|
||||
? "Termin bearbeiten (Admin)"
|
||||
: "Termin anlegen (Admin)"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{existingTermin
|
||||
@@ -189,7 +232,9 @@ export function AdminTerminModal({
|
||||
name="description"
|
||||
placeholder="Details zum Termin..."
|
||||
value={formState.description}
|
||||
onChange={(event) => updateField("description", event.target.value)}
|
||||
onChange={(event) =>
|
||||
updateField("description", event.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -200,18 +245,28 @@ export function AdminTerminModal({
|
||||
name="type"
|
||||
value={formState.type}
|
||||
className="flex h-10 w-full rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-[13.5px] text-[var(--ink)] ring-offset-[var(--surface)] transition-colors hover:border-[var(--accent-mid)] focus-visible:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--focus-ring)]"
|
||||
onChange={(event) => updateField("type", event.target.value as TerminType)}
|
||||
onChange={(event) =>
|
||||
updateField("type", event.target.value as TerminType)
|
||||
}
|
||||
required
|
||||
>
|
||||
<option value={TerminType.KITA_FEST}>Kita-Fest</option>
|
||||
<option value={TerminType.SCHLIESSTAG}>Schließtag</option>
|
||||
<option value={TerminType.TEAMTAG}>Teamtag (Kita geschlossen)</option>
|
||||
<option value={TerminType.TEAMTAG}>
|
||||
Teamtag (Kita geschlossen)
|
||||
</option>
|
||||
<option value={TerminType.MITMACH_TAG}>Mitmach-Tag</option>
|
||||
<option value={TerminType.ELTERNABEND}>Elternabend</option>
|
||||
<option value={TerminType.MITGLIEDERVERSAMMLUNG}>Mitgliederversammlung</option>
|
||||
<option value={TerminType.MITGLIEDERVERSAMMLUNG}>
|
||||
Mitgliederversammlung
|
||||
</option>
|
||||
<option value={TerminType.ELTERNCAFE}>Elterncafe</option>
|
||||
<option value={TerminType.GEBURTSTAG_INTERN}>Geburtstag (Intern)</option>
|
||||
<option value={TerminType.GEBURTSTAG_EXTERN}>Raumanfrage (Extern)</option>
|
||||
<option value={TerminType.GEBURTSTAG_INTERN}>
|
||||
Geburtstag (Intern)
|
||||
</option>
|
||||
<option value={TerminType.GEBURTSTAG_EXTERN}>
|
||||
Raumanfrage (Extern)
|
||||
</option>
|
||||
<option value={TerminType.SONSTIGES}>Sonstiges</option>
|
||||
</select>
|
||||
</div>
|
||||
@@ -225,7 +280,9 @@ export function AdminTerminModal({
|
||||
type="datetime-local"
|
||||
min={existingTermin ? undefined : minDateTime}
|
||||
value={formState.startDate}
|
||||
onChange={(event) => updateField("startDate", event.target.value)}
|
||||
onChange={(event) =>
|
||||
updateField("startDate", event.target.value)
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
@@ -235,14 +292,82 @@ export function AdminTerminModal({
|
||||
id="endDate"
|
||||
name="endDate"
|
||||
type="datetime-local"
|
||||
min={formState.startDate || (existingTermin ? undefined : minDateTime)}
|
||||
min={
|
||||
formState.startDate ||
|
||||
(existingTermin ? undefined : minDateTime)
|
||||
}
|
||||
value={formState.endDate}
|
||||
onChange={(event) => updateField("endDate", event.target.value)}
|
||||
onChange={(event) =>
|
||||
updateField("endDate", event.target.value)
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formState.mitbringselListEnabled}
|
||||
onChange={(e) =>
|
||||
updateField("mitbringselListEnabled", e.target.checked)
|
||||
}
|
||||
/>
|
||||
Mitbring-Liste aktiv
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formState.requiresRsvp}
|
||||
onChange={(e) => updateField("requiresRsvp", e.target.checked)}
|
||||
/>
|
||||
Teilnahme-Abfrage aktivieren
|
||||
</label>
|
||||
{formState.requiresRsvp ? (
|
||||
<div className="grid gap-3 rounded-lg border border-[var(--warn)] bg-[var(--warn-soft)] p-4">
|
||||
<Label htmlFor="calendar-rsvp-mode">Antwortart</Label>
|
||||
<select
|
||||
id="calendar-rsvp-mode"
|
||||
value={formState.rsvpMode}
|
||||
disabled={modeLocked}
|
||||
onChange={(e) => {
|
||||
updateField("rsvpMode", e.target.value as RsvpMode);
|
||||
setModeTouched(true);
|
||||
}}
|
||||
className="h-10 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 text-sm"
|
||||
>
|
||||
<option value="FAMILY">
|
||||
Pro Familie · mit Anzahl Erwachsener
|
||||
</option>
|
||||
<option value="CHILD">Pro Kind · einzelne Zu-/Absage</option>
|
||||
</select>
|
||||
{modeLocked ? (
|
||||
<p className="text-xs">
|
||||
Die Antwortart ist wegen vorhandener Rückmeldungen gesperrt.
|
||||
</p>
|
||||
) : null}
|
||||
<Label htmlFor="calendar-rsvp-deadline">
|
||||
Rückmeldefrist (sonst Terminbeginn)
|
||||
</Label>
|
||||
<Input
|
||||
id="calendar-rsvp-deadline"
|
||||
type="datetime-local"
|
||||
value={formState.rsvpDeadline}
|
||||
onChange={(e) => updateField("rsvpDeadline", e.target.value)}
|
||||
/>
|
||||
<Label htmlFor="calendar-participant-info">
|
||||
Hinweise für Teilnehmer
|
||||
</Label>
|
||||
<Textarea
|
||||
id="calendar-participant-info"
|
||||
value={formState.participantInfo}
|
||||
onChange={(e) =>
|
||||
updateField("participantInfo", e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -250,7 +375,9 @@ export function AdminTerminModal({
|
||||
name="allDay"
|
||||
checked={formState.allDay}
|
||||
className="rounded border-[var(--hairline)] accent-[var(--accent-deep)]"
|
||||
onChange={(event) => updateField("allDay", event.target.checked)}
|
||||
onChange={(event) =>
|
||||
updateField("allDay", event.target.checked)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="allDay" className="font-normal cursor-pointer">
|
||||
Ganztägiger Termin
|
||||
@@ -259,11 +386,19 @@ export function AdminTerminModal({
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="ghost" onClick={() => setOpen(false)}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? "Speichern..." : existingTermin ? "Änderungen speichern" : "Termin erstellen"}
|
||||
{isPending
|
||||
? "Speichern..."
|
||||
: existingTermin
|
||||
? "Änderungen speichern"
|
||||
: "Termin erstellen"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
@@ -4,8 +4,6 @@ import { useState, useMemo, useTransition } from "react";
|
||||
import {
|
||||
TerminType,
|
||||
TerminStatus,
|
||||
EventParticipationStatus,
|
||||
DutyAssignmentStatus,
|
||||
} from "@prisma/client";
|
||||
import {
|
||||
format,
|
||||
@@ -30,10 +28,9 @@ import {
|
||||
MapPin,
|
||||
AlertTriangle,
|
||||
WashingMachine,
|
||||
MoreHorizontal,
|
||||
Trash2,
|
||||
Edit,
|
||||
} from "lucide-react";
|
||||
import { RsvpDialog, RsvpForm } from "@/components/rsvp-form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
@@ -49,11 +46,20 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { CalendarListItemDto } from "./termin-list";
|
||||
import { TerminList } from "./termin-list";
|
||||
import {
|
||||
CalendarListItemDto,
|
||||
NotdienstSwapDialog,
|
||||
NotdienstSwapOptionDto,
|
||||
TerminList,
|
||||
} from "./termin-list";
|
||||
import { MitbringselList } from "./mitbringsel-list";
|
||||
import { AdminTerminModal } from "./admin-termin-modal";
|
||||
import { deleteTerminAdmin } from "../actions";
|
||||
import {
|
||||
acceptNotdienstSwapRequest,
|
||||
cancelNotdienstSwapRequest,
|
||||
declineNotdienstSwapRequest,
|
||||
deleteTerminAdmin,
|
||||
} from "../actions";
|
||||
|
||||
const categories = [
|
||||
{ label: "Schließtag", type: TerminType.SCHLIESSTAG, color: "var(--danger)" },
|
||||
@@ -68,14 +74,30 @@ const categories = [
|
||||
{ label: "Sonstiges", type: TerminType.SONSTIGES, color: "var(--ink-muted)" },
|
||||
];
|
||||
|
||||
export type NotdienstSwapRequestDto = {
|
||||
id: string;
|
||||
direction: "incoming" | "outgoing";
|
||||
targetDate: Date;
|
||||
targetFamilyName: string;
|
||||
targetChildName: string;
|
||||
offeredDate: Date;
|
||||
offeredFamilyName: string;
|
||||
offeredChildName: string;
|
||||
message: string | null;
|
||||
};
|
||||
|
||||
export function CalendarOverviewClient({
|
||||
termine,
|
||||
userId,
|
||||
isAdmin,
|
||||
notdienstSwapOptions = [],
|
||||
pendingSwapRequests = [],
|
||||
}: {
|
||||
termine: CalendarListItemDto[];
|
||||
userId: string;
|
||||
isAdmin: boolean;
|
||||
notdienstSwapOptions?: NotdienstSwapOptionDto[];
|
||||
pendingSwapRequests?: NotdienstSwapRequestDto[];
|
||||
}) {
|
||||
const [view, setView] = useState<"liste" | "monat" | "agenda">("monat");
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
@@ -185,6 +207,10 @@ export function CalendarOverviewClient({
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{!isAdmin && pendingSwapRequests.length > 0 && (
|
||||
<NotdienstSwapRequestsPanel requests={pendingSwapRequests} />
|
||||
)}
|
||||
|
||||
{/* Search and Filters Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center flex-wrap gap-3">
|
||||
@@ -282,7 +308,12 @@ export function CalendarOverviewClient({
|
||||
|
||||
{/* Main View Contents */}
|
||||
{view === "liste" && (
|
||||
<TerminList termine={filteredEvents} userId={userId} isAdmin={isAdmin} />
|
||||
<TerminList
|
||||
termine={filteredEvents}
|
||||
userId={userId}
|
||||
isAdmin={isAdmin}
|
||||
notdienstSwapOptions={notdienstSwapOptions}
|
||||
/>
|
||||
)}
|
||||
|
||||
{view === "monat" && (
|
||||
@@ -431,13 +462,26 @@ export function CalendarOverviewClient({
|
||||
</p>
|
||||
{isAdmin && (
|
||||
<div className="mt-3 flex gap-2">
|
||||
<a href="/dashboard/notdienst/plan">
|
||||
<a href={`/dashboard/notdienst/plan?year=${item.planYear}&month=${item.planMonth}`}>
|
||||
<Button size="sm" variant="outline" className="h-7 text-xs px-2.5">
|
||||
Im Planer bearbeiten
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{!isAdmin && item.canRequestSwap && (
|
||||
<div className="mt-3 flex gap-2">
|
||||
<NotdienstSwapDialog
|
||||
target={item}
|
||||
options={notdienstSwapOptions}
|
||||
trigger={
|
||||
<Button size="sm" variant="outline" className="h-7 px-2.5 text-xs">
|
||||
Tausch anfragen
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
@@ -479,6 +523,11 @@ export function CalendarOverviewClient({
|
||||
</p>
|
||||
)}
|
||||
|
||||
{item.rsvpEvent ? <section className="mt-4 border-t border-[var(--hairline)] pt-4">
|
||||
<h5 className="mb-3 font-medium">Eure Rückmeldung</h5>
|
||||
<RsvpForm key={JSON.stringify(item.rsvpEvent)} event={item.rsvpEvent} />
|
||||
</section> : null}
|
||||
|
||||
{item.participantInfo && item.showParticipantInfo && (
|
||||
<div className="mt-3 rounded-lg border border-[var(--warn)] bg-[var(--warn-soft)] p-3 text-xs text-[var(--ink)]">
|
||||
<div className="mb-0.5 flex items-center gap-1.5 font-medium">
|
||||
@@ -564,6 +613,106 @@ export function CalendarOverviewClient({
|
||||
);
|
||||
}
|
||||
|
||||
function NotdienstSwapRequestsPanel({
|
||||
requests,
|
||||
}: {
|
||||
requests: NotdienstSwapRequestDto[];
|
||||
}) {
|
||||
return (
|
||||
<Card className="p-0">
|
||||
<div className="border-b border-[var(--hairline-soft)] px-5 py-4">
|
||||
<h2 className="text-base font-semibold tracking-[-0.01em] text-[var(--ink)]">
|
||||
Offene Notdienst-Tausche
|
||||
</h2>
|
||||
</div>
|
||||
<div className="divide-y divide-[var(--hairline-soft)]">
|
||||
{requests.map((request) => (
|
||||
<NotdienstSwapRequestRow key={request.id} request={request} />
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function NotdienstSwapRequestRow({
|
||||
request,
|
||||
}: {
|
||||
request: NotdienstSwapRequestDto;
|
||||
}) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const runAction = (
|
||||
action: (requestId: string) => Promise<{ success?: boolean; error?: string }>,
|
||||
successMessage: string,
|
||||
) => {
|
||||
startTransition(async () => {
|
||||
const result = await action(request.id);
|
||||
if (result.error) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
toast.success(successMessage);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 px-5 py-4">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-[var(--ink)]">
|
||||
{request.direction === "incoming" ? "Anfrage an dich" : "Deine Anfrage"}
|
||||
</p>
|
||||
<p className="mt-1 text-sm leading-5 text-[var(--ink-soft)]">
|
||||
{format(request.targetDate, "dd.MM.yyyy", { locale: de })}{" "}
|
||||
({request.targetFamilyName}, {request.targetChildName}) gegen{" "}
|
||||
{format(request.offeredDate, "dd.MM.yyyy", { locale: de })}{" "}
|
||||
({request.offeredFamilyName}, {request.offeredChildName})
|
||||
</p>
|
||||
{request.message && (
|
||||
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">
|
||||
{request.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
{request.direction === "incoming" ? (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
runAction(acceptNotdienstSwapRequest, "Tausch wurde angenommen.")
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
Annehmen
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
runAction(declineNotdienstSwapRequest, "Tausch wurde abgelehnt.")
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
Ablehnen
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
runAction(cancelNotdienstSwapRequest, "Tauschanfrage wurde zurückgezogen.")
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
Zurückziehen
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Month Grid Component
|
||||
// =====================================================================
|
||||
@@ -856,6 +1005,8 @@ function AgendaView({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{item.kind === "termin" && item.rsvpEvent ? <RsvpDialog event={item.rsvpEvent} /> : null}
|
||||
|
||||
{/* Actions for admins */}
|
||||
{isAdmin && item.kind === "termin" && (
|
||||
<div className="flex gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, useTransition } from "react";
|
||||
import { DutyAssignmentStatus, TerminStatus, TerminType } from "@prisma/client";
|
||||
import {
|
||||
DutyAssignmentStatus,
|
||||
RsvpMode,
|
||||
TerminStatus,
|
||||
TerminType,
|
||||
} from "@prisma/client";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import {
|
||||
@@ -11,11 +17,11 @@ import {
|
||||
MapPin,
|
||||
MoreHorizontal,
|
||||
WashingMachine,
|
||||
Trash2,
|
||||
ShieldAlert,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { RsvpForm } from "@/components/rsvp-form";
|
||||
import type { RsvpEventDto } from "@/lib/rsvp";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
@@ -31,7 +37,7 @@ import {
|
||||
import { AdminTerminModal } from "./admin-termin-modal";
|
||||
import { TerminRequestModal } from "./termin-request-modal";
|
||||
import { MitbringselList } from "./mitbringsel-list";
|
||||
import { deleteTerminAdmin } from "../actions";
|
||||
import { createNotdienstSwapRequest, deleteTerminAdmin } from "../actions";
|
||||
|
||||
export type TerminListItemDto = {
|
||||
kind: "termin";
|
||||
@@ -45,6 +51,10 @@ export type TerminListItemDto = {
|
||||
allDay: boolean;
|
||||
mitbringselListEnabled: boolean;
|
||||
requiresRsvp: boolean;
|
||||
rsvpMode: RsvpMode;
|
||||
rsvpDeadline: Date | null;
|
||||
hasRsvpResponses: boolean;
|
||||
rsvpEvent?: RsvpEventDto;
|
||||
participantInfo: string | null;
|
||||
showParticipantInfo: boolean;
|
||||
mitbringselItems?: {
|
||||
@@ -69,24 +79,41 @@ export type DutyCalendarItemDto = {
|
||||
export type NotdienstCalendarItemDto = {
|
||||
kind: "notdienst";
|
||||
id: string;
|
||||
planId: string;
|
||||
planYear: number;
|
||||
planMonth: number;
|
||||
title: string;
|
||||
familyId: string;
|
||||
familyName: string;
|
||||
childName: string;
|
||||
isOwn: boolean;
|
||||
canRequestSwap: boolean;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
};
|
||||
|
||||
export type CalendarListItemDto = TerminListItemDto | DutyCalendarItemDto | NotdienstCalendarItemDto;
|
||||
export type NotdienstSwapOptionDto = {
|
||||
id: string;
|
||||
date: Date;
|
||||
childName: string;
|
||||
familyName: string;
|
||||
};
|
||||
|
||||
export type CalendarListItemDto =
|
||||
| TerminListItemDto
|
||||
| DutyCalendarItemDto
|
||||
| NotdienstCalendarItemDto;
|
||||
|
||||
export function TerminList({
|
||||
termine,
|
||||
userId,
|
||||
isAdmin,
|
||||
notdienstSwapOptions = [],
|
||||
}: {
|
||||
termine: CalendarListItemDto[];
|
||||
userId: string;
|
||||
isAdmin: boolean;
|
||||
notdienstSwapOptions?: NotdienstSwapOptionDto[];
|
||||
}) {
|
||||
if (termine.length === 0) {
|
||||
return (
|
||||
@@ -103,7 +130,10 @@ export function TerminList({
|
||||
</p>
|
||||
<div className="mt-5">
|
||||
{isAdmin ? (
|
||||
<AdminTerminModal triggerLabel="+ Termin anlegen" triggerClassName="" />
|
||||
<AdminTerminModal
|
||||
triggerLabel="+ Termin anlegen"
|
||||
triggerClassName=""
|
||||
/>
|
||||
) : (
|
||||
<TerminRequestModal
|
||||
triggerLabel="+ Termin anlegen"
|
||||
@@ -128,18 +158,33 @@ export function TerminList({
|
||||
{group.label}
|
||||
</h2>
|
||||
<span className="rounded-full border border-[var(--hairline)] bg-[var(--surface-2)] px-2.5 py-1 text-[11px] font-semibold text-[var(--ink-soft)] tabular-nums">
|
||||
{group.items.length} {group.items.length === 1 ? "Termin" : "Termine"}
|
||||
{group.items.length}{" "}
|
||||
{group.items.length === 1 ? "Termin" : "Termine"}
|
||||
</span>
|
||||
</div>
|
||||
<Card className="overflow-hidden p-0">
|
||||
<div className="divide-y divide-[var(--hairline-soft)]">
|
||||
{group.items.map((item) =>
|
||||
item.kind === "duty" ? (
|
||||
<DutyRow key={`duty-${item.id}`} duty={item} isAdmin={isAdmin} />
|
||||
<DutyRow
|
||||
key={`duty-${item.id}`}
|
||||
duty={item}
|
||||
isAdmin={isAdmin}
|
||||
/>
|
||||
) : item.kind === "notdienst" ? (
|
||||
<NotdienstRow key={`notdienst-${item.id}`} notdienst={item} isAdmin={isAdmin} />
|
||||
<NotdienstRow
|
||||
key={`notdienst-${item.id}`}
|
||||
notdienst={item}
|
||||
isAdmin={isAdmin}
|
||||
notdienstSwapOptions={notdienstSwapOptions}
|
||||
/>
|
||||
) : (
|
||||
<TerminRow key={`termin-${item.id}`} termin={item} userId={userId} isAdmin={isAdmin} />
|
||||
<TerminRow
|
||||
key={`termin-${item.id}`}
|
||||
termin={item}
|
||||
userId={userId}
|
||||
isAdmin={isAdmin}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
@@ -150,13 +195,22 @@ export function TerminList({
|
||||
);
|
||||
}
|
||||
|
||||
function DutyRow({ duty, isAdmin }: { duty: DutyCalendarItemDto; isAdmin: boolean }) {
|
||||
function DutyRow({
|
||||
duty,
|
||||
isAdmin,
|
||||
}: {
|
||||
duty: DutyCalendarItemDto;
|
||||
isAdmin: boolean;
|
||||
}) {
|
||||
const color = duty.isOwn ? "oklch(0.60 0.16 160)" : "oklch(0.75 0.08 160)";
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="relative grid grid-cols-[56px_minmax(0,1fr)_auto] items-center gap-4 px-5 py-4 transition-colors hover:bg-[var(--surface-2)]">
|
||||
<div className="absolute inset-y-3 left-0 w-[3px] rounded-r-full" style={{ backgroundColor: color }} />
|
||||
<div
|
||||
className="absolute inset-y-3 left-0 w-[3px] rounded-r-full"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<DateTile date={duty.startDate} />
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-[15px] font-semibold text-[var(--ink)]">
|
||||
@@ -189,7 +243,10 @@ function DutyRow({ duty, isAdmin }: { duty: DutyCalendarItemDto; isAdmin: boolea
|
||||
</Button>
|
||||
{menuOpen && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setMenuOpen(false)} />
|
||||
<div
|
||||
className="fixed inset-0 z-40"
|
||||
onClick={() => setMenuOpen(false)}
|
||||
/>
|
||||
<div className="absolute right-0 mt-1 w-56 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-1.5 shadow-lg z-50 animate-in fade-in-50 slide-in-from-top-1 duration-150">
|
||||
<a
|
||||
href="/dashboard/admin/dienste"
|
||||
@@ -239,7 +296,10 @@ function TerminRow({
|
||||
<>
|
||||
<Dialog>
|
||||
<div className="relative grid grid-cols-[56px_minmax(0,1fr)_auto] items-center gap-4 px-5 py-4 transition-colors hover:bg-[var(--surface-2)]">
|
||||
<div className="absolute inset-y-3 left-0 w-[3px] rounded-r-full" style={{ backgroundColor: color }} />
|
||||
<div
|
||||
className="absolute inset-y-3 left-0 w-[3px] rounded-r-full"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<DateTile date={termin.startDate} />
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -258,7 +318,9 @@ function TerminRow({
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 relative">
|
||||
<CategoryPill color={color}>{getTypeLabel(termin.type)}</CategoryPill>
|
||||
<CategoryPill color={color}>
|
||||
{getTypeLabel(termin.type)}
|
||||
</CategoryPill>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
Details
|
||||
@@ -279,7 +341,10 @@ function TerminRow({
|
||||
</Button>
|
||||
{menuOpen && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setMenuOpen(false)} />
|
||||
<div
|
||||
className="fixed inset-0 z-40"
|
||||
onClick={() => setMenuOpen(false)}
|
||||
/>
|
||||
<div className="absolute right-0 mt-1 w-48 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-1.5 shadow-lg z-50 animate-in fade-in-50 slide-in-from-top-1 duration-150">
|
||||
<AdminTerminModal
|
||||
existingTermin={termin}
|
||||
@@ -324,7 +389,9 @@ function TerminRow({
|
||||
|
||||
<div className="grid gap-4">
|
||||
<div className="flex">
|
||||
<CategoryPill color={color}>{getTypeLabel(termin.type)}</CategoryPill>
|
||||
<CategoryPill color={color}>
|
||||
{getTypeLabel(termin.type)}
|
||||
</CategoryPill>
|
||||
</div>
|
||||
|
||||
{termin.description ? (
|
||||
@@ -337,6 +404,16 @@ function TerminRow({
|
||||
</p>
|
||||
)}
|
||||
|
||||
{termin.rsvpEvent ? (
|
||||
<section className="rounded-lg border border-[var(--hairline)] p-4">
|
||||
<h3 className="mb-3 font-medium">Eure Rückmeldung</h3>
|
||||
<RsvpForm
|
||||
key={JSON.stringify(termin.rsvpEvent)}
|
||||
event={termin.rsvpEvent}
|
||||
/>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{termin.participantInfo && termin.showParticipantInfo && (
|
||||
<div className="rounded-lg border border-[var(--warn)] bg-[var(--warn-soft)] p-4 text-sm text-[var(--ink)]">
|
||||
<div className="mb-1 flex items-center gap-2 font-medium">
|
||||
@@ -367,8 +444,9 @@ function TerminRow({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Termin unwiderruflich löschen?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Möchtest du den Termin “{termin.title}” wirklich löschen? Alle
|
||||
zugehörigen Teilnahmen und Mitbringsel-Einträge gehen verloren.
|
||||
Möchtest du den Termin “{termin.title}” wirklich
|
||||
löschen? Alle zugehörigen Teilnahmen und Mitbringsel-Einträge
|
||||
gehen verloren.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
@@ -418,14 +496,20 @@ function CategoryPill({
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-[var(--hairline)] bg-[var(--surface-2)] px-2.5 py-1 text-[11px] font-semibold text-[var(--ink-soft)]"
|
||||
style={{ color }}
|
||||
>
|
||||
<span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: color }} />
|
||||
<span
|
||||
className="h-1.5 w-1.5 rounded-full"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function groupByMonth(items: CalendarListItemDto[]) {
|
||||
const groups = new Map<string, { key: string; label: string; items: CalendarListItemDto[] }>();
|
||||
const groups = new Map<
|
||||
string,
|
||||
{ key: string; label: string; items: CalendarListItemDto[] }
|
||||
>();
|
||||
|
||||
items.forEach((item) => {
|
||||
const key = format(item.startDate, "yyyy-MM");
|
||||
@@ -492,13 +576,140 @@ function getTypeLabel(type: TerminType): string {
|
||||
}
|
||||
}
|
||||
|
||||
function NotdienstRow({ notdienst, isAdmin }: { notdienst: NotdienstCalendarItemDto; isAdmin: boolean }) {
|
||||
export function NotdienstSwapDialog({
|
||||
target,
|
||||
options,
|
||||
trigger,
|
||||
}: {
|
||||
target: NotdienstCalendarItemDto;
|
||||
options: NotdienstSwapOptionDto[];
|
||||
trigger: ReactNode;
|
||||
}) {
|
||||
const selectableOptions = options.filter((option) => option.id !== target.id);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [offeredAssignmentId, setOfferedAssignmentId] = useState(
|
||||
selectableOptions[0]?.id ?? "",
|
||||
);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!offeredAssignmentId) {
|
||||
toast.error("Bitte wähle einen eigenen Notdienst als Tausch-Angebot.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
const result = await createNotdienstSwapRequest({
|
||||
targetAssignmentId: target.id,
|
||||
offeredAssignmentId,
|
||||
message,
|
||||
});
|
||||
|
||||
if ("error" in result && result.error) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Tauschanfrage wurde versendet.");
|
||||
setOpen(false);
|
||||
setMessage("");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>{trigger}</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Notdienst tauschen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Frage Familie {target.familyName}, ob ihr den Notdienst am{" "}
|
||||
{format(target.startDate, "dd.MM.yyyy", { locale: de })} tauschen
|
||||
könnt.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-[var(--ink)]">
|
||||
Dein Tausch-Angebot
|
||||
</label>
|
||||
<select
|
||||
className="w-full rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-sm text-[var(--ink)] ring-offset-[var(--surface)] hover:border-[var(--accent-mid)] focus-visible:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--focus-ring)]"
|
||||
value={offeredAssignmentId}
|
||||
disabled={isPending || selectableOptions.length === 0}
|
||||
onChange={(event) => setOfferedAssignmentId(event.target.value)}
|
||||
>
|
||||
{selectableOptions.length === 0 ? (
|
||||
<option value="">
|
||||
Kein eigener zukünftiger Notdienst verfügbar
|
||||
</option>
|
||||
) : (
|
||||
selectableOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{format(option.date, "dd.MM.yyyy", { locale: de })} -{" "}
|
||||
{option.childName}
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-[var(--ink)]">
|
||||
Nachricht optional
|
||||
</label>
|
||||
<textarea
|
||||
value={message}
|
||||
onChange={(event) => setMessage(event.target.value)}
|
||||
maxLength={500}
|
||||
rows={3}
|
||||
className="w-full resize-none rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-sm text-[var(--ink)] ring-offset-[var(--surface)] placeholder:text-[var(--ink-muted)] hover:border-[var(--accent-mid)] focus-visible:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--focus-ring)]"
|
||||
placeholder="Zum Beispiel: Wir sind an dem Tag verreist."
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setOpen(false)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={isPending || selectableOptions.length === 0}
|
||||
>
|
||||
Anfrage senden
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function NotdienstRow({
|
||||
notdienst,
|
||||
isAdmin,
|
||||
notdienstSwapOptions,
|
||||
}: {
|
||||
notdienst: NotdienstCalendarItemDto;
|
||||
isAdmin: boolean;
|
||||
notdienstSwapOptions: NotdienstSwapOptionDto[];
|
||||
}) {
|
||||
const color = notdienst.isOwn ? "oklch(0.60 0.18 45)" : "oklch(0.75 0.10 50)";
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="relative grid grid-cols-[56px_minmax(0,1fr)_auto] items-center gap-4 px-5 py-4 transition-colors hover:bg-[var(--surface-2)]">
|
||||
<div className="absolute inset-y-3 left-0 w-[3px] rounded-r-full" style={{ backgroundColor: color }} />
|
||||
<div
|
||||
className="absolute inset-y-3 left-0 w-[3px] rounded-r-full"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<DateTile date={notdienst.startDate} />
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-[15px] font-semibold text-[var(--ink)]">
|
||||
@@ -506,7 +717,8 @@ function NotdienstRow({ notdienst, isAdmin }: { notdienst: NotdienstCalendarItem
|
||||
</h3>
|
||||
<p className="mt-1 flex flex-wrap items-center gap-2 text-[13px] text-[var(--ink-soft)]">
|
||||
<Clock className="h-3.5 w-3.5 [stroke-width:1.7]" />
|
||||
{format(notdienst.startDate, "dd.MM.yyyy", { locale: de })} (ganztägig)
|
||||
{format(notdienst.startDate, "dd.MM.yyyy", { locale: de })}{" "}
|
||||
(ganztägig)
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-[var(--ink-muted)]" />
|
||||
Kind: {notdienst.childName}
|
||||
@@ -532,10 +744,13 @@ function NotdienstRow({ notdienst, isAdmin }: { notdienst: NotdienstCalendarItem
|
||||
</Button>
|
||||
{menuOpen && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setMenuOpen(false)} />
|
||||
<div
|
||||
className="fixed inset-0 z-40"
|
||||
onClick={() => setMenuOpen(false)}
|
||||
/>
|
||||
<div className="absolute right-0 mt-1 w-56 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-1.5 shadow-lg z-50 animate-in fade-in-50 slide-in-from-top-1 duration-150">
|
||||
<a
|
||||
href="/dashboard/notdienst/plan"
|
||||
href={`/dashboard/notdienst/plan?year=${notdienst.planYear}&month=${notdienst.planMonth}`}
|
||||
className="flex w-full items-center rounded-lg px-2.5 py-2 text-sm text-[var(--ink)] hover:bg-[var(--surface-2)]"
|
||||
onClick={() => setMenuOpen(false)}
|
||||
>
|
||||
@@ -545,6 +760,20 @@ function NotdienstRow({ notdienst, isAdmin }: { notdienst: NotdienstCalendarItem
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : notdienst.canRequestSwap ? (
|
||||
<NotdienstSwapDialog
|
||||
target={notdienst}
|
||||
options={notdienstSwapOptions}
|
||||
trigger={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 px-2.5 text-xs"
|
||||
>
|
||||
Tausch anfragen
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-9 h-9" />
|
||||
)}
|
||||
|
||||
@@ -1,43 +1,316 @@
|
||||
"use server";
|
||||
|
||||
import { UserFacingError, publicActionError } from "@/lib/action-error";
|
||||
import { createElement } from "react";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { TerminStatus, TerminType, UserRole } from "@prisma/client";
|
||||
import {
|
||||
Prisma,
|
||||
NotdienstAlertStatus,
|
||||
NotdienstPlanStatus,
|
||||
NotdienstSwapStatus,
|
||||
RsvpMode,
|
||||
TerminStatus,
|
||||
TerminType,
|
||||
UserRole,
|
||||
} from "@prisma/client";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { z } from "zod";
|
||||
|
||||
import { NotdienstSwapEmail } from "@/emails/NotdienstSwapEmail";
|
||||
import { requireKitaSession, requireRole } from "@/lib/auth-utils";
|
||||
import { sendAppEmail } from "@/lib/mail";
|
||||
import { serializableTransaction } from "@/lib/transaction";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { lockEvent } from "@/lib/event-lock";
|
||||
|
||||
// =====================================================================
|
||||
// /dashboard/kalender · Server Actions
|
||||
// =====================================================================
|
||||
|
||||
const terminSchema = z.object({
|
||||
title: z.string().trim().min(2, "Titel muss mindestens 2 Zeichen lang sein"),
|
||||
description: z.string().trim().optional(),
|
||||
title: z.string().trim().min(2, "Titel muss mindestens 2 Zeichen lang sein").max(160),
|
||||
description: z.string().trim().max(20000).optional(),
|
||||
type: z.nativeEnum(TerminType),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
allDay: z.boolean().default(false),
|
||||
mitbringselListEnabled: z.boolean().default(false),
|
||||
requiresRsvp: z.boolean().default(false),
|
||||
mitbringselListEnabled: z.boolean().optional(),
|
||||
requiresRsvp: z.boolean().optional(),
|
||||
rsvpMode: z.nativeEnum(RsvpMode).optional(),
|
||||
rsvpDeadline: z.string().datetime().nullable().optional(),
|
||||
participantInfo: z.string().trim().max(1000).optional(),
|
||||
});
|
||||
|
||||
function buildTerminData(data: z.infer<typeof terminSchema>) {
|
||||
const swapRequestSchema = z.object({
|
||||
targetAssignmentId: z.string().min(1),
|
||||
offeredAssignmentId: z.string().min(1),
|
||||
message: z.string().trim().max(500).optional(),
|
||||
});
|
||||
|
||||
const swapIdSchema = z.string().min(1);
|
||||
|
||||
const activeNotdienstAlertStatuses = [
|
||||
NotdienstAlertStatus.PENDING,
|
||||
NotdienstAlertStatus.CONFIRMED,
|
||||
];
|
||||
|
||||
function getTodayUtcDateOnly() {
|
||||
const today = new Date();
|
||||
return new Date(
|
||||
Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()),
|
||||
);
|
||||
}
|
||||
|
||||
function getBaseUrl() {
|
||||
return (
|
||||
process.env.NEXTAUTH_URL ?? process.env.AUTH_URL ?? "http://localhost:3000"
|
||||
);
|
||||
}
|
||||
|
||||
function formatNotdienstDate(date: Date) {
|
||||
return format(date, "EEEE, dd. MMMM yyyy", { locale: de });
|
||||
}
|
||||
|
||||
function revalidateCalendarAndNotdienst() {
|
||||
try {
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/notdienst/plan");
|
||||
revalidatePath("/dashboard/notdienst");
|
||||
revalidatePath("/dashboard");
|
||||
} catch {
|
||||
// Ignore if called outside Next.js context
|
||||
}
|
||||
}
|
||||
|
||||
type SwapAssignmentWithFamily = {
|
||||
id: string;
|
||||
childId: string;
|
||||
date: Date;
|
||||
plan: {
|
||||
status: NotdienstPlanStatus;
|
||||
};
|
||||
child: {
|
||||
familyId: string;
|
||||
family: {
|
||||
name: string;
|
||||
users: {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
alerts: {
|
||||
id: string;
|
||||
}[];
|
||||
alarms?: { id: string }[];
|
||||
};
|
||||
|
||||
async function getSwapAssignment(
|
||||
assignmentId: string,
|
||||
kitaId: string,
|
||||
db: Prisma.TransactionClient = prisma,
|
||||
): Promise<SwapAssignmentWithFamily | null> {
|
||||
return db.notdienstAssignment.findFirst({
|
||||
where: { id: assignmentId, kitaId },
|
||||
select: {
|
||||
id: true,
|
||||
childId: true,
|
||||
date: true,
|
||||
plan: { select: { status: true } },
|
||||
child: {
|
||||
select: {
|
||||
familyId: true,
|
||||
family: {
|
||||
select: {
|
||||
name: true,
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: {
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
alerts: {
|
||||
where: { alarmId: null, status: { in: activeNotdienstAlertStatuses } },
|
||||
select: { id: true },
|
||||
},
|
||||
alarms: {
|
||||
where: { activeAssignmentId: { not: null } },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function validateSwapAssignmentPair({
|
||||
targetAssignment,
|
||||
offeredAssignment,
|
||||
requesterFamilyId,
|
||||
today,
|
||||
}: {
|
||||
targetAssignment: SwapAssignmentWithFamily | null;
|
||||
offeredAssignment: SwapAssignmentWithFamily | null;
|
||||
requesterFamilyId: string;
|
||||
today: Date;
|
||||
}) {
|
||||
if (!targetAssignment || !offeredAssignment) {
|
||||
return "Notdienst nicht gefunden.";
|
||||
}
|
||||
|
||||
if (targetAssignment.id === offeredAssignment.id) {
|
||||
return "Bitte wähle zwei unterschiedliche Notdienste aus.";
|
||||
}
|
||||
|
||||
if (
|
||||
targetAssignment.plan.status !== NotdienstPlanStatus.PUBLISHED ||
|
||||
offeredAssignment.plan.status !== NotdienstPlanStatus.PUBLISHED
|
||||
) {
|
||||
return "Es können nur veröffentlichte Notdienste getauscht werden.";
|
||||
}
|
||||
|
||||
if (targetAssignment.date < today || offeredAssignment.date < today) {
|
||||
return "Vergangene Notdienste können nicht getauscht werden.";
|
||||
}
|
||||
|
||||
if (offeredAssignment.child.familyId !== requesterFamilyId) {
|
||||
return "Du kannst nur eigene Notdienste als Tausch anbieten.";
|
||||
}
|
||||
|
||||
if (targetAssignment.child.familyId === requesterFamilyId) {
|
||||
return "Du kannst keinen Tausch mit deinem eigenen Haushalt anfragen.";
|
||||
}
|
||||
|
||||
if (
|
||||
targetAssignment.alerts.length > 0 ||
|
||||
offeredAssignment.alerts.length > 0 ||
|
||||
targetAssignment.alarms?.length ||
|
||||
offeredAssignment.alarms?.length
|
||||
) {
|
||||
return "Notdienste mit aktiver Alarmierung können nicht getauscht werden.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function sendSwapMail({
|
||||
to,
|
||||
parentName,
|
||||
subject,
|
||||
heading,
|
||||
preview,
|
||||
kitaName,
|
||||
body,
|
||||
targetDate,
|
||||
offeredDate,
|
||||
}: {
|
||||
to: string;
|
||||
parentName: string;
|
||||
subject: string;
|
||||
heading: string;
|
||||
preview: string;
|
||||
kitaName: string;
|
||||
body: string;
|
||||
targetDate: Date;
|
||||
offeredDate: Date;
|
||||
}) {
|
||||
const result = await sendAppEmail({
|
||||
to,
|
||||
subject,
|
||||
react: createElement(NotdienstSwapEmail, {
|
||||
parentName,
|
||||
heading,
|
||||
preview,
|
||||
kitaName,
|
||||
body,
|
||||
targetDateLabel: formatNotdienstDate(targetDate),
|
||||
offeredDateLabel: formatNotdienstDate(offeredDate),
|
||||
link: `${getBaseUrl()}/dashboard/kalender`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.error(
|
||||
"Notdienst-Tausch-Mail konnte nicht versendet werden:",
|
||||
result.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function notifyFamilyAboutSwap({
|
||||
family,
|
||||
subject,
|
||||
heading,
|
||||
preview,
|
||||
kitaName,
|
||||
body,
|
||||
targetDate,
|
||||
offeredDate,
|
||||
}: {
|
||||
family: SwapAssignmentWithFamily["child"]["family"];
|
||||
subject: string;
|
||||
heading: string;
|
||||
preview: string;
|
||||
kitaName: string;
|
||||
body: string;
|
||||
targetDate: Date;
|
||||
offeredDate: Date;
|
||||
}) {
|
||||
await Promise.all(
|
||||
family.users
|
||||
.filter((parent) => !!parent.email)
|
||||
.map((parent) =>
|
||||
sendSwapMail({
|
||||
to: parent.email,
|
||||
parentName: `${parent.firstName} ${parent.lastName}`,
|
||||
subject,
|
||||
heading,
|
||||
preview,
|
||||
kitaName,
|
||||
body,
|
||||
targetDate,
|
||||
offeredDate,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function buildTerminData(
|
||||
data: z.infer<typeof terminSchema>,
|
||||
allowPast = false,
|
||||
) {
|
||||
const startDate = new Date(data.startDate);
|
||||
const endDate = new Date(data.endDate);
|
||||
const now = new Date();
|
||||
now.setSeconds(0, 0);
|
||||
|
||||
if (startDate < now) {
|
||||
return { error: "Der Startzeitpunkt darf nicht in der Vergangenheit liegen." };
|
||||
if (!allowPast && startDate < now) {
|
||||
return {
|
||||
error: "Der Startzeitpunkt darf nicht in der Vergangenheit liegen.",
|
||||
};
|
||||
}
|
||||
|
||||
if (endDate < startDate) {
|
||||
return { error: "Das Enddatum darf nicht vor dem Startdatum liegen." };
|
||||
}
|
||||
|
||||
if (
|
||||
data.requiresRsvp &&
|
||||
data.rsvpDeadline &&
|
||||
new Date(data.rsvpDeadline) > startDate
|
||||
) {
|
||||
return {
|
||||
error: "Die Rückmeldefrist darf nicht nach dem Terminbeginn liegen.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
title: data.title,
|
||||
@@ -46,22 +319,459 @@ function buildTerminData(data: z.infer<typeof terminSchema>) {
|
||||
startDate,
|
||||
endDate,
|
||||
allDay: data.allDay,
|
||||
mitbringselListEnabled: data.mitbringselListEnabled,
|
||||
requiresRsvp: data.requiresRsvp,
|
||||
mitbringselListEnabled: data.mitbringselListEnabled ?? false,
|
||||
requiresRsvp: data.requiresRsvp ?? false,
|
||||
rsvpMode: data.rsvpMode ?? RsvpMode.CHILD,
|
||||
rsvpDeadline:
|
||||
data.requiresRsvp && data.rsvpDeadline
|
||||
? new Date(data.rsvpDeadline)
|
||||
: null,
|
||||
participantInfo:
|
||||
data.requiresRsvp && data.participantInfo
|
||||
? data.participantInfo
|
||||
: null,
|
||||
data.requiresRsvp && data.participantInfo ? data.participantInfo : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createNotdienstSwapRequest(rawPayload: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!(await rateLimit(`createNotdienstSwapRequest:${session.user.kitaId}:${session.user.id}`, 30, 3600)).allowed) return { error: "Zu viele Anfragen. Bitte versuche es später erneut." };
|
||||
if (session.user.role !== UserRole.ELTERN) {
|
||||
return { error: "Nur Eltern können Notdienst-Tausche anfragen." };
|
||||
}
|
||||
if (!session.user.familyId) {
|
||||
return { error: "Dein Account ist noch keinem Haushalt zugeordnet." };
|
||||
}
|
||||
|
||||
const parsed = swapRequestSchema.safeParse(rawPayload);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
const { targetAssignmentId, offeredAssignmentId, message } = parsed.data;
|
||||
const today = getTodayUtcDateOnly();
|
||||
|
||||
try {
|
||||
const { targetAssignment, offeredAssignment, kita } = await serializableTransaction(async tx => {
|
||||
const [targetAssignment, offeredAssignment, kita, existingRequest] =
|
||||
await Promise.all([
|
||||
getSwapAssignment(targetAssignmentId, session.user.kitaId, tx),
|
||||
getSwapAssignment(offeredAssignmentId, session.user.kitaId, tx),
|
||||
tx.kita.findUnique({
|
||||
where: { id: session.user.kitaId },
|
||||
select: { name: true },
|
||||
}),
|
||||
tx.notdienstSwapRequest.findFirst({
|
||||
where: {
|
||||
kitaId: session.user.kitaId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
OR: [
|
||||
{ targetAssignmentId },
|
||||
{ offeredAssignmentId },
|
||||
{ targetAssignmentId: offeredAssignmentId },
|
||||
{ offeredAssignmentId: targetAssignmentId },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const validationError = validateSwapAssignmentPair({
|
||||
targetAssignment,
|
||||
offeredAssignment,
|
||||
requesterFamilyId: session.user.familyId!,
|
||||
today,
|
||||
});
|
||||
if (validationError) {
|
||||
throw new UserFacingError(validationError);
|
||||
}
|
||||
if (!targetAssignment || !offeredAssignment || !kita) {
|
||||
throw new UserFacingError("Notdienst nicht gefunden.");
|
||||
}
|
||||
if (existingRequest) {
|
||||
throw new UserFacingError("Für einen dieser Notdienste gibt es bereits eine offene Tauschanfrage.");
|
||||
}
|
||||
|
||||
if (await tx.notdienstAlarm.count({ where: { kitaId: session.user.kitaId, activeAssignmentId: { in: [targetAssignment.id, offeredAssignment.id] } } })) throw new UserFacingError("Notdienste mit aktiver Alarmierung können nicht getauscht werden.");
|
||||
|
||||
await tx.notdienstSwapRequest.create({
|
||||
data: {
|
||||
kitaId: session.user.kitaId,
|
||||
requesterUserId: session.user.id,
|
||||
requesterFamilyId: session.user.familyId!,
|
||||
targetAssignmentId,
|
||||
offeredAssignmentId,
|
||||
message: message || null,
|
||||
},
|
||||
});
|
||||
|
||||
return { targetAssignment, offeredAssignment, kita };
|
||||
});
|
||||
|
||||
await notifyFamilyAboutSwap({
|
||||
family: targetAssignment.child.family,
|
||||
subject: `Notdienst-Tauschanfrage für ${formatNotdienstDate(targetAssignment.date)}`,
|
||||
heading: "Neue Tauschanfrage",
|
||||
preview: "Du hast eine neue Notdienst-Tauschanfrage.",
|
||||
kitaName: kita.name,
|
||||
body: `Ein Elternteil aus einem anderen Haushalt möchte einen Notdienst mit dir tauschen.${message ? ` Nachricht: ${message}` : ""}`,
|
||||
targetDate: targetAssignment.date,
|
||||
offeredDate: offeredAssignment.date,
|
||||
});
|
||||
|
||||
revalidateCalendarAndNotdienst();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error && error.message === "Für einen dieser Notdienste gibt es bereits eine offene Tauschanfrage.")) {
|
||||
console.error("Fehler beim Erstellen der Notdienst-Tauschanfrage:", error);
|
||||
}
|
||||
return { error: publicActionError(error, "Tauschanfrage konnte nicht erstellt werden.") };
|
||||
}
|
||||
}
|
||||
|
||||
export async function acceptNotdienstSwapRequest(requestIdRaw: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!session.user.familyId) {
|
||||
return { error: "Dein Account ist noch keinem Haushalt zugeordnet." };
|
||||
}
|
||||
|
||||
const parsed = swapIdSchema.safeParse(requestIdRaw);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
const today = getTodayUtcDateOnly();
|
||||
|
||||
try {
|
||||
const result = await serializableTransaction(async (tx) => {
|
||||
const request = await tx.notdienstSwapRequest.findFirst({
|
||||
where: {
|
||||
id: parsed.data,
|
||||
kitaId: session.user.kitaId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
requesterFamilyId: true,
|
||||
targetAssignmentId: true,
|
||||
offeredAssignmentId: true,
|
||||
targetAssignment: {
|
||||
select: {
|
||||
id: true,
|
||||
childId: true,
|
||||
date: true,
|
||||
plan: { select: { status: true } },
|
||||
child: {
|
||||
select: {
|
||||
familyId: true,
|
||||
family: {
|
||||
select: {
|
||||
name: true,
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
alerts: {
|
||||
where: { status: { in: activeNotdienstAlertStatuses } },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
offeredAssignment: {
|
||||
select: {
|
||||
id: true,
|
||||
childId: true,
|
||||
date: true,
|
||||
plan: { select: { status: true } },
|
||||
child: {
|
||||
select: {
|
||||
familyId: true,
|
||||
family: {
|
||||
select: {
|
||||
name: true,
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
alerts: {
|
||||
where: { status: { in: activeNotdienstAlertStatuses } },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!request) {
|
||||
throw new UserFacingError("Tauschanfrage nicht gefunden oder nicht mehr offen.");
|
||||
}
|
||||
|
||||
if (request.targetAssignment.child.familyId !== session.user.familyId) {
|
||||
throw new UserFacingError("Nur der angefragte Haushalt kann diese Anfrage annehmen.");
|
||||
}
|
||||
|
||||
const validationError = validateSwapAssignmentPair({
|
||||
targetAssignment: request.targetAssignment,
|
||||
offeredAssignment: request.offeredAssignment,
|
||||
requesterFamilyId: request.requesterFamilyId,
|
||||
today,
|
||||
});
|
||||
if (validationError) {
|
||||
throw new UserFacingError(validationError);
|
||||
}
|
||||
|
||||
if (await tx.notdienstAlarm.count({ where: { kitaId: session.user.kitaId, activeAssignmentId: { in: [request.targetAssignmentId, request.offeredAssignmentId] } } })) throw new UserFacingError("Notdienste mit aktiver Alarmierung können nicht getauscht werden.");
|
||||
|
||||
await tx.notdienstAssignment.update({
|
||||
where: { id: request.targetAssignmentId },
|
||||
data: { childId: request.offeredAssignment.childId },
|
||||
});
|
||||
await tx.notdienstAssignment.update({
|
||||
where: { id: request.offeredAssignmentId },
|
||||
data: { childId: request.targetAssignment.childId },
|
||||
});
|
||||
const responded = await tx.notdienstSwapRequest.updateMany({
|
||||
where: { id: request.id, kitaId: session.user.kitaId, status: NotdienstSwapStatus.PENDING },
|
||||
data: {
|
||||
status: NotdienstSwapStatus.ACCEPTED,
|
||||
respondedById: session.user.id,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (responded.count !== 1) throw new UserFacingError("Diese Anfrage ist nicht mehr offen.");
|
||||
await tx.notdienstSwapRequest.updateMany({
|
||||
where: {
|
||||
id: { not: request.id },
|
||||
kitaId: session.user.kitaId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
OR: [
|
||||
{ targetAssignmentId: { in: [request.targetAssignmentId, request.offeredAssignmentId] } },
|
||||
{ offeredAssignmentId: { in: [request.targetAssignmentId, request.offeredAssignmentId] } },
|
||||
],
|
||||
},
|
||||
data: {
|
||||
status: NotdienstSwapStatus.CANCELLED,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
targetAssignment: request.targetAssignment,
|
||||
offeredAssignment: request.offeredAssignment,
|
||||
};
|
||||
});
|
||||
|
||||
const kita = await prisma.kita.findUnique({
|
||||
where: { id: session.user.kitaId },
|
||||
select: { name: true },
|
||||
});
|
||||
if (kita) {
|
||||
await Promise.all([
|
||||
notifyFamilyAboutSwap({
|
||||
family: result.targetAssignment.child.family,
|
||||
subject: "Notdienst-Tausch bestätigt",
|
||||
heading: "Tausch bestätigt",
|
||||
preview: "Ein Notdienst-Tausch wurde bestätigt.",
|
||||
kitaName: kita.name,
|
||||
body: "die Tauschanfrage wurde angenommen. Der Notdienst-Plan wurde automatisch aktualisiert.",
|
||||
targetDate: result.targetAssignment.date,
|
||||
offeredDate: result.offeredAssignment.date,
|
||||
}),
|
||||
notifyFamilyAboutSwap({
|
||||
family: result.offeredAssignment.child.family,
|
||||
subject: "Notdienst-Tausch bestätigt",
|
||||
heading: "Tausch bestätigt",
|
||||
preview: "Ein Notdienst-Tausch wurde bestätigt.",
|
||||
kitaName: kita.name,
|
||||
body: "deine Tauschanfrage wurde angenommen. Der Notdienst-Plan wurde automatisch aktualisiert.",
|
||||
targetDate: result.targetAssignment.date,
|
||||
offeredDate: result.offeredAssignment.date,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
revalidateCalendarAndNotdienst();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: publicActionError(error, "Tauschanfrage konnte nicht angenommen werden."),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function declineNotdienstSwapRequest(requestIdRaw: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!session.user.familyId) {
|
||||
return { error: "Dein Account ist noch keinem Haushalt zugeordnet." };
|
||||
}
|
||||
|
||||
const parsed = swapIdSchema.safeParse(requestIdRaw);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
try {
|
||||
const request = await prisma.notdienstSwapRequest.findFirst({
|
||||
where: {
|
||||
id: parsed.data,
|
||||
kitaId: session.user.kitaId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
targetAssignment: {
|
||||
select: {
|
||||
date: true,
|
||||
child: {
|
||||
select: {
|
||||
familyId: true,
|
||||
family: {
|
||||
select: {
|
||||
name: true,
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
offeredAssignment: {
|
||||
select: {
|
||||
date: true,
|
||||
child: {
|
||||
select: {
|
||||
family: {
|
||||
select: {
|
||||
name: true,
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!request) {
|
||||
return { error: "Tauschanfrage nicht gefunden oder nicht mehr offen." };
|
||||
}
|
||||
if (request.targetAssignment.child.familyId !== session.user.familyId) {
|
||||
return {
|
||||
error: "Nur der angefragte Haushalt kann diese Anfrage ablehnen.",
|
||||
};
|
||||
}
|
||||
|
||||
const responded = await prisma.notdienstSwapRequest.updateMany({
|
||||
where: { id: request.id, kitaId: session.user.kitaId, status: NotdienstSwapStatus.PENDING },
|
||||
data: {
|
||||
status: NotdienstSwapStatus.DECLINED,
|
||||
respondedById: session.user.id,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (responded.count !== 1) return { error: "Diese Anfrage ist nicht mehr offen." };
|
||||
|
||||
const kita = await prisma.kita.findUnique({
|
||||
where: { id: session.user.kitaId },
|
||||
select: { name: true },
|
||||
});
|
||||
if (kita) {
|
||||
await Promise.all([
|
||||
notifyFamilyAboutSwap({
|
||||
family: request.targetAssignment.child.family,
|
||||
subject: "Notdienst-Tauschanfrage abgelehnt",
|
||||
heading: "Tauschanfrage abgelehnt",
|
||||
preview: "Eine Notdienst-Tauschanfrage wurde abgelehnt.",
|
||||
kitaName: kita.name,
|
||||
body: "du hast die Tauschanfrage abgelehnt. Der Notdienst-Plan bleibt unverändert.",
|
||||
targetDate: request.targetAssignment.date,
|
||||
offeredDate: request.offeredAssignment.date,
|
||||
}),
|
||||
notifyFamilyAboutSwap({
|
||||
family: request.offeredAssignment.child.family,
|
||||
subject: "Notdienst-Tauschanfrage abgelehnt",
|
||||
heading: "Tauschanfrage abgelehnt",
|
||||
preview: "Eine Notdienst-Tauschanfrage wurde abgelehnt.",
|
||||
kitaName: kita.name,
|
||||
body: "deine Tauschanfrage wurde abgelehnt. Der Notdienst-Plan bleibt unverändert.",
|
||||
targetDate: request.targetAssignment.date,
|
||||
offeredDate: request.offeredAssignment.date,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
revalidateCalendarAndNotdienst();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Ablehnen der Notdienst-Tauschanfrage:", error);
|
||||
return { error: "Tauschanfrage konnte nicht abgelehnt werden." };
|
||||
}
|
||||
}
|
||||
|
||||
export async function cancelNotdienstSwapRequest(requestIdRaw: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!session.user.familyId) {
|
||||
return { error: "Dein Account ist noch keinem Haushalt zugeordnet." };
|
||||
}
|
||||
|
||||
const parsed = swapIdSchema.safeParse(requestIdRaw);
|
||||
if (!parsed.success) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
try {
|
||||
const request = await prisma.notdienstSwapRequest.findFirst({
|
||||
where: {
|
||||
id: parsed.data,
|
||||
kitaId: session.user.kitaId,
|
||||
requesterFamilyId: session.user.familyId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!request) {
|
||||
return { error: "Tauschanfrage nicht gefunden oder nicht mehr offen." };
|
||||
}
|
||||
|
||||
const responded = await prisma.notdienstSwapRequest.updateMany({
|
||||
where: { id: request.id, kitaId: session.user.kitaId, status: NotdienstSwapStatus.PENDING },
|
||||
data: {
|
||||
status: NotdienstSwapStatus.CANCELLED,
|
||||
respondedById: session.user.id,
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (responded.count !== 1) return { error: "Diese Anfrage ist nicht mehr offen." };
|
||||
|
||||
revalidateCalendarAndNotdienst();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Fehler beim Zurückziehen der Notdienst-Tauschanfrage:",
|
||||
error,
|
||||
);
|
||||
return { error: "Tauschanfrage konnte nicht zurückgezogen werden." };
|
||||
}
|
||||
}
|
||||
|
||||
export async function createTerminRequest(rawPayload: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!(await rateLimit(`createTerminRequest:${session.user.kitaId}:${session.user.id}`, 30, 3600)).allowed) return { error: "Zu viele Anfragen. Bitte versuche es später erneut." };
|
||||
|
||||
const parsed = terminSchema.safeParse(rawPayload);
|
||||
if (!parsed.success) {
|
||||
@@ -131,6 +841,7 @@ export async function createTerminAdmin(rawPayload: unknown) {
|
||||
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Erstellen des Termins:", error);
|
||||
@@ -138,7 +849,10 @@ export async function createTerminAdmin(rawPayload: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateTerminAdmin(terminId: string, rawPayload: unknown) {
|
||||
export async function updateTerminAdmin(
|
||||
terminId: string,
|
||||
rawPayload: unknown,
|
||||
): Promise<{ error?: string; success?: boolean }> {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId;
|
||||
|
||||
@@ -151,19 +865,50 @@ export async function updateTerminAdmin(terminId: string, rawPayload: unknown) {
|
||||
return { error: "Ungültige Eingabedaten." };
|
||||
}
|
||||
|
||||
const terminData = buildTerminData(parsed.data);
|
||||
if ("error" in terminData) {
|
||||
return { error: terminData.error };
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.termin.update({
|
||||
where: {
|
||||
id: terminId,
|
||||
kitaId,
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
await lockEvent(tx, terminId, kitaId);
|
||||
const existing = await tx.termin.findFirst({
|
||||
where: { id: terminId, kitaId },
|
||||
include: {
|
||||
_count: {
|
||||
select: { participations: true, familyParticipations: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!existing) return { error: "Termin wurde nicht gefunden." };
|
||||
const data = {
|
||||
...parsed.data,
|
||||
mitbringselListEnabled:
|
||||
parsed.data.mitbringselListEnabled ?? existing.mitbringselListEnabled,
|
||||
requiresRsvp: parsed.data.requiresRsvp ?? existing.requiresRsvp,
|
||||
rsvpMode: parsed.data.rsvpMode ?? existing.rsvpMode,
|
||||
rsvpDeadline:
|
||||
parsed.data.rsvpDeadline === undefined
|
||||
? (existing.rsvpDeadline?.toISOString() ?? null)
|
||||
: parsed.data.rsvpDeadline,
|
||||
participantInfo:
|
||||
parsed.data.participantInfo ?? existing.participantInfo ?? "",
|
||||
};
|
||||
if (
|
||||
data.rsvpMode !== existing.rsvpMode &&
|
||||
existing._count.participations + existing._count.familyParticipations >
|
||||
0
|
||||
) {
|
||||
return {
|
||||
error:
|
||||
"Die Antwortart kann nach der ersten Rückmeldung nicht mehr geändert werden.",
|
||||
};
|
||||
}
|
||||
const terminData = buildTerminData(data, true);
|
||||
if ("error" in terminData) return { error: terminData.error };
|
||||
await tx.termin.update({
|
||||
where: { id: terminId, kitaId },
|
||||
data: terminData.data,
|
||||
});
|
||||
return { success: true };
|
||||
});
|
||||
if (result.error) return result;
|
||||
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
@@ -197,6 +942,7 @@ export async function approveTermin(terminId: string) {
|
||||
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Bestätigen des Termins:", error);
|
||||
@@ -227,6 +973,7 @@ export async function rejectTermin(terminId: string, reason?: string) {
|
||||
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Ablehnen des Termins:", error);
|
||||
@@ -234,7 +981,10 @@ export async function rejectTermin(terminId: string, reason?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function toggleMitbringselList(terminId: string, enabled: boolean) {
|
||||
export async function toggleMitbringselList(
|
||||
terminId: string,
|
||||
enabled: boolean,
|
||||
) {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId;
|
||||
if (!kitaId) {
|
||||
@@ -254,6 +1004,7 @@ export async function toggleMitbringselList(terminId: string, enabled: boolean)
|
||||
|
||||
revalidatePath("/dashboard/kalender");
|
||||
revalidatePath("/dashboard/admin/kalender");
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Umschalten der Mitbring-Liste:", error);
|
||||
@@ -263,11 +1014,12 @@ export async function toggleMitbringselList(terminId: string, enabled: boolean)
|
||||
|
||||
const mitbringselSchema = z.object({
|
||||
terminId: z.string(),
|
||||
content: z.string().min(1, "Eintrag darf nicht leer sein"),
|
||||
content: z.string().trim().min(1, "Eintrag darf nicht leer sein").max(500),
|
||||
});
|
||||
|
||||
export async function addMitbringsel(rawPayload: unknown) {
|
||||
const session = await requireKitaSession();
|
||||
if (!(await rateLimit(`addMitbringsel:${session.user.kitaId}:${session.user.id}`, 30, 3600)).allowed) return { error: "Zu viele Anfragen. Bitte versuche es später erneut." };
|
||||
|
||||
const parsed = mitbringselSchema.safeParse(rawPayload);
|
||||
if (!parsed.success) {
|
||||
@@ -282,7 +1034,11 @@ export async function addMitbringsel(rawPayload: unknown) {
|
||||
where: { id: terminId, kitaId: session.user.kitaId },
|
||||
});
|
||||
|
||||
if (!termin || termin.status !== TerminStatus.CONFIRMED || !termin.mitbringselListEnabled) {
|
||||
if (
|
||||
!termin ||
|
||||
termin.status !== TerminStatus.CONFIRMED ||
|
||||
!termin.mitbringselListEnabled
|
||||
) {
|
||||
return { error: "Mitbring-Liste ist für diesen Termin nicht aktiv." };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
import {
|
||||
DutyAssignmentStatus,
|
||||
EventParticipationStatus,
|
||||
NotdienstSwapStatus,
|
||||
TerminStatus,
|
||||
TerminType,
|
||||
UserRole,
|
||||
} from "@prisma/client";
|
||||
import { HelpCircle } from "lucide-react";
|
||||
|
||||
import { requireKitaSession } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getRsvpEvents } from "@/lib/rsvp-events";
|
||||
import { AdminTerminModal } from "./_components/admin-termin-modal";
|
||||
import { PendingAnfragen, type PendingTerminDto } from "./_components/pending-anfragen";
|
||||
import { type CalendarListItemDto } from "./_components/termin-list";
|
||||
import {
|
||||
PendingAnfragen,
|
||||
type PendingTerminDto,
|
||||
} from "./_components/pending-anfragen";
|
||||
import {
|
||||
type CalendarListItemDto,
|
||||
type NotdienstSwapOptionDto,
|
||||
} from "./_components/termin-list";
|
||||
import { TerminRequestModal } from "./_components/termin-request-modal";
|
||||
import { CalendarOverviewClient } from "./_components/calendar-overview-client";
|
||||
import {
|
||||
CalendarOverviewClient,
|
||||
type NotdienstSwapRequestDto,
|
||||
} from "./_components/calendar-overview-client";
|
||||
|
||||
export const metadata = { title: "Terminkalender · Kita-Planer" };
|
||||
|
||||
@@ -31,8 +41,11 @@ export default async function KalenderPage({
|
||||
const resolvedSearchParams = await searchParams;
|
||||
const currentTab = resolvedSearchParams.tab || "übersicht";
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
|
||||
const confirmedTermineRows = await prisma.termin.findMany({
|
||||
const [rsvpEventRows, confirmedTermineRows] = await Promise.all([
|
||||
getRsvpEvents(session),
|
||||
prisma.termin.findMany({
|
||||
where: {
|
||||
kitaId: session.user.kitaId,
|
||||
status: TerminStatus.CONFIRMED,
|
||||
@@ -48,6 +61,15 @@ export default async function KalenderPage({
|
||||
allDay: true,
|
||||
mitbringselListEnabled: true,
|
||||
requiresRsvp: true,
|
||||
rsvpMode: true,
|
||||
rsvpDeadline: true,
|
||||
_count: {
|
||||
select: { participations: true, familyParticipations: true },
|
||||
},
|
||||
familyParticipations: {
|
||||
where: { familyId: familyIdForParticipation },
|
||||
select: { status: true },
|
||||
},
|
||||
participantInfo: true,
|
||||
mitbringselItems: {
|
||||
select: {
|
||||
@@ -75,7 +97,8 @@ export default async function KalenderPage({
|
||||
},
|
||||
},
|
||||
orderBy: { startDate: "asc" },
|
||||
});
|
||||
}),
|
||||
]);
|
||||
|
||||
const myPendingTermineRows = await prisma.termin.findMany({
|
||||
where: {
|
||||
@@ -94,6 +117,13 @@ export default async function KalenderPage({
|
||||
allDay: true,
|
||||
mitbringselListEnabled: true,
|
||||
requiresRsvp: true,
|
||||
rsvpMode: true,
|
||||
rsvpDeadline: true,
|
||||
_count: { select: { participations: true, familyParticipations: true } },
|
||||
familyParticipations: {
|
||||
where: { familyId: familyIdForParticipation },
|
||||
select: { status: true },
|
||||
},
|
||||
participantInfo: true,
|
||||
mitbringselItems: {
|
||||
select: {
|
||||
@@ -159,6 +189,13 @@ export default async function KalenderPage({
|
||||
select: {
|
||||
id: true,
|
||||
date: true,
|
||||
planId: true,
|
||||
plan: {
|
||||
select: {
|
||||
year: true,
|
||||
month: true,
|
||||
},
|
||||
},
|
||||
child: {
|
||||
select: {
|
||||
firstName: true,
|
||||
@@ -175,27 +212,82 @@ export default async function KalenderPage({
|
||||
orderBy: { date: "asc" },
|
||||
});
|
||||
|
||||
const pendingSwapRows =
|
||||
!isAdmin && session.user.familyId
|
||||
? await prisma.notdienstSwapRequest.findMany({
|
||||
where: {
|
||||
kitaId: session.user.kitaId,
|
||||
status: NotdienstSwapStatus.PENDING,
|
||||
OR: [
|
||||
{ requesterFamilyId: session.user.familyId },
|
||||
{
|
||||
targetAssignment: {
|
||||
child: {
|
||||
familyId: session.user.familyId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
requesterFamilyId: true,
|
||||
message: true,
|
||||
targetAssignment: {
|
||||
select: {
|
||||
date: true,
|
||||
child: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
family: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
offeredAssignment: {
|
||||
select: {
|
||||
date: true,
|
||||
child: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
family: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
})
|
||||
: [];
|
||||
|
||||
const rsvpEvents = new Map(rsvpEventRows.map((event) => [event.id, event]));
|
||||
const mapTermin = (
|
||||
termin: (typeof confirmedTermineRows)[number],
|
||||
): CalendarListItemDto => {
|
||||
const showParticipantInfo =
|
||||
isAdmin ||
|
||||
termin.familyParticipations.some(
|
||||
(row) => row.status === EventParticipationStatus.ATTENDING,
|
||||
) ||
|
||||
termin.participations.some(
|
||||
(row) => row.status === EventParticipationStatus.ATTENDING,
|
||||
);
|
||||
const { _count, familyParticipations, ...data } = termin;
|
||||
void familyParticipations;
|
||||
return {
|
||||
...data,
|
||||
kind: "termin",
|
||||
showParticipantInfo,
|
||||
participantInfo: showParticipantInfo ? termin.participantInfo : null,
|
||||
hasRsvpResponses: _count.participations + _count.familyParticipations > 0,
|
||||
rsvpEvent: rsvpEvents.get(termin.id),
|
||||
};
|
||||
};
|
||||
const allUserTermine: CalendarListItemDto[] = [
|
||||
...confirmedTermineRows.map((termin) => ({
|
||||
...termin,
|
||||
kind: "termin" as const,
|
||||
showParticipantInfo:
|
||||
isAdmin ||
|
||||
termin.participations.some(
|
||||
(participation) =>
|
||||
participation.status === EventParticipationStatus.ATTENDING,
|
||||
),
|
||||
})),
|
||||
...myPendingTermineRows.map((termin) => ({
|
||||
...termin,
|
||||
kind: "termin" as const,
|
||||
showParticipantInfo:
|
||||
isAdmin ||
|
||||
termin.participations.some(
|
||||
(participation) =>
|
||||
participation.status === EventParticipationStatus.ATTENDING,
|
||||
),
|
||||
})),
|
||||
...confirmedTermineRows.map(mapTermin),
|
||||
...myPendingTermineRows.map(mapTermin),
|
||||
...dutyAssignmentRows.map((assignment) => {
|
||||
const isOwn = assignment.familyId === familyIdForParticipation;
|
||||
return {
|
||||
@@ -213,21 +305,61 @@ export default async function KalenderPage({
|
||||
}),
|
||||
...notdienstAssignmentRows.map((assignment) => {
|
||||
const isOwn = assignment.child.familyId === familyIdForParticipation;
|
||||
const canRequestSwap =
|
||||
!isAdmin &&
|
||||
!isOwn &&
|
||||
!!session.user.familyId &&
|
||||
assignment.date >= today;
|
||||
return {
|
||||
kind: "notdienst" as const,
|
||||
id: assignment.id,
|
||||
planId: assignment.planId,
|
||||
planYear: assignment.plan.year,
|
||||
planMonth: assignment.plan.month,
|
||||
title: isOwn
|
||||
? `Mein Notdienst (${assignment.child.firstName})`
|
||||
: `Notdienst (${assignment.child.family.name})`,
|
||||
familyId: assignment.child.familyId,
|
||||
familyName: assignment.child.family.name,
|
||||
childName: `${assignment.child.firstName} ${assignment.child.lastName}`,
|
||||
isOwn,
|
||||
canRequestSwap,
|
||||
startDate: assignment.date,
|
||||
endDate: assignment.date,
|
||||
};
|
||||
}),
|
||||
].sort((a, b) => a.startDate.getTime() - b.startDate.getTime());
|
||||
|
||||
const notdienstSwapOptions: NotdienstSwapOptionDto[] = notdienstAssignmentRows
|
||||
.filter(
|
||||
(assignment) =>
|
||||
assignment.child.familyId === familyIdForParticipation &&
|
||||
assignment.date >= today,
|
||||
)
|
||||
.map((assignment) => ({
|
||||
id: assignment.id,
|
||||
date: assignment.date,
|
||||
childName: `${assignment.child.firstName} ${assignment.child.lastName}`,
|
||||
familyName: assignment.child.family.name,
|
||||
}));
|
||||
|
||||
const pendingSwapRequests: NotdienstSwapRequestDto[] = pendingSwapRows.map(
|
||||
(request) => ({
|
||||
id: request.id,
|
||||
direction:
|
||||
request.requesterFamilyId === session.user.familyId
|
||||
? "outgoing"
|
||||
: "incoming",
|
||||
targetDate: request.targetAssignment.date,
|
||||
targetFamilyName: request.targetAssignment.child.family.name,
|
||||
targetChildName: `${request.targetAssignment.child.firstName} ${request.targetAssignment.child.lastName}`,
|
||||
offeredDate: request.offeredAssignment.date,
|
||||
offeredFamilyName: request.offeredAssignment.child.family.name,
|
||||
offeredChildName: `${request.offeredAssignment.child.firstName} ${request.offeredAssignment.child.lastName}`,
|
||||
message: request.message,
|
||||
}),
|
||||
);
|
||||
|
||||
let allPendingTermine: PendingTerminDto[] = [];
|
||||
if (isAdmin) {
|
||||
const pendingRows = await prisma.termin.findMany({
|
||||
@@ -268,9 +400,7 @@ export default async function KalenderPage({
|
||||
</p>
|
||||
<h1 className="mt-2 text-[36px] font-normal leading-tight tracking-[-0.025em] text-[var(--ink)]">
|
||||
Was steht{" "}
|
||||
<em className="font-normal italic text-[var(--accent-deep)]">
|
||||
an
|
||||
</em>
|
||||
<em className="font-normal italic text-[var(--accent-deep)]">an</em>
|
||||
?
|
||||
</h1>
|
||||
<p className="mt-2 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
@@ -305,6 +435,8 @@ export default async function KalenderPage({
|
||||
termine={allUserTermine}
|
||||
userId={session.user.id}
|
||||
isAdmin={isAdmin}
|
||||
notdienstSwapOptions={notdienstSwapOptions}
|
||||
pendingSwapRequests={pendingSwapRequests}
|
||||
/>
|
||||
) : currentTab === "anfragen" ? (
|
||||
<PendingAnfragen termine={allPendingTermine} />
|
||||
@@ -313,6 +445,8 @@ export default async function KalenderPage({
|
||||
termine={[]}
|
||||
userId={session.user.id}
|
||||
isAdmin={isAdmin}
|
||||
notdienstSwapOptions={notdienstSwapOptions}
|
||||
pendingSwapRequests={pendingSwapRequests}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -322,14 +456,14 @@ export default async function KalenderPage({
|
||||
termine={allUserTermine}
|
||||
userId={session.user.id}
|
||||
isAdmin={isAdmin}
|
||||
notdienstSwapOptions={notdienstSwapOptions}
|
||||
pendingSwapRequests={pendingSwapRequests}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
function TabBar({
|
||||
currentTab,
|
||||
overviewCount,
|
||||
@@ -405,5 +539,3 @@ function TabLink({
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { Metadata } from "next";
|
||||
import { LogOut } from "lucide-react";
|
||||
|
||||
import { signOut } from "@/auth";
|
||||
import { requireKitaSession } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SidebarNav } from "@/components/dashboard/sidebar-nav";
|
||||
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
robots: {
|
||||
@@ -15,11 +13,11 @@ export const metadata: Metadata = {
|
||||
};
|
||||
|
||||
// =====================================================================
|
||||
// Dashboard-Layout · Linke Sidebar
|
||||
// Dashboard-Layout · Responsive App Shell
|
||||
// ---------------------------------------------------------------------
|
||||
// Server Component: liest kitaId aus der Session, holt den Kita-Namen
|
||||
// aus der DB und rendert das App-Shell (Sidebar + main content area).
|
||||
// Der eigentliche Seiteninhalt kommt via {children} rein.
|
||||
// aus der DB und rendert die responsive DashboardShell (mit Desktop-Sidebar
|
||||
// und Mobile-Drawer).
|
||||
// =====================================================================
|
||||
|
||||
export default async function DashboardLayout({
|
||||
@@ -35,75 +33,20 @@ export default async function DashboardLayout({
|
||||
});
|
||||
const displayName = session.user.name ?? session.user.email ?? "Kita-Planer";
|
||||
|
||||
return (
|
||||
<div className="grid min-h-screen grid-cols-[256px_minmax(0,1fr)] bg-[var(--bg)] max-[760px]:grid-cols-1">
|
||||
{/* ── Sidebar ───────────────────────────────────────────────────── */}
|
||||
<aside className="print:hidden sticky top-0 flex h-screen shrink-0 flex-col border-r border-[var(--hairline)] bg-[var(--surface)] max-[760px]:relative max-[760px]:h-auto">
|
||||
{/* Logo / Kita-Name */}
|
||||
<div className="flex h-[82px] items-center gap-3 border-b border-[var(--hairline-soft)] px-5">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--accent-deep)] text-[13px] font-bold text-white">
|
||||
{kita.name.slice(0, 1).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold leading-none text-[var(--ink)]">
|
||||
{kita.name}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-[var(--ink-soft)]">Kita-Planer</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex-1 overflow-y-auto py-6">
|
||||
<SidebarNav role={session.user.role} />
|
||||
</div>
|
||||
|
||||
{/* Footer: User-Info + Abmelden */}
|
||||
<div className="border-t border-[var(--hairline-soft)] p-4">
|
||||
<div className="mb-3 flex items-center gap-2.5 px-1">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--accent-soft)] text-[11px] font-semibold text-[var(--accent-deep)]">
|
||||
{getInitials(displayName)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-xs font-semibold text-[var(--ink)]">
|
||||
{displayName}
|
||||
</p>
|
||||
<p className="truncate text-[11px] font-semibold uppercase text-[var(--ink-muted)]">
|
||||
{session.user.role}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<form
|
||||
action={async () => {
|
||||
async function handleSignOut() {
|
||||
"use server";
|
||||
await signOut({ redirectTo: "/" });
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-start"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Abmelden
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
|
||||
{/* ── Main Content ──────────────────────────────────────────────── */}
|
||||
<main className="min-w-0 overflow-y-auto">
|
||||
return (
|
||||
<DashboardShell
|
||||
kitaName={kita.name}
|
||||
userName={displayName}
|
||||
userRole={session.user.role}
|
||||
signOutAction={handleSignOut}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</DashboardShell>
|
||||
);
|
||||
}
|
||||
|
||||
function getInitials(value: string) {
|
||||
const parts = value.trim().split(/\s+/).filter(Boolean);
|
||||
if (parts.length >= 2) {
|
||||
return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
|
||||
}
|
||||
|
||||
return value.slice(0, 2).toUpperCase();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import Link from "next/link";
|
||||
import { requireKitaSession } from "@/lib/auth-utils";
|
||||
import { getAnnouncements } from "@/lib/announcements";
|
||||
import { NewsTicker } from "../news-ticker";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export const metadata = { title: "Mitteilungen · Kita-Planer" };
|
||||
|
||||
export default async function MitteilungenPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string }>;
|
||||
}) {
|
||||
const session = await requireKitaSession();
|
||||
const params = await searchParams;
|
||||
const parsed = Number(params.page ?? 1);
|
||||
const page =
|
||||
Number.isSafeInteger(parsed) && parsed > 0 ? Math.min(parsed, 100000) : 1;
|
||||
const pageSize = 12;
|
||||
const items = await getAnnouncements(session, {
|
||||
take: pageSize + 1,
|
||||
skip: (page - 1) * pageSize,
|
||||
});
|
||||
return (
|
||||
<div className="mx-auto max-w-[1280px] px-11 py-9 pb-16 max-[760px]:px-5">
|
||||
<header className="mb-7">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-[var(--accent-deep)]">
|
||||
SCHWARZES BRETT
|
||||
</p>
|
||||
<h1 className="mt-2 text-[36px] tracking-[-0.025em]">
|
||||
Alle{" "}
|
||||
<em className="font-normal text-[var(--accent-deep)]">
|
||||
Mitteilungen
|
||||
</em>
|
||||
</h1>
|
||||
<p className="mt-2 text-[15px] text-[var(--ink-soft)]">
|
||||
Aktuelle und ältere Meldungen für deine Empfängergruppe.
|
||||
</p>
|
||||
</header>
|
||||
<NewsTicker items={items.slice(0, pageSize)} archive />
|
||||
<nav
|
||||
aria-label="Mitteilungen durchblättern"
|
||||
className="flex items-center justify-between gap-3"
|
||||
>
|
||||
<div>
|
||||
{page > 1 ? (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/dashboard/mitteilungen?page=${page - 1}`}>
|
||||
Neuere Meldungen
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-sm text-[var(--ink-soft)]">Seite {page}</span>
|
||||
<div>
|
||||
{items.length > pageSize ? (
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/dashboard/mitteilungen?page=${page + 1}`}>
|
||||
Ältere Meldungen
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { toast } from "sonner";
|
||||
import { useState, useTransition } from "react";
|
||||
import { Bell, FileText, Megaphone } from "lucide-react";
|
||||
|
||||
@@ -26,6 +28,7 @@ export type NewsTickerItemDto = {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
excerpt: string;
|
||||
createdAt: string;
|
||||
authorName: string;
|
||||
isUnread: boolean;
|
||||
@@ -37,22 +40,32 @@ export type NewsTickerItemDto = {
|
||||
}[];
|
||||
};
|
||||
|
||||
export function NewsTicker({ items }: { items: NewsTickerItemDto[] }) {
|
||||
export function NewsTicker({
|
||||
items,
|
||||
archive = false,
|
||||
}: {
|
||||
items: NewsTickerItemDto[];
|
||||
archive?: boolean;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<NewsTickerItemDto | null>(null);
|
||||
const [readIds, setReadIds] = useState<Set<string>>(new Set());
|
||||
const [, startTransition] = useTransition();
|
||||
|
||||
if (items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function openAnnouncement(item: NewsTickerItemDto) {
|
||||
setSelected(item);
|
||||
if (!item.isUnread || readIds.has(item.id)) return;
|
||||
|
||||
setReadIds((current) => new Set(current).add(item.id));
|
||||
startTransition(async () => {
|
||||
await markAnnouncementRead(item.id);
|
||||
try {
|
||||
const result = await markAnnouncementRead(item.id);
|
||||
if (result.error) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
setReadIds((current) => new Set(current).add(item.id));
|
||||
} catch {
|
||||
toast.error("Lesestatus konnte nicht gespeichert werden.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -60,20 +73,33 @@ export function NewsTicker({ items }: { items: NewsTickerItemDto[] }) {
|
||||
<>
|
||||
<Card className="mb-8 border-[var(--good)] bg-[var(--good-soft)]">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2 text-lg">
|
||||
<Megaphone className="h-5 w-5 text-[var(--good)] [stroke-width:1.7]" />
|
||||
Schwarzes Brett
|
||||
{archive ? "Mitteilungen" : "Neues aus der Kita"}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Die neuesten offiziellen Ankündigungen deiner Kita.
|
||||
{archive
|
||||
? "Veröffentlichte Ankündigungen deiner Kita."
|
||||
: "Die neuesten offiziellen Ankündigungen deiner Kita."}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary">{items.length}</Badge>
|
||||
{archive ? (
|
||||
<Badge variant="secondary">{items.length} Meldungen</Badge>
|
||||
) : (
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href="/dashboard/mitteilungen">Alle Mitteilungen</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-3 lg:grid-cols-3">
|
||||
{items.length === 0 ? (
|
||||
<p className="col-span-full py-4 text-sm text-[var(--ink-soft)]">
|
||||
Noch keine Mitteilungen für deine Empfängergruppe.
|
||||
</p>
|
||||
) : null}
|
||||
{items.map((item) => {
|
||||
const isUnread = item.isUnread && !readIds.has(item.id);
|
||||
return (
|
||||
@@ -88,15 +114,13 @@ export function NewsTicker({ items }: { items: NewsTickerItemDto[] }) {
|
||||
<Bell className="h-3.5 w-3.5 [stroke-width:1.7]" />
|
||||
{item.createdAt}
|
||||
</div>
|
||||
{isUnread && (
|
||||
<Badge variant="success">NEU</Badge>
|
||||
)}
|
||||
{isUnread && <Badge variant="success">NEU</Badge>}
|
||||
</div>
|
||||
<h3 className="line-clamp-2 font-semibold leading-snug text-[var(--ink)]">
|
||||
{item.title}
|
||||
</h3>
|
||||
<p className="mt-2 line-clamp-3 text-sm leading-6 text-[var(--ink-soft)]">
|
||||
{item.content}
|
||||
{item.excerpt}
|
||||
</p>
|
||||
{item.attachments.length > 0 && (
|
||||
<p className="mt-3 flex items-center gap-1 text-xs font-medium text-[var(--accent-deep)]">
|
||||
@@ -111,7 +135,10 @@ export function NewsTicker({ items }: { items: NewsTickerItemDto[] }) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={!!selected} onOpenChange={(open) => !open && setSelected(null)}>
|
||||
<Dialog
|
||||
open={!!selected}
|
||||
onOpenChange={(open) => !open && setSelected(null)}
|
||||
>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
{selected && (
|
||||
<>
|
||||
@@ -137,7 +164,11 @@ export function NewsTicker({ items }: { items: NewsTickerItemDto[] }) {
|
||||
variant="outline"
|
||||
className="justify-start"
|
||||
>
|
||||
<a href={attachment.fileUrl} target="_blank" rel="noreferrer">
|
||||
<a
|
||||
href={attachment.fileUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<FileText className="h-4 w-4 [stroke-width:1.7]" />
|
||||
{attachment.fileName}
|
||||
</a>
|
||||
|
||||
@@ -18,13 +18,13 @@ import { getTargetMonthData } from "@/lib/date-utils";
|
||||
const dateKeyPattern = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const payloadSchema = z.object({
|
||||
childrenIds: z.array(z.string()).min(1),
|
||||
childrenIds: z.array(z.string().min(1).max(64)).min(1).max(20),
|
||||
dates: z.array(
|
||||
z.string().regex(dateKeyPattern).refine((value) => {
|
||||
const date = dateKeyToUtcDate(value);
|
||||
return value === date.toISOString().slice(0, 10);
|
||||
return Number.isFinite(date.getTime()) && value === date.toISOString().slice(0, 10);
|
||||
}),
|
||||
),
|
||||
).max(31),
|
||||
});
|
||||
|
||||
function dateKeyToUtcDate(dateKey: string) {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"use server";
|
||||
import { publicActionError } from "@/lib/action-error";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { requireAlarmActor } from "@/lib/alarms/auth";
|
||||
import { executeAlarmCommand } from "@/lib/alarms/service";
|
||||
import { deliverAlarmEmails } from "@/lib/alarms/email";
|
||||
|
||||
export type AlarmActionResult = {
|
||||
error?: string;
|
||||
warning?: string;
|
||||
success?: boolean;
|
||||
alarmId?: string;
|
||||
};
|
||||
export async function alarmAction(
|
||||
command: string,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<AlarmActionResult> {
|
||||
const actor = await requireAlarmActor(command !== "readNotice");
|
||||
try {
|
||||
const result = await executeAlarmCommand(actor, command, data);
|
||||
let warning: string | undefined;
|
||||
if (result.emailIds.length) {
|
||||
try {
|
||||
const delivery = await deliverAlarmEmails(result.emailIds);
|
||||
if (delivery.failed)
|
||||
warning =
|
||||
"Gespeichert. Einige E-Mails warten noch auf den Versand. Bitte den Versandstand im Alarm prüfen.";
|
||||
else if (
|
||||
process.env.NODE_ENV === "development" &&
|
||||
!process.env.RESEND_API_KEY
|
||||
)
|
||||
warning = "Gespeichert. E-Mail-Versand lokal simuliert.";
|
||||
} catch {
|
||||
warning = "Gespeichert. Der E-Mail-Versand ist noch ausstehend.";
|
||||
}
|
||||
}
|
||||
for (const path of [
|
||||
"/dashboard",
|
||||
"/dashboard/notdienst/alarm",
|
||||
"/dashboard/notdienst/plan",
|
||||
"/dashboard/kalender",
|
||||
])
|
||||
revalidatePath(path);
|
||||
revalidatePath("/alert/[token]", "page");
|
||||
return { success: true, alarmId: result.alarmId, warning };
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError)
|
||||
return {
|
||||
error: error.issues[0]?.message ?? "Bitte die Eingaben prüfen.",
|
||||
};
|
||||
const message = publicActionError(error, "");
|
||||
if (message) return { error: message };
|
||||
return { error: "Die Alarmaktion konnte nicht gespeichert werden." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Link from "next/link";
|
||||
import { requireKitaSession } from "@/lib/auth-utils";
|
||||
import { getAlarmFeed, managerRoles } from "@/lib/alarms/service";
|
||||
import {
|
||||
alarmLabel,
|
||||
durationLabel,
|
||||
dateKey,
|
||||
needsClarification,
|
||||
} from "@/lib/alarms/format";
|
||||
import { AlarmRefresh } from "./forms";
|
||||
|
||||
export async function AlarmDashboardHints() {
|
||||
const { user } = await requireKitaSession();
|
||||
if (![...managerRoles, "ELTERN"].includes(user.role)) return null;
|
||||
let alarms;
|
||||
try {
|
||||
alarms = await getAlarmFeed({
|
||||
id: user.id!,
|
||||
kitaId: user.kitaId,
|
||||
role: user.role,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!alarms.length) return null;
|
||||
return (
|
||||
<section className="mb-6 rounded-2xl border border-[var(--accent-mid)] bg-[var(--surface)] p-5">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="text-lg font-semibold">Aktuelle Notdienstalarme</h2>
|
||||
<AlarmRefresh />
|
||||
</div>
|
||||
<div className="grid gap-3">
|
||||
{alarms.map((a) => (
|
||||
<Link
|
||||
key={a.id}
|
||||
href={`/dashboard/notdienst/alarm?alarm=${a.id}`}
|
||||
className={`flex flex-wrap items-center justify-between gap-3 rounded-lg border p-3 text-sm ${needsClarification(a) ? "border-[var(--danger)] text-[var(--danger)]" : "border-[var(--hairline)]"}`}
|
||||
>
|
||||
<span>
|
||||
{dateKey(a.date).split("-").reverse().join(".")} · {a.familyName}
|
||||
<span className="mt-1 block text-xs text-[var(--ink-soft)]">
|
||||
{durationLabel(a)}
|
||||
</span>
|
||||
</span>
|
||||
<strong>{alarmLabel(a)} →</strong>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
"use client";
|
||||
import { useEffect, useId, useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { BellRing } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { clockMinute } from "@/lib/staff/calculations";
|
||||
import { alarmAction } from "./actions";
|
||||
|
||||
const control =
|
||||
"w-full rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-mid)]";
|
||||
export function AlarmRefresh() {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
if (!document.hidden) router.refresh();
|
||||
}, 30000);
|
||||
return () => clearInterval(timer);
|
||||
}, [router]);
|
||||
return (
|
||||
<Button variant="outline" size="sm" onClick={() => router.refresh()}>
|
||||
Stand aktualisieren
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
export type AlarmCandidate = { id: string; label: string; emails: string[] };
|
||||
export function AlarmCreateForm({
|
||||
candidates,
|
||||
educators,
|
||||
selected,
|
||||
}: {
|
||||
candidates: AlarmCandidate[];
|
||||
educators: { id: string; name: string }[];
|
||||
selected?: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(!!selected);
|
||||
const [assignmentId, setAssignmentId] = useState(
|
||||
candidates.find((c) => c.id === selected)?.id ?? candidates[0]?.id ?? "",
|
||||
);
|
||||
const [wholeDay, setWholeDay] = useState(true);
|
||||
const [pending, start] = useTransition();
|
||||
const [error, setError] = useState("");
|
||||
const router = useRouter();
|
||||
const prefix = useId();
|
||||
const candidate = candidates.find((c) => c.id === assignmentId);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button disabled={!candidates.length}>
|
||||
<BellRing className="mr-2 h-4 w-4" />
|
||||
Notdienstalarm auslösen
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Notdienstalarm auslösen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Die eingeteilte Familie wird per E-Mail und in der App informiert.
|
||||
Eine Antwort gilt für den Haushalt.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
setError("");
|
||||
start(async () => {
|
||||
const result = await alarmAction("create", {
|
||||
assignmentId,
|
||||
wholeDay,
|
||||
replyMinutes: Number(form.get("replyMinutes")),
|
||||
...(wholeDay
|
||||
? {}
|
||||
: {
|
||||
startMinute: clockMinute(String(form.get("start"))),
|
||||
endMinute: clockMinute(String(form.get("end"))),
|
||||
}),
|
||||
...(form.get("educatorId")
|
||||
? { educatorId: String(form.get("educatorId")) }
|
||||
: {}),
|
||||
notes: String(form.get("notes") ?? ""),
|
||||
});
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.warning) toast.warning(result.warning);
|
||||
else toast.success("Alarm ausgelöst.");
|
||||
setOpen(false);
|
||||
router.push(`/dashboard/notdienst/alarm?alarm=${result.alarmId}`);
|
||||
router.refresh();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={pending} className="grid gap-4">
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-assignment`}
|
||||
>
|
||||
Eingeteilte Familie
|
||||
<select
|
||||
id={`${prefix}-assignment`}
|
||||
className={control}
|
||||
required
|
||||
value={assignmentId}
|
||||
onChange={(event) => setAssignmentId(event.target.value)}
|
||||
>
|
||||
{candidates.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="rounded-lg bg-[var(--surface-2)] p-3 text-sm">
|
||||
<p className="font-medium">Empfänger</p>
|
||||
{candidate?.emails.length ? (
|
||||
<ul className="mt-1 grid gap-1 break-all">
|
||||
{candidate.emails.map((email) => (
|
||||
<li key={email}>{email}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="mt-1 text-[var(--danger)]">
|
||||
Keine Elternkonten hinterlegt. Bitte den Haushalt zuerst
|
||||
vervollständigen.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-duration`}
|
||||
>
|
||||
Einsatzdauer
|
||||
<select
|
||||
id={`${prefix}-duration`}
|
||||
className={control}
|
||||
value={wholeDay ? "whole" : "hours"}
|
||||
onChange={(event) =>
|
||||
setWholeDay(event.target.value === "whole")
|
||||
}
|
||||
>
|
||||
<option value="whole">Ganzer Kita-Tag</option>
|
||||
<option value="hours">Bestimmte Uhrzeiten</option>
|
||||
</select>
|
||||
</label>
|
||||
{!wholeDay && (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-start`}
|
||||
>
|
||||
Beginn
|
||||
<Input
|
||||
id={`${prefix}-start`}
|
||||
type="time"
|
||||
name="start"
|
||||
required
|
||||
defaultValue="08:00"
|
||||
/>
|
||||
</label>
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-end`}
|
||||
>
|
||||
Ende
|
||||
<Input
|
||||
id={`${prefix}-end`}
|
||||
type="time"
|
||||
name="end"
|
||||
required
|
||||
defaultValue="16:00"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-minutes`}
|
||||
>
|
||||
Antwortfrist in Minuten
|
||||
<Input
|
||||
id={`${prefix}-minutes`}
|
||||
name="replyMinutes"
|
||||
type="number"
|
||||
min={1}
|
||||
max={1440}
|
||||
step={1}
|
||||
defaultValue={30}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs leading-5 text-[var(--ink-soft)]">
|
||||
Die Frist beginnt beim Auslösen und endet spätestens mit dem
|
||||
Einsatz. Eine Absage erfordert sofort Klärung.
|
||||
</p>
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-educator`}
|
||||
>
|
||||
Ausgefallene Fachkraft (optional, intern)
|
||||
<select
|
||||
id={`${prefix}-educator`}
|
||||
className={control}
|
||||
name="educatorId"
|
||||
>
|
||||
<option value="">Ohne Zuordnung</option>
|
||||
{educators.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1.5 text-sm" htmlFor={`${prefix}-notes`}>
|
||||
Interne Notiz (optional)
|
||||
<textarea
|
||||
id={`${prefix}-notes`}
|
||||
className={control}
|
||||
name="notes"
|
||||
maxLength={500}
|
||||
rows={2}
|
||||
/>
|
||||
</label>
|
||||
<Button type="submit" disabled={!candidate?.emails.length}>
|
||||
{pending
|
||||
? "Alarm wird gespeichert …"
|
||||
: "Alarm auslösen und Familie informieren"}
|
||||
</Button>
|
||||
</fieldset>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-[var(--danger)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function AlarmCommand({
|
||||
alarmId,
|
||||
command,
|
||||
label,
|
||||
}: {
|
||||
alarmId: string;
|
||||
command: "cancel" | "recordResponse" | "approveLate";
|
||||
label: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false),
|
||||
[pending, start] = useTransition(),
|
||||
[error, setError] = useState("");
|
||||
const router = useRouter(),
|
||||
prefix = useId();
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
{label}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{label}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{command === "cancel"
|
||||
? "Alle angeschriebenen Elternkonten erhalten eine Stornierung. Ihre Rückmeldelinks erlauben danach keine weitere Antwort."
|
||||
: "Die Rückmeldung gilt für den gesamten Haushalt. Die Familie und die Koordination werden über den Stand informiert."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(event.currentTarget);
|
||||
setError("");
|
||||
start(async () => {
|
||||
const result = await alarmAction(command, {
|
||||
alarmId,
|
||||
reason: String(data.get("reason")),
|
||||
...(command === "recordResponse"
|
||||
? { approve: data.get("response") === "yes" }
|
||||
: {}),
|
||||
});
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.warning) toast.warning(result.warning);
|
||||
else toast.success("Gespeichert.");
|
||||
setOpen(false);
|
||||
router.refresh();
|
||||
});
|
||||
}}
|
||||
>
|
||||
{command === "recordResponse" && (
|
||||
<label
|
||||
className="grid gap-1.5 text-sm"
|
||||
htmlFor={`${prefix}-response`}
|
||||
>
|
||||
Telefonische Rückmeldung / Korrektur
|
||||
<select
|
||||
id={`${prefix}-response`}
|
||||
name="response"
|
||||
className={control}
|
||||
>
|
||||
<option value="yes">Haushalt übernimmt</option>
|
||||
<option value="no">Haushalt kann nicht übernehmen</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="grid gap-1.5 text-sm" htmlFor={`${prefix}-reason`}>
|
||||
Interne Begründung
|
||||
<textarea
|
||||
id={`${prefix}-reason`}
|
||||
className={control}
|
||||
name="reason"
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={500}
|
||||
rows={3}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Die Begründung bleibt intern und wird nicht per E-Mail versendet.
|
||||
</p>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-[var(--danger)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button disabled={pending} type="submit">
|
||||
{pending
|
||||
? "Wird gespeichert …"
|
||||
: command === "cancel"
|
||||
? "Alarm stornieren"
|
||||
: "Rückmeldung speichern"}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function AlarmSimpleAction({
|
||||
command,
|
||||
data,
|
||||
children,
|
||||
}: {
|
||||
command: "retry" | "readNotice";
|
||||
data: Record<string, unknown>;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const [pending, start] = useTransition();
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
start(async () => {
|
||||
const result = await alarmAction(command, data);
|
||||
if (result.error) toast.error(result.error);
|
||||
else if (result.warning) toast.warning(result.warning);
|
||||
else toast.success("Gespeichert.");
|
||||
router.refresh();
|
||||
})
|
||||
}
|
||||
>
|
||||
{pending ? "Bitte warten …" : children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
import Link from "next/link";
|
||||
import { BellRing } from "lucide-react";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireAlarmActor } from "@/lib/alarms/auth";
|
||||
import { managerRoles, importLegacyAlarms } from "@/lib/alarms/service";
|
||||
import {
|
||||
alarmLabel,
|
||||
dateKey,
|
||||
durationLabel,
|
||||
instantLabel,
|
||||
needsClarification,
|
||||
todayKey,
|
||||
} from "@/lib/alarms/format";
|
||||
import { addDays, dateOnly } from "@/lib/staff/calculations";
|
||||
import {
|
||||
AlarmCreateForm,
|
||||
AlarmCommand,
|
||||
AlarmSimpleAction,
|
||||
AlarmRefresh,
|
||||
} from "./forms";
|
||||
|
||||
export const metadata = { title: "Notdienstalarm · Kita-Planer" };
|
||||
const historyLabels: Record<string, string> = {
|
||||
CONFIRMED: "Übernahme bestätigt",
|
||||
DECLINED: "Absage",
|
||||
LATE_CONFIRMATION: "Verspätete Zusage – Freigabe erforderlich",
|
||||
};
|
||||
export default async function AlarmPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ alarm?: string; assignment?: string }>;
|
||||
}) {
|
||||
const actor = await requireAlarmActor(false),
|
||||
manager = managerRoles.includes(actor.role);
|
||||
const params = await searchParams,
|
||||
now = new Date(),
|
||||
today = todayKey(now);
|
||||
if (manager) await importLegacyAlarms(actor.kitaId);
|
||||
const user = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: actor.id },
|
||||
select: { familyId: true },
|
||||
});
|
||||
const [kita, alarms, assignments, educators, notifications] =
|
||||
await Promise.all([
|
||||
prisma.kita.findUniqueOrThrow({
|
||||
where: { id: actor.kitaId },
|
||||
select: { name: true, notdienstModuleEnabled: true },
|
||||
}),
|
||||
prisma.notdienstAlarm.findMany({
|
||||
where: {
|
||||
kitaId: actor.kitaId,
|
||||
...(manager ? {} : { familyId: user.familyId ?? "" }),
|
||||
...(params.alarm
|
||||
? { id: params.alarm }
|
||||
: { date: { gte: dateOnly(addDays(today, -30)) } }),
|
||||
},
|
||||
include: {
|
||||
recipients: {
|
||||
include: { user: { select: { email: true, firstName: true } } },
|
||||
},
|
||||
emails: { orderBy: { createdAt: "desc" } },
|
||||
history: manager
|
||||
? { orderBy: { createdAt: "desc" }, take: 20 }
|
||||
: false,
|
||||
},
|
||||
orderBy: [{ date: "desc" }, { triggeredAt: "desc" }],
|
||||
take: 100,
|
||||
}),
|
||||
manager
|
||||
? prisma.notdienstAssignment.findMany({
|
||||
where: {
|
||||
kitaId: actor.kitaId,
|
||||
date: { gte: dateOnly(today), lt: dateOnly(addDays(today, 93)) },
|
||||
plan: { status: "PUBLISHED" },
|
||||
alarms: { none: { activeAssignmentId: { not: null } } },
|
||||
},
|
||||
include: {
|
||||
child: {
|
||||
include: {
|
||||
family: {
|
||||
include: {
|
||||
users: {
|
||||
where: { role: "ELTERN", kitaId: actor.kitaId },
|
||||
select: { email: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { date: "asc" },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
manager
|
||||
? prisma.educator.findMany({
|
||||
where: { kitaId: actor.kitaId, active: true },
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
orderBy: { lastName: "asc" },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
prisma.notdienstAlarmNotification.findMany({
|
||||
where: {
|
||||
userId: actor.id,
|
||||
alarm: {
|
||||
kitaId: actor.kitaId,
|
||||
...(manager ? {} : { familyId: user.familyId ?? "" }),
|
||||
},
|
||||
readAt: null,
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
}),
|
||||
]);
|
||||
const candidates = assignments.map((a) => ({
|
||||
id: a.id,
|
||||
label: `${dateKey(a.date).split("-").reverse().join(".")} · ${a.child.family.name}`,
|
||||
emails: a.child.family.users.map((u) => u.email),
|
||||
}));
|
||||
return (
|
||||
<div className="mx-auto max-w-[1280px] px-11 py-9 pb-16 max-[760px]:px-5">
|
||||
<header className="mb-7 flex flex-wrap items-end justify-between gap-5">
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-[var(--accent-deep)]">
|
||||
NOTDIENST · {kita.name}
|
||||
</p>
|
||||
<h1 className="mt-2 text-4xl tracking-tight text-[var(--ink)]">
|
||||
Notdienst
|
||||
<span className="italic text-[var(--accent-deep)]">alarm</span>
|
||||
</h1>
|
||||
<p className="mt-3 max-w-2xl text-sm leading-6 text-[var(--ink-soft)]">
|
||||
{manager
|
||||
? "Familien anfragen, Rückmeldungen verfolgen und offene Einsätze klären."
|
||||
: "Eure Rückmeldung gilt für den gesamten Haushalt."}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<AlarmRefresh />
|
||||
{manager && kita.notdienstModuleEnabled && (
|
||||
<AlarmCreateForm
|
||||
candidates={candidates}
|
||||
educators={educators.map((e) => ({
|
||||
id: e.id,
|
||||
name: `${e.firstName} ${e.lastName}`,
|
||||
}))}
|
||||
selected={params.assignment}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{manager &&
|
||||
(!process.env.NOTDIENST_JOB_SECRET ||
|
||||
process.env.NOTDIENST_JOB_SECRET.length < 32) && (
|
||||
<p className="mb-6 rounded-xl border border-[var(--hairline)] bg-[var(--surface-2)] p-4 text-sm leading-6">
|
||||
Die automatische Fristprüfung ist noch nicht eingerichtet. Für
|
||||
Erinnerungen bei geschlossener App muss die Hosting-Konfiguration
|
||||
ergänzt werden. Fristabläufe sind hier bereits sichtbar.
|
||||
</p>
|
||||
)}
|
||||
{!kita.notdienstModuleEnabled && (
|
||||
<p className="mb-6 text-sm">
|
||||
Das Notdienstmodul ist deaktiviert; vorhandene Alarme bleiben
|
||||
einsehbar.
|
||||
</p>
|
||||
)}
|
||||
{notifications.length > 0 && (
|
||||
<details className="mb-6 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-4">
|
||||
<summary className="cursor-pointer text-sm font-semibold">
|
||||
{notifications.length} neue Hinweise
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
{notifications.map((n) => (
|
||||
<div
|
||||
key={n.id}
|
||||
className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--hairline-soft)] pt-3"
|
||||
>
|
||||
<Link
|
||||
className="max-w-3xl text-sm underline decoration-[var(--accent-mid)] underline-offset-4"
|
||||
href={`/dashboard/notdienst/alarm?alarm=${n.alarmId}`}
|
||||
>
|
||||
{n.message}
|
||||
</Link>
|
||||
<AlarmSimpleAction command="readNotice" data={{ id: n.id }}>
|
||||
Gelesen
|
||||
</AlarmSimpleAction>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
{params.alarm && (
|
||||
<Link
|
||||
className="mb-5 inline-block text-sm text-[var(--accent-deep)] underline"
|
||||
href="/dashboard/notdienst/alarm"
|
||||
>
|
||||
Alle Alarme anzeigen
|
||||
</Link>
|
||||
)}
|
||||
{manager && !candidates.length && !params.alarm && (
|
||||
<p className="mb-5 text-sm text-[var(--ink-soft)]">
|
||||
Neue Alarme benötigen eine aktuelle oder zukünftige Einteilung in
|
||||
einem veröffentlichten Plan.{" "}
|
||||
<Link href="/dashboard/notdienst/plan" className="underline">
|
||||
Notdienstplan öffnen
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-5">
|
||||
{alarms.length ? (
|
||||
alarms.map((a) => {
|
||||
const clarify = needsClarification(a, now),
|
||||
ended = a.expiresAt <= now;
|
||||
const pending = a.emails.filter((e) => !e.sentAt && !e.skippedAt);
|
||||
const ownRecipient = a.recipients.find(
|
||||
(r) => r.userId === actor.id,
|
||||
);
|
||||
return (
|
||||
<article
|
||||
key={a.id}
|
||||
id={`alarm-${a.id}`}
|
||||
className={`overflow-hidden rounded-2xl border bg-[var(--surface)] ${clarify ? "border-[var(--danger)]" : "border-[var(--hairline)]"}`}
|
||||
>
|
||||
<div
|
||||
className={`flex flex-wrap items-start justify-between gap-4 border-b border-[var(--hairline-soft)] p-5 sm:p-6 ${clarify ? "bg-[var(--surface-2)]" : ""}`}
|
||||
>
|
||||
<div>
|
||||
<p className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-[var(--ink-soft)]">
|
||||
<BellRing className="h-4 w-4" />
|
||||
{dateKey(a.date) === today ? "Heute · " : ""}
|
||||
{dateKey(a.date).split("-").reverse().join(".")}
|
||||
</p>
|
||||
<h2 className="mt-2 text-2xl">{a.familyName}</h2>
|
||||
<p className="mt-1 text-sm text-[var(--ink-soft)]">
|
||||
{durationLabel(a)}
|
||||
{ended ? " · Einsatz beendet" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className={`max-w-full rounded-full border px-3 py-1.5 text-xs font-semibold ${clarify ? "border-[var(--danger)] text-[var(--danger)]" : "border-[var(--accent-mid)] bg-[var(--accent-soft)] text-[var(--accent-deep)]"}`}
|
||||
>
|
||||
{alarmLabel(a, now)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-5 p-5 sm:p-6">
|
||||
<div className="flex flex-wrap gap-x-8 gap-y-3 text-sm">
|
||||
<p>
|
||||
<span className="text-[var(--ink-muted)]">
|
||||
Antwortfrist
|
||||
</span>
|
||||
<br />
|
||||
<strong>{instantLabel(a.deadline)} Uhr</strong>
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-[var(--ink-muted)]">Ausgelöst</span>
|
||||
<br />
|
||||
{instantLabel(a.triggeredAt)} Uhr
|
||||
</p>
|
||||
{a.respondedAt && (
|
||||
<p>
|
||||
<span className="text-[var(--ink-muted)]">
|
||||
Rückmeldung
|
||||
</span>
|
||||
<br />
|
||||
{instantLabel(a.respondedAt)} Uhr ·{" "}
|
||||
{a.responseSource === "PHONE"
|
||||
? "Telefonisch dokumentiert"
|
||||
: a.responseSource === "COORDINATION"
|
||||
? "Freigabe durch Koordination"
|
||||
: a.responseSource === "LEGACY"
|
||||
? "Bisherige Alarmierung"
|
||||
: "Haushaltsantwort"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{manager ? (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{a.status === "LATE_CONFIRMATION" && !ended && (
|
||||
<AlarmCommand
|
||||
command="approveLate"
|
||||
alarmId={a.id}
|
||||
label="Verspätete Zusage freigeben"
|
||||
/>
|
||||
)}
|
||||
{a.status !== "CANCELLED" && !ended && (
|
||||
<AlarmCommand
|
||||
command="recordResponse"
|
||||
alarmId={a.id}
|
||||
label="Telefonische Rückmeldung / Korrektur"
|
||||
/>
|
||||
)}
|
||||
{a.status !== "CANCELLED" && (
|
||||
<AlarmCommand
|
||||
command="cancel"
|
||||
alarmId={a.id}
|
||||
label="Alarm stornieren"
|
||||
/>
|
||||
)}
|
||||
{pending.length > 0 && (
|
||||
<AlarmSimpleAction
|
||||
command="retry"
|
||||
data={{ alarmId: a.id }}
|
||||
>
|
||||
Ausstehende E-Mails erneut senden ({pending.length})
|
||||
</AlarmSimpleAction>
|
||||
)}
|
||||
</div>
|
||||
{clarify && (
|
||||
<p className="rounded-lg bg-[var(--surface-2)] p-3 text-sm leading-6">
|
||||
Bitte den Haushalt kontaktieren oder Ersatz manuell
|
||||
organisieren. Weitere Familien werden nicht
|
||||
automatisch alarmiert.
|
||||
</p>
|
||||
)}
|
||||
<details className="border-t border-[var(--hairline-soft)] pt-4">
|
||||
<summary className="cursor-pointer text-sm font-medium">
|
||||
Versandstand (
|
||||
{a.emails.filter((e) => e.sentAt).length} angenommen,{" "}
|
||||
{pending.length} ausstehend)
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-2 text-sm">
|
||||
{a.emails.map((e) => (
|
||||
<p key={e.id} className="break-all">
|
||||
{a.recipients.find((r) => r.userId === e.userId)
|
||||
?.user.email ?? "Koordination / Admin"}{" "}
|
||||
·{" "}
|
||||
{e.kind === "REQUEST"
|
||||
? "Anfrage"
|
||||
: e.kind === "CANCEL"
|
||||
? "Stornierung"
|
||||
: "Hinweis"}
|
||||
:{" "}
|
||||
{e.sentAt
|
||||
? "Vom Maildienst angenommen"
|
||||
: e.skippedAt
|
||||
? "Nicht mehr erforderlich / Empfänger geändert"
|
||||
: e.failed
|
||||
? "Versand fehlgeschlagen – wiederholbar"
|
||||
: "Versand ausstehend"}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
<details className="border-t border-[var(--hairline-soft)] pt-4">
|
||||
<summary className="cursor-pointer text-sm font-medium">
|
||||
Interne Details und Verlauf
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-2 text-sm">
|
||||
{a.educatorId && (
|
||||
<p>
|
||||
Ausgefallene Fachkraft:{" "}
|
||||
{educators.find((e) => e.id === a.educatorId)
|
||||
?.firstName ??
|
||||
"Ehemalige / inaktive Fachkraft"}{" "}
|
||||
{educators.find((e) => e.id === a.educatorId)
|
||||
?.lastName ?? ""}
|
||||
</p>
|
||||
)}
|
||||
{a.notes && <p>Interne Notiz: {a.notes}</p>}
|
||||
{a.cancelReason && (
|
||||
<p>Stornierungsgrund: {a.cancelReason}</p>
|
||||
)}
|
||||
{a.history.map((h) => (
|
||||
<p key={h.id}>
|
||||
{instantLabel(h.createdAt)} · {h.action}:{" "}
|
||||
{historyLabels[h.details] ?? h.details}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{ownRecipient && a.status === "PENDING" && !ended && (
|
||||
<Link
|
||||
className="inline-flex w-fit rounded-lg bg-[var(--accent-deep)] px-4 py-2 text-sm font-semibold text-white"
|
||||
href={`/alert/${ownRecipient.token}`}
|
||||
>
|
||||
Für unseren Haushalt antworten
|
||||
</Link>
|
||||
)}
|
||||
<p className="text-sm text-[var(--ink-soft)]">
|
||||
{a.status === "LATE_CONFIRMATION"
|
||||
? "Eure verspätete Zusage wartet auf Freigabe durch die Koordination."
|
||||
: a.status === "CONFIRMED"
|
||||
? "Die Kita rechnet mit euch. Änderungen bitte mit der Koordination klären."
|
||||
: a.status === "CANCELLED"
|
||||
? "Ihr müsst für diesen Alarm nicht einspringen."
|
||||
: a.status === "DECLINED"
|
||||
? "Eure Absage ist gespeichert. Die Koordination organisiert Ersatz."
|
||||
: "Eine Antwort eines Elternteils gilt für euren ganzen Haushalt."}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="rounded-2xl border border-[var(--hairline)] bg-[var(--surface)] p-8 text-sm text-[var(--ink-soft)]">
|
||||
{params.alarm
|
||||
? "Kein zugänglicher Alarm gefunden."
|
||||
: "Noch keine Notdienstalarme in diesem Zeitraum."}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
"use server";
|
||||
|
||||
import { UserFacingError, publicActionError } from "@/lib/action-error";
|
||||
import { dateOnlySchema, validPlanMonth } from "@/lib/date-schema";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { createElement } from "react";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { NotdienstPlanStatus, UserRole } from "@prisma/client";
|
||||
@@ -11,7 +14,12 @@ import { prisma } from "@/lib/prisma";
|
||||
import { getTargetMonthData, getWorkingDaysOfMonth } from "@/lib/date-utils";
|
||||
import { getAppEmailConfigError, sendAppEmail } from "@/lib/mail";
|
||||
import { NotdienstAvailabilityReminderEmail } from "@/emails/NotdienstAvailabilityReminderEmail";
|
||||
import { NotdienstAssignmentEmail } from "@/emails/NotdienstAssignmentEmail";
|
||||
import { NotdienstAssignmentChangeEmail } from "@/emails/NotdienstAssignmentChangeEmail";
|
||||
import { requireAlarmActor } from "@/lib/alarms/auth";
|
||||
import {
|
||||
validateAlarmActor,
|
||||
assertAssignmentNotAlarmed,
|
||||
} from "@/lib/alarms/service";
|
||||
|
||||
// =====================================================================
|
||||
// /dashboard/notdienst/plan · Server Actions
|
||||
@@ -32,6 +40,8 @@ export async function generatePlanAction(year?: number, month?: number) {
|
||||
targetMonth = data.targetMonth;
|
||||
}
|
||||
|
||||
if (!validPlanMonth(targetYear, targetMonth)) return { error: "Ungültiger Planungsmonat." };
|
||||
|
||||
// Prüfen, ob schon ein Plan existiert
|
||||
const existingPlan = await prisma.notdienstPlan.findUnique({
|
||||
where: {
|
||||
@@ -153,57 +163,71 @@ export async function updateAssignmentAction(
|
||||
date: string,
|
||||
newChildId: string | null,
|
||||
) {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId!;
|
||||
const actor = await requireAlarmActor();
|
||||
const kitaId = actor.kitaId;
|
||||
|
||||
if (!dateOnlySchema.safeParse(date).success) return { error: "Ungültiges Datum." };
|
||||
const [yr, mo, dy] = date.slice(0, 10).split("-").map(Number);
|
||||
const parsedDate = new Date(Date.UTC(yr, mo - 1, dy));
|
||||
|
||||
try {
|
||||
const { shouldSendEmails, assignedChildInfo } = await prisma.$transaction(async (tx) => {
|
||||
let txShouldSendEmails = false;
|
||||
let txAssignedChildInfo: {
|
||||
parentEmails: string[];
|
||||
parentNames: string[];
|
||||
dateLabel: string;
|
||||
} | null = null;
|
||||
|
||||
const notifications = await prisma.$transaction(
|
||||
async (tx) => {
|
||||
await validateAlarmActor(tx, actor);
|
||||
const plan = await tx.notdienstPlan.findUnique({
|
||||
where: { id: planId, kitaId },
|
||||
});
|
||||
|
||||
if (!plan) {
|
||||
throw new Error("Plan nicht gefunden.");
|
||||
throw new UserFacingError("Plan nicht gefunden.");
|
||||
}
|
||||
|
||||
const isDraft = plan.status === NotdienstPlanStatus.DRAFT;
|
||||
const isPublished = plan.status === NotdienstPlanStatus.PUBLISHED;
|
||||
|
||||
if (!isDraft && !isPublished) {
|
||||
throw new Error("Plan kann nicht bearbeitet werden.");
|
||||
throw new UserFacingError("Plan kann nicht bearbeitet werden.");
|
||||
}
|
||||
|
||||
if (isPublished) {
|
||||
const today = new Date();
|
||||
const todayUtc = new Date(
|
||||
Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()),
|
||||
);
|
||||
if (parsedDate < todayUtc) {
|
||||
throw new UserFacingError(
|
||||
"Vergangene Notdienste können nicht geändert werden.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Wenn der Plan bereits veröffentlicht ist, dürfen nur unbesetzte Termine geändert werden.
|
||||
// Ein Termin gilt als "unbesetzt", wenn am Veröffentlichungstag kein Assignment existierte
|
||||
// bzw. das Assignment erst nach dem Veröffentlichungs-Zeitpunkt erstellt wurde.
|
||||
const existingAssignment = await tx.notdienstAssignment.findFirst({
|
||||
where: { planId, date: parsedDate },
|
||||
include: {
|
||||
child: {
|
||||
include: {
|
||||
family: {
|
||||
include: {
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (isPublished && existingAssignment) {
|
||||
if (!plan.publishedAt || existingAssignment.createdAt <= plan.publishedAt) {
|
||||
throw new Error("In einem bereits veröffentlichten Plan können nur unbesetzte Termine geändert werden.");
|
||||
}
|
||||
}
|
||||
let newChild: {
|
||||
id: string;
|
||||
family: {
|
||||
users: { email: string; firstName: string; lastName: string }[];
|
||||
};
|
||||
} | null = null;
|
||||
|
||||
// Altes Assignment für diesen Tag löschen
|
||||
await tx.notdienstAssignment.deleteMany({
|
||||
where: { planId, date: parsedDate },
|
||||
});
|
||||
|
||||
// Neues anlegen, falls ausgewählt
|
||||
if (newChildId) {
|
||||
const child = await tx.child.findFirst({
|
||||
newChild = await tx.child.findFirst({
|
||||
where: {
|
||||
id: newChildId,
|
||||
kitaId,
|
||||
@@ -213,7 +237,7 @@ export async function updateAssignmentAction(
|
||||
family: {
|
||||
include: {
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN },
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
select: { email: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
@@ -221,10 +245,30 @@ export async function updateAssignmentAction(
|
||||
},
|
||||
});
|
||||
|
||||
if (!child) {
|
||||
throw new Error("Kind gehört nicht zu dieser Kita.");
|
||||
if (!newChild) {
|
||||
throw new UserFacingError("Kind gehört nicht zu dieser Kita.");
|
||||
}
|
||||
}
|
||||
|
||||
if (existingAssignment?.childId === newChildId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (existingAssignment)
|
||||
await assertAssignmentNotAlarmed(tx, existingAssignment.id, kitaId);
|
||||
|
||||
if (!newChildId) {
|
||||
if (existingAssignment) {
|
||||
await tx.notdienstAssignment.delete({
|
||||
where: { id: existingAssignment.id },
|
||||
});
|
||||
}
|
||||
} else if (existingAssignment) {
|
||||
await tx.notdienstAssignment.update({
|
||||
where: { id: existingAssignment.id },
|
||||
data: { childId: newChildId },
|
||||
});
|
||||
} else {
|
||||
await tx.notdienstAssignment.create({
|
||||
data: {
|
||||
kitaId,
|
||||
@@ -233,62 +277,127 @@ export async function updateAssignmentAction(
|
||||
date: parsedDate,
|
||||
},
|
||||
});
|
||||
|
||||
// Wenn der Plan bereits veröffentlicht ist, bereiten wir E-Mail-Benachrichtigungen vor
|
||||
if (isPublished) {
|
||||
const parents = child.family.users.filter((u) => !!u.email);
|
||||
if (parents.length > 0) {
|
||||
const localFormatDate = new Date(yr, mo - 1, dy);
|
||||
txAssignedChildInfo = {
|
||||
parentEmails: parents.map((p) => p.email!),
|
||||
parentNames: parents.map((p) => `${p.firstName} ${p.lastName}`),
|
||||
dateLabel: format(localFormatDate, "EEEE, dd. MMMM yyyy", { locale: de }),
|
||||
};
|
||||
txShouldSendEmails = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
shouldSendEmails: txShouldSendEmails,
|
||||
assignedChildInfo: txAssignedChildInfo,
|
||||
};
|
||||
if (existingAssignment) {
|
||||
await tx.notdienstSwapRequest.updateMany({
|
||||
where: {
|
||||
kitaId,
|
||||
status: "PENDING",
|
||||
OR: [
|
||||
{ targetAssignmentId: existingAssignment.id },
|
||||
{ offeredAssignmentId: existingAssignment.id },
|
||||
],
|
||||
},
|
||||
data: {
|
||||
status: "CANCELLED",
|
||||
respondedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!isPublished) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dateLabel = format(
|
||||
new Date(yr, mo - 1, dy),
|
||||
"EEEE, dd. MMMM yyyy",
|
||||
{ locale: de },
|
||||
);
|
||||
const messages: {
|
||||
parentEmails: string[];
|
||||
parentNames: string[];
|
||||
subject: string;
|
||||
heading: string;
|
||||
preview: string;
|
||||
body: string;
|
||||
dateLabel: string;
|
||||
}[] = [];
|
||||
|
||||
if (existingAssignment) {
|
||||
const oldParents = existingAssignment.child.family.users.filter(
|
||||
(u) => !!u.email,
|
||||
);
|
||||
if (oldParents.length > 0) {
|
||||
messages.push({
|
||||
parentEmails: oldParents.map((p) => p.email),
|
||||
parentNames: oldParents.map(
|
||||
(p) => `${p.firstName} ${p.lastName}`,
|
||||
),
|
||||
subject: `Notdienst-Einteilung geändert am ${dateLabel}`,
|
||||
heading: "Notdienst wurde geändert",
|
||||
preview: `Deine Notdienst-Einteilung am ${dateLabel} wurde geändert.`,
|
||||
body: "Du bist für diesen Notdienst nicht mehr eingeteilt.",
|
||||
dateLabel,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (newChild && existingAssignment?.childId !== newChild.id) {
|
||||
const newParents = newChild.family.users.filter((u) => !!u.email);
|
||||
if (newParents.length > 0) {
|
||||
messages.push({
|
||||
parentEmails: newParents.map((p) => p.email),
|
||||
parentNames: newParents.map(
|
||||
(p) => `${p.firstName} ${p.lastName}`,
|
||||
),
|
||||
subject: `Notdienst-Einteilung am ${dateLabel}`,
|
||||
heading: "Neuer Notdienst-Termin zugewiesen",
|
||||
preview: `Du wurdest für den Notdienst am ${dateLabel} eingeteilt.`,
|
||||
body: "Du wurdest für folgenden Tag für den Notdienst eingeteilt.",
|
||||
dateLabel,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
},
|
||||
{ isolationLevel: "Serializable" },
|
||||
);
|
||||
|
||||
// E-Mails außerhalb der DB-Transaktion senden
|
||||
if (shouldSendEmails && assignedChildInfo) {
|
||||
if (notifications.length > 0) {
|
||||
const kita = await prisma.kita.findUnique({
|
||||
where: { id: kitaId },
|
||||
select: { name: true },
|
||||
});
|
||||
|
||||
if (kita) {
|
||||
const BASE_URL = process.env.NEXTAUTH_URL ?? process.env.AUTH_URL ?? "http://localhost:3000";
|
||||
const BASE_URL =
|
||||
process.env.NEXTAUTH_URL ??
|
||||
process.env.AUTH_URL ??
|
||||
"http://localhost:3000";
|
||||
const link = `${BASE_URL}/dashboard/notdienst`;
|
||||
|
||||
for (let i = 0; i < assignedChildInfo.parentEmails.length; i++) {
|
||||
const email = assignedChildInfo.parentEmails[i];
|
||||
const name = assignedChildInfo.parentNames[i];
|
||||
for (const notification of notifications) {
|
||||
for (let i = 0; i < notification.parentEmails.length; i++) {
|
||||
const email = notification.parentEmails[i];
|
||||
const name = notification.parentNames[i];
|
||||
|
||||
await sendAppEmail({
|
||||
to: email,
|
||||
subject: `Notdienst-Einteilung am ${assignedChildInfo.dateLabel}`,
|
||||
react: createElement(NotdienstAssignmentEmail, {
|
||||
subject: notification.subject,
|
||||
react: createElement(NotdienstAssignmentChangeEmail, {
|
||||
parentName: name,
|
||||
kitaName: kita.name,
|
||||
dateLabel: assignedChildInfo.dateLabel,
|
||||
heading: notification.heading,
|
||||
preview: notification.preview,
|
||||
body: notification.body,
|
||||
dateLabel: notification.dateLabel,
|
||||
link,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/dashboard/notdienst/plan");
|
||||
revalidatePath("/dashboard/kalender");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: error instanceof Error ? error.message : "Update fehlgeschlagen.",
|
||||
error: publicActionError(error, "Update fehlgeschlagen."),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -303,6 +412,8 @@ export async function updateKitaNotdienstSettingsAction(
|
||||
return { error: "Kein Mandant zugeordnet." };
|
||||
}
|
||||
|
||||
if (!Number.isInteger(minPerChild) || minPerChild < 1 || minPerChild > 31 || !Number.isInteger(reminderDays) || reminderDays < 0 || reminderDays > 31) return { error: "Ungültige Einstellungen." };
|
||||
|
||||
try {
|
||||
await prisma.kita.update({
|
||||
where: { id: kitaId },
|
||||
@@ -320,13 +431,18 @@ export async function updateKitaNotdienstSettingsAction(
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendNotdienstRemindersAction(year: number, month: number) {
|
||||
export async function sendNotdienstRemindersAction(
|
||||
year: number,
|
||||
month: number,
|
||||
) {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId;
|
||||
if (!kitaId) {
|
||||
return { error: "Kein Mandant zugeordnet." };
|
||||
}
|
||||
|
||||
if (!validPlanMonth(year, month)) return { error: "Ungültiger Planungsmonat." };
|
||||
if (!(await rateLimit(`notdienst-reminders:${kitaId}`, 3, 3600)).allowed) return { error: "Zu viele Erinnerungen. Bitte später erneut versuchen." };
|
||||
const mailConfigError = getAppEmailConfigError();
|
||||
if (mailConfigError) {
|
||||
return { error: mailConfigError };
|
||||
@@ -350,7 +466,7 @@ export async function sendNotdienstRemindersAction(year: number, month: number)
|
||||
},
|
||||
include: {
|
||||
users: {
|
||||
where: { role: UserRole.ELTERN },
|
||||
where: { role: UserRole.ELTERN, emailVerifiedAt: { not: null }, disabledAt: null, privacyPolicyAcceptedAt: { not: null } },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -376,7 +492,9 @@ export async function sendNotdienstRemindersAction(year: number, month: number)
|
||||
},
|
||||
});
|
||||
|
||||
const respondedFamilyIds = new Set(respondedFamilies.map((a) => a.child.familyId));
|
||||
const respondedFamilyIds = new Set(
|
||||
respondedFamilies.map((a) => a.child.familyId),
|
||||
);
|
||||
|
||||
// 4. Find open families (not responded yet)
|
||||
const openFamilies = families.filter((f) => !respondedFamilyIds.has(f.id));
|
||||
@@ -388,7 +506,10 @@ export async function sendNotdienstRemindersAction(year: number, month: number)
|
||||
// 5. Build emails list and send
|
||||
const monthDate = new Date(year, month - 1, 1);
|
||||
const monthLabel = format(monthDate, "MMMM yyyy", { locale: de });
|
||||
const BASE_URL = process.env.NEXTAUTH_URL ?? process.env.AUTH_URL ?? "http://localhost:3000";
|
||||
const BASE_URL =
|
||||
process.env.NEXTAUTH_URL ??
|
||||
process.env.AUTH_URL ??
|
||||
"http://localhost:3000";
|
||||
const link = `${BASE_URL}/dashboard/notdienst`;
|
||||
|
||||
let sentCount = 0;
|
||||
@@ -410,7 +531,10 @@ export async function sendNotdienstRemindersAction(year: number, month: number)
|
||||
if (result.success) {
|
||||
sentCount++;
|
||||
} else {
|
||||
console.error(`E-Mail konnte nicht an ${parent.email} gesendet werden:`, result.error);
|
||||
console.error(
|
||||
`E-Mail konnte nicht an ${parent.email} gesendet werden:`,
|
||||
result.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -437,11 +561,13 @@ export async function resetPlanAction(planId: string) {
|
||||
});
|
||||
|
||||
if (!plan) {
|
||||
throw new Error("Plan nicht gefunden.");
|
||||
throw new UserFacingError("Plan nicht gefunden.");
|
||||
}
|
||||
|
||||
if (plan.status !== NotdienstPlanStatus.DRAFT) {
|
||||
throw new Error("Nur Pläne im Entwurfsstatus können zurückgesetzt werden.");
|
||||
throw new UserFacingError(
|
||||
"Nur Pläne im Entwurfsstatus können zurückgesetzt werden.",
|
||||
);
|
||||
}
|
||||
|
||||
// Delete all assignments
|
||||
@@ -459,7 +585,8 @@ export async function resetPlanAction(planId: string) {
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Zurücksetzen des Plans:", error);
|
||||
return { error: error instanceof Error ? error.message : "Fehler beim Zurücksetzen des Plans." };
|
||||
return {
|
||||
error: publicActionError(error, "Fehler beim Zurücksetzen des Plans."),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import Link from "next/link";
|
||||
import { addMonths, getYear, getMonth, format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { TerminType, UserRole } from "@prisma/client";
|
||||
import { TerminType } from "@prisma/client";
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
|
||||
import { requireRole } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getWorkingDaysOfMonth } from "@/lib/date-utils";
|
||||
import { PlanView } from "./plan-view";
|
||||
import { SettingsModal } from "./_components/settings-modal";
|
||||
import { requireAlarmActor } from "@/lib/alarms/auth";
|
||||
import { todayKey } from "@/lib/alarms/format";
|
||||
|
||||
export const metadata = { title: "Plan-Generierung · Kita-Planer" };
|
||||
|
||||
@@ -17,14 +18,18 @@ export default async function PlanungsZentralePage({
|
||||
}: {
|
||||
searchParams: Promise<{ year?: string; month?: string }>;
|
||||
}) {
|
||||
const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
|
||||
const kitaId = session.user.kitaId!;
|
||||
const actor = await requireAlarmActor();
|
||||
const kitaId = actor.kitaId;
|
||||
|
||||
const resolvedSearchParams = await searchParams;
|
||||
const now = new Date();
|
||||
const nextMonth = addMonths(now, 1);
|
||||
const targetYear = resolvedSearchParams.year ? parseInt(resolvedSearchParams.year, 10) : getYear(nextMonth);
|
||||
const targetMonth = resolvedSearchParams.month ? parseInt(resolvedSearchParams.month, 10) : (getMonth(nextMonth) + 1);
|
||||
const targetYear = resolvedSearchParams.year
|
||||
? parseInt(resolvedSearchParams.year, 10)
|
||||
: getYear(nextMonth);
|
||||
const targetMonth = resolvedSearchParams.month
|
||||
? parseInt(resolvedSearchParams.month, 10)
|
||||
: getMonth(nextMonth) + 1;
|
||||
|
||||
const monthDate = new Date(targetYear, targetMonth - 1, 1);
|
||||
const monthName = format(monthDate, "MMMM", { locale: de });
|
||||
@@ -33,7 +38,8 @@ export default async function PlanungsZentralePage({
|
||||
const monthStart = new Date(targetYear, targetMonth - 1, 1);
|
||||
const monthEnd = new Date(targetYear, targetMonth, 1);
|
||||
|
||||
const [plan, families, availabilities, closureCount, kita] = await Promise.all([
|
||||
const [plan, families, availabilities, closureCount, kita] =
|
||||
await Promise.all([
|
||||
prisma.notdienstPlan.findUnique({
|
||||
where: {
|
||||
kitaId_year_month: { kitaId, year: targetYear, month: targetMonth },
|
||||
@@ -48,6 +54,10 @@ export default async function PlanungsZentralePage({
|
||||
childId: true,
|
||||
date: true,
|
||||
createdAt: true,
|
||||
alarms: {
|
||||
where: { activeAssignmentId: { not: null } },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -179,7 +189,7 @@ export default async function PlanungsZentralePage({
|
||||
// Wir mappen die Assignments auf die Werktage
|
||||
const daysWithAssignments = workingDays.map((day) => {
|
||||
const assignment = plan?.assignments.find(
|
||||
(a) => a.date.getTime() === day.getTime()
|
||||
(a) => a.date.getTime() === day.getTime(),
|
||||
);
|
||||
const isOriginallyUnassigned =
|
||||
!assignment ||
|
||||
@@ -190,6 +200,11 @@ export default async function PlanungsZentralePage({
|
||||
assignmentId: assignment?.id || null,
|
||||
childId: assignment?.childId || null,
|
||||
isOriginallyUnassigned: !!isOriginallyUnassigned,
|
||||
activeAlarmId: assignment?.alarms[0]?.id ?? null,
|
||||
canAlarm:
|
||||
!!assignment &&
|
||||
plan?.status === "PUBLISHED" &&
|
||||
day.toISOString().slice(0, 10) >= todayKey(),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { NotdienstPlanStatus } from "@prisma/client";
|
||||
@@ -40,6 +41,8 @@ interface PlanViewProps {
|
||||
days: {
|
||||
date: string;
|
||||
assignmentId: string | null;
|
||||
activeAlarmId?: string | null;
|
||||
canAlarm?: boolean;
|
||||
childId: string | null;
|
||||
isOriginallyUnassigned?: boolean;
|
||||
}[];
|
||||
@@ -92,7 +95,9 @@ export function PlanView({
|
||||
const [resetDialogOpen, setResetDialogOpen] = useState(false);
|
||||
|
||||
const responsePercent =
|
||||
totalFamilies > 0 ? Math.round((respondedFamilies / totalFamilies) * 100) : 0;
|
||||
totalFamilies > 0
|
||||
? Math.round((respondedFamilies / totalFamilies) * 100)
|
||||
: 0;
|
||||
|
||||
const handleGenerate = () => {
|
||||
startTransition(async () => {
|
||||
@@ -123,7 +128,9 @@ export function PlanView({
|
||||
if ("error" in result && result.error) {
|
||||
toast.error(result.error as string);
|
||||
} else if (result.success) {
|
||||
toast.success(`${result.count} Erinnerungs-E-Mail(s) erfolgreich versendet.`);
|
||||
toast.success(
|
||||
`${result.count} Erinnerungs-E-Mail(s) erfolgreich versendet.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -173,7 +180,11 @@ export function PlanView({
|
||||
<Button disabled={isPending} onClick={handleGenerate}>
|
||||
Trotzdem generieren
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={handleSendReminders} disabled={isPending}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleSendReminders}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin [stroke-width:1.7]" />
|
||||
) : (
|
||||
@@ -386,7 +397,7 @@ export function PlanView({
|
||||
<span className="text-sm text-[var(--ink-soft)]">
|
||||
{isDraft
|
||||
? "Du kannst die Liste jetzt manuell anpassen."
|
||||
: "Dieser Plan ist verbindlich."}
|
||||
: "Dieser Plan ist veröffentlicht und kann bei Änderungen nachbearbeitet werden."}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
@@ -408,7 +419,8 @@ export function PlanView({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Plan zurücksetzen?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Möchtest du den Plan wirklich zurücksetzen? Alle Zuteilungen für diesen Monat gehen unwiderruflich verloren.
|
||||
Möchtest du den Plan wirklich zurücksetzen? Alle Zuteilungen für
|
||||
diesen Monat gehen unwiderruflich verloren.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
@@ -524,7 +536,6 @@ function PlanPreviewTable({
|
||||
const assignedChild = allChildren.find(
|
||||
(child) => child.id === day.childId,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={day.date}
|
||||
@@ -543,6 +554,21 @@ function PlanPreviewTable({
|
||||
({assignedChild.name})
|
||||
</span>
|
||||
)}
|
||||
{day.activeAlarmId ? (
|
||||
<Link
|
||||
className="mt-2 block text-xs font-semibold text-[var(--accent-deep)] hover:underline"
|
||||
href={`/dashboard/notdienst/alarm?alarm=${day.activeAlarmId}`}
|
||||
>
|
||||
Aktiven Alarm öffnen
|
||||
</Link>
|
||||
) : day.canAlarm && day.assignmentId ? (
|
||||
<Link
|
||||
className="mt-2 block text-xs font-semibold text-[var(--accent-deep)] hover:underline"
|
||||
href={`/dashboard/notdienst/alarm?assignment=${day.assignmentId}`}
|
||||
>
|
||||
Notdienstalarm auslösen
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="italic text-[var(--ink-faint)]">Noch offen</div>
|
||||
<div>
|
||||
@@ -604,9 +630,6 @@ function ManualAssignmentTable({
|
||||
{days.map((day) => {
|
||||
const [yr, mo, dy] = day.date.slice(0, 10).split("-").map(Number);
|
||||
const dateObj = new Date(yr, mo - 1, dy);
|
||||
const assignedChild = allChildren.find(
|
||||
(child) => child.id === day.childId,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -616,13 +639,11 @@ function ManualAssignmentTable({
|
||||
<div className="font-medium text-[var(--ink)]">
|
||||
{format(dateObj, "EE, dd.MM.", { locale: de })}
|
||||
</div>
|
||||
<div>
|
||||
{isDraft || day.isOriginallyUnassigned ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select
|
||||
className="w-full max-w-sm rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-1.5 text-sm text-[var(--ink)] ring-offset-[var(--surface)] hover:border-[var(--accent-mid)] focus-visible:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--focus-ring)]"
|
||||
value={day.childId || "empty"}
|
||||
disabled={isPending}
|
||||
disabled={isPending || !!day.activeAlarmId}
|
||||
onChange={(event) =>
|
||||
onAssignmentChange(day.date, event.target.value)
|
||||
}
|
||||
@@ -630,7 +651,9 @@ function ManualAssignmentTable({
|
||||
<option value="empty">-- Unbesetzt --</option>
|
||||
{allChildren.map((child) => {
|
||||
const famId = child.familyId;
|
||||
const count = famId ? (familyAssignmentCounts.get(famId) ?? 0) : 0;
|
||||
const count = famId
|
||||
? (familyAssignmentCounts.get(famId) ?? 0)
|
||||
: 0;
|
||||
return (
|
||||
<option key={child.id} value={child.id}>
|
||||
{child.parentName} ({child.name}) — {count}x
|
||||
@@ -640,21 +663,22 @@ function ManualAssignmentTable({
|
||||
</select>
|
||||
{!isDraft && (
|
||||
<span className="text-[11px] font-semibold text-[oklch(0.60_0.18_45)] bg-[oklch(0.95_0.02_45)] border border-[oklch(0.85_0.05_45)] px-2 py-0.5 rounded-md shrink-0">
|
||||
Nachträglich änderbar
|
||||
Veröffentlicht
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : assignedChild ? (
|
||||
<span className="text-sm text-[var(--ink)]">
|
||||
{assignedChild.parentName}{" "}
|
||||
<span className="text-[var(--ink-muted)]">
|
||||
({assignedChild.name})
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-[var(--danger)]">
|
||||
Unbesetzt!
|
||||
</span>
|
||||
{day.assignmentId && day.canAlarm && (
|
||||
<Link
|
||||
className="text-xs font-semibold text-[var(--accent-deep)] underline underline-offset-4"
|
||||
href={
|
||||
day.activeAlarmId
|
||||
? `/dashboard/notdienst/alarm?alarm=${day.activeAlarmId}`
|
||||
: `/dashboard/notdienst/alarm?assignment=${day.assignmentId}`
|
||||
}
|
||||
>
|
||||
{day.activeAlarmId
|
||||
? "Aktiven Alarm öffnen"
|
||||
: "Notdienstalarm auslösen"}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -18,7 +18,12 @@ import { getTargetMonthData } from "@/lib/date-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Stat } from "@/components/ui/stat";
|
||||
import { OnboardingDialog } from "@/components/OnboardingDialog";
|
||||
import { NewsTicker } from "./news-ticker";
|
||||
import { RsvpActionCard } from "./rsvp-action-card";
|
||||
import { getAnnouncements } from "@/lib/announcements";
|
||||
import { getRsvpEvents } from "@/lib/rsvp-events";
|
||||
import { AbsenceCard, UpcomingAbsencesCard } from "./absence-card";
|
||||
import { AlarmDashboardHints } from "./notdienst/alarm/dashboard-hints";
|
||||
|
||||
export const metadata = { title: "Übersicht · Kita-Planer" };
|
||||
|
||||
@@ -55,6 +60,8 @@ export default async function DashboardPage() {
|
||||
onboardingUser,
|
||||
absenceChildren,
|
||||
upcomingAbsences,
|
||||
announcements,
|
||||
rsvpEvents,
|
||||
] = await Promise.all([
|
||||
prisma.family.count({
|
||||
where: { kitaId: session.user.kitaId },
|
||||
@@ -142,6 +149,8 @@ export default async function DashboardPage() {
|
||||
take: 6,
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
getAnnouncements(session, { take: 3 }),
|
||||
getRsvpEvents(session, { onlyOpen: true }),
|
||||
]);
|
||||
|
||||
const canReportAbsences = session.user.role !== UserRole.ERZIEHER;
|
||||
@@ -177,7 +186,7 @@ export default async function DashboardPage() {
|
||||
}
|
||||
/>
|
||||
|
||||
<header className="mb-9 flex items-start justify-between gap-8">
|
||||
<header className="mb-9 flex items-start justify-between gap-8 max-[760px]:flex-col max-[760px]:gap-3">
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold uppercase text-[var(--accent-deep)] [letter-spacing:0.18em]">
|
||||
ÜBERSICHT · {kita.name}
|
||||
@@ -191,18 +200,29 @@ export default async function DashboardPage() {
|
||||
</h1>
|
||||
<p className="mt-3 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
Heute, {format(now, "EEEE, d. MMMM yyyy", { locale: de })}. Hier
|
||||
siehst du auf einen Blick, was bei {kita.name} ansteht und kannst
|
||||
dein Kind schnell für Abwesenheiten melden.
|
||||
siehst du auf einen Blick, was bei {kita.name} ansteht.
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-9 inline-flex shrink-0 items-center gap-2 rounded-full border border-[var(--hairline)] bg-[var(--surface)] px-4 py-2 text-[13px] font-semibold text-[var(--ink-soft)]">
|
||||
<div className="mt-9 max-[760px]:mt-0 inline-flex shrink-0 items-center gap-2 rounded-full border border-[var(--hairline)] bg-[var(--surface)] px-4 py-2 text-[13px] font-semibold text-[var(--ink-soft)]">
|
||||
<Clock3 className="h-3.5 w-3.5 [stroke-width:1.7]" />
|
||||
{format(now, "EEE, d. MMM yyyy", { locale: de })}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<AlarmDashboardHints />
|
||||
<RsvpActionCard events={rsvpEvents} />
|
||||
<NewsTicker items={announcements} />
|
||||
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_360px] gap-5 max-[1100px]:grid-cols-1">
|
||||
<div className="min-w-0">
|
||||
{session.user.role === UserRole.ERZIEHER && (
|
||||
<QuickCard
|
||||
href="/dashboard/personal"
|
||||
icon={Clock3}
|
||||
title="Meine Arbeitszeit & Urlaub"
|
||||
sub="Stunden erfassen, Urlaub beantragen und dein Zeitkonto ansehen."
|
||||
/>
|
||||
)}
|
||||
{canReportAbsences ? (
|
||||
<AbsenceCard
|
||||
today={format(today, "yyyy-MM-dd")}
|
||||
@@ -237,7 +257,11 @@ export default async function DashboardPage() {
|
||||
</div>
|
||||
|
||||
<section className="mt-5 grid grid-cols-4 gap-3.5 max-[1100px]:grid-cols-2 max-[640px]:grid-cols-1">
|
||||
<Stat label="Familien" value={familyCount} hint="registrierte Familien" />
|
||||
<Stat
|
||||
label="Familien"
|
||||
value={familyCount}
|
||||
hint="registrierte Familien"
|
||||
/>
|
||||
<Stat label="Kinder" value={childCount} hint="in der Einrichtung" />
|
||||
<Stat
|
||||
label={`Notdienst ${targetData.monthName}`}
|
||||
@@ -260,12 +284,22 @@ export default async function DashboardPage() {
|
||||
Häufige Aktionen für Vorstand und Koordination.
|
||||
</p>
|
||||
<div className="mt-4 grid grid-cols-3 gap-3 max-[1100px]:grid-cols-1">
|
||||
{session.user.role === UserRole.ADMIN && (
|
||||
<QuickCard
|
||||
href="/dashboard/personal"
|
||||
icon={Clock3}
|
||||
title="Personal & Freigaben"
|
||||
sub="Urlaub, Arbeitswochen und Beschäftigungsprofile verwalten."
|
||||
/>
|
||||
)}
|
||||
{session.user.role === UserRole.ADMIN && (
|
||||
<QuickCard
|
||||
href="/dashboard/families"
|
||||
icon={Users}
|
||||
title="Familien verwalten"
|
||||
sub="Familien anlegen, Kinder zuordnen, Kontakte pflegen."
|
||||
/>
|
||||
)}
|
||||
{kita.terminModuleEnabled ? (
|
||||
<QuickCard
|
||||
href="/dashboard/kalender"
|
||||
@@ -274,7 +308,10 @@ export default async function DashboardPage() {
|
||||
sub="Schließtage, Elternabende und Feste planen."
|
||||
/>
|
||||
) : null}
|
||||
{kita.notdienstModuleEnabled ? (
|
||||
{kita.notdienstModuleEnabled &&
|
||||
[UserRole.ADMIN, UserRole.KOORDINATOR].includes(
|
||||
session.user.role as "ADMIN" | "KOORDINATOR",
|
||||
) ? (
|
||||
<QuickCard
|
||||
href="/dashboard/notdienst/plan"
|
||||
icon={ListTodo}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"use server";
|
||||
import { publicActionError } from "@/lib/action-error";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { requireStaffActor } from "@/lib/staff/auth";
|
||||
import { executeStaffCommand } from "@/lib/staff/service";
|
||||
import { deliverStaffEmails } from "@/lib/staff/email";
|
||||
|
||||
export type StaffActionResult = {
|
||||
educatorId?: string;
|
||||
error?: string;
|
||||
success?: boolean;
|
||||
invitePath?: string;
|
||||
warning?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export async function staffAction(
|
||||
command: string,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<StaffActionResult> {
|
||||
const actor = await requireStaffActor();
|
||||
try {
|
||||
const result = await executeStaffCommand(actor, { command, data });
|
||||
let warning: string | undefined;
|
||||
let message: string | undefined;
|
||||
if (result.emailIds?.length) {
|
||||
try {
|
||||
const delivery = await deliverStaffEmails(result.emailIds);
|
||||
if (delivery.failed)
|
||||
warning =
|
||||
"Gespeichert. Einige E-Mails konnten nicht versendet werden. Im Personalbereich kannst du den Versand erneut versuchen.";
|
||||
else if (
|
||||
process.env.NODE_ENV === "development" &&
|
||||
!process.env.RESEND_API_KEY
|
||||
)
|
||||
warning = "Gespeichert. Der E-Mail-Versand wurde lokal simuliert.";
|
||||
else if (result.invite && delivery.sent)
|
||||
message = "Aktivierungslink per E-Mail versendet.";
|
||||
else if (command === "emailRetry")
|
||||
message = "Ausstehende E-Mails wurden verarbeitet.";
|
||||
} catch {
|
||||
warning =
|
||||
"Gespeichert. E-Mail-Versand ist noch ausstehend; bitte im Personalbereich erneut versuchen.";
|
||||
}
|
||||
}
|
||||
revalidatePath("/dashboard/personal");
|
||||
revalidatePath("/dashboard/profil");
|
||||
revalidatePath("/dashboard/erzieher");
|
||||
revalidatePath("/dashboard");
|
||||
// Returned only to the authenticated admin who generated this single-use link.
|
||||
return {
|
||||
success: true,
|
||||
educatorId: result.educatorId,
|
||||
warning,
|
||||
message,
|
||||
...(result.invite
|
||||
? { invitePath: `/invite/${result.invite.token}` }
|
||||
: {}),
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError)
|
||||
return {
|
||||
error: error.issues[0]?.message ?? "Bitte die Eingaben prüfen.",
|
||||
};
|
||||
const message = publicActionError(error, "");
|
||||
if (message) return { error: message };
|
||||
return { error: "Speichern fehlgeschlagen. Bitte erneut versuchen." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition, type ReactNode } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
DAY_NAMES,
|
||||
clockMinute,
|
||||
minuteClock,
|
||||
todayKey,
|
||||
} from "@/lib/staff/calculations";
|
||||
import { staffAction, type StaffActionResult } from "./actions";
|
||||
|
||||
const control =
|
||||
"w-full rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-mid)]";
|
||||
export function Field({
|
||||
label,
|
||||
name,
|
||||
type = "text",
|
||||
value,
|
||||
required = true,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
}: {
|
||||
label: string;
|
||||
name: string;
|
||||
type?: string;
|
||||
value?: string | number;
|
||||
required?: boolean;
|
||||
min?: string | number;
|
||||
max?: string | number;
|
||||
step?: string | number;
|
||||
}) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className="grid gap-1.5">
|
||||
<label htmlFor={id} className="text-sm font-medium">
|
||||
{label}
|
||||
</label>
|
||||
<Input
|
||||
id={id}
|
||||
name={name}
|
||||
type={type}
|
||||
defaultValue={value}
|
||||
required={required}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function transform(command: string, form: FormData) {
|
||||
const text = (key: string) => String(form.get(key) ?? "");
|
||||
const num = (key: string) => Number(text(key));
|
||||
const hours = (key: string) => Math.round(num(key) * 60);
|
||||
switch (command) {
|
||||
case "emailPreference":
|
||||
return { enabled: form.get("enabled") === "on" };
|
||||
case "setup":
|
||||
return {
|
||||
educatorId: text("educatorId"),
|
||||
employmentStart: text("employmentStart"),
|
||||
employmentEnd: text("employmentEnd") || null,
|
||||
trackingStart: text("trackingStart"),
|
||||
openingMinutes: hours("openingHours"),
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "invite":
|
||||
return { email: text("email") };
|
||||
case "employmentEnd":
|
||||
return {
|
||||
employmentEnd: text("employmentEnd") || null,
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "pattern":
|
||||
return {
|
||||
effectiveFrom: text("effectiveFrom"),
|
||||
dailyMinutes: DAY_NAMES.map((_, i) => hours(`day${i}`)),
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "account":
|
||||
return {
|
||||
year: num("year"),
|
||||
entitlementUnits: Math.round(num("entitlement") * 2),
|
||||
carryUnits: Math.round(num("carry") * 2),
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "override":
|
||||
return {
|
||||
date: text("date"),
|
||||
minutes: hours("hours"),
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "adjust":
|
||||
return {
|
||||
date: text("date"),
|
||||
minutes: hours("hours"),
|
||||
reason: text("reason"),
|
||||
};
|
||||
case "holiday":
|
||||
return { date: text("date"), name: text("name") };
|
||||
case "time":
|
||||
return {
|
||||
date: text("date"),
|
||||
startMinute: clockMinute(text("start")),
|
||||
endMinute: clockMinute(text("end")),
|
||||
breakMinutes: num("breakMinutes"),
|
||||
note: text("note"),
|
||||
};
|
||||
case "leave":
|
||||
return {
|
||||
kind: text("kind"),
|
||||
startDate: text("startDate"),
|
||||
endDate: text("endDate"),
|
||||
halfDay: form.get("halfDay") === "on",
|
||||
...(text("kind") === "TIME_OFF" ? { minutes: hours("hours") } : {}),
|
||||
note: text("note"),
|
||||
};
|
||||
case "leaveReview":
|
||||
case "weekReview":
|
||||
return { reason: text("reason") };
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function StaffForm({
|
||||
command,
|
||||
profileId,
|
||||
extra = {},
|
||||
children,
|
||||
label = "Speichern",
|
||||
onSuccess,
|
||||
}: {
|
||||
command: string;
|
||||
profileId?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
children: ReactNode;
|
||||
label?: string;
|
||||
onSuccess?: (result: StaffActionResult) => void;
|
||||
}) {
|
||||
const [pending, start] = useTransition();
|
||||
const [error, setError] = useState("");
|
||||
const router = useRouter();
|
||||
return (
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
setError("");
|
||||
start(async () => {
|
||||
try {
|
||||
const result = await staffAction(command, {
|
||||
...transform(command, form),
|
||||
...extra,
|
||||
...(profileId ? { profileId } : {}),
|
||||
});
|
||||
if (result.error) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.warning) toast.warning(result.warning);
|
||||
else toast.success(result.message ?? "Gespeichert.");
|
||||
onSuccess?.(result);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Speichern fehlgeschlagen.",
|
||||
);
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={pending} className="grid gap-4 disabled:opacity-60">
|
||||
{children}
|
||||
<div>
|
||||
<Button type="submit">
|
||||
{pending ? "Wird gespeichert …" : label}
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-[var(--danger)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
export function CommandButton({
|
||||
command,
|
||||
profileId,
|
||||
data,
|
||||
children,
|
||||
variant = "outline",
|
||||
}: {
|
||||
command: string;
|
||||
profileId: string;
|
||||
data: Record<string, unknown>;
|
||||
children: ReactNode;
|
||||
variant?: "outline" | "ghost" | "default";
|
||||
}) {
|
||||
const [pending, start] = useTransition();
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant}
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
start(async () => {
|
||||
const result = await staffAction(command, { ...data, profileId });
|
||||
if (result.error) toast.error(result.error);
|
||||
else {
|
||||
if (result.warning) toast.warning(result.warning);
|
||||
else toast.success(result.message ?? "Gespeichert.");
|
||||
router.refresh();
|
||||
}
|
||||
})
|
||||
}
|
||||
>
|
||||
{pending ? "Bitte warten …" : children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
export function ReviewButton({
|
||||
command,
|
||||
profileId,
|
||||
data,
|
||||
label,
|
||||
approve,
|
||||
}: {
|
||||
command: "leaveReview" | "weekReview";
|
||||
profileId: string;
|
||||
data: Record<string, unknown>;
|
||||
label: string;
|
||||
approve: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm" variant={approve ? "default" : "outline"}>
|
||||
{label}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{label}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Die Entscheidung wird im Personalverlauf dokumentiert.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<StaffForm
|
||||
command={command}
|
||||
profileId={profileId}
|
||||
extra={{ ...data, approve }}
|
||||
label={label}
|
||||
onSuccess={() => setOpen(false)}
|
||||
>
|
||||
<Field label="Begründung / Rückmeldung" name="reason" />
|
||||
</StaffForm>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function SetupForm({
|
||||
educatorId,
|
||||
values,
|
||||
}: {
|
||||
educatorId: string;
|
||||
values?: {
|
||||
employmentStart: string;
|
||||
employmentEnd: string | null;
|
||||
trackingStart: string;
|
||||
openingMinutes: number;
|
||||
};
|
||||
}) {
|
||||
return (
|
||||
<StaffForm
|
||||
command="setup"
|
||||
extra={{ educatorId }}
|
||||
label="Beschäftigungsprofil speichern"
|
||||
>
|
||||
<input type="hidden" name="educatorId" value={educatorId} />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field
|
||||
label="Beschäftigung ab"
|
||||
name="employmentStart"
|
||||
type="date"
|
||||
value={values?.employmentStart ?? todayKey()}
|
||||
/>
|
||||
<Field
|
||||
label="Beschäftigung bis (optional)"
|
||||
name="employmentEnd"
|
||||
type="date"
|
||||
value={values?.employmentEnd ?? ""}
|
||||
required={false}
|
||||
/>
|
||||
<Field
|
||||
label="Zeiterfassung ab"
|
||||
name="trackingStart"
|
||||
type="date"
|
||||
value={values?.trackingStart ?? todayKey()}
|
||||
/>
|
||||
<Field
|
||||
label="Anfangssaldo in Stunden"
|
||||
name="openingHours"
|
||||
type="number"
|
||||
step="any"
|
||||
value={(values?.openingMinutes ?? 0) / 60}
|
||||
/>
|
||||
</div>
|
||||
<Field label="Begründung" name="reason" value="Ersteinrichtung" />
|
||||
</StaffForm>
|
||||
);
|
||||
}
|
||||
export function TimeForm({
|
||||
profileId,
|
||||
initial,
|
||||
}: {
|
||||
profileId: string;
|
||||
initial?: {
|
||||
id: string;
|
||||
date: string;
|
||||
startMinute: number;
|
||||
endMinute: number;
|
||||
breakMinutes: number;
|
||||
note: string | null;
|
||||
};
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant={initial ? "outline" : "default"}
|
||||
size={initial ? "sm" : "default"}
|
||||
>
|
||||
{initial ? "Bearbeiten" : "+ Arbeitszeit erfassen"}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{initial ? "Arbeitszeit bearbeiten" : "Arbeitszeit erfassen"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Erfasse Beginn, Ende und die gesamte Pause dieses Arbeitsblocks.
|
||||
Weitere Blöcke am selben Tag sind möglich.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<StaffForm
|
||||
command="time"
|
||||
profileId={profileId}
|
||||
extra={initial ? { id: initial.id } : {}}
|
||||
label="Arbeitszeit speichern"
|
||||
onSuccess={() => setOpen(false)}
|
||||
>
|
||||
<Field
|
||||
label="Datum"
|
||||
name="date"
|
||||
type="date"
|
||||
value={initial?.date ?? todayKey()}
|
||||
max={todayKey()}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field
|
||||
label="Beginn"
|
||||
name="start"
|
||||
type="time"
|
||||
value={minuteClock(initial?.startMinute ?? 480)}
|
||||
/>
|
||||
<Field
|
||||
label="Ende"
|
||||
name="end"
|
||||
type="time"
|
||||
value={minuteClock(initial?.endMinute ?? 960)}
|
||||
/>
|
||||
</div>
|
||||
<Field
|
||||
label="Pause in Minuten"
|
||||
name="breakMinutes"
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={initial?.breakMinutes ?? 30}
|
||||
/>
|
||||
<Field
|
||||
label="Notiz (optional)"
|
||||
name="note"
|
||||
value={initial?.note ?? ""}
|
||||
required={false}
|
||||
/>
|
||||
</StaffForm>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function LeaveForm({
|
||||
profileId,
|
||||
admin,
|
||||
initial,
|
||||
}: {
|
||||
profileId: string;
|
||||
admin: boolean;
|
||||
initial?: {
|
||||
id: string;
|
||||
kind: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
halfDay: boolean;
|
||||
minutes: number | null;
|
||||
note: string | null;
|
||||
};
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [kind, setKind] = useState(initial?.kind ?? "VACATION");
|
||||
const id = useId();
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size={initial ? "sm" : "default"} variant="outline">
|
||||
{initial ? "Ändern" : "+ Abwesenheit beantragen"}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{initial ? "Antrag ändern" : "Abwesenheit beantragen"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Urlaub verbraucht nur deine vorgesehenen Arbeitstage.
|
||||
Freizeitausgleich wird in Stunden für einen einzelnen Tag beantragt.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<StaffForm
|
||||
command="leave"
|
||||
profileId={profileId}
|
||||
extra={initial ? { id: initial.id } : {}}
|
||||
label={
|
||||
kind === "SICKNESS" ? "Krankheit hinterlegen" : "Antrag speichern"
|
||||
}
|
||||
onSuccess={() => setOpen(false)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
<label htmlFor={`${id}-kind`} className="text-sm font-medium">
|
||||
Art
|
||||
</label>
|
||||
<select
|
||||
id={`${id}-kind`}
|
||||
name="kind"
|
||||
className={control}
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value)}
|
||||
>
|
||||
<option value="VACATION">Urlaub</option>
|
||||
<option value="TIME_OFF">Freizeitausgleich</option>
|
||||
{admin && <option value="SICKNESS">Krankheit</option>}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field
|
||||
label="Von"
|
||||
name="startDate"
|
||||
type="date"
|
||||
value={initial?.startDate ?? todayKey()}
|
||||
/>
|
||||
<Field
|
||||
label="Bis"
|
||||
name="endDate"
|
||||
type="date"
|
||||
value={initial?.endDate ?? todayKey()}
|
||||
/>
|
||||
</div>
|
||||
{kind === "VACATION" && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
name="halfDay"
|
||||
type="checkbox"
|
||||
defaultChecked={initial?.halfDay}
|
||||
/>
|
||||
Halber Urlaubstag (Von = Bis)
|
||||
</label>
|
||||
)}
|
||||
{kind === "TIME_OFF" && (
|
||||
<Field
|
||||
label="Freizeitausgleich in Stunden (Von = Bis)"
|
||||
name="hours"
|
||||
type="number"
|
||||
min={1 / 60}
|
||||
max={16}
|
||||
step="any"
|
||||
value={(initial?.minutes ?? 60) / 60}
|
||||
/>
|
||||
)}
|
||||
<Field
|
||||
label="Notiz (optional)"
|
||||
name="note"
|
||||
value={initial?.note ?? ""}
|
||||
required={false}
|
||||
/>
|
||||
<p className="text-xs leading-5 text-[var(--ink-soft)]">
|
||||
Der Antrag wird anhand deines Wochenmodells, der Tagesausnahmen und
|
||||
der Feiertage geprüft. Ein halber Tag entspricht der Hälfte der
|
||||
Sollzeit.
|
||||
</p>
|
||||
</StaffForm>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
function SettingsSection({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<details className="rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-5">
|
||||
<summary className="cursor-pointer font-semibold">{title}</summary>
|
||||
<div className="mt-5">{children}</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
export function StaffEmailSettings({ enabled }: { enabled: boolean }) {
|
||||
return (
|
||||
<StaffForm command="emailPreference" label="E-Mail-Einstellung speichern">
|
||||
<label className="flex items-start gap-3 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="enabled"
|
||||
defaultChecked={enabled}
|
||||
className="mt-1 accent-[var(--accent-deep)]"
|
||||
/>
|
||||
<span>
|
||||
Entscheidungen zu Urlaub, Freizeitausgleich und Arbeitswochen per
|
||||
E-Mail erhalten.
|
||||
</span>
|
||||
</label>
|
||||
<p className="text-sm text-[var(--ink-soft)]">
|
||||
Aktivierungslinks und Hinweise innerhalb der App bleiben davon
|
||||
unabhängig.
|
||||
</p>
|
||||
</StaffForm>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPanel({
|
||||
profileId,
|
||||
educatorId,
|
||||
employment,
|
||||
email,
|
||||
verified,
|
||||
pattern,
|
||||
year,
|
||||
account,
|
||||
}: {
|
||||
profileId: string;
|
||||
educatorId: string;
|
||||
employment: {
|
||||
employmentStart: string;
|
||||
employmentEnd: string | null;
|
||||
trackingStart: string;
|
||||
openingMinutes: number;
|
||||
};
|
||||
email?: string;
|
||||
verified: boolean;
|
||||
pattern?: { effectiveFrom: string; dailyMinutes: number[] };
|
||||
year: number;
|
||||
account?: { entitlementUnits: number; carryUnits: number };
|
||||
}) {
|
||||
const [invitePath, setInvitePath] = useState("");
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
<SettingsSection title="Zugang zur Zeiterfassung">
|
||||
{verified ? (
|
||||
<p className="text-sm">Aktives Konto: {email}</p>
|
||||
) : (
|
||||
<StaffForm
|
||||
command="invite"
|
||||
profileId={profileId}
|
||||
label="Per E-Mail einladen / Account verknüpfen"
|
||||
onSuccess={(r) => setInvitePath(r.invitePath ?? "")}
|
||||
>
|
||||
<Field
|
||||
label="E-Mail-Adresse"
|
||||
name="email"
|
||||
type="email"
|
||||
value={email ?? ""}
|
||||
/>
|
||||
<p className="text-sm text-[var(--ink-soft)]">
|
||||
Erstellt oder verknüpft einen ErzieherInnen-Account. Der
|
||||
persönliche Aktivierungslink wird per E-Mail versendet und ist
|
||||
sieben Tage gültig. Ein neuer Link ersetzt den vorherigen.
|
||||
</p>
|
||||
</StaffForm>
|
||||
)}
|
||||
{invitePath && (
|
||||
<div className="mt-4 grid gap-2 rounded-lg bg-[var(--accent-soft)] p-4">
|
||||
<label htmlFor="activation-link" className="text-sm font-medium">
|
||||
Persönlicher Aktivierungslink
|
||||
</label>
|
||||
<Input
|
||||
id="activation-link"
|
||||
readOnly
|
||||
value={`${window.location.origin}${invitePath}`}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
await navigator.clipboard.writeText(
|
||||
`${window.location.origin}${invitePath}`,
|
||||
);
|
||||
toast.success("Link kopiert.");
|
||||
}}
|
||||
>
|
||||
Link kopieren
|
||||
</Button>
|
||||
<p className="text-xs">
|
||||
Der Link wird per E-Mail versendet. Bei Bedarf kannst du ihn
|
||||
zusätzlich persönlich an die Fachkraft weitergeben.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Feste Wochentage & Sollstunden">
|
||||
<StaffForm
|
||||
command="pattern"
|
||||
profileId={profileId}
|
||||
label="Wochenmodell speichern"
|
||||
>
|
||||
<Field
|
||||
label="Gültig ab"
|
||||
name="effectiveFrom"
|
||||
type="date"
|
||||
value={pattern?.effectiveFrom ?? employment.trackingStart}
|
||||
/>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{DAY_NAMES.map((day, i) => (
|
||||
<Field
|
||||
key={day}
|
||||
label={`${day} · Stunden`}
|
||||
name={`day${i}`}
|
||||
type="number"
|
||||
min={0}
|
||||
max={16}
|
||||
step="any"
|
||||
value={(pattern?.dailyMinutes[i] ?? 0) / 60}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<Field label="Begründung" name="reason" />
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
0 Stunden = frei. Stunden sind Nettozeiten ohne Pause. Änderungen
|
||||
gelten ab dem gewählten Datum; ältere Modelle bleiben erhalten.
|
||||
</p>
|
||||
</StaffForm>
|
||||
</SettingsSection>
|
||||
<SettingsSection title={`Urlaubsanspruch & Übertrag · ${year}`}>
|
||||
<StaffForm command="account" profileId={profileId}>
|
||||
<Field
|
||||
label="Jahr"
|
||||
name="year"
|
||||
type="number"
|
||||
min={2000}
|
||||
max={2100}
|
||||
value={year}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field
|
||||
label="Jahresanspruch in Tagen"
|
||||
name="entitlement"
|
||||
type="number"
|
||||
min={0}
|
||||
max={400}
|
||||
step={0.5}
|
||||
value={(account?.entitlementUnits ?? 0) / 2}
|
||||
/>
|
||||
<Field
|
||||
label="Übertrag in Tagen"
|
||||
name="carry"
|
||||
type="number"
|
||||
min={0}
|
||||
max={400}
|
||||
step={0.5}
|
||||
value={(account?.carryUnits ?? 0) / 2}
|
||||
/>
|
||||
</div>
|
||||
<Field label="Begründung" name="reason" />
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Anspruch individuell für die Arbeitstage dieser Person hinterlegen.
|
||||
Der Übertrag wird ausdrücklich festgelegt.
|
||||
</p>
|
||||
</StaffForm>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Ausnahme für einen einzelnen Tag">
|
||||
<StaffForm command="override" profileId={profileId}>
|
||||
<Field label="Datum" name="date" type="date" value={todayKey()} />
|
||||
<Field
|
||||
label="Abweichende Sollstunden (0 = frei)"
|
||||
name="hours"
|
||||
type="number"
|
||||
min={0}
|
||||
max={16}
|
||||
step="any"
|
||||
value={0}
|
||||
/>
|
||||
<Field label="Begründung" name="reason" />
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Bei einem Tausch beide Tage erfassen: den ursprünglichen Tag auf 0
|
||||
setzen und den neuen Arbeitstag mit Sollstunden hinterlegen.
|
||||
</p>
|
||||
</StaffForm>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Zeitkonto korrigieren">
|
||||
<StaffForm command="adjust" profileId={profileId}>
|
||||
<Field
|
||||
label="Buchungsdatum"
|
||||
name="date"
|
||||
type="date"
|
||||
value={todayKey()}
|
||||
/>
|
||||
<Field
|
||||
label="Korrektur in Stunden (mit Vorzeichen)"
|
||||
name="hours"
|
||||
type="number"
|
||||
step="any"
|
||||
/>
|
||||
<Field label="Begründung" name="reason" />
|
||||
<p className="text-xs text-[var(--ink-soft)]">
|
||||
Korrekturen bleiben im Verlauf erhalten. Falsche Buchungen durch
|
||||
eine Gegenbuchung berichtigen.
|
||||
</p>
|
||||
</StaffForm>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Beschäftigungsbeginn & Anfangssaldo">
|
||||
<SetupForm educatorId={educatorId} values={employment} />
|
||||
<p className="mt-3 text-xs text-[var(--ink-soft)]">
|
||||
Die Grunddaten sind geschützt, sobald Zeiten, Wochen oder Anträge
|
||||
erfasst wurden.
|
||||
</p>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Beschäftigungsende ändern">
|
||||
<StaffForm command="employmentEnd" profileId={profileId}>
|
||||
<Field
|
||||
label="Beschäftigung bis (leer = unbefristet)"
|
||||
name="employmentEnd"
|
||||
type="date"
|
||||
value={employment.employmentEnd ?? ""}
|
||||
required={false}
|
||||
/>
|
||||
<Field label="Begründung" name="reason" />
|
||||
</StaffForm>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function HolidayForm() {
|
||||
return (
|
||||
<StaffForm command="holiday" label="Feiertag speichern">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Datum" name="date" type="date" />
|
||||
<Field label="Bezeichnung" name="name" />
|
||||
</div>
|
||||
</StaffForm>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,7 @@ type ContactFormProps = {
|
||||
street: string | null;
|
||||
postalCode: string | null;
|
||||
city: string | null;
|
||||
directoryOptIn: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -30,6 +31,7 @@ export function ContactForm({ contact }: ContactFormProps) {
|
||||
street: String(formData.get("street") ?? ""),
|
||||
postalCode: String(formData.get("postalCode") ?? ""),
|
||||
city: String(formData.get("city") ?? ""),
|
||||
directoryOptIn: formData.get("directoryOptIn") === "on",
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
@@ -106,6 +108,22 @@ export function ContactForm({ contact }: ContactFormProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="directoryOptIn"
|
||||
name="directoryOptIn"
|
||||
defaultChecked={contact.directoryOptIn}
|
||||
className="rounded border-[var(--hairline)] accent-[var(--accent-deep)]"
|
||||
/>
|
||||
<Label
|
||||
htmlFor="directoryOptIn"
|
||||
className="font-normal cursor-pointer text-xs text-[var(--ink-soft)]"
|
||||
>
|
||||
Im Adressbuch anzeigen (Datenschutzerklärung)
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-1">
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isPending ? (
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getChildBirthdateRange,
|
||||
parseDateInput,
|
||||
} from "@/lib/child-birthdate";
|
||||
import { serializableTransaction } from "@/lib/transaction";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Telefonnummern: führendes "+" optional, dann Ziffern, Leerzeichen, Bindestriche,
|
||||
@@ -80,6 +81,7 @@ const contactSchema = z.object({
|
||||
"Bitte eine gültige Postleitzahl angeben.",
|
||||
),
|
||||
city: z.string().trim().max(100).optional(),
|
||||
directoryOptIn: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// Gibt die erste konkrete Field-Error-Message aus einem Zod-Fehler zurück,
|
||||
@@ -117,15 +119,19 @@ export async function createMyChild(rawPayload: unknown) {
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.child.create({
|
||||
await serializableTransaction(async tx => {
|
||||
const count = await tx.child.count({ where: { kitaId: session.user.kitaId, familyId: session.user.familyId! } });
|
||||
if (count >= 20) throw new Error("Household child limit reached");
|
||||
await tx.child.create({
|
||||
data: {
|
||||
kitaId: session.user.kitaId,
|
||||
familyId: session.user.familyId,
|
||||
familyId: session.user.familyId!,
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
dateOfBirth: parseDateInput(parsed.data.dateOfBirth),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/profil");
|
||||
revalidatePath("/dashboard/families");
|
||||
@@ -157,10 +163,11 @@ export async function createMyFamily(rawPayload: unknown) {
|
||||
},
|
||||
});
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: session.user.id },
|
||||
const attached = await tx.user.updateMany({
|
||||
where: { id: session.user.id, kitaId: session.user.kitaId, familyId: null, disabledAt: null, sessionVersion: session.user.sessionVersion },
|
||||
data: { familyId: family.id },
|
||||
});
|
||||
if (attached.count !== 1) throw new Error("Account already assigned or revoked");
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/profil");
|
||||
@@ -169,7 +176,9 @@ export async function createMyFamily(rawPayload: unknown) {
|
||||
revalidatePath("/dashboard");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error && error.message === "Account already assigned or revoked")) {
|
||||
console.error("Fehler beim Anlegen des eigenen Haushalts:", error);
|
||||
}
|
||||
return { error: "Der Haushalt konnte nicht angelegt werden." };
|
||||
}
|
||||
}
|
||||
@@ -183,6 +192,20 @@ export async function updateMyContact(rawPayload: unknown) {
|
||||
}
|
||||
|
||||
try {
|
||||
const currentUser = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: session.user.id },
|
||||
select: { directoryOptInAt: true },
|
||||
});
|
||||
|
||||
let newDirectoryOptInAt: Date | null = currentUser.directoryOptInAt;
|
||||
if (parsed.data.directoryOptIn) {
|
||||
if (!newDirectoryOptInAt) {
|
||||
newDirectoryOptInAt = new Date();
|
||||
}
|
||||
} else {
|
||||
newDirectoryOptInAt = null;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: {
|
||||
@@ -190,6 +213,7 @@ export async function updateMyContact(rawPayload: unknown) {
|
||||
street: parsed.data.street || null,
|
||||
postalCode: parsed.data.postalCode || null,
|
||||
city: parsed.data.city || null,
|
||||
directoryOptInAt: newDirectoryOptInAt,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -223,7 +247,7 @@ export async function updateMyChild(childId: string, rawPayload: unknown) {
|
||||
}
|
||||
|
||||
await prisma.child.update({
|
||||
where: { id: childId },
|
||||
where: { id: childId, kitaId: session.user.kitaId, familyId: session.user.familyId! },
|
||||
data: {
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
@@ -255,7 +279,7 @@ export async function deleteMyChild(childId: string) {
|
||||
}
|
||||
|
||||
await prisma.child.delete({
|
||||
where: { id: childId },
|
||||
where: { id: childId, kitaId: session.user.kitaId, familyId: session.user.familyId! },
|
||||
});
|
||||
|
||||
revalidatePath("/dashboard/profil");
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import Link from "next/link";
|
||||
import { UserRole } from "@prisma/client";
|
||||
import {
|
||||
AtSign,
|
||||
Baby,
|
||||
@@ -27,6 +29,7 @@ import { DeleteAccountDialog } from "./_components/delete-account-dialog";
|
||||
import { MyChildrenManager } from "./_components/my-children-manager";
|
||||
import { CreateFamilyDialog } from "./_components/create-family-dialog";
|
||||
import { ContactForm } from "./_components/contact-form";
|
||||
import { StaffEmailSettings } from "../personal/forms";
|
||||
|
||||
export const metadata = { title: "Mein Profil · Kita-Planer" };
|
||||
|
||||
@@ -51,6 +54,8 @@ export default async function ProfilPage() {
|
||||
street: true,
|
||||
postalCode: true,
|
||||
city: true,
|
||||
directoryOptInAt: true,
|
||||
staffDecisionEmails: true,
|
||||
createdAt: true,
|
||||
family: {
|
||||
select: {
|
||||
@@ -95,7 +100,9 @@ export default async function ProfilPage() {
|
||||
</em>
|
||||
</h1>
|
||||
<p className="mt-3 max-w-2xl text-[15px] leading-6 text-[var(--ink-soft)]">
|
||||
Deine persönlichen Daten, verknüpfte Kinder und DSGVO-Einstellungen.
|
||||
{user.role === UserRole.ERZIEHER
|
||||
? "Deine persönlichen Daten, dein Arbeitsbereich und Datenschutzeinstellungen."
|
||||
: "Deine persönlichen Daten, verknüpfte Kinder und DSGVO-Einstellungen."}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -123,7 +130,12 @@ export default async function ProfilPage() {
|
||||
label="Telefon"
|
||||
value={user.phone ? user.phone : <EmptyDefValue />}
|
||||
/>
|
||||
<DefItem icon={Shield} label="Rolle" value={<RoleBadge role={user.role} />} />
|
||||
<DefItem
|
||||
icon={Shield}
|
||||
label="Rolle"
|
||||
value={<RoleBadge role={user.role} />}
|
||||
/>
|
||||
{user.role !== UserRole.ERZIEHER && (
|
||||
<DefItem
|
||||
icon={Home}
|
||||
label="Haushalt"
|
||||
@@ -142,6 +154,7 @@ export default async function ProfilPage() {
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<DefItem
|
||||
icon={CalendarHeart}
|
||||
label="Mitglied seit"
|
||||
@@ -152,6 +165,24 @@ export default async function ProfilPage() {
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{user.role === UserRole.ERZIEHER && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Meine Arbeitszeit & Urlaub</CardTitle>
|
||||
<CardDescription>
|
||||
Wochenmodell, Urlaubsanspruch, Zeiterfassung und Überstunden.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Link
|
||||
href="/dashboard/personal"
|
||||
className="font-medium text-[var(--accent-deep)] underline underline-offset-4"
|
||||
>
|
||||
Personalbereich öffnen →
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<Card>
|
||||
<CardHeader className="pb-5">
|
||||
<div className="flex items-start gap-3">
|
||||
@@ -173,11 +204,27 @@ export default async function ProfilPage() {
|
||||
street: user.street,
|
||||
postalCode: user.postalCode,
|
||||
city: user.city,
|
||||
directoryOptIn: !!user.directoryOptInAt,
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{user.role === UserRole.ERZIEHER && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>E-Mail-Hinweise</CardTitle>
|
||||
<CardDescription>
|
||||
Benachrichtigungen aus dem Personalbereich.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StaffEmailSettings enabled={user.staffDecisionEmails} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{user.role !== UserRole.ERZIEHER && (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader className="pb-5">
|
||||
<div className="flex items-start gap-3">
|
||||
@@ -231,8 +278,8 @@ export default async function ProfilPage() {
|
||||
Keine festen Ämter übernommen
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-[var(--ink-soft)]">
|
||||
Dienste und Rollen erscheinen hier, sobald sie zugewiesen
|
||||
sind.
|
||||
Dienste und Rollen erscheinen hier, sobald sie
|
||||
zugewiesen sind.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -259,6 +306,8 @@ export default async function ProfilPage() {
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { EventParticipationStatus } from "@prisma/client";
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
import { format } from "date-fns";
|
||||
import { de } from "date-fns/locale";
|
||||
import { AlertTriangle, Check, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { submitEventRsvp } from "@/actions/rsvp";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { RsvpEventDto } from "@/lib/rsvp";
|
||||
import { RsvpDialog } from "@/components/rsvp-form";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -17,41 +12,18 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
export type DashboardRsvpEventDto = {
|
||||
id: string;
|
||||
title: string;
|
||||
startDate: string;
|
||||
rsvpDeadline: string | null;
|
||||
children: {
|
||||
id: string;
|
||||
name: string;
|
||||
status: EventParticipationStatus | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export function RsvpActionCard({ events }: { events: DashboardRsvpEventDto[] }) {
|
||||
export function RsvpActionCard({ events }: { events: RsvpEventDto[] }) {
|
||||
if (events.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Card className="mb-8 border-[var(--warn)] bg-[var(--warn-soft)]">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center gap-2 text-lg text-[var(--ink)]">
|
||||
<AlertTriangle className="h-5 w-5 text-[var(--warn)] [stroke-width:1.7]" />
|
||||
Aktion erforderlich
|
||||
<Card className="mb-5 border-[var(--warn)] bg-[var(--warn-soft)]">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-lg">
|
||||
<AlertTriangle className="h-5 w-5 text-[var(--warn)]" />
|
||||
Rückmeldung erforderlich
|
||||
</CardTitle>
|
||||
<CardDescription className="text-[var(--ink-soft)]">
|
||||
Für diese Termine fehlt noch mindestens eine Rückmeldung deiner
|
||||
Familie.
|
||||
<CardDescription>
|
||||
Für diese Termine fehlt noch eine Antwort eurer Familie.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-3">
|
||||
@@ -61,7 +33,7 @@ export function RsvpActionCard({ events }: { events: DashboardRsvpEventDto[] })
|
||||
className="flex flex-col gap-3 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] p-4 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-[var(--ink)]">{event.title}</p>
|
||||
<p className="font-medium">{event.title}</p>
|
||||
<p className="mt-1 text-sm text-[var(--ink-soft)]">
|
||||
Rückmeldung bis{" "}
|
||||
{format(
|
||||
@@ -78,130 +50,3 @@ export function RsvpActionCard({ events }: { events: DashboardRsvpEventDto[] })
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function RsvpDialog({ event }: { event: DashboardRsvpEventDto }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const initialSelection = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
event.children.map((child) => [child.id, child.status ?? ""]),
|
||||
) as Record<string, EventParticipationStatus | "">,
|
||||
[event.children],
|
||||
);
|
||||
const [selection, setSelection] = useState(initialSelection);
|
||||
|
||||
function submit() {
|
||||
const missingChild = event.children.find((child) => !selection[child.id]);
|
||||
if (missingChild) {
|
||||
toast.error(`Bitte Rückmeldung für ${missingChild.name} auswählen.`);
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
for (const child of event.children) {
|
||||
const status = selection[child.id];
|
||||
if (!status) continue;
|
||||
|
||||
const result = await submitEventRsvp({
|
||||
eventId: event.id,
|
||||
childId: child.id,
|
||||
status,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
toast.success("Rückmeldung gespeichert.");
|
||||
setOpen(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
setOpen(nextOpen);
|
||||
if (nextOpen) setSelection(initialSelection);
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">Jetzt abstimmen</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rückmeldung für {event.title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Wähle pro Kind aus, ob es am Termin teilnimmt.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-3 py-2">
|
||||
{event.children.map((child) => (
|
||||
<div
|
||||
key={child.id}
|
||||
className="rounded-lg border border-[var(--hairline)] bg-[var(--surface-2)] p-4"
|
||||
>
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<p className="font-medium text-[var(--ink)]">{child.name}</p>
|
||||
{child.status && (
|
||||
<Badge variant="outline">bereits gemeldet</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<label className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] p-3 text-sm text-[var(--ink)] hover:bg-[var(--surface-2)]">
|
||||
<input
|
||||
type="radio"
|
||||
name={`rsvp-${child.id}`}
|
||||
checked={
|
||||
selection[child.id] ===
|
||||
EventParticipationStatus.ATTENDING
|
||||
}
|
||||
onChange={() =>
|
||||
setSelection((current) => ({
|
||||
...current,
|
||||
[child.id]: EventParticipationStatus.ATTENDING,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<Check className="h-4 w-4 text-[var(--good)] [stroke-width:1.7]" />
|
||||
Nimmt teil
|
||||
</label>
|
||||
<label className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] p-3 text-sm text-[var(--ink)] hover:bg-[var(--surface-2)]">
|
||||
<input
|
||||
type="radio"
|
||||
name={`rsvp-${child.id}`}
|
||||
checked={
|
||||
selection[child.id] ===
|
||||
EventParticipationStatus.NOT_ATTENDING
|
||||
}
|
||||
onChange={() =>
|
||||
setSelection((current) => ({
|
||||
...current,
|
||||
[child.id]: EventParticipationStatus.NOT_ATTENDING,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<X className="h-4 w-4 text-[var(--danger)] [stroke-width:1.7]" />
|
||||
Nimmt nicht teil
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="ghost" onClick={() => setOpen(false)}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="button" disabled={isPending} onClick={submit}>
|
||||
{isPending ? "Speichern..." : "Rückmeldung speichern"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { passwordSchema } from "@/lib/password";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
import { hash } from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
|
||||
import { signIn } from "@/auth";
|
||||
import { hashToken, isPublicToken } from "@/lib/tokens";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// =====================================================================
|
||||
@@ -18,8 +21,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
const inviteSchema = z
|
||||
.object({
|
||||
token: z.string().min(1),
|
||||
password: z.string().min(8, "Mindestens 8 Zeichen.").max(72, "Maximal 72 Zeichen."),
|
||||
token: z.string().refine(isPublicToken),
|
||||
password: passwordSchema,
|
||||
confirmPassword: z.string().min(1, "Passwort-Bestätigung fehlt."),
|
||||
acceptPrivacyPolicy: z.literal("on", {
|
||||
error: "Bitte die Datenschutzerklärung akzeptieren.",
|
||||
@@ -80,11 +83,12 @@ export async function acceptInviteAction(
|
||||
}
|
||||
|
||||
const { token, password, directoryOptIn } = parsed.data;
|
||||
if (!(await limitPublicAction("invite", hashToken(token), 10, 900))) return { attempt, values, errors: { _form: ["Bitte versuche es später erneut."] } };
|
||||
const now = new Date();
|
||||
|
||||
// ── 1. Token erneut DB-seitig validieren ──────────────────────────
|
||||
const verificationToken = await prisma.verificationToken.findUnique({
|
||||
where: { token },
|
||||
const verificationToken = await prisma.verificationToken.findFirst({
|
||||
where: { token: { in: [hashToken(token), ...(token.length === 36 ? [token] : [])] }, expires: { gt: new Date() } },
|
||||
});
|
||||
|
||||
if (!verificationToken) {
|
||||
@@ -111,10 +115,10 @@ export async function acceptInviteAction(
|
||||
// ── 2. User validieren (existiert und hat noch kein Passwort) ──────
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true, email: true, passwordHash: true },
|
||||
select: { id: true, email: true, passwordHash: true, disabledAt: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
if (!user || user.disabledAt) {
|
||||
return {
|
||||
attempt,
|
||||
values,
|
||||
@@ -138,22 +142,22 @@ export async function acceptInviteAction(
|
||||
const passwordHash = await hash(password, 12);
|
||||
|
||||
// ── 4. User updaten + Token löschen (atomar) ──────────────────────
|
||||
await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
passwordHash,
|
||||
privacyPolicyAcceptedAt: now,
|
||||
privacyPolicyVersion: PRIVACY_POLICY_VERSION,
|
||||
directoryOptInAt: directoryOptIn === "on" ? now : null,
|
||||
emailVerifiedAt: now,
|
||||
lastLoginAt: now,
|
||||
},
|
||||
}),
|
||||
prisma.verificationToken.delete({
|
||||
where: { token },
|
||||
}),
|
||||
]);
|
||||
try {
|
||||
await prisma.$transaction(async tx => {
|
||||
const consumed = await tx.verificationToken.deleteMany({ where: { token: verificationToken.token, expires: { gt: new Date() } } });
|
||||
if (consumed.count !== 1) throw new Error("INVITE_USED");
|
||||
const activated = await tx.user.updateMany({
|
||||
where: { id: userId, passwordHash: "", disabledAt: null },
|
||||
data: { passwordHash, privacyPolicyAcceptedAt: now, privacyPolicyVersion: PRIVACY_POLICY_VERSION,
|
||||
directoryOptInAt: directoryOptIn === "on" ? now : null, emailVerifiedAt: now, lastLoginAt: now,
|
||||
sessionVersion: { increment: 1 } },
|
||||
});
|
||||
if (activated.count !== 1) throw new Error("INVITE_USED");
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "INVITE_USED") return { attempt, values, errors: { _form: ["Dieser Link kann nicht mehr verwendet werden."] } };
|
||||
throw error;
|
||||
}
|
||||
|
||||
// ── 5. Direkt einloggen → wirft NEXT_REDIRECT ─────────────────────
|
||||
await signIn("credentials", {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Baby } from "lucide-react";
|
||||
|
||||
import { hashToken, isPublicToken } from "@/lib/tokens";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
Card,
|
||||
@@ -12,7 +13,8 @@ import {
|
||||
} from "@/components/ui/card";
|
||||
import { InviteForm } from "./invite-form";
|
||||
|
||||
export const metadata = { title: "Konto aktivieren · Kita-Planer" };
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata = { title: "Konto aktivieren · Kita-Planer", robots: { index: false, follow: false } };
|
||||
|
||||
// =====================================================================
|
||||
// /invite/[token] · Öffentliche Seite (kein Auth erforderlich)
|
||||
@@ -30,9 +32,11 @@ export default async function InvitePage({
|
||||
}) {
|
||||
const { token } = await params;
|
||||
|
||||
if (!isPublicToken(token)) notFound();
|
||||
|
||||
// Token in DB nachschlagen
|
||||
const verificationToken = await prisma.verificationToken.findUnique({
|
||||
where: { token },
|
||||
const verificationToken = await prisma.verificationToken.findFirst({
|
||||
where: { token: { in: [hashToken(token), ...(token.length === 36 ? [token] : [])] }, expires: { gt: new Date() } },
|
||||
});
|
||||
|
||||
// Unbekannter Token → 404
|
||||
@@ -46,6 +50,7 @@ export default async function InvitePage({
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: verificationToken.identifier },
|
||||
select: {
|
||||
disabledAt: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
emailVerifiedAt: true,
|
||||
@@ -53,7 +58,7 @@ export default async function InvitePage({
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) notFound();
|
||||
if (!user || user.disabledAt) notFound();
|
||||
|
||||
const userName = `${user.firstName} ${user.lastName}`;
|
||||
const alreadyAccepted = !!user.emailVerifiedAt;
|
||||
|
||||
+6
-2
@@ -1,3 +1,5 @@
|
||||
import { getSession } from "@/lib/auth-utils";
|
||||
import { headers } from "next/headers";
|
||||
import type { Metadata } from "next";
|
||||
import { Manrope } from "next/font/google";
|
||||
import "./globals.css";
|
||||
@@ -44,11 +46,13 @@ export const metadata: Metadata = {
|
||||
},
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
export default async function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const [requestHeaders, session] = await Promise.all([headers(), getSession()]);
|
||||
const nonce = requestHeaders.get("x-nonce") ?? undefined;
|
||||
return (
|
||||
<html
|
||||
lang="de"
|
||||
@@ -56,7 +60,7 @@ export default function RootLayout({
|
||||
>
|
||||
<body className="min-h-full flex flex-col">
|
||||
{children}
|
||||
<UmamiAnalytics />
|
||||
<UmamiAnalytics nonce={nonce} enabled={!session?.user?.id} />
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { AuthError } from "next-auth";
|
||||
import { z } from "zod";
|
||||
|
||||
import { safeCallbackUrl } from "@/lib/safe-redirect";
|
||||
import { signIn } from "@/auth";
|
||||
|
||||
// =====================================================================
|
||||
@@ -17,7 +18,7 @@ import { signIn } from "@/auth";
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email("Bitte eine gültige E-Mail-Adresse angeben.").toLowerCase().trim(),
|
||||
password: z.string().min(1, "Passwort fehlt."),
|
||||
password: z.string().min(1, "Passwort fehlt.").max(72),
|
||||
callbackUrl: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -29,12 +30,6 @@ export type LoginState = {
|
||||
};
|
||||
};
|
||||
|
||||
function safeCallbackUrl(value: string | undefined) {
|
||||
if (!value) return "/dashboard";
|
||||
if (!value.startsWith("/") || value.startsWith("//")) return "/dashboard";
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function loginAction(
|
||||
_prev: LoginState,
|
||||
formData: FormData,
|
||||
|
||||
+6
-13
@@ -1,6 +1,7 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { safeCallbackUrl } from "@/lib/safe-redirect";
|
||||
import { auth } from "@/auth";
|
||||
import { getPostLoginRedirect } from "@/lib/post-login-redirect";
|
||||
import {
|
||||
@@ -16,25 +17,17 @@ import { LoginForm } from "./login-form";
|
||||
export const metadata = { title: "Anmelden · Kita-Planer" };
|
||||
|
||||
type LoginPageProps = {
|
||||
searchParams?: Promise<{ callbackUrl?: string | string[] }>;
|
||||
searchParams?: Promise<{ callbackUrl?: string | string[]; reauth?: string }>;
|
||||
};
|
||||
|
||||
function getSafeCallbackUrl(value: string | string[] | undefined) {
|
||||
const callbackUrl = Array.isArray(value) ? value[0] : value;
|
||||
if (!callbackUrl) return "/dashboard";
|
||||
if (!callbackUrl.startsWith("/") || callbackUrl.startsWith("//")) {
|
||||
return "/dashboard";
|
||||
}
|
||||
return callbackUrl;
|
||||
}
|
||||
|
||||
export default async function LoginPage({ searchParams }: LoginPageProps) {
|
||||
const resolvedSearchParams = await searchParams;
|
||||
const session = await auth();
|
||||
if (session?.user?.id) {
|
||||
if (session?.user?.id && resolvedSearchParams?.reauth !== "1") {
|
||||
redirect(getPostLoginRedirect(session.user));
|
||||
}
|
||||
const resolvedSearchParams = await searchParams;
|
||||
const callbackUrl = getSafeCallbackUrl(resolvedSearchParams?.callbackUrl);
|
||||
const raw = resolvedSearchParams?.callbackUrl;
|
||||
const callbackUrl = safeCallbackUrl(Array.isArray(raw) ? raw[0] : raw);
|
||||
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
const devAdminEmail = isDev ? process.env.DEV_LOGIN_ADMIN_EMAIL : undefined;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { redirect } from "next/navigation";
|
||||
import { Prisma, UserRole } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import { auth } from "@/auth";
|
||||
import { requireSession } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// =====================================================================
|
||||
@@ -23,9 +23,9 @@ const onboardingSchema = z
|
||||
.trim()
|
||||
.min(2, "Bitte mindestens 2 Zeichen angeben.")
|
||||
.max(120, "Maximal 120 Zeichen."),
|
||||
notdienstModuleEnabled: z.preprocess(checkboxToBool, z.boolean()),
|
||||
terminModuleEnabled: z.preprocess(checkboxToBool, z.boolean()),
|
||||
adressbuchModuleEnabled: z.preprocess(checkboxToBool, z.boolean()),
|
||||
notdienstModuleEnabled: z.preprocess(checkboxToBool, z.boolean()).default(false),
|
||||
terminModuleEnabled: z.preprocess(checkboxToBool, z.boolean()).default(false),
|
||||
adressbuchModuleEnabled: z.preprocess(checkboxToBool, z.boolean()).default(false),
|
||||
notdienstMinPerChildPerMonth: z.coerce
|
||||
.number()
|
||||
.int("Bitte eine ganze Zahl angeben.")
|
||||
@@ -87,10 +87,10 @@ export async function completeOnboardingAction(
|
||||
formData: FormData,
|
||||
): Promise<OnboardingState> {
|
||||
const attempt = prev.attempt + 1;
|
||||
const session = await auth();
|
||||
if (!session?.user) {
|
||||
redirect("/login");
|
||||
}
|
||||
const session = await requireSession();
|
||||
if (session.user.role !== UserRole.ADMIN) redirect("/forbidden");
|
||||
const founder = await prisma.user.findUnique({ where: { id: session.user.id } });
|
||||
if (!founder?.emailVerifiedAt || !founder.privacyPolicyAcceptedAt) redirect("/register");
|
||||
if (session.user.kitaId) {
|
||||
// Onboarding bereits abgeschlossen — verhindert doppeltes Einrichten
|
||||
// (z.B. durch zurück-navigieren oder Replay des Formulars).
|
||||
@@ -124,14 +124,15 @@ export async function completeOnboardingAction(
|
||||
// tatsächlich noch keine Kita hat (verhindert Race-Conditions bei
|
||||
// parallelen Onboarding-Submits).
|
||||
const updated = await tx.user.updateMany({
|
||||
where: { id: session.user.id, kitaId: null },
|
||||
where: { id: session.user.id, kitaId: null, role: UserRole.ADMIN, disabledAt: null,
|
||||
sessionVersion: session.user.sessionVersion, emailVerifiedAt: { not: null }, privacyPolicyAcceptedAt: { not: null } },
|
||||
data: {
|
||||
kitaId: kita.id,
|
||||
role: UserRole.ADMIN,
|
||||
},
|
||||
});
|
||||
|
||||
if (updated.count === 0) {
|
||||
if (updated.count !== 1) {
|
||||
throw new Error("USER_ALREADY_HAS_KITA");
|
||||
}
|
||||
});
|
||||
|
||||
+34
-59
@@ -1,26 +1,23 @@
|
||||
"use server";
|
||||
|
||||
import { hash } from "bcryptjs";
|
||||
import { Prisma, UserRole } from "@prisma/client";
|
||||
import { createElement } from "react";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { signIn } from "@/auth";
|
||||
import { hashToken, newToken } from "@/lib/tokens";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
import { sendAppEmail } from "@/lib/mail";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// =====================================================================
|
||||
// /register · Server Action
|
||||
// ---------------------------------------------------------------------
|
||||
// Legt einen "heimatlosen" Admin-Account an (kitaId === null) und loggt
|
||||
// ihn direkt ein. Die Tenant-Erstellung folgt im Onboarding-Wizard.
|
||||
// Speichert eine kurzlebige Registrierung und versendet einen Bestätigungslink.
|
||||
// Konto und Passwort entstehen erst nach dem Nachweis des Postfachbesitzes.
|
||||
// =====================================================================
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.string().email("Bitte eine gültige E-Mail-Adresse angeben.").toLowerCase().trim(),
|
||||
// bcrypt akzeptiert max. 72 Bytes — wir capen davor zur Sicherheit
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Mindestens 8 Zeichen.")
|
||||
.max(72, "Maximal 72 Zeichen."),
|
||||
email: z.string().trim().max(254).email("Bitte eine gültige E-Mail-Adresse angeben.").toLowerCase(),
|
||||
firstName: z.string().min(1, "Pflichtfeld.").max(100).trim(),
|
||||
lastName: z.string().min(1, "Pflichtfeld.").max(100).trim(),
|
||||
// HTML-Checkboxen senden "on" wenn aktiviert, sonst nichts
|
||||
@@ -29,12 +26,12 @@ const registerSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const PRIVACY_POLICY_VERSION = "2026-05-01";
|
||||
|
||||
export type RegisterState = {
|
||||
// Bumped after every action call so the client can key uncontrolled inputs
|
||||
// and force a remount with the echoed values from a failed submit.
|
||||
attempt: number;
|
||||
message?: string;
|
||||
// Echoed inputs (sans password) so failed submits don't wipe the form.
|
||||
values?: {
|
||||
firstName?: string;
|
||||
@@ -54,9 +51,9 @@ export type RegisterState = {
|
||||
|
||||
function echoValues(formData: FormData): RegisterState["values"] {
|
||||
return {
|
||||
firstName: String(formData.get("firstName") ?? ""),
|
||||
lastName: String(formData.get("lastName") ?? ""),
|
||||
email: String(formData.get("email") ?? ""),
|
||||
firstName: String(formData.get("firstName") ?? "").slice(0, 100),
|
||||
lastName: String(formData.get("lastName") ?? "").slice(0, 100),
|
||||
email: String(formData.get("email") ?? "").slice(0, 254),
|
||||
acceptPrivacyPolicy: formData.get("acceptPrivacyPolicy") === "on",
|
||||
};
|
||||
}
|
||||
@@ -74,50 +71,28 @@ export async function registerAction(
|
||||
errors: parsed.error.flatten().fieldErrors,
|
||||
};
|
||||
}
|
||||
const { email, password, firstName, lastName } = parsed.data;
|
||||
|
||||
const passwordHash = await hash(password, 12);
|
||||
const now = new Date();
|
||||
|
||||
try {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
firstName,
|
||||
lastName,
|
||||
// Gründer wird "heimatloser" Admin — beim Onboarding-Abschluss
|
||||
// wird die Rolle bestätigt und der User mit einer Kita verknüpft.
|
||||
role: UserRole.ADMIN,
|
||||
kitaId: null,
|
||||
privacyPolicyAcceptedAt: now,
|
||||
privacyPolicyVersion: PRIVACY_POLICY_VERSION,
|
||||
emailVerifiedAt: now,
|
||||
},
|
||||
const { email, firstName, lastName } = parsed.data;
|
||||
const message = "Falls die Adresse registriert werden kann, erhältst du eine E-Mail. Öffne den Link, um dein Passwort zu wählen und deine Kita einzurichten. Der Link ist 30 Minuten gültig.";
|
||||
if (!(await limitPublicAction("register", email))) {
|
||||
return { attempt, errors: { _form: ["Zu viele Anfragen. Bitte versuche es später erneut."] } };
|
||||
}
|
||||
const existing = await prisma.user.findUnique({ where: { email }, select: { role: true, kitaId: true, emailVerifiedAt: true, disabledAt: true } });
|
||||
if (existing && (existing.role !== "ADMIN" || existing.kitaId || existing.emailVerifiedAt || existing.disabledAt)) return { attempt, message };
|
||||
const token = newToken();
|
||||
await prisma.pendingRegistration.deleteMany({ where: { expiresAt: { lt: new Date() } } });
|
||||
await prisma.pendingRegistration.upsert({
|
||||
where: { email },
|
||||
create: { email, firstName, lastName, tokenHash: hashToken(token), expiresAt: new Date(Date.now() + 30 * 60_000) },
|
||||
update: { firstName, lastName, tokenHash: hashToken(token), expiresAt: new Date(Date.now() + 30 * 60_000) },
|
||||
});
|
||||
} catch (err) {
|
||||
if (
|
||||
err instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
err.code === "P2002"
|
||||
) {
|
||||
return {
|
||||
attempt,
|
||||
values: echoValues(formData),
|
||||
errors: {
|
||||
email: ["Mit dieser E-Mail-Adresse existiert bereits ein Account."],
|
||||
},
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Direkt einloggen → wirft NEXT_REDIRECT, das wir nicht abfangen.
|
||||
await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
redirectTo: "/onboarding",
|
||||
const base = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "http://localhost:3000";
|
||||
const result = await sendAppEmail({
|
||||
to: email,
|
||||
subject: "E-Mail bestätigen · Kita-Planer",
|
||||
react: createElement("div", null,
|
||||
createElement("p", null, "Bestätige deine E-Mail-Adresse, um dein Konto einzurichten. Falls du dich nicht registriert hast, kannst du diese Nachricht ignorieren."),
|
||||
createElement("a", { href: `${base}/register/verify/${token}` }, "Registrierung abschließen")),
|
||||
});
|
||||
|
||||
// Unreachable – signIn redirected.
|
||||
return { attempt };
|
||||
if (!result.success) return { attempt, errors: { _form: ["Die Bestätigungs-E-Mail konnte nicht versendet werden. Bitte versuche es später erneut."] } };
|
||||
return { attempt, message };
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export default async function RegisterPage() {
|
||||
<CardHeader className="space-y-2">
|
||||
<CardTitle>Kita kostenlos registrieren</CardTitle>
|
||||
<CardDescription>
|
||||
Lege deinen Account an. Im nächsten Schritt richtest du deine Kita ein.
|
||||
Bestätige deine E-Mail-Adresse. Danach wählst du dein Passwort und richtest deine Kita ein.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
|
||||
@@ -22,6 +22,8 @@ export function RegisterForm() {
|
||||
// semantics would wipe them after a failed submit.
|
||||
const attemptKey = state.attempt;
|
||||
|
||||
if (state.message) return <p role="status" className="text-sm">{state.message}</p>;
|
||||
|
||||
return (
|
||||
<form action={formAction} className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
@@ -59,18 +61,6 @@ export function RegisterForm() {
|
||||
error={state.errors?.email?.[0]}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
key={`password-${attemptKey}`}
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
label="Passwort"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
helperText="Mindestens 8 Zeichen."
|
||||
error={state.errors?.password?.[0]}
|
||||
/>
|
||||
|
||||
<div className="flex items-start gap-3 pt-2">
|
||||
<Checkbox
|
||||
key={`acceptPrivacyPolicy-${attemptKey}`}
|
||||
@@ -122,7 +112,7 @@ export function RegisterForm() {
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={pending}>
|
||||
{pending ? "Wird erstellt…" : "Account erstellen"}
|
||||
{pending ? "Wird gesendet…" : "Bestätigungs-E-Mail anfordern"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"use server";
|
||||
import { hash } from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { Prisma, UserRole } from "@prisma/client";
|
||||
import { signIn } from "@/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { passwordSchema } from "@/lib/password";
|
||||
import { hashToken, isPublicToken } from "@/lib/tokens";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
|
||||
const schema = z.object({ token: z.string().refine(isPublicToken), password: passwordSchema,
|
||||
confirmPassword: z.string().max(72), acceptPrivacyPolicy: z.literal("on") })
|
||||
.refine(d => d.password === d.confirmPassword, { message: "Passwörter stimmen nicht überein.", path: ["confirmPassword"] });
|
||||
export type VerificationState = { error?: string };
|
||||
export async function verifyRegistrationAction(_state: VerificationState, form: FormData): Promise<VerificationState> {
|
||||
const parsed = schema.safeParse(Object.fromEntries(form));
|
||||
if (!parsed.success) return { error: parsed.error.issues[0]?.message ?? "Bitte Eingaben prüfen." };
|
||||
const { token, password } = parsed.data;
|
||||
if (!(await limitPublicAction("verify-registration", hashToken(token), 10, 900))) return { error: "Bitte versuche es später erneut." };
|
||||
const draft = await prisma.pendingRegistration.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!draft || draft.expiresAt <= new Date()) return { error: "Der Link ist ungültig oder abgelaufen. Bitte fordere eine neue E-Mail an." };
|
||||
const passwordHash = await hash(password, 12);
|
||||
try {
|
||||
await prisma.$transaction(async tx => {
|
||||
const used = await tx.pendingRegistration.deleteMany({ where: { tokenHash: hashToken(token), expiresAt: { gt: new Date() } } });
|
||||
if (used.count !== 1) throw new Error("TOKEN_USED");
|
||||
const existing = await tx.user.findUnique({ where: { email: draft.email }, select: { id: true } });
|
||||
const data = { firstName: draft.firstName, lastName: draft.lastName, passwordHash,
|
||||
emailVerifiedAt: new Date(), privacyPolicyAcceptedAt: new Date(), privacyPolicyVersion: "2026-05-01" };
|
||||
if (existing) {
|
||||
const changed = await tx.user.updateMany({ where: { id: existing.id, role: UserRole.ADMIN, kitaId: null,
|
||||
emailVerifiedAt: null, disabledAt: null }, data: { ...data, sessionVersion: { increment: 1 } } });
|
||||
if (changed.count !== 1) throw new Error("TOKEN_USED");
|
||||
} else {
|
||||
await tx.user.create({ data: { ...data, email: draft.email, role: UserRole.ADMIN } });
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") ||
|
||||
(error instanceof Error && error.message === "TOKEN_USED")) return { error: "Der Link wurde bereits verwendet. Bitte melde dich an." };
|
||||
throw error;
|
||||
}
|
||||
await signIn("credentials", { email: draft.email, password, redirectTo: "/onboarding" });
|
||||
return {};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashToken, isPublicToken } from "@/lib/tokens";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { VerifyForm } from "./verify-form";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata = { title: "E-Mail bestätigen · Kita-Planer", robots: { index: false, follow: false } };
|
||||
export default async function VerifyPage({ params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
if (!isPublicToken(token)) notFound();
|
||||
const draft = await prisma.pendingRegistration.findUnique({ where: { tokenHash: hashToken(token) }, select: { expiresAt: true } });
|
||||
if (!draft || draft.expiresAt <= new Date()) return <main className="p-8">Dieser Link ist ungültig oder abgelaufen. <a href="/register" className="underline">Neue Bestätigungs-E-Mail anfordern</a></main>;
|
||||
return <main className="flex min-h-screen items-center justify-center p-4"><Card className="w-full max-w-md">
|
||||
<CardHeader><CardTitle>Registrierung abschließen</CardTitle></CardHeader>
|
||||
<CardContent><VerifyForm token={token} /></CardContent>
|
||||
</Card></main>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { verifyRegistrationAction, type VerificationState } from "./actions";
|
||||
export function VerifyForm({ token }: { token: string }) {
|
||||
const [state, action, pending] = useActionState(verifyRegistrationAction, {} as VerificationState);
|
||||
return <form action={action} className="space-y-4">
|
||||
<input type="hidden" name="token" value={token} />
|
||||
<div className="space-y-2"><Label htmlFor="password">Passwort</Label><Input id="password" name="password" type="password" autoComplete="new-password" minLength={8} required /></div>
|
||||
<div className="space-y-2"><Label htmlFor="confirmPassword">Passwort wiederholen</Label><Input id="confirmPassword" name="confirmPassword" type="password" autoComplete="new-password" required /></div>
|
||||
<label className="flex gap-2 text-sm"><input type="checkbox" name="acceptPrivacyPolicy" required />
|
||||
<span>Ich akzeptiere die <a className="underline" href="/datenschutz" target="_blank" rel="noreferrer">Datenschutzerklärung</a>.</span></label>
|
||||
{state.error && <p role="alert" className="text-sm text-destructive">{state.error}</p>}
|
||||
<Button type="submit" disabled={pending}>{pending ? "Wird eingerichtet…" : "E-Mail bestätigen und Konto erstellen"}</Button>
|
||||
</form>;
|
||||
}
|
||||
+40
-37
@@ -1,6 +1,7 @@
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { compare } from "bcryptjs";
|
||||
import { limitPublicAction } from "@/lib/rate-limit";
|
||||
import { z } from "zod";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
@@ -14,12 +15,12 @@ import { prisma } from "@/lib/prisma";
|
||||
// =====================================================================
|
||||
|
||||
const credentialsSchema = z.object({
|
||||
email: z.string().email().toLowerCase().trim(),
|
||||
password: z.string().min(1),
|
||||
email: z.string().trim().max(254).email().toLowerCase(),
|
||||
password: z.string().min(1).refine(value => Buffer.byteLength(value, "utf8") <= 72),
|
||||
});
|
||||
|
||||
// Brute-Force-Schutz auf Account-Ebene (planung.md §5.5).
|
||||
// Globales Rate-Limiting ergänzen wir später per Middleware.
|
||||
// Zusätzlich greifen atomare, instanzübergreifende DB-Limits vor bcrypt.
|
||||
const MAX_FAILED_ATTEMPTS = 10;
|
||||
const LOCKOUT_MINUTES = 15;
|
||||
|
||||
@@ -40,8 +41,14 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
if (!parsed.success) return null;
|
||||
const { email, password } = parsed.data;
|
||||
|
||||
if (!(await limitPublicAction("login", email, 20, 900))) return null;
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
if (!user) return null;
|
||||
if (!user) {
|
||||
// Match the cost for nonexistent accounts without exposing account existence.
|
||||
await compare(password, "$2b$12$KbQiLuL6QbybTw/WNx4Ige2yCZcjVccoruuDx3vmkJt8YYUpphdIu");
|
||||
return null;
|
||||
}
|
||||
if (user.disabledAt || !user.emailVerifiedAt) return null;
|
||||
|
||||
// Account temporär gesperrt → Login pauschal ablehnen.
|
||||
if (user.lockedUntil && user.lockedUntil > new Date()) {
|
||||
@@ -50,23 +57,18 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
|
||||
const passwordOk = await compare(password, user.passwordHash);
|
||||
if (!passwordOk) {
|
||||
const nextAttempts = user.failedLoginAttempts + 1;
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
failedLoginAttempts: nextAttempts,
|
||||
lockedUntil:
|
||||
nextAttempts >= MAX_FAILED_ATTEMPTS
|
||||
? new Date(Date.now() + LOCKOUT_MINUTES * 60_000)
|
||||
: user.lockedUntil,
|
||||
},
|
||||
});
|
||||
await prisma.$executeRaw`
|
||||
UPDATE users SET "failedLoginAttempts" = "failedLoginAttempts" + 1,
|
||||
"lockedUntil" = CASE WHEN "failedLoginAttempts" + 1 >= ${MAX_FAILED_ATTEMPTS}
|
||||
THEN NOW() + make_interval(mins => ${LOCKOUT_MINUTES}::int) ELSE "lockedUntil" END
|
||||
WHERE id = ${user.id}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
// Erfolgreicher Login → Counter zurücksetzen, lastLogin aktualisieren.
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
const admitted = await prisma.user.updateMany({
|
||||
where: { id: user.id, disabledAt: null, sessionVersion: user.sessionVersion, passwordHash: user.passwordHash, emailVerifiedAt: { not: null },
|
||||
OR: [{ lockedUntil: null }, { lockedUntil: { lte: new Date() } }] },
|
||||
data: {
|
||||
failedLoginAttempts: 0,
|
||||
lockedUntil: null,
|
||||
@@ -74,7 +76,10 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
},
|
||||
});
|
||||
|
||||
if (admitted.count !== 1) return null;
|
||||
return {
|
||||
sessionVersion: user.sessionVersion,
|
||||
authenticatedAt: Date.now(),
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: `${user.firstName} ${user.lastName}`.trim(),
|
||||
@@ -86,6 +91,13 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async redirect({ url, baseUrl }) {
|
||||
if (/[\\\x00-\x20]/.test(url)) return baseUrl;
|
||||
try {
|
||||
const destination = new URL(url, baseUrl);
|
||||
return destination.origin === new URL(baseUrl).origin ? destination.href : baseUrl;
|
||||
} catch { return baseUrl; }
|
||||
},
|
||||
/**
|
||||
* Wird beim Login (mit `user`) und bei jedem Token-Refresh (ohne `user`)
|
||||
* aufgerufen. Beim Login schreiben wir die mandantenrelevanten Felder
|
||||
@@ -96,31 +108,20 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id;
|
||||
token.role = user.role;
|
||||
token.kitaId = user.kitaId;
|
||||
token.familyId = user.familyId;
|
||||
return token;
|
||||
token.sessionVersion = user.sessionVersion;
|
||||
token.authenticatedAt = user.authenticatedAt;
|
||||
}
|
||||
|
||||
const tokenUserId = token.id ?? token.sub;
|
||||
if (tokenUserId) {
|
||||
const id = token.id ?? token.sub;
|
||||
if (typeof id !== "string" || !id || id.length > 64 || !Number.isSafeInteger(token.sessionVersion) || !Number.isFinite(token.authenticatedAt) || token.authenticatedAt > Date.now() + 60_000) return null;
|
||||
const fresh = await prisma.user.findUnique({
|
||||
where: { id: tokenUserId },
|
||||
select: { role: true, kitaId: true, familyId: true },
|
||||
where: { id },
|
||||
select: { role: true, kitaId: true, familyId: true, disabledAt: true, sessionVersion: true, emailVerifiedAt: true },
|
||||
});
|
||||
if (!fresh) {
|
||||
// User wurde gelöscht → Token entwerten.
|
||||
// (Auth.js erkennt den fehlenden `sub`/`id` und meldet ab.)
|
||||
delete (token as Partial<typeof token>).id;
|
||||
delete (token as Partial<typeof token>).sub;
|
||||
return token;
|
||||
}
|
||||
token.id = tokenUserId;
|
||||
if (!fresh || fresh.disabledAt || !fresh.emailVerifiedAt || fresh.sessionVersion !== token.sessionVersion) return null;
|
||||
token.id = id;
|
||||
token.role = fresh.role;
|
||||
token.kitaId = fresh.kitaId;
|
||||
token.familyId = fresh.familyId;
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
|
||||
@@ -131,7 +132,9 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
*/
|
||||
async session({ session, token }) {
|
||||
if (token && session.user) {
|
||||
session.user.id = token.id ?? token.sub;
|
||||
session.user.id = token.id;
|
||||
session.user.sessionVersion = token.sessionVersion;
|
||||
session.user.authenticatedAt = token.authenticatedAt;
|
||||
session.user.role = token.role;
|
||||
session.user.kitaId = token.kitaId;
|
||||
session.user.familyId = token.familyId;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user