Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c40ccf77cf | ||
|
|
affa046b4a | ||
|
|
9e938e4d07 | ||
|
|
453bece72c | ||
|
|
bdf6399b35 | ||
|
|
abe072b2d1 | ||
|
|
2a5a2f3815 | ||
|
|
0931ffc777 | ||
|
|
0b65fbba16 | ||
|
|
2949149170 | ||
|
|
11cde23cdb | ||
|
|
f42f4d5d2d | ||
|
|
0d939593c8 | ||
|
|
9308b46d84 | ||
|
|
c9d3f3d1dc | ||
|
|
c6b69eb88d | ||
|
|
dd60fd6ee6 | ||
|
|
a3dc56778d | ||
|
|
9aa79cbce9 | ||
|
|
cccb214229 | ||
|
|
9903d18b84 | ||
|
|
61b1dbe350 | ||
|
|
d8c3508db2 | ||
|
|
3e0221b149 | ||
|
|
f7a311dece | ||
|
|
60d5a95651 | ||
|
|
e328267763 | ||
|
|
844b8f7afd | ||
|
|
0085c721af | ||
|
|
1279f46b1f | ||
|
|
9089dce74a | ||
|
|
b1ef4a8186 | ||
|
|
ec5ed8b22a | ||
|
|
56f21a5289 | ||
|
|
a98c7bc8ee | ||
|
|
3a1f4274a4 | ||
|
|
c1bd620d91 | ||
|
|
60ef5ddab9 | ||
|
|
86dfe8053d | ||
|
|
52dce168dd | ||
|
|
21d41c7017 | ||
|
|
5a76c4fbb4 | ||
|
|
8eadd1f408 | ||
|
|
ca5f79e193 | ||
|
|
6a31e5f411 | ||
|
|
962e2c7dc2 | ||
|
|
f1ed89ea67 | ||
|
|
a7df6bd60a | ||
|
|
a3ec068cac | ||
|
|
b81cd7c3e2 | ||
|
|
dad8e07ec5 | ||
|
|
fe2f82244d | ||
|
|
7e85b35486 | ||
|
|
986828893b | ||
|
|
ed957e6559 | ||
|
|
9fdd76645c | ||
|
|
4667615ed0 | ||
|
|
8dd1e10fea | ||
|
|
d9d69ed861 | ||
|
|
0576d946c5 | ||
|
|
f4c06cbc95 | ||
|
|
6631530dcb | ||
|
|
64147a3282 | ||
|
|
70ebcc9cd5 |
No files matched your search
+9
-3
@@ -17,6 +17,12 @@ SMTP_PASSWORD=replace-with-an-smtp-password
|
||||
SMTP_FROM=portal@example.com
|
||||
|
||||
# Legal pages managed outside the application
|
||||
LEGAL_IMPRINT_URL=https://example.com/impressum
|
||||
LEGAL_PRIVACY_URL=https://example.com/datenschutz
|
||||
LEGAL_TERMS_URL=https://example.com/nutzungsbedingungen
|
||||
LEGAL_IMPRINT_URL=https://leon-tonhaeuser.de/impressum
|
||||
LEGAL_PRIVACY_URL=https://leon-tonhaeuser.de/datenschutz
|
||||
LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb
|
||||
|
||||
# Album auto-rule sync: runs automatically every N seconds (default 120).
|
||||
# AUTO_RULE_SYNC_INTERVAL_SECONDS=120
|
||||
# Optional bearer token to trigger the sync externally via
|
||||
# POST /api/cron/album-sync (Authorization: Bearer <CRON_SECRET>).
|
||||
# CRON_SECRET=replace-with-a-long-random-secret
|
||||
@@ -0,0 +1,64 @@
|
||||
# AI Memory & Context für Immich-Redaktions-Plugin
|
||||
|
||||
Dieses Dokument dient als zentrale Wissensbasis ("Memory") für zukünftige KI-Assistenten, die an diesem Projekt weiterarbeiten.
|
||||
|
||||
## 1. Projekt-Überblick
|
||||
Dieses Projekt ist ein Kundenportal für "Leon Tonhäuser Sportfotografie". Es verbindet sich mit einer bestehenden **Immich-Instanz** und erlaubt es, ausgewählten Redaktionen gezielt Zugriff auf spezifische Immich-Alben zu geben.
|
||||
Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder herunterladen (mit Wasserzeichen versehen oder in Originalqualität lizenziert) und werden automatisch abgerechnet.
|
||||
|
||||
**Tech-Stack:**
|
||||
- **Framework:** Next.js (App Router, Server Actions)
|
||||
- **Datenbank:** PostgreSQL via Drizzle ORM
|
||||
- **Authentifizierung:** BetterAuth
|
||||
- **Styling:** TailwindCSS, UI-Komponenten via shadcn/ui
|
||||
- **E-Mails:** React Email (HTML Templates mit Resend/SMTP)
|
||||
- **PDF-Generierung:** pdfmake (für Rechnungen)
|
||||
|
||||
## 2. Immich API & Spezifische Eigenheiten (WICHTIG!)
|
||||
- **Album-Zuordnung von Assets:** Die Immich-API gibt im Endpoint `getAsset` in der Response `asset.albums` oft einen **leeren Array** für ältere Bilder zurück. **Verlasse dich niemals auf `asset.albums` für die Berechtigungsprüfung!**
|
||||
- *Best Practice (aktuell):* Prüfe die Album-Mitgliedschaft eines Assets über `/search/metadata` mit einem `id` + `albumIds` Filter — der Aufruf liefert das Asset nur zurück, wenn es im angegebenen Album liegt (`isAssetInAlbum` in `src/modules/usages/service.ts`). Für Bulk-Download wird pro freigegebenem Album per `searchPhotos({ albumIds: [albumId], size: 1000 })` die Asset-Liste geholt und eine `assetId → albumId`-Map gebaut (`src/app/api/lightbox/bulk-download/route.ts`).
|
||||
- **WICHTIG (Stand 2026):** `GET /albums/:id` liefert auf aktuelleren Immich-Versionen **keine Assets mehr** zurück (`AlbumService.get` nutzt intern `{ withAssets: false }`, der `withoutAssets`-Query-Param existiert nicht mehr). `album.assets` ist daher immer leer — die frühere "getAlbum + iteriere album.assets"-Strategie funktioniert NICHT mehr und war die Ursache des Download-404-Bugs. `getAlbum` jetzt nur noch für Metadaten wie `albumName` verwenden.
|
||||
- **Wasserzeichen & Thumbnails:** Wasserzeichen für Vorschaubilder werden auf dem Server generiert.
|
||||
- Hole Bilder aus Immich mit `size=preview` (ca. 1440px Auflösung), anstatt der kleinen Thumbnails, da sie sonst beim Skalieren sehr unscharf werden.
|
||||
- **WICHTIG:** Nicht alle Bilder in Immich haben zwingend eine `preview`-Größe (oft bei älteren Uploads). Der `getThumbnail`-Aufruf im `immichClient` (`src/modules/immich/client.ts`) beinhaltet daher einen Fallback-Mechanismus, der bei einem Fehler automatisch die normale `thumbnail`-Größe anfragt, um kaputte Bilder zu vermeiden.
|
||||
- Aufgrund der oben erwähnten `asset.albums`-Problematik prüft die Autorisierung für das Redaktions-Thumbnail (`isGrantedEditorialAsset`) lediglich, ob die Redaktion *überhaupt* Alben zugewiesen hat. Da Asset-IDs (UUIDs) nicht erratbar sind, reicht dies aus, da Redaktionen die IDs ohnehin nur durch zugewiesene Alben erhalten können.
|
||||
- Das Wasserzeichen (`logo-white.png`) wird mit `sharp` auf 60% Deckkraft als SVG-Overlay auf das Bild gerechnet (`src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts`). **WICHTIG:** Bei der SVG-Generierung für `librsvg` (verwendet von `sharp`) MÜSSEN die XML-Namespaces `xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"` sowie das Attribut `xlink:href` für eingebettete Base64-Bilder verwendet werden, da sonst Fehler auftreten (Vierecke statt des Logos).
|
||||
- Um abzuschneidende Hochformate zu vermeiden, werden Thumbnails auf dem Server mit `fit: "inside"` in eine 800x800 Box gerendert und im Frontend (`globals.css`) via `object-fit: contain` angezeigt.
|
||||
## 3. Datenbank-Struktur & Hard-Delete
|
||||
- Die Datenbank verwendet strenges **`onDelete: "restrict"`** für alle Relationen.
|
||||
- Wenn ein Redaktions-Account gelöscht wird, müssen alle abhängigen Tabellen **manuell und in korrekter Reihenfolge** in einer Transaktion gelöscht werden, um Foreign-Key-Constraints nicht zu verletzen.
|
||||
- *Reihenfolge:* `downloadEvents` -> `usages` -> `lightboxItems` -> `billingReports` -> `albumAutoRules` -> `albumGrants` -> `billingAddressVersions` -> `auditEvents` -> `editorialAccounts` -> `accounts` / `sessions` / `users` (aus BetterAuth).
|
||||
- Diese Logik befindet sich in `src/modules/editorials/service.ts` unter `hardDeleteEditorial`.
|
||||
|
||||
## 4. UI & Styling Quirks
|
||||
- **Logo Skalierung:** Das Hauptlogo (`logo-black.png` / `logo-white.png`) darf im `<img>`-Tag **keine** harten `width` und `height`-Attribute (z.B. `1000`) haben, sonst wird das Layout in den Page-Headern gesprengt. Die Skalierung wird dynamisch in `src/app/globals.css` über `.brand-logo` (`max-height: 2.5rem; width: min(10rem, 35vw); object-fit: contain`) geregelt.
|
||||
- **E-Mails & Dark Mode:** Die E-Mail-Templates befinden sich in `src/modules/email/service.ts` und `src/modules/mail/mailer.ts`. Beide unterstützen nativ Dark Mode via CSS (`@media (prefers-color-scheme: dark)`). Im Dark Mode wird `logo-black.png` durch `logo-white.png` ausgetauscht. Die Layouts sind responsiv (`max-width: 100%` für Bilder) aufgebaut, sodass sie auch auf mobilen Geräten gut lesbar bleiben.
|
||||
## 5. Laufende Prozesse & Downloads
|
||||
- **Bulk Downloads:** Zip-Downloads (`archiver`) von mehreren Bildern nutzen Node.js Streams (`PassThrough`). Da Next.js die Response direkt an den Browser streamt, muss sichergestellt werden, dass der Stream nicht blockiert wird (`Readable.toWeb`). Siehe `src/app/api/lightbox/bulk-download/route.ts`.
|
||||
- **WICHTIG (archiver v8):** `require("archiver")` ist ab v8 **keine Funktion mehr**, sondern ein Objekt `{ Archiver, ZipArchive, TarArchive, JsonArchive }`. `archiver('zip', opts)` wirft `TypeError: archiver is not a function` → 500. Korrekt: `new archiver.ZipArchive(opts)` (gleiche `pipe`/`append`/`finalize`/`abort`-API). Dieser Fehler war lange durch den früheren 404 ("No valid assets found", leere Map) maskiert, bevor die Mitgliedschaftsprüfung repariert war.
|
||||
- **E-Mail-Benachrichtigungen bei Auto-Regeln:** Die Funktion für E-Mail-Benachrichtigungen bei Auto-Regeln (`src/modules/albums/auto-rules.ts`) verschickt *gebündelte* E-Mails. Wenn mehrere Alben gleichzeitig greifen, erhält die Redaktion genau **eine** E-Mail mit einer Auflistung aller Alben, anstatt für jedes Album einzeln benachrichtigt zu werden (`emailService.sendNewAlbumNotification` akzeptiert Arrays).
|
||||
- **Automatischer Auto-Regel-Sync (Stand 2026):** `autoRuleService.applyAllRules()` wendet die Keyword-Regeln **aller** aktiven, nicht archivierten Redaktionen auf die komplette Immich-Albenliste an (ein einziger `listAlbums`-Call pro Lauf; Grants mit `adminUserId: null` → Audit `actorType: "system"`). Trigger: (1) In-Prozess-Scheduler via `src/instrumentation.ts` + `src/modules/albums/auto-rule-scheduler.ts` (Intervall `AUTO_RULE_SYNC_INTERVAL_SECONDS`, Default 120s, erste Ausführung 15s nach Serverstart), (2) geschützter Endpoint `POST /api/cron/album-sync` (Bearer `CRON_SECRET`; ohne Secret antwortet er mit 404), (3) manueller Admin-Button „Regeln jetzt anwenden" (pro Redaktion, `applyRules`). Gleichzeitige Läufe werden über eine In-Memory-Mutex in `createAutoRuleService` koalesziert, damit es keine doppelten Grants/E-Mails gibt.
|
||||
|
||||
## 6. Admin-Bereich & Freigaben
|
||||
- **Redaktions-Freigabe:** Wenn eine Redaktion den Status `pending_approval` hat, wird sie im Admin-Detail-Dashboard über die `ApproveForm` freigegeben. In diesem Schritt *muss* der Admin zwingend einen individuellen Nettopreis für die Redaktion festlegen. Ohne das Setzen des Preises bleibt die Redaktion gesperrt.
|
||||
- **Admin-Alben-Tab (Stand 2026-09):** Unter `/admin/alben` gibt es eine zentrale Albumzugriffs-Übersicht: alle Immich-Alben mit den Redaktionen, die Zugriff haben (Chips mit Link + Ein-Klick-Entziehen pro Paar), plus **Bulk-Zuweisung** (mehrere Alben × mehrere Redaktionen per Checkbox, „Alle auswählen", ein Submit). Logik: `albumGrantService.listAlbumAccessOverview()` + `bulkGrantAlbums()` in `src/modules/albums/grants.ts` (Album-Existenz wird EINMAL per `listAlbums` geprüft statt `getAlbum` pro Paar; bereits aktive Paare werden übersprungen; jedes Paar committet in eigener Transaktion und schreibt ein `album_granted`-Audit-Event; ein fehlgeschlagenes Paar bricht den Rest nicht ab). Actions: `src/app/admin/alben/actions.ts` (bulkGrant/revoke, revalidiert `/admin/alben` + jede betroffene `/admin/redaktionen/[id]/alben`). Bulk-Auswahl: nur nicht-archivierte Redaktionen; archivierte erscheinen weiterhin als Chip in der Übersicht.
|
||||
- **„Offen"-Beträge:** „Nicht abgerechnet" bedeutet überall im Portal `usages.billingStatus in ('open', 'reopened')` — derselbe Status-Set, den auch die Abrechnung als wählbar behandelt (`billing/queries.ts`: `selectable`); `voided` und `billed` zählen nie. Stornierte Berichte setzen Nutzungen auf `reopened` zurück, erscheinen also wieder als offen. Die Redaktionsübersicht (`/admin/redaktionen`) zeigt diesen Betrag je Redaktion als „Offen …" neben dem Nettopreis (gruppierte SUM-Query,amber wenn > 0).
|
||||
- **Admin-Hinweise (Stand 2026-09):** Unter `/admin/hinweise` legt der Admin zeitlich begrenzte Meldungen für ALLE Redaktionen an (z. B. „Fotograf beim HSV-Spiel, verzögerte Antworten"). Tabelle `announcements` (message ≤ 500 Zeichen, `event_date`, `created_by_user_id` → users; Migration `0001_add_announcements`). Sichtbarkeitsfenster: ab Erstellung bis `event_date + 3 Tage` (Kalendertage, Europe/Berlin via `isoDateInBerlin` in `src/modules/announcements/service.ts`) — kein Aufräum-Job nötig, abgelaufene Zeilen bleiben unsichtbar liegen und sind im Admin löschbar. Anzeige: Banner (`AnnouncementBanner`) oben auf `/redaktion/alben` in Übersicht UND Suche. Audit: `announcement_created` / `announcement_deleted`; die Actions revalidieren `/admin/hinweise` + `/redaktion/alben`.
|
||||
|
||||
## 7. Auth-Härtung (Stand 2026)
|
||||
- **PROD-MIGRATION-BASELINE (erledigt 2026-08-25):** Die frühere Abweichung zwischen Prod-Journal (Stand 0006) und Schema wurde per History-Squash behoben: `drizzle/` enthält nur noch `0000_baseline.sql` (aus dem aktuellen Schema generiert, Snapshot = altes 0012-Snapshot semantisch identisch, via pg_dump-Diff gegen die alte Migrationskette verifiziert). Der Journal-Eintrag der Baseline trägt bewusst das **Original-Timestamp der alten Migration 0000** (`1786299825190`) – der Drizzle-Migrator vergleicht `created_at` der Tabelle `drizzle.__drizzle_migrations` mit dem Journal-`when`, daher wird die Baseline auf jeder bestehenden DB (Prod, Dev) übersprungen und nur auf frischen DBs angewendet. Zukünftige Migrationen (`drizzle-kit generate`) greifen damit auf allen Umgebungen automatisch. Alte Migrationsdateien + Snapshots liegen in `drizzle-history/pre-squash-2026-08/` und werden NUR von den Historie-Tests genutzt (`tests/db/postgres.ts` akzeptiert dafür `migrationsDir`). Erste Ausführung von `docker compose --profile ops run --rm migrate` auf PROD ist ein No-op (Baseline skippt), danach laufen neue Migrationen normal. **Aber: Der Migrate-Container muss dafür ein aktuelles Image haben — siehe Abschnitt 8 (OPS-Profile-Build-Falle).**
|
||||
- **Zwei-Faktor (TOTP) für Admins Pflicht:** Better-Auth-`twoFactor`-Plugin aktiviert; `requireAdmin` (principal.ts) wirft `TWO_FACTOR_REQUIRED`, wenn `user.two_factor_enabled` false ist. `requirePageAccess` leitet dann auf `/zwei-faktor` weiter (Wizard LIEGT AUSSERHALB von `/admin`, sonst Redirect-Loop mit dem Layout-Guard). Der Wizard nutzt den schwachen Guard `requireAdminForSetup`/`requireTwoFactorSetupPage` (`allowWithoutTwoFactor: true`). Login-Challenge: `signIn.email` antwortet mit `twoFactorRedirect: true` → LoginForm fragt TOTP-Code ab (`authClient.twoFactor.verifyTotp`). Schema der Tabelle `two_factor`: `id`, `user_id`, `secret`, `backup_codes`, `verified`, `failed_verification_count`, `locked_until` – die Feldliste MUSS exakt der Plugin-Deklaration in better-auth `plugins/two-factor/schema.mjs` entsprechen, sonst wirft der Drizzle-Adapter "field does not exist" bei jedem Two-Factor-Endpoint (Migrationen 0010–0012, historisch in `drizzle-history/pre-squash-2026-08/`).
|
||||
- **Step-up für destruktive Aktionen:** `hardDeleteEditorialAction` und `resetUsageDataAction` verlangen Sessions jünger als `DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS` (15 min), sonst `SESSION_STALE` → deutsche Meldung im UI. Beide Actions geben `{ok,message}` zurück statt zu werfen.
|
||||
- **Passwort-Policy:** `MIN_PASSWORD_LENGTH = 12` + Common-Password-Denylist in `src/modules/security/password-policy.ts`. Gilt für Registrierung (validateRegistration) UND Passwort-Reset/-Änderung (Better-Auth-`hooks.before`-Middleware in auth.ts; wirft APIError BAD_REQUEST mit deutscher Message).
|
||||
|
||||
## 8. Deployment & Migrationen (Stand 2026-09) — WICHTIG, hier hatten wir lange ein Problem!
|
||||
- **OPS-PROFILE-BUILD-FALLE (Root Cause des „Migrationen funktionieren nicht mehr"-Debakels):** `docker compose build` baut **nur aktive Services** — alles mit `profiles: ["ops"]` (`migrate`, `seed`, `preflight`) wird stillschweigend **übersprungen** (im Build-Log erscheint nur `✔ portal-app Built`). Und `docker compose run` baut **nie** selbst, es nutzt das bereits existierende (ggf. monatelange alte!) Image. Folge auf PROD: Der Migrate-Container lief über mehrere Deploys mit einem **prae-Squash-Image** (Journal `0000_initial.sql … 0010_two-factor.sql`), dessen alte Journal-Einträge 0006+ gegen die längst aktuelle DB-Schema-Version mit „already exists" crashten → Exit 1, scheinbar „Migrationen kaputt". Das APP-Image war dabei stets frisch gebaut — nur die OPS-Images nicht. Deshalb: **Deploy IMMER mit `docker compose --profile ops build`, nie mit bloßem `docker compose build`.**
|
||||
- **Korrekter Deploy-Ablauf auf dem Server:**
|
||||
1. `git pull --ff-only origin main`
|
||||
2. `docker compose --profile ops build` (baut portal-app UND migrate/seed/preflight)
|
||||
3. Gegenprobe: `docker compose run --rm --no-deps migrate ls /app/drizzle` → muss `0000_baseline.sql` + die neueste Migration enthalten
|
||||
4. `docker compose --profile ops run --rm migrate; echo EXIT=$?` → muss mit `[✓] migrations applied successfully!` und `EXIT=0` enden
|
||||
5. `docker compose up -d`
|
||||
- **Diagnose-Kette, wenn Migrationen „nicht funktionieren":** (1) Server-Checkout prüfen: `git log --oneline -1` + `ls drizzle/`. (2) Image-Inhalt prüfen: `docker compose run --rm --no-deps migrate ls /app/drizzle` — weichen Checkout und Image ab, war der Build nicht/nicht für das Profil gelaufen (Falle oben). (3) DB-Wasserstand prüfen: `SELECT id, hash, created_at FROM drizzle.__drizzle_migrations ORDER BY id;` — der Drizzle-Migrator wendet nur Journal-Einträge mit `when` > max(`created_at`) an. PROD hatte 6 Zeilen / Wasserstand `1786379282947` (= alt-0005); die Baseline (`when=1786299825190`, bewusst alt-0000-Timestamp, siehe Abschnitt 7) liegt darunter und wird korrekt übersprungen — nur tatsächlich neue Migrationen (z. B. `0001_add_announcements`, `when=1789139950413`) laufen. Ein Exit 1 ohne sichtbare Fehlerzeile bedeutet fast immer: altes Image versucht alte Migrationen erneut → „already exists".
|
||||
- **Fehlerbild „Verbindung unterbrochen / Diese Seite konnte nicht geladen werden":** Das ist das eigene Error-Boundary (`src/app/error.tsx`) für Server-Fehler beim Rendern — die App läuft also, aber eine Seite wirft. Nach jedem Deploy zuerst `docker compose logs --tail 50 portal-app` lesen. Typischer Kandidat: neue App-Version fragt eine frische Migration-Tabelle ab, die (wegen der Build-Falle oben) noch nicht existiert → Migration nachholen genügt, App muss dafür nicht neu gestartet werden.
|
||||
- **Git-Remotes:** `origin` ist SSH (`git@gitlab.tonhaeuser.cloud:leon/…`) — der `git`-User ist der feste GitLab-SSH-Systembenutzer, **nicht** der Account-Name; Auth läuft über den SSH-Key des Kontos. `Permission denied (publickey)` = Key fehlt im GitLab-Konto (Preferences → SSH Keys), nicht falscher Username in der URL. Ersatz-Remote `origin-https` (HTTPS + Passwort/PAT) existiert für den Notfall; Push-Status prüfen mit `git status -sb` („ahead" = noch nicht gepusht — dann kam auf dem Server auch nichts an, und `git pull` meldet fälschlich „Already up to date").
|
||||
@@ -27,10 +27,6 @@ ENV SMTP_PORT=587
|
||||
ENV SMTP_USER=portal@localhost
|
||||
ENV SMTP_PASSWORD=dummy-password
|
||||
ENV SMTP_FROM=portal@localhost
|
||||
ENV LEGAL_IMPRINT_URL=https://example.com/impressum
|
||||
ENV LEGAL_PRIVACY_URL=https://example.com/datenschutz
|
||||
ENV LEGAL_TERMS_URL=https://example.com/nutzungsbedingungen
|
||||
|
||||
RUN pnpm build
|
||||
|
||||
FROM node:24-alpine AS runner
|
||||
|
||||
+6
-4
@@ -12,9 +12,11 @@ x-portal-env: &portal-env
|
||||
SMTP_USER: ${SMTP_USER}
|
||||
SMTP_PASSWORD: ${SMTP_PASSWORD}
|
||||
SMTP_FROM: ${SMTP_FROM}
|
||||
LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL}
|
||||
LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL}
|
||||
LEGAL_TERMS_URL: ${LEGAL_TERMS_URL}
|
||||
LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL:-https://leon-tonhaeuser.de/impressum}
|
||||
LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL:-https://leon-tonhaeuser.de/datenschutz}
|
||||
LEGAL_TERMS_URL: ${LEGAL_TERMS_URL:-https://leon-tonhaeuser.de/agb}
|
||||
CRON_SECRET: ${CRON_SECRET:-}
|
||||
AUTO_RULE_SYNC_INTERVAL_SECONDS: ${AUTO_RULE_SYNC_INTERVAL_SECONDS:-}
|
||||
|
||||
services:
|
||||
portal-db:
|
||||
@@ -109,4 +111,4 @@ networks:
|
||||
portal-internal:
|
||||
internal: true
|
||||
immich_default:
|
||||
external: true
|
||||
external: true
|
||||
@@ -0,0 +1,142 @@
|
||||
# AGB sowie Nutzungs- und Lizenzbedingungen – Arbeitsentwurf
|
||||
|
||||
> **Wichtiger Hinweis:** Dieser Text ist ein auf das derzeit beschriebene Geschäftsmodell zugeschnittener Arbeitsentwurf und keine Rechtsberatung. Vor Veröffentlichung sollte er von einer in Deutschland zugelassenen, auf Medien-, Urheber- und Vertragsrecht spezialisierten Rechtsanwältin oder einem entsprechenden Rechtsanwalt geprüft werden. Anbieterangaben, Zahlungsfrist, Leistungsumfang und Gerichtsstand müssen noch mit dem Impressum und der tatsächlichen Arbeitsweise abgeglichen werden.
|
||||
|
||||
## Vor der Implementierung ersetzen oder entscheiden
|
||||
|
||||
- `[VOLLSTÄNDIGER NAME/FIRMA]`, `[ANSCHRIFT]`, `[E-MAIL]` und gegebenenfalls `[UST-ID]` exakt aus dem Impressum übernehmen.
|
||||
- `[ORT DES GERICHTSSTANDS]` nur einsetzen, wenn Leon dort seinen allgemeinen Gerichtsstand hat; die Klausel gilt außerdem nur im gesetzlich zulässigen Umfang.
|
||||
- Prüfen, ob die Zahlungsfrist von 14 Tagen der tatsächlichen Rechnungspraxis entspricht.
|
||||
- Den Versionsstand sichtbar angeben und diese Version bei Portalregistrierung protokollieren.
|
||||
- Auf der Website vor Vertragsschluss deutlich auf die AGB verlinken und eine zumutbare Speichermöglichkeit anbieten.
|
||||
|
||||
---
|
||||
|
||||
# Allgemeine Geschäftsbedingungen sowie Nutzungs- und Lizenzbedingungen
|
||||
|
||||
**Stand: 11. August 2026**
|
||||
|
||||
## 1. Anbieter und Geltungsbereich
|
||||
|
||||
1. Anbieter der fotografischen Leistungen und Bildlizenzen ist `[VOLLSTÄNDIGER NAME/FIRMA]`, `[ANSCHRIFT]`, E-Mail: `[E-MAIL]` – nachfolgend „Fotograf“ genannt.
|
||||
2. Diese Bedingungen gelten für Verträge über Fotoaufträge, die Bereitstellung von Fotografien sowie die Einräumung von Nutzungsrechten, insbesondere über die Website und das Redaktionsportal des Fotografen.
|
||||
3. Das Angebot richtet sich ausschließlich an Unternehmer im Sinne des § 14 BGB, juristische Personen des öffentlichen Rechts und öffentlich-rechtliche Sondervermögen. Verträge mit Verbrauchern werden auf Grundlage dieser Bedingungen nicht geschlossen.
|
||||
4. Abweichende Bedingungen des Auftraggebers oder Lizenznehmers – nachfolgend gemeinsam „Kunde“ genannt – gelten nur, wenn der Fotograf ihrer Geltung ausdrücklich in Textform zugestimmt hat.
|
||||
5. Individuelle Vereinbarungen, Angebote und Lizenzangaben gehen diesen Bedingungen vor.
|
||||
|
||||
## 2. Vertragsschluss und Kommunikation
|
||||
|
||||
1. Darstellungen auf der Website und im Redaktionsportal sind noch kein verbindliches Angebot, sofern sie nicht ausdrücklich als solches bezeichnet sind.
|
||||
2. Ein Vertrag über einen Fotoauftrag kommt durch Annahme eines Angebots, eine Auftragsbestätigung in Textform oder durch Beginn der vereinbarten Leistung zustande.
|
||||
3. Beim Redaktionsportal gibt der Kunde mit der verbindlichen Auswahl eines Fotos, des Nutzungszwecks und der Downloadart eine Bestellung der angezeigten Lizenz ab. Der Vertrag kommt mit der Bereitstellung des Downloads zustande.
|
||||
4. Der Kunde muss Angaben zu Medium, Beitrag, Verwendungszweck, Umfang und gegebenenfalls Kampagne vollständig und wahrheitsgemäß machen. Unklare oder nachträglich geänderte Nutzungen sind vorab mit dem Fotografen abzustimmen.
|
||||
|
||||
## 3. Fotoaufträge
|
||||
|
||||
1. Inhalt, Termin, Ort, Umfang, Honorar und Lieferformat eines Fotoauftrags ergeben sich aus dem jeweiligen Angebot oder der Auftragsbestätigung.
|
||||
2. Die gestalterische und technische Umsetzung liegt im künstlerischen Ermessen des Fotografen, soweit keine konkreten Vorgaben in Textform vereinbart wurden. Ein Anspruch auf einen bestimmten Stil, einzelne Motive oder eine bestimmte Zahl gelungener Aufnahmen besteht nur, wenn dies ausdrücklich vereinbart wurde.
|
||||
3. Termine und Lieferfristen sind nur verbindlich, wenn sie ausdrücklich als verbindlich bestätigt wurden. Verzögerungen aufgrund höherer Gewalt oder anderer vom Fotografen nicht zu vertretender Umstände verlängern die Leistungsfrist angemessen.
|
||||
4. Sagt der Kunde einen bestätigten Termin ab oder verschiebt ihn, kann der Fotograf die bis dahin erbrachten Leistungen und nachweislich angefallenen, nicht mehr vermeidbaren Aufwendungen abrechnen. Weitergehende gesetzliche Ansprüche bleiben unberührt; ersparte Aufwendungen werden angerechnet.
|
||||
5. Rohdateien, unbearbeitete Aufnahmen und offene Bearbeitungsdateien gehören nicht zum Lieferumfang, sofern dies nicht ausdrücklich vereinbart wurde.
|
||||
|
||||
## 4. Redaktionsportal und Benutzerkonto
|
||||
|
||||
1. Der Zugang zum Redaktionsportal bedarf der Registrierung, E-Mail-Bestätigung und Freigabe durch den Fotografen. Ein Anspruch auf Freigabe oder dauerhafte Bereitstellung besteht nicht.
|
||||
2. Ein Redaktionskonto darf innerhalb der freigeschalteten Redaktion gemeinsam genutzt werden. Der Kunde stellt sicher, dass Zugangsdaten nur befugten Mitarbeitenden zugänglich sind, sicher verwahrt und bei Verdacht auf Missbrauch unverzüglich geändert werden.
|
||||
3. Sämtliche über das Redaktionskonto vorgenommenen lizenz- und abrechnungsrelevanten Handlungen werden der freigeschalteten Redaktion zugerechnet, soweit der Kunde keinen vom Fotografen zu vertretenden Missbrauch nachweist.
|
||||
4. Der Fotograf darf Zugänge bei Sicherheitsrisiken, Zahlungsverzug, vertragswidriger Nutzung oder Wegfall der Geschäftsbeziehung vorübergehend sperren. Bereits wirksam eingeräumte und bezahlte Nutzungsrechte bleiben hiervon unberührt.
|
||||
5. Das Portal wird mit angemessener Sorgfalt betrieben. Wartung, Sicherheitsmaßnahmen und Störungen bei technischen Dienstleistern können die Verfügbarkeit zeitweise einschränken. Eine ununterbrochene Verfügbarkeit wird nicht geschuldet.
|
||||
|
||||
## 5. Urheberrecht und Umfang der Bildlizenz
|
||||
|
||||
1. Sämtliche Fotografien bleiben urheber- beziehungsweise leistungsschutzrechtlich geschützt. Eigentum an Dateien oder Datenträgern und Nutzungsrechte sind voneinander zu unterscheiden.
|
||||
2. Soweit nichts anderes ausdrücklich vereinbart ist, erhält der Kunde ein einfaches, nicht ausschließliches und nicht übertragbares Nutzungsrecht ausschließlich für den bei Bestellung angegebenen Zweck. Inhaltlicher, zeitlicher, räumlicher und medialer Umfang richten sich nach dem Angebot, der Portalangabe und dem erkennbaren Vertragszweck.
|
||||
3. Eine Nutzung für einen neuen Beitrag, ein neues Projekt, eine neue Ausgabe, eine neue Kampagne oder einen sonstigen neuen Zweck ist eine neue lizenzpflichtige Nutzung. Sie muss im Portal als „neuer Zweck“ ausgewählt oder gesondert vereinbart werden.
|
||||
4. Ein erneuter Download für denselben bereits lizenzierten Zweck löst nur dann keine zusätzliche nutzungsabhängige Vergütung aus, wenn das Portal ihn ausdrücklich als kostenfreie Wiederholung bestätigt. Ein neuer Nutzungszweck bleibt auch bei identischer Datei gesondert vergütungspflichtig.
|
||||
5. Online- und Social-Media-Nutzungen, Werbung, Eigenwerbung, Presseverteilung, Syndikation, Archivdatenbanken, Print, Bewegtbild, Merchandising und sonstige Verwertungsarten sind nur umfasst, soweit sie vom vereinbarten Zweck oder Lizenzumfang erfasst sind.
|
||||
6. Ausschließliche Nutzungsrechte, Sperrfristen und Branchen- oder Gebietsexklusivität bedürfen einer ausdrücklichen Vereinbarung in Textform.
|
||||
|
||||
## 6. Unzulässige Nutzungen und Bearbeitungen
|
||||
|
||||
1. Ohne vorherige Zustimmung in Textform ist es insbesondere unzulässig,
|
||||
- Fotografien weiterzuverkaufen, unterzulizenzieren oder Dritten zur eigenständigen Nutzung zu überlassen,
|
||||
- Fotografien als Logo, Marke, Produktmotiv oder für Merchandising zu verwenden,
|
||||
- Fotografien in Bilddatenbanken, Stockplattformen, Datensätzen oder vergleichbaren Sammlungen bereitzustellen,
|
||||
- Fotografien zum Training, zur Feinabstimmung, Bewertung oder sonstigen Entwicklung generativer oder analytischer KI-Systeme zu verwenden,
|
||||
- den Aussagegehalt zu verfälschen, Personen oder Gegenstände sinnverändernd hinzuzufügen oder zu entfernen oder irreführende Montagen herzustellen.
|
||||
2. Zulässig sind technisch erforderliche Anpassungen wie maßvolle Ausschnitte, Skalierung sowie übliche Helligkeits- und Farbkorrekturen, soweit Aussage, Urheberpersönlichkeitsrecht und berechtigte Interessen abgebildeter Personen nicht beeinträchtigt werden.
|
||||
3. Bei redaktioneller Nutzung darf das Foto nicht in einen rechtswidrigen, herabwürdigenden, diskriminierenden oder irreführenden Zusammenhang gestellt werden.
|
||||
|
||||
## 7. Urhebervermerk und Metadaten
|
||||
|
||||
1. Soweit nicht ausdrücklich anders vereinbart oder im konkreten Medium branchenüblich ausgeschlossen, ist bei jeder Veröffentlichung gut lesbar und dem Bild zuordenbar der Urhebervermerk **„© Leon Tonhäuser“** anzubringen.
|
||||
2. Vorhandene Urheber-, Rechte- und Herkunftsangaben in Datei-Metadaten dürfen nicht entfernt oder verfälscht werden, soweit dies nicht technisch unvermeidbar ist.
|
||||
3. Der Kunde informiert den Fotografen auf Anfrage über Art und Umfang der erfolgten Nutzung und stellt nach Möglichkeit ein Belegexemplar oder einen Veröffentlichungslink bereit.
|
||||
|
||||
## 8. Rechte abgebildeter Personen und redaktioneller Kontext
|
||||
|
||||
1. Die Einräumung urheberrechtlicher Nutzungsrechte bedeutet nicht automatisch, dass jede denkbare Veröffentlichung persönlichkeits-, presse-, marken-, haus- oder datenschutzrechtlich zulässig ist.
|
||||
2. Der Fotograf informiert den Kunden über ihm bekannte, konkret vereinbarte Model-, Property- oder Veranstaltungsfreigaben und bekannte Nutzungsbeschränkungen. Eine weitergehende Freigabe gilt nur, wenn sie ausdrücklich bestätigt wurde.
|
||||
3. Der Kunde prüft eigenverantwortlich, ob die konkrete Nutzung, Bildunterschrift, Berichterstattung und Einbettung in ihrem jeweiligen Kontext zulässig ist. Das gilt insbesondere bei Werbung, sensiblen Themen, Montagen und Nutzungen außerhalb aktueller redaktioneller Berichterstattung.
|
||||
|
||||
## 9. Vergütung, Nutzungsnachweis und Rechnung
|
||||
|
||||
1. Es gelten die im Angebot, in der Preisliste oder im Redaktionsportal für die jeweilige Redaktion angezeigten beziehungsweise vereinbarten Preise. Alle Preise verstehen sich netto zuzüglich der gesetzlich geschuldeten Umsatzsteuer.
|
||||
2. Nutzungen können einzeln oder aufgrund einer individuell vereinbarten Monats- oder Quartalspauschale abgerechnet werden. Umfang, Preis und gegebenenfalls enthaltene Nutzungseinheiten einer Pauschale ergeben sich aus der Individualvereinbarung.
|
||||
3. Der im Portal oder per E-Mail bereitgestellte Nutzungsnachweis dokumentiert Downloads, Nutzungszwecke und Beträge. **Er ist keine Rechnung. Die Rechnung wird separat übermittelt.** Bei Widersprüchen hat die separate Rechnung Vorrang; offensichtliche Fehler im Nutzungsnachweis sind dem Fotografen unverzüglich mitzuteilen.
|
||||
4. Rechnungen sind innerhalb von 14 Kalendertagen ab Zugang ohne Abzug zahlbar, sofern auf der Rechnung keine andere Frist angegeben ist.
|
||||
5. Bei Zahlungsverzug gelten die gesetzlichen Vorschriften. Der Fotograf kann weitere Downloads bis zum Ausgleich fälliger Forderungen sperren.
|
||||
|
||||
## 10. Mitwirkung, Archivierung und Datensicherung
|
||||
|
||||
1. Der Kunde stellt benötigte Informationen, Freigaben, Ansprechpartner und Zutrittsberechtigungen rechtzeitig zur Verfügung. Mehraufwand und Verzögerungen aufgrund verspäteter oder unzutreffender Angaben können gesondert berechnet werden, soweit der Kunde sie zu vertreten hat.
|
||||
2. Der Kunde ist für die eigene, rechtmäßige Archivierung ausgelieferter Dateien verantwortlich. Der Fotograf schuldet keine zeitlich unbegrenzte Aufbewahrung oder erneute Bereitstellung.
|
||||
3. Beschreibungen, Dateinamen, Albumzuordnung und sonstige Metadaten dienen der Recherche. Sie ersetzen keine eigene redaktionelle Prüfung und werden nicht als vollständig oder fehlerfrei garantiert.
|
||||
|
||||
## 11. Mängel und Beanstandungen
|
||||
|
||||
1. Technisch fehlerhafte oder unvollständige Lieferungen sind nach Entdeckung nachvollziehbar zu melden. Der Fotograf erhält zunächst Gelegenheit zur Nacherfüllung, soweit diese möglich und zumutbar ist.
|
||||
2. Subjektive gestalterische Abweichungen begründen keinen Mangel, wenn sie sich innerhalb des vereinbarten Gestaltungsspielraums bewegen.
|
||||
3. Gesetzliche Untersuchungs- und Rügepflichten, insbesondere nach § 377 HGB, bleiben unberührt.
|
||||
|
||||
## 12. Haftung
|
||||
|
||||
1. Der Fotograf haftet unbeschränkt für Vorsatz und grobe Fahrlässigkeit, für Schäden aus der Verletzung von Leben, Körper oder Gesundheit, nach dem Produkthaftungsgesetz sowie im Umfang ausdrücklich übernommener Garantien.
|
||||
2. Bei leicht fahrlässiger Verletzung einer wesentlichen Vertragspflicht, deren Erfüllung die ordnungsgemäße Durchführung des Vertrags erst ermöglicht und auf deren Einhaltung der Kunde regelmäßig vertrauen darf, ist die Haftung auf den vertragstypischen, bei Vertragsschluss vorhersehbaren Schaden begrenzt.
|
||||
3. Im Übrigen ist die Haftung für leichte Fahrlässigkeit ausgeschlossen. Die vorstehenden Beschränkungen gelten entsprechend zugunsten der Beschäftigten und Erfüllungsgehilfen des Fotografen.
|
||||
4. Für vom Kunden bereitgestellte Inhalte, Weisungen, Bildunterschriften und Nutzungskontexte sowie für Nutzungen außerhalb der eingeräumten Lizenz ist der Kunde verantwortlich. Der Kunde stellt den Fotografen von berechtigten Ansprüchen Dritter frei, soweit diese auf einer vom Kunden zu vertretenden Pflichtverletzung beruhen; die angemessenen Kosten der Rechtsverteidigung sind umfasst. Der Fotograf informiert den Kunden unverzüglich und stimmt die Rechtsverteidigung angemessen mit ihm ab.
|
||||
|
||||
## 13. Vertragsdauer und Beendigung des Portalzugangs
|
||||
|
||||
1. Der Portalnutzungsvertrag läuft auf unbestimmte Zeit und kann von beiden Seiten mit einer Frist von 14 Tagen in Textform gekündigt werden, sofern keine individuelle Mindestlaufzeit vereinbart wurde.
|
||||
2. Das Recht zur außerordentlichen Kündigung aus wichtigem Grund bleibt unberührt. Ein wichtiger Grund liegt insbesondere bei schwerwiegender oder wiederholter vertragswidriger Bildnutzung, Manipulation von Abrechnungsdaten oder erheblichem Zahlungsverzug vor.
|
||||
3. Mit Vertragsende endet der Zugang zum Portal. Ordnungsgemäß erworbene und bezahlte Nutzungsrechte bleiben im vereinbarten Umfang bestehen; offene Zahlungs-, Auskunfts- und Unterlassungsansprüche bleiben unberührt.
|
||||
|
||||
## 14. Datenschutz
|
||||
|
||||
Informationen zur Verarbeitung personenbezogener Daten stehen in der gesonderten Datenschutzerklärung unter `[URL ZUR DATENSCHUTZERKLÄRUNG]`. Das Impressum ist unter `[URL ZUM IMPRESSUM]` erreichbar.
|
||||
|
||||
## 15. Schlussbestimmungen
|
||||
|
||||
1. Es gilt das Recht der Bundesrepublik Deutschland unter Ausschluss des UN-Kaufrechts.
|
||||
2. Ist der Kunde Kaufmann, juristische Person des öffentlichen Rechts oder öffentlich-rechtliches Sondervermögen, ist – soweit gesetzlich zulässig – ausschließlicher Gerichtsstand `[ORT DES GERICHTSSTANDS]`. Gesetzliche ausschließliche Gerichtsstände bleiben unberührt.
|
||||
3. Sollten einzelne Bestimmungen unwirksam sein oder werden, bleibt die Wirksamkeit der übrigen Bestimmungen unberührt. An die Stelle der unwirksamen Bestimmung treten die gesetzlichen Vorschriften.
|
||||
|
||||
---
|
||||
|
||||
## Hinweise für die KI im Website-Projekt
|
||||
|
||||
1. Den Text als eigene öffentliche Seite „AGB & Lizenzbedingungen“ ausgeben, nicht mit Impressum oder Datenschutz vermischen.
|
||||
2. Permanente URL empfehlen: `/agb` oder `/nutzungsbedingungen`.
|
||||
3. Im Footer sowie bei Kontakt-/Anfrageformularen verlinken. Im Redaktionsportal muss `LEGAL_TERMS_URL` auf genau diese öffentliche Seite zeigen.
|
||||
4. Bei einer verbindlichen Portalregistrierung eine nicht vorangekreuzte Checkbox mit Link und protokolliertem Versionsstand verwenden.
|
||||
5. Inhalt semantisch als `article` mit einer `h1` und fortlaufenden `h2`-Überschriften auszeichnen; druckfreundliche Darstellung vorsehen.
|
||||
6. Anbieterangaben und URLs aus dem bestehenden Impressum/Datenschutz übernehmen, nicht erraten.
|
||||
|
||||
## Verwendete amtliche Grundlagen
|
||||
|
||||
- §§ 305, 307 und 310 BGB: Einbeziehung und Inhaltskontrolle Allgemeiner Geschäftsbedingungen, auch im B2B-Bereich.
|
||||
- §§ 13, 15, 19a, 31 und 72 UrhG: Urheberbezeichnung, Verwertungsrechte, öffentliche Zugänglichmachung, Nutzungsrechte und Schutz von Lichtbildern.
|
||||
- §§ 22 und 23 KunstUrhG: Recht am eigenen Bild und gesetzliche Ausnahmen.
|
||||
- § 38 ZPO: Gerichtsstandsvereinbarungen insbesondere zwischen Kaufleuten.
|
||||
- § 5 DDG: gesonderte Anbieterkennzeichnung im Impressum.
|
||||
+49
-3
@@ -31,9 +31,11 @@ All production configuration is provided via environment variables (e.g. `.env`
|
||||
| `SMTP_USER` | SMTP username | `portal@example.de` |
|
||||
| `SMTP_PASSWORD` | SMTP password | Confidential |
|
||||
| `SMTP_FROM` | Default From email address | `Leon Tonhäuser Presse <portal@example.de>` |
|
||||
| `LEGAL_IMPRINT_URL` | Public Impressum link | `https://example.de/impressum` |
|
||||
| `LEGAL_PRIVACY_URL` | Public Datenschutz link | `https://example.de/datenschutz` |
|
||||
| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://example.de/terms` |
|
||||
| `LEGAL_IMPRINT_URL` | Public Impressum link | `https://leon-tonhaeuser.de/impressum` |
|
||||
| `LEGAL_PRIVACY_URL` | Public Datenschutz link | `https://leon-tonhaeuser.de/datenschutz` |
|
||||
| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://leon-tonhaeuser.de/agb` |
|
||||
| `AUTO_RULE_SYNC_INTERVAL_SECONDS` | Interval of the album auto-rule sync in seconds (min 30) | `120` (default) |
|
||||
| `CRON_SECRET` | Optional bearer token for `POST /api/cron/album-sync`; unset disables the endpoint | `openssl rand -hex 32` |
|
||||
|
||||
---
|
||||
|
||||
@@ -52,6 +54,7 @@ When placing Nginx or Traefik in front of the portal:
|
||||
```
|
||||
2. **Body Size Limits**: Unused (portal handles photo downloads only, not uploads).
|
||||
3. **Security Headers**: Managed by Next.js (`next.config.ts`), including restrictive CSP, frame denial (`DENY`), and strict Referrer-Policy.
|
||||
4. **Client-IP headers**: The portal accepts the proxy-appended final hop of `X-Forwarded-For` (the normal Zoraxy/Go reverse-proxy path) and alternatively `X-Real-IP` for abuse protection. Keep the application port unreachable from the public network so clients cannot bypass the trusted proxy. If a proxy sets `X-Real-IP`, it must overwrite rather than pass through a public client value.
|
||||
|
||||
---
|
||||
|
||||
@@ -78,6 +81,17 @@ the `ops` compose profile and do not start with `docker compose up`.
|
||||
```bash
|
||||
docker compose --profile ops run --rm migrate
|
||||
```
|
||||
|
||||
Migrations are safe to run on every environment, including production. The
|
||||
history was squashed into a single baseline (`drizzle/0000_baseline.sql`) in
|
||||
August 2026: the baseline carries the timestamp of the original first
|
||||
migration, so `drizzle-kit migrate` skips it on any database that already has
|
||||
tables (its recorded journal entry is newer) and applies it only on fresh
|
||||
databases. New migrations generated with `pnpm exec drizzle-kit generate` are
|
||||
picked up automatically on all environments — no manual psql steps required
|
||||
anymore. Historical (pre-squash) migration files live in
|
||||
`drizzle-history/pre-squash-2026-08/` and are referenced by integration tests
|
||||
only; do not point `drizzle.config.ts` at that folder.
|
||||
- **Seed the first admin** (override the command to pass credentials):
|
||||
```bash
|
||||
docker compose --profile ops run --rm seed \
|
||||
@@ -125,3 +139,35 @@ docker compose start portal-app
|
||||
- `GET /api/health/live` -> 200 OK (Process liveness).
|
||||
- `GET /api/health/ready` -> 200 OK (Database & Immich connectivity).
|
||||
- **Audit Log Inspection**: Accessible in portal UI under `/admin/audit` (Admin role required).
|
||||
|
||||
---
|
||||
|
||||
## 8. Rolling Out a New App Version (e.g. the Sakani UI, v2.0)
|
||||
|
||||
UI releases such as v2.0 change no database schema; the app keeps using the
|
||||
existing `portal-db`, so all editorials, grants, usages, billing reports and
|
||||
announcements carry over unchanged.
|
||||
|
||||
1. Back up the database (see §6):
|
||||
```bash
|
||||
scripts/backup-db.sh /var/backups/immich-portal
|
||||
```
|
||||
2. Note the running commit for a rollback: `git rev-parse HEAD`.
|
||||
3. Update and rebuild:
|
||||
```bash
|
||||
git pull
|
||||
docker compose build portal-app
|
||||
docker compose --profile ops run --rm migrate # no-op when there are no new migrations
|
||||
docker compose up -d portal-app
|
||||
```
|
||||
4. Verify: `GET /api/health/ready` → 200, then log in as admin and as an
|
||||
editorial account.
|
||||
|
||||
**Rollback**: check out the noted commit (`git checkout <commit>`), then
|
||||
`docker compose build portal-app && docker compose up -d portal-app`, and
|
||||
return to `main` with `git checkout main` afterwards. A UI-only release needs no
|
||||
database restore.
|
||||
|
||||
**Release notes popup**: users see "Was ist neu?" once per version after
|
||||
signing in. For the next release, bump `RELEASE.version` and replace the notes
|
||||
in `src/components/layout/release-notes.tsx`.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Mobile Menu Active Contrast Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Make the active mobile portal navigation item readable in both light and dark themes.
|
||||
|
||||
**Architecture:** Keep the existing theme tokens and navigation logic. Add one unlayered semantic CSS class whose `var(--ink)` background and `var(--paper)` foreground outrank the global inherited anchor color, and apply it only to the active mobile link.
|
||||
|
||||
**Tech Stack:** Next.js 16, React 19, Tailwind CSS 4, Vitest, Testing Library
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Light mode must render the active item with white text on a dark surface.
|
||||
- Dark mode must render the active item with black text on a light surface.
|
||||
- Inactive links, desktop navigation, theme tokens, spacing, motion, and routing must remain unchanged.
|
||||
- Production code must follow a witnessed RED/GREEN TDD cycle.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Active Mobile Navigation Contrast
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/components/layout/mobile-portal-menu.test.tsx`
|
||||
- Modify: `src/components/layout/mobile-portal-menu.tsx`
|
||||
- Modify: `src/app/globals.css`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing `MobilePortalMenu` props and the `--ink` / `--paper` theme tokens
|
||||
- Produces: the CSS class `mobile-portal-menu-active` on the single active navigation link
|
||||
|
||||
- [ ] **Step 1: Write the failing regression test**
|
||||
|
||||
Extend the first component test after opening the menu:
|
||||
|
||||
```tsx
|
||||
const activeLink = screen.getByRole("link", { name: "Redaktionen" });
|
||||
const inactiveLink = screen.getByRole("link", { name: "Dashboard" });
|
||||
|
||||
expect(activeLink.getAttribute("class")).toContain("mobile-portal-menu-active");
|
||||
expect(inactiveLink.getAttribute("class")).not.toContain("mobile-portal-menu-active");
|
||||
```
|
||||
|
||||
This test catches removal or accidental application of the semantic inverse-color class.
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/layout/mobile-portal-menu.test.tsx
|
||||
```
|
||||
|
||||
Expected: the active-link assertion fails because the class is not yet present; the test must not fail from a render or selector error.
|
||||
|
||||
- [ ] **Step 3: Implement the minimal component and CSS change**
|
||||
|
||||
In the active branch of `mobile-portal-menu.tsx`, replace the inverse Tailwind color utilities with the semantic class while preserving layout classes:
|
||||
|
||||
```tsx
|
||||
"mobile-portal-menu-active flex min-h-11 items-center rounded-lg px-3 font-semibold"
|
||||
```
|
||||
|
||||
In `globals.css`, directly after the existing mobile menu panel rule, add:
|
||||
|
||||
```css
|
||||
.mobile-portal-menu-active {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the focused test and verify GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/layout/mobile-portal-menu.test.tsx
|
||||
```
|
||||
|
||||
Expected: all mobile-menu tests pass with no warnings.
|
||||
|
||||
- [ ] **Step 5: Run full deterministic verification**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint .
|
||||
./node_modules/.bin/drizzle-kit check
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: every command exits with status 0.
|
||||
|
||||
- [ ] **Step 6: Run the production build**
|
||||
|
||||
Run `./node_modules/.bin/next build --webpack` with the documented non-secret build-time environment values.
|
||||
|
||||
Expected: the optimized production build completes with exit status 0.
|
||||
|
||||
- [ ] **Step 7: Commit the implementation**
|
||||
|
||||
```bash
|
||||
git add src/components/layout/mobile-portal-menu.test.tsx src/components/layout/mobile-portal-menu.tsx src/app/globals.css
|
||||
git commit -m "fix: restore mobile menu active contrast"
|
||||
```
|
||||
@@ -0,0 +1,405 @@
|
||||
# Mobile Portal Navigation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add an accessible mobile-only dropdown that exposes every role-specific portal destination, theme control and sign-out action while leaving desktop navigation unchanged.
|
||||
|
||||
**Architecture:** A focused client component owns the dropdown interaction and receives the existing `NavItem[]` from the server-rendered `PortalShell`. `PortalShell` renders this component only for mobile layouts and keeps its existing desktop controls behind the `sm` breakpoint, avoiding duplicated route catalogues or new dependencies.
|
||||
|
||||
**Tech Stack:** Next.js 16 App Router, React 19, TypeScript, Tailwind CSS 4, Lucide React, Vitest, Testing Library, jsdom.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- The mobile menu is visible only below the Tailwind `sm` breakpoint.
|
||||
- The existing desktop navigation, route names, authorization and sign-out behavior remain unchanged.
|
||||
- The component consumes the existing role-specific `nav: NavItem[]`; no second navigation catalogue is allowed.
|
||||
- The menu closes on link activation, Escape and outside pointer interaction.
|
||||
- Escape returns focus to the trigger.
|
||||
- The active route uses `aria-current="page"` and a high-contrast visual state.
|
||||
- Touch targets are at least 44 pixels high.
|
||||
- No new runtime dependency or animation framework may be added.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Accessible mobile dropdown behavior
|
||||
|
||||
**Files:**
|
||||
- Create: `src/components/layout/mobile-portal-menu.tsx`
|
||||
- Create: `src/components/layout/mobile-portal-menu.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `NavItem` from `@/components/layout/portal-shell`, `ThemeToggle`, `LogoutButton`, and `usePathname()`.
|
||||
- Produces: `MobilePortalMenu({ nav, sectionLabel }: { nav: NavItem[]; sectionLabel: string }): JSX.Element`.
|
||||
|
||||
- [ ] **Step 1: Write the failing interaction tests**
|
||||
|
||||
Create `src/components/layout/mobile-portal-menu.test.tsx` with jsdom, a controlled `usePathname()` mock, and real child controls:
|
||||
|
||||
```tsx
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
const { usePathname } = vi.hoisted(() => ({
|
||||
usePathname: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({ usePathname }));
|
||||
|
||||
import { MobilePortalMenu } from "./mobile-portal-menu";
|
||||
|
||||
const nav = [
|
||||
{ href: "/admin", label: "Dashboard" },
|
||||
{ href: "/admin/redaktionen", label: "Redaktionen" },
|
||||
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
|
||||
{ href: "/admin/audit", label: "Audit" },
|
||||
];
|
||||
|
||||
beforeEach(() => usePathname.mockReturnValue("/admin/redaktionen/abc"));
|
||||
afterEach(cleanup);
|
||||
|
||||
test("opens every mobile portal action and marks the most specific active route", () => {
|
||||
render(<MobilePortalMenu nav={nav} sectionLabel="Administration" />);
|
||||
|
||||
const trigger = screen.getByRole("button", { name: /menü öffnen/i });
|
||||
expect(trigger.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(screen.queryByRole("navigation", { name: /mobile navigation/i })).toBeNull();
|
||||
|
||||
fireEvent.click(trigger);
|
||||
|
||||
expect(trigger.getAttribute("aria-expanded")).toBe("true");
|
||||
expect(screen.getByRole("link", { name: "Dashboard" })).toBeTruthy();
|
||||
expect(screen.getByRole("link", { name: "Redaktionen" }).getAttribute("aria-current")).toBe("page");
|
||||
expect(screen.getByRole("link", { name: "Abrechnungen" })).toBeTruthy();
|
||||
expect(screen.getByRole("link", { name: "Audit" })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /design umschalten/i })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /abmelden/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
test("closes after navigation, Escape and an outside pointer interaction", () => {
|
||||
render(
|
||||
<div>
|
||||
<MobilePortalMenu nav={nav} sectionLabel="Administration" />
|
||||
<button type="button">Außerhalb</button>
|
||||
</div>,
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole("button", { name: /menü öffnen/i });
|
||||
fireEvent.click(trigger);
|
||||
fireEvent.click(screen.getByRole("link", { name: "Audit" }));
|
||||
expect(trigger.getAttribute("aria-expanded")).toBe("false");
|
||||
|
||||
fireEvent.click(trigger);
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(trigger.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
|
||||
fireEvent.click(trigger);
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "Außerhalb" }));
|
||||
expect(trigger.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/layout/mobile-portal-menu.test.tsx
|
||||
```
|
||||
|
||||
Expected: FAIL because `./mobile-portal-menu` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement the minimal client component**
|
||||
|
||||
Create `src/components/layout/mobile-portal-menu.tsx`:
|
||||
|
||||
```tsx
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Menu, X } from "lucide-react";
|
||||
|
||||
import type { NavItem } from "@/components/layout/portal-shell";
|
||||
import { LogoutButton } from "@/components/layout/logout-button";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
|
||||
type MobilePortalMenuProps = {
|
||||
nav: NavItem[];
|
||||
sectionLabel: string;
|
||||
};
|
||||
|
||||
export function MobilePortalMenu({ nav, sectionLabel }: Readonly<MobilePortalMenuProps>) {
|
||||
const pathname = usePathname();
|
||||
const [open, setOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuId = "mobile-portal-menu";
|
||||
|
||||
const activeHref = useMemo(
|
||||
() => nav
|
||||
.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`))
|
||||
.sort((left, right) => right.href.length - left.href.length)[0]?.href,
|
||||
[nav, pathname],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
function closeOnOutsidePointer(event: PointerEvent) {
|
||||
if (!containerRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
}
|
||||
|
||||
function closeOnEscape(event: KeyboardEvent) {
|
||||
if (event.key !== "Escape") return;
|
||||
setOpen(false);
|
||||
triggerRef.current?.focus();
|
||||
}
|
||||
|
||||
document.addEventListener("pointerdown", closeOnOutsidePointer);
|
||||
document.addEventListener("keydown", closeOnEscape);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", closeOnOutsidePointer);
|
||||
document.removeEventListener("keydown", closeOnEscape);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative sm:hidden">
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
aria-controls={menuId}
|
||||
aria-expanded={open}
|
||||
aria-label={open ? "Menü schließen" : "Menü öffnen"}
|
||||
className="inline-flex min-h-11 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm font-semibold"
|
||||
onClick={() => setOpen((current) => !current)}
|
||||
>
|
||||
{open ? <X aria-hidden="true" className="size-5" /> : <Menu aria-hidden="true" className="size-5" />}
|
||||
Menü
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
id={menuId}
|
||||
className="absolute right-0 top-[calc(100%+0.75rem)] z-50 w-[min(22rem,calc(100vw-2rem))] animate-in fade-in slide-in-from-top-2 rounded-xl border border-border bg-background p-2 shadow-xl duration-150 motion-reduce:animate-none"
|
||||
>
|
||||
<p className="px-3 py-2 text-xs font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{sectionLabel}
|
||||
</p>
|
||||
<nav aria-label="Mobile Navigation" className="grid gap-1">
|
||||
{nav.map((item) => {
|
||||
const active = item.href === activeHref;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={active
|
||||
? "flex min-h-11 items-center rounded-lg bg-foreground px-3 font-semibold text-background"
|
||||
: "flex min-h-11 items-center rounded-lg px-3 font-medium hover:bg-muted"}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<div className="mt-2 flex min-h-11 items-center justify-between border-t border-border px-3 pt-2">
|
||||
<span className="text-sm text-muted-foreground">Darstellung</span>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
<div className="mt-2 border-t border-border px-3 pt-2">
|
||||
<LogoutButton />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the focused test and verify GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/layout/mobile-portal-menu.test.tsx
|
||||
```
|
||||
|
||||
Expected: 1 file and 2 tests PASS.
|
||||
|
||||
- [ ] **Step 5: Run typecheck and lint for the new boundary**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint src/components/layout/mobile-portal-menu.tsx src/components/layout/mobile-portal-menu.test.tsx
|
||||
```
|
||||
|
||||
Expected: both commands exit 0 with no errors.
|
||||
|
||||
- [ ] **Step 6: Commit the independently tested component**
|
||||
|
||||
```bash
|
||||
git add src/components/layout/mobile-portal-menu.tsx src/components/layout/mobile-portal-menu.test.tsx
|
||||
git commit -m "feat: add accessible mobile portal menu"
|
||||
```
|
||||
|
||||
### Task 2: Integrate the menu into the shared portal shell
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/components/layout/portal-shell.tsx`
|
||||
- Modify: `src/components/brand/logo.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `MobilePortalMenu({ nav, sectionLabel })` from Task 1 and the existing `PortalShellProps`.
|
||||
- Produces: one shared responsive header used unchanged by `src/app/admin/layout.tsx` and `src/app/redaktion/layout.tsx`.
|
||||
|
||||
- [ ] **Step 1: Extend the existing shell test with the mobile contract**
|
||||
|
||||
In `src/components/brand/logo.test.tsx`, mock `usePathname()` before imports and extend the `PortalShell` test:
|
||||
|
||||
```tsx
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => "/redaktion/alben",
|
||||
}));
|
||||
|
||||
// Existing tests remain. In the PortalShell test, add:
|
||||
const menuTrigger = screen.getByRole("button", { name: /menü öffnen/i });
|
||||
expect(menuTrigger.parentElement?.className).toContain("sm:hidden");
|
||||
fireEvent.click(menuTrigger);
|
||||
expect(screen.getAllByRole("link", { name: "Alben" })).toHaveLength(2);
|
||||
expect(screen.getByRole("navigation", { name: /mobile navigation/i })).toBeTruthy();
|
||||
```
|
||||
|
||||
The two `Alben` links demonstrate that the unchanged desktop link and the
|
||||
mobile dropdown consume the same supplied `nav` entry. The CSS visibility
|
||||
classes ensure only one is exposed visually at a given breakpoint.
|
||||
|
||||
- [ ] **Step 2: Run the shell test and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/brand/logo.test.tsx
|
||||
```
|
||||
|
||||
Expected: FAIL because `PortalShell` does not yet expose the mobile trigger.
|
||||
|
||||
- [ ] **Step 3: Integrate mobile and desktop control groups**
|
||||
|
||||
Modify `src/components/layout/portal-shell.tsx`:
|
||||
|
||||
```tsx
|
||||
import { MobilePortalMenu } from "@/components/layout/mobile-portal-menu";
|
||||
|
||||
// Inside the right-hand header container, preserve sectionLabel and desktop nav,
|
||||
// replace the always-visible controls with:
|
||||
<div className="hidden items-center gap-4 sm:flex">
|
||||
<ThemeToggle />
|
||||
<LogoutButton />
|
||||
</div>
|
||||
<MobilePortalMenu nav={nav} sectionLabel={sectionLabel} />
|
||||
```
|
||||
|
||||
Keep the existing desktop `<nav className="hidden sm:flex ...">` unchanged.
|
||||
Use `px-4 sm:px-6 lg:px-12` on the header row so the mobile trigger and logo fit
|
||||
at 320 pixels without altering tablet/desktop spacing.
|
||||
|
||||
- [ ] **Step 4: Run component tests and verify GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/components/layout/mobile-portal-menu.test.tsx src/components/brand/logo.test.tsx
|
||||
```
|
||||
|
||||
Expected: 2 files and all tests PASS.
|
||||
|
||||
- [ ] **Step 5: Verify admin and editorial route catalogues remain unchanged**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
rg -n 'Dashboard|Redaktionen|Abrechnungen|Audit' src/app/admin/layout.tsx
|
||||
rg -n 'Alben|Merkzettel|Nutzungen|Profil' src/app/redaktion/layout.tsx
|
||||
```
|
||||
|
||||
Expected: all four role-specific destinations remain present in their existing
|
||||
layout and no duplicate catalogue exists in `mobile-portal-menu.tsx`.
|
||||
|
||||
- [ ] **Step 6: Commit shell integration**
|
||||
|
||||
```bash
|
||||
git add src/components/layout/portal-shell.tsx src/components/brand/logo.test.tsx
|
||||
git commit -m "feat: expose portal navigation on mobile"
|
||||
```
|
||||
|
||||
### Task 3: Full verification and production handoff
|
||||
|
||||
**Files:**
|
||||
- Verify only; no production files are added by this task.
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: completed component and shared-shell integration from Tasks 1–2.
|
||||
- Produces: verified Git history ready for push and container rebuild.
|
||||
|
||||
- [ ] **Step 1: Run the complete deterministic suite**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint .
|
||||
./node_modules/.bin/drizzle-kit check
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: all commands exit 0, with no failed tests or lint/type errors.
|
||||
|
||||
- [ ] **Step 2: Run the production build with non-secret verification values**
|
||||
|
||||
```bash
|
||||
env \
|
||||
DATABASE_URL=postgres://portal:change-me@portal-db:5432/portal \
|
||||
BETTER_AUTH_SECRET=replace-with-a-long-random-secret \
|
||||
BETTER_AUTH_URL=https://redaktionen.leon-tonhaeuser.de \
|
||||
IMMICH_BASE_URL=http://immich-server:2283 \
|
||||
IMMICH_API_KEY=replace-with-a-restricted-immich-api-key \
|
||||
SMTP_HOST=smtp.example.com SMTP_PORT=587 \
|
||||
SMTP_USER=portal@example.com SMTP_PASSWORD=replace-with-an-smtp-password \
|
||||
SMTP_FROM=portal@example.com \
|
||||
LEGAL_IMPRINT_URL=https://leon-tonhaeuser.de/impressum \
|
||||
LEGAL_PRIVACY_URL=https://leon-tonhaeuser.de/datenschutz \
|
||||
LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb \
|
||||
NEXT_DISABLE_TURBOPACK=1 \
|
||||
./node_modules/.bin/next build --webpack
|
||||
```
|
||||
|
||||
Expected: optimized production build exits 0 and lists the authenticated admin
|
||||
and editorial routes.
|
||||
|
||||
- [ ] **Step 3: Inspect final scope and repository state**
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git log -4 --oneline
|
||||
```
|
||||
|
||||
Expected: no uncommitted production changes; the design, component and shell
|
||||
integration commits are visible.
|
||||
|
||||
- [ ] **Step 4: Push after user-authorized integration choice**
|
||||
|
||||
```bash
|
||||
git push origin-https main
|
||||
```
|
||||
|
||||
Expected: GitLab advances `main` to the verified shell integration commit.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Produktionshärtung und Nutzertexte – Implementierungsplan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Die bestätigten Sicherheits- und Abrechnungsfehler schließen und die gewünschten Passwort-/Nutzungsnachweis-Texte ergänzen.
|
||||
|
||||
**Architecture:** Bestehende Servicegrenzen bleiben erhalten. Autorisierung und Abrechnung werden an ihren serverseitigen Wahrheitsquellen korrigiert; UI und E-Mail konsumieren nur daraus abgeleitete, testbare Ergebnisse.
|
||||
|
||||
**Tech Stack:** Node.js 24, Next.js 16, React 19, TypeScript, Drizzle/PostgreSQL, Better Auth, Vitest.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Keine Clientdaten bestimmen Editorial-ID oder Preis.
|
||||
- Keine Historie wird gelöscht, um Abrechnungsfehler zu kaschieren.
|
||||
- Alle Geldbeträge bleiben Integer-Cents.
|
||||
- Alle Monatsgrenzen verwenden Europe/Berlin und halb offene UTC-Spannen.
|
||||
- Jede Produktionsänderung benötigt vorher einen fehlschlagenden Regressionstest.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Thumbnail-Autorisierung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts`
|
||||
- Test: `src/app/api/assets/[assetId]/thumbnail/route.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ImmichClient.listAlbumsForAsset`, `ImmichClient.getAlbum`.
|
||||
- Produces: generischer 404 oder autorisierte Thumbnail-Response.
|
||||
|
||||
- [ ] Test ergänzen: bekannte Fremd-Asset-ID trotz vorhandener Grants ergibt 404; Admin ohne passende Album-Cover-Bindung ergibt 404.
|
||||
- [ ] Fokussierten Test ausführen und erwartetes RED bestätigen.
|
||||
- [ ] Asset-Alben mit Grants schneiden und Admin-Cover-Bindung wiederherstellen.
|
||||
- [ ] Test erneut ausführen und GREEN bestätigen.
|
||||
|
||||
### Task 2: Flatrate-Wahrheit
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/admin/redaktionen/[id]/actions.ts`
|
||||
- Modify: `src/modules/usages/service.ts`
|
||||
- Modify: `src/modules/billing/reports.ts`
|
||||
- Test: `src/app/admin/redaktionen/[id]/actions.test.ts`
|
||||
- Test: `src/modules/usages/service.test.ts`
|
||||
- Test: `src/modules/billing/reports.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: validierte Flatrate-Konfiguration und konsistenter `flatrateCentsSnapshot`.
|
||||
|
||||
- [ ] RED: aktive Flatrate ohne positiven Preis wird abgelehnt.
|
||||
- [ ] RED: Berliner Monatsrand wird korrekt gezählt.
|
||||
- [ ] RED: gerenderter/persistierter Snapshot enthält denselben Pauschalbetrag wie `netTotalCents`.
|
||||
- [ ] Minimale Validierungs-, Perioden- und Snapshotkorrektur implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 3: ZIP-Abrechnung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/api/lightbox/bulk-download/route.ts`
|
||||
- Create: `src/app/api/lightbox/bulk-download/route.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: Same-Origin-geschützten ZIP-Stream und terminale Downloadzustände.
|
||||
|
||||
- [ ] RED: Cross-Origin wird vor Seiteneffekten abgewiesen.
|
||||
- [ ] RED: Archivfehler nach Bytes markiert `interrupted`; Fehler vor Bytes voidet neue Nutzung; erfolgreicher Abschluss markiert erst nach Archivfinalisierung `completed`.
|
||||
- [ ] RED: Response enthält `private, no-store` und `nosniff`.
|
||||
- [ ] Handler-Abhängigkeiten isolieren und minimale Stream-/Settlement-Logik implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 4: Rate-Limit-Verdrahtung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/auth/auth.ts`
|
||||
- Modify: `src/app/(public)/registrieren/page.tsx`
|
||||
- Modify: `src/app/api/download-intents/intent-handler.ts`
|
||||
- Modify: `src/modules/albums/catalog.ts`
|
||||
- Modify: `src/app/api/lightbox/bulk-download/route.ts`
|
||||
- Test: zugehörige Auth-, Intent-, Catalog- und Bulk-Tests.
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 429 plus `Retry-After`; persistente Portal-Limits und explizite Better-Auth-Regeln.
|
||||
|
||||
- [ ] RED-Tests pro produktivem Pfad ergänzen.
|
||||
- [ ] Stabile gehashte Schlüssel und 429-Response zentral implementieren.
|
||||
- [ ] Better-Auth-Regeln für Anmeldung und Reset konfigurieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 5: Nutzertexte
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/auth/public-forms.tsx`
|
||||
- Modify: `src/modules/auth/public-forms.test.tsx`
|
||||
- Modify: `src/modules/email/service.ts`
|
||||
- Create/Modify: `src/modules/email/service.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: wahrheitsgemäße Passwort-Erfolgsmeldung mit Anmeldelink und eindeutig bezeichneten Nutzungsnachweis.
|
||||
|
||||
- [ ] RED: erfolgreicher Reset zeigt „Passwort wurde aktualisiert“ und Link `/anmelden`; API-Fehler zeigt keinen Erfolg.
|
||||
- [ ] RED: Billing-Mail enthält in Text und HTML „keine Rechnung“ sowie Hinweis auf separate Rechnung.
|
||||
- [ ] Minimale UI- und Mail-Content-Änderung implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 6: Quality Gates und Übergabe
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/mail/mailer.test.ts`
|
||||
- Modify: `src/components/brand/logo.test.tsx`
|
||||
- Modify: `src/components/theme-toggle.tsx`
|
||||
- Modify: `eslint.config.mjs`
|
||||
- Delete: `drizzle/0007_album_auto_rules_and_archive.sql`
|
||||
- Create: `docs/legal/agb-und-lizenzbedingungen-entwurf.md`
|
||||
|
||||
- [ ] Veraltete Erwartungen an bewusst geändertes HTML/Logo aktualisieren.
|
||||
- [ ] Theme-Toggle lint-konform und hydration-sicher gestalten; `.worktrees/**` ignorieren.
|
||||
- [ ] Verwaiste, nicht journalisierte Doppel-Migration entfernen.
|
||||
- [ ] AGB-/Lizenzentwurf auf Basis offizieller deutscher Rechtsquellen erstellen.
|
||||
- [ ] Vollsuite, Typecheck, Lint, Drizzle-Check, Build und `git diff --check` ausführen.
|
||||
@@ -0,0 +1,353 @@
|
||||
# Session Expiry and Error Recovery Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Redirect expired protected-page sessions to `/anmelden` and provide a branded retry/sign-in recovery page for genuine unexpected rendering failures.
|
||||
|
||||
**Architecture:** A server-only page-access wrapper classifies the existing `PrincipalAuthorizationError` before protected layouts render. Only `AUTHENTICATION_REQUIRED` becomes a Next.js redirect; every other error propagates to a root route error boundary implemented as a small client component.
|
||||
|
||||
**Tech Stack:** Next.js 16 App Router, React 19, TypeScript, Tailwind CSS 4, Vitest, Testing Library, jsdom.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Expired sessions redirect exactly to `/anmelden`.
|
||||
- Only `PrincipalAuthorizationError("AUTHENTICATION_REQUIRED")` is redirected.
|
||||
- Other authorization, database, Immich and programming errors are rethrown unchanged.
|
||||
- Existing API response behavior, account-status rules and session duration remain unchanged.
|
||||
- The unexpected-error UI exposes no stack, raw message or digest.
|
||||
- Recovery controls are labelled exactly `Erneut versuchen` and `Zur Anmeldung`.
|
||||
- No database migration or new dependency is allowed.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Protected-page authentication boundary
|
||||
|
||||
**Files:**
|
||||
- Create: `src/modules/auth/page-access.ts`
|
||||
- Create: `src/modules/auth/page-access.test.ts`
|
||||
- Modify: `src/app/admin/layout.tsx`
|
||||
- Modify: `src/app/redaktion/layout.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `PrincipalAuthorizationError`, Next.js `redirect`, existing `requireAdmin` and `requireEditorial` page guards.
|
||||
- Produces: `requirePageAccess<T>(loadPrincipal: () => Promise<T>): Promise<T>`.
|
||||
|
||||
- [ ] **Step 1: Write the failing page-access tests**
|
||||
|
||||
Create `src/modules/auth/page-access.test.ts`:
|
||||
|
||||
```ts
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
const { redirect } = vi.hoisted(() => ({
|
||||
redirect: vi.fn((destination: string): never => {
|
||||
throw new Error(`NEXT_REDIRECT:${destination}`);
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({ redirect }));
|
||||
|
||||
import { PrincipalAuthorizationError } from "./principal";
|
||||
import { requirePageAccess } from "./page-access";
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
test("redirects an expired protected-page session to sign-in", async () => {
|
||||
const expired = new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED");
|
||||
|
||||
await expect(
|
||||
requirePageAccess(async () => {
|
||||
throw expired;
|
||||
}),
|
||||
).rejects.toThrow("NEXT_REDIRECT:/anmelden");
|
||||
});
|
||||
|
||||
test("rethrows non-session failures unchanged", async () => {
|
||||
const unavailable = new Error("database unavailable");
|
||||
|
||||
await expect(
|
||||
requirePageAccess(async () => {
|
||||
throw unavailable;
|
||||
}),
|
||||
).rejects.toBe(unavailable);
|
||||
expect(redirect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("returns the principal when the page guard succeeds", async () => {
|
||||
const principal = { userId: "admin-1" };
|
||||
|
||||
await expect(requirePageAccess(async () => principal)).resolves.toBe(principal);
|
||||
expect(redirect).not.toHaveBeenCalled();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because `./page-access` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement the minimal server-only boundary**
|
||||
|
||||
Create `src/modules/auth/page-access.ts`:
|
||||
|
||||
```ts
|
||||
import "server-only";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
|
||||
export async function requirePageAccess<T>(
|
||||
loadPrincipal: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await loadPrincipal();
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof PrincipalAuthorizationError &&
|
||||
error.code === "AUTHENTICATION_REQUIRED"
|
||||
) {
|
||||
redirect("/anmelden");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the focused test and verify GREEN**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts
|
||||
```
|
||||
|
||||
Expected: 1 file and 3 tests PASS.
|
||||
|
||||
- [ ] **Step 5: Integrate both protected layouts**
|
||||
|
||||
In `src/app/admin/layout.tsx`, import `requirePageAccess` and replace the direct
|
||||
guard call with:
|
||||
|
||||
```ts
|
||||
await requirePageAccess(() => requireAdmin(new Headers(await headers())));
|
||||
```
|
||||
|
||||
In `src/app/redaktion/layout.tsx`, import `requirePageAccess` and replace the
|
||||
direct guard call with:
|
||||
|
||||
```ts
|
||||
await requirePageAccess(requireEditorial);
|
||||
```
|
||||
|
||||
Do not alter either layout's `PortalShell`, role navigation or principal guard.
|
||||
|
||||
- [ ] **Step 6: Run focused tests, typecheck and lint**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/auth/page-access.test.ts src/modules/auth/principal.test.ts
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint src/modules/auth/page-access.ts src/modules/auth/page-access.test.ts src/app/admin/layout.tsx src/app/redaktion/layout.tsx
|
||||
```
|
||||
|
||||
Expected: all commands exit 0.
|
||||
|
||||
- [ ] **Step 7: Commit the page-access behavior**
|
||||
|
||||
```bash
|
||||
git add src/modules/auth/page-access.ts src/modules/auth/page-access.test.ts src/app/admin/layout.tsx src/app/redaktion/layout.tsx
|
||||
git commit -m "fix: redirect expired portal sessions"
|
||||
```
|
||||
|
||||
### Task 2: Branded unexpected-error recovery page
|
||||
|
||||
**Files:**
|
||||
- Create: `src/app/error.tsx`
|
||||
- Create: `src/app/error.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Next.js error-boundary props `{ error: Error & { digest?: string }; reset: () => void }`, `Link`, and the existing `Button` component.
|
||||
- Produces: the root route error UI for uncaught child-segment rendering errors.
|
||||
|
||||
- [ ] **Step 1: Write the failing recovery UI test**
|
||||
|
||||
Create `src/app/error.test.tsx`:
|
||||
|
||||
```tsx
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import PortalError from "./error";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("offers retry and sign-in without exposing server details", () => {
|
||||
const reset = vi.fn();
|
||||
render(
|
||||
<PortalError
|
||||
error={Object.assign(new Error("database password leaked"), {
|
||||
digest: "private-digest",
|
||||
})}
|
||||
reset={reset}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Diese Seite konnte nicht geladen werden." }),
|
||||
).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Erneut versuchen" }));
|
||||
expect(reset).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole("link", { name: "Zur Anmeldung" }).getAttribute("href")).toBe(
|
||||
"/anmelden",
|
||||
);
|
||||
expect(document.body.textContent).not.toContain("database password leaked");
|
||||
expect(document.body.textContent).not.toContain("private-digest");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/app/error.test.tsx
|
||||
```
|
||||
|
||||
Expected: FAIL because `src/app/error.tsx` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement the minimal recovery page**
|
||||
|
||||
Create `src/app/error.tsx`:
|
||||
|
||||
```tsx
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type PortalErrorProps = {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
export default function PortalError({ reset }: Readonly<PortalErrorProps>) {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<span className="wordmark">Leon Tonhäuser</span>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
|
||||
<section className="account-panel" aria-labelledby="error-title">
|
||||
<p className="eyebrow">Verbindung unterbrochen</p>
|
||||
<h1 id="error-title">Diese Seite konnte nicht geladen werden.</h1>
|
||||
<p className="lede">
|
||||
Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap gap-3">
|
||||
<Button className="min-h-11" size="lg" type="button" onClick={reset}>
|
||||
Erneut versuchen
|
||||
</Button>
|
||||
<Button asChild className="min-h-11" size="lg" variant="outline">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `error` prop remains part of the required Next.js interface but is not
|
||||
rendered or logged by this component.
|
||||
|
||||
- [ ] **Step 4: Run the focused test and verify GREEN**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/app/error.test.tsx
|
||||
```
|
||||
|
||||
Expected: 1 file and 1 test PASS.
|
||||
|
||||
- [ ] **Step 5: Run typecheck and focused lint**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint src/app/error.tsx src/app/error.test.tsx
|
||||
```
|
||||
|
||||
Expected: both commands exit 0.
|
||||
|
||||
- [ ] **Step 6: Commit the recovery UI**
|
||||
|
||||
```bash
|
||||
git add src/app/error.tsx src/app/error.test.tsx
|
||||
git commit -m "feat: add portal error recovery page"
|
||||
```
|
||||
|
||||
### Task 3: Full verification and deployment handoff
|
||||
|
||||
**Files:**
|
||||
- Verify only; no production file is added by this task.
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: completed page-access and recovery-page tasks.
|
||||
- Produces: verified commits ready for integration and a container-only deployment.
|
||||
|
||||
- [ ] **Step 1: Run the full deterministic verification**
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint .
|
||||
./node_modules/.bin/drizzle-kit check
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: all commands exit 0 with no failed tests, type errors, lint errors or
|
||||
migration inconsistencies.
|
||||
|
||||
- [ ] **Step 2: Run the production build**
|
||||
|
||||
```bash
|
||||
env \
|
||||
DATABASE_URL=postgres://portal:change-me@portal-db:5432/portal \
|
||||
BETTER_AUTH_SECRET=replace-with-a-long-random-secret \
|
||||
BETTER_AUTH_URL=https://redaktionen.leon-tonhaeuser.de \
|
||||
IMMICH_BASE_URL=http://immich-server:2283 \
|
||||
IMMICH_API_KEY=replace-with-a-restricted-immich-api-key \
|
||||
SMTP_HOST=smtp.example.com SMTP_PORT=587 \
|
||||
SMTP_USER=portal@example.com SMTP_PASSWORD=replace-with-an-smtp-password \
|
||||
SMTP_FROM=portal@example.com \
|
||||
LEGAL_IMPRINT_URL=https://leon-tonhaeuser.de/impressum \
|
||||
LEGAL_PRIVACY_URL=https://leon-tonhaeuser.de/datenschutz \
|
||||
LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb \
|
||||
NEXT_DISABLE_TURBOPACK=1 \
|
||||
./node_modules/.bin/next build --webpack
|
||||
```
|
||||
|
||||
Expected: production build exits 0 and includes `/anmelden`, `/admin` and
|
||||
`/redaktion` routes.
|
||||
|
||||
- [ ] **Step 3: Verify scope and history**
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git log -5 --oneline
|
||||
```
|
||||
|
||||
Expected: no uncommitted implementation changes and both feature commits are
|
||||
present.
|
||||
|
||||
- [ ] **Step 4: Deploy without database migration**
|
||||
|
||||
```bash
|
||||
git pull --ff-only origin main
|
||||
docker compose build --pull portal-app
|
||||
docker compose up -d --no-deps --force-recreate portal-app
|
||||
```
|
||||
|
||||
Expected: the refreshed container serves the redirect and recovery UI; Zoraxy
|
||||
and PostgreSQL require no change.
|
||||
@@ -0,0 +1,166 @@
|
||||
# Search Result Download Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Show the existing `Original laden` workflow on every authorized global search result, even when Immich omits the asset's album association.
|
||||
|
||||
**Architecture:** The server-side album catalog already fans a global search out into one request per granted album. Normalize each returned page at that boundary by adding the queried granted album ID when the asset does not include it; the existing gallery then receives enough trusted context to render its unchanged `UsageDialog` on both the tile and lightbox.
|
||||
|
||||
**Tech Stack:** Next.js 16, React 19, TypeScript, Vitest, Testing Library, Immich API adapter
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Reuse the existing `UsageDialog`, download API, pricing, prior-usage, authorization, and accounting logic.
|
||||
- Album context must come from the server-side granted-album query, never from browser input.
|
||||
- Do not issue an additional Immich request per search result.
|
||||
- Preserve album associations already returned by Immich.
|
||||
- Do not change the database schema or add a migration.
|
||||
- Production code must follow a witnessed RED/GREEN TDD cycle.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Restore Authorized Album Context on Search Results
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/albums/catalog.test.ts`
|
||||
- Modify: `src/modules/albums/catalog.ts`
|
||||
- Modify: `src/modules/albums/catalog-content.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ImmichSearchPage`, the granted `albumIds` passed to the existing private `searchAlbum` function, and `PhotoGallery`'s existing `downloadOptions`
|
||||
- Produces: each returned `ImmichAsset` contains the queried authorized `{ id: string }` album association; `PhotoGallery` therefore renders its existing `UsageDialog`
|
||||
|
||||
- [ ] **Step 1: Write the failing catalog regression test**
|
||||
|
||||
Add an asset fixture whose `albums` array is empty, make `searchPhotos` return it for the granted album `allowed`, and assert the catalog result contains the server-selected association:
|
||||
|
||||
```ts
|
||||
test("restores the queried granted album when Immich omits an asset album association", async () => {
|
||||
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
|
||||
immich.searchPhotos.mockResolvedValue({
|
||||
items: [{
|
||||
id: "asset-1",
|
||||
type: "IMAGE",
|
||||
originalFileName: "tor.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [],
|
||||
}],
|
||||
total: 1,
|
||||
nextPage: null,
|
||||
previousPage: null,
|
||||
});
|
||||
|
||||
const result = await catalog.searchVisiblePhotos("editorial-1", { page: 1 });
|
||||
|
||||
expect(result.items[0]?.albums).toEqual([{ id: "allowed" }]);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused catalog test and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/albums/catalog.test.ts
|
||||
```
|
||||
|
||||
Expected: the new assertion fails with `[]` instead of `[{ id: "allowed" }]`; existing tests remain green.
|
||||
|
||||
- [ ] **Step 3: Implement minimal album-context normalization**
|
||||
|
||||
In `searchAlbum`, await the existing Immich response and return a copied page. For every item, preserve it unchanged when its `albums` already contains the queried album. Otherwise prepend the queried album association:
|
||||
|
||||
```ts
|
||||
const searchPage = await immich.searchPhotos({
|
||||
albumIds,
|
||||
...(description === undefined ? {} : { description }),
|
||||
type: "IMAGE",
|
||||
page,
|
||||
size,
|
||||
});
|
||||
const queriedAlbumId = albumIds[0];
|
||||
return {
|
||||
...searchPage,
|
||||
items: queriedAlbumId
|
||||
? searchPage.items.map((asset) => asset.albums.some(({ id }) => id === queriedAlbumId)
|
||||
? asset
|
||||
: { ...asset, albums: [{ id: queriedAlbumId }, ...asset.albums] })
|
||||
: searchPage.items,
|
||||
};
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the focused catalog test and verify GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/albums/catalog.test.ts
|
||||
```
|
||||
|
||||
Expected: all catalog tests pass.
|
||||
|
||||
- [ ] **Step 5: Add the gallery regression test**
|
||||
|
||||
In `catalog-content.test.tsx`, render `PhotoGallery` without its top-level `albumId`, but with an item containing the restored album association and valid `downloadOptions`. Assert the tile offers `Original laden`, open the photo lightbox, and assert the lightbox dialog also contains `Original laden`:
|
||||
|
||||
```tsx
|
||||
test("offers the existing download workflow on a global search result and its lightbox", () => {
|
||||
render(
|
||||
<PhotoGallery
|
||||
albumName="Alle Alben"
|
||||
downloadOptions={{ priceCents: 100, priorUsagesByAsset: {} }}
|
||||
items={[{
|
||||
...photo,
|
||||
id: "22222222-2222-4222-8222-222222222222",
|
||||
albums: [{ id: "33333333-3333-4333-8333-333333333333" }],
|
||||
}]}
|
||||
showAlbumName
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: /original laden/i })).not.toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: /tor-des-sieges\.jpg vergrößern/i }));
|
||||
expect(within(screen.getByRole("dialog")).getByRole("button", { name: /original laden/i })).not.toBeNull();
|
||||
});
|
||||
```
|
||||
|
||||
Import `within` from Testing Library. This test protects reuse of the existing dialog in both search-result surfaces without testing framework internals.
|
||||
|
||||
- [ ] **Step 6: Run both focused suites**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src/modules/albums/catalog.test.ts src/modules/albums/catalog-content.test.tsx
|
||||
```
|
||||
|
||||
Expected: both files and all contained tests pass without warnings.
|
||||
|
||||
- [ ] **Step 7: Run full deterministic verification**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
./node_modules/.bin/vitest run src
|
||||
./node_modules/.bin/tsc --noEmit
|
||||
./node_modules/.bin/eslint .
|
||||
./node_modules/.bin/drizzle-kit check
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected: every command exits with status 0.
|
||||
|
||||
- [ ] **Step 8: Run the production build**
|
||||
|
||||
Run `./node_modules/.bin/next build --webpack` with the documented non-secret build-time environment values.
|
||||
|
||||
Expected: the optimized production build completes with exit status 0.
|
||||
|
||||
- [ ] **Step 9: Commit the implementation**
|
||||
|
||||
```bash
|
||||
git add src/modules/albums/catalog.test.ts src/modules/albums/catalog.ts src/modules/albums/catalog-content.test.tsx
|
||||
git commit -m "feat: enable downloads from search results"
|
||||
```
|
||||
@@ -0,0 +1,42 @@
|
||||
# Mobile Menu Active Contrast Design
|
||||
|
||||
## Context
|
||||
|
||||
The active navigation link in the mobile portal menu uses Tailwind's
|
||||
`text-background` utility. The project also defines an unlayered global
|
||||
`a { color: inherit; }` rule. Unlayered CSS outranks Tailwind utilities in the
|
||||
cascade, so the link inherits the surrounding text color instead of using the
|
||||
intended inverse color. This produces dark text on a dark active background in
|
||||
light mode and the corresponding low-contrast result in dark mode.
|
||||
|
||||
## Design
|
||||
|
||||
Give the active mobile navigation link one semantic class owned by the mobile
|
||||
menu component. Define that class in the existing global stylesheet, outside
|
||||
Tailwind's utility layer, with the portal's established inverse theme tokens:
|
||||
|
||||
- background: `var(--ink)`
|
||||
- text: `var(--paper)`
|
||||
|
||||
The existing tokens already reverse with the selected theme. The result is a
|
||||
dark surface with white text in light mode and a light surface with black text
|
||||
in dark mode. Inactive links, menu spacing, motion, routing, and interaction
|
||||
remain unchanged.
|
||||
|
||||
## Verification
|
||||
|
||||
Extend the existing mobile-menu component test to assert that the active link
|
||||
receives the semantic contrast class while an inactive link does not. Observe
|
||||
the new test fail before adding the production class, then pass after the CSS
|
||||
and component changes. Run the focused test, all source tests, TypeScript,
|
||||
ESLint, and the production webpack build.
|
||||
|
||||
## Scope
|
||||
|
||||
This change is limited to:
|
||||
|
||||
- `src/components/layout/mobile-portal-menu.tsx`
|
||||
- `src/components/layout/mobile-portal-menu.test.tsx`
|
||||
- `src/app/globals.css`
|
||||
|
||||
No theme tokens, desktop navigation, or other link styles will be changed.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Mobile Portal Navigation Design
|
||||
|
||||
## Goal
|
||||
|
||||
Authenticated admin and editorial users must be able to reach every portal
|
||||
section on a mobile viewport. The existing desktop navigation remains
|
||||
unchanged.
|
||||
|
||||
## Scope
|
||||
|
||||
The shared `PortalShell` gains one mobile-only dropdown trigger. The dropdown
|
||||
uses the same role-specific `nav` items already supplied by the admin and
|
||||
editorial layouts, so no second navigation catalogue is introduced.
|
||||
|
||||
The mobile header contains:
|
||||
|
||||
- the existing brand link;
|
||||
- one labelled menu button with a menu/close icon.
|
||||
|
||||
The open dropdown contains:
|
||||
|
||||
- every role-specific navigation destination;
|
||||
- the existing theme control;
|
||||
- the existing sign-out action in a visually separated action row.
|
||||
|
||||
On `sm` and larger viewports, the current inline navigation, theme control and
|
||||
sign-out button remain visible and the mobile trigger and dropdown are hidden.
|
||||
|
||||
## Interaction
|
||||
|
||||
- The trigger exposes its state with `aria-expanded` and references the menu
|
||||
with `aria-controls`.
|
||||
- Activating the trigger toggles the dropdown.
|
||||
- Selecting a navigation link closes the dropdown before navigation.
|
||||
- Pressing Escape closes the dropdown and returns focus to the trigger.
|
||||
- Clicking outside the dropdown closes it.
|
||||
- The current route is indicated visually and with `aria-current="page"`.
|
||||
- All interactive rows provide a touch target of at least 44 pixels.
|
||||
|
||||
## Visual Direction
|
||||
|
||||
The menu follows the portal's restrained black-and-white identity. It appears
|
||||
directly below the sticky masthead, inset from the viewport edges, with a solid
|
||||
background, fine border and modest shadow. Navigation rows use clear spacing
|
||||
and typography rather than decorative elements. The active destination uses a
|
||||
high-contrast filled state. Motion is limited to a short opacity/position
|
||||
transition and is disabled when reduced motion is requested.
|
||||
|
||||
## Component Boundary
|
||||
|
||||
A focused client component, `MobilePortalMenu`, owns open state, focus,
|
||||
outside-click handling, Escape handling and active-route detection. It receives
|
||||
only `nav` and `sectionLabel`. `PortalShell` remains a server component and
|
||||
renders this client boundary alongside the unchanged desktop controls.
|
||||
|
||||
The existing `ThemeToggle` and `LogoutButton` are reused inside the mobile
|
||||
dropdown. Separate desktop instances remain in the desktop-only control group;
|
||||
CSS breakpoints ensure only one instance of each control is interactive at a
|
||||
time.
|
||||
|
||||
## Verification
|
||||
|
||||
Component tests cover:
|
||||
|
||||
- the closed initial state and correct accessible trigger state;
|
||||
- opening the menu and exposing all supplied navigation destinations;
|
||||
- rendering the theme and sign-out actions inside the open mobile menu;
|
||||
- indicating the active destination;
|
||||
- closing on link activation, Escape and outside click.
|
||||
|
||||
The existing full test, typecheck, lint and production-build checks must remain
|
||||
green. A mobile viewport smoke check verifies that desktop controls are hidden
|
||||
and the dropdown provides every role-specific destination.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Changing desktop navigation or route names.
|
||||
- Adding nested navigation levels.
|
||||
- Changing authentication, authorization or sign-out behavior.
|
||||
- Adding a full-screen drawer or animation framework.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Produktionshärtung und Nutzertexte – Design
|
||||
|
||||
## Ziel
|
||||
|
||||
Die nach dem Portal-Audit bestätigten Autorisierungs-, Abrechnungs- und Schutzlücken werden geschlossen. Zusätzlich erhalten Nutzer nach einem erfolgreichen Passwortwechsel eine eindeutige Anmeldung-Aufforderung, und der per E-Mail versandte PDF-Anhang wird unmissverständlich als Nutzungsnachweis statt als Rechnung bezeichnet.
|
||||
|
||||
## Freigegebener Umfang
|
||||
|
||||
Der Nutzer hat die im Audit vorgeschlagene Reihenfolge und die dort beschriebenen Korrekturen freigegeben. Änderungen bleiben auf folgende Bereiche begrenzt:
|
||||
|
||||
1. Thumbnail-Zugriff nur für Assets in aktuell freigegebenen Alben; Admin-Zugriff nur auf ein an ein Album gebundenes Cover.
|
||||
2. Flatrate nur mit positivem Preis; Berlin-sichere Monatsgrenzen; derselbe serverseitig ermittelte Pauschal-Snapshot in Summe, PDF und Datenbank.
|
||||
3. ZIP-Downloads mit Same-Origin-Prüfung, privaten No-Store-Headern, Abbruchpropagierung und wahrheitsgemäßen Terminalzuständen.
|
||||
4. Bestehende Rate-Limit-Policies werden an die produktiven Pfade angebunden. Auth-Endpunkte verwenden die Better-Auth-Regeln; registrierungs- und portalspezifische Pfade verwenden den vorhandenen PostgreSQL-Limiter.
|
||||
5. Passwort-Reset zeigt nur bei bestätigtem API-Erfolg einen Link zur Anmeldung; Fehler bleiben sichtbar.
|
||||
6. Abrechnungs-E-Mails heißen „Nutzungsnachweis“ und weisen in Text und HTML darauf hin, dass die Rechnung separat folgt.
|
||||
7. Veraltete Tests und die verwaiste Doppel-Migration werden bereinigt.
|
||||
|
||||
## Datenfluss und Sicherheitsgrenzen
|
||||
|
||||
### Thumbnails
|
||||
|
||||
Die Redaktion wird wie bisher aus der Session bestimmt. Danach werden die aktuellen Grant-IDs mit den durch Immich für das Asset gelieferten Album-IDs geschnitten. Eine leere Schnittmenge ergibt denselben generischen 404 wie ein unbekanntes Asset. Admins müssen `albumId` übergeben; nur `album.albumThumbnailAssetId === assetId` ist zulässig.
|
||||
|
||||
### Flatrate
|
||||
|
||||
Aktivierung ohne positiven Preis wird abgelehnt. `buildSnapshot` ist die einzige Quelle für den Pauschalbetrag. Der zurückgegebene Wert wird für PDF, Gesamtbetrag und persistierten Report wiederverwendet. Monatslimits verwenden `monthPeriod(..., "Europe/Berlin")` und eine halb offene UTC-Spanne.
|
||||
|
||||
### ZIP
|
||||
|
||||
Jeder Claim bleibt einem Asset zugeordnet. Ein vollständig erzeugtes und geschlossenenes Archiv setzt erfolgreich eingebrachte Events auf `completed`. Vor dem ersten Byte wird `failed_before_delivery` verwendet, nach Bytes `interrupted`. Abbruch oder Archivfehler terminalisiert alle bereits geclaimten, noch offenen Events; noch nicht begonnene Assets erzeugen keine Nutzung. Der Response ist `private, no-store` und `nosniff`.
|
||||
|
||||
### Rate-Limits
|
||||
|
||||
Authentifizierte Portalpfade verwenden stabile Schlüssel aus der serverseitigen Editorial-ID. Registrierung verwendet einen SHA-256-Schlüssel aus normalisierter E-Mail und einer vom Reverse Proxy gesetzten Clientadresse; Rohdaten werden nicht gespeichert. Eine Überschreitung liefert 429 und `Retry-After`. Better Auth erhält explizite Produktionsregeln für Anmeldung und Passwort-Reset.
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
- Autorisierungsfehler verraten weder Asset-Existenz noch Fremdzugriff.
|
||||
- Abrechnungsfehler löschen keine Historie.
|
||||
- Ein ungültiger oder verbrauchter Passwort-Reset-Link zeigt keine falsche Erfolgsmeldung.
|
||||
- E-Mail-Versandfehler ändern nicht den bereits atomar finalisierten Report.
|
||||
|
||||
## Tests
|
||||
|
||||
Jede Verhaltensänderung beginnt mit einem reproduzierenden RED-Test. Danach laufen fokussierte Tests, die vollständige deterministische Suite, Typecheck, Lint, Drizzle-Check und Produktionsbuild. Testcontainers-/E2E-Tests werden ausgeführt, sofern Docker verfügbar ist; andernfalls bleibt der externe Blocker dokumentiert.
|
||||
|
||||
## AGB-Übergabe
|
||||
|
||||
Der AGB-/Lizenzbedingungen-Entwurf wird getrennt von der Portalimplementierung erstellt. Er ist eine Arbeitsvorlage für die Hauptwebsite, enthält markierte Betreiber-/Vergütungsplatzhalter und muss vor Veröffentlichung anwaltlich geprüft werden.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Session Expiry and Error Recovery Design
|
||||
|
||||
## Goal
|
||||
|
||||
Refreshing a protected page after the session expires must not produce the
|
||||
generic Next.js server error screen. Users must be returned to the existing
|
||||
sign-in page, while genuine unexpected rendering failures receive a branded
|
||||
recovery screen.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The admin and editorial layouts call principal guards during server rendering.
|
||||
An expired session causes `PrincipalAuthorizationError` with code
|
||||
`AUTHENTICATION_REQUIRED`. Neither protected layout handles this expected
|
||||
state, and the application has no route-level `error.tsx`, so Next.js renders
|
||||
its generic production error page.
|
||||
|
||||
## Expected Authentication Handling
|
||||
|
||||
A small server-only page-access boundary executes the existing principal guard.
|
||||
It handles only `PrincipalAuthorizationError("AUTHENTICATION_REQUIRED")` by
|
||||
calling `redirect("/anmelden")`. Every other authorization or infrastructure
|
||||
error is rethrown unchanged.
|
||||
|
||||
Both `src/app/admin/layout.tsx` and `src/app/redaktion/layout.tsx` use this
|
||||
boundary. API routes retain their existing HTTP error behavior. Authentication,
|
||||
session duration and account status rules are not changed.
|
||||
|
||||
## Unexpected Error Recovery
|
||||
|
||||
`src/app/error.tsx` provides a client-side route error boundary for unexpected
|
||||
rendering failures below the root layout. It follows the portal's black-and-
|
||||
white visual language and contains:
|
||||
|
||||
- the heading `Diese Seite konnte nicht geladen werden.`;
|
||||
- a short instruction to retry or sign in again;
|
||||
- `Erneut versuchen`, which invokes Next.js' supplied `reset()` callback;
|
||||
- `Zur Anmeldung`, which navigates directly to `/anmelden`.
|
||||
|
||||
The page does not expose stack traces, database errors or the Next.js error
|
||||
digest. It does not turn authorization failures other than an expired session
|
||||
into login redirects; those remain visible as unexpected failures for diagnosis.
|
||||
|
||||
## Verification
|
||||
|
||||
Automated tests prove that:
|
||||
|
||||
- an expired page session redirects exactly to `/anmelden`;
|
||||
- non-authentication errors are rethrown;
|
||||
- the error boundary renders both recovery controls;
|
||||
- `Erneut versuchen` calls `reset()` once;
|
||||
- `Zur Anmeldung` links exactly to `/anmelden`.
|
||||
|
||||
The complete deterministic suite, typecheck, lint and production build must
|
||||
remain green. No database migration or new dependency is required.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Changing session expiry duration.
|
||||
- Automatically retrying database or Immich failures.
|
||||
- Changing API response status codes.
|
||||
- Creating a separate public home-page recovery action.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Download aus Suchergebnissen – Design
|
||||
|
||||
Stand: 12. August 2026
|
||||
Status: fachlich freigegeben
|
||||
|
||||
## Ziel
|
||||
|
||||
Redaktionen können ein Foto direkt aus der albumübergreifenden Suche genauso
|
||||
herunterladen wie aus einer einzelnen Albumansicht. Der bestehende Dialog für
|
||||
neue Nutzungen und kostenfreie Wiederholungsdownloads wird unverändert
|
||||
wiederverwendet.
|
||||
|
||||
## Ursache
|
||||
|
||||
Die globale Suchseite lädt bereits die serverseitigen Downloadoptionen und
|
||||
rendert dieselbe `PhotoGallery` wie die Albumansicht. Der Downloadbutton wird
|
||||
jedoch nur angezeigt, wenn für den Treffer eine freigegebene Album-ID bekannt
|
||||
ist. Immich liefert im Ergebnis von `POST /search/metadata` nicht zuverlässig
|
||||
eine `albums`-Zuordnung pro Asset. Dadurch fehlt der Galerie bei einzelnen oder
|
||||
allen Suchtreffern der notwendige Albumkontext und sie blendet den Button aus.
|
||||
|
||||
## Lösung
|
||||
|
||||
Die bestehende albumbezogene Suche im Portal kennt für jeden Immich-Aufruf
|
||||
bereits die serverseitig geprüfte Album-ID. Wenn Immich einen Treffer ohne diese
|
||||
Albumzuordnung zurückgibt, ergänzt der Albumkatalog den Treffer um die geprüfte
|
||||
Album-ID, über die er gefunden wurde.
|
||||
|
||||
Die Galerie erhält dadurch auch in der globalen Suche einen gültigen
|
||||
`activeAlbumId` und zeigt den vorhandenen `UsageDialog`:
|
||||
|
||||
- direkt auf der Fotokarte;
|
||||
- in der vergrößerten Lightbox;
|
||||
- mit dem redaktionsbezogenen Preis;
|
||||
- mit früheren Nutzungen des Bildes;
|
||||
- mit derselben API-, Berechtigungs- und Abrechnungslogik wie innerhalb eines
|
||||
Albums.
|
||||
|
||||
Bereits von Immich gelieferte Albumdaten bleiben erhalten. Es werden keine
|
||||
zusätzlichen Immich-Anfragen pro Foto eingeführt.
|
||||
|
||||
## Sicherheit und Fehlerverhalten
|
||||
|
||||
Die ergänzte Album-ID stammt ausschließlich aus der serverseitig ermittelten
|
||||
Liste aktuell freigegebener Alben. Browserdaten werden nicht als
|
||||
Berechtigungsnachweis verwendet. Die bestehende Download-API prüft Album,
|
||||
Asset, Redaktion und Nutzung weiterhin erneut, bevor ein Original ausgeliefert
|
||||
wird.
|
||||
|
||||
Ist kein freigegebenes Album vorhanden oder schlägt die Immich-Suche fehl,
|
||||
bleibt das bestehende Leer- beziehungsweise Fehlerverhalten unverändert.
|
||||
|
||||
## Tests
|
||||
|
||||
Ein Katalogtest bildet den Fehlerfall nach: Immich liefert in einer
|
||||
albumbezogenen Suche ein Asset mit leerem `albums`-Array. Der Albumkatalog muss
|
||||
dieses Asset mit der serverseitig angefragten Album-ID zurückgeben.
|
||||
|
||||
Ein Galerietest bestätigt, dass ein globaler Suchtreffer mit ergänzter Album-ID
|
||||
den Button `Original laden` sowohl in der Kartenansicht als auch nach Öffnen der
|
||||
Lightbox anbietet. Anschließend werden die vollständigen Quelltests,
|
||||
TypeScript, ESLint, Drizzle und der Produktions-Build ausgeführt.
|
||||
|
||||
## Umfang
|
||||
|
||||
Voraussichtlich geändert werden ausschließlich:
|
||||
|
||||
- `src/modules/albums/catalog.ts`
|
||||
- `src/modules/albums/catalog.test.ts`
|
||||
- `src/modules/albums/catalog-content.test.tsx`
|
||||
|
||||
Die Download-API, Abrechnung, Datenbank und Migrationen werden nicht verändert.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1 @@
|
||||
CREATE INDEX "usages_created_at_idx" ON "usages" USING btree ("created_at");
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE "two_factor" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"secret" text NOT NULL,
|
||||
"backup_codes" text,
|
||||
CONSTRAINT "two_factor_user_id_unique" UNIQUE("user_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "user" ADD COLUMN "two_factor_enabled" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "two_factor" ADD CONSTRAINT "two_factor_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "two_factor" ADD COLUMN "verified" boolean DEFAULT false NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "two_factor" ADD COLUMN "failed_verification_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "two_factor" ADD COLUMN "locked_until" timestamp with time zone;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1786299825190,
|
||||
"tag": "0000_initial",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1786303607054,
|
||||
"tag": "0001_editorial_approval_notice",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1786354215684,
|
||||
"tag": "0002_accounting_intents",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1786358492749,
|
||||
"tag": "0003_stream_delivery",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1786363479515,
|
||||
"tag": "0004_download_history_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1786379282947,
|
||||
"tag": "0005_rate_limits",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "7",
|
||||
"when": 1786410282719,
|
||||
"tag": "0006_chubby_screwball",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "7",
|
||||
"when": 1786410724623,
|
||||
"tag": "0007_amused_franklin_storm",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "7",
|
||||
"when": 1786411419497,
|
||||
"tag": "0008_overjoyed_wrecking_crew",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1786455754414,
|
||||
"tag": "0009_usage_created_at_index",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "7",
|
||||
"when": 1787617368189,
|
||||
"tag": "0010_two-factor",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 11,
|
||||
"version": "7",
|
||||
"when": 1787620365940,
|
||||
"tag": "0011_two-factor-verified",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 12,
|
||||
"version": "7",
|
||||
"when": 1787621254728,
|
||||
"tag": "0012_two-factor-plugin-fields",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
CREATE TYPE "public"."portal_role" AS ENUM('ADMIN', 'EDITORIAL');--> statement-breakpoint
|
||||
CREATE TYPE "public"."report_status" AS ENUM('draft', 'final', 'cancelled');--> statement-breakpoint
|
||||
CREATE TYPE "public"."account_status" AS ENUM('pending_email', 'pending_approval', 'active', 'suspended', 'rejected');--> statement-breakpoint
|
||||
CREATE TYPE "public"."download_status" AS ENUM('authorized', 'streaming', 'completed', 'failed_before_delivery', 'interrupted');--> statement-breakpoint
|
||||
CREATE TYPE "public"."usage_billing_status" AS ENUM('open', 'billed', 'reopened', 'voided');--> statement-breakpoint
|
||||
CREATE TABLE "album_grants" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"immich_album_id" text NOT NULL,
|
||||
"granted_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"revoked_at" timestamp with time zone,
|
||||
"granted_by_user_id" uuid,
|
||||
CONSTRAINT "album_grants_immich_album_id_uuid_check" CHECK ("album_grants"."immich_album_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "audit_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"event_type" text NOT NULL,
|
||||
"actor_user_id" uuid,
|
||||
"actor_type" text DEFAULT 'system' NOT NULL,
|
||||
"entity_type" text NOT NULL,
|
||||
"entity_id" text NOT NULL,
|
||||
"previous_values" jsonb,
|
||||
"new_values" jsonb,
|
||||
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"request_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "account" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"account_id" text NOT NULL,
|
||||
"provider_id" text NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"access_token" text,
|
||||
"refresh_token" text,
|
||||
"id_token" text,
|
||||
"access_token_expires_at" timestamp with time zone,
|
||||
"refresh_token_expires_at" timestamp with time zone,
|
||||
"scope" text,
|
||||
"password" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "session" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"token" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"ip_address" text,
|
||||
"user_agent" text,
|
||||
"user_id" uuid NOT NULL,
|
||||
CONSTRAINT "session_token_unique" UNIQUE("token")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "two_factor" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"secret" text NOT NULL,
|
||||
"backup_codes" text,
|
||||
"verified" boolean DEFAULT false NOT NULL,
|
||||
"failed_verification_count" integer DEFAULT 0 NOT NULL,
|
||||
"locked_until" timestamp with time zone,
|
||||
CONSTRAINT "two_factor_user_id_unique" UNIQUE("user_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"email" text NOT NULL,
|
||||
"email_verified" boolean DEFAULT false NOT NULL,
|
||||
"image" text,
|
||||
"role" "portal_role" DEFAULT 'EDITORIAL' NOT NULL,
|
||||
"two_factor_enabled" boolean DEFAULT false NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "user_email_unique" UNIQUE("email")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "verification" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"identifier" text NOT NULL,
|
||||
"value" text NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "album_auto_rules" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"keyword" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_report_items" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"billing_report_id" uuid NOT NULL,
|
||||
"usage_id" uuid NOT NULL,
|
||||
"immich_asset_id_snapshot" text NOT NULL,
|
||||
"filename_snapshot" text NOT NULL,
|
||||
"album_name_snapshot" text NOT NULL,
|
||||
"purpose_snapshot" text NOT NULL,
|
||||
"internal_reference_snapshot" text,
|
||||
"price_cents" integer NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_reports" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"report_number" integer NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"period_starts_at" timestamp with time zone NOT NULL,
|
||||
"period_ends_at" timestamp with time zone NOT NULL,
|
||||
"billing_address_snapshot" jsonb NOT NULL,
|
||||
"invoice_number" text,
|
||||
"net_total_cents" integer NOT NULL,
|
||||
"flatrate_cents_snapshot" integer,
|
||||
"status" "report_status" DEFAULT 'draft' NOT NULL,
|
||||
"pdf" "bytea",
|
||||
"pdf_sha256" varchar(64),
|
||||
"created_by_user_id" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"finalized_at" timestamp with time zone,
|
||||
"cancelled_at" timestamp with time zone,
|
||||
"cancellation_reason" text,
|
||||
"cancelled_by_user_id" uuid,
|
||||
CONSTRAINT "billing_reports_pdf_sha256_hex_check" CHECK ("billing_reports"."pdf_sha256" ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT "billing_reports_final_pdf_check" CHECK ("billing_reports"."status" <> 'final' OR ("billing_reports"."pdf" IS NOT NULL AND "billing_reports"."pdf_sha256" IS NOT NULL))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_address_versions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"company_name" text NOT NULL,
|
||||
"contact_name" text NOT NULL,
|
||||
"address_line_1" text NOT NULL,
|
||||
"address_line_2" text,
|
||||
"postal_code" text NOT NULL,
|
||||
"city" text NOT NULL,
|
||||
"country_code" text NOT NULL,
|
||||
"valid_from" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"superseded_by_id" uuid,
|
||||
"created_by_user_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "editorial_accounts" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"contact_name" text NOT NULL,
|
||||
"login_email" text NOT NULL,
|
||||
"status" "account_status" DEFAULT 'pending_email' NOT NULL,
|
||||
"current_price_cents" integer,
|
||||
"flatrate_active" boolean DEFAULT false NOT NULL,
|
||||
"flatrate_price_cents" integer,
|
||||
"flatrate_asset_limit" integer,
|
||||
"approval_notice_status" text DEFAULT 'not_requested' NOT NULL,
|
||||
"current_billing_address_version_id" uuid,
|
||||
"email_verified_at" timestamp with time zone,
|
||||
"accepted_terms_version" text,
|
||||
"accepted_terms_at" timestamp with time zone,
|
||||
"privacy_acknowledged_at" timestamp with time zone,
|
||||
"archived_at" timestamp with time zone,
|
||||
"archived_by_user_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "editorial_accounts_user_id_unique" UNIQUE("user_id"),
|
||||
CONSTRAINT "editorial_accounts_login_email_unique" UNIQUE("login_email")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "lightbox_items" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"asset_id" text NOT NULL,
|
||||
"added_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "rate_limits" (
|
||||
"key" text NOT NULL,
|
||||
"window_boundary" integer NOT NULL,
|
||||
"count" integer DEFAULT 1 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "rate_limits_key_window_boundary_pk" PRIMARY KEY("key","window_boundary")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "download_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"usage_id" uuid NOT NULL,
|
||||
"immich_asset_id" text NOT NULL,
|
||||
"authorized_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"started_at" timestamp with time zone,
|
||||
"completed_at" timestamp with time zone,
|
||||
"status" "download_status" DEFAULT 'authorized' NOT NULL,
|
||||
"transferred_bytes" bigint,
|
||||
"repeat_download_note" text,
|
||||
"request_id" uuid NOT NULL,
|
||||
"idempotency_key" text NOT NULL,
|
||||
"intent_kind" text DEFAULT 'new_usage' NOT NULL,
|
||||
"request_fingerprint" varchar(64) NOT NULL,
|
||||
"legacy_intent" boolean DEFAULT false NOT NULL,
|
||||
CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy')),
|
||||
CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("download_events"."legacy_intent" OR "download_events"."idempotency_key" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'),
|
||||
CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("download_events"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "usages" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"immich_asset_id" text NOT NULL,
|
||||
"filename_snapshot" text NOT NULL,
|
||||
"immich_album_id_snapshot" text NOT NULL,
|
||||
"album_name_snapshot" text NOT NULL,
|
||||
"purpose" text NOT NULL,
|
||||
"internal_reference" text,
|
||||
"price_cents" integer NOT NULL,
|
||||
"billing_status" "usage_billing_status" DEFAULT 'open' NOT NULL,
|
||||
"billing_report_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("usages"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'),
|
||||
CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("usages"."immich_album_id_snapshot" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_granted_by_user_id_user_id_fk" FOREIGN KEY ("granted_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "audit_events" ADD CONSTRAINT "audit_events_actor_user_id_user_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "two_factor" ADD CONSTRAINT "two_factor_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_cancelled_by_user_id_user_id_fk" FOREIGN KEY ("cancelled_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_superseded_by_id_billing_address_versions_id_fk" FOREIGN KEY ("superseded_by_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk" FOREIGN KEY ("current_billing_address_version_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_archived_by_user_id_user_id_fk" FOREIGN KEY ("archived_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lightbox_items" ADD CONSTRAINT "lightbox_items_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "usages" ADD CONSTRAINT "usages_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "usages" ADD CONSTRAINT "usages_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "album_grants_editorial_account_id_idx" ON "album_grants" USING btree ("editorial_account_id");--> statement-breakpoint
|
||||
CREATE INDEX "album_grants_immich_album_id_idx" ON "album_grants" USING btree ("immich_album_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "album_grants_editorial_active_album_unique" ON "album_grants" USING btree ("editorial_account_id",lower("immich_album_id")) WHERE "album_grants"."revoked_at" is null;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "album_auto_rules_editorial_account_id_keyword_idx" ON "album_auto_rules" USING btree ("editorial_account_id",lower("keyword"));--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_report_items_report_usage_unique" ON "billing_report_items" USING btree ("billing_report_id","usage_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_reports_report_number_unique" ON "billing_reports" USING btree ("report_number");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_reports_invoice_number_unique" ON "billing_reports" USING btree ("invoice_number");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "lightbox_items_editorial_asset_idx" ON "lightbox_items" USING btree ("editorial_account_id","asset_id");--> statement-breakpoint
|
||||
CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "download_events_editorial_idempotency_key_unique" ON "download_events" USING btree ("editorial_account_id","idempotency_key");--> statement-breakpoint
|
||||
CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
|
||||
CREATE INDEX "usages_created_at_idx" ON "usages" USING btree ("created_at");
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE "announcements" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"message" text NOT NULL,
|
||||
"event_date" date NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "announcements" ADD CONSTRAINT "announcements_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;
|
||||
@@ -1,32 +0,0 @@
|
||||
-- 1. Create the album_auto_rules table
|
||||
CREATE TABLE IF NOT EXISTS "album_auto_rules" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"keyword" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid
|
||||
);
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "album_auto_rules_editorial_account_id_keyword_idx" ON "album_auto_rules" ("editorial_account_id", lower("keyword"));
|
||||
|
||||
-- 2. Add archived_at and archived_by_user_id to editorial_accounts
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_at" timestamp with time zone;
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_by_user_id" uuid;
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_archived_by_user_id_users_id_fk" FOREIGN KEY ("archived_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"id": "64eb37ed-2ab5-4c12-a8be-4375e8f6a732",
|
||||
"id": "5ac645f2-0e76-4853-b029-724095bf1138",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
@@ -77,6 +77,28 @@
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"album_grants_editorial_active_album_unique": {
|
||||
"name": "album_grants_editorial_active_album_unique",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "lower(\"immich_album_id\")",
|
||||
"asc": true,
|
||||
"isExpression": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"where": "\"album_grants\".\"revoked_at\" is null",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
@@ -110,7 +132,12 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"album_grants_immich_album_id_uuid_check": {
|
||||
"name": "album_grants_immich_album_id_uuid_check",
|
||||
"value": "\"album_grants\".\"immich_album_id\" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.audit_events": {
|
||||
@@ -397,6 +424,86 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.two_factor": {
|
||||
"name": "two_factor",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"backup_codes": {
|
||||
"name": "backup_codes",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"verified": {
|
||||
"name": "verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"failed_verification_count": {
|
||||
"name": "failed_verification_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"locked_until": {
|
||||
"name": "locked_until",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"two_factor_user_id_user_id_fk": {
|
||||
"name": "two_factor_user_id_user_id_fk",
|
||||
"tableFrom": "two_factor",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"two_factor_user_id_unique": {
|
||||
"name": "two_factor_user_id_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"user_id"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.user": {
|
||||
"name": "user",
|
||||
"schema": "",
|
||||
@@ -441,6 +548,13 @@
|
||||
"notNull": true,
|
||||
"default": "'EDITORIAL'"
|
||||
},
|
||||
"two_factor_enabled": {
|
||||
"name": "two_factor_enabled",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
@@ -524,6 +638,100 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.album_auto_rules": {
|
||||
"name": "album_auto_rules",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"editorial_account_id": {
|
||||
"name": "editorial_account_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"keyword": {
|
||||
"name": "keyword",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"created_by_user_id": {
|
||||
"name": "created_by_user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"album_auto_rules_editorial_account_id_keyword_idx": {
|
||||
"name": "album_auto_rules_editorial_account_id_keyword_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "lower(\"keyword\")",
|
||||
"asc": true,
|
||||
"isExpression": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"album_auto_rules_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "album_auto_rules_editorial_account_id_editorial_accounts_id_fk",
|
||||
"tableFrom": "album_auto_rules",
|
||||
"tableTo": "editorial_accounts",
|
||||
"columnsFrom": [
|
||||
"editorial_account_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"album_auto_rules_created_by_user_id_user_id_fk": {
|
||||
"name": "album_auto_rules_created_by_user_id_user_id_fk",
|
||||
"tableFrom": "album_auto_rules",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.billing_report_items": {
|
||||
"name": "billing_report_items",
|
||||
"schema": "",
|
||||
@@ -701,6 +909,12 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"flatrate_cents_snapshot": {
|
||||
"name": "flatrate_cents_snapshot",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "report_status",
|
||||
@@ -1030,6 +1244,32 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"flatrate_active": {
|
||||
"name": "flatrate_active",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"flatrate_price_cents": {
|
||||
"name": "flatrate_price_cents",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"flatrate_asset_limit": {
|
||||
"name": "flatrate_asset_limit",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"approval_notice_status": {
|
||||
"name": "approval_notice_status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'not_requested'"
|
||||
},
|
||||
"current_billing_address_version_id": {
|
||||
"name": "current_billing_address_version_id",
|
||||
"type": "uuid",
|
||||
@@ -1060,6 +1300,18 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"archived_at": {
|
||||
"name": "archived_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"archived_by_user_id": {
|
||||
"name": "archived_by_user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
@@ -1102,6 +1354,19 @@
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"editorial_accounts_archived_by_user_id_user_id_fk": {
|
||||
"name": "editorial_accounts_archived_by_user_id_user_id_fk",
|
||||
"tableFrom": "editorial_accounts",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"archived_by_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
@@ -1125,6 +1390,135 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.lightbox_items": {
|
||||
"name": "lightbox_items",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"editorial_account_id": {
|
||||
"name": "editorial_account_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"added_at": {
|
||||
"name": "added_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"lightbox_items_editorial_asset_idx": {
|
||||
"name": "lightbox_items_editorial_asset_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "asset_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"lightbox_items_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "lightbox_items_editorial_account_id_editorial_accounts_id_fk",
|
||||
"tableFrom": "lightbox_items",
|
||||
"tableTo": "editorial_accounts",
|
||||
"columnsFrom": [
|
||||
"editorial_account_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.rate_limits": {
|
||||
"name": "rate_limits",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"window_boundary": {
|
||||
"name": "window_boundary",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"count": {
|
||||
"name": "count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 1
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {
|
||||
"rate_limits_key_window_boundary_pk": {
|
||||
"name": "rate_limits_key_window_boundary_pk",
|
||||
"columns": [
|
||||
"key",
|
||||
"window_boundary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.download_events": {
|
||||
"name": "download_events",
|
||||
"schema": "",
|
||||
@@ -1204,9 +1598,56 @@
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"intent_kind": {
|
||||
"name": "intent_kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'new_usage'"
|
||||
},
|
||||
"request_fingerprint": {
|
||||
"name": "request_fingerprint",
|
||||
"type": "varchar(64)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"legacy_intent": {
|
||||
"name": "legacy_intent",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"download_events_editorial_authorized_id_idx": {
|
||||
"name": "download_events_editorial_authorized_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "authorized_at",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"download_events_editorial_idempotency_key_unique": {
|
||||
"name": "download_events_editorial_idempotency_key_unique",
|
||||
"columns": [
|
||||
@@ -1260,7 +1701,24 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"download_events_intent_kind_check": {
|
||||
"name": "download_events_intent_kind_check",
|
||||
"value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')"
|
||||
},
|
||||
"download_events_request_fingerprint_hex_check": {
|
||||
"name": "download_events_request_fingerprint_hex_check",
|
||||
"value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'"
|
||||
},
|
||||
"download_events_canonical_idempotency_key_check": {
|
||||
"name": "download_events_canonical_idempotency_key_check",
|
||||
"value": "\"download_events\".\"legacy_intent\" OR \"download_events\".\"idempotency_key\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
},
|
||||
"download_events_canonical_immich_asset_id_check": {
|
||||
"name": "download_events_canonical_immich_asset_id_check",
|
||||
"value": "\"download_events\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.usages": {
|
||||
@@ -1344,7 +1802,50 @@
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"indexes": {
|
||||
"usages_editorial_created_id_idx": {
|
||||
"name": "usages_editorial_created_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"usages_created_at_idx": {
|
||||
"name": "usages_created_at_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"usages_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "usages_editorial_account_id_editorial_accounts_id_fk",
|
||||
@@ -1376,7 +1877,16 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"usages_canonical_immich_asset_id_check": {
|
||||
"name": "usages_canonical_immich_asset_id_check",
|
||||
"value": "\"usages\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
},
|
||||
"usages_canonical_immich_album_id_check": {
|
||||
"name": "usages_canonical_immich_album_id_check",
|
||||
"value": "\"usages\".\"immich_album_id_snapshot\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
@@ -1426,7 +1936,8 @@
|
||||
"values": [
|
||||
"open",
|
||||
"billed",
|
||||
"reopened"
|
||||
"reopened",
|
||||
"voided"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "cfd5f4d1-55ac-46d9-9667-cd156f26e070",
|
||||
"prevId": "64eb37ed-2ab5-4c12-a8be-4375e8f6a732",
|
||||
"id": "b98d41ae-a5a1-4e1c-bb31-99cc096528a0",
|
||||
"prevId": "5ac645f2-0e76-4853-b029-724095bf1138",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
@@ -77,6 +77,28 @@
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"album_grants_editorial_active_album_unique": {
|
||||
"name": "album_grants_editorial_active_album_unique",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "lower(\"immich_album_id\")",
|
||||
"asc": true,
|
||||
"isExpression": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"where": "\"album_grants\".\"revoked_at\" is null",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
@@ -110,6 +132,70 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"album_grants_immich_album_id_uuid_check": {
|
||||
"name": "album_grants_immich_album_id_uuid_check",
|
||||
"value": "\"album_grants\".\"immich_album_id\" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.announcements": {
|
||||
"name": "announcements",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"message": {
|
||||
"name": "message",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"event_date": {
|
||||
"name": "event_date",
|
||||
"type": "date",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"created_by_user_id": {
|
||||
"name": "created_by_user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"announcements_created_by_user_id_user_id_fk": {
|
||||
"name": "announcements_created_by_user_id_user_id_fk",
|
||||
"tableFrom": "announcements",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
@@ -397,6 +483,86 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.two_factor": {
|
||||
"name": "two_factor",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"secret": {
|
||||
"name": "secret",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"backup_codes": {
|
||||
"name": "backup_codes",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"verified": {
|
||||
"name": "verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"failed_verification_count": {
|
||||
"name": "failed_verification_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"locked_until": {
|
||||
"name": "locked_until",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"two_factor_user_id_user_id_fk": {
|
||||
"name": "two_factor_user_id_user_id_fk",
|
||||
"tableFrom": "two_factor",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"two_factor_user_id_unique": {
|
||||
"name": "two_factor_user_id_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"user_id"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.user": {
|
||||
"name": "user",
|
||||
"schema": "",
|
||||
@@ -441,6 +607,13 @@
|
||||
"notNull": true,
|
||||
"default": "'EDITORIAL'"
|
||||
},
|
||||
"two_factor_enabled": {
|
||||
"name": "two_factor_enabled",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
@@ -524,6 +697,100 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.album_auto_rules": {
|
||||
"name": "album_auto_rules",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"editorial_account_id": {
|
||||
"name": "editorial_account_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"keyword": {
|
||||
"name": "keyword",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"created_by_user_id": {
|
||||
"name": "created_by_user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"album_auto_rules_editorial_account_id_keyword_idx": {
|
||||
"name": "album_auto_rules_editorial_account_id_keyword_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "lower(\"keyword\")",
|
||||
"asc": true,
|
||||
"isExpression": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"album_auto_rules_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "album_auto_rules_editorial_account_id_editorial_accounts_id_fk",
|
||||
"tableFrom": "album_auto_rules",
|
||||
"tableTo": "editorial_accounts",
|
||||
"columnsFrom": [
|
||||
"editorial_account_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"album_auto_rules_created_by_user_id_user_id_fk": {
|
||||
"name": "album_auto_rules_created_by_user_id_user_id_fk",
|
||||
"tableFrom": "album_auto_rules",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.billing_report_items": {
|
||||
"name": "billing_report_items",
|
||||
"schema": "",
|
||||
@@ -701,6 +968,12 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"flatrate_cents_snapshot": {
|
||||
"name": "flatrate_cents_snapshot",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "report_status",
|
||||
@@ -1030,6 +1303,25 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"flatrate_active": {
|
||||
"name": "flatrate_active",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"flatrate_price_cents": {
|
||||
"name": "flatrate_price_cents",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"flatrate_asset_limit": {
|
||||
"name": "flatrate_asset_limit",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"approval_notice_status": {
|
||||
"name": "approval_notice_status",
|
||||
"type": "text",
|
||||
@@ -1067,6 +1359,18 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"archived_at": {
|
||||
"name": "archived_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"archived_by_user_id": {
|
||||
"name": "archived_by_user_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
@@ -1109,6 +1413,19 @@
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"editorial_accounts_archived_by_user_id_user_id_fk": {
|
||||
"name": "editorial_accounts_archived_by_user_id_user_id_fk",
|
||||
"tableFrom": "editorial_accounts",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"archived_by_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
@@ -1132,6 +1449,135 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.lightbox_items": {
|
||||
"name": "lightbox_items",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"editorial_account_id": {
|
||||
"name": "editorial_account_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"added_at": {
|
||||
"name": "added_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"lightbox_items_editorial_asset_idx": {
|
||||
"name": "lightbox_items_editorial_asset_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "asset_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"lightbox_items_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "lightbox_items_editorial_account_id_editorial_accounts_id_fk",
|
||||
"tableFrom": "lightbox_items",
|
||||
"tableTo": "editorial_accounts",
|
||||
"columnsFrom": [
|
||||
"editorial_account_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.rate_limits": {
|
||||
"name": "rate_limits",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"key": {
|
||||
"name": "key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"window_boundary": {
|
||||
"name": "window_boundary",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"count": {
|
||||
"name": "count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 1
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {
|
||||
"rate_limits_key_window_boundary_pk": {
|
||||
"name": "rate_limits_key_window_boundary_pk",
|
||||
"columns": [
|
||||
"key",
|
||||
"window_boundary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.download_events": {
|
||||
"name": "download_events",
|
||||
"schema": "",
|
||||
@@ -1211,9 +1657,56 @@
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"intent_kind": {
|
||||
"name": "intent_kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'new_usage'"
|
||||
},
|
||||
"request_fingerprint": {
|
||||
"name": "request_fingerprint",
|
||||
"type": "varchar(64)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"legacy_intent": {
|
||||
"name": "legacy_intent",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"download_events_editorial_authorized_id_idx": {
|
||||
"name": "download_events_editorial_authorized_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "authorized_at",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"download_events_editorial_idempotency_key_unique": {
|
||||
"name": "download_events_editorial_idempotency_key_unique",
|
||||
"columns": [
|
||||
@@ -1267,7 +1760,24 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"download_events_intent_kind_check": {
|
||||
"name": "download_events_intent_kind_check",
|
||||
"value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')"
|
||||
},
|
||||
"download_events_request_fingerprint_hex_check": {
|
||||
"name": "download_events_request_fingerprint_hex_check",
|
||||
"value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'"
|
||||
},
|
||||
"download_events_canonical_idempotency_key_check": {
|
||||
"name": "download_events_canonical_idempotency_key_check",
|
||||
"value": "\"download_events\".\"legacy_intent\" OR \"download_events\".\"idempotency_key\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
},
|
||||
"download_events_canonical_immich_asset_id_check": {
|
||||
"name": "download_events_canonical_immich_asset_id_check",
|
||||
"value": "\"download_events\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.usages": {
|
||||
@@ -1351,7 +1861,50 @@
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"indexes": {
|
||||
"usages_editorial_created_id_idx": {
|
||||
"name": "usages_editorial_created_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "editorial_account_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": false,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"usages_created_at_idx": {
|
||||
"name": "usages_created_at_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"usages_editorial_account_id_editorial_accounts_id_fk": {
|
||||
"name": "usages_editorial_account_id_editorial_accounts_id_fk",
|
||||
@@ -1383,7 +1936,16 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"usages_canonical_immich_asset_id_check": {
|
||||
"name": "usages_canonical_immich_asset_id_check",
|
||||
"value": "\"usages\".\"immich_asset_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
},
|
||||
"usages_canonical_immich_album_id_check": {
|
||||
"name": "usages_canonical_immich_album_id_check",
|
||||
"value": "\"usages\".\"immich_album_id_snapshot\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
@@ -1433,7 +1995,8 @@
|
||||
"values": [
|
||||
"open",
|
||||
"billed",
|
||||
"reopened"
|
||||
"reopened",
|
||||
"voided"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,63 +6,14 @@
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1786299825190,
|
||||
"tag": "0000_initial",
|
||||
"tag": "0000_baseline",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1786303607054,
|
||||
"tag": "0001_editorial_approval_notice",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1786354215684,
|
||||
"tag": "0002_accounting_intents",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1786358492749,
|
||||
"tag": "0003_stream_delivery",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1786363479515,
|
||||
"tag": "0004_download_history_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1786379282947,
|
||||
"tag": "0005_rate_limits",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "7",
|
||||
"when": 1786410282719,
|
||||
"tag": "0006_chubby_screwball",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "7",
|
||||
"when": 1786410724623,
|
||||
"tag": "0007_amused_franklin_storm",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "7",
|
||||
"when": 1786411419497,
|
||||
"tag": "0008_overjoyed_wrecking_crew",
|
||||
"when": 1789139950413,
|
||||
"tag": "0001_add_announcements",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
|
||||
const eslintConfig = [...nextVitals];
|
||||
const eslintConfig = [
|
||||
{ ignores: [".next/**", ".worktrees/**"] },
|
||||
...nextVitals,
|
||||
];
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -3,6 +3,9 @@ import type { NextConfig } from "next";
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
poweredByHeader: false,
|
||||
experimental: {
|
||||
optimizePackageImports: ["lucide-react", "recharts"],
|
||||
},
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
|
||||
+2
-2
@@ -17,13 +17,14 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/drizzle-adapter": "^1.6.26",
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@js-temporal/polyfill": "^0.5.1",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@sakaniui/react": "^0.23.0",
|
||||
"archiver": "^8.0.0",
|
||||
"better-auth": "^1.6.26",
|
||||
"clsx": "^2.1.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"lucide-react": "^1.31.0",
|
||||
"next": "^16.3.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"nodemailer": "^9.0.5",
|
||||
@@ -31,7 +32,6 @@
|
||||
"pg": "^8.22.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"recharts": "^3.10.1",
|
||||
"server-only": "^0.0.1",
|
||||
"sharp": "^0.35.3",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
|
||||
Generated
+28
-15
@@ -11,12 +11,18 @@ importers:
|
||||
'@better-auth/drizzle-adapter':
|
||||
specifier: ^1.6.26
|
||||
version: 1.6.26(@better-auth/core@1.6.26(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.8)(kysely@0.29.4)(nanostores@1.4.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0))
|
||||
'@fontsource-variable/geist':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@js-temporal/polyfill':
|
||||
specifier: ^0.5.1
|
||||
version: 0.5.1
|
||||
'@radix-ui/react-slot':
|
||||
specifier: ^1.3.3
|
||||
version: 1.3.3(@types/react@19.2.18)(react@19.2.8)
|
||||
'@sakaniui/react':
|
||||
specifier: ^0.23.0
|
||||
version: 0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
|
||||
archiver:
|
||||
specifier: ^8.0.0
|
||||
version: 8.0.0
|
||||
@@ -29,9 +35,6 @@ importers:
|
||||
drizzle-orm:
|
||||
specifier: ^0.45.2
|
||||
version: 0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0)
|
||||
lucide-react:
|
||||
specifier: ^1.31.0
|
||||
version: 1.31.0(react@19.2.8)
|
||||
next:
|
||||
specifier: ^16.3.0
|
||||
version: 16.3.0(@babel/core@7.29.7)(@playwright/test@1.62.1)(@types/node@24.13.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
||||
@@ -53,9 +56,6 @@ importers:
|
||||
react-dom:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8(react@19.2.8)
|
||||
recharts:
|
||||
specifier: ^3.10.1
|
||||
version: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
|
||||
server-only:
|
||||
specifier: ^0.0.1
|
||||
version: 0.0.1
|
||||
@@ -875,6 +875,9 @@ packages:
|
||||
'@noble/hashes':
|
||||
optional: true
|
||||
|
||||
'@fontsource-variable/geist@5.3.0':
|
||||
resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==}
|
||||
|
||||
'@grpc/grpc-js@1.14.4':
|
||||
resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
|
||||
engines: {node: '>=12.10.0'}
|
||||
@@ -1492,6 +1495,13 @@ packages:
|
||||
'@rtsao/scc@1.1.0':
|
||||
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
|
||||
|
||||
'@sakaniui/react@0.23.0':
|
||||
resolution: {integrity: sha512-9BnsvgacsDaERq0lQZNHuqNwfCSNhiPSkQLQMhH0mRSJ9K0I9Jz0Ht4W5HifuMAWnCwb3J6aZUEV6wpn7hk/kw==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
react: ^19.0.0
|
||||
react-dom: ^19.0.0
|
||||
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
@@ -3462,11 +3472,6 @@ packages:
|
||||
lru-cache@5.1.1:
|
||||
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
|
||||
|
||||
lucide-react@1.31.0:
|
||||
resolution: {integrity: sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg==}
|
||||
peerDependencies:
|
||||
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
lz-string@1.5.0:
|
||||
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
|
||||
hasBin: true
|
||||
@@ -5090,6 +5095,8 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@noble/hashes': 2.3.0
|
||||
|
||||
'@fontsource-variable/geist@5.3.0': {}
|
||||
|
||||
'@grpc/grpc-js@1.14.4':
|
||||
dependencies:
|
||||
'@grpc/proto-loader': 0.8.1
|
||||
@@ -5530,6 +5537,16 @@ snapshots:
|
||||
|
||||
'@rtsao/scc@1.1.0': {}
|
||||
|
||||
'@sakaniui/react@0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)':
|
||||
dependencies:
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8(react@19.2.8)
|
||||
recharts: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
|
||||
transitivePeerDependencies:
|
||||
- '@types/react'
|
||||
- react-is
|
||||
- redux
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
'@standard-schema/utils@0.3.0': {}
|
||||
@@ -7578,10 +7595,6 @@ snapshots:
|
||||
dependencies:
|
||||
yallist: 3.1.1
|
||||
|
||||
lucide-react@1.31.0(react@19.2.8):
|
||||
dependencies:
|
||||
react: 19.2.8
|
||||
|
||||
lz-string@1.5.0: {}
|
||||
|
||||
magic-string@0.30.21:
|
||||
|
||||
@@ -1,38 +1,21 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { LoginForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="login-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="login-title">Anmelden</h1>
|
||||
<p className="lede">Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an.</p>
|
||||
<LoginForm />
|
||||
<nav className="account-links" aria-label="Zugang verwalten">
|
||||
<Link href="/passwort-vergessen">Passwort vergessen?</Link>
|
||||
<Link href="/registrieren">Neue Redaktion registrieren</Link>
|
||||
</nav>
|
||||
</section>
|
||||
<LegalFooter imprint={env.LEGAL_IMPRINT_URL} privacy={env.LEGAL_PRIVACY_URL} terms={env.LEGAL_TERMS_URL} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function LegalFooter({ imprint, privacy, terms }: { imprint: string; privacy: string; terms: string }) {
|
||||
return (
|
||||
<footer className="public-footer">
|
||||
<a href={imprint}>Impressum</a>
|
||||
<a href={privacy}>Datenschutz</a>
|
||||
<a href={terms}>Nutzungsbedingungen</a>
|
||||
</footer>
|
||||
<PublicShell
|
||||
kicker="Zugang"
|
||||
title="Anmelden"
|
||||
titleId="login-title"
|
||||
lede="Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an."
|
||||
>
|
||||
<LoginForm />
|
||||
<nav aria-label="Zugang verwalten" className="flex flex-wrap justify-between gap-x-4 gap-y-2 text-sm">
|
||||
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/passwort-vergessen">Passwort vergessen?</Link>
|
||||
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/registrieren">Neue Redaktion registrieren</Link>
|
||||
</nav>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,15 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { PasswordResetRequestForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="forgot-password-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="forgot-password-title">Passwort vergessen?</h1>
|
||||
<p className="lede">Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.</p>
|
||||
<PasswordResetRequestForm />
|
||||
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</section>
|
||||
</main>
|
||||
<PublicShell kicker="Zugang" title="Passwort vergessen?" titleId="forgot-password-title" lede="Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.">
|
||||
<PasswordResetRequestForm />
|
||||
<nav aria-label="Zurück zur Anmeldung" className="text-sm">
|
||||
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { PasswordResetForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default async function ResetPasswordPage({
|
||||
@@ -10,22 +11,11 @@ export default async function ResetPasswordPage({
|
||||
const { token } = await searchParams;
|
||||
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="reset-password-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="reset-password-title">Neues Passwort setzen</h1>
|
||||
<p className="lede">Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.</p>
|
||||
<PasswordResetForm token={token} />
|
||||
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</section>
|
||||
</main>
|
||||
<PublicShell kicker="Zugang" title="Neues Passwort setzen" titleId="reset-password-title" lede="Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.">
|
||||
<PasswordResetForm token={token} />
|
||||
<nav aria-label="Zurück zur Anmeldung" className="text-sm">
|
||||
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,21 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function RegistrationConfirmedPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="confirmation-title">
|
||||
<p className="eyebrow">Registrierung</p>
|
||||
<h1 id="confirmation-title">Vielen Dank.</h1>
|
||||
<p className="lede">
|
||||
Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach
|
||||
prüfen wir Ihre Registrierung.
|
||||
</p>
|
||||
<Link className="primary-action" href="/anmelden">
|
||||
Zur Anmeldung
|
||||
</Link>
|
||||
</section>
|
||||
</main>
|
||||
<PublicShell
|
||||
kicker="Registrierung"
|
||||
title="Vielen Dank."
|
||||
titleId="confirmation-title"
|
||||
lede="Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach prüfen wir Ihre Registrierung."
|
||||
>
|
||||
<div>
|
||||
<Button asChild>
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { env } from "@/config/env";
|
||||
import { registerEditorial } from "@/modules/auth/auth";
|
||||
import {
|
||||
@@ -11,32 +12,26 @@ import {
|
||||
RegistrationForm,
|
||||
type RegistrationFormState,
|
||||
} from "@/modules/auth/public-forms";
|
||||
import { RateLimitExceededError } from "@/modules/security/rate-limit-guard";
|
||||
|
||||
export default function RegistrationPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel account-panel-wide" aria-labelledby="registration-title">
|
||||
<p className="eyebrow">B2B-Zugang</p>
|
||||
<h1 id="registration-title">Redaktion registrieren</h1>
|
||||
<p className="lede">
|
||||
Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung.
|
||||
</p>
|
||||
<RegistrationForm
|
||||
action={registerAction}
|
||||
legalUrls={{
|
||||
imprint: env.LEGAL_IMPRINT_URL,
|
||||
privacy: env.LEGAL_PRIVACY_URL,
|
||||
terms: env.LEGAL_TERMS_URL,
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
<PublicShell
|
||||
kicker="B2B-Zugang"
|
||||
title="Redaktion registrieren"
|
||||
titleId="registration-title"
|
||||
lede="Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung."
|
||||
wide
|
||||
>
|
||||
<RegistrationForm
|
||||
action={registerAction}
|
||||
legalUrls={{
|
||||
imprint: env.LEGAL_IMPRINT_URL,
|
||||
privacy: env.LEGAL_PRIVACY_URL,
|
||||
terms: env.LEGAL_TERMS_URL,
|
||||
}}
|
||||
/>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -62,8 +57,15 @@ async function registerAction(
|
||||
actsForBusiness: formData.has("actsForBusiness"),
|
||||
termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
|
||||
privacyAcknowledged: formData.has("privacyAcknowledged"),
|
||||
});
|
||||
}, await headers());
|
||||
} catch (error) {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return {
|
||||
errors: {
|
||||
form: "Es wurden zu viele Registrierungsversuche gesendet. Bitte versuchen Sie es später erneut.",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (error instanceof RegistrationValidationError) {
|
||||
return { errors: { [error.field]: error.message } };
|
||||
}
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
|
||||
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
|
||||
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||
import { formatCents } from "@/modules/billing/format";
|
||||
@@ -40,6 +45,12 @@ const STATUS_LABELS: Record<BillingPosition["status"], string> = {
|
||||
reopened: "Wiedereröffnet",
|
||||
};
|
||||
|
||||
const STATUS_BADGES: Record<BillingPosition["status"], "warning" | "success"> = {
|
||||
open: "warning",
|
||||
billed: "success",
|
||||
reopened: "warning",
|
||||
};
|
||||
|
||||
const REPORT_STATUS_LABELS: Record<string, string> = {
|
||||
draft: "Entwurf",
|
||||
final: "Erstellt",
|
||||
@@ -172,178 +183,162 @@ export function BillingSelection({
|
||||
<>
|
||||
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
|
||||
|
||||
<div className="billing-selection-controls">
|
||||
<button type="button" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="button" variant="secondary" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
|
||||
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
|
||||
</button>
|
||||
{isQuarter ? (
|
||||
<Link href={monthHref} className="billing-nav-link">
|
||||
Monatsansicht
|
||||
</Link>
|
||||
) : (
|
||||
<Link href={quarterHref} className="billing-nav-link">
|
||||
Ganzes Quartal
|
||||
</Link>
|
||||
)}
|
||||
<button type="button" onClick={clearSelection} disabled={selectedCount === 0}>
|
||||
</Button>
|
||||
<Button asChild variant="outline">
|
||||
{isQuarter ? <Link href={monthHref}>Monatsansicht</Link> : <Link href={quarterHref}>Ganzes Quartal</Link>}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={clearSelection} disabled={selectedCount === 0}>
|
||||
Auswahl aufheben
|
||||
</button>
|
||||
</Button>
|
||||
<p className="ml-auto text-sm text-[var(--color-fg-muted)]" aria-live="polite">
|
||||
Zeitraum: {periodLabel}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="billing-period-label" aria-live="polite">
|
||||
Zeitraum: {periodLabel}
|
||||
</p>
|
||||
|
||||
{positions.length === 0 ? (
|
||||
<p className="billing-empty">Keine abrechenbaren Nutzungen in diesem Zeitraum.</p>
|
||||
) : (
|
||||
<table className="billing-table">
|
||||
<caption className="billing-caption">
|
||||
Abrechenbare Nutzungen
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Auswahl</th>
|
||||
<th scope="col">Datei</th>
|
||||
<th scope="col">Album</th>
|
||||
<th scope="col">Zweck</th>
|
||||
<th scope="col">Referenz</th>
|
||||
<th scope="col">Preis</th>
|
||||
<th scope="col">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{positions.map((position) => (
|
||||
<tr key={position.id} className={position.selectable ? "" : "billing-row-billed"}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.has(position.id)}
|
||||
onChange={() => togglePosition(position.id)}
|
||||
disabled={!position.selectable}
|
||||
<section className="flex flex-col gap-3" aria-labelledby="positions-title">
|
||||
<h2 id="positions-title" className="text-lg font-semibold">Abrechenbare Nutzungen</h2>
|
||||
{positions.length === 0 ? (
|
||||
<EmptyState title="Keine abrechenbaren Nutzungen in diesem Zeitraum." description="Wählen Sie oben einen anderen Monat oder ein Quartal." />
|
||||
) : (
|
||||
<Table<BillingPosition>
|
||||
rowKey={(position) => position.id}
|
||||
rows={positions}
|
||||
columns={[
|
||||
{
|
||||
key: "id",
|
||||
header: "Auswahl",
|
||||
render: (position) => (
|
||||
<Checkbox
|
||||
aria-label={`${position.filename} auswählen`}
|
||||
checked={selectedIds.has(position.id)}
|
||||
disabled={!position.selectable}
|
||||
onChange={() => togglePosition(position.id)}
|
||||
/>
|
||||
</td>
|
||||
<td>{position.filename}</td>
|
||||
<td>{position.albumName}</td>
|
||||
<td>{position.purpose}</td>
|
||||
<td>{position.reference ?? "—"}</td>
|
||||
<td className="billing-price">{formatCents(position.priceCents)}</td>
|
||||
<td>
|
||||
<span className="billing-status">
|
||||
{STATUS_LABELS[position.status]}
|
||||
),
|
||||
},
|
||||
{ key: "filename", header: "Datei" },
|
||||
{ key: "albumName", header: "Album" },
|
||||
{ key: "purpose", header: "Zweck" },
|
||||
{ key: "reference", header: "Referenz", render: (position) => position.reference ?? "—" },
|
||||
{
|
||||
key: "priceCents",
|
||||
header: "Preis",
|
||||
align: "right",
|
||||
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
header: "Status",
|
||||
render: (position) => (
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant={STATUS_BADGES[position.status] ?? "neutral"}>{STATUS_LABELS[position.status]}</Badge>
|
||||
{position.status === "billed" && position.reportNumber !== null && (
|
||||
<span className="billing-report-ref">
|
||||
{" "}· Bericht Nr. {position.reportNumber}
|
||||
<span className="text-xs text-[var(--color-fg-muted)]">
|
||||
Bericht Nr. {position.reportNumber}
|
||||
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{repeatDownloads.length > 0 && (
|
||||
<section aria-labelledby="repeat-downloads-title" className="billing-repeat-section">
|
||||
<h2 id="repeat-downloads-title">Kostenlose Wiederabrufe</h2>
|
||||
<p className="form-note">
|
||||
<section aria-labelledby="repeat-downloads-title" className="flex flex-col gap-3">
|
||||
<h2 id="repeat-downloads-title" className="text-lg font-semibold">Kostenlose Wiederabrufe</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
|
||||
abrechenbar.
|
||||
</p>
|
||||
<table className="billing-table billing-table-repeat">
|
||||
<caption className="billing-caption">Wiederabrufe im Zeitraum</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Datei</th>
|
||||
<th scope="col">Datum</th>
|
||||
<th scope="col">Status</th>
|
||||
<th scope="col">Notiz</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{repeatDownloads.map((download) => (
|
||||
<tr key={download.id}>
|
||||
<td>{download.assetId}</td>
|
||||
<td>
|
||||
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
|
||||
{download.authorizedAt.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</td>
|
||||
<td>{download.status}</td>
|
||||
<td>{download.repeatDownloadNote ?? "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<Table<RepeatDownloadPosition>
|
||||
rowKey={(download) => download.id}
|
||||
rows={repeatDownloads}
|
||||
columns={[
|
||||
{ key: "assetId", header: "Datei" },
|
||||
{
|
||||
key: "authorizedAt",
|
||||
header: "Datum",
|
||||
render: (download) => (
|
||||
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
|
||||
{download.authorizedAt.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
),
|
||||
},
|
||||
{ key: "status", header: "Status" },
|
||||
{ key: "repeatDownloadNote", header: "Notiz", render: (download) => download.repeatDownloadNote ?? "—" },
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<div className="billing-summary" aria-live="polite">
|
||||
<p>
|
||||
<strong>{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
|
||||
</p>
|
||||
<p className="billing-summary-total">
|
||||
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="billing-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePreview}
|
||||
disabled={selectedCount === 0 || actionState.loading}
|
||||
>
|
||||
Vorschau
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="billing-action-primary"
|
||||
onClick={handleFinalize}
|
||||
disabled={selectedCount === 0 || actionState.loading}
|
||||
>
|
||||
Abrechnung erstellen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{actionState.message && (
|
||||
<p className="billing-status-message" role={actionState.isError ? "alert" : "status"}>
|
||||
{actionState.message}
|
||||
</p>
|
||||
)}
|
||||
<Card>
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div aria-live="polite" className="billing-summary flex flex-col gap-1">
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
<strong className="text-[var(--color-fg-default)]">{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
|
||||
</p>
|
||||
<p className="text-2xl font-semibold tabular-nums">
|
||||
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button type="button" variant="outline" onClick={handlePreview} disabled={selectedCount === 0 || actionState.loading}>
|
||||
Vorschau
|
||||
</Button>
|
||||
<Button type="button" onClick={handleFinalize} disabled={selectedCount === 0 || actionState.loading}>
|
||||
Abrechnung erstellen
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{actionState.message && (
|
||||
<div role={actionState.isError ? undefined : "status"}>
|
||||
<Alert color={actionState.isError ? "danger" : "info"} description={actionState.message} />
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{reports.length > 0 && (
|
||||
<section aria-labelledby="reports-title" className="billing-reports-section">
|
||||
<h2 id="reports-title">Erstellte Abrechnungen</h2>
|
||||
<ul className="billing-reports-list">
|
||||
<section aria-labelledby="reports-title" className="flex flex-col gap-3">
|
||||
<h2 id="reports-title" className="text-lg font-semibold">Erstellte Abrechnungen</h2>
|
||||
<ul className="flex flex-col gap-3">
|
||||
{reports.map((report) => (
|
||||
<li key={report.id}>
|
||||
<div className="billing-report-meta">
|
||||
<span>Bericht Nr. {report.reportNumber}</span>
|
||||
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
|
||||
<span>Summe: {formatCents(report.netTotalCents)}</span>
|
||||
<span>Status: {REPORT_STATUS_LABELS[report.status] ?? report.status}</span>
|
||||
<span>
|
||||
Erstellt am:{" "}
|
||||
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
|
||||
{report.createdAt.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</span>
|
||||
</div>
|
||||
{report.status === "final" && (
|
||||
<>
|
||||
<Card>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
|
||||
<span className="inline-flex items-center gap-2 font-semibold">
|
||||
<IconFileText size={16} aria-hidden="true" />
|
||||
Bericht Nr. {report.reportNumber}
|
||||
</span>
|
||||
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
|
||||
<span className="tabular-nums">Summe: {formatCents(report.netTotalCents)}</span>
|
||||
<Badge variant={report.status === "final" ? "success" : "neutral"}>
|
||||
{REPORT_STATUS_LABELS[report.status] ?? report.status}
|
||||
</Badge>
|
||||
<span className="text-[var(--color-fg-muted)]">
|
||||
Erstellt am:{" "}
|
||||
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
|
||||
{report.createdAt.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</span>
|
||||
{report.status === "final" && (
|
||||
<Button asChild variant="outline">
|
||||
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
|
||||
<IconDownload size={16} aria-hidden="true" />
|
||||
PDF herunterladen
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{report.status === "final" && (
|
||||
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
|
||||
<a
|
||||
href={`/api/billing-reports/${encodeURIComponent(report.id)}`}
|
||||
className="billing-report-download"
|
||||
download
|
||||
>
|
||||
PDF herunterladen
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
)}
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -364,42 +359,33 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
|
||||
const years = [2025, 2026, 2027];
|
||||
|
||||
return (
|
||||
<form className="billing-period-selector" method="get">
|
||||
<label>
|
||||
<span>Jahr</span>
|
||||
<select name="year" defaultValue={year}>
|
||||
{years.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{isQuarter ? (
|
||||
<label>
|
||||
<span>Quartal</span>
|
||||
<select name="quarter" defaultValue={quarter ?? 1}>
|
||||
{[1, 2, 3, 4].map((q) => (
|
||||
<option key={q} value={q}>
|
||||
Q{q}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
<label>
|
||||
<span>Monat</span>
|
||||
<select name="month" defaultValue={month ?? 8}>
|
||||
{MONTHS.map((name, index) => (
|
||||
<option key={index} value={index + 1}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<button type="submit">Zeitraum laden</button>
|
||||
</form>
|
||||
<Card>
|
||||
<form className="flex flex-wrap items-end gap-4" method="get">
|
||||
<div className="w-32">
|
||||
<FormSelect name="year" label="Jahr" defaultValue={String(year)} options={years.map((y) => ({ label: String(y), value: String(y) }))} />
|
||||
</div>
|
||||
{isQuarter ? (
|
||||
<div className="w-32">
|
||||
<FormSelect
|
||||
name="quarter"
|
||||
label="Quartal"
|
||||
defaultValue={String(quarter ?? 1)}
|
||||
options={[1, 2, 3, 4].map((q) => ({ label: `Q${q}`, value: String(q) }))}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-40">
|
||||
<FormSelect
|
||||
name="month"
|
||||
label="Monat"
|
||||
defaultValue={String(month ?? 8)}
|
||||
options={MONTHS.map((name, index) => ({ label: name, value: String(index + 1) }))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Zeitraum laden</Button>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -440,38 +426,28 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="billing-cancel-form" onSubmit={handleSubmit}>
|
||||
<label>
|
||||
<span>Stornierungsgrund (5–500 Zeichen)</span>
|
||||
<textarea
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={500}
|
||||
<form className="flex flex-col gap-3 border-t border-[var(--color-border-subtle)] pt-4" onSubmit={handleSubmit}>
|
||||
<Textarea
|
||||
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
|
||||
disabled={loading}
|
||||
label="Stornierungsgrund (5–500 Zeichen)"
|
||||
maxLength={500}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
rows={2}
|
||||
value={reason}
|
||||
/>
|
||||
</label>
|
||||
<div className="billing-cancel-controls">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<Checkbox
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
disabled={loading}
|
||||
aria-label="Stornierung bestätigen"
|
||||
label="Stornierung bestätigen"
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>
|
||||
<span>Stornierung bestätigen</span>
|
||||
</label>
|
||||
<button type="submit" disabled={!valid || loading}>
|
||||
{loading ? "Wird storniert…" : "Stornieren"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="billing-status-message" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
<Button type="submit" variant="destructive" disabled={!valid || loading}>
|
||||
{loading ? "Wird storniert …" : "Stornieren"}
|
||||
</Button>
|
||||
</div>
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { loadBillingSelection } from "./page-content";
|
||||
import { BillingSelection } from "./BillingSelection";
|
||||
|
||||
@@ -17,12 +20,12 @@ export default async function BillingSelectionPage({
|
||||
if (!data) notFound();
|
||||
|
||||
return (
|
||||
<section className="content-section" aria-labelledby="billing-selection-title">
|
||||
<p className="eyebrow">Abrechnungen</p>
|
||||
<h1 id="billing-selection-title">{data.editorial.name}</h1>
|
||||
<p>
|
||||
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
|
||||
</p>
|
||||
<section className="flex flex-col gap-6" aria-labelledby="billing-selection-title">
|
||||
<PageHeader kicker="Abrechnungen" title={data.editorial.name} titleId="billing-selection-title">
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<BillingSelection
|
||||
editorialId={data.editorial.id}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { desc } from "drizzle-orm";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { formatCents } from "@/modules/billing/format";
|
||||
@@ -18,30 +22,44 @@ export default async function BillingOverviewPage() {
|
||||
.orderBy(desc(editorialAccounts.createdAt));
|
||||
|
||||
return (
|
||||
<section className="content-section" aria-labelledby="billing-title">
|
||||
<p className="eyebrow">Abrechnungen</p>
|
||||
<h1 id="billing-title">Redaktionen</h1>
|
||||
<p className="form-note">
|
||||
Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal
|
||||
auszuwählen.
|
||||
</p>
|
||||
<section className="flex flex-col gap-6" aria-labelledby="billing-title">
|
||||
<PageHeader
|
||||
kicker="Abrechnungen"
|
||||
title="Redaktionen"
|
||||
titleId="billing-title"
|
||||
description="Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal auszuwählen."
|
||||
/>
|
||||
{editorials.length === 0 ? (
|
||||
<p>Noch keine Redaktionen registriert.</p>
|
||||
<EmptyState title="Noch keine Redaktionen registriert." description="Registrierte Redaktionen erscheinen hier zur Abrechnung." />
|
||||
) : (
|
||||
<ul className="billing-editorial-list">
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{editorials.map((editorial) => (
|
||||
<li key={editorial.id}>
|
||||
<a href={`/admin/abrechnungen/${editorial.id}`}>{editorial.name}</a>
|
||||
<p>
|
||||
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
|
||||
{editorial.currentPriceCents === null
|
||||
? " · Preis noch nicht festgelegt"
|
||||
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||
</p>
|
||||
<Link
|
||||
className="block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
|
||||
href={`/admin/abrechnungen/${editorial.id}`}
|
||||
>
|
||||
<Card interactive className="h-full">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 className="text-base font-semibold">{editorial.name}</h2>
|
||||
<Badge variant={editorial.status === "active" ? "success" : editorial.status === "pending_approval" ? "warning" : "danger"}>
|
||||
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
{editorial.contactName} · {editorial.loginEmail}
|
||||
</p>
|
||||
<p className="text-sm font-medium">
|
||||
{editorial.currentPriceCents === null
|
||||
? "Preis noch nicht festgelegt"
|
||||
: `Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||
</p>
|
||||
</Card>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
class PrincipalAuthorizationError extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
PrincipalAuthorizationError,
|
||||
headers: vi.fn(),
|
||||
redirect: vi.fn((destination: string): never => {
|
||||
throw new Error(`NEXT_REDIRECT:${destination}`);
|
||||
}),
|
||||
requireAdmin: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react", () => ({ cache: (callback: unknown) => callback }));
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));
|
||||
vi.mock("@/modules/auth/principal", () => ({
|
||||
PrincipalAuthorizationError: mocks.PrincipalAuthorizationError,
|
||||
requireAdmin: mocks.requireAdmin,
|
||||
}));
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
|
||||
import { requireAdminPage } from "./access";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
});
|
||||
|
||||
test("redirects an expired admin page loader session to sign-in", async () => {
|
||||
mocks.requireAdmin.mockRejectedValue(
|
||||
new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
|
||||
);
|
||||
|
||||
await expect(requireAdminPage()).rejects.toThrow("NEXT_REDIRECT:/anmelden");
|
||||
});
|
||||
|
||||
test("rethrows non-session admin page loader failures unchanged", async () => {
|
||||
const unavailable = new Error("database unavailable");
|
||||
mocks.requireAdmin.mockRejectedValue(unavailable);
|
||||
|
||||
await expect(requireAdminPage()).rejects.toBe(unavailable);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import "server-only";
|
||||
|
||||
import { cache } from "react";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requirePageAccess } from "@/modules/auth/page-access";
|
||||
import { requireAdmin, requireAdminForSetup } from "@/modules/auth/principal";
|
||||
|
||||
/** Strict guard: valid admin session with finished two-factor setup. */
|
||||
export const requireAdminPage = cache(async () =>
|
||||
requirePageAccess(async () => requireAdmin(new Headers(await headers()))),
|
||||
);
|
||||
@@ -0,0 +1,163 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
AlbumAccessManager,
|
||||
type AlbumAccessManagerAlbum,
|
||||
type AlbumAccessManagerEditorial,
|
||||
} from "./AlbumAccessManager";
|
||||
import type { AlbumAccessActionResult } from "./actions";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const albumOne = "11111111-1111-4111-8111-111111111111";
|
||||
const albumTwo = "22222222-2222-4222-8222-222222222222";
|
||||
const editorialOne = "33333333-3333-4333-8333-333333333333";
|
||||
const editorialTwo = "44444444-4444-4444-8444-444444444444";
|
||||
|
||||
const albums: AlbumAccessManagerAlbum[] = [
|
||||
{
|
||||
id: albumOne,
|
||||
albumName: "Pressefotos",
|
||||
albumThumbnailAssetId: null,
|
||||
assetCount: 4,
|
||||
grants: [
|
||||
{ editorialId: editorialOne, editorialName: "Kicker Daily", archived: false },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: albumTwo,
|
||||
albumName: "Spieltagfotos",
|
||||
albumThumbnailAssetId: null,
|
||||
assetCount: 12,
|
||||
grants: [],
|
||||
},
|
||||
];
|
||||
|
||||
const editorials: AlbumAccessManagerEditorial[] = [
|
||||
{ id: editorialOne, name: "Kicker Daily" },
|
||||
{ id: editorialTwo, name: "Sport Woche" },
|
||||
];
|
||||
|
||||
const okResult: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 };
|
||||
|
||||
function setup() {
|
||||
const bulkGrantAction = vi.fn().mockResolvedValue(okResult);
|
||||
const revokeAction = vi.fn().mockResolvedValue(okResult);
|
||||
render(
|
||||
<AlbumAccessManager
|
||||
albums={albums}
|
||||
editorials={editorials}
|
||||
bulkGrantAction={bulkGrantAction}
|
||||
revokeAction={revokeAction}
|
||||
/>,
|
||||
);
|
||||
return { bulkGrantAction, revokeAction };
|
||||
}
|
||||
|
||||
function bulkFieldset() {
|
||||
return within(
|
||||
screen
|
||||
.getByLabelText("Alben für die Bulk-Zuweisung durchsuchen")
|
||||
.closest("fieldset") as HTMLFieldSetElement,
|
||||
);
|
||||
}
|
||||
|
||||
function overviewTable() {
|
||||
return within(screen.getByRole("table"));
|
||||
}
|
||||
|
||||
test("lists every album with its granted editorials and a link to the editorial", () => {
|
||||
setup();
|
||||
|
||||
const overview = overviewTable();
|
||||
const pressefotosRow = overview.getByText("Pressefotos").closest("tr");
|
||||
expect(pressefotosRow?.textContent).toContain("Kicker Daily");
|
||||
expect(
|
||||
overview
|
||||
.getByRole("link", { name: "Kicker Daily" })
|
||||
.getAttribute("href")
|
||||
?.startsWith("/admin/redaktionen/33333333"),
|
||||
).toBe(true);
|
||||
const spieltagRow = overview.getByText("Spieltagfotos").closest("tr");
|
||||
expect(spieltagRow?.textContent).toContain("Noch keine Redaktion");
|
||||
});
|
||||
|
||||
test("the grant button stays disabled until an album and an editorial are selected", () => {
|
||||
setup();
|
||||
|
||||
const grantButton = screen.getByRole("button", {
|
||||
name: "Zugriff gewähren",
|
||||
}) as HTMLButtonElement;
|
||||
expect(grantButton.disabled).toBe(true);
|
||||
|
||||
fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Pressefotos/ }));
|
||||
expect(grantButton.disabled).toBe(true);
|
||||
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Sport Woche" }));
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Zugriff gewähren (1 Album, 1 Redaktion)" }),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
test("selects all albums via Alle auswählen and clears them again", () => {
|
||||
setup();
|
||||
|
||||
fireEvent.click(bulkFieldset().getByRole("button", { name: /Alle auswählen/i }));
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Zugriff gewähren (2 Alben, 0 Redaktionen)" }),
|
||||
).toBeTruthy();
|
||||
|
||||
fireEvent.click(bulkFieldset().getByRole("button", { name: /Auswahl aufheben/i }));
|
||||
expect(screen.getByRole("button", { name: "Zugriff gewähren" })).toBeTruthy();
|
||||
});
|
||||
|
||||
test("the album search narrows the bulk selection and select-all respects the filter", () => {
|
||||
setup();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Alben für die Bulk-Zuweisung durchsuchen"), {
|
||||
target: { value: "Spieltag" },
|
||||
});
|
||||
|
||||
expect(bulkFieldset().queryByRole("checkbox", { name: /Pressefotos/ })).toBeNull();
|
||||
fireEvent.click(bulkFieldset().getByRole("button", { name: /Alle auswählen/i }));
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Zugriff gewähren (1 Album, 0 Redaktionen)" }),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
test("the selected checkboxes carry album and editorial ids for the server action", () => {
|
||||
const { bulkGrantAction } = setup();
|
||||
const form = screen
|
||||
.getByRole("button", { name: "Zugriff gewähren" })
|
||||
.closest("form") as HTMLFormElement;
|
||||
|
||||
fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Pressefotos/ }));
|
||||
fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Spieltagfotos/ }));
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Sport Woche" }));
|
||||
|
||||
const albumValues = [...form.querySelectorAll<HTMLInputElement>('input[name="immichAlbumIds"]')]
|
||||
.filter((input) => input.checked)
|
||||
.map((input) => input.value);
|
||||
const editorialValues = [...form.querySelectorAll<HTMLInputElement>('input[name="editorialIds"]')]
|
||||
.filter((input) => input.checked)
|
||||
.map((input) => input.value);
|
||||
|
||||
expect(albumValues).toEqual([albumOne, albumTwo]);
|
||||
expect(editorialValues).toEqual([editorialTwo]);
|
||||
expect(bulkGrantAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the overview search matches album names and granted editorial names", () => {
|
||||
setup();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Albumzugriffe durchsuchen"), {
|
||||
target: { value: "Kicker" },
|
||||
});
|
||||
|
||||
const overview = overviewTable();
|
||||
expect(overview.queryByText("Spieltagfotos")).toBeNull();
|
||||
expect(overview.getByText("Pressefotos")).toBeTruthy();
|
||||
});
|
||||
@@ -0,0 +1,376 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useActionState, useMemo, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Alert, Checkbox, EmptyState, Input, Table } from "@sakaniui/react";
|
||||
import { IconSearch, IconX } from "@sakaniui/react/icons";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type { AlbumAccessActionResult } from "./actions";
|
||||
|
||||
type AccessAction = (
|
||||
state: AlbumAccessActionResult,
|
||||
formData: FormData,
|
||||
) => Promise<AlbumAccessActionResult>;
|
||||
|
||||
type OverviewRow = AlbumAccessManagerAlbum;
|
||||
|
||||
export type AlbumAccessManagerAlbum = {
|
||||
id: string;
|
||||
albumName: string;
|
||||
albumThumbnailAssetId: string | null;
|
||||
assetCount: number;
|
||||
grants: Array<{ editorialId: string; editorialName: string; archived: boolean }>;
|
||||
};
|
||||
|
||||
export type AlbumAccessManagerEditorial = { id: string; name: string };
|
||||
|
||||
const INITIAL_RESULT: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 };
|
||||
|
||||
export function AlbumAccessManager({
|
||||
albums,
|
||||
editorials,
|
||||
bulkGrantAction,
|
||||
revokeAction,
|
||||
}: Readonly<{
|
||||
albums: AlbumAccessManagerAlbum[];
|
||||
editorials: AlbumAccessManagerEditorial[];
|
||||
bulkGrantAction: AccessAction;
|
||||
revokeAction: AccessAction;
|
||||
}>) {
|
||||
const [bulkState, setBulkState] = useState<AlbumAccessActionResult>(INITIAL_RESULT);
|
||||
const [bulkPending, startBulkTransition] = useTransition();
|
||||
const [revokeState, revokeFormAction, revokePending] = useActionState(
|
||||
revokeAction,
|
||||
INITIAL_RESULT,
|
||||
);
|
||||
const [selectedAlbumIds, setSelectedAlbumIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [selectedEditorialIds, setSelectedEditorialIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [bulkSearch, setBulkSearch] = useState("");
|
||||
const [overviewSearch, setOverviewSearch] = useState("");
|
||||
|
||||
// Same selection flow as the single-editorial AlbumGrid: call the action in a
|
||||
// transition so the result can clear the checkboxes without an effect.
|
||||
const handleBulkSubmit = (formData: FormData) => {
|
||||
startBulkTransition(async () => {
|
||||
const result = await bulkGrantAction(INITIAL_RESULT, formData);
|
||||
setBulkState(result);
|
||||
if (result.ok && result.grantedCount > 0) {
|
||||
setSelectedAlbumIds(new Set());
|
||||
setSelectedEditorialIds(new Set());
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const bulkQuery = bulkSearch.trim().toLowerCase();
|
||||
const bulkAlbums = useMemo(
|
||||
() =>
|
||||
bulkQuery
|
||||
? albums.filter((album) => album.albumName.toLowerCase().includes(bulkQuery))
|
||||
: albums,
|
||||
[albums, bulkQuery],
|
||||
);
|
||||
|
||||
const overviewQuery = overviewSearch.trim().toLowerCase();
|
||||
const overviewAlbums = useMemo(
|
||||
() =>
|
||||
overviewQuery
|
||||
? albums.filter(
|
||||
(album) =>
|
||||
album.albumName.toLowerCase().includes(overviewQuery) ||
|
||||
album.grants.some((holder) =>
|
||||
holder.editorialName.toLowerCase().includes(overviewQuery),
|
||||
),
|
||||
)
|
||||
: albums,
|
||||
[albums, overviewQuery],
|
||||
);
|
||||
|
||||
const allBulkAlbumsSelected =
|
||||
bulkAlbums.length > 0 && bulkAlbums.every((album) => selectedAlbumIds.has(album.id));
|
||||
const allEditorialsSelected =
|
||||
editorials.length > 0 && editorials.every((editorial) => selectedEditorialIds.has(editorial.id));
|
||||
|
||||
const toggleAlbumSelection = (albumId: string, selected: boolean) => {
|
||||
setSelectedAlbumIds((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (selected) {
|
||||
next.add(albumId);
|
||||
} else {
|
||||
next.delete(albumId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleEditorialSelection = (editorialId: string, selected: boolean) => {
|
||||
setSelectedEditorialIds((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (selected) {
|
||||
next.add(editorialId);
|
||||
} else {
|
||||
next.delete(editorialId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleAllBulkAlbums = () => {
|
||||
setSelectedAlbumIds((previous) => {
|
||||
const next = new Set(previous);
|
||||
for (const album of bulkAlbums) {
|
||||
if (allBulkAlbumsSelected) {
|
||||
next.delete(album.id);
|
||||
} else {
|
||||
next.add(album.id);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleAllEditorials = () => {
|
||||
setSelectedEditorialIds((previous) => {
|
||||
const next = new Set(previous);
|
||||
for (const editorial of editorials) {
|
||||
if (allEditorialsSelected) {
|
||||
next.delete(editorial.id);
|
||||
} else {
|
||||
next.add(editorial.id);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const canSubmit = selectedAlbumIds.size > 0 && selectedEditorialIds.size > 0;
|
||||
const submitLabel =
|
||||
selectedAlbumIds.size === 0 && selectedEditorialIds.size === 0
|
||||
? "Zugriff gewähren"
|
||||
: `Zugriff gewähren (${selectedAlbumIds.size} ${
|
||||
selectedAlbumIds.size === 1 ? "Album" : "Alben"
|
||||
}, ${selectedEditorialIds.size} ${
|
||||
selectedEditorialIds.size === 1 ? "Redaktion" : "Redaktionen"
|
||||
})`;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bulk-Zuweisung</CardTitle>
|
||||
<CardDescription>
|
||||
Alben und Redaktionen auswählen und allen ausgewählten Redaktionen mit einem Klick
|
||||
Zugriff auf alle ausgewählten Alben geben. Bereits bestehende Zuweisungen werden
|
||||
übersprungen.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={handleBulkSubmit} className="flex flex-col gap-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<fieldset className="flex min-w-0 flex-col gap-3">
|
||||
<legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
|
||||
Alben ({selectedAlbumIds.size} ausgewählt)
|
||||
</legend>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Input
|
||||
leadingIcon={<IconSearch size={16} />}
|
||||
type="search"
|
||||
value={bulkSearch}
|
||||
onChange={(event) => setBulkSearch(event.target.value)}
|
||||
placeholder="Alben suchen…"
|
||||
aria-label="Alben für die Bulk-Zuweisung durchsuchen"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="whitespace-nowrap"
|
||||
onClick={toggleAllBulkAlbums}
|
||||
disabled={bulkAlbums.length === 0}
|
||||
>
|
||||
{allBulkAlbumsSelected ? "Auswahl aufheben" : "Alle auswählen"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-80 divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
|
||||
{bulkAlbums.length === 0 ? (
|
||||
<p className="p-4 text-sm text-[var(--color-fg-muted)]">Keine Alben gefunden.</p>
|
||||
) : (
|
||||
bulkAlbums.map((album) => (
|
||||
<div key={album.id} className="flex items-center gap-3 px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
|
||||
<Checkbox
|
||||
checked={selectedAlbumIds.has(album.id)}
|
||||
label={album.albumName}
|
||||
name="immichAlbumIds"
|
||||
onChange={(event) => toggleAlbumSelection(album.id, event.target.checked)}
|
||||
value={album.id}
|
||||
/>
|
||||
<span className="ml-auto shrink-0 text-xs text-[var(--color-fg-muted)]">
|
||||
{album.assetCount} Fotos
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="flex min-w-0 flex-col gap-3">
|
||||
<legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
|
||||
Redaktionen ({selectedEditorialIds.size} ausgewählt)
|
||||
</legend>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={toggleAllEditorials}
|
||||
disabled={editorials.length === 0}
|
||||
>
|
||||
{allEditorialsSelected ? "Auswahl aufheben" : "Alle auswählen"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-80 divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
|
||||
{editorials.length === 0 ? (
|
||||
<p className="p-4 text-sm text-[var(--color-fg-muted)]">
|
||||
Keine aktiven Redaktionen vorhanden.
|
||||
</p>
|
||||
) : (
|
||||
editorials.map((editorial) => (
|
||||
<div key={editorial.id} className="px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
|
||||
<Checkbox
|
||||
checked={selectedEditorialIds.has(editorial.id)}
|
||||
label={editorial.name}
|
||||
name="editorialIds"
|
||||
onChange={(event) => toggleEditorialSelection(editorial.id, event.target.checked)}
|
||||
value={editorial.id}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
|
||||
{bulkState.message ? (
|
||||
<Alert color={bulkState.ok ? "success" : "danger"} description={bulkState.message} />
|
||||
) : (
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Wähle mindestens ein Album und eine Redaktion aus.
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit || bulkPending} className="shrink-0">
|
||||
{bulkPending ? "Wird verarbeitet…" : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="gap-4">
|
||||
<div>
|
||||
<CardTitle>Albumzugriffe</CardTitle>
|
||||
<CardDescription>
|
||||
Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den
|
||||
Zugriff für die einzelne Redaktion.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="sm:max-w-sm">
|
||||
<Input
|
||||
leadingIcon={<IconSearch size={16} />}
|
||||
type="search"
|
||||
value={overviewSearch}
|
||||
onChange={(event) => setOverviewSearch(event.target.value)}
|
||||
placeholder="Album oder Redaktion suchen…"
|
||||
aria-label="Albumzugriffe durchsuchen"
|
||||
/>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{revokeState.message ? (
|
||||
<Alert color={revokeState.ok ? "success" : "danger"} description={revokeState.message} />
|
||||
) : null}
|
||||
|
||||
{albums.length === 0 ? (
|
||||
<EmptyState title="Derzeit sind keine Alben vorhanden." description="Alben erscheinen hier, sobald der Immich-Zugang sie lesen kann." />
|
||||
) : overviewAlbums.length === 0 ? (
|
||||
<EmptyState type="no-results" title="Keine Alben gefunden." description="Versuchen Sie einen anderen Suchbegriff." />
|
||||
) : (
|
||||
<Table<OverviewRow>
|
||||
rowKey={(album) => album.id}
|
||||
rows={overviewAlbums}
|
||||
columns={[
|
||||
{
|
||||
key: "albumName",
|
||||
header: "Album",
|
||||
render: (album) => (
|
||||
<div className="flex items-center gap-3">
|
||||
{album.albumThumbnailAssetId ? (
|
||||
<img
|
||||
className="h-10 w-14 shrink-0 rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] object-cover"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
|
||||
/>
|
||||
) : (
|
||||
<div aria-hidden="true" className="grid h-10 w-14 shrink-0 place-items-center rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] text-[10px] text-[var(--color-fg-muted)]">
|
||||
Kein Cover
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium" title={album.albumName}>{album.albumName}</p>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "grants",
|
||||
header: "Redaktionen mit Zugriff",
|
||||
render: (album) =>
|
||||
album.grants.length === 0 ? (
|
||||
<span className="text-[var(--color-fg-muted)]">Noch keine Redaktion</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{album.grants.map((holder) => (
|
||||
<form
|
||||
key={holder.editorialId}
|
||||
action={revokeFormAction}
|
||||
className="inline-flex items-center overflow-hidden rounded-[var(--radius-full)] border border-[var(--color-border-default)] bg-[var(--color-bg-subtle)] text-[var(--color-fg-default)]"
|
||||
>
|
||||
<input type="hidden" name="immichAlbumId" value={album.id} />
|
||||
<input type="hidden" name="editorialId" value={holder.editorialId} />
|
||||
<Link
|
||||
href={`/admin/redaktionen/${holder.editorialId}`}
|
||||
className="py-0.5 pl-2.5 text-xs font-medium hover:underline"
|
||||
>
|
||||
{holder.editorialName}
|
||||
{holder.archived ? " (archiviert)" : ""}
|
||||
</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={revokePending}
|
||||
aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`}
|
||||
title={`Zugriff für ${holder.editorialName} entziehen`}
|
||||
className="grid place-items-center px-1.5 py-1 hover:bg-[var(--color-bg-muted)] disabled:opacity-50"
|
||||
>
|
||||
<IconX size={12} aria-hidden="true" />
|
||||
</button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ key: "assetCount", header: "Anzahl", align: "right", render: (album) => <span className="tabular-nums">{album.grants.length}</span> },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
bulkGrantAlbums: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
requireAdmin: vi.fn(),
|
||||
revalidatePath: vi.fn(),
|
||||
revokeAlbum: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||
vi.mock("@/modules/albums/grants", () => ({
|
||||
AlbumGrantError: class AlbumGrantError extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
},
|
||||
albumGrantService: { bulkGrantAlbums: mocks.bulkGrantAlbums, revokeAlbum: mocks.revokeAlbum },
|
||||
}));
|
||||
|
||||
import { bulkGrantAlbumAccessAction, revokeAlbumAccessAction } from "./actions";
|
||||
|
||||
const initial = { ok: true, message: "", grantedCount: 0 };
|
||||
const albumOne = "11111111-1111-4111-8111-111111111111";
|
||||
const albumTwo = "22222222-2222-4222-8222-222222222222";
|
||||
const editorialOne = "33333333-3333-4333-8333-333333333333";
|
||||
const editorialTwo = "44444444-4444-4444-8444-444444444444";
|
||||
|
||||
function bulkFormData(): FormData {
|
||||
const formData = new FormData();
|
||||
for (const albumId of [albumOne, albumTwo]) {
|
||||
formData.append("immichAlbumIds", albumId);
|
||||
}
|
||||
for (const editorialId of [editorialOne, editorialTwo]) {
|
||||
formData.append("editorialIds", editorialId);
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
|
||||
test("the bulk action rejects unauthenticated callers before touching the service", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
|
||||
|
||||
await expect(bulkGrantAlbumAccessAction(initial, bulkFormData())).rejects.toThrow(
|
||||
"ADMIN_REQUIRED",
|
||||
);
|
||||
expect(mocks.bulkGrantAlbums).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the bulk action demands at least one album and one editorial", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
|
||||
const result = await bulkGrantAlbumAccessAction(initial, new FormData());
|
||||
|
||||
expect(result).toMatchObject({ ok: false, grantedCount: 0 });
|
||||
expect(result.message).toContain("mindestens ein Album und eine Redaktion");
|
||||
expect(mocks.bulkGrantAlbums).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the bulk action grants every selected combination and revalidates affected pages", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.bulkGrantAlbums.mockResolvedValue({ granted: 4, skipped: 0, failed: 0 });
|
||||
|
||||
const result = await bulkGrantAlbumAccessAction(initial, bulkFormData());
|
||||
|
||||
expect(mocks.bulkGrantAlbums).toHaveBeenCalledWith({
|
||||
albumIds: [albumOne, albumTwo],
|
||||
editorialIds: [editorialOne, editorialTwo],
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(result).toMatchObject({ ok: true, grantedCount: 4 });
|
||||
expect(result.message).toContain("4 Zuweisung(en) erstellt");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/alben");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialOne}/alben`);
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialTwo}/alben`);
|
||||
});
|
||||
|
||||
test("the bulk action reports skipped and failed pairs in German", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.bulkGrantAlbums.mockResolvedValue({ granted: 1, skipped: 2, failed: 1 });
|
||||
|
||||
const result = await bulkGrantAlbumAccessAction(initial, bulkFormData());
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.message).toContain("1 Zuweisung(en) erstellt");
|
||||
expect(result.message).toContain("2 bestand(en) bereits");
|
||||
expect(result.message).toContain("1 fehlgeschlagen");
|
||||
});
|
||||
|
||||
test("the bulk action returns a German message when Immich is down", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
const { AlbumGrantError } = await import("@/modules/albums/grants");
|
||||
mocks.bulkGrantAlbums.mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE"));
|
||||
|
||||
const result = await bulkGrantAlbumAccessAction(initial, bulkFormData());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
grantedCount: 0,
|
||||
message: "Immich ist momentan nicht erreichbar. Bitte später erneut versuchen.",
|
||||
});
|
||||
expect(mocks.revalidatePath).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the revoke action entzieht a single album-editorial pair", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.revokeAlbum.mockResolvedValue(undefined);
|
||||
const formData = new FormData();
|
||||
formData.set("immichAlbumId", albumOne);
|
||||
formData.set("editorialId", editorialOne);
|
||||
|
||||
const result = await revokeAlbumAccessAction(initial, formData);
|
||||
|
||||
expect(mocks.revokeAlbum).toHaveBeenCalledWith({
|
||||
editorialId: editorialOne,
|
||||
immichAlbumId: albumOne,
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(result).toEqual({ ok: true, message: "", grantedCount: 0 });
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/alben");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialOne}/alben`);
|
||||
});
|
||||
|
||||
test("the revoke action rejects malformed identifiers", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
const formData = new FormData();
|
||||
formData.set("immichAlbumId", "not-a-uuid");
|
||||
formData.set("editorialId", editorialOne);
|
||||
|
||||
const result = await revokeAlbumAccessAction(initial, formData);
|
||||
|
||||
expect(result).toMatchObject({ ok: false, grantedCount: 0 });
|
||||
expect(mocks.revokeAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
|
||||
// Returned to the client form so failures surface as inline German text
|
||||
// instead of an opaque Next.js error-digest page (a thrown server action
|
||||
// becomes a 500 with a digest the user can't read).
|
||||
export type AlbumAccessActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
grantedCount: number;
|
||||
};
|
||||
|
||||
const INITIAL_RESULT: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 };
|
||||
|
||||
const UUID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function bulkGrantAlbumAccessAction(
|
||||
_prevState: AlbumAccessActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AlbumAccessActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const albumIds = formData.getAll("immichAlbumIds").filter(isValidUuid);
|
||||
const editorialIds = formData.getAll("editorialIds").filter(isValidUuid);
|
||||
|
||||
if (albumIds.length === 0 || editorialIds.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Bitte mindestens ein Album und eine Redaktion auswählen.",
|
||||
grantedCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let result: Awaited<ReturnType<typeof albumGrantService.bulkGrantAlbums>>;
|
||||
try {
|
||||
result = await albumGrantService.bulkGrantAlbums({
|
||||
albumIds,
|
||||
editorialIds,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: albumGrantErrorMessage(error), grantedCount: 0 };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/alben");
|
||||
for (const editorialId of editorialIds) {
|
||||
revalidatePath(`/admin/redaktionen/${editorialId}/alben`);
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
if (result.granted > 0) parts.push(`${result.granted} Zuweisung(en) erstellt`);
|
||||
if (result.skipped > 0) parts.push(`${result.skipped} bestand(en) bereits`);
|
||||
if (result.failed > 0) parts.push(`${result.failed} fehlgeschlagen`);
|
||||
return {
|
||||
ok: result.failed === 0,
|
||||
message:
|
||||
parts.length > 0
|
||||
? `${parts.join(", ")}.`
|
||||
: "Es gab nichts zu zuweisen — alle ausgewählten Kombinationen bestanden bereits.",
|
||||
grantedCount: result.granted,
|
||||
};
|
||||
}
|
||||
|
||||
export async function revokeAlbumAccessAction(
|
||||
_prevState: AlbumAccessActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AlbumAccessActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const immichAlbumId = formData.get("immichAlbumId");
|
||||
const editorialId = formData.get("editorialId");
|
||||
if (!isValidUuid(immichAlbumId) || !isValidUuid(editorialId)) {
|
||||
return { ok: false, message: "Ungültige Kennung.", grantedCount: 0 };
|
||||
}
|
||||
|
||||
try {
|
||||
await albumGrantService.revokeAlbum({
|
||||
editorialId,
|
||||
immichAlbumId,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: albumGrantErrorMessage(error), grantedCount: 0 };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/alben");
|
||||
revalidatePath(`/admin/redaktionen/${editorialId}/alben`);
|
||||
return INITIAL_RESULT;
|
||||
}
|
||||
|
||||
function isValidUuid(value: FormDataEntryValue | null): value is string {
|
||||
return typeof value === "string" && UUID_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function albumGrantErrorMessage(error: unknown): string {
|
||||
if (error instanceof AlbumGrantError) {
|
||||
const messages: Record<AlbumGrantError["code"], string> = {
|
||||
ALBUM_NOT_ASSIGNABLE:
|
||||
"Mindestens ein Album konnte nicht gefunden werden oder lässt sich nicht zuweisen.",
|
||||
IMMICH_UNAVAILABLE:
|
||||
"Immich ist momentan nicht erreichbar. Bitte später erneut versuchen.",
|
||||
EDITORIAL_NOT_FOUND: "Redaktion nicht gefunden.",
|
||||
INVALID_ALBUM_GRANT_INPUT: "Ungültige Auswahl.",
|
||||
};
|
||||
return messages[error.code] ?? "Die Zuweisung ist fehlgeschlagen.";
|
||||
}
|
||||
return "Die Zuweisung ist fehlgeschlagen.";
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { AlbumGrantError } from "@/modules/albums/grants";
|
||||
|
||||
import { loadAlbumAccess } from "./page-content";
|
||||
|
||||
test("only an explicit Immich-unavailable error renders the unavailable album state", async () => {
|
||||
const unavailableService = {
|
||||
listAlbumAccessOverview: vi.fn().mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE")),
|
||||
};
|
||||
|
||||
await expect(loadAlbumAccess(unavailableService)).resolves.toEqual({
|
||||
albums: [],
|
||||
unavailable: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("database and programming errors propagate instead of being displayed as Immich unavailable", async () => {
|
||||
const databaseFailure = new Error("database connection lost");
|
||||
const failingService = {
|
||||
listAlbumAccessOverview: vi.fn().mockRejectedValue(databaseFailure),
|
||||
};
|
||||
|
||||
await expect(loadAlbumAccess(failingService)).rejects.toBe(databaseFailure);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { asc, isNull } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import {
|
||||
AlbumGrantError,
|
||||
albumGrantService,
|
||||
type AlbumAccessOverviewAlbum,
|
||||
} from "@/modules/albums/grants";
|
||||
|
||||
export type EditorialOption = { id: string; name: string };
|
||||
|
||||
export async function loadAlbumAccess(
|
||||
service: Pick<typeof albumGrantService, "listAlbumAccessOverview"> = albumGrantService,
|
||||
): Promise<{ albums: AlbumAccessOverviewAlbum[]; unavailable: boolean }> {
|
||||
try {
|
||||
const albums = await service.listAlbumAccessOverview();
|
||||
return { albums, unavailable: false };
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") {
|
||||
return { albums: [], unavailable: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk-grant targets: every non-archived editorial. Archived accounts cannot
|
||||
* log in anymore, so they stay out of the selection; grants they still hold
|
||||
* remain visible in the overview.
|
||||
*/
|
||||
export async function loadAssignableEditorials(): Promise<EditorialOption[]> {
|
||||
return db
|
||||
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
|
||||
.from(editorialAccounts)
|
||||
.where(isNull(editorialAccounts.archivedAt))
|
||||
.orderBy(asc(editorialAccounts.name));
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert } from "@/components/ui/sakani";
|
||||
|
||||
import { loadAlbumAccess, loadAssignableEditorials } from "./page-content";
|
||||
import { AlbumAccessManager } from "./AlbumAccessManager";
|
||||
import { bulkGrantAlbumAccessAction, revokeAlbumAccessAction } from "./actions";
|
||||
|
||||
export default async function AdminAlbumsPage() {
|
||||
const [albumResult, editorials] = await Promise.all([
|
||||
loadAlbumAccess(),
|
||||
loadAssignableEditorials(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Albumverwaltung"
|
||||
title="Alben"
|
||||
description="Alle Immich-Alben mit ihren Redaktionsfreigaben — inklusive Bulk-Zuweisung für mehrere Alben und Redaktionen auf einmal."
|
||||
>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/redaktionen">Zu den Redaktionen</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
{albumResult.unavailable ? (
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
|
||||
/>
|
||||
) : (
|
||||
<AlbumAccessManager
|
||||
albums={albumResult.albums.map((album) => ({
|
||||
id: album.id,
|
||||
albumName: album.albumName,
|
||||
albumThumbnailAssetId: album.albumThumbnailAssetId,
|
||||
assetCount: album.assetCount,
|
||||
grants: album.grants.map((holder) => ({
|
||||
editorialId: holder.editorialId,
|
||||
editorialName: holder.editorialName,
|
||||
archived: holder.archivedAt !== null,
|
||||
})),
|
||||
}))}
|
||||
editorials={editorials}
|
||||
bulkGrantAction={bulkGrantAlbumAccessAction}
|
||||
revokeAction={revokeAlbumAccessAction}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import Link from "next/link";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, DataTable, EmptyState, Input } from "@/components/ui/sakani";
|
||||
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
|
||||
const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
timeZone: "Europe/Berlin",
|
||||
dateStyle: "short",
|
||||
@@ -13,7 +16,7 @@ const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
|
||||
|
||||
export default async function AuditPage({ searchParams }: { searchParams: SearchParams }) {
|
||||
await requireAdmin(new Headers(await headers()));
|
||||
await requireAdminPage();
|
||||
|
||||
const params = await searchParams;
|
||||
const eventType = firstParam(params, "eventType");
|
||||
@@ -31,71 +34,52 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="content-section" aria-labelledby="audit-title">
|
||||
<p className="eyebrow">Administration</p>
|
||||
<h1 id="audit-title">Audit-Protokoll</h1>
|
||||
<p className="form-note">
|
||||
Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach
|
||||
Zeitstempel (neueste zuerst).
|
||||
</p>
|
||||
<section className="flex flex-col gap-6" aria-labelledby="audit-title">
|
||||
<PageHeader
|
||||
kicker="Administration"
|
||||
title="Audit-Protokoll"
|
||||
titleId="audit-title"
|
||||
description="Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach Zeitstempel (neueste zuerst)."
|
||||
/>
|
||||
|
||||
<form method="get" className="audit-filters" aria-label="Audit-Filter">
|
||||
<label>
|
||||
<span className="field-label">Ereignistyp</span>
|
||||
<input
|
||||
name="eventType"
|
||||
defaultValue={eventType ?? ""}
|
||||
placeholder="z. B. editorial_approved"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span className="field-label">Datum von (Berlin)</span>
|
||||
<input type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
|
||||
</label>
|
||||
<label>
|
||||
<span className="field-label">Datum bis (Berlin)</span>
|
||||
<input type="date" name="dateTo" defaultValue={dateTo ?? ""} />
|
||||
</label>
|
||||
<button type="submit">Filtern</button>
|
||||
</form>
|
||||
<Card>
|
||||
<form method="get" className="grid gap-4 sm:grid-cols-[1fr_11rem_11rem_auto] sm:items-end" aria-label="Audit-Filter">
|
||||
<Input label="Ereignistyp" name="eventType" defaultValue={eventType ?? ""} placeholder="z. B. editorial_approved" />
|
||||
<Input label="Datum von (Berlin)" type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
|
||||
<Input label="Datum bis (Berlin)" type="date" name="dateTo" defaultValue={dateTo ?? ""} />
|
||||
<Button type="submit" variant="secondary">Filtern</Button>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
{page.events.length === 0 ? (
|
||||
<p>Keine Einträge gefunden.</p>
|
||||
<EmptyState type="no-results" title="Keine Einträge gefunden." description="Passen Sie die Filter an oder setzen Sie sie zurück." />
|
||||
) : (
|
||||
<table className="audit-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Zeitstempel</th>
|
||||
<th>Akteur</th>
|
||||
<th>Ereignistyp</th>
|
||||
<th>Betreff</th>
|
||||
<th>Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{page.events.map((event) => (
|
||||
<tr key={event.id}>
|
||||
<td>{berlinFormatter.format(event.occurredAt)}</td>
|
||||
<td>{actorLabel(event)}</td>
|
||||
<td>{event.eventType}</td>
|
||||
<td>{entityLabel(event)}</td>
|
||||
<td>
|
||||
<pre className="audit-metadata">{formatMetadata(event)}</pre>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "at", header: "Zeitstempel" },
|
||||
{ key: "actor", header: "Akteur" },
|
||||
{ key: "type", header: "Ereignistyp" },
|
||||
{ key: "subject", header: "Betreff" },
|
||||
{ key: "details", header: "Details" },
|
||||
]}
|
||||
rows={page.events.map((event) => ({
|
||||
at: <span className="whitespace-nowrap tabular-nums">{berlinFormatter.format(new Date(event.occurredAt))}</span>,
|
||||
actor: actorLabel(event),
|
||||
type: <code className="break-all text-xs">{event.eventType}</code>,
|
||||
subject: <span className="break-all text-xs">{entityLabel(event)}</span>,
|
||||
details: <pre className="audit-metadata">{formatMetadata(event)}</pre>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{page.nextCursor && (
|
||||
<p className="audit-pagination">
|
||||
<Link
|
||||
href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}
|
||||
>
|
||||
Ältere Einträge laden
|
||||
</Link>
|
||||
</p>
|
||||
<div>
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}>
|
||||
Ältere Einträge laden
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
@@ -156,4 +140,4 @@ function buildPaginationHref(params: {
|
||||
if (params.dateTo) searchParams.set("dateTo", params.dateTo);
|
||||
searchParams.set("cursor", params.cursor);
|
||||
return searchParams.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
} from "recharts";
|
||||
|
||||
type DownloadsChartProps = {
|
||||
data: { date: string; downloads: number }[];
|
||||
};
|
||||
|
||||
export function DownloadsChart({ data }: DownloadsChartProps) {
|
||||
const { theme } = useTheme();
|
||||
|
||||
// Indigo primary color variables
|
||||
const primaryColor = theme === "dark" ? "#6366f1" : "#4f46e5"; // indigo-500 : indigo-600
|
||||
|
||||
return (
|
||||
<div className="h-[300px] w-full mt-4">
|
||||
{data.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-muted-foreground">
|
||||
Keine Download-Daten in den letzten 30 Tagen verfügbar.
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={data} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={theme === "dark" ? "#333" : "#e5e5e5"} />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
stroke="#888888"
|
||||
fontSize={12}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={(value) => {
|
||||
const date = new Date(value);
|
||||
return date.toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
stroke="#888888"
|
||||
fontSize={12}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={(value) => `${value}`}
|
||||
allowDecimals={false}
|
||||
/>
|
||||
<Tooltip
|
||||
cursor={{ fill: theme === "dark" ? "#ffffff10" : "#00000005" }}
|
||||
contentStyle={{
|
||||
backgroundColor: theme === "dark" ? "#1f2937" : "#ffffff",
|
||||
borderColor: theme === "dark" ? "#374151" : "#e5e7eb",
|
||||
borderRadius: "8px",
|
||||
color: theme === "dark" ? "#f3f4f6" : "#111827",
|
||||
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
|
||||
}}
|
||||
labelFormatter={(label: any) => {
|
||||
const date = new Date(label as string);
|
||||
return date.toLocaleDateString("de-DE", { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });
|
||||
}}
|
||||
formatter={(value: any) => [value as number, "Downloads"]}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="downloads"
|
||||
fill={primaryColor}
|
||||
radius={[4, 4, 0, 0]}
|
||||
maxBarSize={40}
|
||||
animationDuration={1000}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Alert, Input, Textarea } from "@sakaniui/react";
|
||||
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
|
||||
// Same direct-call-in-transition pattern as the album bulk grant form so the
|
||||
// message box clears after a successful publish without an effect.
|
||||
export function AnnouncementForm({
|
||||
action,
|
||||
defaultEventDate,
|
||||
}: Readonly<{
|
||||
action: (
|
||||
state: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
) => Promise<AnnouncementActionResult>;
|
||||
defaultEventDate: string;
|
||||
}>) {
|
||||
const messageId = useId();
|
||||
const dateId = useId();
|
||||
const [state, setState] = useState<AnnouncementActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [message, setMessage] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
if (result.ok) {
|
||||
setMessage("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="Neuer Hinweis">
|
||||
<form action={handleSubmit} className="flex flex-col gap-4">
|
||||
<Textarea
|
||||
description={`${message.length}/500 Zeichen`}
|
||||
id={messageId}
|
||||
label="Nachricht"
|
||||
maxLength={500}
|
||||
name="message"
|
||||
onChange={(event) => setMessage(event.target.value)}
|
||||
placeholder="z. B. Liebl ist heute beim HSV-Spiel — Freigaben und Downloads sind trotzdem verfügbar, Antworten dauern etwas länger."
|
||||
required
|
||||
rows={3}
|
||||
value={message}
|
||||
/>
|
||||
<div className="sm:max-w-xs">
|
||||
<Input
|
||||
defaultValue={defaultEventDate}
|
||||
description="Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem Datum."
|
||||
id={dateId}
|
||||
label="Datum des Ereignisses (z. B. Spieltag)"
|
||||
name="eventDate"
|
||||
required
|
||||
type="date"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird veröffentlicht …" : "Hinweis veröffentlichen"}
|
||||
</Button>
|
||||
</div>
|
||||
{state.message ? (
|
||||
<div aria-live="polite">
|
||||
<Alert color={state.ok ? "success" : "danger"} description={state.message} />
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
|
||||
import { IconTrash } from "@sakaniui/react/icons";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
|
||||
// One tiny form per announcement row so every delete button reports its own
|
||||
// result inline (same pattern as AlbumGrantForm).
|
||||
export function DeleteAnnouncementButton({
|
||||
action,
|
||||
announcementId,
|
||||
}: Readonly<{
|
||||
action: (
|
||||
state: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
) => Promise<AnnouncementActionResult>;
|
||||
announcementId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
<input type="hidden" name="announcementId" value={announcementId} />
|
||||
<Button type="submit" variant="ghost" size="sm" disabled={pending} leftIcon={<IconTrash size={16} />}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
{state.ok ? null : (
|
||||
<p role="alert" className="text-xs text-[var(--color-danger-fg)]">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createAnnouncement: vi.fn(),
|
||||
deleteAnnouncement: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
requireAdmin: vi.fn(),
|
||||
revalidatePath: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||
vi.mock("@/modules/announcements/service", () => ({
|
||||
AnnouncementServiceError: class AnnouncementServiceError extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
},
|
||||
announcementService: {
|
||||
createAnnouncement: mocks.createAnnouncement,
|
||||
deleteAnnouncement: mocks.deleteAnnouncement,
|
||||
},
|
||||
}));
|
||||
|
||||
import { AnnouncementServiceError } from "@/modules/announcements/service";
|
||||
|
||||
import { createAnnouncementAction, deleteAnnouncementAction } from "./actions";
|
||||
|
||||
const initial = { ok: true, message: "" };
|
||||
|
||||
test("the create action rejects unauthenticated callers before touching the service", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
|
||||
|
||||
await expect(createAnnouncementAction(initial, new FormData())).rejects.toThrow(
|
||||
"ADMIN_REQUIRED",
|
||||
);
|
||||
expect(mocks.createAnnouncement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the create action publishes a hint with the authenticated admin and revalidates both pages", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.createAnnouncement.mockResolvedValue({
|
||||
id: "announcement-1",
|
||||
message: "Hinweis",
|
||||
eventDate: "2026-09-14",
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("message", "Liebl ist beim HSV-Spiel.");
|
||||
formData.set("eventDate", "2026-09-14");
|
||||
|
||||
const result = await createAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(mocks.createAnnouncement).toHaveBeenCalledWith({
|
||||
message: "Liebl ist beim HSV-Spiel.",
|
||||
eventDate: "2026-09-14",
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/hinweise");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/redaktion/alben");
|
||||
});
|
||||
|
||||
test("the create action maps service errors to inline German messages", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.createAnnouncement.mockRejectedValue(
|
||||
new AnnouncementServiceError("INVALID_EVENT_DATE"),
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("message", "Hallo");
|
||||
formData.set("eventDate", "2026-02-30");
|
||||
|
||||
const result = await createAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
message: "Bitte wählen Sie ein gültiges Datum.",
|
||||
});
|
||||
expect(mocks.revalidatePath).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the delete action reports a vanished announcement in German", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.deleteAnnouncement.mockRejectedValue(
|
||||
new AnnouncementServiceError("ANNOUNCEMENT_NOT_FOUND"),
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("announcementId", "11111111-1111-4111-8111-111111111111");
|
||||
|
||||
const result = await deleteAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.message).toContain("existiert nicht mehr");
|
||||
});
|
||||
|
||||
test("the delete action revalidates both pages after a successful removal", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.deleteAnnouncement.mockResolvedValue(undefined);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("announcementId", "11111111-1111-4111-8111-111111111111");
|
||||
|
||||
const result = await deleteAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result).toEqual({ ok: true, message: "" });
|
||||
expect(mocks.deleteAnnouncement).toHaveBeenCalledWith({
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/hinweise");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/redaktion/alben");
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import {
|
||||
AnnouncementServiceError,
|
||||
announcementService,
|
||||
} from "@/modules/announcements/service";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
|
||||
// Returned to the client form so failures surface as inline German text
|
||||
// instead of an opaque Next.js error-digest page (same pattern as the album
|
||||
// access actions).
|
||||
export type AnnouncementActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createAnnouncementAction(
|
||||
_prevState: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AnnouncementActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const message = formData.get("message");
|
||||
const eventDate = formData.get("eventDate");
|
||||
|
||||
if (typeof message !== "string" || typeof eventDate !== "string") {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Bitte Nachricht und Datum ausfüllen.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
await announcementService.createAnnouncement({
|
||||
message,
|
||||
eventDate,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: announcementErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/hinweise");
|
||||
revalidatePath("/redaktion/alben");
|
||||
return {
|
||||
ok: true,
|
||||
message:
|
||||
"Hinweis veröffentlicht. Er ist für die Redaktionen sichtbar und verschwindet drei Tage nach dem Datum automatisch.",
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteAnnouncementAction(
|
||||
_prevState: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AnnouncementActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const announcementId = formData.get("announcementId");
|
||||
if (typeof announcementId !== "string" || announcementId.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await announcementService.deleteAnnouncement({
|
||||
id: announcementId,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: announcementErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/hinweise");
|
||||
revalidatePath("/redaktion/alben");
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
|
||||
function announcementErrorMessage(error: unknown): string {
|
||||
if (error instanceof AnnouncementServiceError) {
|
||||
const messages: Record<AnnouncementServiceError["code"], string> = {
|
||||
INVALID_MESSAGE: "Bitte geben Sie einen Text mit 1 bis 500 Zeichen ein.",
|
||||
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
|
||||
ANNOUNCEMENT_NOT_FOUND: "Dieser Hinweis existiert nicht mehr.",
|
||||
};
|
||||
return messages[error.code] ?? "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
return "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import {
|
||||
formatIsoDateGerman,
|
||||
isoDateInBerlin,
|
||||
announcementService,
|
||||
} from "@/modules/announcements/service";
|
||||
|
||||
import { AnnouncementForm } from "./AnnouncementForm";
|
||||
import { DeleteAnnouncementButton } from "./DeleteAnnouncementButton";
|
||||
import { createAnnouncementAction, deleteAnnouncementAction } from "./actions";
|
||||
|
||||
export default async function AdminAnnouncementsPage() {
|
||||
const items = await announcementService.listAnnouncements(new Date());
|
||||
const activeCount = items.filter((item) => item.isActive).length;
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Kommunikation"
|
||||
title="Hinweise"
|
||||
description="Kurze Meldungen für alle Redaktionen — z. B. wenn Sie bei einem Spiel nicht erreichbar sind. Ein Hinweis erscheint sofort in der Album-Übersicht und verschwindet drei Tage nach dem Ereignisdatum automatisch."
|
||||
/>
|
||||
|
||||
<AnnouncementForm
|
||||
action={createAnnouncementAction}
|
||||
defaultEventDate={isoDateInBerlin(new Date())}
|
||||
/>
|
||||
|
||||
<section className="flex flex-col gap-4" aria-labelledby="announcements-list-title">
|
||||
<div className="flex items-baseline justify-between gap-4">
|
||||
<h2 id="announcements-list-title" className="text-xl font-semibold">
|
||||
Alle Hinweise
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
{activeCount} aktiv · {items.length} insgesamt
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<EmptyState title="Noch keine Hinweise vorhanden." description="Veröffentlichte Hinweise erscheinen hier und in der Album-Übersicht der Redaktionen." />
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Card>
|
||||
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-start">
|
||||
<div className="flex min-w-0 flex-col gap-2">
|
||||
<p className="whitespace-pre-line break-words text-sm text-[var(--color-fg-default)]">{item.message}</p>
|
||||
<p className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-fg-muted)]">
|
||||
Ereignis: {formatIsoDateGerman(item.eventDate)}
|
||||
{item.isActive ? (
|
||||
<Badge variant="success">sichtbar bis {formatIsoDateGerman(item.visibleUntil)}</Badge>
|
||||
) : (
|
||||
<Badge>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</Badge>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
|
||||
</div>
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,19 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import { AppShell } from "@/components/layout/app-shell";
|
||||
import { env } from "@/config/env";
|
||||
|
||||
import { PortalShell } from "@/components/layout/portal-shell";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { requireAdminPage } from "./access";
|
||||
|
||||
export default async function AdminLayout({ children }: Readonly<{ children: ReactNode }>) {
|
||||
await requireAdmin(new Headers(await headers()));
|
||||
await requireAdminPage();
|
||||
|
||||
return (
|
||||
<PortalShell
|
||||
brandHref="/admin"
|
||||
sectionLabel="Administration"
|
||||
nav={[
|
||||
{ href: "/admin", label: "Dashboard" },
|
||||
{ href: "/admin/redaktionen", label: "Redaktionen" },
|
||||
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
|
||||
{ href: "/admin/audit", label: "Audit" },
|
||||
]}
|
||||
mainClassName=""
|
||||
<AppShell
|
||||
area="admin"
|
||||
legal={{ imprint: env.LEGAL_IMPRINT_URL, privacy: env.LEGAL_PRIVACY_URL, terms: env.LEGAL_TERMS_URL }}
|
||||
>
|
||||
{children}
|
||||
</PortalShell>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
}
|
||||
+117
-157
@@ -1,66 +1,69 @@
|
||||
import { eq, sql, and, desc, gte } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { usages, editorialAccounts } from "@/db/schema";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DownloadsChart } from "./downloads-chart";
|
||||
import { BarChart, Card, EmptyState, StatCard, DataTable } from "@/components/ui/sakani";
|
||||
import { requireAdminPage } from "./access";
|
||||
|
||||
export default async function AdminDashboardPage() {
|
||||
await requireAdmin(new Headers(await headers()));
|
||||
await requireAdminPage();
|
||||
|
||||
const now = new Date();
|
||||
const firstDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth(), 1));
|
||||
|
||||
// 1. Umsatz diesen Monat (Offen + Abgerechnet, aber nur usages aus diesem Monat)
|
||||
const [revenueStats] = await db
|
||||
.select({
|
||||
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
count: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, firstDayOfMonth));
|
||||
|
||||
// 2. Aktivste Redaktionen (nach Anzahl an Downloads insgesamt)
|
||||
const topEditorials = await db
|
||||
.select({
|
||||
editorialId: usages.editorialAccountId,
|
||||
name: editorialAccounts.name,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
|
||||
.groupBy(usages.editorialAccountId, editorialAccounts.name)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5);
|
||||
|
||||
// 3. Beliebteste Alben
|
||||
const topAlbums = await db
|
||||
.select({
|
||||
albumName: usages.albumNameSnapshot,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.groupBy(usages.albumNameSnapshot)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5);
|
||||
|
||||
// 4. Time-series data for the last 30 days
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
const dailyDownloads = await db
|
||||
.select({
|
||||
date: sql<string>`DATE_TRUNC('day', ${usages.createdAt})::date::text`,
|
||||
downloads: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, thirtyDaysAgo))
|
||||
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
.orderBy(sql`DATE_TRUNC('day', ${usages.createdAt})`);
|
||||
|
||||
const [revenueStatsResult, topEditorials, topAlbums, dailyDownloads] = await Promise.all([
|
||||
// 1. Umsatz diesen Monat (Offen + Abgerechnet, aber nur usages aus diesem Monat)
|
||||
db
|
||||
.select({
|
||||
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
count: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, firstDayOfMonth)),
|
||||
|
||||
// 2. Aktivste Redaktionen (nach Anzahl an Downloads insgesamt)
|
||||
db
|
||||
.select({
|
||||
editorialId: usages.editorialAccountId,
|
||||
name: editorialAccounts.name,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
|
||||
.groupBy(usages.editorialAccountId, editorialAccounts.name)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5),
|
||||
|
||||
// 3. Beliebteste Alben
|
||||
db
|
||||
.select({
|
||||
albumName: usages.albumNameSnapshot,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.groupBy(usages.albumNameSnapshot)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5),
|
||||
|
||||
// 4. Time-series data for the last 30 days
|
||||
db
|
||||
.select({
|
||||
date: sql<string>`DATE_TRUNC('day', ${usages.createdAt})::date::text`,
|
||||
downloads: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, thirtyDaysAgo))
|
||||
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
.orderBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
]);
|
||||
|
||||
const revenueStats = revenueStatsResult[0];
|
||||
|
||||
// Fill in missing days
|
||||
const chartData = [];
|
||||
@@ -70,125 +73,82 @@ export default async function AdminDashboardPage() {
|
||||
const dateStr = d.toISOString().split('T')[0];
|
||||
const record = dailyDownloads.find(r => r.date === dateStr);
|
||||
chartData.push({
|
||||
date: dateStr,
|
||||
downloads: record ? record.downloads : 0,
|
||||
label: d.toLocaleDateString("de-DE", { day: "numeric" }), // ponytail: day only; 30 "dd. MMM" labels overlap
|
||||
value: record ? record.downloads : 0,
|
||||
});
|
||||
}
|
||||
|
||||
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div>
|
||||
<h1 className="text-4xl font-bold tracking-tight">Admin Dashboard</h1>
|
||||
<p className="text-muted-foreground mt-2">Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals.</p>
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Admin Dashboard"
|
||||
description="Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals."
|
||||
>
|
||||
<Button asChild>
|
||||
<Link href="/admin/redaktionen">Redaktionen verwalten</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard
|
||||
title="Umsatz diesen Monat"
|
||||
value={formatter.format((revenueStats?.totalCents ?? 0) / 100)}
|
||||
description={`${revenueStats?.count ?? 0} lizenzierte Bilder im ${now.toLocaleString("de-DE", { month: "long" })}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium uppercase tracking-wide text-muted-foreground">Umsatz diesen Monat</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-4xl font-bold text-primary-600 dark:text-primary-500">
|
||||
{formatter.format((revenueStats?.totalCents ?? 0) / 100)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{revenueStats?.count ?? 0} lizenzierte Bilder im {now.toLocaleString("de-DE", { month: "long" })}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="flex flex-col justify-center items-center bg-primary-50/50 dark:bg-primary-900/10 border-primary-100 dark:border-primary-900/30">
|
||||
<CardContent className="pt-6">
|
||||
<Button asChild size="lg" className="w-full">
|
||||
<Link href="/admin/redaktionen">
|
||||
Redaktionen verwalten
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Downloads der letzten 30 Tage</CardTitle>
|
||||
<CardDescription>Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DownloadsChart data={chartData} />
|
||||
</CardContent>
|
||||
<Card title="Downloads der letzten 30 Tage" description="Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.">
|
||||
{chartData.every((day) => day.value === 0) ? (
|
||||
<EmptyState title="Keine Downloads" description="In den letzten 30 Tagen wurden keine Bilder geladen." />
|
||||
) : (
|
||||
<BarChart data={chartData} seriesLabels={["Downloads"]} size="lg" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Aktivste Redaktionen</CardTitle>
|
||||
<CardDescription>Die Top 5 Redaktionen nach Downloads.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{topEditorials.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p>
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-md border border-border">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="bg-muted/50 border-b border-border">
|
||||
<tr>
|
||||
<th className="py-3 px-4 font-semibold">Redaktion</th>
|
||||
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
|
||||
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topEditorials.map((ed, i) => (
|
||||
<tr key={ed.editorialId} className={i !== topEditorials.length - 1 ? "border-b border-border" : ""}>
|
||||
<td className="py-3 px-4">
|
||||
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="text-primary-600 dark:text-primary-400 hover:underline font-medium">
|
||||
{ed.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="py-3 px-4 text-right tabular-nums">{ed.downloadCount}</td>
|
||||
<td className="py-3 px-4 text-right tabular-nums">{formatter.format(ed.revenueCents / 100)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Aktivste Redaktionen" description="Die Top 5 Redaktionen nach Downloads.">
|
||||
{topEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "name", header: "Redaktion" },
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
]}
|
||||
rows={topEditorials.map((ed) => ({
|
||||
id: ed.editorialId,
|
||||
name: (
|
||||
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="font-medium text-[var(--color-brand-fg)] hover:underline">
|
||||
{ed.name}
|
||||
</Link>
|
||||
),
|
||||
downloads: <span className="tabular-nums">{ed.downloadCount}</span>,
|
||||
revenue: <span className="tabular-nums">{formatter.format(ed.revenueCents / 100)}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Beliebteste Alben</CardTitle>
|
||||
<CardDescription>Die Top 5 Alben nach Nutzung.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{topAlbums.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p>
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-md border border-border">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="bg-muted/50 border-b border-border">
|
||||
<tr>
|
||||
<th className="py-3 px-4 font-semibold">Album</th>
|
||||
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topAlbums.map((album, i) => (
|
||||
<tr key={album.albumName} className={i !== topAlbums.length - 1 ? "border-b border-border" : ""}>
|
||||
<td className="py-3 px-4 font-medium">{album.albumName}</td>
|
||||
<td className="py-3 px-4 text-right tabular-nums">{album.downloadCount}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
<Card title="Beliebteste Alben" description="Die Top 5 Alben nach Nutzung.">
|
||||
{topAlbums.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "albumName", header: "Album" },
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
]}
|
||||
rows={topAlbums.map((album) => ({
|
||||
albumName: album.albumName,
|
||||
downloads: <span className="tabular-nums">{album.downloadCount}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,21 @@ beforeEach(() => {
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
approveEditorial: vi.fn(),
|
||||
dbSet: vi.fn(),
|
||||
dbWhere: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
requireAdmin: vi.fn(),
|
||||
revalidatePath: vi.fn(),
|
||||
}));
|
||||
|
||||
mocks.dbSet.mockReturnValue({ where: mocks.dbWhere });
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||
vi.mock("@/db/client", () => ({
|
||||
db: { update: vi.fn(() => ({ set: mocks.dbSet })) },
|
||||
}));
|
||||
vi.mock("@/modules/editorials/service", () => ({
|
||||
editorialService: { approveEditorial: mocks.approveEditorial },
|
||||
EditorialServiceError: class EditorialServiceError extends Error {
|
||||
@@ -23,7 +30,7 @@ vi.mock("@/modules/editorials/service", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { approveEditorialAction } from "./actions";
|
||||
import { approveEditorialAction, updateFlatrateAction } from "./actions";
|
||||
|
||||
const initial = { ok: true, message: "" };
|
||||
|
||||
@@ -97,4 +104,34 @@ test("the approve action translates a service error into a German message", asyn
|
||||
ok: false,
|
||||
message: "Bitte weisen Sie zuerst mindestens ein Album zu.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("an active flatrate cannot be persisted without a positive price", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
const formData = new FormData();
|
||||
formData.set("flatrateActive", "on");
|
||||
|
||||
await expect(
|
||||
updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData),
|
||||
).rejects.toThrow("INVALID_FLATRATE_PRICE");
|
||||
expect(mocks.dbSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("an active flatrate persists a positive cents price and optional limit", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.dbWhere.mockResolvedValue(undefined);
|
||||
const formData = new FormData();
|
||||
formData.set("flatrateActive", "on");
|
||||
formData.set("flatratePriceEuros", "149,50");
|
||||
formData.set("flatrateAssetLimit", "20");
|
||||
|
||||
await updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData);
|
||||
|
||||
expect(mocks.dbSet).toHaveBeenCalledWith({
|
||||
flatrateActive: true,
|
||||
flatratePriceCents: 14_950,
|
||||
flatrateAssetLimit: 20,
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { eq } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
|
||||
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
|
||||
|
||||
// Returned to the client form so failures surface as inline German text
|
||||
@@ -55,6 +55,93 @@ export async function archiveEditorialAction(editorialId: string): Promise<void>
|
||||
redirect("/admin/redaktionen");
|
||||
}
|
||||
|
||||
export async function unarchiveEditorialAction(editorialId: string): Promise<void> {
|
||||
const admin = await requireAdmin(new Headers(await headers()));
|
||||
await editorialService.unarchiveEditorial({
|
||||
editorialId,
|
||||
adminUserId: admin.userId,
|
||||
});
|
||||
revalidatePath(`/admin/redaktionen/${editorialId}`);
|
||||
revalidatePath("/admin/redaktionen");
|
||||
}
|
||||
|
||||
export type ResetUsageResult = { ok: boolean; message: string };
|
||||
|
||||
/**
|
||||
* Step-up guard for irreversible operations (OWASP ASVS 2.5.4): the session
|
||||
* must be recent, otherwise the admin re-authenticates first.
|
||||
*/
|
||||
async function freshAdminPrincipal(): Promise<
|
||||
Awaited<ReturnType<typeof requireAdmin>> | ResetUsageResult
|
||||
> {
|
||||
try {
|
||||
return await requireAdmin(new Headers(await headers()), {
|
||||
maxSessionAgeSeconds: DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return { ok: false, message: adminGuardMessage(error.code) };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function adminGuardMessage(code: PrincipalAuthorizationError["code"]): string {
|
||||
switch (code) {
|
||||
case "SESSION_STALE":
|
||||
return "Aus Sicherheitsgründen ist Ihre Sitzung zu alt für diese Aktion. Bitte melden Sie sich erneut an und wiederholen Sie den Schritt.";
|
||||
case "TWO_FACTOR_REQUIRED":
|
||||
return "Für diese Aktion ist Zwei-Faktor-Authentifizierung erforderlich.";
|
||||
default:
|
||||
return "Die Aktion ist fehlgeschlagen.";
|
||||
}
|
||||
}
|
||||
|
||||
function isPrincipal(result: unknown): result is Awaited<ReturnType<typeof requireAdmin>> {
|
||||
return typeof result === "object" && result !== null && "userId" in result;
|
||||
}
|
||||
|
||||
export async function hardDeleteEditorialAction(editorialId: string): Promise<ResetUsageResult> {
|
||||
const safeEditorialId = requiredId(editorialId);
|
||||
const principal = await freshAdminPrincipal();
|
||||
if (!isPrincipal(principal)) {
|
||||
return principal;
|
||||
}
|
||||
|
||||
await editorialService.hardDeleteEditorial(safeEditorialId);
|
||||
revalidatePath("/admin/redaktionen");
|
||||
redirect("/admin/redaktionen");
|
||||
}
|
||||
|
||||
export async function resetUsageDataAction(editorialId: string): Promise<ResetUsageResult> {
|
||||
const safeEditorialId = requiredId(editorialId);
|
||||
const principal = await freshAdminPrincipal();
|
||||
if (!isPrincipal(principal)) {
|
||||
return principal;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await editorialService.resetUsageData({
|
||||
editorialId: safeEditorialId,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
|
||||
revalidatePath("/admin/redaktionen");
|
||||
revalidatePath("/admin");
|
||||
revalidatePath("/admin/abrechnungen");
|
||||
return {
|
||||
ok: true,
|
||||
message: `${result.deletedUsages} Nutzung(en) und ${result.deletedReports} Abrechnung(en) gelöscht.`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof EditorialServiceError && error.code === "EDITORIAL_NOT_FOUND") {
|
||||
return { ok: false, message: "Redaktion nicht gefunden." };
|
||||
}
|
||||
console.error("Failed to reset usage data:", error);
|
||||
return { ok: false, message: "Das Zurücksetzen ist fehlgeschlagen." };
|
||||
}
|
||||
}
|
||||
|
||||
export async function suspendEditorialAction(editorialId: string): Promise<void> {
|
||||
const admin = await requireAdmin(new Headers(await headers()));
|
||||
await editorialService.transitionEditorialStatus({
|
||||
@@ -91,6 +178,9 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
|
||||
flatratePriceCents = price.cents;
|
||||
}
|
||||
}
|
||||
if (flatrateActive && flatratePriceCents === null) {
|
||||
throw new Error("INVALID_FLATRATE_PRICE");
|
||||
}
|
||||
|
||||
let flatrateAssetLimit: number | null = null;
|
||||
const rawLimit = formData.get("flatrateAssetLimit");
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import Image from "next/image";
|
||||
import { Badge, Button, EmptyState, Input } from "@sakaniui/react";
|
||||
import { IconMail, IconSearch } from "@sakaniui/react/icons";
|
||||
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import type { AlbumActionResult } from "./actions";
|
||||
|
||||
@@ -22,20 +27,20 @@ type AlbumGridProps = {
|
||||
editorialId: string;
|
||||
grantAction: AlbumGridAction;
|
||||
revokeAction: AlbumGridAction;
|
||||
notifyAction: AlbumGridAction;
|
||||
};
|
||||
|
||||
function AlbumCard({
|
||||
album,
|
||||
editorialId,
|
||||
grantAction,
|
||||
revokeAction,
|
||||
}: {
|
||||
album: AlbumGridProps["albums"][0];
|
||||
type AlbumCardProps = {
|
||||
album: AlbumGridProps["albums"][number];
|
||||
editorialId: string;
|
||||
grantAction: AlbumGridAction;
|
||||
revokeAction: AlbumGridAction;
|
||||
}) {
|
||||
notifyAction: AlbumGridAction;
|
||||
};
|
||||
|
||||
function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction }: AlbumCardProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [notifyStatus, setNotifyStatus] = useState<"idle" | "pending" | "success" | "error">("idle");
|
||||
|
||||
const handleAction = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
@@ -48,55 +53,74 @@ function AlbumCard({
|
||||
});
|
||||
};
|
||||
|
||||
const notifyLabel =
|
||||
notifyStatus === "pending" ? "Wird gesendet …" :
|
||||
notifyStatus === "success" ? "E-Mail gesendet!" :
|
||||
notifyStatus === "error" ? "Fehler beim Senden" :
|
||||
"Redaktion benachrichtigen";
|
||||
|
||||
return (
|
||||
<li className={`flex flex-col bg-white border ${album.isGranted ? 'border-green-500 shadow-md ring-1 ring-green-500' : 'border-gray-200'} rounded-xl overflow-hidden transition-all duration-300 hover:shadow-lg`} data-granted={album.isGranted}>
|
||||
<div className="relative aspect-[3/2] bg-gray-100 overflow-hidden">
|
||||
{album.albumThumbnailAssetId ? (
|
||||
<Image
|
||||
className="w-full h-full object-cover transition-transform duration-500 hover:scale-105"
|
||||
alt={`Titelbild von ${album.albumName}`}
|
||||
height={200}
|
||||
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
|
||||
width={300}
|
||||
/>
|
||||
) : (
|
||||
<div aria-label="Kein Albumcover verfügbar" className="w-full h-full flex items-center justify-center text-gray-400 text-xs uppercase tracking-widest" role="img">
|
||||
Kein Cover
|
||||
</div>
|
||||
)}
|
||||
{album.isGranted && (
|
||||
<div className="absolute top-2 right-2 bg-green-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-sm">
|
||||
Zugewiesen
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4 flex flex-col flex-grow">
|
||||
<h2 className="text-base font-bold text-gray-900 mb-1 truncate" id={`album-${album.id}`} title={album.albumName}>
|
||||
{album.albumName}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p>
|
||||
<div className="mt-auto">
|
||||
<form action={handleAction}>
|
||||
<input name="immichAlbumId" type="hidden" value={album.id} />
|
||||
<button
|
||||
type="submit"
|
||||
className={`w-full py-2 px-4 rounded-lg font-semibold text-sm transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-1 ${
|
||||
album.isGranted
|
||||
? "bg-red-50 text-red-600 hover:bg-red-100 focus:ring-red-500 border border-red-200"
|
||||
: "bg-gray-900 text-white hover:bg-gray-800 focus:ring-gray-900"
|
||||
}`}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? "Wird verarbeitet..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
|
||||
</button>
|
||||
</form>
|
||||
<li data-granted={album.isGranted}>
|
||||
<Card className={`h-full ${album.isGranted ? "outline-2 outline-[var(--color-success-solid)]" : ""}`}>
|
||||
<div className="relative aspect-[3/2] overflow-hidden rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)]">
|
||||
{album.albumThumbnailAssetId ? (
|
||||
<img
|
||||
className="h-full w-full object-contain"
|
||||
alt={`Titelbild von ${album.albumName}`}
|
||||
loading="lazy"
|
||||
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
|
||||
/>
|
||||
) : (
|
||||
<div aria-label="Kein Albumcover verfügbar" className="grid h-full w-full place-items-center text-xs text-[var(--color-fg-muted)]" role="img">
|
||||
Kein Cover
|
||||
</div>
|
||||
)}
|
||||
{album.isGranted && (
|
||||
<Badge className="absolute top-2 right-2" emphasis="solid" variant="success">Zugewiesen</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 className="truncate text-base font-semibold" id={`album-${album.id}`} title={album.albumName}>
|
||||
{album.albumName}
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
|
||||
</div>
|
||||
<div className="mt-auto flex flex-col gap-2">
|
||||
<form action={handleAction} className="flex flex-col">
|
||||
<input name="immichAlbumId" type="hidden" value={album.id} />
|
||||
<Button disabled={isPending} type="submit" variant={album.isGranted ? "outline" : "primary"}>
|
||||
{isPending ? "Wird verarbeitet …" : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
|
||||
</Button>
|
||||
</form>
|
||||
{album.isGranted && (
|
||||
<form
|
||||
className="flex flex-col"
|
||||
action={(formData) => {
|
||||
setNotifyStatus("pending");
|
||||
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
|
||||
setNotifyStatus(res.ok ? "success" : "error");
|
||||
setTimeout(() => setNotifyStatus("idle"), 3000);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<input name="albumName" type="hidden" value={album.albumName} />
|
||||
<Button
|
||||
disabled={notifyStatus === "pending" || notifyStatus === "success"}
|
||||
leftIcon={<IconMail size={16} />}
|
||||
type="submit"
|
||||
variant={notifyStatus === "error" ? "destructive" : "ghost"}
|
||||
>
|
||||
{notifyLabel}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: AlbumGridProps) {
|
||||
export function AlbumGrid({ albums, editorialId, grantAction, revokeAction, notifyAction }: AlbumGridProps) {
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const filteredAlbums = albums.filter((album) =>
|
||||
@@ -104,20 +128,22 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<input
|
||||
type="search"
|
||||
className="album-grid-search"
|
||||
placeholder="Alben suchen..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
aria-label="Alben durchsuchen"
|
||||
/>
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="max-w-md">
|
||||
<Input
|
||||
aria-label="Alben durchsuchen"
|
||||
leadingIcon={<IconSearch size={16} />}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Alben suchen …"
|
||||
type="search"
|
||||
value={search}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredAlbums.length === 0 ? (
|
||||
<p>Keine Alben gefunden.</p>
|
||||
<EmptyState type="no-results" title="Keine Alben gefunden." description="Versuchen Sie einen anderen Suchbegriff." />
|
||||
) : (
|
||||
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6" aria-label="Zuweisbare Immich-Alben">
|
||||
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4" aria-label="Zuweisbare Immich-Alben">
|
||||
{filteredAlbums.map((album) => (
|
||||
<AlbumCard
|
||||
key={album.id}
|
||||
@@ -125,6 +151,7 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al
|
||||
editorialId={editorialId}
|
||||
grantAction={grantAction}
|
||||
revokeAction={revokeAction}
|
||||
notifyAction={notifyAction}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -5,6 +5,10 @@ import { headers } from "next/headers";
|
||||
|
||||
import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { emailService } from "@/modules/email/service";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
// Returned to the client form so failures surface as inline German text
|
||||
// instead of an opaque Next.js error-digest page (a thrown server action
|
||||
@@ -55,6 +59,37 @@ export async function revokeAlbumAction(
|
||||
return INITIAL_RESULT;
|
||||
}
|
||||
|
||||
export async function sendAlbumNotificationAction(
|
||||
editorialId: string,
|
||||
_prevState: AlbumActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AlbumActionResult> {
|
||||
await getAdminPrincipal();
|
||||
const safeEditorialId = requiredId(editorialId);
|
||||
const albumName = formData.get("albumName");
|
||||
|
||||
if (typeof albumName !== "string" || !albumName) {
|
||||
return { ok: false, message: "Ungültiger Albumname." };
|
||||
}
|
||||
|
||||
try {
|
||||
const [editorial] = await db
|
||||
.select({ loginEmail: editorialAccounts.loginEmail })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, safeEditorialId));
|
||||
|
||||
if (!editorial) {
|
||||
return { ok: false, message: "Redaktion nicht gefunden." };
|
||||
}
|
||||
|
||||
await emailService.sendNewAlbumNotification(editorial.loginEmail, albumName);
|
||||
return { ok: true, message: "Benachrichtigung erfolgreich gesendet." };
|
||||
} catch (error) {
|
||||
console.error("Failed to send album notification:", error);
|
||||
return { ok: false, message: "E-Mail konnte nicht gesendet werden." };
|
||||
}
|
||||
}
|
||||
|
||||
async function getAdminPrincipal() {
|
||||
return requireAdmin(new Headers(await headers()));
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, EmptyState } from "@/components/ui/sakani";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
|
||||
import { grantAlbumAction, revokeAlbumAction } from "./actions";
|
||||
import { grantAlbumAction, revokeAlbumAction, sendAlbumNotificationAction } from "./actions";
|
||||
import { loadAssignableAlbums } from "./page-content";
|
||||
import { AlbumGrid } from "./AlbumGrid";
|
||||
|
||||
@@ -26,48 +28,49 @@ export default async function EditorialAlbumsPage({
|
||||
|
||||
const albumResult = await loadAssignableAlbums(editorial.id, albumGrantService);
|
||||
|
||||
const header = (
|
||||
<PageHeader
|
||||
kicker="Redaktion · Albumrechte"
|
||||
title={`Alben für ${editorial.name}`}
|
||||
description="Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen."
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
|
||||
</Button>
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln verwalten</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</PageHeader>
|
||||
);
|
||||
|
||||
if (albumResult.unavailable) {
|
||||
return (
|
||||
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div>
|
||||
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p>
|
||||
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1>
|
||||
</div>
|
||||
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status">
|
||||
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert.
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
|
||||
</div>
|
||||
</div>
|
||||
<section className="flex flex-col gap-6">
|
||||
{header}
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div>
|
||||
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p>
|
||||
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen.
|
||||
</p>
|
||||
<div className="flex gap-4 mt-4 text-sm font-medium">
|
||||
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`} className="text-primary-600 hover:underline">Auto-Zuweisungsregeln verwalten</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="flex flex-col gap-6">
|
||||
{header}
|
||||
{albumResult.albums.length === 0 ? (
|
||||
<p className="text-muted-foreground">Derzeit sind keine zuweisbaren Alben vorhanden.</p>
|
||||
<EmptyState title="Keine zuweisbaren Alben" description="Derzeit sind keine zuweisbaren Alben vorhanden." />
|
||||
) : (
|
||||
<AlbumGrid
|
||||
albums={albumResult.albums}
|
||||
editorialId={editorial.id}
|
||||
grantAction={grantAlbumAction}
|
||||
revokeAction={revokeAlbumAction}
|
||||
notifyAction={sendAlbumNotificationAction}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import Link from "next/link";
|
||||
import { IconPlayerPlay, IconPlus, IconTrash } from "@sakaniui/react/icons";
|
||||
import { notFound } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
|
||||
import { autoRuleService } from "@/modules/albums/auto-rules";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { EmptyState, Input } from "@/components/ui/sakani";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { requireAdminPage } from "../../../access";
|
||||
import { applyAutoRulesAction, createAutoRuleAction, deleteAutoRuleAction } from "./actions";
|
||||
|
||||
type AutoRulesPageProps = Readonly<{
|
||||
@@ -13,7 +20,7 @@ type AutoRulesPageProps = Readonly<{
|
||||
}>;
|
||||
|
||||
export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
await requireAdmin(new Headers(await headers()));
|
||||
await requireAdminPage();
|
||||
const { id } = await params;
|
||||
|
||||
const [editorial] = await db
|
||||
@@ -28,45 +35,74 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
const rules = await autoRuleService.listRules(id);
|
||||
|
||||
return (
|
||||
<section className="content-section" aria-labelledby="auto-rules-title">
|
||||
<p className="eyebrow">Redaktion · Auto-Zuweisungsregeln</p>
|
||||
<h1 id="auto-rules-title">Auto-Regeln für {editorial.name}</h1>
|
||||
<p>
|
||||
Alben, deren Name eines der folgenden Schlüsselwörter enthält, werden automatisch zugewiesen.
|
||||
</p>
|
||||
<p>
|
||||
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Zurück zu Albumrechte</Link>
|
||||
</p>
|
||||
<section className="flex max-w-4xl flex-col gap-6">
|
||||
<PageHeader kicker="Redaktion · Auto-Zuweisungsregeln" title={`Auto-Regeln für ${editorial.name}`}>
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Zurück zur Album-Verwaltung</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<form action={createAutoRuleAction.bind(null, editorial.id)}>
|
||||
<label>
|
||||
<span>Neues Schlüsselwort</span>
|
||||
<input name="keyword" type="text" required placeholder="z.B. FC Bayern" />
|
||||
</label>
|
||||
<button type="submit">Regel hinzufügen</button>
|
||||
</form>
|
||||
<div className="grid gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Neue Regel hinzufügen</CardTitle>
|
||||
<CardDescription>
|
||||
Alben, deren Name eines der folgenden Schlüsselwörter enthält, werden dieser Redaktion automatisch zugewiesen, sobald sie von Immich synchronisiert werden.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex flex-col gap-4 sm:flex-row sm:items-end">
|
||||
<div className="w-full max-w-md">
|
||||
<Input label="Schlüsselwort" name="keyword" placeholder="z.B. FC Bayern" required type="text" />
|
||||
</div>
|
||||
<Button type="submit" leftIcon={<IconPlus size={16} />}>
|
||||
Regel hinzufügen
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
|
||||
<button type="submit">Regeln jetzt anwenden</button>
|
||||
</form>
|
||||
|
||||
{rules.length === 0 ? (
|
||||
<p>Noch keine Auto-Regeln angelegt.</p>
|
||||
) : (
|
||||
<ul className="auto-rules-list">
|
||||
{rules.map((rule) => (
|
||||
<li key={rule.id} className="auto-rule-item">
|
||||
<span className="auto-rule-keyword">{rule.keyword}</span>
|
||||
<span className="auto-rule-date">
|
||||
{rule.createdAt.toLocaleDateString('de-DE')}
|
||||
</span>
|
||||
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
|
||||
<button type="submit" className="auto-rule-delete">Entfernen</button>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<CardTitle>Bestehende Regeln</CardTitle>
|
||||
<CardDescription>
|
||||
Alle derzeit aktiven automatischen Zuweisungen.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
|
||||
<Button type="submit" variant="secondary" leftIcon={<IconPlayerPlay size={16} />}>
|
||||
Regeln jetzt anwenden
|
||||
</Button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{rules.length === 0 ? (
|
||||
<EmptyState title="Noch keine Auto-Regeln angelegt." description="Legen Sie oben ein Schlüsselwort an." />
|
||||
) : (
|
||||
<ul className="divide-y divide-[var(--color-border-subtle)] rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
|
||||
{rules.map((rule) => (
|
||||
<li key={rule.id} className="flex items-center justify-between p-4">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{rule.keyword}</span>
|
||||
<span className="mt-1 text-xs text-[var(--color-fg-muted)]">
|
||||
Erstellt am {new Date(rule.createdAt).toLocaleDateString('de-DE')}
|
||||
</span>
|
||||
</div>
|
||||
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
|
||||
<Button type="submit" variant="ghost" size="sm" leftIcon={<IconTrash size={16} />}>
|
||||
Entfernen
|
||||
</Button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,30 +1,47 @@
|
||||
import { desc } from "drizzle-orm";
|
||||
import { desc, inArray, sql } from "drizzle-orm";
|
||||
import Link from "next/link";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { editorialAccounts, usages } from "@/db/schema";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { IconChevronRight } from "@sakaniui/react/icons";
|
||||
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
|
||||
export default async function EditorialsPage() {
|
||||
const editorials = await db
|
||||
.select({
|
||||
id: editorialAccounts.id,
|
||||
name: editorialAccounts.name,
|
||||
contactName: editorialAccounts.contactName,
|
||||
loginEmail: editorialAccounts.loginEmail,
|
||||
status: editorialAccounts.status,
|
||||
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||
createdAt: editorialAccounts.createdAt,
|
||||
archivedAt: editorialAccounts.archivedAt,
|
||||
})
|
||||
.from(editorialAccounts)
|
||||
.orderBy(desc(editorialAccounts.createdAt));
|
||||
const [editorials, openUsageTotals] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: editorialAccounts.id,
|
||||
name: editorialAccounts.name,
|
||||
contactName: editorialAccounts.contactName,
|
||||
loginEmail: editorialAccounts.loginEmail,
|
||||
status: editorialAccounts.status,
|
||||
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||
createdAt: editorialAccounts.createdAt,
|
||||
archivedAt: editorialAccounts.archivedAt,
|
||||
})
|
||||
.from(editorialAccounts)
|
||||
.orderBy(desc(editorialAccounts.createdAt)),
|
||||
// Nicht abgerechnete Nutzungen je Redaktion — dieselben Status, die auch
|
||||
// in der Abrechnung wählbar sind (voided zählt nicht).
|
||||
db
|
||||
.select({
|
||||
editorialId: usages.editorialAccountId,
|
||||
openCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(inArray(usages.billingStatus, ["open", "reopened"]))
|
||||
.groupBy(usages.editorialAccountId),
|
||||
]);
|
||||
|
||||
const openCentsByEditorial = new Map(
|
||||
openUsageTotals.map((total) => [total.editorialId, total.openCents]),
|
||||
);
|
||||
|
||||
const activeEditorials = editorials.filter((e) => !e.archivedAt);
|
||||
const archivedEditorials = editorials.filter((e) => e.archivedAt);
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500 max-w-7xl">
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Kontoverwaltung"
|
||||
title="Redaktionen"
|
||||
@@ -32,83 +49,84 @@ export default async function EditorialsPage() {
|
||||
/>
|
||||
|
||||
{activeEditorials.length === 0 ? (
|
||||
<p className="text-muted-foreground">Noch keine aktiven Redaktionen registriert.</p>
|
||||
<EmptyState title="Noch keine aktiven Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{activeEditorials.map((editorial) => (
|
||||
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
|
||||
<Card className="h-full transition-all duration-300 hover:shadow-md hover:border-primary-500/50 hover:-translate-y-1">
|
||||
<CardContent className="p-6 flex flex-col h-full justify-between">
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
|
||||
{editorial.name}
|
||||
</h3>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">Kontakt:</span> {editorial.contactName}
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">E-Mail:</span> {editorial.loginEmail}
|
||||
</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<span className="font-medium text-foreground">Status:</span>
|
||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
|
||||
editorial.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" :
|
||||
editorial.status === "pending_approval" ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" :
|
||||
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
|
||||
}`}>
|
||||
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
|
||||
</span>
|
||||
</p>
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{activeEditorials.map((editorial) => {
|
||||
const openCents = openCentsByEditorial.get(editorial.id) ?? 0;
|
||||
return (
|
||||
<li key={editorial.id}>
|
||||
<Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
|
||||
<Card interactive className="h-full">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 className="text-base font-semibold text-[var(--color-fg-default)]">{editorial.name}</h2>
|
||||
<Badge variant={STATUS[editorial.status]?.variant ?? "danger"}>
|
||||
{STATUS[editorial.status]?.label ?? "Gesperrt"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 pt-4 border-t border-border">
|
||||
<p className="text-sm font-medium">
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm">
|
||||
<dt className="text-[var(--color-fg-muted)]">Kontakt</dt>
|
||||
<dd className="truncate">{editorial.contactName}</dd>
|
||||
<dt className="text-[var(--color-fg-muted)]">E-Mail</dt>
|
||||
<dd className="truncate">{editorial.loginEmail}</dd>
|
||||
</dl>
|
||||
<p className="mt-auto border-t border-[var(--color-border-subtle)] pt-3 text-sm font-medium">
|
||||
{editorial.currentPriceCents === null
|
||||
? "Preis noch nicht festgelegt"
|
||||
: `Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||
<span
|
||||
className={`ml-2 ${openCents > 0 ? "text-[var(--color-warning-fg)]" : "text-[var(--color-fg-muted)]"}`}
|
||||
title="Summe der noch nicht abgerechneten Bildnutzungen"
|
||||
>
|
||||
· Offen {formatCents(openCents)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{archivedEditorials.length > 0 && (
|
||||
<details className="mt-12 group">
|
||||
<summary className="cursor-pointer flex items-center gap-2 text-sm font-semibold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-colors mb-6 list-none">
|
||||
<span className="bg-muted p-1 rounded-sm group-open:rotate-90 transition-transform">
|
||||
▶
|
||||
</span>
|
||||
<details className="group mt-6">
|
||||
<summary className="mb-4 flex cursor-pointer list-none items-center gap-2 text-sm font-medium text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]">
|
||||
<IconChevronRight size={16} aria-hidden="true" className="transition-transform group-open:rotate-90" />
|
||||
Archivierte Redaktionen ({archivedEditorials.length})
|
||||
</summary>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 opacity-75 grayscale hover:grayscale-0 transition-all duration-500">
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{archivedEditorials.map((editorial) => (
|
||||
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
|
||||
<Card className="h-full transition-all duration-300 hover:shadow-sm">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-2 text-muted-foreground group-hover:text-foreground transition-colors">
|
||||
{editorial.name}
|
||||
</h3>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p>{editorial.contactName} · {editorial.loginEmail}</p>
|
||||
<p className="pt-2">
|
||||
Archiviert am: {editorial.archivedAt?.toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
<li key={editorial.id}>
|
||||
<Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
|
||||
<Card interactive className="h-full opacity-80">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h2 className="text-base font-semibold text-[var(--color-fg-muted)]">{editorial.name}</h2>
|
||||
<Badge>Archiviert</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">{editorial.contactName} · {editorial.loginEmail}</p>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Archiviert am: {editorial.archivedAt ? new Date(editorial.archivedAt).toLocaleDateString("de-DE") : ""}
|
||||
</p>
|
||||
</Card>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</div>
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const CARD_LINK =
|
||||
"block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]";
|
||||
|
||||
const STATUS: Record<string, { label: string; variant: "success" | "warning" | "danger" }> = {
|
||||
active: { label: "Aktiv", variant: "success" },
|
||||
pending_approval: { label: "Ausstehend", variant: "warning" },
|
||||
};
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { createThumbnailHandler } from "./thumbnail-handler";
|
||||
vi.mock("sharp", () => {
|
||||
return {
|
||||
default: () => ({
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
|
||||
composite: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
@@ -53,6 +54,13 @@ function createHandler(options?: {
|
||||
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
|
||||
immich: {
|
||||
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
|
||||
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({
|
||||
...grantedAlbum,
|
||||
id,
|
||||
}));
|
||||
}),
|
||||
getAsset: vi.fn().mockImplementation(async () => {
|
||||
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||
return {
|
||||
@@ -97,6 +105,7 @@ test("streams a thumbnail when the requested asset belongs to any current grant"
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
await expect(response.arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||
});
|
||||
|
||||
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
|
||||
@@ -105,7 +114,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -164,8 +173,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -5,13 +5,14 @@ import { albumGrantService } from "@/modules/albums/grants";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichBinary } from "@/modules/immich/types";
|
||||
import sharp from "sharp";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
|
||||
|
||||
type ThumbnailImmich = {
|
||||
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
|
||||
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
|
||||
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
|
||||
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
|
||||
getThumbnail(assetId: string): Promise<ImmichBinary>;
|
||||
};
|
||||
|
||||
@@ -48,9 +49,9 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
|
||||
|
||||
const thumbnail = await dependencies.immich.getThumbnail(assetId);
|
||||
if (access.kind === "editorial") {
|
||||
return watermarkedThumbnailResponse(thumbnail);
|
||||
return watermarkedThumbnailResponse(thumbnail, assetId);
|
||||
}
|
||||
return thumbnailResponse(thumbnail);
|
||||
return thumbnailResponse(thumbnail, assetId);
|
||||
} catch (err) {
|
||||
return genericNotFound();
|
||||
}
|
||||
@@ -79,15 +80,10 @@ async function isGrantedEditorialAsset(
|
||||
editorialId: string,
|
||||
assetId: string,
|
||||
): Promise<boolean> {
|
||||
const grantedAlbumIds = [...new Set(await dependencies.getGrantedAlbumIds(editorialId))];
|
||||
if (grantedAlbumIds.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const asset = await dependencies.immich.getAsset(assetId);
|
||||
const assetAlbums = asset.albums;
|
||||
const granted = new Set(grantedAlbumIds);
|
||||
return assetAlbums.some((album) => granted.has(album.id));
|
||||
const grantedAlbumIds = new Set(await dependencies.getGrantedAlbumIds(editorialId));
|
||||
if (grantedAlbumIds.size === 0) return false;
|
||||
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
|
||||
return assetAlbums.some((album) => grantedAlbumIds.has(album.id));
|
||||
}
|
||||
|
||||
async function isAdminAlbumCover(
|
||||
@@ -95,18 +91,17 @@ async function isAdminAlbumCover(
|
||||
assetId: string,
|
||||
albumId: string | null,
|
||||
): Promise<boolean> {
|
||||
if (!albumId || !isSafeAssetId(albumId)) {
|
||||
return false;
|
||||
}
|
||||
if (!albumId || !isSafeAssetId(albumId)) return false;
|
||||
const album = await immich.getAlbum(albumId);
|
||||
return album.albumThumbnailAssetId === assetId;
|
||||
}
|
||||
|
||||
function thumbnailResponse(thumbnail: ImmichBinary): Response {
|
||||
function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
|
||||
const responseHeaders = new Headers({
|
||||
"cache-control": "private, no-store",
|
||||
"content-type": thumbnail.contentType,
|
||||
"x-content-type-options": "nosniff",
|
||||
"etag": `"${assetId}"`,
|
||||
});
|
||||
if (thumbnail.contentLength !== null) {
|
||||
responseHeaders.set("content-length", String(thumbnail.contentLength));
|
||||
@@ -115,10 +110,13 @@ function thumbnailResponse(thumbnail: ImmichBinary): Response {
|
||||
}
|
||||
|
||||
function genericNotFound(): Response {
|
||||
return new Response(null, { status: 404 });
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Response> {
|
||||
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): Promise<Response> {
|
||||
const reader = thumbnail.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
@@ -128,33 +126,56 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Re
|
||||
}
|
||||
|
||||
const buffer = Buffer.concat(chunks);
|
||||
const metadata = await sharp(buffer).metadata();
|
||||
const width = metadata.width ?? 400;
|
||||
const height = metadata.height ?? 300;
|
||||
|
||||
const svgText = `
|
||||
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<text x="50%" y="50%" font-family="Arial, sans-serif" font-size="${Math.max(24, width / 8)}" font-weight="bold" fill="white" opacity="0.5" text-anchor="middle" alignment-baseline="middle" transform="rotate(-30 ${width/2} ${height/2})">
|
||||
PREVIEW
|
||||
</text>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
const watermarked = await sharp(buffer)
|
||||
.composite([
|
||||
{
|
||||
input: Buffer.from(svgText),
|
||||
gravity: "center",
|
||||
},
|
||||
])
|
||||
.webp({ quality: 80 })
|
||||
|
||||
// Skaliere das Bild auf 480px Breite (wie vom User gewünscht)
|
||||
// Skaliere das Bild so, dass es in eine 800x800 Box passt (damit Hoch- und Querformat korrekt skaliert werden)
|
||||
const targetSize = 800;
|
||||
const resizedBuffer = await sharp(buffer)
|
||||
.resize({ width: targetSize, height: targetSize, fit: "inside", withoutEnlargement: true })
|
||||
.toBuffer();
|
||||
|
||||
let watermarked = resizedBuffer;
|
||||
try {
|
||||
const logoPath = path.join(process.cwd(), "public", "brand", "logo-white.png");
|
||||
const logoBuffer = await fs.readFile(logoPath);
|
||||
|
||||
const { width, height } = await sharp(resizedBuffer).metadata();
|
||||
|
||||
// Berechne Wasserzeichen-Größe (50% der Bildbreite, max 400px)
|
||||
const logoTargetWidth = Math.min(Math.floor((width ?? targetSize) * 0.5), 400);
|
||||
|
||||
const resizedLogo = await sharp(logoBuffer)
|
||||
.resize({ width: logoTargetWidth, withoutEnlargement: true })
|
||||
.toBuffer();
|
||||
|
||||
const logoMetadata = await sharp(resizedLogo).metadata();
|
||||
const logoBase64 = resizedLogo.toString("base64");
|
||||
const logoWidth = logoMetadata.width ?? logoTargetWidth;
|
||||
const logoHeight = logoMetadata.height ?? (logoTargetWidth / 2);
|
||||
|
||||
// XLink wird für librsvg (welches von sharp genutzt wird) zwingend benötigt
|
||||
const svgOverlay = `
|
||||
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<image xlink:href="data:image/png;base64,${logoBase64}" x="${((width ?? targetSize) - logoWidth) / 2}" y="${((height ?? targetSize) - logoHeight) / 2}" width="${logoWidth}" height="${logoHeight}" opacity="0.6"/>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
watermarked = await sharp(resizedBuffer)
|
||||
.composite([{ input: Buffer.from(svgOverlay), gravity: "center" }])
|
||||
.webp({ quality: 80 })
|
||||
.toBuffer();
|
||||
} catch (err) {
|
||||
console.error("Watermark logo error:", err);
|
||||
// Fallback falls logo-white.png nicht existiert
|
||||
watermarked = await sharp(resizedBuffer).webp({ quality: 80 }).toBuffer();
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers({
|
||||
"cache-control": "private, no-store",
|
||||
"content-type": "image/webp",
|
||||
"content-length": String(watermarked.length),
|
||||
"x-content-type-options": "nosniff",
|
||||
"etag": `"${assetId}-watermark"`,
|
||||
});
|
||||
|
||||
return new Response(watermarked, { headers: responseHeaders });
|
||||
|
||||
@@ -20,7 +20,7 @@ export function createGetReportHandler(dependencies: GetHandlerDependencies) {
|
||||
const report = await dependencies.getReportPdf(reportId);
|
||||
if (!report) return notFound();
|
||||
|
||||
const filename = buildFilename(report.invoiceNumber);
|
||||
const filename = buildFilename(report.invoiceNumber, reportId);
|
||||
return new Response(new Uint8Array(report.bytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
@@ -38,7 +38,10 @@ export function createGetReportHandler(dependencies: GetHandlerDependencies) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildFilename(invoiceNumber: string): string {
|
||||
function buildFilename(invoiceNumber: string | null, reportId: string): string {
|
||||
if (!invoiceNumber) {
|
||||
return `entwurf-${reportId}.pdf`;
|
||||
}
|
||||
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
|
||||
return `${safe || "nutzungsnachweis"}.pdf`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import "server-only";
|
||||
|
||||
import type { autoRuleService } from "@/modules/albums/auto-rules";
|
||||
|
||||
const noStoreHeaders = { "cache-control": "private, no-store" } as const;
|
||||
|
||||
export type AlbumSyncHandlerDependencies = {
|
||||
applyAllRules: typeof autoRuleService.applyAllRules;
|
||||
cronSecret: string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Manual/external trigger for the album auto-rule sync (e.g. an uptime
|
||||
* monitor cron hitting this endpoint). Protected via CRON_SECRET bearer
|
||||
* token; disabled when no secret is configured.
|
||||
*/
|
||||
export function createAlbumSyncHandler({
|
||||
applyAllRules,
|
||||
cronSecret,
|
||||
}: AlbumSyncHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
if (!cronSecret) {
|
||||
return Response.json(
|
||||
{ code: "SYNC_DISABLED" },
|
||||
{ status: 404, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
|
||||
const authorization = request.headers.get("authorization");
|
||||
if (authorization !== `Bearer ${cronSecret}`) {
|
||||
return Response.json(
|
||||
{ code: "FORBIDDEN" },
|
||||
{ status: 403, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await applyAllRules();
|
||||
return Response.json(result, { headers: noStoreHeaders });
|
||||
} catch (error) {
|
||||
console.error("[album-sync] failed:", error);
|
||||
return Response.json(
|
||||
{ code: "SYNC_FAILED" },
|
||||
{ status: 503, headers: noStoreHeaders },
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createAlbumSyncHandler } from "./album-sync-handler";
|
||||
|
||||
const secret = "cron-secret-at-least-16-chars";
|
||||
|
||||
function post(handler: ReturnType<typeof createAlbumSyncHandler>, headers: Record<string, string>) {
|
||||
return handler(
|
||||
new Request("http://portal.test/api/cron/album-sync", {
|
||||
method: "POST",
|
||||
headers,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test("runs the sync and reports the granted count with a valid bearer token", async () => {
|
||||
const applyAllRules = vi.fn().mockResolvedValue({ granted: 3 });
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({ granted: 3 });
|
||||
expect(applyAllRules).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("rejects a missing or wrong bearer token without running the sync", async () => {
|
||||
const applyAllRules = vi.fn();
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const missing = await post(handler, {});
|
||||
const wrong = await post(handler, { authorization: "Bearer nope" });
|
||||
|
||||
expect(missing.status).toBe(403);
|
||||
expect(wrong.status).toBe(403);
|
||||
expect(applyAllRules).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("reports the endpoint as disabled when no cron secret is configured", async () => {
|
||||
const applyAllRules = vi.fn();
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: undefined });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(applyAllRules).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("maps sync failures to a retryable upstream error", async () => {
|
||||
const applyAllRules = vi.fn().mockRejectedValue(new Error("db down"));
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret });
|
||||
|
||||
const response = await post(handler, { authorization: `Bearer ${secret}` });
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
await expect(response.json()).resolves.toEqual({ code: "SYNC_FAILED" });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import "server-only";
|
||||
|
||||
import { autoRuleService } from "@/modules/albums/auto-rules";
|
||||
import { env } from "@/config/env";
|
||||
|
||||
import { createAlbumSyncHandler } from "./album-sync-handler";
|
||||
|
||||
export const POST = createAlbumSyncHandler({
|
||||
applyAllRules: (...args) => autoRuleService.applyAllRules(...args),
|
||||
cronSecret: env.CRON_SECRET,
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import { z } from "zod";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { downloadIntentsPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
import { createNewUsage } from "@/modules/usages/service";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
@@ -32,6 +38,7 @@ type IntentHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
createNewUsage: typeof createNewUsage;
|
||||
createRepeatDownload: typeof createRepeatDownload;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||
@@ -39,6 +46,11 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`download-intent:${principal.editorialId}`,
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = intentPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
|
||||
|
||||
@@ -85,6 +97,11 @@ async function readJson(request: Request): Promise<unknown> {
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return errorResponse(429, "RATE_LIMITED", {
|
||||
"retry-after": String(error.retryAfterSeconds),
|
||||
});
|
||||
}
|
||||
if (error instanceof CrossOriginRequestError) {
|
||||
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
|
||||
}
|
||||
@@ -115,10 +132,12 @@ function mappedError(error: unknown): Response {
|
||||
return errorResponse(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function errorResponse(status: number, code: string): Response {
|
||||
function errorResponse(status: number, code: string, extraHeaders?: HeadersInit): Response {
|
||||
const headers = new Headers(extraHeaders);
|
||||
headers.set("cache-control", "private, no-store");
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
{ status, headers },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -126,4 +145,5 @@ export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
|
||||
requireActiveEditorial,
|
||||
createNewUsage,
|
||||
createRepeatDownload,
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -30,6 +30,7 @@ function dependencies() {
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,3 +139,23 @@ test("passes one submitted idempotency key through unchanged", async () => {
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
|
||||
});
|
||||
|
||||
test("returns retry-after without creating an intent when the editorial limit is exhausted", async () => {
|
||||
const deps = dependencies();
|
||||
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 23 });
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("retry-after")).toBe("23");
|
||||
expect(deps.consumeRateLimit).toHaveBeenCalledWith(
|
||||
`download-intent:${editorialId}`,
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -26,7 +26,7 @@ export async function GET(
|
||||
const reportPdf = await getReportPdf(reportId);
|
||||
if (!reportPdf) return notFound();
|
||||
|
||||
const filename = buildFilename(reportPdf.invoiceNumber);
|
||||
const filename = buildFilename(reportPdf.invoiceNumber, reportId);
|
||||
return new Response(new Uint8Array(reportPdf.bytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
@@ -43,7 +43,10 @@ export async function GET(
|
||||
}
|
||||
}
|
||||
|
||||
function buildFilename(invoiceNumber: string): string {
|
||||
function buildFilename(invoiceNumber: string | null, reportId: string): string {
|
||||
if (!invoiceNumber) {
|
||||
return `entwurf-${reportId}.pdf`;
|
||||
}
|
||||
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
|
||||
return `${safe || "nutzungsnachweis"}.pdf`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { PassThrough, type Readable as NodeReadable } from "node:stream";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "33333333-3333-4333-8333-333333333333";
|
||||
const downloadId = "44444444-4444-4444-8444-444444444444";
|
||||
const secondAssetId = "66666666-6666-4666-8666-666666666666";
|
||||
|
||||
function fakeArchive(): BulkArchive {
|
||||
let destination: PassThrough | undefined;
|
||||
const pending: Promise<void>[] = [];
|
||||
return {
|
||||
pipe(target) {
|
||||
destination = target;
|
||||
},
|
||||
append(source: NodeReadable) {
|
||||
pending.push(
|
||||
new Promise((resolve, reject) => {
|
||||
source.on("data", (chunk) => destination?.write(chunk));
|
||||
source.once("end", resolve);
|
||||
source.once("error", reject);
|
||||
}),
|
||||
);
|
||||
},
|
||||
async finalize() {
|
||||
await Promise.all(pending);
|
||||
destination?.end();
|
||||
},
|
||||
abort() {
|
||||
destination?.destroy(new Error("aborted"));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]),
|
||||
searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }),
|
||||
getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }),
|
||||
getOriginal: vi.fn().mockResolvedValue({
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
filename: "foto.jpg",
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
}),
|
||||
listPriorUsages: vi.fn().mockResolvedValue([]),
|
||||
createNewUsage: vi.fn().mockResolvedValue({ id: downloadId }),
|
||||
createRepeatDownload: vi.fn(),
|
||||
repository: {
|
||||
claimAuthorized: vi.fn().mockResolvedValue({
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
id: downloadId,
|
||||
usageId: "55555555-5555-4555-8555-555555555555",
|
||||
assetId,
|
||||
filename: "foto.jpg",
|
||||
intentKind: "new_usage",
|
||||
},
|
||||
}),
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
},
|
||||
createArchive: vi.fn(fakeArchive),
|
||||
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
|
||||
};
|
||||
}
|
||||
|
||||
function request(origin = "http://portal.test", assetIds = [assetId]) {
|
||||
return new Request("http://portal.test/api/lightbox/bulk-download", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", host: "portal.test", origin },
|
||||
body: JSON.stringify({ assetIds, purpose: "Titelgeschichte" }),
|
||||
});
|
||||
}
|
||||
|
||||
test("rejects cross-origin archive requests before authentication or accounting", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await createBulkDownloadHandler(deps)(request("https://attacker.test"));
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(deps.requireActiveEditorial).not.toHaveBeenCalled();
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("streams a private archive and completes accounting after response consumption", async () => {
|
||||
const deps = dependencies();
|
||||
const incoming = request();
|
||||
const response = await createBulkDownloadHandler(deps)(incoming);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(deps.repository.markCompleted).not.toHaveBeenCalled();
|
||||
|
||||
await response.arrayBuffer();
|
||||
|
||||
expect(deps.getOriginal).toHaveBeenCalledWith(assetId, incoming.signal);
|
||||
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
|
||||
expect(deps.repository.failBeforeDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rate-limits bulk creation before usages are opened", async () => {
|
||||
const deps = dependencies();
|
||||
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 31 });
|
||||
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("retry-after")).toBe("31");
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("settles an already claimed first item when preparation of a later item fails", async () => {
|
||||
const deps = dependencies();
|
||||
deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] });
|
||||
deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` }));
|
||||
deps.createNewUsage
|
||||
.mockResolvedValueOnce({ id: downloadId })
|
||||
.mockRejectedValueOnce(new Error("accounting unavailable"));
|
||||
|
||||
const response = await createBulkDownloadHandler(deps)(
|
||||
request("http://portal.test", [assetId, secondAssetId]),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,343 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
createBulkDeliveryAccounting,
|
||||
streamBulkArchiveWithAccounting,
|
||||
} from "@/modules/downloads/bulk-accounting";
|
||||
import type { DownloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { downloadIntentsPolicy } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
export type BulkArchive = {
|
||||
pipe(destination: PassThrough): unknown;
|
||||
append(source: NodeReadable, options: { name: string }): unknown;
|
||||
finalize(): Promise<unknown> | unknown;
|
||||
abort(): unknown;
|
||||
};
|
||||
|
||||
type BulkDownloadHandlerDependencies = {
|
||||
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>;
|
||||
getGrantedAlbumIds(editorialId: string): Promise<string[]>;
|
||||
searchPhotos(input: {
|
||||
albumIds: string[];
|
||||
type: "IMAGE";
|
||||
page: number;
|
||||
size: number;
|
||||
withExif: false;
|
||||
}): Promise<{ items: Array<{ id: string }> }>;
|
||||
getAsset(assetId: string): Promise<{ id: string; originalFileName: string }>;
|
||||
getOriginal(
|
||||
assetId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ body: ReadableStream<Uint8Array> }>;
|
||||
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
|
||||
createNewUsage(input: {
|
||||
editorialId: string;
|
||||
assetId: string;
|
||||
albumId: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
createRepeatDownload(input: {
|
||||
editorialId: string;
|
||||
usageId: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
repository: DownloadDeliveryRepository;
|
||||
createArchive(): BulkArchive;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
type PreparedDownload = {
|
||||
assetId: string;
|
||||
downloadId: string;
|
||||
filename: string;
|
||||
};
|
||||
|
||||
export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`bulk-download:${principal.editorialId}`,
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = await parsePayload(request);
|
||||
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
|
||||
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
|
||||
const accounting = createBulkDeliveryAccounting(dependencies.repository);
|
||||
let downloads: PreparedDownload[];
|
||||
try {
|
||||
downloads = await prepareDownloads(
|
||||
dependencies,
|
||||
principal.editorialId,
|
||||
payload,
|
||||
assetToGrantedAlbum,
|
||||
async (item) => {
|
||||
const claim = await dependencies.repository.claimAuthorized(
|
||||
principal.editorialId,
|
||||
item.downloadId,
|
||||
);
|
||||
if (claim.outcome !== "claimed") {
|
||||
throw new Error("Fresh bulk-download intent could not be claimed");
|
||||
}
|
||||
accounting.track({
|
||||
downloadId: item.downloadId,
|
||||
intentKind: claim.download.intentKind,
|
||||
});
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (downloads.length === 0) return plainError(404, "No valid assets found for download");
|
||||
|
||||
const passThrough = new PassThrough();
|
||||
const archive = dependencies.createArchive();
|
||||
archive.pipe(passThrough);
|
||||
const abortArchive = () => {
|
||||
try {
|
||||
archive.abort();
|
||||
} catch {
|
||||
// The archive may already be finalized.
|
||||
}
|
||||
passThrough.destroy(new Error("Archive request aborted"));
|
||||
};
|
||||
request.signal.addEventListener("abort", abortArchive, { once: true });
|
||||
passThrough.once("close", () => request.signal.removeEventListener("abort", abortArchive));
|
||||
|
||||
void produceArchive({
|
||||
archive,
|
||||
passThrough,
|
||||
downloads,
|
||||
requestSignal: request.signal,
|
||||
getOriginal: dependencies.getOriginal,
|
||||
accounting,
|
||||
});
|
||||
|
||||
const body = streamBulkArchiveWithAccounting(
|
||||
Readable.toWeb(passThrough) as ReadableStream<Uint8Array>,
|
||||
accounting,
|
||||
);
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||
"content-type": "application/zip",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[bulk-download] failed:", error);
|
||||
return mappedBulkError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function produceArchive({
|
||||
archive,
|
||||
passThrough,
|
||||
downloads,
|
||||
requestSignal,
|
||||
getOriginal,
|
||||
accounting,
|
||||
}: {
|
||||
archive: BulkArchive;
|
||||
passThrough: PassThrough;
|
||||
downloads: PreparedDownload[];
|
||||
requestSignal: AbortSignal;
|
||||
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
|
||||
accounting: ReturnType<typeof createBulkDeliveryAccounting>;
|
||||
}) {
|
||||
try {
|
||||
for (const item of downloads) {
|
||||
if (requestSignal.aborted) throw new Error("Archive request aborted");
|
||||
const original = await getOriginal(item.assetId, requestSignal);
|
||||
const source = Readable.fromWeb(
|
||||
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
|
||||
);
|
||||
source.on("data", (chunk: Buffer) => accounting.addBytes(item.downloadId, chunk.length));
|
||||
const ended = new Promise<void>((resolve, reject) => {
|
||||
source.once("end", resolve);
|
||||
source.once("error", reject);
|
||||
});
|
||||
archive.append(source, { name: safeArchiveFilename(item.filename) });
|
||||
await ended;
|
||||
accounting.markEntryReady(item.downloadId);
|
||||
}
|
||||
await archive.finalize();
|
||||
} catch (error) {
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
try {
|
||||
archive.abort();
|
||||
} catch {
|
||||
// Ignore cleanup errors; the accounting state is already terminal.
|
||||
}
|
||||
passThrough.destroy(error instanceof Error ? error : new Error("Archive failed"));
|
||||
}
|
||||
}
|
||||
|
||||
async function grantedAssetMap(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
grantedAlbumIds: string[],
|
||||
) {
|
||||
const result = new Map<string, string>();
|
||||
const albums = await Promise.all(
|
||||
grantedAlbumIds.map(async (albumId) => {
|
||||
try {
|
||||
const page = await dependencies.searchPhotos({
|
||||
albumIds: [albumId],
|
||||
type: "IMAGE",
|
||||
page: 1,
|
||||
size: 1_000,
|
||||
withExif: false,
|
||||
});
|
||||
return { albumId, items: page.items };
|
||||
} catch {
|
||||
return { albumId, items: [] };
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const album of albums) {
|
||||
for (const asset of album.items) {
|
||||
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function prepareDownloads(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
payload: { assetIds: string[]; purpose: string },
|
||||
assetToGrantedAlbum: Map<string, string>,
|
||||
onPrepared: (item: PreparedDownload) => Promise<void>,
|
||||
) {
|
||||
const assets = await Promise.all(
|
||||
payload.assetIds.map(async (assetId) => {
|
||||
try {
|
||||
return await dependencies.getAsset(assetId);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
const downloads: PreparedDownload[] = [];
|
||||
for (const asset of assets) {
|
||||
if (!asset) continue;
|
||||
const albumId = assetToGrantedAlbum.get(asset.id);
|
||||
if (!albumId) continue;
|
||||
const prior = await dependencies.listPriorUsages(editorialId, asset.id);
|
||||
const intent = prior[0]
|
||||
? await dependencies.createRepeatDownload({
|
||||
editorialId,
|
||||
usageId: prior[0].id,
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
: await dependencies.createNewUsage({
|
||||
editorialId,
|
||||
assetId: asset.id,
|
||||
albumId,
|
||||
purpose: payload.purpose,
|
||||
reference: undefined,
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
const prepared = {
|
||||
assetId: asset.id,
|
||||
downloadId: intent.id,
|
||||
filename: asset.originalFileName,
|
||||
};
|
||||
await onPrepared(prepared);
|
||||
downloads.push(prepared);
|
||||
}
|
||||
return downloads;
|
||||
}
|
||||
|
||||
async function parsePayload(request: Request) {
|
||||
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown };
|
||||
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
if (body.assetIds.some((value) => typeof value !== "string" || !uuid.test(value))) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
if (typeof body.purpose !== "string" || body.purpose.trim().length === 0 || body.purpose.trim().length > 500) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
return { assetIds: body.assetIds as string[], purpose: body.purpose.trim() };
|
||||
}
|
||||
|
||||
class BulkInputError extends Error {}
|
||||
|
||||
function safeArchiveFilename(value: string) {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
|
||||
.trim()
|
||||
.slice(0, 180);
|
||||
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto";
|
||||
}
|
||||
|
||||
function plainError(status: number, message: string) {
|
||||
return new Response(message, {
|
||||
status,
|
||||
headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
|
||||
});
|
||||
}
|
||||
|
||||
function mappedBulkError(error: unknown): Response {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return jsonError(429, "RATE_LIMITED", {
|
||||
"retry-after": String(error.retryAfterSeconds),
|
||||
});
|
||||
}
|
||||
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||
if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT");
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof UsageAccountingError) {
|
||||
const statusByCode: Record<UsageAccountingError["code"], number> = {
|
||||
INVALID_INPUT: 400,
|
||||
IDEMPOTENCY_CONFLICT: 409,
|
||||
ALBUM_NOT_GRANTED: 404,
|
||||
ASSET_NOT_FOUND: 404,
|
||||
ASSET_NOT_IN_ALBUM: 404,
|
||||
ASSET_NOT_IMAGE: 422,
|
||||
USAGE_NOT_FOUND: 404,
|
||||
IMMICH_UNAVAILABLE: 503,
|
||||
EDITORIAL_NOT_ACTIVE: 403,
|
||||
INVALID_PRICE: 409,
|
||||
};
|
||||
return jsonError(statusByCode[error.code] ?? 500, error.code);
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string, extraHeaders?: HeadersInit) {
|
||||
const headers = new Headers(extraHeaders);
|
||||
headers.set("cache-control", "private, no-store");
|
||||
headers.set("x-content-type-options", "nosniff");
|
||||
return Response.json(
|
||||
{ code },
|
||||
{
|
||||
status,
|
||||
headers,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,144 +1,25 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { usageService } from "@/modules/usages/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
const archiver = require("archiver");
|
||||
import { Readable } from "stream";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { consumeRateLimit } from "@/modules/security/rate-limit";
|
||||
import { usageService } from "@/modules/usages/service";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const principal = await requireActiveEditorial(request.headers);
|
||||
const { assetIds, purpose } = await request.json();
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
if (!Array.isArray(assetIds) || assetIds.length === 0 || !purpose) {
|
||||
return new Response("Invalid request", { status: 400 });
|
||||
}
|
||||
const archiver = require("archiver") as { ZipArchive: new (options: unknown) => BulkArchive };
|
||||
|
||||
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
|
||||
const grantedSet = new Set(grantedAlbumIds);
|
||||
|
||||
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
|
||||
|
||||
for (const assetId of assetIds) {
|
||||
// 1. Fetch asset to find its albums
|
||||
let asset;
|
||||
try {
|
||||
asset = await immichClient.getAsset(assetId);
|
||||
} catch (err) {
|
||||
console.error("Asset fetch failed", assetId, err);
|
||||
continue; // Skip unavailable assets
|
||||
}
|
||||
|
||||
// 2. Find the first album the editorial has access to
|
||||
const validAlbum = asset.albums.find(a => grantedSet.has(a.id));
|
||||
if (!validAlbum) continue; // Editorial does not have access
|
||||
|
||||
// 3. Check for prior usages to avoid double charging
|
||||
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
|
||||
const isRepeat = priorUsages.length > 0;
|
||||
|
||||
// 4. Create new usage (or repeat download if prior usages exist)
|
||||
// Since createNewUsage handles idempotent repeats automatically, we just need to pass an idempotency key.
|
||||
const idempotencyKey = `${principal.editorialId}-${assetId}-${purpose}`;
|
||||
|
||||
const newUsage = await usageService.createNewUsage({
|
||||
editorialId: principal.editorialId,
|
||||
assetId,
|
||||
albumId: validAlbum.id,
|
||||
purpose,
|
||||
reference: undefined,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
downloadsToProcess.push({
|
||||
assetId,
|
||||
downloadId: newUsage.id,
|
||||
filename: asset.originalFileName,
|
||||
intentKind: isRepeat ? "repeat" : "new_usage",
|
||||
});
|
||||
}
|
||||
|
||||
if (downloadsToProcess.length === 0) {
|
||||
return new Response("No valid assets found for download", { status: 404 });
|
||||
}
|
||||
|
||||
// Create a streaming response with archiver
|
||||
const archive = archiver('zip', { zlib: { level: 0 } }); // No compression, images are already compressed
|
||||
|
||||
// We must return a ReadableStream to Next.js
|
||||
const transformStream = new TransformStream();
|
||||
|
||||
// Pipe archiver output to the writable side of the TransformStream
|
||||
const writableNodeStream = new WritableStreamToNodeStream(transformStream.writable);
|
||||
archive.pipe(writableNodeStream);
|
||||
|
||||
// Start appending files asynchronously
|
||||
(async () => {
|
||||
for (const download of downloadsToProcess) {
|
||||
// Claim the download to verify it's authorized
|
||||
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
|
||||
if (claim.outcome !== "claimed") continue;
|
||||
|
||||
try {
|
||||
const original = await immichClient.getOriginal(download.assetId);
|
||||
|
||||
// Track bytes read for accounting
|
||||
let transferredBytes = 0;
|
||||
const trackingTransform = new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
transferredBytes += chunk.length;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
async flush() {
|
||||
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
|
||||
}
|
||||
});
|
||||
|
||||
const trackedStream = original.body.pipeThrough(trackingTransform);
|
||||
const nodeStream = Readable.fromWeb(trackedStream as any);
|
||||
|
||||
archive.append(nodeStream, { name: download.filename });
|
||||
} catch (err) {
|
||||
console.error("Failed to append original for asset", download.assetId, err);
|
||||
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
|
||||
voidNewUsage: download.intentKind === "new_usage"
|
||||
});
|
||||
}
|
||||
}
|
||||
archive.finalize();
|
||||
})();
|
||||
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
return new Response(transformStream.readable, {
|
||||
headers: {
|
||||
"Content-Type": "application/zip",
|
||||
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||
},
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error("Bulk download failed", err);
|
||||
return new Response("Internal Server Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to convert Web WritableStream to Node Writable Stream
|
||||
import { Writable } from "stream";
|
||||
class WritableStreamToNodeStream extends Writable {
|
||||
private writer: WritableStreamDefaultWriter<any>;
|
||||
|
||||
constructor(writableStream: WritableStream) {
|
||||
super();
|
||||
this.writer = writableStream.getWriter();
|
||||
}
|
||||
|
||||
_write(chunk: any, encoding: string, callback: (error?: Error | null) => void) {
|
||||
this.writer.write(chunk).then(() => callback()).catch(callback);
|
||||
}
|
||||
|
||||
_final(callback: (error?: Error | null) => void) {
|
||||
this.writer.close().then(() => callback()).catch(callback);
|
||||
}
|
||||
}
|
||||
export const POST = createBulkDownloadHandler({
|
||||
requireActiveEditorial,
|
||||
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
|
||||
searchPhotos: (input) => immichClient.searchPhotos(input),
|
||||
getAsset: (assetId) => immichClient.getAsset(assetId),
|
||||
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
|
||||
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
|
||||
createNewUsage: (input) => usageService.createNewUsage(input),
|
||||
createRepeatDownload,
|
||||
repository: downloadDeliveryRepository,
|
||||
createArchive: () => new archiver.ZipArchive({ zlib: { level: 0 } }),
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import PortalError from "./error";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("offers retry and sign-in without exposing server details", () => {
|
||||
const reset = vi.fn();
|
||||
render(
|
||||
<PortalError
|
||||
error={Object.assign(new Error("database password leaked"), {
|
||||
digest: "private-digest",
|
||||
})}
|
||||
reset={reset}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Diese Seite konnte nicht geladen werden." }),
|
||||
).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Erneut versuchen" }));
|
||||
expect(reset).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole("link", { name: "Zur Anmeldung" }).getAttribute("href")).toBe(
|
||||
"/anmelden",
|
||||
);
|
||||
expect(document.body.textContent).not.toContain("database password leaked");
|
||||
expect(document.body.textContent).not.toContain("private-digest");
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type PortalErrorProps = {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
export default function PortalError({ reset }: Readonly<PortalErrorProps>) {
|
||||
return (
|
||||
<PublicShell
|
||||
kicker="Verbindung unterbrochen"
|
||||
title="Diese Seite konnte nicht geladen werden."
|
||||
titleId="error-title"
|
||||
lede="Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an."
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button size="lg" type="button" onClick={reset}>
|
||||
Erneut versuchen
|
||||
</Button>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user