Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8748cc1098 | ||
|
|
cba70310f9 | ||
|
|
2775b406bf | ||
|
|
4fb6f2d373 | ||
|
|
d479e1e79b | ||
|
|
71110208a9 | ||
|
|
c0c2425dda | ||
|
|
7204dd6b60 | ||
|
|
58a28e391c | ||
|
|
319e3dc101 | ||
|
|
f899417b1e | ||
|
|
e8da50c998 | ||
|
|
69264ce165 |
No files matched your search
@@ -0,0 +1,56 @@
|
||||
**
|
||||
!Dockerfile
|
||||
!package.json
|
||||
!pnpm-lock.yaml
|
||||
!pnpm-workspace.yaml
|
||||
!next.config.ts
|
||||
!next-env.d.ts
|
||||
!postcss.config.mjs
|
||||
!tsconfig.json
|
||||
!drizzle.config.ts
|
||||
!src/
|
||||
!src/**/*.ts
|
||||
!src/**/*.tsx
|
||||
!src/**/*.css
|
||||
!src/modules/pdf/fonts/*.ttf
|
||||
!src/modules/pdf/fonts/LICENSE.txt
|
||||
# The production TypeScript build only needs application sources.
|
||||
src/**/*.test.ts
|
||||
src/**/*.test.tsx
|
||||
!public/
|
||||
!public/brand/
|
||||
!public/brand/logo-black.png
|
||||
!public/brand/logo-white.png
|
||||
!drizzle/
|
||||
# Every migration must ship, or `migrate` fails on journal entries without files.
|
||||
!drizzle/*.sql
|
||||
!drizzle/meta/
|
||||
!drizzle/meta/_journal.json
|
||||
!scripts/
|
||||
!scripts/backup-db.sh
|
||||
!scripts/check-smtp.ts
|
||||
!scripts/create-admin.ts
|
||||
!scripts/preflight.ts
|
||||
**/.*
|
||||
**/.*/**
|
||||
**/*.env
|
||||
**/worktrees
|
||||
**/worktrees/**
|
||||
**/*credentials*
|
||||
**/secrets
|
||||
**/secrets.*
|
||||
**/*.pem
|
||||
**/*.key
|
||||
**/*.p12
|
||||
**/*.pfx
|
||||
**/*.sql
|
||||
!drizzle/*.sql
|
||||
**/*.dump
|
||||
**/*.backup
|
||||
**/*.bak
|
||||
**/*.tar
|
||||
**/*.gz
|
||||
**/*.zip
|
||||
**/*.sqlite*
|
||||
**/backup
|
||||
**/backups
|
||||
@@ -11,3 +11,5 @@ dist/
|
||||
coverage/
|
||||
*.tsbuildinfo
|
||||
.DS_Store
|
||||
test-results/
|
||||
playwright-report/
|
||||
@@ -0,0 +1,83 @@
|
||||
# AGENTS.md — Projektregeln für das Immich-Redaktions-Portal
|
||||
|
||||
Technisches Wissen (Immich-API-Eigenheiten, Migrationen, Deployment, Auth-Härtung)
|
||||
steht in `AI_MEMORY.md`. Diese Datei hier regelt den Arbeitsablauf.
|
||||
|
||||
## Versionierung & Versionshinweise (PFLICHT bei jeder Änderung)
|
||||
|
||||
Bei jedem neuen Feature, jeder Änderung und jedem Fix im Portal:
|
||||
|
||||
1. **Versionshinweise aktualisieren** — für Admins UND Redaktionen (Zielgruppen
|
||||
`admin`, `editorial`, `both`). Pflege im Portal unter `/admin/versionen`
|
||||
(Tabelle `release_notes`), für Deployments zusätzlich als Seed in der
|
||||
jeweiligen Drizzle-Migration (`ON CONFLICT DO NOTHING`).
|
||||
2. **Versionsnummer fortführen** — nie neu starten, nie überspringen.
|
||||
Größenordnung nach Umfang der Änderung:
|
||||
- kleiner Fix / Politur: Patch, z. B. `2.1.1`
|
||||
- neues Feature / spürbare Erweiterung: Minor, z. B. `2.2`
|
||||
- großer Umbau / breaking: Major, z. B. `3.0`
|
||||
3. **Nummer vorschlagen und absegnen lassen** — vor der Umsetzung eine konkrete
|
||||
Nummer vorschlagen; der Nutzer approved sie oder nennt eine eigene. Ohne
|
||||
Antwort keine eigenmächtige Major-/Minor-Sprünge.
|
||||
4. Hinweis-Texte kurz und konkret auf Deutsch, aus Nutzersicht formuliert
|
||||
(was ist neu, wo findet man es). Keine Marketing-Floskeln.
|
||||
|
||||
Aktueller Stand: siehe neueste Einträge in `release_notes` (Basis `2.0.0`,
|
||||
Kalender/Selbstbedienung/Sortierung/Beschreibung: `2.1.0`,
|
||||
Dateiname-Suche: `2.1.1`, Statistik/Collab/Rechnungsversand: `2.2.0`,
|
||||
Quartalsabrechnung + Sakani-Formulare: `2.2.1`, Versionshistorie: `2.2.2`,
|
||||
Kategorien/Vormerken/Monatskalender/Dashboard: `2.3.0`,
|
||||
Mehrfach-Download/Toasts/Sakani-Feinschliff: `2.4.0`, Album-Import im Kalender: `2.4.1`).
|
||||
|
||||
## Sicherheit (bei jeder Änderung mitprüfen)
|
||||
|
||||
- Album-Zugriff läuft ausschließlich über `album_grants` (Service
|
||||
`albumGrantService`). Neue Zugriffswege nur mit Audit-Event und
|
||||
Admin-Entzugsmöglichkeit; Selbstbedienung nur über Kalender-Events
|
||||
(`source: 'self_service'`), Auto-Regeln stehen über dem Kalender.
|
||||
- Niemals `asset.albums` für Berechtigungen vertrauen (siehe AI_MEMORY §2).
|
||||
- Nutzertexte (Immich-Beschreibungen, Albumnamen, Hinweise) immer als
|
||||
React-Text rendern, nie als HTML (`dangerouslySetInnerHTML` ist tabu).
|
||||
- Neue mutierende Endpoints/Actions: Session-Guard (`requireAdmin` /
|
||||
`requireActiveEditorial`) und bei Missbrauchspotenzial Rate-Limit
|
||||
(`src/modules/security/rate-limit.ts`).
|
||||
- Lösch-Actions mit Folgewirkung (z. B. Kalender-Event löschen entzieht
|
||||
Selbstzugriffe) im UI bestätigen lassen.
|
||||
|
||||
## UI & Design
|
||||
|
||||
- Vor UI-Arbeit `~/.claude/DESIGN.md` lesen; das Portal ist auf **SakaniUI**
|
||||
aufgebaut (`@sakaniui/react`). Server Components importieren Sakani über
|
||||
die Client-Grenze `src/components/ui/sakani.tsx` (Card, StatCard, Badge,
|
||||
Button, Checkbox, Input, FormSelect, DataTable, BarChart, EmptyState, …).
|
||||
Projekt-Tokens stehen in `src/app/globals.css` (alte Tailwind-Namen wie
|
||||
`bg-card`/`border-border` sind auf Sakani-Tokens gemappt). Beide Themes
|
||||
(hell/dunkel) prüfen.
|
||||
- Navigation lebt in `src/components/layout/app-shell.tsx` (AREAS), nicht in
|
||||
den Layouts. Release-Popup: `src/components/layout/release-notes.tsx`
|
||||
(RELEASE.version bei jedem Release bumpen); die pflegbare Historie liegt
|
||||
in `release_notes` und wird über `ReleaseHistory`
|
||||
(`src/modules/releases/release-history.tsx`, nach Version gruppiert)
|
||||
unter /admin/versionen und /redaktion/neuigkeiten angezeigt; das Popup
|
||||
verlinkt mit „Frühere Änderungen ansehen“ dorthin.
|
||||
- Header-Logo: `/brand/logo-black.png` / `logo-white.png` (AppShell/PublicShell).
|
||||
Originale bleiben für Wasserzeichen/E-Mail/PDF unverändert.
|
||||
|
||||
## Tests & Verifikation
|
||||
|
||||
- `pnpm typecheck`, `pnpm lint`, `pnpm test` (Vitest) vor Abschluss.
|
||||
- `tests/db/*` brauchen Docker (Testcontainers); ohne Docker laufen nur die
|
||||
Unit-Tests — das im Abschlussbericht offen benennen.
|
||||
- Migrationen: `drizzle-kit generate`, nie manuellSnapshots editieren;
|
||||
Seed-Daten idempotent anhängen. Deploy-Reihenfolge siehe AI_MEMORY §8
|
||||
(`docker compose --profile ops build`!).
|
||||
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
+41
-1
@@ -31,7 +31,8 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
- 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.
|
||||
- **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 in `src/app/globals.css` über `.brand-logo` geregelt (height-led: `height: 2.25rem; width: auto; max-width: min(12rem, 40vw)` plus `aspect-ratio` je Variante).
|
||||
- **Header-Logo-Varianten (Stand 2026-11, v2.1):** Die Originale haben riesige transparente/weiße Ränder (`logo-black.png` ist 1000×1000 mit weißem 900×900-Block, Motiv nur ~776×417). Unter der alten `width`+`max-height`-Letterboxung schrumpfte das Motiv auf ~17px und war praktisch unsichtbar. Der Header (`BrandLogo`) nutzt deshalb **beschnittene Varianten** `public/brand/logo-black-header.png` (800×441, weißer Grund) und `logo-white-header.png` (194×104, transparent). Die Originale bleiben unverändert für Wasserzeichen (`thumbnail-handler.ts`), E-Mails und PDF. Nie die Originale für den Header verwenden, nie die Header-Varianten fürs Wasserzeichen (Skalierung dort = 50% Bildbreite).
|
||||
- **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`.
|
||||
@@ -53,6 +54,7 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
|
||||
## 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`.**
|
||||
- **DOCKERIGNORE-FALLE (2026-11-30):** `.dockerignore` ist eine Whitelist. Bis v2.2.2 waren nur `0000_baseline.sql` und `0001_add_announcements.sql` freigegeben, 0002+ fehlten im Image (Gegenprobe zeigte nur 0000/0001 + meta), obwohl das Journal sie kennt. Jetzt `!drizzle/*.sql` (zweimal: nach `!drizzle/` und nach `**/*.sql`). Neue Dateiarten, die ins Image müssen, immer dort freigeben.
|
||||
- **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)
|
||||
@@ -62,3 +64,41 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
- **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").
|
||||
|
||||
## 9. Kalender, Selbstbedienung & Versionshinweise (Stand 2026-11, v2.1)
|
||||
- **Versionierung ist Projektpflicht:** `CLAUDE.md` verlangt bei JEDER Änderung aktualisierte Versionshinweise für Admins und Redaktionen plus fortlaufende Nummer (Patch/Minor/Major je Umfang). Nummer wird dem Nutzer vorgeschlagen und von ihm approved. Pflege: `/admin/versionen` (Tabelle `release_notes`, unique je Version+Zielgruppe), Anzeige für Redaktionen: `/redaktion/neuigkeiten`. Migration `0002` seedet idempotent `2.0.0` (Basis) und `2.1.0`.
|
||||
- **Kalender (`calendar_events`):** Admin legt Termine an (`/admin/kalender`, Titel + Datum + optional explizite Album-ID). Album-Verknüpfung passiert automatisch per **exaktem Namens-Match**: Album heißt `{Titel}` oder `{Titel} | {TT.MM.JJJJ}` (Datum des Termins) — siehe `matchEventAlbum` in `src/modules/calendar/event-albums.ts`. Albumnamen des Fotografen folgen genau diesem Schema. Private Alben matchen nie, solange der Admin ihren Namen nicht bewusst als Termin-Titel wählt (die Trust Boundary ist der admin-erstellte Termin).
|
||||
- **Selbstbedienung (`album_grants.source`):** Redaktionen schalten das verknüpfte Album eines Termins unter `/redaktion/kalender` frei (ab v2.3 über `reserve`, siehe §11; Rate-Limit `calendarSelfGrantPolicy`, Audit `album_self_granted`, `source: 'self_service'`). Grants ohne Kalender-Termin sind nicht self-servicebar. **Auto-Regeln stehen über dem Kalender:** `source: 'auto_rule'` und `admin`-Grants werden nie vom Kalender angetastet. Löscht der Admin einen Termin, entzieht `revokeSelfServiceGrantsForAlbum` NUR die `self_service`-Grants dieses Albums (Audit `album_revoked` mit `reason: calendar_event_deleted`).
|
||||
- **RSVP (`event_responses`):** ab v2.3 entfernt (Migration 0007), ersetzt durch Vormerkungen, siehe §11.
|
||||
- **Sichtbarkeitsfenster Redaktion:** Termine ab `heute - 30 Tage` (`CALENDAR_PAST_DAYS`), kommende aufsteigend, vergangene absteigend. Immich-Ausfall degradiert nur die Album-Verknüpfung (`immichUnavailable`), Termine/RSVP funktionieren weiter.
|
||||
- **Sortierung Fotos:** `sortierung=neueste|aelteste` (Default neueste) in Album-Suche UND Cross-Alben-Suche; `sortPhotos` in `src/modules/albums/filter.ts` sortiert das gesamte geholte Set VOR dem Paginieren (auch über gemergte Per-Album-Seiten). Pagination-Links (`pageHref`, `globalPageHref`) führen den Parameter mit, ebenso Format/Jahr.
|
||||
- **Bildbeschreibung:** Immich liefert sie in `exifInfo.description` (`withExif: true` war schon aktiv). Schema/Typ erweitert, Anzeige in der Lightbox (`PhotoLightbox` in `photo-gallery.tsx`, Klasse `.lightbox-description`, scrollbar bei >24vh). Nur React-Text, kein HTML.
|
||||
|
||||
## 10. Dateiname-Suche, Collab, Rechnungsversand & Statistiken (Stand 2026-11, v2.2)
|
||||
- **Dateiname-Suche (2.1.1):** Immich verknüpft Metadaten-Filter mit UND. Deshalb sucht `searchAlbumMerged` (`src/modules/albums/catalog.ts`) bei Query je Album zweimal (description ODER originalFileName) und merged dedupliziert. Merkzettel-Deep-Links (`?suche={dateiname}`) funktionieren damit. Gleiche Grant-Prüfung wie bisher.
|
||||
- **Collab (2.2.0):** `editorial_accounts.collab_enabled` (Admin-Toggle unter `/admin/redaktionen/[id]`, Audit `editorial_collab_updated`). Nur freigeschaltete Redaktionen sehen die Checkbox „Collab-Nutzung (kostenfrei)" im UsageDialog und im Merkzettel-Bulk-Download. `usages.collab` + `priceCents = 0`; Collab zählt NICHT gegen das Flatrate-Limit (`eq(usages.collab, false)` im Limit-Count). Fehler `COLLAB_NOT_ENABLED` → 403. Admin kann offene/wiedereröffnete Nutzungen unter Abrechnungen nachträglich markieren/entmarken (`POST /api/usages/[usageId]/collab`, Preis 0 ↔ currentPriceCents, Audit `usage_collab_updated`). Nutzungsnachweis-PDF zeigt `(Collab)` hinter dem Zweck, `billing_report_items.collab` als Snapshot.
|
||||
- **Fingerprint-Kompatibilität (WICHTIG):** `requestFingerprint` für `new_usage` DARF nicht um neue Felder (z. B. collab) erweitert werden — die historischen Migrationen 0001/0002 rekonstruieren Legacy-Fingerprints aus der alten Payload-Form. Tests in `tests/db/accounting-migration.test.ts` prüfen das.
|
||||
- **Rechnungsversand (2.2.0):** Finalisieren verschickt KEINE E-Mail mehr (Nutzungsnachweis dient der Prüfung; Korrekturen via Collab-Toggle oder Storno + Neu-Finalisierung). Admin lädt die Rechnungs-PDF unter Abrechnungen hoch (`POST /api/billing-reports/[reportId]/invoice`, multipart, %PDF-Magic, max 20 MB, Rate-Limit `invoiceUploadPolicy`). Der Upload speichert (`invoice_pdf`, `invoice_pdf_sha256`, …) und sendet automatisch GEBÜNDELT Rechnung + Nutzungsnachweis (`emailService.sendInvoiceBundle`, Vorlage `invoice-message.ts`). Status `invoice_email_status` (not_sent/sent/failed) + `invoice_email_sent_at`/`invoice_email_error`; „Erneut senden" via `POST …/invoice/resend`, Download via `GET …/invoice`. Audit: `invoice_uploaded`, `invoice_email_sent`, `invoice_email_failed`.
|
||||
- **Activity-Tracking (2.2.0):** `activity_events` (album_view/search/lightbox_view) nur für Browsing; Downloads bleiben in `download_events`. Server-Hooks in den Albumseiten, Lightbox-Beacon `POST /api/activity` (nur lightbox_view). `recordActivity` ist fire-and-forget: validiert, rate-limited (`activityPolicy` 240/60s), schluckt alle Fehler. Statistikseite `/admin/statistiken` (`src/modules/stats/queries.ts`, Zeitraum 7/30/90 Tage via `zeitraum`): KPI-Karten mit Trend-Pills (Vorperiode), Recharts Area/Bar (lazy, ssr:false, Theme-Farben), Top-Redaktionen/Alben, offene Umsätze, letzte Aktivitäten. SakaniUI-Elemente: Pill-Segmented-Control, Uppercase-Muted-Labels, Tabular-Nums, Hover-Shadow.
|
||||
- **Quartalsabrechnung (2.2.1):** Abgerechnet wird immer quartalsweise. `resolvePeriod` (`src/app/admin/abrechnungen/[editorialId]/page-content.ts`) liefert nur Quartale; alte `?month=`-Links landen im passenden Quartal, ungültige Werte im aktuellen. Die Billing-APIs akzeptieren weiter `month`, das UI sendet nur `quarter`. Mail-Betreff: `Ihre Rechnung für Q4 2026`. Seed der Versionshinweise: `drizzle/0004_release_notes_2_2_1.sql` (Custom-Migration ohne Schemaänderung).
|
||||
- **Lokale Verifikation (tmp/, gitignored):** Dev-Server `NEXT_DISABLE_TURBOPACK=1 next dev` (Port 3000), Mock-Immich :2283 (inkl. `/original`), Mock-SMTP :587 (`tmp/mock-smtp.mjs`, loggt nach `tmp/mock-smtp.log`), DB-Container `portal-clickthrough-db` :5433. BetterAuth-Sign-In-Limit 5/15min liegt IM SPEICHER des Dev-Servers — vor jedem Click-Through-Lauf Dev-Server neu starten; die Spec cached Session-Cookies nach dem ersten Login (`loginCached`). `tmp/dev-seed.ts` ist idempotent: User per E-Mail auflösen (signUp mit existierender E-Mail liefert Phantom-User ohne Persistenz!), 2FA-Setup überspringen wenn verified, Rechnungsadresse anlegen. Click-Through: `node_modules/.bin/playwright test --config tmp/playwright.config.ts` (7 Tests, Reset via beforeAll, FK-Reihenfolge beachten: items → download_events → usages → billing_reports).
|
||||
|
||||
## 11. Kategorien, Vormerken, Monatskalender, Dashboard (Stand 2026-11, v2.3)
|
||||
- **Kategorien (`event_categories`):** Name (unique über `lower(name)`) + eine von 8 Sakani-Farben (`blue|green|orange|purple|teal|gold|red|neutral`, Check-Constraint; Quelle `src/modules/calendar/colors.ts`, dort auch die CSS-Variablen, mit denen Sakani die Chips malt). Admin-Seite `/admin/kalender/kategorien`; Löschen nur ohne Termine (FK `calendar_events.category_id` RESTRICT, Service prüft vorher und mappt 23503). Audit `event_category_created/deleted`.
|
||||
- **Vormerken (`event_reservations`):** "Zu meinen Alben hinzufügen" = `calendarService.reserve`. Album schon da: sofort `grantAlbum(source: self_service)` + `granted_at`. Sonst bleibt die Vormerkung offen; `resolvePendingReservations` läuft im Auto-Regel-Scheduler-Tick (`auto-rule-scheduler.ts`, Default 120 s, erster Tick 15 s nach Start) und schaltet frei, sobald das Album matcht. Nur offene Vormerkungen sind zurücknehmbar (`unreserve`). Termin löschen löscht Vormerkungen mit. Audit `event_reserved`, `event_reservation_removed`, `album_self_granted` (beim Job `actorType: system`, `viaReservation: true`).
|
||||
- **Status je Termin (`eventAccessState`):** granted (admin/self_service) > auto_granted (Grant mit `source: auto_rule`) > auto_rule (Stichwort der Redaktion steckt im Titel oder Albumnamen, `matchesAutoRule`, gleiche Logik wie der Job) > reserved > available.
|
||||
- **Monatskalender:** `src/components/calendar/event-month.tsx` (Sakani `MonthCalendar`, `hideHeader` + eigene deutsche Kopfzeile, Wochentage per CSS `.event-month` in `globals.css`, weil Sakani nur Englisch kann; "Dec 1"-Labels am Monatsersten bleiben englisch). Klick auf Chip scrollt zum Listeneintrag `#termin-{id}` und fokussiert ihn.
|
||||
- **Bildraster:** `.photo-gallery` ist ein CSS-Grid (zeilenweise), Kacheln 3:2 `object-fit: cover`, `object-position: center 30%`; die Lightbox zeigt das ganze Bild.
|
||||
- **Dashboard (`/admin`):** `src/modules/dashboard/tasks.ts` (rein, getestet) + `queries.ts` (Aufgaben-Zähler), Rest aus `statsQueries.loadOverview(30)` und `calendarService.listAdminEvents()`.
|
||||
- **drizzle-kit generate ohne TTY:** Fragt bei "neue Tabelle + gelöschte Tabelle" interaktiv nach Umbenennung und bricht ohne Terminal ab. Lösung: in zwei Schritten generieren (erst hinzufügen, dann löschen), so entstanden 0006 und 0007.
|
||||
|
||||
## 12. Mehrfach-Download, Toasts, Sakani-Feinschliff (Stand 2026-11, v2.4)
|
||||
- **Toasts:** Ein `<AppToaster />` (Sakani `Toaster`, unten rechts) im Root-Layout. Helfer in `src/components/ui/feedback.tsx`: `notifyResult(result, fallback)` für Actions mit `{ ok, message }`, `useResultToast(state)` für `useActionState`, `ToastForm` für Server-Actions ohne Rückgabe (Speichern + `router.refresh()`). Bei Seiten, die vorher `window.location.reload()` nutzten (Abrechnungen), jetzt `router.refresh()`, sonst wäre der Toast weg.
|
||||
- **Toasts nicht in modalen Dialogen:** Native `<dialog>.showModal()` liegt im Top-Layer; ein Toast landet dahinter. Fehler in Nutzungsdialog und ZIP-Dialog bleiben deshalb als `Alert` im Dialog; Erfolg kommt als Toast nach dem Schließen.
|
||||
- **Mehrfach-Download (`DownloadLightboxForm`):** Standard ist für jedes Bild "Neue Nutzung" (gemeinsamer Zweck, optional eigener je Bild). Nur Bilder mit früheren Nutzungen bekommen einen `SegmentedControl` "Neue Nutzung / Bereits genutzt" (Voreinstellung neue Nutzung, vom Nutzer so gewählt); bei mehreren früheren Nutzungen Auswahl per `Select`, sonst die eine. "Bild auslassen" gibt es nicht mehr (Bilder werden über den Merkzettel entfernt). API-Payload unverändert.
|
||||
- **Pagination:** `UrlPagination` (`src/components/ui/url-pagination.tsx`, Sakani `Pagination`) für Album, Cross-Album-Suche und Nutzungshistorie. Die Quellen liefern nur "hat nächste Seite", daher `total = page + 1` solange es weitergeht. Cursor-basierte Auslieferungsliste bleibt bei `PageLinks`.
|
||||
- **Albenübersicht:** Blog-Listing-Optik (randloses 3:2-Cover, Anzahl, Titel, Beschreibung); Cover ist dekorativ (`alt=""`), der Titel im Link benennt es. Skeletons hinter Covern/Fotokacheln und in `loading.tsx`.
|
||||
- **Registrierung:** `RegistrationSteps` (Sakani `Stepper`, mobil vertikal). Die Bestätigungsmail führt auf `/registrieren/bestaetigt?schritt=freigabe` (Schritt 3), das Formular auf die Seite ohne Parameter (Schritt 2).
|
||||
- **Redaktionen:** `EditorialsTable` (Client, Sakani `Table` + Suche + Statusfilter; "Alle" ohne Archivierte). **Audit:** Ereignis als Auswahl der vorhandenen Typen (`selectDistinct`), deutsche Bezeichnungen (`EVENT_LABELS` in `src/app/admin/audit/page.tsx`, neue Audit-Typen dort ergänzen), Details aufklappbar.
|
||||
- **Album-Import (2.4.1):** `/admin/kalender` → "Ältere Alben übernehmen". `parseAlbumEventName` (`event-albums.ts`) liest `Titel | TT.MM.JJJJ`; `listImportableAlbums` bietet nur datierte Alben ohne passenden Termin an (private Alben ohne Datum nie), `importAlbums` rechnet die Liste serverseitig neu, legt Termine mit expliziter `immich_album_id` in einer Transaktion an (max. 500), optional mit Kategorie, Audit `calendar_events_imported`. Redaktionen sehen seitdem ALLE vergangenen Termine (kein 30-Tage-Fenster mehr); die Liste "Vergangene Termine" ist einklappbar, ein Klick im Monatskalender öffnet sie.
|
||||
|
||||
+6
-2
@@ -6,13 +6,17 @@ RUN corepack enable && corepack prepare pnpm@10.34.5 --activate
|
||||
|
||||
FROM base AS dependencies
|
||||
WORKDIR /app
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml next.config.ts next-env.d.ts tsconfig.json postcss.config.mjs drizzle.config.ts ./
|
||||
COPY src ./src
|
||||
COPY public ./public
|
||||
COPY drizzle ./drizzle
|
||||
COPY scripts ./scripts
|
||||
|
||||
# Set build-time dummy env vars required for static layout evaluation during next build
|
||||
ENV NODE_ENV=production
|
||||
|
||||
+3
-4
@@ -70,16 +70,15 @@ services:
|
||||
- portal-internal
|
||||
profiles: ["ops"]
|
||||
|
||||
# One-shot: seed the first admin. Override the command to pass credentials:
|
||||
# docker compose --profile ops run --rm seed \
|
||||
# pnpm tsx scripts/create-admin.ts admin@example.de "Password!" "Name"
|
||||
# One-shot: create a new admin. See docs/operations.md for the stdin workflow.
|
||||
seed:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: builder
|
||||
environment: *portal-env
|
||||
command: ["pnpm", "tsx", "scripts/create-admin.ts"]
|
||||
entrypoint: ["node", "--conditions=react-server", "--import", "tsx", "scripts/create-admin.ts"]
|
||||
command: []
|
||||
depends_on:
|
||||
portal-db:
|
||||
condition: service_healthy
|
||||
|
||||
+12
-3
@@ -92,11 +92,20 @@ the `ops` compose profile and do not start with `docker compose up`.
|
||||
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):
|
||||
- **Seed a new admin** after migrations. In Bash, enter a unique password of
|
||||
at least 12 characters at the hidden prompt. Compose forwards it on standard
|
||||
input. The email and display name are the two arguments.
|
||||
```bash
|
||||
docker compose --profile ops run --rm seed \
|
||||
pnpm tsx scripts/create-admin.ts admin@example.de "AdminPassword!" "Name"
|
||||
(
|
||||
set +x
|
||||
read -rs -p 'Admin password: ' seed_password || exit 1
|
||||
printf '\n' >&2
|
||||
printf '%s\n' "$seed_password" | docker compose --profile ops run --rm -i -T seed \
|
||||
admin@example.de "Portal Admin"
|
||||
)
|
||||
```
|
||||
The seed creates a verified account. An existing email or a failed insert
|
||||
exits with an error. After the first sign-in, complete the TOTP setup.
|
||||
- **Smoke-test env + connectivity** (DB, Better Auth, SMTP, Immich):
|
||||
```bash
|
||||
docker compose --profile ops run --rm preflight
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Kalender, Kategorien, Vormerken, Dashboard (v2.3.0) 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:** Kategorien mit Farben, Monatskalender mit Legende, "Zu meinen Alben hinzufügen" (Vormerken mit automatischer Freischaltung), neues Admin-Dashboard, Bildraster zeilenweise.
|
||||
|
||||
**Architecture:** Neue Tabellen `event_categories` und `event_reservations` (Drizzle-Migration, `event_responses` entfällt). Der Kalender-Service bekommt `reserve`/`unreserve`/`resolvePendingReservations` und eine reine Statusfunktion; der bestehende Auto-Regel-Scheduler ruft `resolvePendingReservations` je Tick. UI mit Sakani `MonthCalendar`, `Badge`, `Card`, `FormSelect`.
|
||||
|
||||
**Tech Stack:** Next.js 16, Drizzle/Postgres, @sakaniui/react 0.23, Vitest, Playwright (tmp/clickthrough.spec.ts).
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-11-30-kalender-kategorien-dashboard-design.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Version 2.3.0; Seeds als eigene Custom-Migration mit Zeilenumbruch nach dem Kommentar.
|
||||
- Keine Em-Dashes in neuen UI-Texten; beide Themes; Actions mit Guards; Vormerken mit `calendarSelfGrantPolicy`.
|
||||
- Farben exakt: `blue|green|orange|purple|teal|gold|red|neutral`.
|
||||
- Freischaltung nur über `grants.grantAlbum({ source: "self_service" })`.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- Vormerken, während Immich nicht erreichbar ist: Vormerkung wird gespeichert, kein Fehler; Job holt es nach.
|
||||
- Termin gelöscht mit offenen und eingelösten Vormerkungen: beide weg, self_service entzogen, Auto-Regel-Freigaben bleiben.
|
||||
- Doppelter Kategoriename mit anderer Groß-/Kleinschreibung: klare Fehlermeldung statt 500.
|
||||
- Kategorie löschen, die ein Termin nutzt: abgelehnt mit Hinweis.
|
||||
- `eventDate` am Monatsende/Zeitzone: Chip erscheint am richtigen Tag (lokales Datum, allDay).
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Schema + Migration
|
||||
**Files:** Modify `src/db/schema/calendar.ts`; generate `drizzle/0006_*.sql`; Test `tests/db/` (bestehende Migrationstests laufen mit).
|
||||
- [ ] `eventCategories` (unique index auf `lower(name)`, Check auf Farben), `calendarEvents.categoryId` (FK restrict, nullable), `eventReservations` (unique event+editorial, `grantedAt` nullable, FK event restrict), `eventResponses` entfernen.
|
||||
- [ ] `drizzle-kit generate --name calendar_categories_reservations`, gegen Test-DB migrieren, `vitest run tests/db` grün.
|
||||
|
||||
### Task 2: Kategorie-Service
|
||||
**Files:** Create `src/modules/calendar/categories.ts` (+ `.test.ts`).
|
||||
**Produces:** `CATEGORY_COLORS`, `type CategoryColor`, `categoryService.{listCategories(): Promise<EventCategory[] & {eventCount}>, createCategory({name,color,adminUserId}), deleteCategory({id,adminUserId})}`, Fehler `INVALID_NAME|INVALID_COLOR|DUPLICATE_NAME|CATEGORY_IN_USE|CATEGORY_NOT_FOUND`.
|
||||
- [ ] Tests: leerer/zu langer Name (max 80) → INVALID_NAME; Farbe "pink" → INVALID_COLOR; Duplikat (Unique-Verletzung 23505) → DUPLICATE_NAME; benutzte Kategorie → CATEGORY_IN_USE. Audit `event_category_created/deleted`.
|
||||
|
||||
### Task 3: Kalender-Service: Vormerken + Status
|
||||
**Files:** Modify `src/modules/calendar/service.ts`, `service.test.ts`, `src/modules/albums/auto-rule-scheduler.ts`.
|
||||
**Produces:** `type EventAccessState = "granted" | "auto_granted" | "auto_rule" | "reserved" | "available"`; `eventAccessState({ isGranted, grantSource, autoRuleMatch, reserved }): EventAccessState`; `EditorialCalendarEvent` mit `category`, `access`, `album`; `AdminCalendarEvent` mit `category`, `reservations: {editorialId, editorialName, grantedAt}[]`; `reserve`, `unreserve`, `resolvePendingReservations(): Promise<{granted:number}>`; `createEvent` nimmt `categoryId`.
|
||||
- [ ] Tests: reserve ohne Album → Vormerkung, kein Grant; reserve mit Album → Grant self_service + grantedAt; Immich down → Vormerkung bleibt; unreserve nur ohne grantedAt; resolve löst passende ein, überspringt andere; deleteEvent löscht Vormerkungen; Statusreihenfolge; Auto-Regel-Match über Titel/Albumname (case-insensitive).
|
||||
- [ ] Scheduler-Tick ruft nach `applyAllRules` `calendarService.resolvePendingReservations()`.
|
||||
|
||||
### Task 4: Admin: Kategorien-Seite, Termin-Formular, Kalenderansicht
|
||||
**Files:** Create `src/app/admin/kalender/kategorien/{page.tsx,CategoryForm.tsx,DeleteCategoryButton.tsx,actions.ts}`, `src/components/calendar/{event-month.tsx,category-legend.tsx}`; Modify `src/app/admin/kalender/{page.tsx,CalendarEventForm.tsx,actions.ts}`.
|
||||
- [ ] `EventMonth` (client): `MonthCalendar` mit `events` aus `{id,title,eventDate,color}` (Datum lokal, allDay), Klick → `onSelect(id)`; `CategoryLegend`: Farbpunkte + Namen.
|
||||
- [ ] Admin-Liste zeigt Kategorie-Badge, Albumstatus, Vormerkungen.
|
||||
|
||||
### Task 5: Redaktions-Kalender
|
||||
**Files:** Modify `src/app/redaktion/kalender/{page.tsx,actions.ts}`; Create `EventAccessAction.tsx`; Delete `EventRsvpButtons.tsx`, `SelfGrantButton.tsx`.
|
||||
- [ ] Monatsansicht + Legende + Detailkarte des gewählten Termins + Liste "Kommende Termine"; Aktion nach `access`.
|
||||
|
||||
### Task 6: Bildraster
|
||||
**Files:** Modify `src/app/globals.css` (`.photo-gallery`), `src/modules/albums/photo-gallery.tsx`.
|
||||
- [ ] CSS-Grid `repeat(auto-fill, minmax(17rem, 1fr))`, Kacheln 3:2 `object-fit: cover`, Reihenfolge zeilenweise; Großansicht unverändert.
|
||||
|
||||
### Task 7: Admin-Dashboard
|
||||
**Files:** Modify `src/app/admin/page.tsx`; Create `src/modules/dashboard/queries.ts` (+ test der reinen Teile).
|
||||
- [ ] Aufgaben (pending_approval, final ohne Rechnungs-PDF, Rechnungsmail failed, offener Umsatz Quartal), nächste 5 Termine, Kurzzahlen 30 Tage, letzte Aktivitäten.
|
||||
|
||||
### Task 8: Release 2.3.0 + Verifikation
|
||||
- [ ] `RELEASE.version = "2.3"`/Notes, Seed-Migration, AGENTS/AI_MEMORY, Click-Through angepasst; tsc, eslint, vitest, build, Playwright 7/7+; Commit.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Kalender mit Kategorien, Vormerken und neues Admin-Dashboard (Paket 1, v2.3.0)
|
||||
|
||||
Stand: 2026-11-30. Paket 2 (Sakani-Feinschliff: Pagination, Stepper, Blog-Listing-Albenübersicht, Toasts, Lade-Zustände, Audit, Redaktionen-Tabelle) folgt separat.
|
||||
|
||||
## Warum
|
||||
|
||||
Die meisten Redaktionen sind bei Spielen nicht vor Ort, sie wollen die Bilder. "Bin da / Bin nicht da" passt deshalb nicht. Redaktionen sollen ein Spiel vormerken können, auch bevor das Album existiert, und sehen, ob sie es über eine Auto-Regel ohnehin bekommen. Der Admin will Termine nach Sportart/Liga einordnen und den Kalender als farbige Monatsansicht sehen. Das Dashboard zeigt bisher nur Umsatz und Downloads; inzwischen gibt es Kalender, Statistiken und Rechnungsversand.
|
||||
|
||||
## Ziele
|
||||
|
||||
- Kategorien (Name + Farbe) im Admin anlegen, als Liste speichern, beim Termin auswählen.
|
||||
- Kalender als Sakani `MonthCalendar` (Redaktion und Admin), Termine in Kategoriefarbe, Legende darunter.
|
||||
- Redaktion: "Zu meinen Alben hinzufügen" (Vormerken). Album schon da: sofort freigeschaltet. Sonst automatisch, sobald es auftaucht.
|
||||
- Sichtbar, wenn eine Auto-Regel den Zugriff ohnehin gibt.
|
||||
- Admin-Dashboard mit Aufgaben, nächsten Terminen, Kurzzahlen und letzten Aktivitäten.
|
||||
|
||||
## Nicht-Ziele
|
||||
|
||||
- Termine bearbeiten oder per Drag & Drop verschieben (wie bisher: anlegen und löschen).
|
||||
- Freie Hex-Farben (Sakani-Kalender kennt 8 Farben; nur die ziehen im Dunkelmodus mit).
|
||||
- Anfrage-Workflow mit Admin-Freigabe (bewusst Variante "Vormerken" gewählt).
|
||||
- Paket-2-Themen (Toasts usw.); neue Formulare nutzen vorerst das bestehende Alert-Muster.
|
||||
|
||||
## Anti-Ziele
|
||||
|
||||
- Vormerken darf nie Zugriff auf ein Album geben, das nicht über einen vom Admin angelegten Termin verknüpft ist (gleiche Vertrauensgrenze wie die heutige Selbstbedienung).
|
||||
- Kein Verlust von Auto-Regel- oder Admin-Freigaben beim Löschen von Terminen (nur `self_service` wird entzogen, wie heute).
|
||||
|
||||
## Ansätze
|
||||
|
||||
1. **Gewählt: eigene Tabelle `event_reservations`, Freischaltung durch den bestehenden Auto-Regel-Job.** Der Job läuft ohnehin alle 120 s (`AUTO_RULE_SYNC_INTERVAL_SECONDS`) und kennt die Immich-Albenliste. Er löst offene Vormerkungen ein, sobald das Album zum Termin passt. Existiert das Album beim Vormerken schon, wird sofort freigeschaltet.
|
||||
2. Verworfen: Freischaltung erst beim nächsten Seitenaufruf der Redaktion. Kein Job nötig, aber das Album fehlt in "Meine Alben", bis die Redaktion zufällig den Kalender öffnet.
|
||||
3. Verworfen: `event_responses` umdeuten (Status `attending` = vorgemerkt). Spart eine Tabelle, aber Name und Bedeutung passen nicht mehr, und `granted_at` fehlt. Da 2.1 noch nicht deployt ist, gibt es keine echten Zusagen, die erhalten werden müssten.
|
||||
|
||||
## Datenmodell (neue Drizzle-Migration, generiert)
|
||||
|
||||
- `event_categories`: `id` uuid, `name` text (unique, case-insensitive über `lower(name)`), `color` text mit Check auf `blue|green|orange|purple|teal|gold|red|neutral`, `created_at`, `created_by_user_id`.
|
||||
- `calendar_events.category_id` uuid null, FK auf `event_categories` mit `ON DELETE RESTRICT` (Kategorie nur löschbar, wenn kein Termin sie nutzt; UI zeigt das).
|
||||
- `event_reservations`: `id`, `event_id` FK, `editorial_account_id` FK restrict, `created_at`, `granted_at` null; unique (`event_id`, `editorial_account_id`).
|
||||
- `event_responses` wird entfernt (keine Produktionsdaten, 2.1 nicht deployt).
|
||||
- Versionshinweise 2.3.0 als eigene Custom-Migration (Seed, `ON CONFLICT DO NOTHING`).
|
||||
|
||||
## Verhalten
|
||||
|
||||
**Kategorien (Admin, `/admin/kalender/kategorien`, verlinkt vom Kalender):** Liste mit Farbpunkt, Name, Anzahl Termine, Löschen (deaktiviert mit Hinweis, wenn benutzt). Formular: Name + Farbauswahl (8 Farben als Auswahl mit Farbvorschau). Audit: `event_category_created/deleted`.
|
||||
|
||||
**Termin anlegen:** zusätzliches Feld "Kategorie" (Auswahl, "Ohne Kategorie" erlaubt, dann Farbe Grau).
|
||||
|
||||
**Redaktions-Kalender (`/redaktion/kalender`):**
|
||||
- `MonthCalendar` mit Monatsnavigation, Termine als Chips in Kategoriefarbe, Legende aller Kategorien darunter.
|
||||
- Klick auf Termin: Detailkarte (Titel, Datum, Kategorie, Status, Aktion).
|
||||
- Darunter Liste "Kommende Termine" mit denselben Aktionen (auf dem Handy die Hauptansicht, weil das Monatsraster dort eng wird).
|
||||
- Aktion je Termin, in dieser Reihenfolge geprüft:
|
||||
1. Zugriff besteht: Badge "Freigeschaltet" (bzw. "Automatisch freigegeben" bei `auto_rule`) + "Album öffnen".
|
||||
2. Auto-Regel passt (ein Stichwort der Redaktion steckt im Termintitel oder im verknüpften Albumnamen, gleiche Logik wie der Job): Badge "Automatisch freigegeben (Auto-Regel)", kein Button.
|
||||
3. Vorgemerkt, noch kein Album: Badge "Vorgemerkt" + "Vormerkung entfernen".
|
||||
4. Sonst: Button "Zu meinen Alben hinzufügen".
|
||||
- Vergangene Termine (bis 30 Tage, wie heute) bleiben vormerkbar, solange das Album verknüpfbar ist.
|
||||
|
||||
**Service:**
|
||||
- `reserve(eventId, editorial)`: Rate-Limit (bestehende `calendarSelfGrantPolicy`), Reservierung anlegen (idempotent). Passt ein Album: `grantAlbum(source: self_service)`, `granted_at` setzen, Audit `album_self_granted`. Sonst Audit `event_reserved`.
|
||||
- `unreserve(eventId, editorial)`: nur offene Vormerkungen (ohne `granted_at`) löschbar. Audit `event_reservation_removed`.
|
||||
- `resolvePendingReservations()`: im Scheduler-Tick nach dem Auto-Regel-Sync. Für jede offene Vormerkung: Album matchen, freischalten, `granted_at` setzen. Fehler werden geloggt, nicht geworfen (wie der Auto-Regel-Sync).
|
||||
- `deleteEvent`: löscht Vormerkungen mit und entzieht `self_service`-Freigaben wie heute.
|
||||
|
||||
**Admin-Kalender (`/admin/kalender`):** `MonthCalendar` + Legende; Liste aller Termine mit Kategorie-Badge, Albumstatus und Vormerkungen (Anzahl + Namen, je mit Status "vorgemerkt" / "freigeschaltet") statt Zusagen.
|
||||
|
||||
**Admin-Dashboard (`/admin`):**
|
||||
1. "Zu erledigen": Redaktionen in `pending_approval`, finalisierte Abrechnungen ohne Rechnungs-PDF, Rechnungsmails mit Status `failed`, offener Umsatz im laufenden Quartal. Jede Zeile verlinkt zur passenden Seite; leere Aufgaben werden ausgeblendet, ganz leer: "Alles erledigt".
|
||||
2. "Nächste Termine": die nächsten 5 mit Kategorie, Vormerkungen und Albumstatus.
|
||||
3. Kurzzahlen 30 Tage (Downloads, Umsatz, Album-Aufrufe) mit Link zu `/admin/statistiken`, Download-Diagramm bleibt.
|
||||
4. "Letzte Aktivitäten" (aus `activity_events`, wie auf der Statistikseite, 8 Einträge).
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Alle neuen Actions mit `requireAdmin` / `requireActiveEditorial`; Vormerken mit Rate-Limit.
|
||||
- Freischaltung nur über `albumGrantService` mit `source: 'self_service'` und Audit.
|
||||
- Kategorienamen als React-Text rendern.
|
||||
|
||||
## Versionierung
|
||||
|
||||
v2.3.0 (Minor, neues Feature). Popup-Version und Notes bumpen, Seeds für admin + editorial.
|
||||
|
||||
## Tests
|
||||
|
||||
- Unit: Kategorie-Validierung, Aktions-Status-Logik (Reihenfolge oben), `reserve`/`unreserve`/`resolvePendingReservations`, Auto-Regel-Vorhersage.
|
||||
- DB-Test: Migration (Tabellen, Constraints, `event_responses` weg).
|
||||
- Click-Through: Kategorie anlegen, Termin mit Kategorie, Monatsansicht + Legende, Vormerken ohne Album (Status "Vorgemerkt"), Album erscheint (Mock-Immich), Job löst ein, "Album öffnen"; Auto-Regel-Fall; Dashboard-Aufgaben.
|
||||
|
||||
## Dem Builder überlassen
|
||||
|
||||
- Genaue Komponentenwahl für die Detailkarte (Sakani `Popover` oder Karte unter dem Kalender).
|
||||
- Datumsumrechnung `eventDate` (ISO-Tag) zu `Date` für `MonthCalendar` ohne Zeitzonenverschiebung (lokales Mitternacht-Datum, `allDay: true`).
|
||||
- Texte im Detail, solange ohne Em-Dashes und aus Nutzersicht.
|
||||
@@ -0,0 +1,45 @@
|
||||
CREATE TABLE "calendar_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"title" text NOT NULL,
|
||||
"event_date" date NOT NULL,
|
||||
"immich_album_id" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "event_responses" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"event_id" uuid NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"status" text NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "event_responses_status_check" CHECK ("event_responses"."status" in ('attending', 'not_attending'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "release_notes" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"version" text NOT NULL,
|
||||
"audience" text DEFAULT 'both' NOT NULL,
|
||||
"body" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid,
|
||||
CONSTRAINT "release_notes_audience_check" CHECK ("release_notes"."audience" in ('admin', 'editorial', 'both')),
|
||||
CONSTRAINT "release_notes_version_check" CHECK ("release_notes"."version" ~ '^[0-9]+\.[0-9]+(\.[0-9]+)?$')
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD COLUMN "source" text DEFAULT 'admin' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_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 "event_responses" ADD CONSTRAINT "event_responses_event_id_calendar_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."calendar_events"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "event_responses" ADD CONSTRAINT "event_responses_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 "release_notes" ADD CONSTRAINT "release_notes_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
|
||||
CREATE UNIQUE INDEX "event_responses_event_editorial_unique" ON "event_responses" USING btree ("event_id","editorial_account_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "release_notes_version_audience_unique" ON "release_notes" USING btree ("version","audience");--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_source_check" CHECK ("album_grants"."source" in ('admin', 'auto_rule', 'self_service'));--> statement-breakpoint
|
||||
-- Seed the version notes: 2.0.0 documents the existing portal as the baseline,
|
||||
-- 2.1.0 documents this release. Idempotent so re-runs never duplicate rows.
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.0.0', 'both', 'Basisversion des Redaktionsportals: Albumfreigaben mit automatischen Regeln, Suche über alle Alben, Merkzettel, Wasserzeichen-Vorschauen, lizenzierte Downloads mit automatischer Abrechnung, Hinweise des Fotografen und Zwei-Faktor-Schutz für Admins.', NULL),
|
||||
('2.1.0', 'editorial', 'Neu in 2.1: Fotos lassen sich in der Album-Suche und in der Suche über alle Alben nach ältesten und neuesten sortieren. Die Bildbeschreibung wird jetzt in der Großansicht angezeigt. Der neue Kalender zeigt kommende Termine, Sie können je Termin zurückmelden, ob Sie da sind. Event-Alben aus dem Kalender können Sie selbst freischalten und sofort öffnen. Das Logo im Kopfbereich ist wieder sichtbar.', NULL),
|
||||
('2.1.0', 'admin', 'Neu in 2.1: Kalender unter /admin/kalender (Termine anlegen, Alben verknüpfen, Zusagen der Redaktionen einsehen). Redaktionen schalten Kalender-Alben selbst frei, jeder Selbstzugriff wird im Audit protokolliert und lässt sich unter Alben entziehen. Versionshinweise werden unter /admin/versionen gepflegt. Sortierung und Bildbeschreibung in der Redaktionssuche, Logo im Kopfbereich korrigiert.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,35 @@
|
||||
CREATE TABLE "activity_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"event_type" text NOT NULL,
|
||||
"immich_album_id" text,
|
||||
"immich_asset_id" text,
|
||||
"query" text,
|
||||
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "activity_events_event_type_check" CHECK ("activity_events"."event_type" in ('album_view', 'search', 'lightbox_view'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "billing_report_items" ADD COLUMN "collab" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_pdf" "bytea";--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_pdf_sha256" varchar(64);--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_pdf_filename" text;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_uploaded_at" timestamp with time zone;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_email_status" text DEFAULT 'not_sent' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_email_sent_at" timestamp with time zone;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD COLUMN "invoice_email_error" text;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "collab_enabled" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "usages" ADD COLUMN "collab" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "activity_events" ADD CONSTRAINT "activity_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
|
||||
CREATE INDEX "activity_events_occurred_at_idx" ON "activity_events" USING btree ("occurred_at" DESC NULLS LAST);--> statement-breakpoint
|
||||
CREATE INDEX "activity_events_editorial_occurred_idx" ON "activity_events" USING btree ("editorial_account_id","occurred_at" DESC NULLS LAST);--> statement-breakpoint
|
||||
CREATE INDEX "activity_events_type_occurred_idx" ON "activity_events" USING btree ("event_type","occurred_at" DESC NULLS LAST);--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_invoice_pdf_sha256_hex_check" CHECK ("billing_reports"."invoice_pdf_sha256" IS NULL OR "billing_reports"."invoice_pdf_sha256" ~ '^[0-9a-f]{64}$');--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_invoice_email_status_check" CHECK ("billing_reports"."invoice_email_status" in ('not_sent', 'sent', 'failed'));
|
||||
-- Seed the version notes for this release chain. Idempotent so re-runs never
|
||||
-- duplicate rows (unique on version + audience).
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.1.1', 'editorial', 'Die Suche in Alben und über alle Alben findet jetzt auch Dateinamen. Links vom Merkzettel führen damit direkt zum richtigen Bild.', NULL),
|
||||
('2.2.0', 'admin', 'Neu in 2.2: Statistik-Seite unter /admin/statistiken mit Downloads, Datenmenge, Aufrufen, Suchen, Umsatz und Collab-Nutzungen. Collab-Nutzung je Redaktion unter Redaktionen freischalten; Collab-Positionen erscheinen mit 0,00 € in der Abrechnung und lassen sich dort vor dem Versand korrigieren. Rechnungen: PDF je Abrechnung unter Abrechnungen hochladen, danach geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per E-Mail an die Redaktion. Der Nutzungsnachweis wird beim Finalisieren nicht mehr automatisch verschickt.', NULL),
|
||||
('2.2.0', 'editorial', 'Neu in 2.2: Wenn Ihre Redaktion für Collab freigeschaltet ist, können Sie beim Download die Option Collab (kostenfrei) wählen, auch für mehrere Bilder vom Merkzettel. Rechnung und Nutzungsnachweis kommen gebündelt per E-Mail, sobald die Rechnung vorliegt.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.2.1', 'admin', 'Abrechnungen laufen jetzt immer quartalsweise: Die Abrechnungsseite öffnet direkt das aktuelle Quartal, die Monatsansicht entfällt. Das Logo in der Seitenleiste ist im dunklen Design wieder sichtbar. Die Formulare für Kalender und Versionshinweise nutzen jetzt das einheitliche Portal-Design.', NULL),
|
||||
('2.2.1', 'editorial', 'Die Rückmeldung zu Kalender-Terminen (Bin da / Bin nicht da) passt sich jetzt dem hellen und dunklen Design an, und das Logo in der Seitenleiste ist im dunklen Design wieder sichtbar.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.2.2', 'admin', 'Versionshistorie: Unter /admin/versionen sind alle Hinweise jetzt nach Version gruppiert, neueste zuerst. Das Fenster „Was ist neu?“ verlinkt direkt auf die früheren Änderungen.', NULL),
|
||||
('2.2.2', 'editorial', 'Neu: Unter Neuigkeiten steht die komplette Versionshistorie mit allen Änderungen seit Version 2.0. Das Fenster „Was ist neu?“ führt über „Frühere Änderungen ansehen“ direkt dorthin.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE "event_categories" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"color" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid,
|
||||
CONSTRAINT "event_categories_color_check" CHECK ("event_categories"."color" in ('blue', 'green', 'orange', 'purple', 'teal', 'gold', 'red', 'neutral'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "event_reservations" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"event_id" uuid NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"granted_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "calendar_events" ADD COLUMN "category_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "event_categories" ADD CONSTRAINT "event_categories_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 "event_reservations" ADD CONSTRAINT "event_reservations_event_id_calendar_events_id_fk" FOREIGN KEY ("event_id") REFERENCES "public"."calendar_events"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "event_reservations" ADD CONSTRAINT "event_reservations_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
|
||||
CREATE UNIQUE INDEX "event_categories_name_lower_unique" ON "event_categories" USING btree (lower("name"));--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "event_reservations_event_editorial_unique" ON "event_reservations" USING btree ("event_id","editorial_account_id");--> statement-breakpoint
|
||||
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_category_id_event_categories_id_fk" FOREIGN KEY ("category_id") REFERENCES "public"."event_categories"("id") ON DELETE restrict ON UPDATE no action;
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE "event_responses" CASCADE;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.3.0', 'admin', 'Neu in 2.3: Kategorien (Name und Farbe) unter Kalender, Kategorien verwalten. Der Kalender ist jetzt eine Monatsansicht mit Legende. Statt Zusagen merken Redaktionen Termine vor; das Album wird automatisch freigeschaltet, sobald es in Immich erscheint. Neues Dashboard mit offenen Aufgaben, nächsten Terminen, Kurzzahlen und letzten Aktivitäten.', NULL),
|
||||
('2.3.0', 'editorial', 'Neu in 2.3: Der Kalender ist jetzt eine Monatsansicht, farbig nach Sportart und Liga. Mit „Zu meinen Alben hinzufügen“ merken Sie ein Spiel vor; das Album wird automatisch freigeschaltet, sobald es da ist. Ob Sie ein Album über eine automatische Regel bekommen, sehen Sie direkt am Termin. Die Fotos im Album stehen jetzt in gleich großen Kacheln, zeilenweise von links nach rechts.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.4.0', 'admin', 'Neu in 2.4: Speichern und Ändern bestätigt das Portal mit einer kurzen Meldung, Fehler bei Abrechnungen sind verständlich formuliert. Redaktionen erscheinen als Tabelle mit Suche, Statusfilter und offenen Beträgen. Das Audit-Protokoll hat eine Ereignisauswahl, lesbare Bezeichnungen und aufklappbare Details. Die Registrierung zeigt den Ablauf in Schritten.', NULL),
|
||||
('2.4.0', 'editorial', 'Neu in 2.4: Beim ZIP-Download vom Merkzettel laufen alle Bilder als neue Nutzung; nur bei schon geladenen Bildern wählen Sie zwischen neuer Nutzung und kostenloser Wiederholung. Die Albenübersicht zeigt große Vorschaubilder, unter den Fotos gibt es Seitenzahlen, und Bestätigungen erscheinen als kurze Meldung unten rechts.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.4.1', 'admin', 'Ältere Alben übernehmen: Unter Kalender zeigt „Alben aus Immich anzeigen“ alle Alben im Format „Titel | TT.MM.JJJJ“, die noch keinen Termin haben. Auswählen, optional eine Kategorie setzen und übernehmen; Titel und Datum kommen aus dem Albumnamen.', NULL),
|
||||
('2.4.1', 'editorial', 'Im Kalender stehen jetzt auch ältere Spiele. Sie können sie wie neue mit „Zu meinen Alben hinzufügen“ freischalten.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
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
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
File diff suppressed because it is too large.
Load diff
@@ -15,6 +15,69 @@
|
||||
"when": 1789139950413,
|
||||
"tag": "0001_add_announcements",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1796065000672,
|
||||
"tag": "0002_release_notes_calendar",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1796067598623,
|
||||
"tag": "0003_collab_invoice_activity",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1796073940910,
|
||||
"tag": "0004_release_notes_2_2_1",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1796074977959,
|
||||
"tag": "0005_release_notes_2_2_2",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "7",
|
||||
"when": 1796077322641,
|
||||
"tag": "0006_calendar_categories_reservations",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "7",
|
||||
"when": 1796077322892,
|
||||
"tag": "0007_drop_event_responses",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "7",
|
||||
"when": 1796077763423,
|
||||
"tag": "0008_release_notes_2_3_0",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1796079496182,
|
||||
"tag": "0009_release_notes_2_4_0",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "7",
|
||||
"when": 1796081618450,
|
||||
"tag": "0010_release_notes_2_4_1",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
+2
-3
@@ -16,9 +16,8 @@ const nextConfig: NextConfig = {
|
||||
// ponytail: Next.js App Router injects inline scripts (RSC flight
|
||||
// data + bootstrap) to hydrate client components. Without
|
||||
// 'unsafe-inline' or a nonce in script-src the browser blocks them,
|
||||
// hydration never runs, and every client form (login, registration,
|
||||
// reset) falls back to a native GET submit. 'unsafe-inline' for
|
||||
// scripts is the pragmatic fix; upgrade path is per-request nonces
|
||||
// client forms cannot hydrate. 'unsafe-inline' for scripts is
|
||||
// the pragmatic fix; upgrade path is per-request nonces
|
||||
// via middleware (Next attaches the nonce to its inline scripts).
|
||||
value: [
|
||||
"default-src 'self'",
|
||||
|
||||
+8
-8
@@ -16,26 +16,26 @@
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/drizzle-adapter": "^1.6.26",
|
||||
"@better-auth/drizzle-adapter": "^1.7.29",
|
||||
"@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",
|
||||
"better-auth": "^1.7.29",
|
||||
"clsx": "^2.1.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"next": "^16.3.0",
|
||||
"next": "^16.4.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"nodemailer": "^9.0.5",
|
||||
"nodemailer": "^10.6.2",
|
||||
"pdfmake": "~0.3.11",
|
||||
"pg": "^8.22.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"server-only": "^0.0.1",
|
||||
"sharp": "^0.35.3",
|
||||
"sharp": "^0.35.6",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"zod": "^4.4.3"
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.50.0",
|
||||
@@ -53,7 +53,7 @@
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "^16.3.0",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"jsdom": "^30.0.1",
|
||||
"msw": "^2.15.0",
|
||||
"pdfjs-dist": "^6.2.108",
|
||||
@@ -61,6 +61,6 @@
|
||||
"testcontainers": "^12.1.0",
|
||||
"tsx": "^4.23.11",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.10"
|
||||
"vitest": "^4.1.12"
|
||||
}
|
||||
}
|
||||
Generated
+637
-726
File diff suppressed because it is too large.
Load diff
@@ -4,3 +4,15 @@ allowBuilds:
|
||||
protobufjs: false
|
||||
ssh2: false
|
||||
unrs-resolver: true
|
||||
|
||||
overrides:
|
||||
"@grpc/grpc-js@1.14.4": 1.14.7
|
||||
brace-expansion@1.1.18: 1.1.22
|
||||
brace-expansion@2.1.4: 2.1.8
|
||||
brace-expansion@5.0.9: 5.0.12
|
||||
"@esbuild-kit/core-utils>esbuild": 0.25.12
|
||||
js-yaml@4.3.1: 4.3.2
|
||||
"readdir-glob@3>minimatch": 11.0.9
|
||||
source-map-js@1.2.1: 1.2.2
|
||||
undici@8.10.0: 8.12.4
|
||||
vite@8.2.1: 8.2.4
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
+17
-37
@@ -1,44 +1,24 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { auth } from "../src/modules/auth/auth";
|
||||
import { db } from "../src/db/client";
|
||||
import { users } from "../src/db/schema";
|
||||
import { text } from "node:stream/consumers";
|
||||
|
||||
import { insertAdminCredential, seedAdmin } from "../src/modules/auth/admin-bootstrap";
|
||||
|
||||
async function main() {
|
||||
const email = process.argv[2] || "mail@leon-tonhaeuser.de";
|
||||
const password = process.argv[3] || "AdminPassword123!";
|
||||
const name = process.argv[4] || "Leon Tonhäuser";
|
||||
|
||||
console.log(`Creating Admin user: ${email}...`);
|
||||
|
||||
try {
|
||||
const res = await auth.api.signUpEmail({
|
||||
body: {
|
||||
email,
|
||||
name,
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
const userId = res.user.id;
|
||||
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, userId));
|
||||
|
||||
console.log(`Successfully created Admin account!`);
|
||||
console.log(`Email: ${email}`);
|
||||
console.log(`Password: ${password}`);
|
||||
} catch (error) {
|
||||
console.error("Error creating admin user:", error);
|
||||
// If user already exists, update to admin
|
||||
const [existing] = await db.select().from(users).where(eq(users.email, email));
|
||||
if (existing) {
|
||||
await db.update(users).set({ role: "ADMIN", emailVerified: true }).where(eq(users.id, existing.id));
|
||||
console.log(`Updated existing user ${email} to ADMIN role.`);
|
||||
}
|
||||
const [email, name, ...extra] = process.argv.slice(2);
|
||||
if (!email || !name || extra.length > 0 || process.stdin.isTTY) {
|
||||
throw new Error("Supply email and name as arguments and the password on stdin");
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
const password = (await text(process.stdin)).replace(/\r?\n$/, "");
|
||||
const { db, pool } = await import("../src/db/client");
|
||||
try {
|
||||
await seedAdmin({ email, name, password }, (credential) => insertAdminCredential(db, credential));
|
||||
} finally {
|
||||
await pool.end();
|
||||
}
|
||||
console.log("Admin account created.");
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
main().catch(() => {
|
||||
console.error("Admin seed failed. Check the input, database connectivity and whether the email is already registered.");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -41,6 +41,7 @@ function basePosition(priceCents = 6_000) {
|
||||
purpose: "Print Nutzung",
|
||||
reference: "REF-001" as string | null,
|
||||
priceCents,
|
||||
collab: false,
|
||||
createdAt: new Date("2026-03-15T10:00:00.000Z"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { RegistrationSteps } from "@/components/layout/registration-steps";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function RegistrationConfirmedPage() {
|
||||
// Two arrivals share this page: right after the form (e-mail still to
|
||||
// confirm) and from the confirmation link (?schritt=freigabe, see auth.ts).
|
||||
export default async function RegistrationConfirmedPage({
|
||||
searchParams,
|
||||
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
|
||||
const { schritt } = await searchParams;
|
||||
const confirmed = schritt === "freigabe";
|
||||
|
||||
return (
|
||||
<PublicShell
|
||||
kicker="Registrierung"
|
||||
title="Vielen Dank."
|
||||
title={confirmed ? "E-Mail bestätigt." : "Vielen Dank."}
|
||||
titleId="confirmation-title"
|
||||
lede="Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach prüfen wir Ihre Registrierung."
|
||||
lede={
|
||||
confirmed
|
||||
? "Wir prüfen jetzt Ihre Registrierung und melden uns per E-Mail, sobald Ihr Zugang freigeschaltet ist."
|
||||
: "Wir haben Ihnen eine E-Mail geschickt. Bitte bestätigen Sie Ihre Adresse über den Link darin. Danach prüfen wir Ihre Registrierung."
|
||||
}
|
||||
wide
|
||||
>
|
||||
<RegistrationSteps current={confirmed ? 2 : 1} />
|
||||
<div>
|
||||
<Button asChild>
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { RegistrationSteps } from "@/components/layout/registration-steps";
|
||||
import { env } from "@/config/env";
|
||||
import { registerEditorial } from "@/modules/auth/auth";
|
||||
import {
|
||||
@@ -23,6 +24,7 @@ export default function RegistrationPage() {
|
||||
lede="Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung."
|
||||
wide
|
||||
>
|
||||
<RegistrationSteps current={0} />
|
||||
<RegistrationForm
|
||||
action={registerAction}
|
||||
legalUrls={{
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
import { BillingSelection } from "./BillingSelection";
|
||||
import type { FinalizedReportSummary } from "./page-content";
|
||||
@@ -17,6 +19,7 @@ const openPosition: BillingPosition = {
|
||||
purpose: "Titelgeschichte",
|
||||
reference: "Ausgabe 8/26",
|
||||
priceCents: 6_000,
|
||||
collab: false,
|
||||
status: "open",
|
||||
selectable: true,
|
||||
createdAt: new Date("2026-08-05T10:00:00.000Z"),
|
||||
@@ -32,6 +35,7 @@ const billedPosition: BillingPosition = {
|
||||
purpose: "Sportbericht",
|
||||
reference: null,
|
||||
priceCents: 1_500,
|
||||
collab: false,
|
||||
status: "billed",
|
||||
selectable: false,
|
||||
createdAt: new Date("2026-08-06T10:00:00.000Z"),
|
||||
@@ -47,6 +51,7 @@ const reopenedPosition: BillingPosition = {
|
||||
purpose: "Reopened",
|
||||
reference: null,
|
||||
priceCents: 1_500,
|
||||
collab: false,
|
||||
status: "reopened",
|
||||
selectable: true,
|
||||
createdAt: new Date("2026-08-07T10:00:00.000Z"),
|
||||
@@ -67,10 +72,8 @@ const defaultProps = {
|
||||
editorialId: "e1",
|
||||
repeatDownloads: [] as RepeatDownloadPosition[],
|
||||
year: 2026,
|
||||
month: 8 as number | null,
|
||||
quarter: null as number | null,
|
||||
isQuarter: false,
|
||||
periodLabel: "August 2026",
|
||||
quarter: 3,
|
||||
periodLabel: "Q3 2026",
|
||||
reports: [] as FinalizedReportSummary[],
|
||||
};
|
||||
|
||||
@@ -107,7 +110,7 @@ test("disables the checkbox for billed positions and shows report reference", ()
|
||||
expect(screen.getByText(/RE-2026-042/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("selects all open positions via Alle offenen im Monat", () => {
|
||||
test("selects all open positions via Alle offenen im Quartal", () => {
|
||||
render(
|
||||
<BillingSelection
|
||||
{...defaultProps}
|
||||
@@ -115,7 +118,7 @@ test("selects all open positions via Alle offenen im Monat", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Quartal/i }));
|
||||
|
||||
expect(getCheckbox("jubel.jpg").checked).toBe(true);
|
||||
expect(getCheckbox("redaktion.jpg").checked).toBe(true);
|
||||
@@ -146,7 +149,7 @@ test("displays selected count and cents-derived EUR total", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Quartal/i }));
|
||||
|
||||
const summary = container.querySelector(".billing-summary");
|
||||
expect(summary?.textContent ?? "").toMatch(/2 Nutzungen ausgewählt/);
|
||||
@@ -177,30 +180,11 @@ test("shows empty state when no billable positions exist", () => {
|
||||
expect(screen.getByText(/Keine abrechenbaren Nutzungen/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("links to quarter view from month view", () => {
|
||||
render(
|
||||
<BillingSelection
|
||||
{...defaultProps}
|
||||
positions={[openPosition]}
|
||||
/>,
|
||||
);
|
||||
test("offers only quarterly periods", () => {
|
||||
render(<BillingSelection {...defaultProps} positions={[openPosition]} />);
|
||||
|
||||
const quarterLink = screen.getByRole("link", { name: /Ganzes Quartal/i });
|
||||
expect(quarterLink.getAttribute("href") ?? "").toContain("quarter=3");
|
||||
expect(screen.queryByRole("link", { name: /Monatsansicht/i })).toBeNull();
|
||||
expect(screen.queryByText("Monat")).toBeNull();
|
||||
expect(screen.getByText("Quartal")).toBeTruthy();
|
||||
expect(screen.getByText(/Zeitraum: Q3 2026/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("links to month view from quarter view", () => {
|
||||
render(
|
||||
<BillingSelection
|
||||
{...defaultProps}
|
||||
positions={[openPosition]}
|
||||
month={null}
|
||||
quarter={3}
|
||||
isQuarter={true}
|
||||
periodLabel="Q3 2026"
|
||||
/>,
|
||||
);
|
||||
|
||||
const monthLink = screen.getByRole("link", { name: /Monatsansicht/i });
|
||||
expect(monthLink.getAttribute("href") ?? "").toContain("month=");
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Badge, Checkbox, EmptyState, Table, Textarea, toast } from "@sakaniui/react";
|
||||
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -17,28 +17,11 @@ type BillingSelectionProps = {
|
||||
positions: BillingPosition[];
|
||||
repeatDownloads: RepeatDownloadPosition[];
|
||||
year: number;
|
||||
month: number | null;
|
||||
quarter: number | null;
|
||||
isQuarter: boolean;
|
||||
quarter: number;
|
||||
periodLabel: string;
|
||||
reports: FinalizedReportSummary[];
|
||||
};
|
||||
|
||||
const MONTHS = [
|
||||
"Januar",
|
||||
"Februar",
|
||||
"März",
|
||||
"April",
|
||||
"Mai",
|
||||
"Juni",
|
||||
"Juli",
|
||||
"August",
|
||||
"September",
|
||||
"Oktober",
|
||||
"November",
|
||||
"Dezember",
|
||||
];
|
||||
|
||||
const STATUS_LABELS: Record<BillingPosition["status"], string> = {
|
||||
open: "Offen",
|
||||
billed: "Abgerechnet",
|
||||
@@ -62,18 +45,13 @@ export function BillingSelection({
|
||||
positions,
|
||||
repeatDownloads,
|
||||
year,
|
||||
month,
|
||||
quarter,
|
||||
isQuarter,
|
||||
periodLabel,
|
||||
reports,
|
||||
}: BillingSelectionProps) {
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
const [actionState, setActionState] = useState<{
|
||||
loading: boolean;
|
||||
message: string | null;
|
||||
isError: boolean;
|
||||
}>({ loading: false, message: null, isError: false });
|
||||
const router = useRouter();
|
||||
const [actionState, setActionState] = useState({ loading: false });
|
||||
|
||||
const selectablePositions = useMemo(
|
||||
() => positions.filter((p) => p.selectable),
|
||||
@@ -107,11 +85,11 @@ export function BillingSelection({
|
||||
setSelectedIds(new Set());
|
||||
}
|
||||
|
||||
const periodPayload = { year, ...(isQuarter ? { quarter: quarter ?? 1 } : { month: month ?? 1 }) };
|
||||
const periodPayload = { year, quarter };
|
||||
|
||||
async function handlePreview() {
|
||||
if (selectedIds.size === 0) return;
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch("/api/billing-reports/preview", {
|
||||
method: "POST",
|
||||
@@ -124,25 +102,22 @@ export function BillingSelection({
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Vorschau fehlgeschlagen");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
window.open(url, "_blank");
|
||||
URL.revokeObjectURL(url);
|
||||
setActionState({ loading: false, message: null, isError: false });
|
||||
setActionState({ loading: false });
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Vorschau fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleFinalize() {
|
||||
if (selectedIds.size === 0) return;
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch("/api/billing-reports", {
|
||||
method: "POST",
|
||||
@@ -155,40 +130,48 @@ export function BillingSelection({
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Abrechnung konnte nicht erstellt werden");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
const result = await response.json();
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: `Abrechnung Nr. ${result.reportNumber} wurde erstellt.`,
|
||||
isError: false,
|
||||
});
|
||||
window.location.reload();
|
||||
setActionState({ loading: false });
|
||||
setSelectedIds(new Set());
|
||||
toast.success(`Abrechnung Nr. ${result.reportNumber} wurde erstellt.`);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Abrechnung fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleCollab(position: BillingPosition) {
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ collab: !position.collab }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
setActionState({ loading: false });
|
||||
toast.success(position.collab ? "Collab-Kennzeichnung entfernt." : "Als Collab-Nutzung markiert.");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
|
||||
const quarterHref = quarter
|
||||
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
|
||||
: `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarterParam}`;
|
||||
const monthHref = `/admin/abrechnungen/${editorialId}?year=${year}&month=${month ?? (quarter ? (quarter - 1) * 3 + 1 : new Date().getUTCMonth() + 1)}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
|
||||
<PeriodSelector year={year} quarter={quarter} />
|
||||
|
||||
<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>
|
||||
<Button asChild variant="outline">
|
||||
{isQuarter ? <Link href={monthHref}>Monatsansicht</Link> : <Link href={quarterHref}>Ganzes Quartal</Link>}
|
||||
Alle offenen im Quartal
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={clearSelection} disabled={selectedCount === 0}>
|
||||
Auswahl aufheben
|
||||
@@ -201,7 +184,7 @@ export function BillingSelection({
|
||||
<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." />
|
||||
<EmptyState title="Keine abrechenbaren Nutzungen in diesem Zeitraum." description="Wählen Sie oben ein anderes Quartal." />
|
||||
) : (
|
||||
<Table<BillingPosition>
|
||||
rowKey={(position) => position.id}
|
||||
@@ -227,7 +210,25 @@ export function BillingSelection({
|
||||
key: "priceCents",
|
||||
header: "Preis",
|
||||
align: "right",
|
||||
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
|
||||
render: (position) => (
|
||||
<span className="flex flex-col items-end gap-1">
|
||||
<span className="flex items-center gap-2 tabular-nums">
|
||||
{formatCents(position.priceCents)}
|
||||
{position.collab && <Badge variant="neutral">Collab</Badge>}
|
||||
</span>
|
||||
{position.selectable && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleToggleCollab(position)}
|
||||
disabled={actionState.loading}
|
||||
>
|
||||
{position.collab ? "Collab entfernen" : "Als Collab markieren"}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
@@ -296,11 +297,6 @@ export function BillingSelection({
|
||||
</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 && (
|
||||
@@ -330,11 +326,47 @@ export function BillingSelection({
|
||||
<Button asChild variant="outline">
|
||||
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
|
||||
<IconDownload size={16} aria-hidden="true" />
|
||||
PDF herunterladen
|
||||
Nutzungsnachweis herunterladen
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{report.status === "final" && (
|
||||
<div className="flex flex-col gap-3 rounded-[var(--radius-lg)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-subtle)] p-4">
|
||||
<p className="text-sm font-medium">
|
||||
Rechnung:{" "}
|
||||
{report.invoiceEmailStatus === "sent" ? (
|
||||
<>
|
||||
versendet am{" "}
|
||||
<time
|
||||
dateTime={report.invoiceEmailSentAt?.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{report.invoiceEmailSentAt?.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</>
|
||||
) : report.hasInvoicePdf ? (
|
||||
"PDF hinterlegt, Versand fehlgeschlagen"
|
||||
) : (
|
||||
"noch keine PDF hinterlegt"
|
||||
)}
|
||||
</p>
|
||||
<InvoiceUploadForm
|
||||
reportId={report.id}
|
||||
reportNumber={report.reportNumber}
|
||||
hasInvoice={report.hasInvoicePdf}
|
||||
emailFailed={report.hasInvoicePdf && report.invoiceEmailStatus === "failed"}
|
||||
/>
|
||||
{report.hasInvoicePdf && (
|
||||
<Button asChild variant="outline">
|
||||
<a href={`/api/billing-reports/${encodeURIComponent(report.id)}/invoice`} download>
|
||||
<IconDownload size={16} aria-hidden="true" />
|
||||
Rechnungs-PDF herunterladen
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{report.status === "final" && (
|
||||
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
|
||||
)}
|
||||
@@ -350,12 +382,10 @@ export function BillingSelection({
|
||||
|
||||
type PeriodSelectorProps = {
|
||||
year: number;
|
||||
month: number | null;
|
||||
quarter: number | null;
|
||||
isQuarter: boolean;
|
||||
quarter: number;
|
||||
};
|
||||
|
||||
function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps) {
|
||||
function PeriodSelector({ year, quarter }: PeriodSelectorProps) {
|
||||
const years = [2025, 2026, 2027];
|
||||
|
||||
return (
|
||||
@@ -364,41 +394,134 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
|
||||
<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>
|
||||
)}
|
||||
<div className="w-32">
|
||||
<FormSelect
|
||||
name="quarter"
|
||||
label="Quartal"
|
||||
defaultValue={String(quarter)}
|
||||
options={[1, 2, 3, 4].map((q) => ({ label: `Q${q}`, value: String(q) }))}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" variant="secondary">Zeitraum laden</Button>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type InvoiceUploadFormProps = {
|
||||
reportId: string;
|
||||
reportNumber: number;
|
||||
hasInvoice: boolean;
|
||||
emailFailed: boolean;
|
||||
};
|
||||
|
||||
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
|
||||
const router = useRouter();
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleUpload(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!file || loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.set("invoice", file);
|
||||
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/invoice`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
toast.success(`Rechnung zu Bericht Nr. ${reportNumber} hochgeladen. Der Versand an die Redaktion läuft.`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : invoiceErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
async function handleResend() {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
toast.success("Rechnung erneut versendet.");
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : invoiceErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-3" onSubmit={handleUpload}>
|
||||
<label className="flex flex-col gap-1 text-sm font-medium">
|
||||
<span>
|
||||
{hasInvoice ? "Rechnungs-PDF ersetzen" : "Rechnungs-PDF hochladen"} (Bericht Nr. {reportNumber})
|
||||
</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
required
|
||||
disabled={loading}
|
||||
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
|
||||
aria-label={`Rechnungs-PDF für Bericht Nr. ${reportNumber}`}
|
||||
className="text-sm text-[var(--color-fg-muted)] file:mr-3 file:rounded-[var(--radius-md)] file:border file:border-[var(--color-border-subtle)] file:bg-[var(--color-bg-surface)] file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-[var(--color-fg-default)]"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" disabled={!file || loading}>
|
||||
{loading ? "Wird gesendet…" : "Hochladen & senden"}
|
||||
</Button>
|
||||
{hasInvoice && (
|
||||
<Button type="button" variant="outline" onClick={handleResend} disabled={loading}>
|
||||
{emailFailed ? "Erneut senden" : "Nochmal senden"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
Nach dem Upload geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per
|
||||
E-Mail an die Redaktion.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function invoiceErrorMessage(code: unknown): string {
|
||||
switch (code) {
|
||||
case "INVALID_PDF":
|
||||
return "Die Datei ist keine gültige PDF (max. 20 MB).";
|
||||
case "REPORT_NOT_FINAL":
|
||||
return "Der Bericht ist nicht finalisiert.";
|
||||
case "INVOICE_NOT_UPLOADED":
|
||||
return "Es ist noch keine Rechnungs-PDF hinterlegt.";
|
||||
case "RATE_LIMITED":
|
||||
return "Zu viele Versuche. Bitte kurz warten.";
|
||||
default:
|
||||
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
|
||||
}
|
||||
}
|
||||
|
||||
type CancelReportFormProps = {
|
||||
reportId: string;
|
||||
reportNumber: number;
|
||||
};
|
||||
|
||||
function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
const router = useRouter();
|
||||
const [reason, setReason] = useState("");
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const trimmed = reason.trim();
|
||||
const valid = trimmed.length >= 5 && trimmed.length <= 500 && confirmed;
|
||||
@@ -407,7 +530,6 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
event.preventDefault();
|
||||
if (!valid) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/cancel`, {
|
||||
method: "POST",
|
||||
@@ -416,13 +538,14 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Stornierung fehlgeschlagen");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
toast.success(`Bericht Nr. ${reportNumber} storniert. Die Nutzungen sind wieder offen.`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Stornierung fehlgeschlagen");
|
||||
setLoading(false);
|
||||
toast.error(err instanceof Error ? err.message : billingErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -447,7 +570,30 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
{loading ? "Wird storniert …" : "Stornieren"}
|
||||
</Button>
|
||||
</div>
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function billingErrorMessage(code: unknown): string {
|
||||
switch (code) {
|
||||
case "NO_USAGES_SELECTED":
|
||||
return "Bitte mindestens eine offene Nutzung auswählen.";
|
||||
case "USAGE_NOT_ELIGIBLE":
|
||||
case "USAGE_NOT_FOUND":
|
||||
return "Eine der gewählten Nutzungen ist nicht mehr abrechenbar. Bitte die Seite neu laden.";
|
||||
case "ADDRESS_NOT_FOUND":
|
||||
return "Für diese Redaktion fehlt die Rechnungsadresse.";
|
||||
case "EDITORIAL_NOT_FOUND":
|
||||
return "Diese Redaktion existiert nicht mehr.";
|
||||
case "REPORT_NOT_FOUND":
|
||||
return "Dieser Bericht existiert nicht mehr.";
|
||||
case "INVALID_CANCELLATION_REASON":
|
||||
return "Bitte einen Stornierungsgrund mit 5 bis 500 Zeichen angeben.";
|
||||
case "REPORT_NUMBER_COLLISION":
|
||||
return "Die Berichtsnummer war gerade vergeben. Bitte erneut versuchen.";
|
||||
case "RATE_LIMITED":
|
||||
return "Zu viele Versuche. Bitte kurz warten.";
|
||||
default:
|
||||
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { resolvePeriod } from "./page-content";
|
||||
|
||||
test("resolvePeriod is always quarterly", () => {
|
||||
expect(resolvePeriod({ year: "2026", quarter: "4" })).toMatchObject({ year: 2026, quarter: 4, periodLabel: "Q4 2026" });
|
||||
// Old month links land in their quarter.
|
||||
expect(resolvePeriod({ year: "2026", month: "8" })).toMatchObject({ quarter: 3, periodLabel: "Q3 2026" });
|
||||
// Invalid quarters fall back to the current one instead of throwing.
|
||||
const current = Math.floor(new Date().getUTCMonth() / 3) + 1;
|
||||
expect(resolvePeriod({ year: "2026", quarter: "7" }).quarter).toBe(current);
|
||||
expect(resolvePeriod({}).quarter).toBe(current);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { desc, eq } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { billingReports, editorialAccounts } from "@/db/schema";
|
||||
import { queries } from "@/modules/billing/queries";
|
||||
import { monthPeriod, quarterPeriod, type BillingPeriod } from "@/modules/billing/period";
|
||||
import { quarterPeriod, type BillingPeriod } from "@/modules/billing/period";
|
||||
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||
|
||||
export type FinalizedReportSummary = {
|
||||
@@ -15,16 +15,18 @@ export type FinalizedReportSummary = {
|
||||
netTotalCents: number;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
hasInvoicePdf: boolean;
|
||||
invoiceUploadedAt: Date | null;
|
||||
invoiceEmailStatus: string;
|
||||
invoiceEmailSentAt: Date | null;
|
||||
};
|
||||
|
||||
export type BillingSelectionData = {
|
||||
editorial: { id: string; name: string };
|
||||
period: BillingPeriod;
|
||||
periodLabel: string;
|
||||
isQuarter: boolean;
|
||||
year: number;
|
||||
month: number | null;
|
||||
quarter: number | null;
|
||||
quarter: number;
|
||||
positions: BillingPosition[];
|
||||
repeatDownloads: RepeatDownloadPosition[];
|
||||
reports: FinalizedReportSummary[];
|
||||
@@ -41,7 +43,7 @@ export async function loadBillingSelection(
|
||||
.limit(1);
|
||||
if (!editorial) return null;
|
||||
|
||||
const { period, isQuarter, year, month, quarter, periodLabel } = resolvePeriod(searchParams);
|
||||
const { period, year, quarter, periodLabel } = resolvePeriod(searchParams);
|
||||
|
||||
const [positions, repeatDownloads, reportRows] = await Promise.all([
|
||||
queries.listBillablePositions(editorialId, period),
|
||||
@@ -54,6 +56,10 @@ export async function loadBillingSelection(
|
||||
netTotalCents: billingReports.netTotalCents,
|
||||
status: billingReports.status,
|
||||
createdAt: billingReports.createdAt,
|
||||
invoicePdfSha256: billingReports.invoicePdfSha256,
|
||||
invoiceUploadedAt: billingReports.invoiceUploadedAt,
|
||||
invoiceEmailStatus: billingReports.invoiceEmailStatus,
|
||||
invoiceEmailSentAt: billingReports.invoiceEmailSentAt,
|
||||
})
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.editorialAccountId, editorialId))
|
||||
@@ -64,9 +70,7 @@ export async function loadBillingSelection(
|
||||
editorial,
|
||||
period,
|
||||
periodLabel,
|
||||
isQuarter,
|
||||
year,
|
||||
month,
|
||||
quarter,
|
||||
positions,
|
||||
repeatDownloads,
|
||||
@@ -77,64 +81,34 @@ export async function loadBillingSelection(
|
||||
netTotalCents: row.netTotalCents,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt,
|
||||
hasInvoicePdf: row.invoicePdfSha256 !== null,
|
||||
invoiceUploadedAt: row.invoiceUploadedAt,
|
||||
invoiceEmailStatus: row.invoiceEmailStatus,
|
||||
invoiceEmailSentAt: row.invoiceEmailSentAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Billing is always quarterly. An old `?month=` link resolves to its quarter;
|
||||
* invalid values fall back to the current quarter.
|
||||
*/
|
||||
export function resolvePeriod(searchParams: Record<string, string | string[] | undefined>): {
|
||||
period: BillingPeriod;
|
||||
isQuarter: boolean;
|
||||
year: number;
|
||||
month: number | null;
|
||||
quarter: number | null;
|
||||
quarter: number;
|
||||
periodLabel: string;
|
||||
} {
|
||||
const now = new Date();
|
||||
const defaultYear = now.getUTCFullYear();
|
||||
const defaultMonth = now.getUTCMonth() + 1;
|
||||
|
||||
const year = parseNumberParam(searchParams.year, defaultYear);
|
||||
const quarterParam = firstParam(searchParams.quarter);
|
||||
|
||||
if (quarterParam !== undefined) {
|
||||
const quarter = parseNumberParam(searchParams.quarter, Math.floor((defaultMonth - 1) / 3) + 1);
|
||||
return {
|
||||
period: quarterPeriod(year, quarter),
|
||||
isQuarter: true,
|
||||
year,
|
||||
month: null,
|
||||
quarter,
|
||||
periodLabel: `Q${quarter} ${year}`,
|
||||
};
|
||||
}
|
||||
|
||||
const month = parseNumberParam(searchParams.month, defaultMonth);
|
||||
return {
|
||||
period: monthPeriod(year, month),
|
||||
isQuarter: false,
|
||||
year,
|
||||
month,
|
||||
quarter: null,
|
||||
periodLabel: monthLabel(year, month),
|
||||
};
|
||||
}
|
||||
|
||||
function monthLabel(year: number, month: number): string {
|
||||
const names = [
|
||||
"Januar",
|
||||
"Februar",
|
||||
"März",
|
||||
"April",
|
||||
"Mai",
|
||||
"Juni",
|
||||
"Juli",
|
||||
"August",
|
||||
"September",
|
||||
"Oktober",
|
||||
"November",
|
||||
"Dezember",
|
||||
];
|
||||
return `${names[month - 1]} ${year}`;
|
||||
const currentQuarter = Math.floor(now.getUTCMonth() / 3) + 1;
|
||||
const year = parseNumberParam(searchParams.year, now.getUTCFullYear());
|
||||
const month = parseNumberParam(searchParams.month, 0);
|
||||
const requested = parseNumberParam(
|
||||
searchParams.quarter,
|
||||
month >= 1 && month <= 12 ? Math.floor((month - 1) / 3) + 1 : currentQuarter,
|
||||
);
|
||||
const quarter = requested >= 1 && requested <= 4 ? requested : currentQuarter;
|
||||
return { period: quarterPeriod(year, quarter), year, quarter, periodLabel: `Q${quarter} ${year}` };
|
||||
}
|
||||
|
||||
function parseNumberParam(
|
||||
|
||||
@@ -32,9 +32,7 @@ export default async function BillingSelectionPage({
|
||||
positions={data.positions}
|
||||
repeatDownloads={data.repeatDownloads}
|
||||
year={data.year}
|
||||
month={data.month}
|
||||
quarter={data.quarter}
|
||||
isQuarter={data.isQuarter}
|
||||
periodLabel={data.periodLabel}
|
||||
reports={data.reports}
|
||||
/>
|
||||
|
||||
@@ -27,7 +27,7 @@ export default async function BillingOverviewPage() {
|
||||
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."
|
||||
description="Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für ein Quartal auszuwählen."
|
||||
/>
|
||||
{editorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Redaktionen registriert." description="Registrierte Redaktionen erscheinen hier zur Abrechnung." />
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
import { useActionState, useMemo, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Alert, Checkbox, EmptyState, Input, Table } from "@sakaniui/react";
|
||||
import { 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";
|
||||
import { notifyResult, useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
type AccessAction = (
|
||||
state: AlbumAccessActionResult,
|
||||
@@ -42,12 +43,12 @@ export function AlbumAccessManager({
|
||||
bulkGrantAction: AccessAction;
|
||||
revokeAction: AccessAction;
|
||||
}>) {
|
||||
const [bulkState, setBulkState] = useState<AlbumAccessActionResult>(INITIAL_RESULT);
|
||||
const [bulkPending, startBulkTransition] = useTransition();
|
||||
const [revokeState, revokeFormAction, revokePending] = useActionState(
|
||||
revokeAction,
|
||||
INITIAL_RESULT,
|
||||
);
|
||||
useResultToast(revokeState);
|
||||
const [selectedAlbumIds, setSelectedAlbumIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [selectedEditorialIds, setSelectedEditorialIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [bulkSearch, setBulkSearch] = useState("");
|
||||
@@ -58,7 +59,7 @@ export function AlbumAccessManager({
|
||||
const handleBulkSubmit = (formData: FormData) => {
|
||||
startBulkTransition(async () => {
|
||||
const result = await bulkGrantAction(INITIAL_RESULT, formData);
|
||||
setBulkState(result);
|
||||
notifyResult(result);
|
||||
if (result.ok && result.grantedCount > 0) {
|
||||
setSelectedAlbumIds(new Set());
|
||||
setSelectedEditorialIds(new Set());
|
||||
@@ -255,13 +256,9 @@ export function AlbumAccessManager({
|
||||
</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)]">
|
||||
<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>
|
||||
@@ -291,9 +288,6 @@ export function AlbumAccessManager({
|
||||
</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." />
|
||||
|
||||
@@ -2,7 +2,9 @@ import Link from "next/link";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, DataTable, EmptyState, Input } from "@/components/ui/sakani";
|
||||
import { Badge, Card, DataTable, EmptyState, FormSelect, Input } from "@/components/ui/sakani";
|
||||
import { db } from "@/db/client";
|
||||
import { auditEvents } from "@/db/schema";
|
||||
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
@@ -24,14 +26,21 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
const dateTo = firstParam(params, "dateTo");
|
||||
const cursor = firstParam(params, "cursor");
|
||||
|
||||
const page = await listAuditEvents(
|
||||
const [page, typeRows] = await Promise.all([
|
||||
listAuditEvents(
|
||||
{
|
||||
eventType: eventType || undefined,
|
||||
dateFrom: dateFrom ? berlinDateToUtc(dateFrom) : undefined,
|
||||
dateTo: dateTo ? berlinDateToUtcEndOfDay(dateTo) : undefined,
|
||||
},
|
||||
cursor || null,
|
||||
);
|
||||
cursor || null,
|
||||
),
|
||||
db.selectDistinct({ eventType: auditEvents.eventType }).from(auditEvents).orderBy(auditEvents.eventType),
|
||||
]);
|
||||
const typeOptions = [
|
||||
{ label: "Alle Ereignisse", value: "" },
|
||||
...typeRows.map(({ eventType: type }) => ({ label: eventLabel(type), value: type })),
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6" aria-labelledby="audit-title">
|
||||
@@ -44,7 +53,7 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
|
||||
<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" />
|
||||
<FormSelect defaultValue={eventType ?? ""} label="Ereignis" name="eventType" options={typeOptions} />
|
||||
<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>
|
||||
@@ -58,16 +67,30 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
columns={[
|
||||
{ key: "at", header: "Zeitstempel" },
|
||||
{ key: "actor", header: "Akteur" },
|
||||
{ key: "type", header: "Ereignistyp" },
|
||||
{ key: "type", header: "Ereignis" },
|
||||
{ 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>,
|
||||
actor: (
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<Badge variant={ACTOR_BADGES[event.actorType]?.variant ?? "neutral"}>
|
||||
{ACTOR_BADGES[event.actorType]?.label ?? event.actorType}
|
||||
</Badge>
|
||||
{event.actorType === "system" ? null : (
|
||||
<span className="break-all text-xs text-[var(--color-fg-muted)]">{actorLabel(event)}</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
type: (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{eventLabel(event.eventType)}</span>
|
||||
<code className="break-all text-xs text-[var(--color-fg-muted)]">{event.eventType}</code>
|
||||
</div>
|
||||
),
|
||||
subject: <span className="break-all text-xs text-[var(--color-fg-muted)]">{entityLabel(event)}</span>,
|
||||
details: <AuditDetails event={event} />,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
@@ -104,10 +127,65 @@ function entityLabel(event: AuditEventRow): string {
|
||||
return `${event.entityType} · ${event.entityId}`;
|
||||
}
|
||||
|
||||
function formatMetadata(event: AuditEventRow): string {
|
||||
const ACTOR_BADGES: Record<string, { label: string; variant: "info" | "accent" | "neutral" }> = {
|
||||
admin: { label: "Admin", variant: "accent" },
|
||||
editorial: { label: "Redaktion", variant: "info" },
|
||||
system: { label: "System", variant: "neutral" },
|
||||
};
|
||||
|
||||
const EVENT_LABELS: Record<string, string> = {
|
||||
album_granted: "Album freigegeben",
|
||||
album_revoked: "Albumzugriff entzogen",
|
||||
album_self_granted: "Album selbst freigeschaltet",
|
||||
announcement_created: "Hinweis veröffentlicht",
|
||||
announcement_deleted: "Hinweis gelöscht",
|
||||
billable_usage_created: "Neue Nutzung",
|
||||
billing_address_replaced: "Rechnungsadresse geändert",
|
||||
billing_report_cancelled: "Abrechnung storniert",
|
||||
billing_report_finalized: "Abrechnung erstellt",
|
||||
calendar_event_created: "Termin angelegt",
|
||||
calendar_event_deleted: "Termin gelöscht",
|
||||
editorial_approved: "Redaktion freigegeben",
|
||||
editorial_collab_updated: "Collab-Einstellung geändert",
|
||||
event_category_created: "Kategorie angelegt",
|
||||
event_category_deleted: "Kategorie gelöscht",
|
||||
event_reservation_removed: "Vormerkung entfernt",
|
||||
event_reserved: "Termin vorgemerkt",
|
||||
event_response_recorded: "Rückmeldung zu Termin",
|
||||
invoice_email_failed: "Rechnungsmail fehlgeschlagen",
|
||||
invoice_email_sent: "Rechnungsmail versendet",
|
||||
invoice_uploaded: "Rechnung hochgeladen",
|
||||
release_note_created: "Versionshinweis angelegt",
|
||||
release_note_deleted: "Versionshinweis gelöscht",
|
||||
usage_collab_updated: "Collab-Kennzeichnung geändert",
|
||||
};
|
||||
|
||||
function eventLabel(type: string): string {
|
||||
return EVENT_LABELS[type] ?? type.replaceAll("_", " ");
|
||||
}
|
||||
|
||||
function AuditDetails({ event }: Readonly<{ event: AuditEventRow }>) {
|
||||
const detail = event.newValues ?? event.previousValues;
|
||||
if (!detail) return "—";
|
||||
return JSON.stringify(detail, null, 2);
|
||||
if (!detail || typeof detail !== "object") {
|
||||
return <span className="text-[var(--color-fg-muted)]">-</span>;
|
||||
}
|
||||
const entries = Object.entries(detail as Record<string, unknown>);
|
||||
if (entries.length === 0) return <span className="text-[var(--color-fg-muted)]">-</span>;
|
||||
return (
|
||||
<details className="group text-xs">
|
||||
<summary className="cursor-pointer select-none font-medium text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]">
|
||||
{entries.length === 1 ? "1 Angabe" : `${entries.length} Angaben`}
|
||||
</summary>
|
||||
<dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1">
|
||||
{entries.map(([key, value]) => (
|
||||
<div className="contents" key={key}>
|
||||
<dt className="text-[var(--color-fg-muted)]">{key}</dt>
|
||||
<dd className="break-all font-mono">{typeof value === "string" ? value : JSON.stringify(value)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function berlinDateToUtc(dateStr: string): Date | undefined {
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Alert, Input, Textarea } from "@sakaniui/react";
|
||||
import { Input, Textarea } from "@sakaniui/react";
|
||||
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
// Same direct-call-in-transition pattern as the album bulk grant form so the
|
||||
// message box clears after a successful publish without an effect.
|
||||
@@ -24,14 +25,13 @@ export function AnnouncementForm({
|
||||
}>) {
|
||||
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);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setMessage("");
|
||||
}
|
||||
@@ -69,11 +69,6 @@ export function AnnouncementForm({
|
||||
{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>
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IconTrash } from "@sakaniui/react/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
import { useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
// One tiny form per announcement row so every delete button reports its own
|
||||
// result inline (same pattern as AlbumGrantForm).
|
||||
@@ -21,6 +22,7 @@ export function DeleteAnnouncementButton({
|
||||
announcementId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
useResultToast(state, "Hinweis gelöscht.");
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
@@ -28,11 +30,6 @@ export function DeleteAnnouncementButton({
|
||||
<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,121 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { Badge, Button, Checkbox } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
import type { ImportableAlbum } from "@/modules/calendar/service";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
const dateFormat = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeZone: "UTC" });
|
||||
|
||||
/**
|
||||
* Older Immich albums ("Titel | TT.MM.JJJJ") without an event: preview with
|
||||
* everything preselected, untick what should stay out, pick a category.
|
||||
*/
|
||||
export function AlbumImport({
|
||||
albums,
|
||||
categories,
|
||||
action,
|
||||
}: Readonly<{
|
||||
albums: ImportableAlbum[];
|
||||
categories: Array<{ id: string; name: string }>;
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
}>) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(new Set());
|
||||
const [pending, startTransition] = useTransition();
|
||||
const selected = useMemo(() => albums.filter((album) => !excluded.has(album.albumId)), [albums, excluded]);
|
||||
|
||||
const toggle = (albumId: string, checked: boolean) =>
|
||||
setExcluded((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked) next.delete(albumId);
|
||||
else next.add(albumId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const submit = (formData: FormData) => {
|
||||
for (const album of selected) formData.append("albumId", album.albumId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setOpen(false);
|
||||
setExcluded(new Set());
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
description={
|
||||
albums.length === 0
|
||||
? "Alle Alben im Format „Titel | TT.MM.JJJJ“ haben bereits einen Termin."
|
||||
: `${albums.length} ${albums.length === 1 ? "Album" : "Alben"} im Format „Titel | TT.MM.JJJJ“ ohne Termin gefunden. Titel und Datum werden aus dem Albumnamen übernommen.`
|
||||
}
|
||||
title="Ältere Alben übernehmen"
|
||||
>
|
||||
{albums.length > 0 && !open ? (
|
||||
<div>
|
||||
<Button leftIcon={<IconDownload size={16} />} onClick={() => setOpen(true)} type="button" variant="secondary">
|
||||
Alben aus Immich anzeigen
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{open ? (
|
||||
<form action={submit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<Button onClick={() => setExcluded(new Set())} size="sm" type="button" variant="ghost">
|
||||
Alle auswählen
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setExcluded(new Set(albums.map((album) => album.albumId)))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
Keine
|
||||
</Button>
|
||||
<Badge variant="info">{selected.length} ausgewählt</Badge>
|
||||
</div>
|
||||
<ul className="flex max-h-96 flex-col divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)]">
|
||||
{albums.map((album) => (
|
||||
<li className="flex items-center justify-between gap-4 px-3 py-2.5" key={album.albumId}>
|
||||
<Checkbox
|
||||
checked={!excluded.has(album.albumId)}
|
||||
description={`${dateFormat.format(new Date(`${album.eventDate}T00:00:00Z`))} · ${album.assetCount} Fotos`}
|
||||
disabled={pending}
|
||||
label={album.title}
|
||||
onChange={(event) => toggle(album.albumId, event.target.checked)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="sm:max-w-xs">
|
||||
<FormSelect
|
||||
label="Kategorie für alle übernommenen Termine"
|
||||
name="categoryId"
|
||||
options={[
|
||||
{ label: "Ohne Kategorie", value: "" },
|
||||
...categories.map((category) => ({ label: category.name, value: category.id })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button disabled={pending || selected.length === 0} loading={pending} type="submit">
|
||||
{selected.length === 1 ? "1 Termin übernehmen" : `${selected.length} Termine übernehmen`}
|
||||
</Button>
|
||||
<Button disabled={pending} onClick={() => setOpen(false)} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : null}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Input } from "@sakaniui/react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function CalendarEventForm({
|
||||
action,
|
||||
defaultEventDate,
|
||||
albums,
|
||||
categories,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
defaultEventDate: string;
|
||||
albums: Array<{ id: string; albumName: string }>;
|
||||
categories: Array<{ id: string; name: string }>;
|
||||
}>) {
|
||||
const titleId = useId();
|
||||
const dateId = useId();
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [title, setTitle] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setTitle("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="Neuer Termin">
|
||||
<form action={handleSubmit} className="flex flex-col gap-4">
|
||||
<Input
|
||||
description="Ohne direkte Album-Auswahl wird automatisch verknüpft, sobald ein Album exakt „{Titel}“ oder „{Titel} | TT.MM.JJJJ“ heißt (Datum dieses Termins)."
|
||||
id={titleId}
|
||||
label="Titel (Spielpaarung oder Event)"
|
||||
maxLength={200}
|
||||
name="title"
|
||||
onChange={(event) => setTitle(event.target.value)}
|
||||
placeholder="z. B. Hamburger SV - VfL Wolfsburg"
|
||||
required
|
||||
value={title}
|
||||
/>
|
||||
<div className="flex flex-col gap-4 sm:flex-row">
|
||||
<div className="sm:w-64">
|
||||
<FormSelect
|
||||
label="Kategorie"
|
||||
name="categoryId"
|
||||
options={[
|
||||
{ label: "Ohne Kategorie", value: "" },
|
||||
...categories.map((category) => ({ label: category.name, value: category.id })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:w-48">
|
||||
<Input defaultValue={defaultEventDate} id={dateId} label="Datum" name="eventDate" required type="date" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<FormSelect
|
||||
label="Album direkt verknüpfen (optional)"
|
||||
name="immichAlbumId"
|
||||
options={[
|
||||
{ label: "Automatisch über den Namen", value: "" },
|
||||
...albums.map((album) => ({ label: album.albumName, value: album.id })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird angelegt …" : "Termin anlegen"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
// Deleting an event also revokes self-service grants on its linked album, so
|
||||
// the admin confirms once before the action runs.
|
||||
export function DeleteCalendarEventButton({
|
||||
action,
|
||||
eventId,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
eventId: string;
|
||||
}>) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
if (!window.confirm("Termin löschen? Selbst freigeschaltete Zugriffe auf das verknüpfte Album werden entzogen.")) {
|
||||
return;
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
notifyResult(await action({ ok: true, message: "" }, formData), "Termin gelöscht.");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button type="button" variant="outline" size="sm" disabled={pending} onClick={handleClick}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { CalendarServiceError, calendarService } from "@/modules/calendar/service";
|
||||
|
||||
export type CalendarActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createCalendarEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const title = formData.get("title");
|
||||
const eventDate = formData.get("eventDate");
|
||||
const immichAlbumId = formData.get("immichAlbumId");
|
||||
const categoryId = formData.get("categoryId");
|
||||
|
||||
if (typeof title !== "string" || typeof eventDate !== "string") {
|
||||
return { ok: false, message: "Bitte Titel und Datum ausfüllen." };
|
||||
}
|
||||
|
||||
try {
|
||||
await calendarService.createEvent({
|
||||
title,
|
||||
eventDate,
|
||||
immichAlbumId: typeof immichAlbumId === "string" && immichAlbumId ? immichAlbumId : null,
|
||||
categoryId: typeof categoryId === "string" && categoryId ? categoryId : null,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
return {
|
||||
ok: true,
|
||||
message:
|
||||
"Termin angelegt. Redaktionen können ihn sofort vormerken; das Album wird freigeschaltet, sobald es in Immich erscheint.",
|
||||
};
|
||||
}
|
||||
|
||||
/** Imports selected older Immich albums as calendar events. */
|
||||
export async function importAlbumsAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const albumIds = formData.getAll("albumId").filter((value): value is string => typeof value === "string");
|
||||
const categoryId = formData.get("categoryId");
|
||||
try {
|
||||
const { imported } = await calendarService.importAlbums({
|
||||
albumIds,
|
||||
categoryId: typeof categoryId === "string" && categoryId ? categoryId : null,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
return { ok: true, message: imported === 1 ? "1 Termin übernommen." : `${imported} Termine übernommen.` };
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCalendarEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const eventId = formData.get("eventId");
|
||||
if (typeof eventId !== "string" || eventId.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await calendarService.deleteEvent({ id: eventId, adminUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
revalidatePath("/redaktion/alben");
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
|
||||
function calendarErrorMessage(error: unknown): string {
|
||||
if (error instanceof CalendarServiceError) {
|
||||
const messages: Record<CalendarServiceError["code"], string> = {
|
||||
INVALID_TITLE: "Bitte geben Sie einen Titel mit 1 bis 200 Zeichen ein.",
|
||||
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
|
||||
INVALID_ALBUM: "Das gewählte Album existiert nicht mehr in Immich.",
|
||||
INVALID_CATEGORY: "Die gewählte Kategorie existiert nicht mehr.",
|
||||
NOTHING_TO_IMPORT: "Bitte mindestens ein Album auswählen, das noch keinen Termin hat.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung existiert nicht mehr.",
|
||||
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
|
||||
};
|
||||
return messages[error.code];
|
||||
}
|
||||
return "Der Termin konnte nicht gespeichert werden.";
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
import { Input } from "@sakaniui/react";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
import { CATEGORY_COLOR_LABELS, CATEGORY_COLORS, type CategoryColor } from "@/modules/calendar/colors";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function CategoryForm({
|
||||
action,
|
||||
}: Readonly<{ action: (state: CategoryActionResult, formData: FormData) => Promise<CategoryActionResult> }>) {
|
||||
const nameId = useId();
|
||||
const [name, setName] = useState("");
|
||||
const [color, setColor] = useState<CategoryColor>("blue");
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
notifyResult(result);
|
||||
if (result.ok) setName("");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="Neue Kategorie">
|
||||
<form action={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="sm:max-w-md">
|
||||
<Input
|
||||
id={nameId}
|
||||
label="Name"
|
||||
maxLength={80}
|
||||
name="name"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="z. B. Fußball - 1. Bundesliga"
|
||||
required
|
||||
value={name}
|
||||
/>
|
||||
</div>
|
||||
<fieldset className="flex flex-col gap-2">
|
||||
<legend className="mb-2 text-sm font-medium text-[var(--color-fg-default)]">Farbe</legend>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{CATEGORY_COLORS.map((option) => (
|
||||
<label
|
||||
className={`flex min-h-10 cursor-pointer items-center gap-2 rounded-full border px-3 text-sm transition-colors has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 ${
|
||||
color === option
|
||||
? "border-[var(--color-fg-default)] bg-[var(--color-bg-subtle)] font-medium"
|
||||
: "border-[var(--color-border-subtle)] text-[var(--color-fg-muted)] hover:bg-[var(--color-bg-subtle)]"
|
||||
}`}
|
||||
key={option}
|
||||
>
|
||||
<input
|
||||
checked={color === option}
|
||||
className="sr-only"
|
||||
name="color"
|
||||
onChange={() => setColor(option)}
|
||||
type="radio"
|
||||
value={option}
|
||||
/>
|
||||
<CategoryDot color={option} />
|
||||
{CATEGORY_COLOR_LABELS[option]}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird gespeichert …" : "Kategorie speichern"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function DeleteCategoryButton({
|
||||
action,
|
||||
categoryId,
|
||||
inUse,
|
||||
}: Readonly<{
|
||||
action: (state: CategoryActionResult, formData: FormData) => Promise<CategoryActionResult>;
|
||||
categoryId: string;
|
||||
inUse: boolean;
|
||||
}>) {
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
const formData = new FormData();
|
||||
formData.set("categoryId", categoryId);
|
||||
startTransition(async () => notifyResult(await action({ ok: true, message: "" }, formData), "Kategorie gelöscht."));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button
|
||||
disabled={pending || inUse}
|
||||
onClick={handleClick}
|
||||
size="sm"
|
||||
title={inUse ? "Wird noch von Terminen genutzt" : undefined}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { CategoryServiceError, categoryService } from "@/modules/calendar/categories";
|
||||
|
||||
export type CategoryActionResult = { ok: boolean; message: string };
|
||||
|
||||
const MESSAGES: Record<CategoryServiceError["code"], string> = {
|
||||
INVALID_NAME: "Bitte geben Sie einen Namen mit 1 bis 80 Zeichen ein.",
|
||||
INVALID_COLOR: "Bitte wählen Sie eine Farbe aus der Liste.",
|
||||
DUPLICATE_NAME: "Diese Kategorie gibt es schon.",
|
||||
CATEGORY_IN_USE: "Die Kategorie wird noch von Terminen genutzt und kann nicht gelöscht werden.",
|
||||
CATEGORY_NOT_FOUND: "Diese Kategorie existiert nicht mehr.",
|
||||
};
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof CategoryServiceError ? MESSAGES[error.code] : fallback;
|
||||
}
|
||||
|
||||
function revalidate() {
|
||||
revalidatePath("/admin/kalender/kategorien");
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
}
|
||||
|
||||
export async function createCategoryAction(
|
||||
_prevState: CategoryActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CategoryActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const name = formData.get("name");
|
||||
const color = formData.get("color");
|
||||
try {
|
||||
await categoryService.createCategory({
|
||||
name: typeof name === "string" ? name : "",
|
||||
color: typeof color === "string" ? color : "",
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: errorMessage(error, "Die Kategorie konnte nicht gespeichert werden.") };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "Kategorie gespeichert." };
|
||||
}
|
||||
|
||||
export async function deleteCategoryAction(
|
||||
_prevState: CategoryActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CategoryActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const id = formData.get("categoryId");
|
||||
if (typeof id !== "string" || id.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
try {
|
||||
await categoryService.deleteCategory({ id, adminUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: errorMessage(error, "Die Kategorie konnte nicht gelöscht werden.") };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { CATEGORY_COLOR_LABELS } from "@/modules/calendar/colors";
|
||||
|
||||
import { requireAdminPage } from "../../access";
|
||||
import { CategoryForm } from "./CategoryForm";
|
||||
import { DeleteCategoryButton } from "./DeleteCategoryButton";
|
||||
import { createCategoryAction, deleteCategoryAction } from "./actions";
|
||||
|
||||
export default async function AdminCategoriesPage() {
|
||||
await requireAdminPage();
|
||||
const categories = await categoryService.listCategories();
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Planung · Kalender"
|
||||
title="Kategorien"
|
||||
description="Sportarten und Ligen für den Kalender. Die Farbe erscheint bei den Terminen und in der Legende."
|
||||
>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/kalender">Zum Kalender</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<CategoryForm action={createCategoryAction} />
|
||||
|
||||
<Card title="Gespeicherte Kategorien">
|
||||
{categories.length === 0 ? (
|
||||
<EmptyState title="Noch keine Kategorien" description="Legen Sie oben die erste Kategorie an." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{categories.map((category) => (
|
||||
<li className="flex items-center justify-between gap-4 py-3" key={category.id}>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<CategoryDot color={category.color} />
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium break-words">{category.name}</p>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{CATEGORY_COLOR_LABELS[category.color]} ·{" "}
|
||||
{category.eventCount === 1 ? "1 Termin" : `${category.eventCount} Termine`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DeleteCategoryButton
|
||||
action={deleteCategoryAction}
|
||||
categoryId={category.id}
|
||||
inUse={category.eventCount > 0}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { CategoryDot, CategoryLegend } from "@/components/calendar/category-legend";
|
||||
import { EventMonth } from "@/components/calendar/event-month";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
import { CalendarEventForm } from "./CalendarEventForm";
|
||||
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
|
||||
import { AlbumImport } from "./AlbumImport";
|
||||
import { createCalendarEventAction, deleteCalendarEventAction, importAlbumsAction } from "./actions";
|
||||
|
||||
export default async function AdminCalendarPage() {
|
||||
await requireAdminPage();
|
||||
const [{ events, immichUnavailable }, albums, categories, importable] = await Promise.all([
|
||||
calendarService.listAdminEvents(),
|
||||
immichClient.listAlbums().catch(() => []),
|
||||
categoryService.listCategories(),
|
||||
calendarService.listImportableAlbums(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Planung"
|
||||
title="Kalender"
|
||||
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen merken Termine vor und bekommen das verknüpfte Album automatisch, sobald es da ist. Alben ohne Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
|
||||
>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/kalender/kategorien">Kategorien verwalten</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<CalendarEventForm
|
||||
action={createCalendarEventAction}
|
||||
albums={albums.map((album) => ({ id: album.id, albumName: album.albumName }))}
|
||||
categories={categories.map((category) => ({ id: category.id, name: category.name }))}
|
||||
defaultEventDate={today}
|
||||
/>
|
||||
|
||||
{importable.immichUnavailable ? null : (
|
||||
<AlbumImport
|
||||
action={importAlbumsAction}
|
||||
albums={importable.albums}
|
||||
categories={categories.map((category) => ({ id: category.id, name: category.name }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{immichUnavailable ? (
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht."
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Card title="Monatsübersicht">
|
||||
<EventMonth
|
||||
events={events.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.title,
|
||||
eventDate: event.eventDate,
|
||||
color: event.category?.color ?? null,
|
||||
}))}
|
||||
/>
|
||||
<CategoryLegend categories={categories} showUncategorized={events.some((event) => !event.category)} />
|
||||
</Card>
|
||||
|
||||
<section aria-labelledby="calendar-list-title" className="flex flex-col gap-4">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h2 className="text-xl font-semibold" id="calendar-list-title">
|
||||
Alle Termine
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">{events.length} insgesamt</p>
|
||||
</div>
|
||||
|
||||
{events.length === 0 ? (
|
||||
<EmptyState title="Noch keine Termine" description="Legen Sie oben den ersten Termin an." />
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{events.map((event) => {
|
||||
const granted = event.reservations.filter((row) => row.grantedAt).length;
|
||||
return (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] sm:flex-row sm:items-start"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-2">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
<span>· {event.album ? `Album: ${event.album.albumName}` : "Noch kein Album verknüpft"}</span>
|
||||
</p>
|
||||
{event.reservations.length > 0 ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{event.reservations.length === 1 ? "1 Vormerkung" : `${event.reservations.length} Vormerkungen`}
|
||||
{granted > 0 ? `, ${granted} freigeschaltet` : ""}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{event.reservations.map((row) => (
|
||||
<Badge key={row.editorialId} variant={row.grantedAt ? "success" : "neutral"}>
|
||||
{row.editorialName}: {row.grantedAt ? "freigeschaltet" : "vorgemerkt"}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">Noch keine Vormerkungen.</p>
|
||||
)}
|
||||
</div>
|
||||
<DeleteCalendarEventButton action={deleteCalendarEventAction} eventId={event.id} />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+122
-110
@@ -1,116 +1,116 @@
|
||||
import { eq, sql, and, desc, gte } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { usages, editorialAccounts } from "@/db/schema";
|
||||
import Link from "next/link";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { BarChart, Card, EmptyState, StatCard, DataTable } from "@/components/ui/sakani";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, BarChart, Card, DataTable, EmptyState, StatCard } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
import { loadDashboardCounts } from "@/modules/dashboard/queries";
|
||||
import { dashboardTasks } from "@/modules/dashboard/tasks";
|
||||
import { statsQueries } from "@/modules/stats/queries";
|
||||
|
||||
import { requireAdminPage } from "./access";
|
||||
|
||||
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
const ACTIVITY_LABELS: Record<string, string> = {
|
||||
album_view: "Album geöffnet",
|
||||
search: "Suche",
|
||||
lightbox_view: "Großansicht",
|
||||
};
|
||||
|
||||
const linkClass = "font-medium text-[var(--color-fg-default)] underline-offset-4 hover:underline";
|
||||
|
||||
export default async function AdminDashboardPage() {
|
||||
await requireAdminPage();
|
||||
|
||||
const now = new Date();
|
||||
const firstDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth(), 1));
|
||||
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
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 [counts, stats, calendar] = await Promise.all([
|
||||
loadDashboardCounts(now),
|
||||
statsQueries.loadOverview(30),
|
||||
calendarService.listAdminEvents(),
|
||||
]);
|
||||
|
||||
const revenueStats = revenueStatsResult[0];
|
||||
|
||||
// Fill in missing days
|
||||
const chartData = [];
|
||||
for (let i = 29; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const dateStr = d.toISOString().split('T')[0];
|
||||
const record = dailyDownloads.find(r => r.date === dateStr);
|
||||
chartData.push({
|
||||
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" });
|
||||
const tasks = dashboardTasks(counts);
|
||||
const today = isoDateInBerlin(now);
|
||||
const nextEvents = calendar.events.filter((event) => event.eventDate >= today).slice(0, 5);
|
||||
const { kpis } = stats;
|
||||
const downloads = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.downloads,
|
||||
}));
|
||||
|
||||
return (
|
||||
<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>
|
||||
<PageHeader title="Dashboard" description="Was ansteht, was als Nächstes kommt und wie das Portal genutzt wird.">
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/statistiken">Alle Statistiken</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 className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Zu erledigen">
|
||||
{tasks.length === 0 ? (
|
||||
<EmptyState title="Alles erledigt" description="Keine offenen Freigaben, Rechnungen oder Fehler." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{tasks.map((task) => (
|
||||
<li className="flex items-center justify-between gap-4 py-3" key={task.id}>
|
||||
<Link className={linkClass} href={task.href}>
|
||||
{task.label}
|
||||
</Link>
|
||||
<Badge variant={task.tone}>{task.value}</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="Nächste Termine">
|
||||
{nextEvents.length === 0 ? (
|
||||
<EmptyState title="Keine Termine geplant" description="Neue Spiele legen Sie im Kalender an." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{nextEvents.map((event) => (
|
||||
<li className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 py-3" key={event.id}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{event.category ? <CategoryDot color={event.category.color} /> : <CategoryDot color="neutral" />}
|
||||
<span className="truncate font-medium">{event.title}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-[var(--color-fg-muted)]">
|
||||
<span className="tabular-nums">{formatIsoDateGerman(event.eventDate)}</span>
|
||||
<Badge>
|
||||
{event.reservations.length === 1 ? "1 Vormerkung" : `${event.reservations.length} Vormerkungen`}
|
||||
</Badge>
|
||||
<Badge variant={event.album ? "success" : "neutral"}>{event.album ? "Album da" : "Kein Album"}</Badge>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<Link className={`${linkClass} text-sm`} href="/admin/kalender">
|
||||
Zum Kalender
|
||||
</Link>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card title="Downloads der letzten 30 Tage" description="Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.">
|
||||
{chartData.every((day) => day.value === 0) ? (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard title="Downloads (30 Tage)" value={String(kpis.downloadsCompleted)} description="Ausgelieferte Originale" />
|
||||
<StatCard title="Umsatz (30 Tage)" value={euro.format(kpis.revenueCents / 100)} description="Netto, aus neuen Nutzungen" />
|
||||
<StatCard title="Album-Aufrufe (30 Tage)" value={String(kpis.albumViews)} description="Seit Version 2.2 erfasst" />
|
||||
</div>
|
||||
|
||||
<Card title="Downloads der letzten 30 Tage" description="Tägliche Downloads über alle Redaktionen.">
|
||||
{downloads.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" />
|
||||
<BarChart data={downloads} seriesLabels={["Downloads"]} size="lg" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<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." />
|
||||
<Card title="Aktivste Redaktionen" description="Nach Downloads in den letzten 30 Tagen.">
|
||||
{stats.topEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten" description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
@@ -118,34 +118,46 @@ export default async function AdminDashboardPage() {
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
]}
|
||||
rows={topEditorials.map((ed) => ({
|
||||
id: ed.editorialId,
|
||||
rows={stats.topEditorials.slice(0, 5).map((row) => ({
|
||||
id: row.editorialId,
|
||||
name: (
|
||||
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="font-medium text-[var(--color-brand-fg)] hover:underline">
|
||||
{ed.name}
|
||||
<Link className={linkClass} href={`/admin/redaktionen/${row.editorialId}`}>
|
||||
{row.name}
|
||||
</Link>
|
||||
),
|
||||
downloads: <span className="tabular-nums">{ed.downloadCount}</span>,
|
||||
revenue: <span className="tabular-nums">{formatter.format(ed.revenueCents / 100)}</span>,
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
revenue: <span className="tabular-nums">{euro.format(row.revenueCents / 100)}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<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." />
|
||||
<Card title="Letzte Aktivitäten" description="Aufrufe, Suchen und Großansichten der Redaktionen.">
|
||||
{stats.recentActivity.length === 0 ? (
|
||||
<EmptyState title="Noch keine Aktivitäten" description="Aufrufe und Suchen werden seit Version 2.2 erfasst." />
|
||||
) : (
|
||||
<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>,
|
||||
}))}
|
||||
/>
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{stats.recentActivity.slice(0, 8).map((event) => (
|
||||
<li className="flex flex-wrap items-center gap-3 py-2.5 text-sm" key={event.id}>
|
||||
<Badge>{ACTIVITY_LABELS[event.eventType] ?? event.eventType}</Badge>
|
||||
<span className="font-medium">{event.editorialName}</span>
|
||||
{event.query ? <span className="text-[var(--color-fg-muted)]">„{event.query}“</span> : null}
|
||||
<time
|
||||
className="ml-auto text-xs tabular-nums text-[var(--color-fg-muted)]"
|
||||
dateTime={event.occurredAt.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{event.occurredAt.toLocaleString("de-DE", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "Europe/Berlin",
|
||||
})}
|
||||
</time>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Badge, EmptyState, Input, SegmentedControl, Table, type TableColumn } from "@sakaniui/react";
|
||||
import { IconSearch } from "@sakaniui/react/icons";
|
||||
|
||||
export type EditorialRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
contactName: string;
|
||||
loginEmail: string;
|
||||
status: string;
|
||||
archived: boolean;
|
||||
priceCents: number | null;
|
||||
openCents: number;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type StatusKey = "active" | "pending" | "suspended" | "archived";
|
||||
|
||||
const STATUS: Record<StatusKey, { label: string; variant: "success" | "warning" | "danger" | "neutral" }> = {
|
||||
active: { label: "Aktiv", variant: "success" },
|
||||
pending: { label: "Ausstehend", variant: "warning" },
|
||||
suspended: { label: "Gesperrt", variant: "danger" },
|
||||
archived: { label: "Archiviert", variant: "neutral" },
|
||||
};
|
||||
|
||||
function statusOf(row: EditorialRow): StatusKey {
|
||||
if (row.archived) return "archived";
|
||||
if (row.status === "active") return "active";
|
||||
if (row.status === "pending_email" || row.status === "pending_approval") return "pending";
|
||||
return "suspended";
|
||||
}
|
||||
|
||||
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
const date = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeZone: "Europe/Berlin" });
|
||||
|
||||
type Row = EditorialRow & { statusCell?: never; priceCell?: never; openCell?: never; createdCell?: never };
|
||||
|
||||
const columns: TableColumn<Row>[] = [
|
||||
{
|
||||
key: "name",
|
||||
header: "Redaktion",
|
||||
render: (row) => (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<Link
|
||||
className="font-medium text-[var(--color-fg-default)] underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
|
||||
href={`/admin/redaktionen/${row.id}`}
|
||||
>
|
||||
{row.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-[var(--color-fg-muted)]">{row.loginEmail}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ key: "contactName", header: "Kontakt" },
|
||||
{
|
||||
key: "statusCell",
|
||||
header: "Status",
|
||||
render: (row) => {
|
||||
const status = STATUS[statusOf(row)];
|
||||
return <Badge variant={status.variant}>{status.label}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "priceCell",
|
||||
header: "Preis netto",
|
||||
align: "right",
|
||||
render: (row) => (
|
||||
<span className="tabular-nums">{row.priceCents === null ? "offen" : euro.format(row.priceCents / 100)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "openCell",
|
||||
header: "Nicht abgerechnet",
|
||||
align: "right",
|
||||
render: (row) => (
|
||||
<span className={`tabular-nums ${row.openCents > 0 ? "font-medium text-[var(--color-warning-fg)]" : "text-[var(--color-fg-muted)]"}`}>
|
||||
{euro.format(row.openCents / 100)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "createdCell",
|
||||
header: "Registriert",
|
||||
align: "right",
|
||||
render: (row) => <span className="tabular-nums text-[var(--color-fg-muted)]">{date.format(new Date(row.createdAt))}</span>,
|
||||
},
|
||||
];
|
||||
|
||||
const FILTERS = [
|
||||
{ value: "all", label: "Alle" },
|
||||
{ value: "active", label: "Aktiv" },
|
||||
{ value: "pending", label: "Ausstehend" },
|
||||
{ value: "suspended", label: "Gesperrt" },
|
||||
{ value: "archived", label: "Archiviert" },
|
||||
];
|
||||
|
||||
export function EditorialsTable({ rows }: Readonly<{ rows: EditorialRow[] }>) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [filter, setFilter] = useState("all");
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
return rows.filter((row) => {
|
||||
const status = statusOf(row);
|
||||
// "Alle" hides archived accounts; they have their own filter.
|
||||
if (filter === "all" ? status === "archived" : status !== filter) return false;
|
||||
return !needle || [row.name, row.contactName, row.loginEmail].some((value) => value.toLowerCase().includes(needle));
|
||||
});
|
||||
}, [rows, query, filter]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="w-full lg:w-[34rem]">
|
||||
<SegmentedControl aria-label="Nach Status filtern" fullWidth onChange={setFilter} options={FILTERS} value={filter} />
|
||||
</div>
|
||||
<div className="lg:w-80">
|
||||
<Input
|
||||
aria-label="Redaktionen durchsuchen"
|
||||
leadingIcon={<IconSearch size={16} />}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Name, Kontakt oder E-Mail …"
|
||||
type="search"
|
||||
value={query}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<EmptyState
|
||||
description={query ? "Keine Redaktion passt zur Suche." : "In diesem Status gibt es gerade keine Redaktion."}
|
||||
title="Keine Redaktionen"
|
||||
/>
|
||||
) : (
|
||||
<Table<Row> columns={columns} rowKey={(row) => row.id} rows={visible} />
|
||||
)}
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{visible.length} von {rows.length} Redaktionen
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { editorialAccounts } from "@/db/schema";
|
||||
|
||||
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
|
||||
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
|
||||
import { writeAudit } from "@/modules/audit/write";
|
||||
|
||||
// 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
|
||||
@@ -203,6 +204,39 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
|
||||
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
|
||||
}
|
||||
|
||||
export async function updateCollabAction(editorialId: string, formData: FormData): Promise<void> {
|
||||
const admin = await requireAdmin(new Headers(await headers()));
|
||||
const safeEditorialId = requiredId(editorialId);
|
||||
const collabEnabled = formData.get("collabEnabled") === "on";
|
||||
|
||||
const [previous] = await db
|
||||
.select({ collabEnabled: editorialAccounts.collabEnabled })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, safeEditorialId))
|
||||
.limit(1);
|
||||
if (!previous) throw new Error("EDITORIAL_NOT_FOUND");
|
||||
|
||||
await db
|
||||
.update(editorialAccounts)
|
||||
.set({ collabEnabled })
|
||||
.where(eq(editorialAccounts.id, safeEditorialId));
|
||||
|
||||
try {
|
||||
await writeAudit({
|
||||
type: "editorial_collab_updated",
|
||||
actorUserId: admin.userId,
|
||||
actorType: "admin",
|
||||
entityType: "editorial_account",
|
||||
entityId: safeEditorialId,
|
||||
metadata: { from: previous.collabEnabled, to: collabEnabled },
|
||||
});
|
||||
} catch {
|
||||
// Audit is observability, not a transaction participant.
|
||||
}
|
||||
|
||||
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
|
||||
}
|
||||
|
||||
function parsePriceCents(
|
||||
value: unknown,
|
||||
): { ok: true; cents: number } | { ok: false; message: string } {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { IconMail, IconSearch } from "@sakaniui/react/icons";
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import type { AlbumActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
type AlbumGridAction = (
|
||||
editorialId: string,
|
||||
@@ -46,9 +47,9 @@ function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction
|
||||
startTransition(async () => {
|
||||
const initial: AlbumActionResult = { ok: true, message: "" };
|
||||
if (album.isGranted) {
|
||||
await revokeAction(editorialId, initial, formData);
|
||||
notifyResult(await revokeAction(editorialId, initial, formData), "Zuweisung aufgehoben.");
|
||||
} else {
|
||||
await grantAction(editorialId, initial, formData);
|
||||
notifyResult(await grantAction(editorialId, initial, formData), "Album zugewiesen.");
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -99,6 +100,7 @@ function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction
|
||||
setNotifyStatus("pending");
|
||||
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
|
||||
setNotifyStatus(res.ok ? "success" : "error");
|
||||
notifyResult(res, "E-Mail an die Redaktion gesendet.");
|
||||
setTimeout(() => setNotifyStatus("idle"), 3000);
|
||||
});
|
||||
}}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
import { EditorialDetailContent } from "@/modules/editorials/admin-detail";
|
||||
import { AlbumGrantError } from "@/modules/albums/grants";
|
||||
import { loadAssignableAlbums } from "./page-content";
|
||||
@@ -18,6 +20,7 @@ const editorial = {
|
||||
flatrateActive: false,
|
||||
flatratePriceCents: null,
|
||||
flatrateAssetLimit: null,
|
||||
collabEnabled: false,
|
||||
archivedAt: null,
|
||||
};
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { requireAdminPage } from "../../../access";
|
||||
import { applyAutoRulesAction, createAutoRuleAction, deleteAutoRuleAction } from "./actions";
|
||||
import { ToastForm } from "@/components/ui/feedback";
|
||||
|
||||
type AutoRulesPageProps = Readonly<{
|
||||
params: Promise<{ id: string }>;
|
||||
@@ -51,14 +52,14 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex flex-col gap-4 sm:flex-row sm:items-end">
|
||||
<ToastForm action={createAutoRuleAction.bind(null, editorial.id)} failure="Die Regel konnte nicht gespeichert werden. Bitte das Stichwort prüfen." success="Regel gespeichert." 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>
|
||||
</ToastForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -71,11 +72,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
Alle derzeit aktiven automatischen Zuweisungen.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
|
||||
<ToastForm action={applyAutoRulesAction.bind(null, editorial.id)} success="Regeln angewendet.">
|
||||
<Button type="submit" variant="secondary" leftIcon={<IconPlayerPlay size={16} />}>
|
||||
Regeln jetzt anwenden
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -91,11 +92,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
Erstellt am {new Date(rule.createdAt).toLocaleDateString('de-DE')}
|
||||
</span>
|
||||
</div>
|
||||
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
|
||||
<ToastForm action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)} success="Regel gelöscht.">
|
||||
<Button type="submit" variant="ghost" size="sm" leftIcon={<IconTrash size={16} />}>
|
||||
Entfernen
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -21,6 +21,7 @@ export default async function EditorialDetailPage({
|
||||
flatrateActive: editorialAccounts.flatrateActive,
|
||||
flatratePriceCents: editorialAccounts.flatratePriceCents,
|
||||
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
|
||||
collabEnabled: editorialAccounts.collabEnabled,
|
||||
archivedAt: editorialAccounts.archivedAt,
|
||||
})
|
||||
.from(editorialAccounts)
|
||||
|
||||
@@ -3,10 +3,13 @@ import Link from "next/link";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts, usages } from "@/db/schema";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { IconChevronRight } from "@sakaniui/react/icons";
|
||||
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { EmptyState } from "@/components/ui/sakani";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
import { EditorialsTable } from "./EditorialsTable";
|
||||
|
||||
export default async function EditorialsPage() {
|
||||
await requireAdminPage();
|
||||
const [editorials, openUsageTotals] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
@@ -37,96 +40,31 @@ export default async function EditorialsPage() {
|
||||
openUsageTotals.map((total) => [total.editorialId, total.openCents]),
|
||||
);
|
||||
|
||||
const activeEditorials = editorials.filter((e) => !e.archivedAt);
|
||||
const archivedEditorials = editorials.filter((e) => e.archivedAt);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Kontoverwaltung"
|
||||
title="Redaktionen"
|
||||
description="Verwalte hier alle registrierten und archivierten Redaktionszugänge."
|
||||
description="Alle registrierten Redaktionszugänge mit Status, Preis und noch nicht abgerechneten Nutzungen."
|
||||
/>
|
||||
|
||||
{activeEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine aktiven Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
|
||||
{editorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
|
||||
) : (
|
||||
<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>
|
||||
<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>
|
||||
</Card>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{archivedEditorials.length > 0 && (
|
||||
<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>
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{archivedEditorials.map((editorial) => (
|
||||
<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>
|
||||
<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>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
<EditorialsTable
|
||||
rows={editorials.map((editorial) => ({
|
||||
id: editorial.id,
|
||||
name: editorial.name,
|
||||
contactName: editorial.contactName,
|
||||
loginEmail: editorial.loginEmail,
|
||||
status: editorial.status,
|
||||
archived: Boolean(editorial.archivedAt),
|
||||
priceCents: editorial.currentPriceCents,
|
||||
openCents: openCentsByEditorial.get(editorial.id) ?? 0,
|
||||
createdAt: editorial.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</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);
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, BarChart, Card, DataTable, EmptyState, StatCard } from "@/components/ui/sakani";
|
||||
import {
|
||||
formatBytes,
|
||||
normalizeStatsDays,
|
||||
percentChange,
|
||||
STATS_PERIOD_OPTIONS,
|
||||
statsQueries,
|
||||
} from "@/modules/stats/queries";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
|
||||
const euroFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
const ACTIVITY_LABELS: Record<string, string> = {
|
||||
album_view: "Album geöffnet",
|
||||
search: "Suche",
|
||||
lightbox_view: "Großansicht",
|
||||
};
|
||||
|
||||
export default async function AdminStatsPage({
|
||||
searchParams,
|
||||
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
|
||||
await requireAdminPage();
|
||||
const sp = await searchParams;
|
||||
const rawDays = Array.isArray(sp.zeitraum) ? sp.zeitraum[0] : sp.zeitraum;
|
||||
const days = normalizeStatsDays(rawDays);
|
||||
const stats = await statsQueries.loadOverview(days);
|
||||
const { kpis, previousKpis } = stats;
|
||||
|
||||
const activityData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.downloads,
|
||||
value2: day.views,
|
||||
}));
|
||||
const searchData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.searches,
|
||||
}));
|
||||
const revenueData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.revenueCents / 100,
|
||||
}));
|
||||
const hasActivity = stats.daily.some((day) => day.downloads + day.views + day.searches > 0);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Statistiken"
|
||||
description="Downloads, Aufrufe, Suchen und Umsatz im Detail. Aufrufe und Suchen werden seit Version 2.2 erfasst."
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<nav
|
||||
aria-label="Zeitraum"
|
||||
className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-subtle)] bg-[var(--color-bg-subtle)] p-1"
|
||||
>
|
||||
{STATS_PERIOD_OPTIONS.map((option) => (
|
||||
<Link
|
||||
key={option}
|
||||
href={`/admin/statistiken?zeitraum=${option}`}
|
||||
aria-current={option === days ? "page" : undefined}
|
||||
className={`rounded-full px-4 py-1.5 text-sm transition-colors ${
|
||||
option === days
|
||||
? "bg-[var(--color-bg-surface)] font-semibold shadow-[var(--shadow-sm)]"
|
||||
: "text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]"
|
||||
}`}
|
||||
>
|
||||
{option} Tage
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Zeitraum: {stats.window.fromUtc.toLocaleDateString("de-DE")} bis{" "}
|
||||
{stats.window.toUtcExclusive.toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatCard
|
||||
title="Downloads"
|
||||
value={String(kpis.downloadsCompleted)}
|
||||
description={`${kpis.downloadsInterrupted} unterbrochen, ${kpis.downloadsFailed} fehlgeschlagen`}
|
||||
{...trendProps(percentChange(kpis.downloadsCompleted, previousKpis.downloadsCompleted))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Datenmenge"
|
||||
value={formatBytes(kpis.transferredBytes)}
|
||||
description="Ausgelieferte Originaldateien"
|
||||
/>
|
||||
<StatCard
|
||||
title="Neue Nutzungen"
|
||||
value={String(kpis.newUsages)}
|
||||
description={`${kpis.collabUsages} davon Collab (kostenfrei)`}
|
||||
{...trendProps(percentChange(kpis.newUsages, previousKpis.newUsages))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Umsatz im Zeitraum"
|
||||
value={euroFormatter.format(kpis.revenueCents / 100)}
|
||||
description="Netto, aus neuen Nutzungen"
|
||||
{...trendProps(percentChange(kpis.revenueCents, previousKpis.revenueCents))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Album-Aufrufe"
|
||||
value={String(kpis.albumViews)}
|
||||
description="Seitenaufrufe der Albumansicht"
|
||||
{...trendProps(percentChange(kpis.albumViews, previousKpis.albumViews))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Suchen"
|
||||
value={String(kpis.searches)}
|
||||
description="In Alben und über alle Alben"
|
||||
{...trendProps(percentChange(kpis.searches, previousKpis.searches))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Großansichten"
|
||||
value={String(kpis.lightboxViews)}
|
||||
description="Lightbox-Öffnungen"
|
||||
{...trendProps(percentChange(kpis.lightboxViews, previousKpis.lightboxViews))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Aktive Redaktionen"
|
||||
value={String(kpis.activeEditorials)}
|
||||
description="Mit mindestens einem Download"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard
|
||||
title="Offener Umsatz gesamt"
|
||||
value={euroFormatter.format(stats.openRevenueCents / 100)}
|
||||
description="Noch nicht abgerechnete Nutzungen"
|
||||
/>
|
||||
<StatCard
|
||||
title="Abrechnungen im Zeitraum"
|
||||
value={String(stats.finalizedReports)}
|
||||
description="Finalisierte Nutzungsnachweise"
|
||||
/>
|
||||
<StatCard
|
||||
title="Collab-Quote"
|
||||
value={kpis.newUsages > 0 ? `${Math.round((kpis.collabUsages / kpis.newUsages) * 100)} %` : "0 %"}
|
||||
description="Anteil kostenfreier Collab-Nutzungen"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card
|
||||
title={`Aktivität der letzten ${days} Tage`}
|
||||
description="Downloads und Album-Aufrufe pro Tag über alle Redaktionen."
|
||||
>
|
||||
{hasActivity ? (
|
||||
<BarChart
|
||||
data={activityData}
|
||||
variant="multiple"
|
||||
seriesLabels={["Downloads", "Album-Aufrufe"]}
|
||||
size="lg"
|
||||
appearance="rich"
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="Noch keine Aktivität"
|
||||
description="Downloads und Aufrufe erscheinen hier, sobald Redaktionen das Portal nutzen."
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Suchen pro Tag" description="Suchanfragen in Alben und über alle Alben.">
|
||||
{stats.daily.some((day) => day.searches > 0) ? (
|
||||
<BarChart data={searchData} seriesLabels={["Suchen"]} size="md" />
|
||||
) : (
|
||||
<EmptyState title="Keine Suchen" description="Im Zeitraum wurden keine Suchen erfasst." />
|
||||
)}
|
||||
</Card>
|
||||
<Card title="Umsatz pro Tag" description="Netto-Umsatz aus neuen Nutzungen in Euro.">
|
||||
{stats.daily.some((day) => day.revenueCents > 0) ? (
|
||||
<BarChart data={revenueData} seriesLabels={["Umsatz (€)"]} size="md" />
|
||||
) : (
|
||||
<EmptyState title="Kein Umsatz" description="Im Zeitraum wurden keine neuen Nutzungen erfasst." />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Redaktionen im Zeitraum" description="Nach Downloads sortiert.">
|
||||
{stats.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: "collab", header: "Collab", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
{ key: "views", header: "Aufrufe", align: "right" },
|
||||
{ key: "searches", header: "Suchen", align: "right" },
|
||||
]}
|
||||
rows={stats.topEditorials.map((row) => ({
|
||||
id: row.editorialId,
|
||||
name: (
|
||||
<Link
|
||||
href={`/admin/redaktionen/${row.editorialId}`}
|
||||
className="font-medium text-[var(--color-brand-fg)] hover:underline"
|
||||
>
|
||||
{row.name}
|
||||
</Link>
|
||||
),
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
collab: row.collabUsages > 0 ? <Badge variant="neutral">{row.collabUsages}</Badge> : <span className="tabular-nums">0</span>,
|
||||
revenue: <span className="tabular-nums">{euroFormatter.format(row.revenueCents / 100)}</span>,
|
||||
views: <span className="tabular-nums">{row.views}</span>,
|
||||
searches: <span className="tabular-nums">{row.searches}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="Alben im Zeitraum" description="Nach Downloads und Aufrufen sortiert.">
|
||||
{stats.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" },
|
||||
{ key: "views", header: "Aufrufe", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
]}
|
||||
rows={stats.topAlbums.map((row) => ({
|
||||
id: row.albumKey,
|
||||
albumName: row.albumName,
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
views: <span className="tabular-nums">{row.views}</span>,
|
||||
revenue: <span className="tabular-nums">{euroFormatter.format(row.revenueCents / 100)}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card title="Letzte Aktivitäten" description="Die neuesten erfassten Aktionen der Redaktionen.">
|
||||
{stats.recentActivity.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Noch keine Aktivitäten erfasst"
|
||||
description="Aufrufe und Suchen werden ab Version 2.2 gezählt."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{stats.recentActivity.map((event) => (
|
||||
<li key={event.id} className="flex flex-wrap items-center gap-3 py-2.5 text-sm">
|
||||
<Badge variant="neutral">{ACTIVITY_LABELS[event.eventType] ?? event.eventType}</Badge>
|
||||
<span className="font-medium">{event.editorialName}</span>
|
||||
{event.query ? <span className="text-[var(--color-fg-muted)]">„{event.query}“</span> : null}
|
||||
<time
|
||||
className="ml-auto text-xs tabular-nums text-[var(--color-fg-muted)]"
|
||||
dateTime={event.occurredAt.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{event.occurredAt.toLocaleString("de-DE", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</time>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function trendProps(change: number | null): { delta?: string; trend?: "up" | "down" | "flat" } {
|
||||
if (change === null) return {};
|
||||
return {
|
||||
delta: `${change > 0 ? "+" : ""}${change} %`,
|
||||
trend: change > 0 ? "up" : change < 0 ? "down" : "flat",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
import { useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
export function DeleteReleaseNoteButton({
|
||||
action,
|
||||
noteId,
|
||||
}: Readonly<{
|
||||
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
|
||||
noteId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
useResultToast(state, "Versionshinweis gelöscht.");
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
<input type="hidden" name="noteId" value={noteId} />
|
||||
<Button type="submit" variant="outline" size="sm" disabled={pending}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Input, Textarea } from "@sakaniui/react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function ReleaseNoteForm({
|
||||
action,
|
||||
}: Readonly<{
|
||||
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
|
||||
}>) {
|
||||
const versionId = useId();
|
||||
const bodyId = useId();
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [body, setBody] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setBody("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="Neuer Versionshinweis">
|
||||
<form action={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4 sm:flex-row">
|
||||
<div className="sm:w-36">
|
||||
<Input id={versionId} label="Version" name="version" placeholder="z. B. 2.1.1" required />
|
||||
</div>
|
||||
<div className="sm:w-48">
|
||||
<FormSelect
|
||||
defaultValue="editorial"
|
||||
label="Zielgruppe"
|
||||
name="audience"
|
||||
options={[
|
||||
{ label: "Redaktionen", value: "editorial" },
|
||||
{ label: "Admins", value: "admin" },
|
||||
{ label: "Beide", value: "both" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Textarea
|
||||
description={`${body.length}/2000 Zeichen`}
|
||||
id={bodyId}
|
||||
label="Hinweis"
|
||||
maxLength={2000}
|
||||
name="body"
|
||||
onChange={(event) => setBody(event.target.value)}
|
||||
placeholder="Was ist neu in dieser Version?"
|
||||
required
|
||||
rows={4}
|
||||
value={body}
|
||||
/>
|
||||
<div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird veröffentlicht …" : "Hinweis veröffentlichen"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import {
|
||||
ReleaseNoteServiceError,
|
||||
releaseNoteService,
|
||||
type ReleaseNoteAudience,
|
||||
} from "@/modules/releases/service";
|
||||
|
||||
export type ReleaseNoteActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createReleaseNoteAction(
|
||||
_prevState: ReleaseNoteActionResult,
|
||||
formData: FormData,
|
||||
): Promise<ReleaseNoteActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const version = formData.get("version");
|
||||
const audience = formData.get("audience");
|
||||
const body = formData.get("body");
|
||||
|
||||
if (typeof version !== "string" || typeof body !== "string") {
|
||||
return { ok: false, message: "Bitte Version und Text ausfüllen." };
|
||||
}
|
||||
if (audience !== "admin" && audience !== "editorial" && audience !== "both") {
|
||||
return { ok: false, message: "Bitte Zielgruppe wählen." };
|
||||
}
|
||||
|
||||
try {
|
||||
await releaseNoteService.createReleaseNote({
|
||||
version,
|
||||
audience: audience as ReleaseNoteAudience,
|
||||
body,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: releaseNoteErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/versionen");
|
||||
revalidatePath("/redaktion/neuigkeiten");
|
||||
return { ok: true, message: "Versionshinweis veröffentlicht." };
|
||||
}
|
||||
|
||||
export async function deleteReleaseNoteAction(
|
||||
_prevState: ReleaseNoteActionResult,
|
||||
formData: FormData,
|
||||
): Promise<ReleaseNoteActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const noteId = formData.get("noteId");
|
||||
if (typeof noteId !== "string" || noteId.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await releaseNoteService.deleteReleaseNote({ id: noteId, adminUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: releaseNoteErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/versionen");
|
||||
revalidatePath("/redaktion/neuigkeiten");
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
|
||||
function releaseNoteErrorMessage(error: unknown): string {
|
||||
if (error instanceof ReleaseNoteServiceError) {
|
||||
const messages: Record<ReleaseNoteServiceError["code"], string> = {
|
||||
INVALID_VERSION: "Bitte eine Version wie 2.1 oder 2.1.1 angeben.",
|
||||
INVALID_BODY: "Bitte einen Text mit 1 bis 2000 Zeichen eingeben.",
|
||||
INVALID_AUDIENCE: "Bitte Zielgruppe wählen.",
|
||||
DUPLICATE_RELEASE_NOTE: "Für diese Version und Zielgruppe gibt es bereits einen Hinweis.",
|
||||
RELEASE_NOTE_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,38 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { ReleaseHistory } from "@/modules/releases/release-history";
|
||||
import { releaseNoteService } from "@/modules/releases/service";
|
||||
|
||||
import { DeleteReleaseNoteButton } from "./DeleteReleaseNoteButton";
|
||||
import { ReleaseNoteForm } from "./ReleaseNoteForm";
|
||||
import { createReleaseNoteAction, deleteReleaseNoteAction } from "./actions";
|
||||
|
||||
export default async function AdminVersionsPage() {
|
||||
const notes = await releaseNoteService.listReleaseNotes();
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Portal"
|
||||
title="Versionshinweise"
|
||||
description="Was sich im Portal geändert hat, getrennt nach Zielgruppe. Redaktionen sehen ihre Hinweise unter Neuigkeiten. Jede Veröffentlichung im Portal bekommt hier einen Eintrag und eine fortlaufende Versionsnummer."
|
||||
/>
|
||||
|
||||
<ReleaseNoteForm action={createReleaseNoteAction} />
|
||||
|
||||
<section className="flex flex-col gap-4" aria-labelledby="release-notes-list-title">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h2 id="release-notes-list-title" className="text-xl font-semibold">
|
||||
Versionshistorie
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">{notes.length} Einträge</p>
|
||||
</div>
|
||||
|
||||
<ReleaseHistory
|
||||
notes={notes}
|
||||
renderAction={(note) => <DeleteReleaseNoteButton action={deleteReleaseNoteAction} noteId={note.id} />}
|
||||
showAudience
|
||||
/>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { recordActivity } from "@/modules/activity/service";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
|
||||
// Client beacon for lightbox views. Album views and searches are recorded
|
||||
// server-side in the pages themselves; this endpoint only accepts lightbox_view.
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await requireActiveEditorial(request.headers);
|
||||
const body = (await request.json().catch(() => null)) as {
|
||||
type?: unknown;
|
||||
albumId?: unknown;
|
||||
assetId?: unknown;
|
||||
} | null;
|
||||
if (!body || body.type !== "lightbox_view") {
|
||||
return Response.json({ code: "INVALID_REQUEST" }, { status: 400 });
|
||||
}
|
||||
await recordActivity({
|
||||
editorialId: principal.editorialId,
|
||||
type: "lightbox_view",
|
||||
...(typeof body.albumId === "string" ? { albumId: body.albumId } : {}),
|
||||
...(typeof body.assetId === "string" ? { assetId: body.assetId } : {}),
|
||||
});
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof CrossOriginRequestError) {
|
||||
return Response.json({ code: "CROSS_ORIGIN_REQUEST" }, { status: 403 });
|
||||
}
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return Response.json(
|
||||
{ code: "FORBIDDEN" },
|
||||
{ status: error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403 },
|
||||
);
|
||||
}
|
||||
return Response.json({ code: "REQUEST_FAILED" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
uploadInvoice,
|
||||
resendInvoice,
|
||||
getInvoicePdf,
|
||||
InvoiceError,
|
||||
INVOICE_PDF_MAX_BYTES,
|
||||
} from "@/modules/billing/invoice";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { invoiceUploadPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
|
||||
type InvoiceRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
|
||||
|
||||
type InvoiceHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
uploadInvoice: typeof uploadInvoice;
|
||||
resendInvoice: typeof resendInvoice;
|
||||
getInvoicePdf: typeof getInvoicePdf;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
export function createInvoiceUploadHandler(dependencies: InvoiceHandlerDependencies) {
|
||||
return async function POST(request: Request, context: InvoiceRouteContext): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireAdmin(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`invoice-upload:${principal.userId}`,
|
||||
invoiceUploadPolicy,
|
||||
);
|
||||
const { reportId } = await context.params;
|
||||
|
||||
const formData = await request.formData().catch(() => null);
|
||||
const file = formData?.get("invoice");
|
||||
if (!(file instanceof File)) return jsonError(400, "INVALID_REQUEST");
|
||||
if (file.size === 0 || file.size > INVOICE_PDF_MAX_BYTES) {
|
||||
return jsonError(400, "INVALID_PDF");
|
||||
}
|
||||
const bytes = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
const result = await dependencies.uploadInvoice({
|
||||
reportId,
|
||||
bytes,
|
||||
filename: file.name || "rechnung.pdf",
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
return Response.json(
|
||||
{ ok: true, emailStatus: result.emailStatus },
|
||||
{ status: 200, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createInvoiceResendHandler(dependencies: InvoiceHandlerDependencies) {
|
||||
return async function POST(request: Request, context: InvoiceRouteContext): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireAdmin(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`invoice-upload:${principal.userId}`,
|
||||
invoiceUploadPolicy,
|
||||
);
|
||||
const { reportId } = await context.params;
|
||||
const result = await dependencies.resendInvoice({
|
||||
reportId,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
return Response.json(
|
||||
{ ok: true, emailStatus: result.emailStatus },
|
||||
{ status: 200, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createInvoiceGetHandler(dependencies: InvoiceHandlerDependencies) {
|
||||
return async function GET(request: Request, context: InvoiceRouteContext): Promise<Response> {
|
||||
try {
|
||||
await dependencies.requireAdmin(request.headers);
|
||||
const { reportId } = await context.params;
|
||||
const invoice = await dependencies.getInvoicePdf(reportId);
|
||||
if (!invoice) {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
const filename = invoice.filename.replace(/[^\w.\-]/g, "_");
|
||||
return new Response(new Uint8Array(invoice.bytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": `attachment; filename="${filename}"`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function mappedError(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 PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof InvoiceError) {
|
||||
switch (error.code) {
|
||||
case "REPORT_NOT_FOUND":
|
||||
return jsonError(404, "REPORT_NOT_FOUND");
|
||||
case "REPORT_NOT_FINAL":
|
||||
return jsonError(409, "REPORT_NOT_FINAL");
|
||||
case "INVALID_PDF":
|
||||
return jsonError(400, "INVALID_PDF");
|
||||
case "INVOICE_NOT_UPLOADED":
|
||||
return jsonError(409, "INVOICE_NOT_UPLOADED");
|
||||
case "EDITORIAL_NOT_FOUND":
|
||||
return jsonError(404, "EDITORIAL_NOT_FOUND");
|
||||
}
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(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 });
|
||||
}
|
||||
|
||||
const dependencies: InvoiceHandlerDependencies = {
|
||||
requireAdmin,
|
||||
uploadInvoice,
|
||||
resendInvoice,
|
||||
getInvoicePdf,
|
||||
consumeRateLimit,
|
||||
};
|
||||
|
||||
export const invoiceUploadHandler = createInvoiceUploadHandler(dependencies);
|
||||
export const invoiceResendHandler = createInvoiceResendHandler(dependencies);
|
||||
export const invoiceGetHandler = createInvoiceGetHandler(dependencies);
|
||||
@@ -0,0 +1,3 @@
|
||||
import { invoiceResendHandler } from "../invoice-handler";
|
||||
|
||||
export const POST = invoiceResendHandler;
|
||||
@@ -0,0 +1,4 @@
|
||||
import { invoiceGetHandler, invoiceUploadHandler } from "./invoice-handler";
|
||||
|
||||
export const POST = invoiceUploadHandler;
|
||||
export const GET = invoiceGetHandler;
|
||||
@@ -8,11 +8,6 @@ import {
|
||||
} from "@/modules/billing/reports";
|
||||
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { emailService } from "@/modules/email/service";
|
||||
import { getReportPdf } from "@/modules/billing/reports";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const finalizePayload = z
|
||||
.object({
|
||||
@@ -51,34 +46,9 @@ export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies)
|
||||
flatrateCentsSnapshot: null,
|
||||
});
|
||||
|
||||
// Email dispatch
|
||||
try {
|
||||
const [editorial] = await db
|
||||
.select({ email: editorialAccounts.loginEmail })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, editorialId))
|
||||
.limit(1);
|
||||
|
||||
if (editorial?.email) {
|
||||
const reportPdf = await getReportPdf(result.reportId);
|
||||
if (reportPdf) {
|
||||
const periodString = month
|
||||
? `${month.toString().padStart(2, "0")}/${year}`
|
||||
: `Q${quarter}/${year}`;
|
||||
|
||||
// Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background)
|
||||
await emailService.sendBillingReport(
|
||||
editorial.email,
|
||||
periodString,
|
||||
reportPdf.bytes,
|
||||
result.reportNumber
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (emailError) {
|
||||
console.error("Failed to send billing email:", emailError);
|
||||
// Do not fail the request if email fails
|
||||
}
|
||||
// No email here: the admin reviews the Nutzungsnachweis (and can fix
|
||||
// collab/wrong positions via cancel + re-finalize), then uploads the
|
||||
// invoice PDF. That upload sends invoice + Nutzungsnachweis bundled.
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
|
||||
@@ -20,6 +20,7 @@ const newUsagePayload = z
|
||||
purpose: z.string(),
|
||||
reference: z.string().optional(),
|
||||
idempotencyKey: z.string(),
|
||||
collab: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
@@ -65,6 +66,7 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
|
||||
? {}
|
||||
: { reference: payload.data.reference }),
|
||||
idempotencyKey: payload.data.idempotencyKey,
|
||||
...(payload.data.collab === true ? { collab: true } : {}),
|
||||
})
|
||||
: await dependencies.createRepeatDownload({
|
||||
editorialId: principal.editorialId,
|
||||
@@ -125,6 +127,8 @@ function mappedError(error: unknown): Response {
|
||||
return errorResponse(422, "INVALID_ASSET");
|
||||
case "EDITORIAL_NOT_ACTIVE":
|
||||
return errorResponse(403, "FORBIDDEN");
|
||||
case "COLLAB_NOT_ENABLED":
|
||||
return errorResponse(403, "COLLAB_NOT_ENABLED");
|
||||
case "INVALID_PRICE":
|
||||
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createDownloadIntentHandler } from "./intent-handler";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||
@@ -159,3 +160,46 @@ test("returns retry-after without creating an intent when the editorial limit is
|
||||
);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("passes the collab flag through to the usage service", async () => {
|
||||
const deps = dependencies();
|
||||
deps.createNewUsage.mockResolvedValue({
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
priceCents: 0,
|
||||
billable: true,
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
});
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Collab Strecke",
|
||||
idempotencyKey,
|
||||
collab: true,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deps.createNewUsage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ editorialId, collab: true }),
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ priceCents: 0 });
|
||||
});
|
||||
|
||||
test("maps COLLAB_NOT_ENABLED to 403 with a stable code", async () => {
|
||||
const deps = dependencies();
|
||||
deps.createNewUsage.mockRejectedValue(new UsageAccountingError("COLLAB_NOT_ENABLED"));
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Collab Strecke",
|
||||
idempotencyKey,
|
||||
collab: true,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
await expect(response.json()).resolves.toEqual({ code: "COLLAB_NOT_ENABLED" });
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
@@ -10,6 +11,7 @@ type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string
|
||||
type DownloadFileHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
repository: typeof downloadDeliveryRepository;
|
||||
assertOriginalAccess: typeof assertOriginalAccess;
|
||||
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
|
||||
};
|
||||
|
||||
@@ -35,6 +37,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
|
||||
|
||||
let original: ImmichBinary;
|
||||
try {
|
||||
await dependencies.assertOriginalAccess(
|
||||
principal.editorialId, claim.download.assetId, claim.download.albumId,
|
||||
);
|
||||
original = await dependencies.immich.getOriginal(
|
||||
claim.download.assetId,
|
||||
request.signal,
|
||||
@@ -163,5 +168,6 @@ function jsonError(status: number, code: string): Response {
|
||||
export const authorizedDownloadFileHandler = createDownloadFileHandler({
|
||||
requireActiveEditorial,
|
||||
repository: downloadDeliveryRepository,
|
||||
assertOriginalAccess,
|
||||
immich: immichClient,
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { contentDisposition, createDownloadFileHandler } from "./download-handle
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "66666666-6666-4666-8666-666666666666";
|
||||
const downloadId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const assetId = "55555555-5555-4555-8555-555555555555";
|
||||
@@ -48,6 +49,7 @@ function dependencies(options: {
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
albumId,
|
||||
filename: "snapshot.jpg",
|
||||
intentKind: options.intentKind ?? "new_usage",
|
||||
},
|
||||
@@ -63,6 +65,7 @@ function dependencies(options: {
|
||||
return { editorialId };
|
||||
}),
|
||||
repository,
|
||||
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
|
||||
immich: {
|
||||
getOriginal: vi.fn().mockImplementation(async () => {
|
||||
if (options.originalError) throw options.originalError;
|
||||
@@ -226,3 +229,18 @@ test("returns stable authentication semantics without exposing guard details", a
|
||||
expect(second.status).toBe(403);
|
||||
expect(await second.text()).not.toContain("SUSPENDED");
|
||||
});
|
||||
|
||||
test.each(["new_usage", "repeat_download"] as const)(
|
||||
"denies a previously authorized %s after album access is lost",
|
||||
async (intentKind) => {
|
||||
const deps = dependencies({ intentKind });
|
||||
deps.assertOriginalAccess.mockRejectedValue(new Error("access lost"));
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
expect(response.status).toBe(503);
|
||||
expect(deps.assertOriginalAccess).toHaveBeenCalledWith(editorialId, assetId, albumId);
|
||||
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: intentKind === "new_usage",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,8 @@
|
||||
import { PassThrough, type Readable as NodeReadable } from "node:stream";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
@@ -37,10 +39,9 @@ function fakeArchive(): BulkArchive {
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
assertOriginalAccess: vi.fn().mockResolvedValue(undefined),
|
||||
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" }),
|
||||
findAttempt: vi.fn().mockResolvedValue(undefined),
|
||||
getOriginal: vi.fn().mockResolvedValue({
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
@@ -62,6 +63,7 @@ function dependencies() {
|
||||
id: downloadId,
|
||||
usageId: "55555555-5555-4555-8555-555555555555",
|
||||
assetId,
|
||||
albumId,
|
||||
filename: "foto.jpg",
|
||||
intentKind: "new_usage",
|
||||
},
|
||||
@@ -75,11 +77,20 @@ function dependencies() {
|
||||
};
|
||||
}
|
||||
|
||||
function request(origin = "http://portal.test", assetIds = [assetId]) {
|
||||
const usageId = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
function request(origin = "http://portal.test", assetIds = [assetId], repeatUsageId?: string) {
|
||||
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" }),
|
||||
body: JSON.stringify({
|
||||
items: assetIds.map((id) => ({
|
||||
assetId: id,
|
||||
idempotencyKey: id,
|
||||
...(repeatUsageId ? { usageId: repeatUsageId } : { purpose: "Titelgeschichte", albumId }),
|
||||
})),
|
||||
maxPriceCents: 1500,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -122,8 +133,6 @@ test("rate-limits bulk creation before usages are opened", async () => {
|
||||
|
||||
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"));
|
||||
@@ -137,3 +146,88 @@ test("settles an already claimed first item when preparation of a later item fai
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("denies original bytes when a ZIP entry loses album access after preparation", async () => {
|
||||
const deps = dependencies();
|
||||
deps.assertOriginalAccess.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("grant revoked"));
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
await expect(response.arrayBuffer()).rejects.toThrow();
|
||||
expect(deps.assertOriginalAccess).toHaveBeenNthCalledWith(2, editorialId, assetId, albumId);
|
||||
expect(deps.getOriginal).not.toHaveBeenCalled();
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("books a new purpose when explicitly selected despite an eligible older usage", async () => {
|
||||
const deps = dependencies();
|
||||
deps.listPriorUsages.mockResolvedValue([{ id: usageId }]);
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
await response.arrayBuffer();
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
expect(deps.createNewUsage).toHaveBeenCalledWith({
|
||||
editorialId, assetId, albumId, purpose: "Titelgeschichte", maxPriceCents: 1500,
|
||||
idempotencyKey: assetId,
|
||||
});
|
||||
});
|
||||
|
||||
test("uses a specifically selected previous usage for a free repeat", async () => {
|
||||
const deps = dependencies();
|
||||
deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }, { id: usageId }]);
|
||||
deps.createRepeatDownload.mockResolvedValue({ id: downloadId });
|
||||
const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId));
|
||||
await response.arrayBuffer();
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
expect(deps.createRepeatDownload).toHaveBeenCalledWith({ editorialId, usageId, idempotencyKey: assetId });
|
||||
});
|
||||
|
||||
test("rejects a repeat that does not belong to the selected editorial and image", async () => {
|
||||
const deps = dependencies();
|
||||
deps.listPriorUsages.mockResolvedValue([{ id: "other-usage" }]);
|
||||
const response = await createBulkDownloadHandler(deps)(request(undefined, undefined, usageId));
|
||||
expect(response.status).toBe(404);
|
||||
expect(deps.listPriorUsages).toHaveBeenCalledWith(editorialId, assetId);
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
expect(deps.getOriginal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects duplicate image selections before any bookings", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await createBulkDownloadHandler(deps)(request(undefined, [assetId, assetId]));
|
||||
expect(response.status).toBe(400);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("retries a confirmed zero-byte void with a stable successor key", async () => {
|
||||
const deps = dependencies();
|
||||
deps.findAttempt.mockResolvedValueOnce({
|
||||
id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte",
|
||||
status: "failed_before_delivery", transferredBytes: 0, billingStatus: "voided",
|
||||
});
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
expect(response.status).toBe(200);
|
||||
await response.arrayBuffer();
|
||||
expect(deps.createNewUsage).toHaveBeenCalledWith(expect.objectContaining({ idempotencyKey: downloadId }));
|
||||
expect(deps.findAttempt).toHaveBeenNthCalledWith(2, editorialId, downloadId);
|
||||
});
|
||||
|
||||
test("keeps an interrupted delivery booked and does not retry it as a new usage", async () => {
|
||||
const deps = dependencies();
|
||||
deps.findAttempt.mockResolvedValueOnce({
|
||||
id: downloadId, assetId, usageId, kind: "new_usage", purpose: "Titelgeschichte",
|
||||
status: "interrupted", transferredBytes: 100, billingStatus: "open",
|
||||
});
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
expect(response.status).toBe(409);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
expect(deps.getOriginal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does not create a new booking for a ZIP album that is no longer granted", async () => {
|
||||
const deps = dependencies();
|
||||
deps.assertOriginalAccess.mockRejectedValue(new UsageAccountingError("ALBUM_NOT_GRANTED"));
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
expect(response.status).toBe(404);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
expect(deps.getOriginal).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import type { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
createBulkDeliveryAccounting,
|
||||
@@ -15,7 +17,11 @@ import {
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
import {
|
||||
UsageAccountingError,
|
||||
type CreateNewUsageInput,
|
||||
type CreateRepeatDownloadInput,
|
||||
} from "@/modules/usages/types";
|
||||
|
||||
export type BulkArchive = {
|
||||
pipe(destination: PassThrough): unknown;
|
||||
@@ -24,41 +30,35 @@ export type BulkArchive = {
|
||||
abort(): unknown;
|
||||
};
|
||||
|
||||
type BulkAttempt = {
|
||||
id: string;
|
||||
assetId: string;
|
||||
usageId: string;
|
||||
kind: string;
|
||||
purpose: string;
|
||||
status: string;
|
||||
transferredBytes: number | null;
|
||||
billingStatus: string;
|
||||
};
|
||||
|
||||
type BulkDownloadHandlerDependencies = {
|
||||
findAttempt(editorialId: string, key: string): Promise<BulkAttempt | undefined>;
|
||||
assertOriginalAccess: typeof assertOriginalAccess;
|
||||
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 }>;
|
||||
createNewUsage(input: CreateNewUsageInput): Promise<{ id: string }>;
|
||||
createRepeatDownload(input: CreateRepeatDownloadInput): Promise<{ id: string }>;
|
||||
repository: DownloadDeliveryRepository;
|
||||
createArchive(): BulkArchive;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
type PreparedDownload = {
|
||||
albumId: string;
|
||||
assetId: string;
|
||||
downloadId: string;
|
||||
filename: string;
|
||||
@@ -75,37 +75,28 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = await parsePayload(request);
|
||||
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
|
||||
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
|
||||
const items = [];
|
||||
for (const item of payload.items) {
|
||||
const idempotencyKey = await resolveRetryKey(dependencies, principal.editorialId, item);
|
||||
items.push({ ...item, idempotencyKey });
|
||||
}
|
||||
const accounting = createBulkDeliveryAccounting(dependencies.repository);
|
||||
let downloads: PreparedDownload[];
|
||||
const 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,
|
||||
});
|
||||
},
|
||||
);
|
||||
for (const item of items) {
|
||||
const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents, payload.collab === true);
|
||||
const claim = await dependencies.repository.claimAuthorized(principal.editorialId, intent.id);
|
||||
if (claim.outcome !== "claimed") throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
|
||||
const { albumId, assetId, filename, intentKind } = claim.download;
|
||||
accounting.track({ downloadId: intent.id, intentKind });
|
||||
downloads.push({ albumId, assetId, filename, downloadId: intent.id });
|
||||
}
|
||||
} 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);
|
||||
@@ -125,7 +116,10 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
passThrough,
|
||||
downloads,
|
||||
requestSignal: request.signal,
|
||||
getOriginal: dependencies.getOriginal,
|
||||
async getOriginal(item, signal) {
|
||||
await dependencies.assertOriginalAccess(principal.editorialId, item.assetId, item.albumId);
|
||||
return dependencies.getOriginal(item.assetId, signal);
|
||||
},
|
||||
accounting,
|
||||
});
|
||||
|
||||
@@ -143,7 +137,6 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[bulk-download] failed:", error);
|
||||
return mappedBulkError(error);
|
||||
}
|
||||
};
|
||||
@@ -161,13 +154,13 @@ async function produceArchive({
|
||||
passThrough: PassThrough;
|
||||
downloads: PreparedDownload[];
|
||||
requestSignal: AbortSignal;
|
||||
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
|
||||
getOriginal(item: PreparedDownload, signal: AbortSignal): Promise<{ body: ReadableStream<Uint8Array> }>;
|
||||
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 original = await getOriginal(item, requestSignal);
|
||||
const source = Readable.fromWeb(
|
||||
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
|
||||
);
|
||||
@@ -192,99 +185,84 @@ async function produceArchive({
|
||||
}
|
||||
}
|
||||
|
||||
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: [] };
|
||||
}
|
||||
const uuid = z.uuid().transform((value) => value.toLowerCase());
|
||||
const selectionFields = { assetId: uuid, idempotencyKey: uuid };
|
||||
const bulkPayload = z.strictObject({
|
||||
items: z.array(z.union([
|
||||
z.strictObject({ ...selectionFields, usageId: uuid }),
|
||||
z.strictObject({
|
||||
...selectionFields,
|
||||
albumId: uuid,
|
||||
purpose: z.string().trim().refine((value) => [...value].length >= 3 && [...value].length <= 200),
|
||||
}),
|
||||
);
|
||||
for (const album of albums) {
|
||||
for (const asset of album.items) {
|
||||
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
])).min(1).max(100),
|
||||
maxPriceCents: z.number().int().nonnegative(),
|
||||
collab: z.boolean().optional(),
|
||||
});
|
||||
|
||||
async function prepareDownloads(
|
||||
type Selection = z.output<typeof bulkPayload>["items"][number];
|
||||
|
||||
async function resolveRetryKey(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
payload: { assetIds: string[]; purpose: string },
|
||||
assetToGrantedAlbum: Map<string, string>,
|
||||
onPrepared: (item: PreparedDownload) => Promise<void>,
|
||||
item: Selection,
|
||||
) {
|
||||
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);
|
||||
let key = item.idempotencyKey;
|
||||
for (let attempt = 0; attempt < 16; attempt += 1) {
|
||||
const existing = await dependencies.findAttempt(editorialId, key);
|
||||
if (!existing) return key;
|
||||
|
||||
const repeat = "usageId" in item;
|
||||
const sameSelection = existing.assetId === item.assetId && (repeat
|
||||
? existing.kind === "repeat_download" && existing.usageId === item.usageId
|
||||
: existing.kind === "new_usage" && existing.purpose === item.purpose);
|
||||
if (sameSelection && existing.status === "authorized") return key;
|
||||
|
||||
if (!sameSelection || existing.status !== "failed_before_delivery" ||
|
||||
existing.transferredBytes !== 0 || (!repeat && existing.billingStatus !== "voided")) {
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
// Everyone retrying the same voided attempt converges on one new key.
|
||||
key = existing.id;
|
||||
}
|
||||
return downloads;
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
|
||||
async function createIntent(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
item: Selection,
|
||||
maxPriceCents: number,
|
||||
collab: boolean,
|
||||
) {
|
||||
if ("usageId" in item) {
|
||||
const prior = await dependencies.listPriorUsages(editorialId, item.assetId);
|
||||
if (!prior.some(({ id }) => id === item.usageId)) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
return dependencies.createRepeatDownload({
|
||||
editorialId, usageId: item.usageId, idempotencyKey: item.idempotencyKey,
|
||||
});
|
||||
}
|
||||
|
||||
await dependencies.assertOriginalAccess(editorialId, item.assetId, item.albumId);
|
||||
return dependencies.createNewUsage({
|
||||
...item,
|
||||
editorialId,
|
||||
maxPriceCents,
|
||||
...(collab ? { collab: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
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 parsed = bulkPayload.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) throw new UsageAccountingError("INVALID_INPUT");
|
||||
const { items } = parsed.data;
|
||||
if (new Set(items.map(({ assetId }) => assetId)).size !== items.length ||
|
||||
new Set(items.map(({ idempotencyKey }) => idempotencyKey)).size !== items.length) {
|
||||
throw new UsageAccountingError("INVALID_INPUT");
|
||||
}
|
||||
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() };
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
class BulkInputError extends Error {}
|
||||
|
||||
function safeArchiveFilename(value: string) {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
|
||||
@@ -293,13 +271,6 @@ function safeArchiveFilename(value: string) {
|
||||
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", {
|
||||
@@ -307,7 +278,6 @@ function mappedBulkError(error: unknown): Response {
|
||||
});
|
||||
}
|
||||
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");
|
||||
}
|
||||
@@ -322,6 +292,7 @@ function mappedBulkError(error: unknown): Response {
|
||||
USAGE_NOT_FOUND: 404,
|
||||
IMMICH_UNAVAILABLE: 503,
|
||||
EDITORIAL_NOT_ACTIVE: 403,
|
||||
COLLAB_NOT_ENABLED: 403,
|
||||
INVALID_PRICE: 409,
|
||||
};
|
||||
return jsonError(statusByCode[error.code] ?? 500, error.code);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { downloadEvents, usages } from "@/db/schema";
|
||||
import { assertOriginalAccess } from "@/modules/albums/photo-access";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
@@ -12,9 +16,24 @@ const archiver = require("archiver") as { ZipArchive: new (options: unknown) =>
|
||||
|
||||
export const POST = createBulkDownloadHandler({
|
||||
requireActiveEditorial,
|
||||
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
|
||||
searchPhotos: (input) => immichClient.searchPhotos(input),
|
||||
getAsset: (assetId) => immichClient.getAsset(assetId),
|
||||
async findAttempt(editorialId, key) {
|
||||
const [attempt] = await db.select({
|
||||
id: downloadEvents.id,
|
||||
assetId: downloadEvents.immichAssetId,
|
||||
usageId: downloadEvents.usageId,
|
||||
kind: downloadEvents.intentKind,
|
||||
purpose: usages.purpose,
|
||||
status: downloadEvents.status,
|
||||
transferredBytes: downloadEvents.transferredBytes,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(downloadEvents)
|
||||
.innerJoin(usages, and(eq(usages.id, downloadEvents.usageId), eq(usages.editorialAccountId, editorialId)))
|
||||
.where(and(eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.idempotencyKey, key)))
|
||||
.limit(1);
|
||||
return attempt;
|
||||
},
|
||||
assertOriginalAccess,
|
||||
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
|
||||
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
|
||||
createNewUsage: (input) => usageService.createNewUsage(input),
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { setUsageCollab, CollabAdminError } from "@/modules/usages/collab-admin";
|
||||
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";
|
||||
|
||||
const payloadSchema = z.object({ collab: z.boolean() }).strict();
|
||||
|
||||
type CollabRouteContext = Readonly<{ params: Promise<{ usageId: string }> }>;
|
||||
|
||||
type CollabHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
setUsageCollab: typeof setUsageCollab;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
export function createUsageCollabHandler(dependencies: CollabHandlerDependencies) {
|
||||
return async function POST(request: Request, context: CollabRouteContext): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireAdmin(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`usage-collab:${principal.userId}`,
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const { usageId } = await context.params;
|
||||
const parsed = payloadSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) return jsonError(400, "INVALID_REQUEST");
|
||||
|
||||
const result = await dependencies.setUsageCollab({
|
||||
usageId,
|
||||
collab: parsed.data.collab,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
return Response.json(
|
||||
{ ok: true, priceCents: result.priceCents },
|
||||
{ status: 200, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
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 PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof CollabAdminError) {
|
||||
switch (error.code) {
|
||||
case "USAGE_NOT_FOUND":
|
||||
return jsonError(404, "USAGE_NOT_FOUND");
|
||||
case "USAGE_NOT_EDITABLE":
|
||||
return jsonError(409, "USAGE_NOT_EDITABLE");
|
||||
case "INVALID_PRICE":
|
||||
return jsonError(409, "INVALID_PRICE");
|
||||
}
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function jsonError(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 });
|
||||
}
|
||||
|
||||
export const usageCollabHandler = createUsageCollabHandler({
|
||||
requireAdmin,
|
||||
setUsageCollab,
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { usageCollabHandler } from "./collab-handler";
|
||||
|
||||
export const POST = usageCollabHandler;
|
||||
+48
-15
@@ -180,29 +180,25 @@ body:has([data-app-shell]) .legal-footer {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
/* --- Photo overview: masonry grid + hover overlay + lightbox --------------
|
||||
Replaces the old contact-sheet (forced 3:2 tiles, object-fit: contain,
|
||||
permanent monospace caption strips). Each photo keeps its native aspect
|
||||
ratio via an inline `aspect-ratio` set from EXIF dimensions; the grid uses
|
||||
CSS columns for a dense masonry layout. Captions and actions appear on
|
||||
hover/focus, and a full-screen lightbox opens on click. */
|
||||
/* --- Photo overview: uniform grid + hover overlay + lightbox --------------
|
||||
Rows read left to right, then down (CSS grid, not columns: a masonry made
|
||||
people scroll up and down to follow the order). Every tile is 3:2 with
|
||||
object-fit: cover, so rows line up; the lightbox shows the full photo.
|
||||
Portraits keep their upper part (faces) via object-position. */
|
||||
.photo-gallery {
|
||||
columns: 4 17rem;
|
||||
column-gap: clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
|
||||
gap: clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
@media (max-width: 64rem) {
|
||||
.photo-gallery { columns: 3 14rem; }
|
||||
}
|
||||
@media (max-width: 48rem) {
|
||||
.photo-gallery { columns: 2 9rem; }
|
||||
.photo-gallery { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
.photo-tile {
|
||||
break-inside: avoid;
|
||||
margin: 0 0 clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.photo-tile-frame {
|
||||
@@ -212,7 +208,15 @@ body:has([data-app-shell]) .legal-footer {
|
||||
background: var(--contact-sheet);
|
||||
}
|
||||
|
||||
.photo-tile-skeleton {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.photo-tile-trigger {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -224,11 +228,13 @@ body:has([data-app-shell]) .legal-footer {
|
||||
}
|
||||
|
||||
.photo-tile-image {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
min-height: 6rem;
|
||||
aspect-ratio: 3 / 2;
|
||||
object-fit: cover;
|
||||
object-position: center 30%;
|
||||
background: var(--contact-sheet);
|
||||
transition: transform 200ms ease-out;
|
||||
}
|
||||
@@ -351,6 +357,18 @@ body:has([data-app-shell]) .legal-footer {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* Photographer description; plain React text, scrollable when long. */
|
||||
.lightbox-description {
|
||||
flex-basis: 100%;
|
||||
max-height: 24vh;
|
||||
margin: 0;
|
||||
overflow-y: auto;
|
||||
color: rgb(255 255 255 / 85%);
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre-line;
|
||||
}
|
||||
|
||||
.lightbox-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -698,3 +716,18 @@ body:has([data-app-shell]) .legal-footer {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Event calendar: German weekday labels ---------------------------------
|
||||
ponytail: Sakani's MonthCalendar hard-codes English weekday names and has
|
||||
no locale prop. With weekStartsOn={1} the row is always Mon..Sun, so the
|
||||
labels are swapped here. Breaks if Sakani renames its hashed "_weekdays_"
|
||||
class; drop this once Sakani ships a locale option. */
|
||||
.event-month [class*="_weekdays_"] > span { font-size: 0; }
|
||||
.event-month [class*="_weekdays_"] > span::after { font-size: 0.75rem; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(1)::after { content: "Mo"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(2)::after { content: "Di"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(3)::after { content: "Mi"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(4)::after { content: "Do"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(5)::after { content: "Fr"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(6)::after { content: "Sa"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(7)::after { content: "So"; }
|
||||
@@ -10,6 +10,7 @@ import "./globals.css";
|
||||
import { LegalFooter } from "@/components/layout/legal-footer";
|
||||
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { AppToaster } from "@/components/ui/feedback";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Redaktionsportal | Leon Tonhäuser",
|
||||
@@ -34,6 +35,7 @@ export default function RootLayout({ children }: Readonly<{ children: ReactNode
|
||||
{children}
|
||||
</div>
|
||||
<LegalFooter />
|
||||
<AppToaster />
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { Spinner } from "@/components/ui/sakani";
|
||||
import { Skeleton } from "@/components/ui/sakani";
|
||||
|
||||
export default function AlbumLoading() {
|
||||
return (
|
||||
<div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
|
||||
<Spinner size="sm" label="Fotos werden geladen." />
|
||||
<p>Fotos werden geladen.</p>
|
||||
<div aria-busy="true" aria-live="polite" className="flex flex-col gap-6">
|
||||
<span className="sr-only">Fotos werden geladen.</span>
|
||||
<Skeleton height={36} variant="rect" width={320} />
|
||||
<Skeleton height={96} variant="rect" />
|
||||
<ul className="photo-gallery">
|
||||
{Array.from({ length: 8 }, (_, index) => (
|
||||
<li className="aspect-[3/2]" key={index}>
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { recordActivity } from "@/modules/activity/service";
|
||||
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
|
||||
import { formatCount, PhotoPagination, PhotoSearchForm } from "@/modules/albums/catalog-content";
|
||||
import { filterPhotos, paginatePhotos } from "@/modules/albums/filter";
|
||||
import { filterPhotos, normalizeSort, paginatePhotos, sortPhotos } from "@/modules/albums/filter";
|
||||
import { PhotoGallery } from "@/modules/albums/photo-gallery";
|
||||
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
import { lightboxService } from "@/modules/lightbox/service";
|
||||
@@ -21,7 +22,7 @@ const ALBUM_FETCH_SIZE = 1000;
|
||||
|
||||
type AlbumPageProps = Readonly<{
|
||||
params: Promise<{ albumId: string }>;
|
||||
searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[] }>;
|
||||
searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[]; sortierung?: string | string[] }>;
|
||||
}>;
|
||||
|
||||
export default async function AlbumPage({ params, searchParams }: AlbumPageProps) {
|
||||
@@ -33,6 +34,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
||||
const format = singleValue(rawSearchParams.format);
|
||||
const jahr = singleValue(rawSearchParams.jahr);
|
||||
const sortierung = normalizeSort(singleValue(rawSearchParams.sortierung));
|
||||
const result = await loadAlbumPage({
|
||||
editorialId: principal.editorialId,
|
||||
albumId,
|
||||
@@ -40,6 +42,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
page: singleValue(rawSearchParams.page),
|
||||
format,
|
||||
jahr,
|
||||
sortierung,
|
||||
});
|
||||
|
||||
if (result.unavailable) {
|
||||
@@ -49,6 +52,13 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
notFound();
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
editorialId: principal.editorialId,
|
||||
type: query ? "search" : "album_view",
|
||||
albumId: result.album.id,
|
||||
...(query ? { query } : {}),
|
||||
});
|
||||
|
||||
return (
|
||||
<section aria-labelledby="album-title">
|
||||
<PageHeader
|
||||
@@ -65,17 +75,17 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
ariaLabel="Fotos in diesem Album durchsuchen"
|
||||
query={query}
|
||||
format={format}
|
||||
sortierung={sortierung}
|
||||
placeholder="Dieses Album durchsuchen …"
|
||||
/>
|
||||
<p aria-live="polite" className="my-4 text-sm text-[var(--color-fg-muted)]" role="status">
|
||||
{formatCount(result.page.total, "Foto")} gefunden
|
||||
</p>
|
||||
<PhotoGallery
|
||||
albumId={result.album.id}
|
||||
albumName={result.album.albumName}
|
||||
items={result.page.items}
|
||||
downloadOptions={result.downloadOptions}
|
||||
lightboxAssetIds={[...result.lightboxAssetIds]}
|
||||
lightboxAssetIds={result.page.items.filter(({ id }) => result.lightboxAssetIds.has(id)).map(({ id }) => id)}
|
||||
/>
|
||||
<PhotoPagination
|
||||
albumId={result.album.id}
|
||||
@@ -84,6 +94,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
query={query}
|
||||
format={format}
|
||||
jahr={jahr}
|
||||
sortierung={sortierung}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
@@ -96,6 +107,7 @@ async function loadAlbumPage({
|
||||
page,
|
||||
format,
|
||||
jahr,
|
||||
sortierung,
|
||||
}: {
|
||||
editorialId: string;
|
||||
albumId: string;
|
||||
@@ -103,6 +115,7 @@ async function loadAlbumPage({
|
||||
page: string | undefined;
|
||||
format?: string;
|
||||
jahr?: string;
|
||||
sortierung: ReturnType<typeof normalizeSort>;
|
||||
}) {
|
||||
try {
|
||||
const albums = await albumCatalog.getVisibleAlbums(editorialId);
|
||||
@@ -121,7 +134,7 @@ async function loadAlbumPage({
|
||||
// total, the page slice, and the has-more-pages signal all reflect the
|
||||
// active filters. The old code filtered a single 60-item page client-side,
|
||||
// which silently dropped matching photos and reported the unfiltered total.
|
||||
const filtered = filterPhotos(results.items, { format, jahr });
|
||||
const filtered = sortPhotos(filterPhotos(results.items, { format, jahr }), sortierung);
|
||||
const { result: resultPage, currentPage } = paginatePhotos(filtered, page, PHOTO_PAGE_SIZE);
|
||||
|
||||
const downloadOptions = await loadEditorialDownloadOptions(
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
import { Spinner } from "@/components/ui/sakani";
|
||||
import { Skeleton } from "@/components/ui/sakani";
|
||||
|
||||
// Sakani's Skeleton sizes itself via width/height props (its CSS outranks
|
||||
// Tailwind sizing classes on its root).
|
||||
export default function AlbumsLoading() {
|
||||
return (
|
||||
<div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
|
||||
<Spinner size="sm" label="Alben werden geladen." />
|
||||
<p>Alben werden geladen.</p>
|
||||
<div aria-busy="true" aria-live="polite" className="flex flex-col gap-6">
|
||||
<span className="sr-only">Alben werden geladen.</span>
|
||||
<Skeleton height={36} variant="rect" width={256} />
|
||||
<Skeleton height={96} variant="rect" />
|
||||
<ul className="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<li className="flex flex-col gap-3" key={index}>
|
||||
<div className="aspect-[3/2] w-full">
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</div>
|
||||
<Skeleton width={64} />
|
||||
<Skeleton width="75%" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { recordActivity } from "@/modules/activity/service";
|
||||
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
|
||||
import { AlbumContactSheet, formatCount, PageLinks, PhotoSearchForm } from "@/modules/albums/catalog-content";
|
||||
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
|
||||
import { UrlPagination } from "@/components/ui/url-pagination";
|
||||
import { AlbumContactSheet, formatCount, PhotoSearchForm } from "@/modules/albums/catalog-content";
|
||||
import { filterPhotos, normalizeSort, paginatePhotos, sortPhotos, type InAppPage, type PhotoSort } from "@/modules/albums/filter";
|
||||
import { PhotoGallery } from "@/modules/albums/photo-gallery";
|
||||
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
|
||||
import { announcementService } from "@/modules/announcements/service";
|
||||
@@ -15,12 +17,13 @@ import { requireEditorial } from "../access";
|
||||
// up to 1000 matching photos, then filters/paginates in-app.
|
||||
const SEARCH_FETCH_SIZE = 1000;
|
||||
|
||||
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[] }> }) {
|
||||
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[]; sortierung?: string | string[] }> }) {
|
||||
const principal = await requireEditorial();
|
||||
const rawSearchParams = await searchParams;
|
||||
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
||||
const format = singleValue(rawSearchParams.format);
|
||||
const jahr = singleValue(rawSearchParams.jahr);
|
||||
const sortierung = normalizeSort(singleValue(rawSearchParams.sortierung));
|
||||
const hints = await announcementService.listActiveAnnouncements(new Date());
|
||||
|
||||
if (query) {
|
||||
@@ -33,12 +36,14 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumCatalogError && error.code === "RATE_LIMITED") {
|
||||
return <SearchRateLimited query={query} format={format} jahr={jahr} />;
|
||||
return <SearchRateLimited query={query} format={format} jahr={jahr} sortierung={sortierung} />;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const filtered = filterPhotos(results.items, { format, jahr });
|
||||
await recordActivity({ editorialId: principal.editorialId, type: "search", query });
|
||||
|
||||
const filtered = sortPhotos(filterPhotos(results.items, { format, jahr }), sortierung);
|
||||
const { result: page, currentPage } = paginatePhotos(filtered, singleValue(rawSearchParams.page), PHOTO_PAGE_SIZE);
|
||||
|
||||
const downloadOptions = await loadEditorialDownloadOptions(
|
||||
@@ -52,7 +57,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
<section className="flex flex-col gap-6" aria-labelledby="albums-title">
|
||||
<PageHeader kicker="Bildarchiv · Suche" title="Suchergebnisse" titleId="albums-title" />
|
||||
<AnnouncementBanner items={hints} />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} sortierung={sortierung} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
<p aria-live="polite" className="text-sm text-[var(--color-fg-muted)]" role="status">
|
||||
{formatCount(page.total, "Foto")} gefunden
|
||||
</p>
|
||||
@@ -60,10 +65,10 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
albumName="Alle Alben"
|
||||
items={page.items}
|
||||
downloadOptions={downloadOptions}
|
||||
lightboxAssetIds={[...lightboxAssetIds]}
|
||||
lightboxAssetIds={page.items.filter(({ id }) => lightboxAssetIds.has(id)).map(({ id }) => id)}
|
||||
showAlbumName
|
||||
/>
|
||||
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} />
|
||||
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} sortierung={sortierung} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -83,7 +88,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen."
|
||||
/>
|
||||
<AnnouncementBanner items={hints} />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} sortierung={sortierung} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
{result.albums.length === 0 ? (
|
||||
<EmptyState title="Noch keine Alben" description="Für Ihre Redaktion sind noch keine Fotoalben freigegeben." />
|
||||
) : (
|
||||
@@ -93,35 +98,32 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
);
|
||||
}
|
||||
|
||||
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
|
||||
function SearchRateLimited({ query, format, jahr, sortierung }: { query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
|
||||
return (
|
||||
<section className="flex flex-col gap-6" aria-labelledby="albums-title">
|
||||
<PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} sortierung={sortierung} withYear placeholder="Alle Alben durchsuchen …" />
|
||||
<Alert color="warning" description="Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut." />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string }) {
|
||||
const hasPrev = currentPage > 1;
|
||||
const hasNext = page.nextPage !== null;
|
||||
if (!hasPrev && !hasNext) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function GlobalSearchPagination({ currentPage, page, query, format, jahr, sortierung }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
|
||||
return (
|
||||
<PageLinks
|
||||
prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr) : null}
|
||||
nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr) : null}
|
||||
<UrlPagination
|
||||
ariaLabel="Suchergebnisseiten"
|
||||
hasNext={page.nextPage !== null}
|
||||
href={globalPageHref(currentPage, query, format, jahr, sortierung)}
|
||||
page={currentPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function globalPageHref(page: number, query: string, format?: string, jahr?: string): string {
|
||||
function globalPageHref(page: number, query: string, format?: string, jahr?: string, sortierung?: PhotoSort): string {
|
||||
const parameters = new URLSearchParams({ suche: query, page: String(page) });
|
||||
if (format) parameters.set("format", format);
|
||||
if (jahr) parameters.set("jahr", jahr);
|
||||
if (sortierung === "aelteste") parameters.set("sortierung", "aelteste");
|
||||
return `/redaktion/alben?${parameters.toString()}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Badge, Button, toast } from "@sakaniui/react";
|
||||
|
||||
import type { EventAccessState } from "@/modules/calendar/service";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
type Action = (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
|
||||
export function EventAccessAction({
|
||||
eventId,
|
||||
access,
|
||||
albumId,
|
||||
reserveAction,
|
||||
unreserveAction,
|
||||
}: Readonly<{
|
||||
eventId: string;
|
||||
access: EventAccessState;
|
||||
albumId: string | null;
|
||||
reserveAction: Action;
|
||||
unreserveAction: Action;
|
||||
}>) {
|
||||
const router = useRouter();
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const run = (action: Action) => {
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
if (result.ok) {
|
||||
toast.success(result.message);
|
||||
router.refresh();
|
||||
} else {
|
||||
toast.error(result.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let content: React.ReactNode;
|
||||
if ((access === "granted" || access === "auto_granted") && albumId) {
|
||||
content = (
|
||||
<>
|
||||
<Badge variant="success">{access === "auto_granted" ? "Automatisch freigegeben" : "Freigeschaltet"}</Badge>
|
||||
<Link
|
||||
className="inline-flex min-h-10 items-center justify-center rounded-md border border-[var(--color-border-default)] px-4 text-sm font-medium transition-colors hover:bg-[var(--color-bg-subtle)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
|
||||
href={`/redaktion/alben/${encodeURIComponent(albumId)}`}
|
||||
>
|
||||
Album öffnen
|
||||
</Link>
|
||||
</>
|
||||
);
|
||||
} else if (access === "auto_rule" || access === "auto_granted") {
|
||||
content = <Badge variant="info">Automatisch freigegeben (Auto-Regel)</Badge>;
|
||||
} else if (access === "reserved") {
|
||||
content = (
|
||||
<>
|
||||
<Badge variant="accent">Vorgemerkt</Badge>
|
||||
<Button disabled={pending} onClick={() => run(unreserveAction)} size="sm" type="button" variant="ghost">
|
||||
Vormerkung entfernen
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
content = (
|
||||
<Button disabled={pending} onClick={() => run(reserveAction)} type="button" variant="primary">
|
||||
{pending ? "Wird hinzugefügt …" : "Zu meinen Alben hinzufügen"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">{content}</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { CalendarServiceError, calendarService } from "@/modules/calendar/service";
|
||||
|
||||
export type CalendarActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
albumId?: string;
|
||||
};
|
||||
|
||||
function eventIdFrom(formData: FormData): string | null {
|
||||
const eventId = formData.get("eventId");
|
||||
return typeof eventId === "string" && eventId.length > 0 ? eventId : null;
|
||||
}
|
||||
|
||||
function revalidate(albumId?: string) {
|
||||
revalidatePath("/redaktion/kalender");
|
||||
revalidatePath("/redaktion/alben");
|
||||
revalidatePath("/admin/kalender");
|
||||
if (albumId) revalidatePath(`/redaktion/alben/${albumId}`);
|
||||
}
|
||||
|
||||
/** "Zu meinen Alben hinzufügen": grants at once if the album exists, else reserves. */
|
||||
export async function reserveEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireActiveEditorial(new Headers(await headers()));
|
||||
const eventId = eventIdFrom(formData);
|
||||
if (!eventId) return { ok: false, message: "Ungültiger Termin." };
|
||||
|
||||
try {
|
||||
const result = await calendarService.reserve({
|
||||
eventId,
|
||||
editorialId: principal.editorialId,
|
||||
actorUserId: principal.userId,
|
||||
});
|
||||
revalidate(result.album?.id);
|
||||
return result.status === "granted"
|
||||
? { ok: true, message: "Album freigeschaltet.", albumId: result.album!.id }
|
||||
: { ok: true, message: "Vorgemerkt. Das Album erscheint automatisch in Ihren Alben, sobald es da ist." };
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function unreserveEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireActiveEditorial(new Headers(await headers()));
|
||||
const eventId = eventIdFrom(formData);
|
||||
if (!eventId) return { ok: false, message: "Ungültiger Termin." };
|
||||
|
||||
try {
|
||||
await calendarService.unreserve({ eventId, editorialId: principal.editorialId, actorUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "Vormerkung entfernt." };
|
||||
}
|
||||
|
||||
function calendarErrorMessage(error: unknown): string {
|
||||
if (error instanceof CalendarServiceError) {
|
||||
const messages: Record<CalendarServiceError["code"], string> = {
|
||||
INVALID_TITLE: "Ungültiger Termin.",
|
||||
INVALID_EVENT_DATE: "Ungültiger Termin.",
|
||||
INVALID_ALBUM: "Ungültiger Termin.",
|
||||
INVALID_CATEGORY: "Ungültiger Termin.",
|
||||
NOTHING_TO_IMPORT: "Ungültiger Termin.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung gibt es nicht mehr. Das Album ist vermutlich schon freigeschaltet.",
|
||||
IMMICH_UNAVAILABLE: "Das Bildarchiv ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
|
||||
};
|
||||
return messages[error.code];
|
||||
}
|
||||
return "Die Aktion konnte nicht ausgeführt werden.";
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { CategoryDot, CategoryLegend } from "@/components/calendar/category-legend";
|
||||
import { EventMonth } from "@/components/calendar/event-month";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { calendarService, type EditorialCalendarEvent } from "@/modules/calendar/service";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
import { EventAccessAction } from "./EventAccessAction";
|
||||
import { reserveEventAction, unreserveEventAction } from "./actions";
|
||||
|
||||
export default async function EditorialCalendarPage() {
|
||||
const principal = await requireEditorial();
|
||||
const [{ events, immichUnavailable }, categories] = await Promise.all([
|
||||
calendarService.listEditorialEvents(principal.editorialId),
|
||||
categoryService.listCategories(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
const upcoming = events.filter((event) => event.eventDate >= today);
|
||||
const past = events.filter((event) => event.eventDate < today).reverse();
|
||||
const usedCategoryIds = new Set(events.map((event) => event.category?.id).filter(Boolean));
|
||||
|
||||
return (
|
||||
<section aria-labelledby="calendar-title" className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Bildarchiv · Kalender"
|
||||
title="Kalender"
|
||||
titleId="calendar-title"
|
||||
description="Kommende Spiele und Termine. Fügen Sie einen Termin zu Ihren Alben hinzu: Ist das Album schon da, ist es sofort freigeschaltet, sonst automatisch, sobald es angelegt ist."
|
||||
/>
|
||||
|
||||
{immichUnavailable ? (
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Das Bildarchiv ist gerade nicht erreichbar. Termine und Vormerkungen funktionieren weiterhin, Alben erscheinen wieder, sobald die Verbindung steht."
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{events.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Zurzeit keine Termine"
|
||||
description="Sobald ein Spiel oder Event geplant ist, erscheint es hier."
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Card title="Monatsübersicht">
|
||||
<EventMonth
|
||||
events={events.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.title,
|
||||
eventDate: event.eventDate,
|
||||
color: event.category?.color ?? null,
|
||||
}))}
|
||||
/>
|
||||
<CategoryLegend
|
||||
categories={categories.filter((category) => usedCategoryIds.has(category.id))}
|
||||
showUncategorized={events.some((event) => !event.category)}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{upcoming.length > 0 ? (
|
||||
<section aria-labelledby="calendar-upcoming" className="flex flex-col gap-3">
|
||||
<h2 className="text-xl font-semibold" id="calendar-upcoming">
|
||||
Kommende Termine
|
||||
</h2>
|
||||
<EventList events={upcoming} today={today} />
|
||||
</section>
|
||||
) : null}
|
||||
{past.length > 0 ? (
|
||||
// Imported older albums can make this long; the month view shows
|
||||
// them too, and a click there opens this section (event-month.tsx).
|
||||
<details className="group" open={upcoming.length === 0}>
|
||||
<summary className="flex cursor-pointer list-none items-center gap-2 text-xl font-semibold">
|
||||
<span aria-hidden="true" className="transition-transform group-open:rotate-90">›</span>
|
||||
Vergangene Termine ({past.length})
|
||||
</summary>
|
||||
<div className="mt-3">
|
||||
<EventList events={past} today={today} />
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function EventList({ events, today }: Readonly<{ events: EditorialCalendarEvent[]; today: string }>) {
|
||||
return (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{events.map((event) => (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] lg:flex-row lg:items-center"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
{event.album ? null : <span>· Album noch nicht angelegt</span>}
|
||||
</p>
|
||||
</div>
|
||||
<EventAccessAction
|
||||
access={event.access}
|
||||
albumId={event.album?.id ?? null}
|
||||
eventId={event.id}
|
||||
reserveAction={reserveEventAction}
|
||||
unreserveAction={unreserveEventAction}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { DownloadLightboxForm } from "./DownloadLightboxForm";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) }));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
const photos = [
|
||||
{ assetId: "first", albumId: "allowed", filename: "first.jpg" },
|
||||
{ assetId: "second", albumId: "allowed", filename: "second.jpg" },
|
||||
];
|
||||
const options = {
|
||||
priceCents: 1500,
|
||||
collabEnabled: false,
|
||||
priorUsagesByAsset: {
|
||||
second: [{ id: "prior", purpose: "Früherer Artikel", createdAt: "2026-11-01T12:00:00Z" }],
|
||||
},
|
||||
};
|
||||
|
||||
test("books every photo as a new usage and offers a choice only for already downloaded ones", () => {
|
||||
render(<DownloadLightboxForm options={options} photos={photos} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
|
||||
|
||||
expect(screen.queryByText("Bild auslassen")).toBeNull();
|
||||
const [firstRow, secondRow] = screen.getAllByRole("listitem");
|
||||
expect(within(firstRow).queryByText("Bereits genutzt")).toBeNull();
|
||||
expect(within(secondRow).getByText("Bereits genutzt")).toBeTruthy();
|
||||
|
||||
const submit = screen.getByRole<HTMLButtonElement>("button", { name: "Nutzungen bestätigen und laden" });
|
||||
expect(submit.disabled).toBe(true);
|
||||
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
|
||||
expect(submit.disabled).toBe(false);
|
||||
expect(screen.getByRole("status").textContent).toMatch(/2 neue Nutzungen.*30,00/);
|
||||
});
|
||||
|
||||
test("switching to 'Bereits genutzt' repeats the earlier usage and keeps keys after a failed request", async () => {
|
||||
const fetch = vi.fn().mockRejectedValue(new Error("connection lost"));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
render(<DownloadLightboxForm options={options} photos={photos} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
|
||||
|
||||
fireEvent.click(within(screen.getAllByRole("listitem")[1]).getByText("Bereits genutzt"));
|
||||
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
|
||||
expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*1 kostenlos erneut.*15,00/);
|
||||
|
||||
const submit = screen.getByRole<HTMLButtonElement>("button", { name: "Nutzungen bestätigen und laden" });
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(submit.disabled).toBe(false));
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(submit.disabled).toBe(false));
|
||||
|
||||
const payload = JSON.parse(fetch.mock.calls[0][1].body);
|
||||
expect(payload).toEqual({
|
||||
maxPriceCents: 1500,
|
||||
items: [
|
||||
{ assetId: "first", albumId: "allowed", purpose: "Neuer Artikel", idempotencyKey: expect.any(String) },
|
||||
{ assetId: "second", usageId: "prior", idempotencyKey: expect.any(String) },
|
||||
],
|
||||
});
|
||||
expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual(payload);
|
||||
});
|
||||
@@ -1,103 +1,293 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Input } from "@sakaniui/react";
|
||||
import { Alert, Badge, Button, Checkbox, Input, SegmentedControl, Select, toast } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
|
||||
import { thumbnailUrl } from "@/modules/albums/catalog-content";
|
||||
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
|
||||
type Photo = { assetId: string; albumId: string; filename: string };
|
||||
// Every photo is a new usage unless the editorial switches an already
|
||||
// downloaded one to "Bereits genutzt" (free repeat of an earlier usage).
|
||||
type Choice = { mode: "new" | "repeat"; usageId?: string; purpose?: string; ownPurpose?: boolean };
|
||||
|
||||
const MAX_PHOTOS = 100;
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
const MODE_OPTIONS = [
|
||||
{ value: "new", label: "Neu" },
|
||||
{ value: "repeat", label: "Bereits genutzt" },
|
||||
];
|
||||
|
||||
export function DownloadLightboxForm({
|
||||
photos,
|
||||
options,
|
||||
}: {
|
||||
photos: Photo[];
|
||||
options: EditorialDownloadOptions;
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const [choices, setChoices] = useState<Record<string, Choice>>({});
|
||||
const [commonPurpose, setCommonPurpose] = useState("");
|
||||
const [collab, setCollab] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const inFlight = useRef(false);
|
||||
const intentKeys = useRef(new Map<string, string>());
|
||||
const router = useRouter();
|
||||
|
||||
async function handleBulkDownload(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!purpose.trim() || assetIds.length === 0) return;
|
||||
const priorUsages = (assetId: string) =>
|
||||
[...(options.priorUsagesByAsset[assetId] ?? [])].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||
const choiceFor = (assetId: string): Choice => {
|
||||
const choice = choices[assetId] ?? { mode: "new" };
|
||||
if (choice.mode === "repeat" && !priorUsages(assetId).some(({ id }) => id === choice.usageId)) {
|
||||
return { ...choice, usageId: priorUsages(assetId)[0]?.id };
|
||||
}
|
||||
return choice;
|
||||
};
|
||||
const update = (assetId: string, patch: Partial<Choice>) =>
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { ...choiceFor(assetId), ...patch } }));
|
||||
const purposeFor = (choice: Choice) => (choice.ownPurpose && choice.purpose?.trim()) || commonPurpose.trim();
|
||||
|
||||
const newPhotos = photos.filter(({ assetId }) => choiceFor(assetId).mode === "new");
|
||||
const repeatCount = photos.length - newPhotos.length;
|
||||
const missingPurpose = newPhotos.some(({ assetId }) => [...purposeFor(choiceFor(assetId))].length < 3);
|
||||
const ready = photos.length > 0 && photos.length <= MAX_PHOTOS && !missingPurpose;
|
||||
const price = priceFormatter.format(options.priceCents / 100);
|
||||
|
||||
async function handleBulkDownload(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!ready || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const items = photos.map(({ assetId, albumId }) => {
|
||||
const choice = choiceFor(assetId);
|
||||
const purpose = choice.mode === "new" ? purposeFor(choice) : undefined;
|
||||
const key = JSON.stringify([assetId, choice.mode, choice.usageId, purpose]);
|
||||
let idempotencyKey = intentKeys.current.get(key);
|
||||
if (!idempotencyKey) {
|
||||
idempotencyKey = crypto.randomUUID();
|
||||
intentKeys.current.set(key, idempotencyKey);
|
||||
}
|
||||
return purpose
|
||||
? { assetId, albumId, purpose, idempotencyKey }
|
||||
: { assetId, usageId: choice.usageId, idempotencyKey };
|
||||
});
|
||||
|
||||
const response = await fetch("/api/lightbox/bulk-download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetIds, purpose }),
|
||||
body: JSON.stringify({
|
||||
items,
|
||||
maxPriceCents: options.priceCents,
|
||||
...(collab && newPhotos.length > 0 ? { collab: true } : {}),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Surface the server's error code instead of a generic message so the
|
||||
// real cause (e.g. IMMICH_UNAVAILABLE, REQUEST_FAILED) is visible in the
|
||||
// browser console — the bulk handler maps UsageAccountingError to codes.
|
||||
let code: string | undefined;
|
||||
try {
|
||||
code = (await response.clone().json()).code;
|
||||
} catch {
|
||||
/* non-JSON body (e.g. plain 500) — code stays undefined */
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (payload?.code === "INVALID_PRICE") {
|
||||
router.refresh();
|
||||
throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis.");
|
||||
}
|
||||
const status = response.status;
|
||||
console.error("[bulk-download] server error:", { status, code });
|
||||
throw new Error(`Download fehlgeschlagen (${status}${code ? ` ${code}` : ""})`);
|
||||
if (payload?.code === "IDEMPOTENCY_CONFLICT") {
|
||||
router.refresh();
|
||||
throw new Error("Der Downloadversuch ist bereits erfasst. Prüfen Sie Ihre Nutzungen, bevor Sie einen neuen Zweck buchen.");
|
||||
}
|
||||
if (payload?.code === "COLLAB_NOT_ENABLED") {
|
||||
throw new Error("Collab-Nutzung ist für Ihr Konto nicht freigeschaltet. Bitte den Admin, die Option zu aktivieren.");
|
||||
}
|
||||
throw new Error("Bitte prüfen Sie die Auswahl und versuchen Sie es erneut.");
|
||||
}
|
||||
|
||||
// Download the ZIP file
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "leuchtkasten.zip";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
intentKeys.current.clear();
|
||||
dialogRef.current?.close();
|
||||
setPurpose("");
|
||||
router.refresh(); // Refresh to update usage history
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
|
||||
setError(`Bulk-Download fehlgeschlagen: ${message}`);
|
||||
console.error(err);
|
||||
setChoices({});
|
||||
setCommonPurpose("");
|
||||
setCollab(false);
|
||||
toast.success(`ZIP mit ${photos.length} ${photos.length === 1 ? "Bild" : "Bildern"} wird heruntergeladen.`);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
// Stays inside the open modal: a toast would sit behind its backdrop.
|
||||
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={assetIds.length === 0}
|
||||
leftIcon={<IconDownload size={16} />}
|
||||
onClick={() => dialogRef.current?.showModal()}
|
||||
type="button"
|
||||
>
|
||||
Alle herunterladen
|
||||
<Button leftIcon={<IconDownload size={16} />} onClick={() => dialogRef.current?.showModal()} type="button">
|
||||
ZIP-Download vorbereiten
|
||||
</Button>
|
||||
|
||||
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
|
||||
<form className="flex flex-col gap-4 p-6" onSubmit={handleBulkDownload}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
|
||||
</p>
|
||||
<Input
|
||||
disabled={loading}
|
||||
id="purpose"
|
||||
label="Verwendungszweck"
|
||||
onChange={(e) => setPurpose(e.target.value)}
|
||||
placeholder="z.B. Webseite, Social Media"
|
||||
required
|
||||
type="text"
|
||||
value={purpose}
|
||||
/>
|
||||
{error ? <Alert color="danger" description={error} /> : null}
|
||||
<div className="mt-4 flex justify-end gap-3">
|
||||
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-2xl">
|
||||
<form className="flex flex-col gap-5 p-6" method="post" onSubmit={handleBulkDownload}>
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="editorial-kicker">ZIP-Download · {photos.length} {photos.length === 1 ? "Bild" : "Bilder"}</p>
|
||||
<h2 className="text-xl font-semibold" id="bulk-download-title">Nutzungen bestätigen</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Alle Bilder werden als neue Nutzung gebucht. Bilder, die Sie schon einmal geladen haben, können Sie
|
||||
stattdessen kostenlos unter der bisherigen Nutzung erneut laden.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{newPhotos.length > 0 && (
|
||||
<Input
|
||||
description="Gilt für alle neuen Nutzungen, außer Sie geben bei einem Bild einen eigenen Zweck an."
|
||||
disabled={loading}
|
||||
label="Verwendungszweck"
|
||||
maxLength={200}
|
||||
onChange={(event) => setCommonPurpose(event.target.value)}
|
||||
placeholder="z. B. Spielbericht HSV - Wolfsburg, Ausgabe 13.12."
|
||||
value={commonPurpose}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ul className="flex max-h-[50vh] flex-col divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)]">
|
||||
{photos.map(({ assetId, filename }) => {
|
||||
const choice = choiceFor(assetId);
|
||||
const prior = priorUsages(assetId);
|
||||
return (
|
||||
<li className="flex flex-col gap-3 p-3" key={assetId}>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<img
|
||||
alt=""
|
||||
className="aspect-[3/2] w-20 shrink-0 rounded-[var(--radius-md)] bg-[var(--color-bg-subtle)] object-cover"
|
||||
loading="lazy"
|
||||
src={thumbnailUrl(assetId)}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="truncate text-sm font-medium">{filename}</span>
|
||||
{prior.length === 0 ? (
|
||||
<span>
|
||||
<Badge>Neue Nutzung · bis {price}</Badge>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-[var(--color-fg-muted)]">
|
||||
Schon geladen am {formatBerlinDate(new Date(prior[0].createdAt))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{prior.length > 0 && (
|
||||
<div className="w-full sm:w-72">
|
||||
<SegmentedControl
|
||||
aria-label={`Nutzung für ${filename}`}
|
||||
fullWidth
|
||||
onChange={(value) => update(assetId, { mode: value === "repeat" ? "repeat" : "new" })}
|
||||
options={MODE_OPTIONS}
|
||||
value={choice.mode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{choice.mode === "repeat" && prior.length > 1 && (
|
||||
<Select
|
||||
aria-label={`Bisherige Nutzung für ${filename}`}
|
||||
disabled={loading}
|
||||
label="Bisherige Nutzung"
|
||||
onChange={(usageId) => update(assetId, { usageId })}
|
||||
options={prior.map((usage) => ({
|
||||
label: `${usage.purpose} (${formatBerlinDate(new Date(usage.createdAt))})`,
|
||||
value: usage.id,
|
||||
}))}
|
||||
value={choice.usageId}
|
||||
/>
|
||||
)}
|
||||
{choice.mode === "repeat" && prior.length === 1 && (
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
Kostenlos unter „{prior[0].purpose}“ erneut laden.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{choice.mode === "new" &&
|
||||
(choice.ownPurpose ? (
|
||||
<Input
|
||||
disabled={loading}
|
||||
label={`Eigener Zweck für ${filename}`}
|
||||
maxLength={200}
|
||||
onChange={(event) => update(assetId, { purpose: event.target.value })}
|
||||
value={choice.purpose ?? ""}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
className="self-start text-xs font-medium text-[var(--color-fg-muted)] underline underline-offset-4 hover:text-[var(--color-fg-default)]"
|
||||
disabled={loading}
|
||||
onClick={() => update(assetId, { ownPurpose: true })}
|
||||
type="button"
|
||||
>
|
||||
Eigenen Zweck für dieses Bild angeben
|
||||
</button>
|
||||
))}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{options.collabEnabled && newPhotos.length > 0 && (
|
||||
<Checkbox
|
||||
checked={collab}
|
||||
description={
|
||||
newPhotos.length === 1
|
||||
? "Die neue Nutzung wird mit 0,00 € in der Abrechnung geführt."
|
||||
: `Alle ${newPhotos.length} neuen Nutzungen werden mit 0,00 € in der Abrechnung geführt.`
|
||||
}
|
||||
disabled={loading}
|
||||
label="Collab-Nutzung (kostenfrei)"
|
||||
onChange={(event) => setCollab(event.target.checked)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-[var(--radius-xl)] bg-[var(--color-bg-subtle)] p-3 text-sm" role="status">
|
||||
{newPhotos.length > 0 && (
|
||||
<Badge variant="info">
|
||||
{newPhotos.length} {newPhotos.length === 1 ? "neue Nutzung" : "neue Nutzungen"}
|
||||
</Badge>
|
||||
)}
|
||||
{repeatCount > 0 && <Badge>{repeatCount} kostenlos erneut</Badge>}
|
||||
<span className="text-[var(--color-fg-muted)]">
|
||||
{newPhotos.length === 0
|
||||
? "Keine neuen Kosten."
|
||||
: collab
|
||||
? "Kostenfrei als Collab-Nutzung."
|
||||
: `Bis ${priceFormatter.format((newPhotos.length * options.priceCents) / 100)} netto; ein Flatrate-Kontingent wird angerechnet.`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{photos.length > MAX_PHOTOS && (
|
||||
<Alert
|
||||
color="warning"
|
||||
description={`Höchstens ${MAX_PHOTOS} Bilder pro ZIP. Entfernen Sie einige Bilder aus dem Merkzettel.`}
|
||||
/>
|
||||
)}
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
|
||||
{missingPurpose && newPhotos.length > 0 && (
|
||||
<p className="text-right text-xs text-[var(--color-fg-muted)]">Bitte einen Verwendungszweck mit mindestens 3 Zeichen angeben.</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={loading || !purpose.trim()} type="submit">
|
||||
{loading ? "Wird verpackt …" : "Download starten (ZIP)"}
|
||||
<Button disabled={loading || !ready} loading={loading} type="submit">
|
||||
{loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
const { lightboxService, findGrantedPhoto, assertOriginalAccess, getAsset, options, zipForm } = vi.hoisted(() => ({
|
||||
lightboxService: {
|
||||
getLightboxItems: vi.fn(),
|
||||
addLightboxItem: vi.fn(),
|
||||
removeLightboxItem: vi.fn(),
|
||||
isAssetInLightbox: vi.fn(),
|
||||
},
|
||||
findGrantedPhoto: vi.fn(),
|
||||
assertOriginalAccess: vi.fn(),
|
||||
getAsset: vi.fn(),
|
||||
options: vi.fn(),
|
||||
zipForm: vi.fn(),
|
||||
}));
|
||||
|
||||
const editorialId = "55555555-5555-4555-8555-555555555555";
|
||||
const photoId = "22222222-2222-4222-8222-222222222222";
|
||||
const revokedId = "33333333-3333-4333-8333-333333333333";
|
||||
|
||||
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
|
||||
vi.mock("next/headers", () => ({ headers: () => new Headers() }));
|
||||
vi.mock("../access", () => ({ requireEditorial: async () => ({ editorialId }) }));
|
||||
vi.mock("@/modules/auth/principal", () => ({
|
||||
requireActiveEditorial: async () => ({ editorialId }),
|
||||
}));
|
||||
vi.mock("@/modules/lightbox/service", () => ({ lightboxService }));
|
||||
vi.mock("@/modules/albums/photo-access", () => ({ findGrantedPhoto, assertOriginalAccess }));
|
||||
vi.mock("@/modules/immich/client", () => ({ immichClient: { getAsset } }));
|
||||
vi.mock("@/modules/downloads/stream", () => ({
|
||||
DOWNLOAD_OPTIONS_MAX_ASSETS: 60,
|
||||
loadEditorialDownloadOptions: options,
|
||||
}));
|
||||
vi.mock("./DownloadLightboxForm", () => ({ DownloadLightboxForm: zipForm }));
|
||||
|
||||
import { toggleLightboxItem } from "./actions";
|
||||
import LightboxPage from "./page";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
test("rejects a new bookmark without current access and can remove the old bookmark", async () => {
|
||||
lightboxService.isAssetInLightbox.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
|
||||
findGrantedPhoto.mockResolvedValue(null);
|
||||
await expect(toggleLightboxItem(revokedId)).rejects.toThrow();
|
||||
expect(lightboxService.addLightboxItem).not.toHaveBeenCalled();
|
||||
await expect(toggleLightboxItem(revokedId)).resolves.toMatchObject({ isNowInLightbox: false });
|
||||
expect(lightboxService.removeLightboxItem).toHaveBeenCalledWith(editorialId, revokedId);
|
||||
expect(findGrantedPhoto).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("shows a removable placeholder and excludes a revoked bookmark from ZIP options", async () => {
|
||||
lightboxService.getLightboxItems.mockResolvedValue([{ assetId: photoId }, { assetId: revokedId }]);
|
||||
findGrantedPhoto.mockResolvedValueOnce({ albumId: "allowed-album", filename: "allowed.jpg" })
|
||||
.mockResolvedValueOnce(null);
|
||||
getAsset.mockResolvedValue({
|
||||
id: revokedId, originalFileName: "private.jpg", albums: [{ id: "private-album" }],
|
||||
});
|
||||
options.mockResolvedValue({ priceCents: 1500, priorUsagesByAsset: {} });
|
||||
zipForm.mockReturnValue(null);
|
||||
|
||||
render(await LightboxPage());
|
||||
|
||||
expect(getAsset).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText("private.jpg")).toBeNull();
|
||||
expect(screen.getByText("Foto derzeit nicht verfügbar")).toBeTruthy();
|
||||
expect(screen.getAllByRole("button", { name: "Aus Merkzettel entfernen" })).toHaveLength(2);
|
||||
expect(options).toHaveBeenCalledWith(editorialId, [photoId], expect.any(Function));
|
||||
expect(zipForm.mock.calls[0][0].photos).toEqual([{ assetId: photoId, albumId: "allowed-album", filename: "allowed.jpg" }]);
|
||||
const allowPrior = options.mock.calls[0][2];
|
||||
assertOriginalAccess.mockRejectedValue(new Error("previous album revoked"));
|
||||
await expect(allowPrior(photoId, "allowed-album")).resolves.toBe(true);
|
||||
await expect(allowPrior(photoId, "revoked-album")).resolves.toBe(false);
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
import { findGrantedPhoto } from "@/modules/albums/photo-access";
|
||||
import { normalizeUuid } from "@/modules/usages/types";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { lightboxService } from "@/modules/lightbox/service";
|
||||
|
||||
@@ -12,7 +14,11 @@ export async function toggleLightboxItem(assetId: string) {
|
||||
if (isInLightbox) {
|
||||
await lightboxService.removeLightboxItem(principal.editorialId, assetId);
|
||||
} else {
|
||||
await lightboxService.addLightboxItem(principal.editorialId, assetId);
|
||||
const normalizedAssetId = normalizeUuid(assetId);
|
||||
if (!(await findGrantedPhoto(principal.editorialId, normalizedAssetId))) {
|
||||
throw new Error("Foto nicht verfügbar");
|
||||
}
|
||||
await lightboxService.addLightboxItem(principal.editorialId, normalizedAssetId);
|
||||
}
|
||||
|
||||
// Revalidate routes where lightbox state is shown
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { lightboxService } from "@/modules/lightbox/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { assertOriginalAccess, findGrantedPhoto } from "@/modules/albums/photo-access";
|
||||
import { DOWNLOAD_OPTIONS_MAX_ASSETS, loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
import Link from "next/link";
|
||||
import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
|
||||
import { DownloadLightboxForm } from "./DownloadLightboxForm";
|
||||
@@ -13,13 +14,34 @@ export default async function LightboxPage() {
|
||||
const principal = await requireEditorial();
|
||||
const items = await lightboxService.getLightboxItems(principal.editorialId);
|
||||
|
||||
// Fetch asset details for all items in the lightbox
|
||||
const assets = items.length > 0
|
||||
? await Promise.all(items.map(i => immichClient.getAsset(i.assetId).catch(() => null)))
|
||||
: [];
|
||||
|
||||
const validAssets = assets.filter((a): a is NonNullable<typeof a> => a !== null);
|
||||
const assetMap = new Map(validAssets.map(a => [a.id, a]));
|
||||
const photos = new Map<string, NonNullable<Awaited<ReturnType<typeof findGrantedPhoto>>>>();
|
||||
const lookupDeadline = AbortSignal.timeout(15_000);
|
||||
for (let start = 0; start < items.length && !lookupDeadline.aborted; start += 8) {
|
||||
await Promise.all(items.slice(start, start + 8).map(async ({ assetId }) => {
|
||||
const photo = await findGrantedPhoto(principal.editorialId, assetId, lookupDeadline).catch(() => null);
|
||||
if (photo) photos.set(assetId, photo);
|
||||
}));
|
||||
}
|
||||
|
||||
const downloadable = items.flatMap(({ assetId }) => {
|
||||
const photo = photos.get(assetId);
|
||||
return photo ? [{ assetId, ...photo }] : [];
|
||||
});
|
||||
let downloadOptions: Awaited<ReturnType<typeof loadEditorialDownloadOptions>> | undefined;
|
||||
for (let start = 0; start < downloadable.length; start += DOWNLOAD_OPTIONS_MAX_ASSETS) {
|
||||
const batch = downloadable.slice(start, start + DOWNLOAD_OPTIONS_MAX_ASSETS);
|
||||
const options = await loadEditorialDownloadOptions(
|
||||
principal.editorialId,
|
||||
batch.map(({ assetId }) => assetId),
|
||||
async (assetId, albumId) => {
|
||||
if (photos.get(assetId)?.albumId === albumId) return true;
|
||||
if (lookupDeadline.aborted) return false;
|
||||
return assertOriginalAccess(principal.editorialId, assetId, albumId).then(() => true, () => false);
|
||||
},
|
||||
);
|
||||
downloadOptions ??= options;
|
||||
Object.assign(downloadOptions.priorUsagesByAsset, options.priorUsagesByAsset);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
@@ -37,33 +59,37 @@ export default async function LightboxPage() {
|
||||
<p className="text-sm font-medium text-[var(--color-fg-muted)]">
|
||||
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
|
||||
</p>
|
||||
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
|
||||
{downloadOptions && <DownloadLightboxForm photos={downloadable} options={downloadOptions} />}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<ul className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
|
||||
{items.map((item) => {
|
||||
const asset = assetMap.get(item.assetId);
|
||||
if (!asset) return null;
|
||||
const albumId = asset.albums?.[0]?.id;
|
||||
const href = albumId
|
||||
? `/redaktion/alben/${encodeURIComponent(albumId)}?suche=${encodeURIComponent(asset.originalFileName)}`
|
||||
: '#';
|
||||
const photo = photos.get(item.assetId);
|
||||
if (!photo) {
|
||||
return (
|
||||
<li key={item.assetId} className="flex items-center justify-between gap-2 rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] p-3">
|
||||
<span className="text-sm text-[var(--color-fg-muted)]">Foto derzeit nicht verfügbar</span>
|
||||
<RemoveLightboxItemButton assetId={item.assetId} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
const href = `/redaktion/alben/${encodeURIComponent(photo.albumId)}?suche=${encodeURIComponent(photo.filename)}`;
|
||||
|
||||
return (
|
||||
<li key={item.assetId} className="group relative overflow-hidden rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] transition-shadow hover:shadow-[var(--shadow-md)]">
|
||||
<Link href={href} className="block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]">
|
||||
<div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]">
|
||||
<img
|
||||
alt={asset.originalFileName ?? "Bild"}
|
||||
alt={photo.filename}
|
||||
className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
|
||||
loading="lazy"
|
||||
src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`}
|
||||
/>
|
||||
</div>
|
||||
<div className="border-t border-[var(--color-border-subtle)] p-3">
|
||||
<span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={asset.originalFileName}>
|
||||
{asset.originalFileName ?? "Unbekannt"}
|
||||
<span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={photo.filename}>
|
||||
{photo.filename}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { ReleaseHistory } from "@/modules/releases/release-history";
|
||||
import { releaseNoteService } from "@/modules/releases/service";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
|
||||
export default async function EditorialNewsPage() {
|
||||
await requireEditorial();
|
||||
const notes = await releaseNoteService.listEditorialReleaseNotes();
|
||||
|
||||
return (
|
||||
<section aria-labelledby="news-title" className="flex max-w-4xl flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Portal · Versionshistorie"
|
||||
title="Neuigkeiten"
|
||||
titleId="news-title"
|
||||
description="Alle Änderungen am Redaktionsportal, neueste Version zuerst. So sehen Sie, was sich wann geändert hat."
|
||||
/>
|
||||
<ReleaseHistory notes={notes} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user