Merge v2.1-2.2.0 features onto SakaniUI base

Ports calendar, self-service, sorting, image descriptions, logo (2.1),
filename search (2.1.1), statistics page, collab option and bundled
invoice PDF delivery (2.2.0) onto the deployed SakaniUI portal.

Also fixes the statistics daily series, which ended yesterday and so
hid today's activity from the charts, and ignores Playwright
test-results/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Leon TonhäuserandClaude Opus 5.5 committed 2026-11-30 22:19:34 +01:00
commit c0c2425dda
106 files changed
+9999 -109

No files matched your search

+2
View File
@@ -11,3 +11,5 @@ dist/
coverage/
*.tsbuildinfo
.DS_Store
test-results/
playwright-report/
+77
View File
@@ -0,0 +1,77 @@
# 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`).
## 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` (/admin/versionen, /redaktion/neuigkeiten).
- 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 -->
+19 -1
View File
@@ -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`.
@@ -62,3 +63,20 @@ 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 können das verknüpfte Album eines Termins unter `/redaktion/kalender` selbst freischalten (`selfGrantAlbum`, 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`):** Je Termin und Redaktion genau eine Zeile (`attending`/`not_attending`, Upsert). Admin sieht Zusagen/Absagen als Chips je Termin. Audit `event_response_recorded` (actorType `editorial`).
- **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.
- **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).
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+45
View File
@@ -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;
+35
View File
@@ -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;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -15,6 +15,20 @@
"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
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

+1
View File
@@ -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"),
};
}
@@ -17,6 +17,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 +33,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 +49,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"),
@@ -173,6 +173,28 @@ export function BillingSelection({
}
}
async function handleToggleCollab(position: BillingPosition) {
setActionState({ loading: true, message: null, isError: false });
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(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
}
window.location.reload();
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Collab-Kennzeichnung fehlgeschlagen",
isError: true,
});
}
}
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
const quarterHref = quarter
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
@@ -227,7 +249,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",
@@ -330,11 +370,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} />
)}
@@ -389,6 +465,111 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
);
}
type InvoiceUploadFormProps = {
reportId: string;
reportNumber: number;
hasInvoice: boolean;
emailFailed: boolean;
};
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleUpload(event: React.FormEvent) {
event.preventDefault();
if (!file || loading) return;
setLoading(true);
setError(null);
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));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
setLoading(false);
}
}
async function handleResend() {
if (loading) return;
setLoading(true);
setError(null);
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));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
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>
{error && <Alert color="danger" description={error} />}
</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;
@@ -15,6 +15,10 @@ export type FinalizedReportSummary = {
netTotalCents: number;
status: string;
createdAt: Date;
hasInvoicePdf: boolean;
invoiceUploadedAt: Date | null;
invoiceEmailStatus: string;
invoiceEmailSentAt: Date | null;
};
export type BillingSelectionData = {
@@ -54,6 +58,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))
@@ -77,6 +85,10 @@ 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,
})),
};
}
@@ -0,0 +1,99 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { CalendarActionResult } from "./actions";
export function CalendarEventForm({
action,
defaultEventDate,
albums,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
defaultEventDate: string;
albums: Array<{ id: string; albumName: string }>;
}>) {
const titleId = useId();
const dateId = useId();
const albumId = useId();
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [title, setTitle] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setTitle("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="space-y-2">
<label htmlFor={titleId} className="text-sm font-medium">
Titel (Spielpaarung oder Event)
</label>
<Input
id={titleId}
name="title"
value={title}
onChange={(event) => setTitle(event.target.value)}
maxLength={200}
required
placeholder="z. B. Hamburger SV - VfL Wolfsburg"
/>
<p className="text-xs text-muted-foreground">
Ohne direkte Album-Auswahl wird automatisch verknüpft, sobald ein Album exakt
{" „{Titel}“ "}oder{" „{Titel} | TT.MM.JJJJ“ "}heißt (Datum dieses Termins).
</p>
</div>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={dateId} className="text-sm font-medium">
Datum
</label>
<Input id={dateId} type="date" name="eventDate" defaultValue={defaultEventDate} required className="sm:w-48" />
</div>
<div className="space-y-2 flex-1">
<label htmlFor={albumId} className="text-sm font-medium">
Album direkt verknüpfen (optional)
</label>
<select
id={albumId}
name="immichAlbumId"
defaultValue=""
className="flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Automatisch über den Namen</option>
{albums.map((album) => (
<option key={album.id} value={album.id}>
{album.albumName}
</option>
))}
</select>
</div>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird angelegt…" : "Termin anlegen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
@@ -0,0 +1,44 @@
"use client";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import type { CalendarActionResult } from "./actions";
// 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 [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
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 () => {
setState(await action({ ok: true, message: "" }, formData));
});
};
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>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
"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");
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,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/admin/kalender");
revalidatePath("/redaktion/kalender");
return {
ok: true,
message:
"Termin angelegt. Sobald ein passendes Album in Immich erscheint, können Redaktionen es selbst freischalten.",
};
}
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_STATUS: "Ungültige Rückmeldung.",
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verknüpft.",
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
};
return messages[error.code] ?? "Der Termin konnte nicht gespeichert werden.";
}
return "Der Termin konnte nicht gespeichert werden.";
}
+107
View File
@@ -0,0 +1,107 @@
import { PageHeader } from "@/components/ui/page-header";
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
import { calendarService } from "@/modules/calendar/service";
import { immichClient } from "@/modules/immich/client";
import { CalendarEventForm } from "./CalendarEventForm";
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
import { createCalendarEventAction, deleteCalendarEventAction } from "./actions";
export default async function AdminCalendarPage() {
const [{ events, immichUnavailable }, albums] = await Promise.all([
calendarService.listAdminEvents(),
immichClient.listAlbums().catch(() => []),
]);
const today = isoDateInBerlin(new Date());
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Planung"
title="Kalender"
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen melden zurück, ob sie da sind, und können das verknüpfte Album selbst freischalten. Alben ohne Kalender-Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
/>
<CalendarEventForm
action={createCalendarEventAction}
defaultEventDate={today}
albums={albums.map((album) => ({ id: album.id, albumName: album.albumName }))}
/>
{immichUnavailable ? (
<p className="bg-muted p-4 rounded-md text-sm" role="status">
Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht.
</p>
) : null}
<section className="space-y-4" aria-labelledby="calendar-list-title">
<div className="flex items-baseline justify-between">
<h2 id="calendar-list-title" className="text-xl font-semibold">
Alle Termine
</h2>
<p className="text-sm text-muted-foreground">{events.length} insgesamt</p>
</div>
{events.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Termine vorhanden. Legen Sie oben den ersten Termin an.
</p>
) : (
<ul className="space-y-3">
{events.map((event) => {
const attending = event.responses.filter((response) => response.status === "attending");
const notAttending = event.responses.filter((response) => response.status === "not_attending");
return (
<li
key={event.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-2 min-w-0">
<p className="font-semibold">
{event.title}
{event.eventDate < today ? (
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
) : null}
</p>
<p className="text-xs text-muted-foreground">
{formatIsoDateGerman(event.eventDate)} ·{" "}
{event.album ? (
<span>Album: {event.album.albumName}</span>
) : (
<span>Noch kein Album verknüpft</span>
)}
</p>
{event.responses.length > 0 ? (
<div className="flex flex-wrap gap-1.5 text-xs">
{attending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-green-600/10 px-2.5 py-1 font-medium text-green-700 dark:text-green-400"
>
{response.editorialName}: da
</span>
))}
{notAttending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-muted px-2.5 py-1 text-muted-foreground"
>
{response.editorialName}: nicht da
</span>
))}
</div>
) : (
<p className="text-xs text-muted-foreground">Noch keine Rückmeldungen.</p>
)}
</div>
<DeleteCalendarEventButton action={deleteCalendarEventAction} eventId={event.id} />
</li>
);
})}
</ul>
)}
</section>
</div>
);
}
+34
View File
@@ -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 } {
@@ -18,6 +18,7 @@ const editorial = {
flatrateActive: false,
flatratePriceCents: null,
flatrateAssetLimit: null,
collabEnabled: false,
archivedAt: null,
};
+1
View File
@@ -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)
+282
View File
@@ -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,31 @@
"use client";
import { useActionState } from "react";
import { Button } from "@/components/ui/button";
import type { ReleaseNoteActionResult } from "./actions";
export function DeleteReleaseNoteButton({
action,
noteId,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
noteId: string;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction} className="flex flex-col items-end gap-1">
<input type="hidden" name="noteId" value={noteId} />
<Button type="submit" variant="outline" size="sm" disabled={pending}>
{pending ? "…" : "Löschen"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</form>
);
}
@@ -0,0 +1,91 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ReleaseNoteActionResult } from "./actions";
export function ReleaseNoteForm({
action,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
}>) {
const versionId = useId();
const audienceId = useId();
const bodyId = useId();
const [state, setState] = useState<ReleaseNoteActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [body, setBody] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setBody("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={versionId} className="text-sm font-medium">
Version
</label>
<Input id={versionId} name="version" placeholder="z. B. 2.1.1" required className="sm:w-36" />
</div>
<div className="space-y-2">
<label htmlFor={audienceId} className="text-sm font-medium">
Zielgruppe
</label>
<select
id={audienceId}
name="audience"
defaultValue="editorial"
className="flex h-10 w-full sm:w-48 rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="editorial">Redaktionen</option>
<option value="admin">Admins</option>
<option value="both">Beide</option>
</select>
</div>
</div>
<div className="space-y-2">
<label htmlFor={bodyId} className="text-sm font-medium">
Hinweis
</label>
<textarea
id={bodyId}
name="body"
rows={4}
maxLength={2000}
required
value={body}
onChange={(event) => setBody(event.target.value)}
placeholder="Was ist neu in dieser Version?"
className="flex w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-xs text-muted-foreground">{body.length}/2000 Zeichen</p>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
+83
View File
@@ -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.";
}
+66
View File
@@ -0,0 +1,66 @@
import { PageHeader } from "@/components/ui/page-header";
import { releaseNoteService, type ReleaseNoteAudience } from "@/modules/releases/service";
import { DeleteReleaseNoteButton } from "./DeleteReleaseNoteButton";
import { ReleaseNoteForm } from "./ReleaseNoteForm";
import { createReleaseNoteAction, deleteReleaseNoteAction } from "./actions";
const audienceLabels: Record<ReleaseNoteAudience, string> = {
admin: "Admins",
editorial: "Redaktionen",
both: "Beide",
};
export default async function AdminVersionsPage() {
const notes = await releaseNoteService.listReleaseNotes();
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<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="space-y-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">
Alle Hinweise
</h2>
<p className="text-sm text-muted-foreground">{notes.length} insgesamt</p>
</div>
{notes.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Versionshinweise vorhanden.
</p>
) : (
<ul className="space-y-3">
{notes.map((note) => (
<li
key={note.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-1 min-w-0">
<p className="text-sm font-semibold">
Version {note.version}
<span className="ml-2 rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
{audienceLabels[note.audience]}
</span>
</p>
<p className="text-sm whitespace-pre-line break-words">{note.body}</p>
<p className="text-xs text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(note.createdAt)}
</p>
</div>
<DeleteReleaseNoteButton action={deleteReleaseNoteAction} noteId={note.id} />
</li>
))}
</ul>
)}
</section>
</div>
);
}
+41
View File
@@ -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" });
});
@@ -84,7 +84,7 @@ export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDepen
const downloads: PreparedDownload[] = [];
try {
for (const item of items) {
const intent = await createIntent(dependencies, principal.editorialId, item, payload.maxPriceCents);
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");
@@ -197,6 +197,7 @@ const bulkPayload = z.strictObject({
}),
])).min(1).max(100),
maxPriceCents: z.number().int().nonnegative(),
collab: z.boolean().optional(),
});
type Selection = z.output<typeof bulkPayload>["items"][number];
@@ -232,6 +233,7 @@ async function createIntent(
editorialId: string,
item: Selection,
maxPriceCents: number,
collab: boolean,
) {
if ("usageId" in item) {
const prior = await dependencies.listPriorUsages(editorialId, item.assetId);
@@ -242,7 +244,12 @@ async function createIntent(
}
await dependencies.assertOriginalAccess(editorialId, item.assetId, item.albumId);
return dependencies.createNewUsage({ ...item, editorialId, maxPriceCents });
return dependencies.createNewUsage({
...item,
editorialId,
maxPriceCents,
...(collab ? { collab: true } : {}),
});
}
async function parsePayload(request: Request) {
@@ -285,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);
@@ -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;
+12
View File
@@ -351,6 +351,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;
+17 -3
View File
@@ -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,6 +75,7 @@ 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">
@@ -83,6 +94,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
query={query}
format={format}
jahr={jahr}
sortierung={sortierung}
/>
</section>
);
@@ -95,6 +107,7 @@ async function loadAlbumPage({
page,
format,
jahr,
sortierung,
}: {
editorialId: string;
albumId: string;
@@ -102,6 +115,7 @@ async function loadAlbumPage({
page: string | undefined;
format?: string;
jahr?: string;
sortierung: ReturnType<typeof normalizeSort>;
}) {
try {
const albums = await albumCatalog.getVisibleAlbums(editorialId);
@@ -120,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(
+18 -13
View File
@@ -1,6 +1,7 @@
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 { 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 +16,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 +35,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 +56,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>
@@ -63,7 +67,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
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 +87,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,17 +97,17 @@ 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 }) {
function GlobalSearchPagination({ currentPage, page, query, format, jahr, sortierung }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
const hasPrev = currentPage > 1;
const hasNext = page.nextPage !== null;
if (!hasPrev && !hasNext) {
@@ -112,16 +116,17 @@ function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { cu
return (
<PageLinks
prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr) : null}
nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr) : null}
prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr, sortierung) : null}
nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr, sortierung) : null}
/>
);
}
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,71 @@
"use client";
import { useState, useTransition } from "react";
import type { EventResponseStatus } from "@/modules/calendar/service";
import type { CalendarActionResult } from "./actions";
export function EventRsvpButtons({
action,
eventId,
initialResponse,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
eventId: string;
initialResponse: EventResponseStatus | null;
}>) {
const [response, setResponse] = useState<EventResponseStatus | null>(initialResponse);
const [error, setError] = useState("");
const [pending, startTransition] = useTransition();
const respond = (status: EventResponseStatus) => {
const formData = new FormData();
formData.set("eventId", eventId);
formData.set("status", status);
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
if (result.ok) {
setResponse(status);
setError("");
} else {
setError(result.message);
}
});
};
const base =
"min-h-11 rounded-md border px-4 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50";
const active = "border-primary-600 bg-primary-600 text-white";
const inactive = "border-border bg-background hover:bg-accent";
return (
<div className="flex flex-col gap-1">
<div className="flex flex-wrap gap-2" role="group" aria-label="Rückmeldung zu diesem Termin">
<button
type="button"
className={`${base} ${response === "attending" ? active : inactive}`}
aria-pressed={response === "attending"}
disabled={pending}
onClick={() => respond("attending")}
>
Bin da
</button>
<button
type="button"
className={`${base} ${response === "not_attending" ? active : inactive}`}
aria-pressed={response === "not_attending"}
disabled={pending}
onClick={() => respond("not_attending")}
>
Bin nicht da
</button>
</div>
{error ? (
<p role="alert" className="text-xs text-destructive">
{error}
</p>
) : null}
</div>
);
}
@@ -0,0 +1,47 @@
"use client";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import type { CalendarActionResult } from "./actions";
// Grants access to the event's linked album and jumps straight into it.
export function SelfGrantButton({
action,
eventId,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
eventId: string;
}>) {
const router = useRouter();
const [error, setError] = useState("");
const [pending, startTransition] = useTransition();
const handleClick = () => {
const formData = new FormData();
formData.set("eventId", eventId);
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
if (result.ok && result.albumId) {
router.push(`/redaktion/alben/${encodeURIComponent(result.albumId)}`);
} else {
setError(result.message);
}
});
};
return (
<div className="flex flex-col gap-1">
<Button type="button" className="min-h-11" disabled={pending} onClick={handleClick}>
{pending ? "Wird freigeschaltet…" : "Zugriff freischalten"}
</Button>
{error ? (
<p role="alert" className="text-xs text-destructive">
{error}
</p>
) : null}
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireActiveEditorial } from "@/modules/auth/principal";
import {
CalendarServiceError,
calendarService,
type EventResponseStatus,
} from "@/modules/calendar/service";
export type CalendarActionResult = {
ok: boolean;
message: string;
albumId?: string;
};
export async function respondToEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireActiveEditorial(new Headers(await headers()));
const eventId = formData.get("eventId");
const status = formData.get("status");
if (typeof eventId !== "string" || (status !== "attending" && status !== "not_attending")) {
return { ok: false, message: "Ungültige Rückmeldung." };
}
try {
await calendarService.respond({
eventId,
editorialId: principal.editorialId,
actorUserId: principal.userId,
status: status as EventResponseStatus,
});
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/redaktion/kalender");
revalidatePath("/admin/kalender");
return { ok: true, message: "" };
}
export async function selfGrantAlbumAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireActiveEditorial(new Headers(await headers()));
const eventId = formData.get("eventId");
if (typeof eventId !== "string" || eventId.length === 0) {
return { ok: false, message: "Ungültiger Termin." };
}
let albumId: string;
try {
const album = await calendarService.selfGrantAlbum({
eventId,
editorialId: principal.editorialId,
actorUserId: principal.userId,
});
albumId = album.id;
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/redaktion/kalender");
revalidatePath("/redaktion/alben");
revalidatePath(`/redaktion/alben/${albumId}`);
return { ok: true, message: "", albumId };
}
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_STATUS: "Ungültige Rückmeldung.",
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verfügbar.",
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] ?? "Die Aktion konnte nicht ausgeführt werden.";
}
return "Die Aktion konnte nicht ausgeführt werden.";
}
+84
View File
@@ -0,0 +1,84 @@
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
import { calendarService } from "@/modules/calendar/service";
import { requireEditorial } from "../access";
import { EventRsvpButtons } from "./EventRsvpButtons";
import { SelfGrantButton } from "./SelfGrantButton";
import { respondToEventAction, selfGrantAlbumAction } from "./actions";
export default async function EditorialCalendarPage() {
const principal = await requireEditorial();
const { events, immichUnavailable } = await calendarService.listEditorialEvents(
principal.editorialId,
new Date(),
);
const today = isoDateInBerlin(new Date());
const upcoming = events.filter((event) => event.eventDate >= today);
const past = events.filter((event) => event.eventDate < today).reverse();
const ordered = [...upcoming, ...past];
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="calendar-title">
<PageHeader
kicker="Bildarchiv · Kalender"
title="Kalender"
titleId="calendar-title"
description="Kommende Spiele und Termine. Melden Sie zurück, ob Sie da sind, und schalten Sie das Album zum Termin selbst frei, sobald es angelegt ist."
/>
{immichUnavailable ? (
<p className="bg-muted p-4 rounded-md text-sm" role="status">
Das Bildarchiv ist gerade nicht erreichbar. Termine und Rückmeldungen funktionieren weiterhin, Alben erscheinen wieder, sobald die Verbindung steht.
</p>
) : null}
{ordered.length === 0 ? (
<p className="text-muted-foreground text-center py-12">
Zurzeit sind keine Termine eingetragen. Sobald ein Spiel oder Event geplant ist, erscheint es hier.
</p>
) : (
<ul className="space-y-3">
{ordered.map((event) => (
<li
key={event.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col lg:flex-row lg:items-center gap-4 justify-between"
>
<div className="min-w-0 space-y-1">
<p className="font-semibold">
{event.title}
{event.eventDate < today ? (
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
) : null}
</p>
<p className="text-xs text-muted-foreground">{formatIsoDateGerman(event.eventDate)}</p>
{event.album ? null : (
<p className="text-xs text-muted-foreground">Album noch nicht angelegt.</p>
)}
</div>
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
<EventRsvpButtons
action={respondToEventAction}
eventId={event.id}
initialResponse={event.response}
/>
{event.album && event.isGranted ? (
<Link
className="inline-flex min-h-11 items-center justify-center rounded-md border border-border bg-background px-4 text-sm font-medium transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
href={`/redaktion/alben/${encodeURIComponent(event.album.id)}`}
>
Album öffnen
</Link>
) : event.album ? (
<SelfGrantButton action={selfGrantAlbumAction} eventId={event.id} />
) : null}
</div>
</li>
))}
</ul>
)}
</div>
);
}
@@ -22,6 +22,7 @@ test("confirms new and previous uses separately and preserves the keys after a f
]}
options={{
priceCents: 1500,
collabEnabled: false,
priorUsagesByAsset: {
second: [{ id: "prior", purpose: "Früherer Artikel", createdAt: "2026-11-01T12:00:00Z" }],
},
@@ -2,7 +2,7 @@
import { useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Alert, Button, Input } from "@sakaniui/react";
import { Alert, Button, Checkbox, Input } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons";
import { formatBerlinDate } from "@/modules/downloads/format";
@@ -23,6 +23,7 @@ export function DownloadLightboxForm({
const [loading, setLoading] = useState(false);
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);
@@ -74,7 +75,11 @@ export function DownloadLightboxForm({
const response = await fetch("/api/lightbox/bulk-download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items, maxPriceCents: options.priceCents }),
body: JSON.stringify({
items,
maxPriceCents: options.priceCents,
...(collab && newPhotos.length > 0 ? { collab: true } : {}),
}),
});
if (!response.ok) {
@@ -87,6 +92,9 @@ export function DownloadLightboxForm({
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.");
}
@@ -102,6 +110,7 @@ export function DownloadLightboxForm({
dialogRef.current?.close();
setChoices({});
setCommonPurpose("");
setCollab(false);
router.refresh();
} catch (error) {
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
@@ -169,11 +178,21 @@ export function DownloadLightboxForm({
);
})}
</ul>
{options.collabEnabled && newPhotos.length > 0 && (
<Checkbox
checked={collab}
disabled={loading}
label="Collab-Nutzung (kostenfrei)"
description={`Alle ${newPhotos.length} neuen Nutzungen werden mit 0,00 € in der Abrechnung geführt.`}
onChange={(event) => setCollab(event.target.checked)}
/>
)}
{newPhotos.length > 0 && (
<p className="text-sm" role="status">
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} · bis{" "}
{priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto.
Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} ·{" "}
{collab
? "kostenfrei als Collab-Nutzung."
: `bis ${priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto. Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.`}
</p>
)}
{selected.length > 100 && <Alert color="warning" description="Wählen Sie höchstens 100 Bilder pro ZIP aus." />}
+40
View File
@@ -0,0 +1,40 @@
import { PageHeader } from "@/components/ui/page-header";
import { releaseNoteService } from "@/modules/releases/service";
import { requireEditorial } from "../access";
export default async function EditorialNewsPage() {
await requireEditorial();
const notes = await releaseNoteService.listEditorialReleaseNotes();
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="news-title">
<PageHeader
kicker="Portal · Versionshinweise"
title="Neuigkeiten"
titleId="news-title"
description="Was sich im Redaktionsportal geändert hat, neueste Version zuerst."
/>
{notes.length === 0 ? (
<p className="text-muted-foreground text-center py-12">
Noch keine Versionshinweise vorhanden.
</p>
) : (
<ul className="space-y-3">
{notes.map((note) => (
<li key={note.id} className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-1">
<p className="text-sm font-semibold">
Version {note.version}
<span className="ml-2 text-xs font-normal text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(note.createdAt)}
</span>
</p>
<p className="text-sm whitespace-pre-line break-words">{note.body}</p>
</li>
))}
</ul>
)}
</div>
);
}
@@ -107,6 +107,58 @@ test("reuses one idempotency key when the same failed submission is retried", as
}
});
test("collab checkbox only appears for enabled editorials and sends collab with price 0", async () => {
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
const fetch = vi.fn().mockResolvedValue(
Response.json({
downloadId: "66666666-6666-4666-8666-666666666666",
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
priceCents: 0,
billable: true,
}),
);
vi.stubGlobal("fetch", fetch);
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
const { unmount } = render(
<UsageDialog
albumId="33333333-3333-4333-8333-333333333333"
assetId="22222222-2222-4222-8222-222222222222"
filename="tor-des-monats.jpg"
newUsagePriceCents={1_500}
priorUsages={[]}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
expect(screen.queryByRole("checkbox", { name: /collab/i })).toBeNull();
unmount();
render(
<UsageDialog
albumId="33333333-3333-4333-8333-333333333333"
assetId="22222222-2222-4222-8222-222222222222"
filename="tor-des-monats.jpg"
newUsagePriceCents={1_500}
priorUsages={[]}
collabEnabled
/>,
);
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
const checkbox = screen.getByRole("checkbox", { name: /collab-nutzung \(kostenfrei\)/i });
fireEvent.click(checkbox);
expect(screen.getByText("0,00 €")).not.toBeNull();
fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), {
target: { value: "Collab Strecke" },
});
fireEvent.click(screen.getByRole("button", { name: /download anfordern/i }));
await waitFor(() => expect(fetch).toHaveBeenCalledOnce());
expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toMatchObject({
kind: "new_usage",
collab: true,
});
});
test("suppresses double-click submission while one request is pending", async () => {
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
let resolveRequest: ((response: Response) => void) | undefined;
+26 -1
View File
@@ -13,6 +13,7 @@ type UsageDialogProps = Readonly<{
filename: string;
newUsagePriceCents: number;
priorUsages: DownloadDialogUsage[];
collabEnabled?: boolean;
}>;
type IntentResponse = {
@@ -33,18 +34,21 @@ export function UsageDialog({
filename,
newUsagePriceCents,
priorUsages,
collabEnabled = false,
}: UsageDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
const firstChoiceRef = useRef<HTMLInputElement>(null);
const idempotencyKeyRef = useRef<string | null>(null);
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
const [choice, setChoice] = useState(initialChoice);
const [collab, setCollab] = useState(false);
const [purpose, setPurpose] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
function openDialog() {
setChoice(initialChoice);
setCollab(false);
setPurpose("");
setPending(false);
setError(null);
@@ -81,6 +85,7 @@ export function UsageDialog({
albumId,
purpose,
idempotencyKey: idempotencyKeyRef.current,
...(collab ? { collab: true } : {}),
};
try {
@@ -177,10 +182,28 @@ export function UsageDialog({
<strong>Neue Nutzung</strong>
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
</span>
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
<b>{priceFormatter.format((collab ? 0 : newUsagePriceCents) / 100)}</b>
</label>
</fieldset>
{collabEnabled && isNewUsage ? (
<label className="usage-option">
<input
checked={collab}
disabled={pending}
onChange={(event) => {
setCollab(event.target.checked);
resetSubmission();
}}
type="checkbox"
/>
<span>
<strong>Collab-Nutzung (kostenfrei)</strong>
<small>Diese Nutzung wird mit 0,00 € in der Abrechnung geführt.</small>
</span>
</label>
) : null}
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
Verwendungszweck
<textarea
@@ -244,6 +267,8 @@ function downloadErrorMessage(code: string | null, status: number): string {
switch (code) {
case "FORBIDDEN":
return "Ihr Konto ist nicht freigegeben oder gesperrt.";
case "COLLAB_NOT_ENABLED":
return "Collab-Nutzung ist für Ihr Konto nicht freigeschaltet. Bitte den Admin, die Option zu aktivieren.";
case "INVALID_REQUEST":
return "Die Anfrage war unvollständig. Bitte laden Sie die Seite neu und versuchen Sie es erneut.";
case "IDEMPOTENCY_CONFLICT":
+8
View File
@@ -7,11 +7,14 @@ import { useTheme } from "next-themes";
import { Button, IconButton, Sidebar, SidebarHeader, SidebarItem, TopBar } from "@sakaniui/react";
import {
IconBookmark,
IconCalendar,
IconChartBar,
IconChecklist,
IconLayoutDashboard,
IconLibraryPhoto,
IconLogout,
IconMenu2,
IconNews,
IconReceipt,
IconSparkles,
IconSpeakerphone,
@@ -34,8 +37,10 @@ const AREAS = {
label: "Redaktionsportal",
nav: [
{ href: "/redaktion/alben", label: "Alben", icon: IconLibraryPhoto },
{ href: "/redaktion/kalender", label: "Kalender", icon: IconCalendar },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel", icon: IconBookmark },
{ href: "/redaktion/nutzungen", label: "Nutzungen", icon: IconReceipt },
{ href: "/redaktion/neuigkeiten", label: "Neuigkeiten", icon: IconNews },
{ href: "/redaktion/profil", label: "Profil", icon: IconUserCircle },
],
},
@@ -43,9 +48,12 @@ const AREAS = {
label: "Administration",
nav: [
{ href: "/admin", label: "Dashboard", icon: IconLayoutDashboard },
{ href: "/admin/statistiken", label: "Statistiken", icon: IconChartBar },
{ href: "/admin/redaktionen", label: "Redaktionen", icon: IconUsers },
{ href: "/admin/alben", label: "Alben", icon: IconLibraryPhoto },
{ href: "/admin/kalender", label: "Kalender", icon: IconCalendar },
{ href: "/admin/hinweise", label: "Hinweise", icon: IconSpeakerphone },
{ href: "/admin/versionen", label: "Versionen", icon: IconNews },
{ href: "/admin/abrechnungen", label: "Abrechnungen", icon: IconReceipt },
{ href: "/admin/audit", label: "Audit", icon: IconChecklist },
],
+13 -14
View File
@@ -8,24 +8,23 @@ import { IconCheck } from "@sakaniui/react/icons";
// then sees the popup once more. ponytail: only the latest release is kept;
// add a history list when users ask for older notes.
export const RELEASE = {
version: "2.0",
title: "Neues Design",
version: "2.2",
title: "Kalender, Statistiken, Collab und Rechnungen",
notes: {
redaktion: [
"Neues, ruhigeres Design – hell oder dunkel, umschaltbar oben rechts.",
"Navigation links in einer Seitenleiste, auf dem Handy über das Menü-Symbol.",
"Suche und Filter nach Format und Jahr übersichtlich in einem Feld.",
"Nutzungen und Abrechnungen zeigen ihren Status farbig (Offen, Abgerechnet …).",
"Der Download-Dialog erscheint jetzt mittig im Bild.",
"Impressum, Datenschutz und Nutzungsbedingungen finden Sie unten links.",
"Neuer Kalender: kommende Termine sehen, zurückmelden ob Sie da sind, und das verknüpfte Album selbst freischalten.",
"Die Suche findet jetzt auch Dateinamen; Merkzettel-Links führen direkt zum richtigen Bild.",
"Fotos lassen sich nach ältesten und neuesten sortieren; die Bildbeschreibung erscheint in der Großansicht.",
"Wenn Ihre Redaktion für Collab freigeschaltet ist, können Sie Downloads als kostenlose Collab-Nutzung markieren (auch für mehrere Bilder vom Merkzettel).",
"Rechnung und Nutzungsnachweis kommen gebündelt per E-Mail, sobald die Rechnung vorliegt.",
"Alle Versionshinweise finden Sie unter Neuigkeiten.",
],
admin: [
"Neues Design mit Seitenleiste für alle Admin-Bereiche, hell oder dunkel.",
"Dashboard mit Umsatz des Monats und Download-Diagramm der letzten 30 Tage.",
"Redaktionen als Karten mit Status, Preis und offenem Betrag.",
"Albumrechte mit Vorschaubild; zugewiesene Alben sind grün markiert.",
"Abrechnung als Tabelle mit Auswahl, Status und Summe auf einen Blick.",
"Hinweise, Audit-Protokoll und Anmeldung im neuen Layout.",
"Neue Statistik-Seite: Downloads, Datenmenge, Aufrufe, Suchen, Umsatz und Collab-Quote mit Zeitraum-Vergleich.",
"Kalender unter /admin/kalender: Termine anlegen, Alben verknüpfen, Zusagen der Redaktionen einsehen.",
"Collab-Nutzung je Redaktion freischalten; Collab-Positionen erscheinen mit 0,00 € in der Abrechnung und lassen sich dort korrigieren.",
"Rechnungs-PDF je Abrechnung hochladen: danach geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per E-Mail raus. Der Nutzungsnachweis wird beim Finalisieren nicht mehr automatisch verschickt.",
"Versionshinweise werden unter /admin/versionen gepflegt.",
],
},
} as const;
+34
View File
@@ -0,0 +1,34 @@
import { sql } from "drizzle-orm";
import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { editorialAccounts } from "./editorials";
// Lightweight editorial activity trail for the admin statistics page.
// Downloads/usages are NOT duplicated here; they already live in their own
// accounting tables. This table only captures browsing behaviour.
export const activityEvents = pgTable(
"activity_events",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
eventType: text("event_type").notNull(),
immichAlbumId: text("immich_album_id"),
immichAssetId: text("immich_asset_id"),
query: text("query"),
occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("activity_events_occurred_at_idx").on(table.occurredAt.desc()),
index("activity_events_editorial_occurred_idx").on(
table.editorialAccountId,
table.occurredAt.desc(),
),
index("activity_events_type_occurred_idx").on(table.eventType, table.occurredAt.desc()),
check(
"activity_events_event_type_check",
sql`${table.eventType} in ('album_view', 'search', 'lightbox_view')`,
),
],
);
+6
View File
@@ -17,6 +17,11 @@ export const albumGrants = pgTable(
grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
// How the grant came to be: manual admin assignment, an auto-rule sync,
// or editorial self-service via the event calendar. Self-service grants
// are revocable in bulk when their calendar event is deleted; auto-rule
// and admin grants are never touched by the calendar.
source: text("source").notNull().default("admin"),
},
(table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
@@ -28,5 +33,6 @@ export const albumGrants = pgTable(
"album_grants_immich_album_id_uuid_check",
sql`${table.immichAlbumId} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
),
check("album_grants_source_check", sql`${table.source} in ('admin', 'auto_rule', 'self_service')`),
],
);
+19
View File
@@ -1,5 +1,6 @@
import { sql } from "drizzle-orm";
import {
boolean,
check,
customType,
integer,
@@ -43,6 +44,15 @@ export const billingReports = pgTable(
status: reportStatus("status").notNull().default("draft"),
pdf: bytea("pdf"),
pdfSha256: varchar("pdf_sha256", { length: 64 }),
// The actual VAT invoice is uploaded by the admin AFTER finalization.
// Uploading it triggers the bundled email (invoice + Nutzungsnachweis).
invoicePdf: bytea("invoice_pdf"),
invoicePdfSha256: varchar("invoice_pdf_sha256", { length: 64 }),
invoicePdfFilename: text("invoice_pdf_filename"),
invoiceUploadedAt: timestamp("invoice_uploaded_at", { withTimezone: true }),
invoiceEmailStatus: text("invoice_email_status").notNull().default("not_sent"),
invoiceEmailSentAt: timestamp("invoice_email_sent_at", { withTimezone: true }),
invoiceEmailError: text("invoice_email_error"),
createdByUserId: uuid("created_by_user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
@@ -58,6 +68,14 @@ export const billingReports = pgTable(
uniqueIndex("billing_reports_report_number_unique").on(table.reportNumber),
uniqueIndex("billing_reports_invoice_number_unique").on(table.invoiceNumber),
check("billing_reports_pdf_sha256_hex_check", sql`${table.pdfSha256} ~ '^[0-9a-f]{64}$'`),
check(
"billing_reports_invoice_pdf_sha256_hex_check",
sql`${table.invoicePdfSha256} IS NULL OR ${table.invoicePdfSha256} ~ '^[0-9a-f]{64}$'`,
),
check(
"billing_reports_invoice_email_status_check",
sql`${table.invoiceEmailStatus} in ('not_sent', 'sent', 'failed')`,
),
check(
"billing_reports_final_pdf_check",
sql`${table.status} <> 'final' OR (${table.pdf} IS NOT NULL AND ${table.pdfSha256} IS NOT NULL)`,
@@ -81,6 +99,7 @@ export const billingReportItems = pgTable(
purposeSnapshot: text("purpose_snapshot").notNull(),
internalReferenceSnapshot: text("internal_reference_snapshot"),
priceCents: integer("price_cents").notNull(),
collab: boolean("collab").notNull().default(false),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
+42
View File
@@ -0,0 +1,42 @@
import { sql } from "drizzle-orm";
import { check, date, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
import { editorialAccounts } from "./editorials";
// Admin-managed event calendar (e.g. upcoming matches). An event links to an
// Immich album either explicitly (immichAlbumId) or by exact name match once
// the album appears: "{title}" or "{title} | {TT.MM.JJJJ}". Only linked albums
// are eligible for editorial self-service access; auto-rule grants stay
// independent of the calendar.
export const calendarEvents = pgTable("calendar_events", {
id: uuid("id").defaultRandom().primaryKey(),
title: text("title").notNull(),
eventDate: date("event_date").notNull(),
immichAlbumId: text("immich_album_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
});
// Editorial RSVP per event: "attending" or "not_attending". One row per
// (event, editorial); responding again updates the existing row.
export const eventResponses = pgTable(
"event_responses",
{
id: uuid("id").defaultRandom().primaryKey(),
eventId: uuid("event_id")
.notNull()
.references(() => calendarEvents.id, { onDelete: "restrict" }),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
status: text("status").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("event_responses_event_editorial_unique").on(table.eventId, table.editorialAccountId),
check("event_responses_status_check", sql`${table.status} in ('attending', 'not_attending')`),
],
);
+1
View File
@@ -26,6 +26,7 @@ export const editorialAccounts = pgTable("editorial_accounts", {
flatrateActive: boolean("flatrate_active").notNull().default(false),
flatratePriceCents: integer("flatrate_price_cents"),
flatrateAssetLimit: integer("flatrate_asset_limit"),
collabEnabled: boolean("collab_enabled").notNull().default(false),
approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"),
currentBillingAddressVersionId: uuid("current_billing_address_version_id").references(
(): AnyPgColumn => billingAddressVersions.id,
+3
View File
@@ -1,10 +1,13 @@
export * from "./activity";
export * from "./albums";
export * from "./announcements";
export * from "./audit";
export * from "./auth";
export * from "./auto-rules";
export * from "./billing";
export * from "./calendar";
export * from "./editorials";
export * from "./lightbox";
export * from "./rate-limits";
export * from "./releases";
export * from "./usages";
+27
View File
@@ -0,0 +1,27 @@
import { sql } from "drizzle-orm";
import { check, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
// Version notes ("Versionshinweise") maintained by the admin. One row per
// version and audience, so a release can carry separate notes for admins and
// editorial users. The editorial portal shows rows with audience 'editorial'
// or 'both'; the admin overview shows everything.
export const releaseNotes = pgTable(
"release_notes",
{
id: uuid("id").defaultRandom().primaryKey(),
version: text("version").notNull(),
audience: text("audience").notNull().default("both"),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
},
(table) => [
uniqueIndex("release_notes_version_audience_unique").on(table.version, table.audience),
check("release_notes_audience_check", sql`${table.audience} in ('admin', 'editorial', 'both')`),
check("release_notes_version_check", sql`${table.version} ~ '^[0-9]+\\.[0-9]+(\\.[0-9]+)?$'`),
],
);
+1
View File
@@ -43,6 +43,7 @@ export const usages = pgTable(
purpose: text("purpose").notNull(),
internalReference: text("internal_reference"),
priceCents: integer("price_cents").notNull(),
collab: boolean("collab").notNull().default(false),
billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
onDelete: "restrict",
+84
View File
@@ -0,0 +1,84 @@
import { expect, test, vi } from "vitest";
import { createActivityService, normalizeActivityInput } from "./service";
import type { RateLimitPolicy, RateLimitResult } from "@/modules/security/rate-limit";
type Consume = (key: string, policy: RateLimitPolicy) => Promise<RateLimitResult>;
const editorialId = "1111111a-1111-4111-8111-11111111111a";
const albumId = "2222222b-2222-4222-8222-22222222222b";
test("normalizeActivityInput validates ids, types and query length", () => {
expect(
normalizeActivityInput({ editorialId, type: "album_view", albumId }),
).toEqual({ editorialId, type: "album_view", albumId });
expect(normalizeActivityInput({ editorialId: "nope", type: "album_view" })).toBeNull();
expect(
normalizeActivityInput({ editorialId, type: "download" as never }),
).toBeNull();
expect(
normalizeActivityInput({ editorialId, type: "search", albumId: "bad id" }),
).toBeNull();
const normalized = normalizeActivityInput({
editorialId: editorialId.toUpperCase(),
type: "search",
query: ` wob ${"x".repeat(300)} `,
});
expect(normalized?.editorialId).toBe(editorialId);
expect(normalized?.query?.length).toBeLessThanOrEqual(200);
expect(normalized?.query?.startsWith("wob")).toBe(true);
});
function createService(overrides: {
consume?: ReturnType<typeof vi.fn>;
insert?: ReturnType<typeof vi.fn>;
editorialExists?: boolean;
} = {}) {
const insert = overrides.insert ?? vi.fn().mockResolvedValue(undefined);
const consume = (overrides.consume ??
vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 })) as Consume;
const database = {
select: vi.fn().mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue(
overrides.editorialExists === false ? [] : [{ id: editorialId }],
),
}),
}),
}),
insert: vi.fn().mockReturnValue({ values: insert }),
};
return {
service: createActivityService({ database: database as never, consume }),
insert,
consume,
};
}
test("record inserts a normalized activity row", async () => {
const { service, insert } = createService();
await service.record({ editorialId, type: "search", albumId, query: " wob " });
expect(insert).toHaveBeenCalledWith({
editorialAccountId: editorialId,
eventType: "search",
immichAlbumId: albumId,
immichAssetId: null,
query: "wob",
});
});
test("record stays silent when rate-limited, unknown editorial or DB fails", async () => {
const limited = createService({
consume: vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 10 }),
});
await limited.service.record({ editorialId, type: "album_view" });
expect(limited.insert).not.toHaveBeenCalled();
const unknown = createService({ editorialExists: false });
await unknown.service.record({ editorialId, type: "album_view" });
expect(unknown.insert).not.toHaveBeenCalled();
const broken = createService({ insert: vi.fn().mockRejectedValue(new Error("db down")) });
await expect(broken.service.record({ editorialId, type: "album_view" })).resolves.toBeUndefined();
});
+83
View File
@@ -0,0 +1,83 @@
import "server-only";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { activityEvents, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { activityPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
export const ACTIVITY_EVENT_TYPES = ["album_view", "search", "lightbox_view"] as const;
export type ActivityEventType = (typeof ACTIVITY_EVENT_TYPES)[number];
export type RecordActivityInput = {
editorialId: string;
type: ActivityEventType;
albumId?: string;
assetId?: string;
query?: string;
};
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function normalizeActivityInput(input: RecordActivityInput): RecordActivityInput | null {
if (!UUID_PATTERN.test(input.editorialId)) return null;
if (!ACTIVITY_EVENT_TYPES.includes(input.type)) return null;
if (input.albumId !== undefined && !UUID_PATTERN.test(input.albumId)) return null;
if (input.assetId !== undefined && !UUID_PATTERN.test(input.assetId)) return null;
const query = input.query?.replace(/\s+/g, " ").trim().slice(0, 200);
return {
editorialId: input.editorialId.toLowerCase(),
type: input.type,
...(input.albumId === undefined ? {} : { albumId: input.albumId.toLowerCase() }),
...(input.assetId === undefined ? {} : { assetId: input.assetId.toLowerCase() }),
...(query ? { query } : {}),
};
}
export function createActivityService({
database,
consume,
}: {
database: NodePgDatabase<typeof schema>;
consume: typeof consumeRateLimit;
}) {
return {
/**
* Fire-and-forget browsing trail for the statistics page. Never throws and
* never blocks the page: invalid input, rate limits and DB errors are all
* swallowed. Downloads are NOT recorded here (see download_events).
*/
async record(rawInput: RecordActivityInput): Promise<void> {
try {
const input = normalizeActivityInput(rawInput);
if (!input) return;
const limit = await consume(`activity:${input.editorialId}`, activityPolicy);
if (!limit.allowed) return;
const [editorial] = await database
.select({ id: editorialAccounts.id })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.limit(1);
if (!editorial) return;
await database.insert(activityEvents).values({
editorialAccountId: input.editorialId,
eventType: input.type,
immichAlbumId: input.albumId ?? null,
immichAssetId: input.assetId ?? null,
query: input.query ?? null,
});
} catch {
// Observability must never break the editorial experience.
}
},
};
}
export const activityService = createActivityService({
database: db,
consume: consumeRateLimit,
});
export const recordActivity = activityService.record;
+4 -1
View File
@@ -71,6 +71,9 @@ function createFakeGrantService(initial: FakeGrant[] = []) {
async revoke() {
return false;
},
async revokeSelfServiceForAlbum() {
return 0;
},
};
return { repository, grants, grantInputs };
}
@@ -258,6 +261,6 @@ test("applyRules keeps admin attribution for the manual per-editorial run", asyn
await expect(service.applyRules(editorialA, adminUuid)).resolves.toEqual({ granted: 1 });
expect(grantInputs).toEqual([
{ editorialId: editorialA, immichAlbumId: albumFcBayern, adminUserId: adminUuid },
{ editorialId: editorialA, immichAlbumId: albumFcBayern, adminUserId: adminUuid, source: "auto_rule" },
]);
});
+1
View File
@@ -78,6 +78,7 @@ export function createAutoRuleService({
editorialId: input.editorialId,
immichAlbumId: album.id,
adminUserId: input.adminUserId,
source: "auto_rule",
});
grantedAlbumIds.add(album.id);
newlyGrantedAlbumNames.push(album.albumName);
+3 -1
View File
@@ -39,6 +39,7 @@ const photo = {
height: null,
albumId: "heimspiel",
albumName: "Heimspiel gegen Nord",
description: null,
};
test("renders the gallery list labelled by album name", () => {
@@ -55,6 +56,7 @@ test("renders the server-scoped download choices for a catalog photo", () => {
albumName="Heimspiel gegen Nord"
downloadOptions={{
priceCents: 1_500,
collabEnabled: false,
priorUsagesByAsset: {
"22222222-2222-4222-8222-222222222222": [
{
@@ -83,7 +85,7 @@ test("offers the existing download workflow on a global search result and its li
render(
<PhotoGallery
albumName="Alle Alben"
downloadOptions={{ priceCents: 100, priorUsagesByAsset: {} }}
downloadOptions={{ priceCents: 100, collabEnabled: false, priorUsagesByAsset: {} }}
items={[{
...photo,
id: "22222222-2222-4222-8222-222222222222",
+17 -2
View File
@@ -59,6 +59,7 @@ export function PhotoPagination({
query,
format,
jahr,
sortierung,
}: Readonly<{
albumId: string;
currentPage: number;
@@ -66,6 +67,7 @@ export function PhotoPagination({
query: string;
format?: string;
jahr?: string;
sortierung?: string;
}>) {
const hasPrev = currentPage > 1;
const hasNext = page.nextPage !== null;
@@ -73,7 +75,7 @@ export function PhotoPagination({
return null;
}
return <PageLinks prevHref={hasPrev ? pageHref(albumId, currentPage - 1, query, format, jahr) : null} nextHref={hasNext ? pageHref(albumId, currentPage + 1, query, format, jahr) : null} />;
return <PageLinks prevHref={hasPrev ? pageHref(albumId, currentPage - 1, query, format, jahr, sortierung) : null} nextHref={hasNext ? pageHref(albumId, currentPage + 1, query, format, jahr, sortierung) : null} />;
}
// Server-rendered prev/next links (album search, usage history, …).
@@ -101,6 +103,11 @@ const FORMAT_OPTIONS = [
{ label: "Hochformat", value: "hoch" },
];
const SORT_OPTIONS = [
{ label: "Neueste zuerst", value: "neueste" },
{ label: "Älteste zuerst", value: "aelteste" },
];
// Plain GET form (works without JS) for the album overview and album detail.
// `withYear` adds the year filter the overview offers.
export function PhotoSearchForm({
@@ -108,6 +115,7 @@ export function PhotoSearchForm({
query,
format,
jahr,
sortierung,
withYear = false,
placeholder,
ariaLabel,
@@ -116,6 +124,7 @@ export function PhotoSearchForm({
query: string;
format?: string;
jahr?: string;
sortierung?: string;
withYear?: boolean;
placeholder: string;
ariaLabel?: string;
@@ -127,11 +136,12 @@ export function PhotoSearchForm({
<form
action={action}
aria-label={ariaLabel}
className={`grid gap-4 sm:items-end ${withYear ? "sm:grid-cols-[1fr_10rem_8rem_auto]" : "sm:grid-cols-[1fr_10rem_auto]"}`}
className={`grid gap-4 sm:items-end ${withYear ? "sm:grid-cols-[1fr_10rem_9rem_8rem_auto]" : "sm:grid-cols-[1fr_10rem_9rem_auto]"}`}
role="search"
>
<Input type="search" name="suche" label="Suche" defaultValue={query} placeholder={placeholder} leadingIcon={<IconSearch size={16} />} />
<FormSelect name="format" label="Format" defaultValue={format ?? ""} options={FORMAT_OPTIONS} />
<FormSelect name="sortierung" label="Sortierung" defaultValue={sortierung ?? "neueste"} options={SORT_OPTIONS} />
{withYear ? (
<FormSelect
name="jahr"
@@ -156,6 +166,7 @@ export function pageHref(
query: string,
format?: string,
jahr?: string,
sortierung?: string,
): string {
const parameters = new URLSearchParams({ page: String(page) });
if (query) {
@@ -167,6 +178,10 @@ export function pageHref(
if (jahr) {
parameters.set("jahr", jahr);
}
// Only the non-default order travels in links; newest-first stays implicit.
if (sortierung === "aelteste") {
parameters.set("sortierung", "aelteste");
}
return `/redaktion/alben/${encodeURIComponent(albumId)}?${parameters.toString()}`;
}
+34
View File
@@ -62,6 +62,39 @@ test("uses a requested album only when it is in the current editorial grants", a
);
});
test("a query searches description and filename and merges deduplicated", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
const asset = (id: string, fileName: string) => ({
id,
type: "IMAGE" as const,
originalFileName: fileName,
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "allowed" }],
});
immich.searchPhotos.mockImplementation(async (input: { description?: string; originalFileName?: string }) => {
if (input.description) {
return { items: [asset("a1", "tor.jpg"), asset("a2", "jubel.jpg")], total: 2, nextPage: null, previousPage: null };
}
return { items: [asset("a2", "jubel.jpg"), asset("a3", "torjubel.jpg")], total: 2, nextPage: null, previousPage: null };
});
const result = await catalog.searchVisiblePhotos("editorial-1", {
requestedAlbumId: "allowed",
description: "tor",
page: 1,
});
expect(result.items.map((item) => item.id)).toEqual(["a1", "a2", "a3"]);
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["allowed"], description: "tor" }),
);
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["allowed"], originalFileName: "tor" }),
);
});
test("restores the queried granted album when Immich omits an asset album association", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
immich.searchPhotos.mockResolvedValue({
@@ -116,6 +149,7 @@ test("projects only display fields and the queried granted album for the client
height: 800,
albumId: "allowed",
albumName: "Heimspiel gegen Nord",
description: null,
}]);
});
+38 -4
View File
@@ -24,6 +24,8 @@ export type GalleryPhoto = {
height: number | null;
albumId: string;
albumName: string | null;
/** Photographer description from EXIF; shown in the lightbox as plain text. */
description: string | null;
};
type GalleryPage = Omit<ImmichSearchPage, "items"> & { items: GalleryPhoto[] };
@@ -91,7 +93,7 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
if (albumIds.length === 0) {
return emptySearchPage();
}
return searchAlbum(immich, albumIds, description, page, size);
return searchAlbumMerged(immich, albumIds, description, page, size);
}
// Cross-album search. Immich's `albumIds` filter is AND across albums —
@@ -106,25 +108,56 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
const visibleAlbums = new Map((await loadAlbums(immich)).map(({ id, albumName }) => [id, albumName]));
const pages = await Promise.all(
grantedAlbumIds.filter((id) => visibleAlbums.has(id))
.map((albumId) => searchAlbum(immich, [albumId], description, page, size, visibleAlbums.get(albumId))),
.map((albumId) => searchAlbumMerged(immich, [albumId], description, page, size, visibleAlbums.get(albumId) ?? null)),
);
return mergeSearchPages(pages);
},
};
}
async function searchAlbum(
/**
* A query matches the photographer description OR the original filename (the
* Merkzettel deep-links into the album search with filenames). Immich combines
* metadata filters with AND, so the two predicates run as separate searches
* and merge deduplicated. ponytail: two upstream calls per album when a query
* is present; bounded by the grant count and the per-album size cap.
*/
async function searchAlbumMerged(
immich: Pick<ImmichClient, "searchPhotos">,
albumIds: string[],
description: string | undefined,
page: number,
size: number,
albumName: string | null = null,
): Promise<GalleryPage> {
if (description === undefined) {
return searchAlbum(immich, albumIds, {}, page, size, albumName);
}
const [byDescription, byFileName] = await Promise.all([
searchAlbum(immich, albumIds, { description }, page, size, albumName),
searchAlbum(immich, albumIds, { originalFileName: description }, page, size, albumName),
]);
const seen = new Set<string>();
const items = [...byDescription.items, ...byFileName.items].filter((item) => {
if (seen.has(item.id)) return false;
seen.add(item.id);
return true;
});
return { items, total: items.length, nextPage: null, previousPage: null };
}
async function searchAlbum(
immich: Pick<ImmichClient, "searchPhotos">,
albumIds: string[],
filter: { description?: string; originalFileName?: string },
page: number,
size: number,
albumName: string | null = null,
): Promise<GalleryPage> {
try {
const searchPage = await immich.searchPhotos({
albumIds,
...(description === undefined ? {} : { description }),
...filter,
type: "IMAGE",
page,
size,
@@ -139,6 +172,7 @@ async function searchAlbum(
height: asset.exifInfo?.exifImageHeight ?? null,
albumId: albumIds[0],
albumName,
description: asset.exifInfo?.description?.trim() || null,
})),
};
} catch {
+32 -1
View File
@@ -1,6 +1,6 @@
import { expect, test } from "vitest";
import { filterPhotos, matchesOrientation, matchesYear, paginatePhotos } from "./filter";
import { filterPhotos, matchesOrientation, matchesYear, normalizeSort, paginatePhotos, sortPhotos } from "./filter";
import type { GalleryPhoto } from "./catalog";
function photo(overrides: Partial<GalleryPhoto> & { id: string }): GalleryPhoto {
@@ -11,6 +11,7 @@ function photo(overrides: Partial<GalleryPhoto> & { id: string }): GalleryPhoto
height: null,
albumId: "album",
albumName: null,
description: null,
...overrides,
};
}
@@ -85,3 +86,33 @@ test("paginatePhotos handles an empty set without dividing by zero", () => {
expect(result.nextPage).toBeNull();
expect(result.previousPage).toBeNull();
});
test("normalizeSort only accepts aelteste, everything else stays newest-first", () => {
expect(normalizeSort("aelteste")).toBe("aelteste");
expect(normalizeSort("neueste")).toBe("neueste");
expect(normalizeSort(undefined)).toBe("neueste");
expect(normalizeSort("DESC")).toBe("neueste");
expect(normalizeSort(["aelteste"])).toBe("neueste");
});
test("sortPhotos orders the whole set by capture date in both directions", () => {
const items = [
photo({ id: "mid", takenAt: "2026-05-01T10:00:00.000Z" }),
photo({ id: "old", takenAt: "2025-01-01T10:00:00.000Z" }),
photo({ id: "new", takenAt: "2026-09-01T10:00:00.000Z" }),
];
expect(sortPhotos(items, "neueste").map((p) => p.id)).toEqual(["new", "mid", "old"]);
expect(sortPhotos(items, "aelteste").map((p) => p.id)).toEqual(["old", "mid", "new"]);
// Does not mutate the input order.
expect(items.map((p) => p.id)).toEqual(["mid", "old", "new"]);
});
test("sortPhotos keeps undated and broken-date assets last in both directions", () => {
const items = [
photo({ id: "undated", takenAt: null }),
photo({ id: "dated", takenAt: "2026-03-01T00:00:00.000Z" }),
photo({ id: "broken", takenAt: "not-a-date" }),
];
expect(sortPhotos(items, "neueste").map((p) => p.id)).toEqual(["dated", "undated", "broken"]);
expect(sortPhotos(items, "aelteste").map((p) => p.id)).toEqual(["dated", "undated", "broken"]);
});
+30
View File
@@ -39,6 +39,36 @@ export function filterPhotos(
return filtered;
}
export type PhotoSort = "neueste" | "aelteste";
/** Only "aelteste" flips the order; anything else keeps the newest-first default. */
export function normalizeSort(value: unknown): PhotoSort {
return value === "aelteste" ? "aelteste" : "neueste";
}
/**
* Sort the fetched set by capture date before paginating, so the order holds
* across the whole result (and across merged per-album pages in the global
* search), not just within one upstream page. Assets without a usable date
* keep a stable order at the end in both directions.
*/
export function sortPhotos(items: GalleryPhoto[], sort: PhotoSort): GalleryPhoto[] {
const direction = sort === "aelteste" ? 1 : -1;
const timestamp = (asset: GalleryPhoto): number | null => {
if (!asset.takenAt) return null;
const parsed = Date.parse(asset.takenAt);
return Number.isNaN(parsed) ? null : parsed;
};
return [...items].sort((left, right) => {
const leftTime = timestamp(left);
const rightTime = timestamp(right);
if (leftTime === null && rightTime === null) return 0;
if (leftTime === null) return 1;
if (rightTime === null) return -1;
return (leftTime - rightTime) * direction;
});
}
export type InAppPage = {
items: GalleryPhoto[];
total: number;
+57 -5
View File
@@ -11,7 +11,7 @@ import {
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null };
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null; source?: string };
type Audit = {
eventType: string;
actorUserId: string | null;
@@ -183,8 +183,14 @@ function createRepository(
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
survivor.source = input.source ?? "admin";
} else {
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
grants.push({
editorialId: input.editorialId,
albumId: input.immichAlbumId,
revokedAt: null,
source: input.source ?? "admin",
});
}
audit.push({
eventType: "album_granted",
@@ -192,7 +198,7 @@ function createRepository(
editorialId: input.editorialId,
albumId: input.immichAlbumId,
previousValues: { granted: false },
newValues: { granted: true },
newValues: { granted: true, source: input.source ?? "admin" },
});
return true;
},
@@ -217,6 +223,18 @@ function createRepository(
});
return true;
},
async revokeSelfServiceForAlbum(immichAlbumId) {
const active = grants.filter(
(grant) =>
grant.albumId.toLowerCase() === immichAlbumId &&
grant.source === "self_service" &&
grant.revokedAt === null,
);
for (const grant of active) {
grant.revokedAt = new Date();
}
return active.length;
},
};
return { repository, grants, audit };
}
@@ -269,7 +287,7 @@ test("canonicalizes UUID grant input before Immich and repository side effects",
expect(immich.getAlbum).toHaveBeenCalledWith(albumUuid);
expect(grants).toEqual([
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null, source: "admin" },
]);
});
@@ -378,7 +396,7 @@ test("granting an album is idempotent and records one state-change audit event",
editorialId: editorialUuid,
albumId: albumUuid,
previousValues: { granted: false },
newValues: { granted: true },
newValues: { granted: true, source: "admin" },
}),
]);
});
@@ -564,3 +582,37 @@ test("bulk grant reports a stable unavailable error when Immich is down", async
).rejects.toEqual(new AlbumGrantError("IMMICH_UNAVAILABLE"));
expect(grants).toHaveLength(0);
});
test("self-service revoke only retires self-service grants, never admin or auto-rule grants", async () => {
const { service, grants } = createService();
await service.grantAlbum({ editorialId: editorialUuid, immichAlbumId: albumUuid, adminUserId: adminUuid });
await service.grantAlbum({
editorialId: secondEditorialUuid,
immichAlbumId: albumUuid,
adminUserId: null,
source: "auto_rule",
});
await service.grantAlbum({
editorialId: secondEditorialUuid,
immichAlbumId: secondAlbumUuid,
adminUserId: null,
source: "self_service",
});
await expect(service.revokeSelfServiceGrantsForAlbum(secondAlbumUuid)).resolves.toBe(1);
const active = grants.filter((grant) => grant.revokedAt === null);
expect(active).toHaveLength(2);
expect(active.every((grant) => grant.albumId === albumUuid)).toBe(true);
});
test("grant records its source for the audit trail", async () => {
const { service, audit } = createService();
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: null,
source: "self_service",
});
expect(audit[0].newValues.source).toBe("self_service");
});
+66
View File
@@ -12,11 +12,15 @@ import type { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
export type AssignableAlbum = ImmichAlbumSummary & { isGranted: boolean };
export type AlbumGrantSource = "admin" | "auto_rule" | "self_service";
export type AlbumGrantInput = {
editorialId: string;
immichAlbumId: string;
/** Admin user for audit attribution; null marks an automated (system) grant. */
adminUserId: string | null;
/** How the grant came to be; defaults to a manual admin assignment. */
source?: AlbumGrantSource;
};
export type AlbumGrantHolder = {
@@ -48,6 +52,7 @@ export type AlbumGrantRepository = {
>;
grant(input: AlbumGrantInput): Promise<boolean>;
revoke(input: AlbumGrantInput): Promise<boolean>;
revokeSelfServiceForAlbum(immichAlbumId: string): Promise<number>;
};
export type AlbumGrantMutationCandidate = {
@@ -117,6 +122,15 @@ export function createAlbumGrantService({
await repository.revoke(normalizeInput(input));
},
/**
* Revokes only self-service grants for one album (used when its calendar
* event is deleted). Admin and auto-rule grants are never touched, so
* automatic keyword assignments keep outranking the calendar.
*/
async revokeSelfServiceGrantsForAlbum(immichAlbumId: string): Promise<number> {
return repository.revokeSelfServiceForAlbum(normalizeIdentifier(immichAlbumId));
},
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId));
return uniqueCanonicalIdentifiers(albumIds);
@@ -258,6 +272,7 @@ export function createAlbumGrantRepository(
immichAlbumId: input.immichAlbumId,
grantedAt: changedAt,
grantedByUserId: input.adminUserId,
source: input.source ?? "admin",
revokedAt: null,
})
.where(eq(albumGrants.id, plan.survivorId));
@@ -267,6 +282,7 @@ export function createAlbumGrantRepository(
immichAlbumId: input.immichAlbumId,
grantedAt: changedAt,
grantedByUserId: input.adminUserId,
source: input.source ?? "admin",
});
}
@@ -285,6 +301,7 @@ export function createAlbumGrantRepository(
editorialId: editorial.id,
immichAlbumId: input.immichAlbumId,
granted: true,
source: input.source ?? "admin",
},
occurredAt: changedAt,
});
@@ -292,6 +309,54 @@ export function createAlbumGrantRepository(
});
},
async revokeSelfServiceForAlbum(immichAlbumId) {
return database.transaction(async (transaction) => {
const grants = await transaction
.select({ id: albumGrants.id, editorialAccountId: albumGrants.editorialAccountId })
.from(albumGrants)
.where(
and(
sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`,
eq(albumGrants.source, "self_service"),
isNull(albumGrants.revokedAt),
),
)
.for("update");
if (grants.length === 0) {
return 0;
}
const changedAt = new Date();
await transaction
.update(albumGrants)
.set({ revokedAt: changedAt })
.where(inArray(albumGrants.id, grants.map((grant) => grant.id)));
for (const grant of grants) {
await transaction.insert(auditEvents).values({
eventType: "album_revoked",
actorUserId: null,
actorType: "system",
entityType: "album_grant",
entityId: immichAlbumId,
previousValues: {
editorialId: grant.editorialAccountId,
immichAlbumId,
granted: true,
source: "self_service",
},
newValues: {
editorialId: grant.editorialAccountId,
immichAlbumId,
granted: false,
reason: "calendar_event_deleted",
},
occurredAt: changedAt,
});
}
return grants.length;
});
},
async revoke(input) {
return database.transaction(async (transaction) => {
await lockEditorialAlbumMutation(transaction, input.editorialId);
@@ -350,6 +415,7 @@ function normalizeInput(input: AlbumGrantInput): AlbumGrantInput {
immichAlbumId: normalizeIdentifier(input.immichAlbumId),
adminUserId:
input.adminUserId === null ? null : normalizeIdentifier(input.adminUserId),
source: input.source ?? "admin",
};
}
+17
View File
@@ -32,6 +32,20 @@ export function PhotoGallery({
const [openIndex, setOpenIndex] = useState<number | null>(null);
const inLightbox = new Set(lightboxAssetIds);
// Lightbox-view beacon for the admin statistics page. Fire-and-forget; the
// server rate-limits and never lets tracking break the gallery.
useEffect(() => {
if (openIndex === null) return;
const asset = items[openIndex];
if (!asset) return;
fetch("/api/activity", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "lightbox_view", assetId: asset.id, albumId: asset.albumId }),
keepalive: true,
}).catch(() => undefined);
}, [openIndex, items]);
// Keyboard nav + scroll lock while the lightbox is open. ponytail: a single
// window listener is enough; the lightbox is the only overlay in this view.
useEffect(() => {
@@ -100,6 +114,7 @@ export function PhotoGallery({
filename={asset.filename}
newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
collabEnabled={downloadOptions.collabEnabled}
/>
) : null}
</div>
@@ -161,6 +176,7 @@ function PhotoLightbox({
<figcaption className="lightbox-caption">
<span className="photo-tile-name">{asset.filename}</span>
<span className="photo-tile-date">{formatDate(asset.takenAt)}</span>
{asset.description ? <p className="lightbox-description">{asset.description}</p> : null}
</figcaption>
</figure>
<div className="lightbox-actions">
@@ -172,6 +188,7 @@ function PhotoLightbox({
filename={asset.filename}
newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
collabEnabled={downloadOptions.collabEnabled}
/>
) : null}
</div>
+141
View File
@@ -0,0 +1,141 @@
import { expect, test, vi } from "vitest";
import {
assertPdfBytes,
createInvoiceService,
formatPeriodLabel,
InvoiceError,
type InvoiceReport,
type InvoiceRepository,
} from "./invoice";
const reportId = "1111111a-1111-4111-8111-11111111111a";
const editorialId = "2222222b-2222-4222-8222-22222222222b";
const adminUserId = "3333333c-3333-4333-8333-33333333333c";
const pdfBytes = Buffer.from("%PDF-1.4 test invoice");
function baseReport(overrides: Partial<InvoiceReport> = {}): InvoiceReport {
return {
id: reportId,
status: "final",
editorialAccountId: editorialId,
reportNumber: 7,
invoiceNumber: "NN-2026-0007",
periodStartsAt: new Date("2026-07-01T00:00:00.000Z"),
periodEndsAt: new Date("2026-10-01T00:00:00.000Z"),
pdf: Buffer.from("%PDF-1.4 nutzungsnachweis"),
invoicePdf: null,
invoicePdfFilename: null,
...overrides,
};
}
function createRepo(report: InvoiceReport | null) {
let stored = report;
const repo: InvoiceRepository = {
getReport: vi.fn(async () => stored),
getEditorialEmail: vi.fn(async () => "redaktion@example.com"),
storeInvoice: vi.fn(async (_id, input) => {
if (stored) {
stored = {
...stored,
invoicePdf: input.bytes,
invoicePdfFilename: input.filename,
};
}
}),
markEmailOutcome: vi.fn(async () => undefined),
};
return { repo, getStored: () => stored };
}
test("assertPdfBytes accepts PDF magic and rejects everything else", () => {
expect(() => assertPdfBytes(pdfBytes)).not.toThrow();
expect(() => assertPdfBytes(Buffer.alloc(0))).toThrow(InvoiceError);
const zipMagic = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from("zip")]);
expect(() => assertPdfBytes(zipMagic)).toThrow(InvoiceError);
expect(() => assertPdfBytes(Buffer.alloc(21 * 1024 * 1024))).toThrow(InvoiceError);
});
test("formatPeriodLabel renders Berlin months and quarters", () => {
expect(
formatPeriodLabel(new Date("2026-08-01T00:00:00.000Z"), new Date("2026-09-01T00:00:00.000Z")),
).toBe("August 2026");
expect(
formatPeriodLabel(new Date("2026-07-01T00:00:00.000Z"), new Date("2026-10-01T00:00:00.000Z")),
).toBe("Q3 2026");
// Berlin rollover: Dec 31 23:00 UTC is already January in Berlin.
expect(
formatPeriodLabel(new Date("2026-12-31T23:00:00.000Z"), new Date("2027-02-01T00:00:00.000Z")),
).toBe("Januar 2027");
});
test("upload stores the PDF and sends the bundled email", async () => {
const { repo } = createRepo(baseReport());
const sendEmail = vi.fn().mockResolvedValue(undefined);
const service = createInvoiceService({ repo, sendEmail });
const result = await service.uploadInvoice({
reportId,
bytes: pdfBytes,
filename: "rechnung.pdf",
adminUserId,
});
expect(result.emailStatus).toBe("sent");
expect(repo.storeInvoice).toHaveBeenCalledOnce();
expect(sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
toEmail: "redaktion@example.com",
periodLabel: "Q3 2026",
invoiceNumber: "NN-2026-0007",
}),
);
expect(repo.markEmailOutcome).toHaveBeenCalledWith(reportId, "sent", null);
});
test("a failed send keeps the upload and marks the outcome failed", async () => {
const { repo, getStored } = createRepo(baseReport());
const sendEmail = vi.fn().mockRejectedValue(new Error("smtp down"));
const service = createInvoiceService({ repo, sendEmail });
const result = await service.uploadInvoice({
reportId,
bytes: pdfBytes,
filename: "rechnung.pdf",
adminUserId,
});
expect(result.emailStatus).toBe("failed");
expect(getStored()?.invoicePdf).toEqual(pdfBytes);
expect(repo.markEmailOutcome).toHaveBeenCalledWith(reportId, "failed", "smtp down");
});
test("upload rejects non-final reports and non-PDF bytes", async () => {
const { repo } = createRepo(baseReport({ status: "cancelled" }));
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(
service.uploadInvoice({ reportId, bytes: pdfBytes, filename: "r.pdf", adminUserId }),
).rejects.toMatchObject({ code: "REPORT_NOT_FINAL" });
const final = createRepo(baseReport());
const service2 = createInvoiceService({ repo: final.repo, sendEmail: vi.fn() });
await expect(
service2.uploadInvoice({ reportId, bytes: Buffer.from("nope"), filename: "r.pdf", adminUserId }),
).rejects.toMatchObject({ code: "INVALID_PDF" });
});
test("resend requires an uploaded invoice", async () => {
const { repo } = createRepo(baseReport());
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(
service.resendInvoice({ reportId, adminUserId }),
).rejects.toMatchObject({ code: "INVOICE_NOT_UPLOADED" });
});
test("getInvoicePdf returns null without an uploaded invoice", async () => {
const { repo } = createRepo(baseReport());
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(service.getInvoicePdf(reportId)).resolves.toBeNull();
});
+302
View File
@@ -0,0 +1,302 @@
import "server-only";
import { createHash } from "node:crypto";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { billingReports, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
import { emailService } from "@/modules/email/service";
export const INVOICE_PDF_MAX_BYTES = 20 * 1024 * 1024;
export class InvoiceError extends Error {
readonly name = "InvoiceError";
constructor(
readonly code:
| "REPORT_NOT_FOUND"
| "REPORT_NOT_FINAL"
| "INVALID_PDF"
| "INVOICE_NOT_UPLOADED"
| "EDITORIAL_NOT_FOUND",
) {
super(code);
}
}
export type InvoiceReport = {
id: string;
status: "draft" | "final" | "cancelled";
editorialAccountId: string;
reportNumber: number;
invoiceNumber: string | null;
periodStartsAt: Date;
periodEndsAt: Date;
pdf: Buffer | null;
invoicePdf: Buffer | null;
invoicePdfFilename: string | null;
};
export type InvoiceEmailOutcome = "sent" | "failed";
export type InvoiceRepository = {
getReport(reportId: string): Promise<InvoiceReport | null>;
getEditorialEmail(editorialId: string): Promise<string | null>;
storeInvoice(
reportId: string,
input: { bytes: Buffer; sha256: string; filename: string; uploadedAt: Date },
): Promise<void>;
markEmailOutcome(
reportId: string,
outcome: InvoiceEmailOutcome,
error: string | null,
): Promise<void>;
};
export type SendInvoiceBundle = (input: {
toEmail: string;
periodLabel: string;
invoicePdf: Buffer;
reportPdf: Buffer;
invoiceNumber: string;
}) => Promise<void>;
export function createInvoiceService({
repo,
sendEmail,
}: {
repo: InvoiceRepository;
sendEmail: SendInvoiceBundle;
}) {
async function dispatch(report: InvoiceReport, adminUserId: string): Promise<InvoiceEmailOutcome> {
const invoicePdf = report.invoicePdf;
if (!invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED");
const toEmail = await repo.getEditorialEmail(report.editorialAccountId);
if (!toEmail) throw new InvoiceError("EDITORIAL_NOT_FOUND");
const periodLabel = formatPeriodLabel(report.periodStartsAt, report.periodEndsAt);
const invoiceNumber = report.invoiceNumber ?? String(report.reportNumber);
try {
await sendEmail({
toEmail,
periodLabel,
invoicePdf,
reportPdf: report.pdf ?? Buffer.alloc(0),
invoiceNumber,
});
await repo.markEmailOutcome(report.id, "sent", null);
await audit("invoice_email_sent", adminUserId, report.id, { toEmail, periodLabel });
return "sent";
} catch (error) {
const message = error instanceof Error ? error.message.slice(0, 500) : "unknown";
await repo.markEmailOutcome(report.id, "failed", message);
await audit("invoice_email_failed", adminUserId, report.id, { toEmail, error: message });
return "failed";
}
}
return {
/**
* Stores the admin-uploaded invoice PDF on a finalized report and sends
* the bundled email (invoice + Nutzungsnachweis). A failed send does not
* undo the upload; the admin can resend from the report list.
*/
async uploadInvoice(input: {
reportId: string;
bytes: Buffer;
filename: string;
adminUserId: string;
}): Promise<{ emailStatus: InvoiceEmailOutcome }> {
assertPdfBytes(input.bytes);
const report = await repo.getReport(input.reportId);
if (!report) throw new InvoiceError("REPORT_NOT_FOUND");
if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL");
const sha256 = createHash("sha256").update(input.bytes).digest("hex");
const filename = sanitizeFilename(input.filename);
await repo.storeInvoice(input.reportId, {
bytes: input.bytes,
sha256,
filename,
uploadedAt: new Date(),
});
await audit("invoice_uploaded", input.adminUserId, input.reportId, {
filename,
sizeBytes: input.bytes.length,
sha256,
});
const updated = await repo.getReport(input.reportId);
if (!updated) throw new InvoiceError("REPORT_NOT_FOUND");
const emailStatus = await dispatch(updated, input.adminUserId);
return { emailStatus };
},
async resendInvoice(input: {
reportId: string;
adminUserId: string;
}): Promise<{ emailStatus: InvoiceEmailOutcome }> {
const report = await repo.getReport(input.reportId);
if (!report) throw new InvoiceError("REPORT_NOT_FOUND");
if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL");
if (!report.invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED");
const emailStatus = await dispatch(report, input.adminUserId);
return { emailStatus };
},
async getInvoicePdf(
reportId: string,
): Promise<{ bytes: Buffer; filename: string } | null> {
const report = await repo.getReport(reportId);
if (!report || report.status !== "final" || !report.invoicePdf) return null;
return {
bytes: report.invoicePdf,
filename: report.invoicePdfFilename ?? `rechnung-${report.reportNumber}.pdf`,
};
},
};
}
export function assertPdfBytes(bytes: Buffer): void {
if (
bytes.length === 0 ||
bytes.length > INVOICE_PDF_MAX_BYTES ||
bytes.subarray(0, 5).toString("latin1") !== "%PDF-"
) {
throw new InvoiceError("INVALID_PDF");
}
}
function sanitizeFilename(value: string): string {
const cleaned = value.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_").trim().slice(0, 180);
return cleaned.toLowerCase().endsWith(".pdf") ? cleaned : `${cleaned || "rechnung"}.pdf`;
}
/**
* Human period label for the invoice email, derived from the stored report
* period (Europe/Berlin). Spans longer than 40 days are treated as quarters.
*/
export function formatPeriodLabel(startsAt: Date, endsAt: Date): string {
const spanDays = (endsAt.getTime() - startsAt.getTime()) / 86_400_000;
const parts = new Intl.DateTimeFormat("de-DE", {
month: "long",
year: "numeric",
timeZone: "Europe/Berlin",
}).formatToParts(startsAt);
const month = parts.find((part) => part.type === "month")?.value ?? "";
const year = parts.find((part) => part.type === "year")?.value ?? "";
if (spanDays > 40) {
const monthIndex = new Intl.DateTimeFormat("en-US", {
month: "numeric",
timeZone: "Europe/Berlin",
}).format(startsAt);
const quarter = Math.floor((Number(monthIndex) - 1) / 3) + 1;
return `Q${quarter} ${year}`;
}
return `${month} ${year}`;
}
async function audit(
type: string,
adminUserId: string,
reportId: string,
metadata: Record<string, unknown>,
): Promise<void> {
try {
await writeAudit({
type,
actorUserId: adminUserId,
actorType: "admin",
entityType: "billing_report",
entityId: reportId,
metadata,
});
} catch {
// Audit is observability, not a transaction participant.
}
}
// ---------------------------------------------------------------------------
// Drizzle repository
// ---------------------------------------------------------------------------
export function createInvoiceRepository(
database: NodePgDatabase<typeof schema>,
): InvoiceRepository {
return {
async getReport(reportId) {
const [row] = await database
.select({
id: billingReports.id,
status: billingReports.status,
editorialAccountId: billingReports.editorialAccountId,
reportNumber: billingReports.reportNumber,
invoiceNumber: billingReports.invoiceNumber,
periodStartsAt: billingReports.periodStartsAt,
periodEndsAt: billingReports.periodEndsAt,
pdf: billingReports.pdf,
invoicePdf: billingReports.invoicePdf,
invoicePdfFilename: billingReports.invoicePdfFilename,
})
.from(billingReports)
.where(eq(billingReports.id, reportId))
.limit(1);
return (row as InvoiceReport | undefined) ?? null;
},
async getEditorialEmail(editorialId) {
const [row] = await database
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
return row?.email ?? null;
},
async storeInvoice(reportId, input) {
await database
.update(billingReports)
.set({
invoicePdf: input.bytes,
invoicePdfSha256: input.sha256,
invoicePdfFilename: input.filename,
invoiceUploadedAt: input.uploadedAt,
invoiceEmailStatus: "not_sent",
invoiceEmailSentAt: null,
invoiceEmailError: null,
})
.where(eq(billingReports.id, reportId));
},
async markEmailOutcome(reportId, outcome, error) {
await database
.update(billingReports)
.set({
invoiceEmailStatus: outcome,
invoiceEmailSentAt: outcome === "sent" ? new Date() : null,
invoiceEmailError: error,
})
.where(eq(billingReports.id, reportId));
},
};
}
export const invoiceService = createInvoiceService({
repo: createInvoiceRepository(db),
sendEmail: async (input) => {
await emailService.sendInvoiceBundle(
input.toEmail,
input.periodLabel,
input.invoicePdf,
input.reportPdf,
input.invoiceNumber,
);
},
});
export const uploadInvoice = invoiceService.uploadInvoice;
export const resendInvoice = invoiceService.resendInvoice;
export const getInvoicePdf = invoiceService.getInvoicePdf;
+8
View File
@@ -50,6 +50,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Titelgeschichte",
internalReference: "Ausgabe 8/26",
priceCents: 1_500,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-05T10:00:00.000Z"),
billingReportId: null,
@@ -64,6 +65,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Sportbericht",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "billed",
createdAt: new Date("2026-08-06T10:00:00.000Z"),
billingReportId: "r1",
@@ -78,6 +80,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Reopened story",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "reopened",
createdAt: new Date("2026-08-07T10:00:00.000Z"),
billingReportId: null,
@@ -103,6 +106,7 @@ test("maps raw billable usages to billing positions with snapshot fields", async
purpose: "Titelgeschichte",
internalReference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-05T10:00:00.000Z"),
billingReportId: null,
@@ -120,6 +124,7 @@ test("maps raw billable usages to billing positions with snapshot fields", async
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
status: "open",
selectable: true,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
@@ -138,6 +143,7 @@ test("surfaces report and invoice references on billed positions", async () => {
purpose: "Sportbericht",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "billed",
createdAt: new Date("2026-08-06T10:00:00.000Z"),
billingReportId: "r1",
@@ -164,6 +170,7 @@ test("excludes voided usages from billable positions", async () => {
purpose: "Voided",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "voided",
createdAt: new Date("2026-08-03T10:00:00.000Z"),
billingReportId: null,
@@ -178,6 +185,7 @@ test("excludes voided usages from billable positions", async () => {
purpose: "Open",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-04T10:00:00.000Z"),
billingReportId: null,
+4
View File
@@ -21,6 +21,7 @@ export type BillingPosition = {
purpose: string;
reference: string | null;
priceCents: number;
collab: boolean;
status: "open" | "billed" | "reopened";
selectable: boolean;
createdAt: Date;
@@ -49,6 +50,7 @@ export type RawBillableUsage = {
purpose: string;
internalReference: string | null;
priceCents: number;
collab: boolean;
billingStatus: "open" | "billed" | "reopened" | "voided";
createdAt: Date;
billingReportId: string | null;
@@ -129,6 +131,7 @@ function toBillingPosition(row: RawBillableUsage): BillingPosition {
purpose: row.purpose,
reference: row.internalReference,
priceCents: row.priceCents,
collab: row.collab,
status,
selectable: status === "open" || status === "reopened",
createdAt: row.createdAt,
@@ -155,6 +158,7 @@ export function createBillingRepository(
purpose: usages.purpose,
internalReference: usages.internalReference,
priceCents: usages.priceCents,
collab: usages.collab,
billingStatus: usages.billingStatus,
createdAt: usages.createdAt,
billingReportId: usages.billingReportId,
+1
View File
@@ -46,6 +46,7 @@ function selectedUsage(id: string, status: "open" | "reopened" = "open"): Select
purpose: "Titelgeschichte",
internalReference: null,
priceCents: 3_000,
collab: false,
billingStatus: status,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
editorialAccountId: "e1",
+4
View File
@@ -87,6 +87,7 @@ export type SelectedUsage = {
purpose: string;
internalReference: string | null;
priceCents: number;
collab: boolean;
billingStatus: "open" | "billed" | "reopened" | "voided";
createdAt: Date;
editorialAccountId: string;
@@ -468,6 +469,7 @@ function toReportPosition(usage: SelectedUsage): BillingReportPosition {
purpose: usage.purpose,
reference: usage.internalReference,
priceCents: usage.priceCents,
collab: usage.collab,
createdAt: usage.createdAt,
};
}
@@ -533,6 +535,7 @@ export function createReportRepository(
purpose: usages.purpose,
internalReference: usages.internalReference,
priceCents: usages.priceCents,
collab: usages.collab,
billingStatus: usages.billingStatus,
createdAt: usages.createdAt,
editorialAccountId: usages.editorialAccountId,
@@ -639,6 +642,7 @@ export function createReportRepository(
purposeSnapshot: u.purpose,
internalReferenceSnapshot: u.internalReference,
priceCents: u.priceCents,
collab: u.collab,
})),
);
+2
View File
@@ -29,6 +29,8 @@ export type BillingReportPosition = {
purpose: string;
reference: string | null;
priceCents: number;
/** Free collaborative usage: rendered with 0,00 € and a Collab marker. */
collab: boolean;
createdAt: Date;
};
+57
View File
@@ -0,0 +1,57 @@
import { expect, test } from "vitest";
import { expectedAlbumNames, germanEventDate, matchEventAlbum } from "./event-albums";
const matchAlbum = { id: "2222222b-2222-4222-8222-22222222222b", albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026" };
const eventAlbum = { id: "3333333c-3333-4333-8333-33333333333c", albumName: "DFB-Pokal Finale" };
const privateAlbum = { id: "4444444d-4444-4444-8444-44444444444d", albumName: "Privaturlaub Sylt" };
test("germanEventDate formats ISO dates as TT.MM.JJJJ", () => {
expect(germanEventDate("2026-09-12")).toBe("12.09.2026");
});
test("expectedAlbumNames covers the bare event and the match naming convention", () => {
expect(expectedAlbumNames("Hamburger SV - VfL Wolfsburg", "2026-09-12")).toEqual([
"Hamburger SV - VfL Wolfsburg",
"Hamburger SV - VfL Wolfsburg | 12.09.2026",
]);
});
test("matchEventAlbum links the dated match album by exact name", () => {
const event = { title: "Hamburger SV - VfL Wolfsburg", eventDate: "2026-09-12", immichAlbumId: null };
expect(matchEventAlbum(event, [privateAlbum, matchAlbum])).toEqual(matchAlbum);
});
test("matchEventAlbum links a bare event album by exact name", () => {
const event = { title: "DFB-Pokal Finale", eventDate: "2026-05-23", immichAlbumId: null };
expect(matchEventAlbum(event, [eventAlbum])).toEqual(eventAlbum);
});
test("matchEventAlbum never links private or differently named albums", () => {
const event = { title: "Hamburger SV - VfL Wolfsburg", eventDate: "2026-09-12", immichAlbumId: null };
expect(matchEventAlbum(event, [privateAlbum])).toBeNull();
// Wrong date in the album name must not match.
const otherDate = { id: matchAlbum.id, albumName: "Hamburger SV - VfL Wolfsburg | 13.09.2026" };
expect(matchEventAlbum(event, [otherDate])).toBeNull();
//Substring or partial titles must not match.
const partial = { id: matchAlbum.id, albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026 Highlights" };
expect(matchEventAlbum(event, [partial])).toBeNull();
});
test("matchEventAlbum prefers the explicit album id over name matching", () => {
const event = {
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: eventAlbum.id.toUpperCase(),
};
expect(matchEventAlbum(event, [matchAlbum, eventAlbum])).toEqual(eventAlbum);
});
test("matchEventAlbum falls back to name matching when the explicit album is gone", () => {
const event = {
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: "99999999-9999-4999-8999-999999999999",
};
expect(matchEventAlbum(event, [matchAlbum])).toEqual(matchAlbum);
});
+46
View File
@@ -0,0 +1,46 @@
import type { ImmichAlbumSummary } from "@/modules/immich/types";
/**
* Pure linking rules between calendar events and Immich albums.
*
* Album names follow the photographer's convention "{Event}" or
* "{Verein A} - {Verein B} | {TT.MM.JJJJ}". An event links to an album either
* explicitly (admin picked its id) or by exact name match once the album
* appears: the bare title, or the title plus " | {TT.MM.JJJJ}" of the event
* date. Exact matching keeps private albums out: only albums whose names the
* admin deliberately mirrored into an event title ever become linkable.
*/
export type EventAlbumLink = {
title: string;
/** ISO date YYYY-MM-DD. */
eventDate: string;
immichAlbumId: string | null;
};
export type LinkableAlbum = Pick<ImmichAlbumSummary, "id" | "albumName">;
/** Formats an ISO date as TT.MM.JJJJ without timezone round-trips. */
export function germanEventDate(isoDate: string): string {
const [year, month, day] = isoDate.split("-");
return `${day}.${month}.${year}`;
}
export function expectedAlbumNames(title: string, eventDate: string): string[] {
const trimmed = title.trim();
return [trimmed, `${trimmed} | ${germanEventDate(eventDate)}`];
}
export function matchEventAlbum<T extends LinkableAlbum>(
event: EventAlbumLink,
albums: T[],
): T | null {
if (event.immichAlbumId) {
const explicit = albums.find(
(album) => album.id.toLowerCase() === event.immichAlbumId!.toLowerCase(),
);
if (explicit) return explicit;
}
const names = new Set(expectedAlbumNames(event.title, event.eventDate));
return albums.find((album) => names.has(album.albumName.trim())) ?? null;
}
+266
View File
@@ -0,0 +1,266 @@
import { expect, test, vi } from "vitest";
import { AlbumGrantError } from "@/modules/albums/grants";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import {
CalendarServiceError,
createCalendarService,
type CalendarRepository,
type CalendarEvent,
type EventResponseStatus,
} from "./service";
const editorialUuid = "1111111a-1111-4111-8111-11111111111a";
const userUuid = "3333333c-3333-4333-8333-33333333333c";
const eventUuid = "5555555e-5555-4555-8555-55555555555e";
const albumUuid = "2222222b-2222-4222-8222-22222222222b";
const matchAlbum: ImmichAlbumSummary = {
id: albumUuid,
albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026",
description: null,
albumThumbnailAssetId: null,
assetCount: 42,
};
function event(overrides: Partial<CalendarEvent> = {}): CalendarEvent {
return {
id: eventUuid,
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: null,
createdAt: new Date("2026-09-01T08:00:00.000Z"),
...overrides,
};
}
function setup(options: {
events?: CalendarEvent[];
albums?: ImmichAlbumSummary[] | null;
grantedAlbumIds?: string[];
responses?: Array<{ eventId: string; status: EventResponseStatus }>;
rateLimitAllowed?: boolean;
} = {}) {
const events = [...(options.events ?? [event()])];
const responses = [...(options.responses ?? [])];
const repository: CalendarRepository = {
async insertEvent(input) {
const created = event({
id: "6666666f-6666-4666-8666-66666666666f",
title: input.title,
eventDate: input.eventDate,
immichAlbumId: input.immichAlbumId,
});
events.push(created);
return created;
},
async getEvent(id) {
return events.find((candidate) => candidate.id === id) ?? null;
},
async listEvents() {
return [...events].sort((left, right) => left.eventDate.localeCompare(right.eventDate));
},
async deleteEvent(id) {
const index = events.findIndex((candidate) => candidate.id === id);
if (index === -1) return null;
const [deleted] = events.splice(index, 1);
return deleted;
},
async upsertResponse(input) {
const existing = responses.find((response) => response.eventId === input.eventId);
if (existing) {
existing.status = input.status;
} else {
responses.push({ eventId: input.eventId, status: input.status });
}
},
async listResponsesForEditorial() {
return responses;
},
async listAllResponses() {
return responses.map((response) => ({
...response,
editorialId: editorialUuid,
editorialName: "Kicker Daily",
}));
},
};
const immich = {
listAlbums: vi.fn(async () => {
if (options.albums === null) throw new Error("immich down");
return options.albums ?? [matchAlbum];
}),
};
const grants = {
getGrantedAlbumIds: vi.fn().mockResolvedValue(options.grantedAlbumIds ?? []),
grantAlbum: vi.fn().mockResolvedValue(undefined),
revokeSelfServiceGrantsForAlbum: vi.fn().mockResolvedValue(1),
};
const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) };
const consumeRateLimit = vi.fn().mockResolvedValue({
allowed: options.rateLimitAllowed ?? true,
retryAfterSeconds: 42,
});
return {
service: createCalendarService({ repository, immich, grants, audit, consumeRateLimit }),
repository,
immich,
grants,
audit,
consumeRateLimit,
events,
responses,
};
}
test("createEvent rejects an empty title and an invalid date", async () => {
const { service } = setup();
await expect(
service.createEvent({ title: " ", eventDate: "2026-09-12", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_TITLE" });
await expect(
service.createEvent({ title: "HSV - Wolfsburg", eventDate: "12.09.2026", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_EVENT_DATE" });
});
test("createEvent rejects an explicit album that does not exist in Immich", async () => {
const { service } = setup({ albums: [matchAlbum] });
await expect(
service.createEvent({
title: "HSV - Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: "99999999-9999-4999-8999-999999999999",
adminUserId: userUuid,
}),
).rejects.toMatchObject({ code: "INVALID_ALBUM" });
});
test("selfGrantAlbum grants only the album linked to the event, as self_service", async () => {
const { service, grants, audit } = setup();
const album = await service.selfGrantAlbum({
eventId: eventUuid,
editorialId: editorialUuid,
actorUserId: userUuid,
});
expect(album).toEqual({ id: albumUuid, albumName: matchAlbum.albumName });
expect(grants.grantAlbum).toHaveBeenCalledWith({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: null,
source: "self_service",
});
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "album_self_granted", actorType: "editorial" }),
);
});
test("selfGrantAlbum refuses events without a linked album", async () => {
const { service, grants } = setup({ albums: [] });
await expect(
service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
).rejects.toMatchObject({ code: "EVENT_ALBUM_UNAVAILABLE" });
expect(grants.grantAlbum).not.toHaveBeenCalled();
});
test("selfGrantAlbum refuses unknown events", async () => {
const { service } = setup();
await expect(
service.selfGrantAlbum({
eventId: "99999999-9999-4999-8999-999999999999",
editorialId: editorialUuid,
actorUserId: userUuid,
}),
).rejects.toMatchObject({ code: "EVENT_NOT_FOUND" });
});
test("selfGrantAlbum surfaces rate limits and Immich outages", async () => {
const limited = setup({ rateLimitAllowed: false });
await expect(
limited.service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
).rejects.toMatchObject({ code: "RATE_LIMITED", retryAfterSeconds: 42 });
const down = setup({ albums: null });
await expect(
down.service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
});
test("selfGrantAlbum maps a vanished album to EVENT_ALBUM_UNAVAILABLE", async () => {
const { service, grants } = setup();
grants.grantAlbum.mockRejectedValue(new AlbumGrantError("ALBUM_NOT_ASSIGNABLE"));
await expect(
service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
).rejects.toMatchObject({ code: "EVENT_ALBUM_UNAVAILABLE" });
});
test("respond validates the status and upserts one response per event", async () => {
const { service, responses, audit } = setup();
await expect(
service.respond({
eventId: eventUuid,
editorialId: editorialUuid,
actorUserId: userUuid,
status: "maybe" as EventResponseStatus,
}),
).rejects.toMatchObject({ code: "INVALID_STATUS" });
await service.respond({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid, status: "attending" });
await service.respond({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid, status: "not_attending" });
expect(responses).toEqual([{ eventId: eventUuid, status: "not_attending" }]);
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "event_response_recorded", actorType: "editorial" }),
);
});
test("deleteEvent revokes self-service grants on the linked album and removes the event", async () => {
const { service, grants, events, audit } = setup();
await service.deleteEvent({ id: eventUuid, adminUserId: userUuid });
expect(grants.revokeSelfServiceGrantsForAlbum).toHaveBeenCalledWith(albumUuid);
expect(events).toHaveLength(0);
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "calendar_event_deleted" }),
);
});
test("deleteEvent reports unknown events", async () => {
const { service } = setup();
await expect(
service.deleteEvent({ id: "99999999-9999-4999-8999-999999999999", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "EVENT_NOT_FOUND" });
});
test("listEditorialEvents marks granted albums, own responses and the past window", async () => {
const oldEvent = event({ id: "7777777a-7777-4777-8777-77777777777a", eventDate: "2026-01-01" });
const { service } = setup({
events: [event(), oldEvent],
grantedAlbumIds: [albumUuid],
responses: [{ eventId: eventUuid, status: "attending" }],
});
const { events, immichUnavailable } = await service.listEditorialEvents(
editorialUuid,
new Date("2026-09-10T08:00:00.000Z"),
);
expect(immichUnavailable).toBe(false);
// The January event is outside the 30-day past window.
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({
id: eventUuid,
isGranted: true,
response: "attending",
album: { id: albumUuid, albumName: matchAlbum.albumName },
});
});
test("listEditorialEvents degrades gracefully when Immich is down", async () => {
const { service } = setup({ albums: null });
const { events, immichUnavailable } = await service.listEditorialEvents(
editorialUuid,
new Date("2026-09-10T08:00:00.000Z"),
);
expect(immichUnavailable).toBe(true);
expect(events[0].album).toBeNull();
expect(events[0].isGranted).toBe(false);
});
+468
View File
@@ -0,0 +1,468 @@
import "server-only";
import { asc, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { calendarEvents, editorialAccounts, eventResponses } from "@/db/schema";
import type * as schema from "@/db/schema";
import { albumGrantService, AlbumGrantError } from "@/modules/albums/grants";
import {
isoDateInBerlin,
isValidIsoDate,
shiftIsoDate,
} from "@/modules/announcements/service";
import { writeAudit } from "@/modules/audit/write";
import { immichClient } from "@/modules/immich/client";
import type { ImmichClient } from "@/modules/immich/types";
import { consumeRateLimit, calendarSelfGrantPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import { matchEventAlbum } from "./event-albums";
export const CALENDAR_EVENT_MAX_TITLE_LENGTH = 200;
/** Past events stay visible (and self-serviceable) for this many days. */
export const CALENDAR_PAST_DAYS = 30;
export type EventResponseStatus = "attending" | "not_attending";
export type CalendarEvent = {
id: string;
title: string;
eventDate: string;
immichAlbumId: string | null;
createdAt: Date;
};
export type LinkedAlbum = { id: string; albumName: string };
export type EditorialCalendarEvent = CalendarEvent & {
album: LinkedAlbum | null;
isGranted: boolean;
response: EventResponseStatus | null;
};
export type AdminCalendarEvent = CalendarEvent & {
album: LinkedAlbum | null;
responses: Array<{
editorialId: string;
editorialName: string;
status: EventResponseStatus;
}>;
};
export type CalendarError =
| "INVALID_TITLE"
| "INVALID_EVENT_DATE"
| "INVALID_ALBUM"
| "INVALID_STATUS"
| "EVENT_NOT_FOUND"
| "EVENT_ALBUM_UNAVAILABLE"
| "IMMICH_UNAVAILABLE"
| "RATE_LIMITED";
export class CalendarServiceError extends Error {
readonly name = "CalendarServiceError";
constructor(
readonly code: CalendarError,
readonly retryAfterSeconds?: number,
) {
super(code);
}
}
export type CalendarRepository = {
insertEvent(input: {
title: string;
eventDate: string;
immichAlbumId: string | null;
adminUserId: string;
}): Promise<CalendarEvent>;
getEvent(id: string): Promise<CalendarEvent | null>;
listEvents(): Promise<CalendarEvent[]>;
deleteEvent(id: string): Promise<CalendarEvent | null>;
upsertResponse(input: {
eventId: string;
editorialId: string;
status: EventResponseStatus;
}): Promise<void>;
listResponsesForEditorial(editorialId: string): Promise<Array<{ eventId: string; status: EventResponseStatus }>>;
listAllResponses(): Promise<
Array<{ eventId: string; editorialId: string; editorialName: string; status: EventResponseStatus }>
>;
};
export type CalendarDependencies = {
repository: CalendarRepository;
immich: Pick<ImmichClient, "listAlbums">;
grants: Pick<
typeof albumGrantService,
"getGrantedAlbumIds" | "grantAlbum" | "revokeSelfServiceGrantsForAlbum"
>;
audit: { writeAudit: typeof writeAudit };
consumeRateLimit: ConsumeRateLimit;
};
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function createCalendarService({
repository,
immich,
grants,
audit,
consumeRateLimit: consume,
}: CalendarDependencies) {
async function loadAlbumsOrNull() {
try {
return await immich.listAlbums();
} catch {
return null;
}
}
return {
async createEvent(input: {
title: string;
eventDate: string;
immichAlbumId?: string | null;
adminUserId: string;
}): Promise<CalendarEvent> {
const title = input.title.trim();
if (title.length === 0 || title.length > CALENDAR_EVENT_MAX_TITLE_LENGTH) {
throw new CalendarServiceError("INVALID_TITLE");
}
if (!isValidIsoDate(input.eventDate)) {
throw new CalendarServiceError("INVALID_EVENT_DATE");
}
let immichAlbumId: string | null = null;
if (input.immichAlbumId) {
if (!UUID_PATTERN.test(input.immichAlbumId)) {
throw new CalendarServiceError("INVALID_ALBUM");
}
const albums = await loadAlbumsOrNull();
if (!albums) {
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
}
const album = albums.find(
(candidate) => candidate.id.toLowerCase() === input.immichAlbumId!.toLowerCase(),
);
if (!album) {
throw new CalendarServiceError("INVALID_ALBUM");
}
immichAlbumId = album.id;
}
const created = await repository.insertEvent({
title,
eventDate: input.eventDate,
immichAlbumId,
adminUserId: input.adminUserId,
});
await audit.writeAudit({
type: "calendar_event_created",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "calendar_event",
entityId: created.id,
metadata: { title: created.title, eventDate: created.eventDate, immichAlbumId },
});
return created;
},
async deleteEvent(input: { id: string; adminUserId: string }): Promise<void> {
const event = await repository.getEvent(input.id);
if (!event) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
// Revoking self-service grants keeps the calendar authoritative: an
// album that leaves the calendar loses self-service access. Admin and
// auto-rule grants are untouched (auto assignment outranks the calendar).
const albums = (await loadAlbumsOrNull()) ?? [];
const album = matchEventAlbum(event, albums);
const revoked = album
? await grants.revokeSelfServiceGrantsForAlbum(album.id)
: 0;
const deleted = await repository.deleteEvent(input.id);
if (!deleted) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
await audit.writeAudit({
type: "calendar_event_deleted",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "calendar_event",
entityId: deleted.id,
metadata: {
title: deleted.title,
eventDate: deleted.eventDate,
revokedSelfServiceGrants: revoked,
},
});
},
/** Editorial calendar: upcoming events plus the recent past window. */
async listEditorialEvents(
editorialId: string,
now: Date,
): Promise<{ events: EditorialCalendarEvent[]; immichUnavailable: boolean }> {
const today = isoDateInBerlin(now);
const minDate = shiftIsoDate(today, -CALENDAR_PAST_DAYS);
const [allEvents, albums, grantedAlbumIds, responses] = await Promise.all([
repository.listEvents(),
loadAlbumsOrNull(),
grants.getGrantedAlbumIds(editorialId),
repository.listResponsesForEditorial(editorialId),
]);
const granted = new Set(grantedAlbumIds.map((id) => id.toLowerCase()));
const responseByEvent = new Map(responses.map((response) => [response.eventId, response.status]));
const events = allEvents
.filter((event) => event.eventDate >= minDate)
.map((event) => {
const album = albums ? matchEventAlbum(event, albums) : null;
return {
...event,
album: album ? { id: album.id, albumName: album.albumName } : null,
isGranted: album ? granted.has(album.id.toLowerCase()) : false,
response: responseByEvent.get(event.id) ?? null,
};
});
return { events, immichUnavailable: albums === null };
},
/** Admin overview: every event with its linked album and all RSVPs. */
async listAdminEvents(): Promise<{ events: AdminCalendarEvent[]; immichUnavailable: boolean }> {
const [allEvents, albums, responses] = await Promise.all([
repository.listEvents(),
loadAlbumsOrNull(),
repository.listAllResponses(),
]);
const responsesByEvent = new Map<string, AdminCalendarEvent["responses"]>();
for (const response of responses) {
const list = responsesByEvent.get(response.eventId) ?? [];
list.push({
editorialId: response.editorialId,
editorialName: response.editorialName,
status: response.status,
});
responsesByEvent.set(response.eventId, list);
}
const events = allEvents.map((event) => {
const album = albums ? matchEventAlbum(event, albums) : null;
return {
...event,
album: album ? { id: album.id, albumName: album.albumName } : null,
responses: responsesByEvent.get(event.id) ?? [],
};
});
return { events, immichUnavailable: albums === null };
},
async respond(input: {
eventId: string;
editorialId: string;
actorUserId: string;
status: EventResponseStatus;
}): Promise<void> {
if (input.status !== "attending" && input.status !== "not_attending") {
throw new CalendarServiceError("INVALID_STATUS");
}
const event = await repository.getEvent(input.eventId);
if (!event) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
await repository.upsertResponse({
eventId: input.eventId,
editorialId: input.editorialId,
status: input.status,
});
await audit.writeAudit({
type: "event_response_recorded",
actorUserId: input.actorUserId,
actorType: "editorial",
entityType: "calendar_event",
entityId: input.eventId,
metadata: { status: input.status, title: event.title, eventDate: event.eventDate },
});
},
/**
* Editorial self-service: grant access to the album linked to a calendar
* event. The event (admin-created) is the trust boundary; only its linked
* album is grantable, never arbitrary Immich albums. Idempotent: an
* existing active grant is left as-is.
*/
async selfGrantAlbum(input: {
eventId: string;
editorialId: string;
actorUserId: string;
}): Promise<LinkedAlbum> {
try {
await enforceRateLimit(consume, `calendar-self-grant:${input.editorialId}`, calendarSelfGrantPolicy);
} catch (error) {
if (error instanceof RateLimitExceededError) {
throw new CalendarServiceError("RATE_LIMITED", error.retryAfterSeconds);
}
throw error;
}
const event = await repository.getEvent(input.eventId);
if (!event) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
const albums = await loadAlbumsOrNull();
if (!albums) {
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
}
const album = matchEventAlbum(event, albums);
if (!album) {
throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE");
}
try {
await grants.grantAlbum({
editorialId: input.editorialId,
immichAlbumId: album.id,
adminUserId: null,
source: "self_service",
});
} catch (error) {
if (error instanceof AlbumGrantError && error.code === "ALBUM_NOT_ASSIGNABLE") {
throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE");
}
if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") {
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
}
throw error;
}
await audit.writeAudit({
type: "album_self_granted",
actorUserId: input.actorUserId,
actorType: "editorial",
entityType: "album_grant",
entityId: album.id,
metadata: {
editorialId: input.editorialId,
eventId: input.eventId,
albumName: album.albumName,
},
});
return { id: album.id, albumName: album.albumName };
},
};
}
export function createCalendarRepository(database: NodePgDatabase<typeof schema>): CalendarRepository {
const eventColumns = {
id: calendarEvents.id,
title: calendarEvents.title,
eventDate: calendarEvents.eventDate,
immichAlbumId: calendarEvents.immichAlbumId,
createdAt: calendarEvents.createdAt,
};
return {
async insertEvent(input) {
const [row] = await database
.insert(calendarEvents)
.values({
title: input.title,
eventDate: input.eventDate,
immichAlbumId: input.immichAlbumId,
createdByUserId: input.adminUserId,
})
.returning(eventColumns);
return row;
},
async getEvent(id) {
const [row] = await database
.select(eventColumns)
.from(calendarEvents)
.where(eq(calendarEvents.id, id))
.limit(1);
return row ?? null;
},
async listEvents() {
return database
.select(eventColumns)
.from(calendarEvents)
.orderBy(asc(calendarEvents.eventDate), asc(calendarEvents.createdAt));
},
async deleteEvent(id) {
return database.transaction(async (transaction) => {
const [event] = await transaction
.select(eventColumns)
.from(calendarEvents)
.where(eq(calendarEvents.id, id))
.for("update")
.limit(1);
if (!event) {
return null;
}
await transaction.delete(eventResponses).where(eq(eventResponses.eventId, id));
await transaction.delete(calendarEvents).where(eq(calendarEvents.id, id));
return event;
});
},
async upsertResponse(input) {
await database
.insert(eventResponses)
.values({
eventId: input.eventId,
editorialAccountId: input.editorialId,
status: input.status,
updatedAt: new Date(),
})
.onConflictDoUpdate({
target: [eventResponses.eventId, eventResponses.editorialAccountId],
set: { status: input.status, updatedAt: new Date() },
});
},
async listResponsesForEditorial(editorialId) {
const rows = await database
.select({ eventId: eventResponses.eventId, status: eventResponses.status })
.from(eventResponses)
.where(eq(eventResponses.editorialAccountId, editorialId));
return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus }));
},
async listAllResponses() {
const rows = await database
.select({
eventId: eventResponses.eventId,
editorialId: editorialAccounts.id,
editorialName: editorialAccounts.name,
status: eventResponses.status,
})
.from(eventResponses)
.innerJoin(editorialAccounts, eq(eventResponses.editorialAccountId, editorialAccounts.id))
.orderBy(asc(editorialAccounts.name));
return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus }));
},
};
}
export const calendarService = createCalendarService({
repository: createCalendarRepository(db),
immich: immichClient,
grants: albumGrantService,
audit: { writeAudit },
consumeRateLimit,
});
+8 -3
View File
@@ -598,6 +598,7 @@ export type DownloadDialogUsage = {
export type EditorialDownloadOptions = {
priceCents: number;
collabEnabled: boolean;
priorUsagesByAsset: Record<string, DownloadDialogUsage[]>;
};
@@ -615,7 +616,10 @@ export function createEditorialDownloadOptionsLoader(
throw new UsageAccountingError("INVALID_INPUT");
}
const [editorial] = await database
.select({ currentPriceCents: editorialAccounts.currentPriceCents })
.select({
currentPriceCents: editorialAccounts.currentPriceCents,
collabEnabled: editorialAccounts.collabEnabled,
})
.from(editorialAccounts)
.where(
and(
@@ -628,8 +632,9 @@ export function createEditorialDownloadOptionsLoader(
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
throw new UsageAccountingError("INVALID_PRICE");
}
const collabEnabled = editorial?.collabEnabled === true;
if (normalizedAssets.length === 0) {
return { priceCents: priceCents!, priorUsagesByAsset: {} };
return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset: {} };
}
const deliveredOriginal = database
@@ -669,7 +674,7 @@ export function createEditorialDownloadOptionsLoader(
createdAt: row.createdAt.toISOString(),
});
}
return { priceCents: priceCents!, priorUsagesByAsset };
return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset };
};
}
+27 -1
View File
@@ -3,7 +3,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/com
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { Alert, Badge, Checkbox, Input } from "@/components/ui/sakani";
import { archiveEditorialAction, unarchiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions";
import { archiveEditorialAction, unarchiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction, updateCollabAction } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone";
import { ResetUsageCard } from "./ResetUsageCard";
import { ApproveForm } from "./ApproveForm";
@@ -19,6 +19,7 @@ export type EditorialDetail = {
flatrateActive: boolean;
flatratePriceCents: number | null;
flatrateAssetLimit: number | null;
collabEnabled: boolean;
archivedAt: Date | null;
};
@@ -168,6 +169,31 @@ export function EditorialDetailContent({
</Card>
)}
{!editorial.archivedAt && (
<Card>
<CardHeader>
<CardTitle>Collab-Nutzung</CardTitle>
<CardDescription>
Erlaubt der Redaktion, Downloads als kostenlose Collab-Nutzung zu markieren
(0,00 € in der Abrechnung, mit Collab-Kennzeichnung).
</CardDescription>
</CardHeader>
<CardContent>
<form action={updateCollabAction.bind(null, editorial.id)} className="flex flex-col gap-6">
<Checkbox
defaultChecked={editorial.collabEnabled}
id="collabEnabled"
label="Collab-Option freischalten"
name="collabEnabled"
/>
<div>
<Button type="submit">Speichern</Button>
</div>
</form>
</CardContent>
</Card>
)}
{!editorial.archivedAt && (
<Card>
<CardHeader>
+11
View File
@@ -0,0 +1,11 @@
import { expect, test } from "vitest";
import { invoiceMessage } from "./invoice-message";
test("invoice message names the period and both attachments", () => {
const message = invoiceMessage("Q3 2026");
expect(message.subject).toBe("Ihre Rechnung für Q3 2026");
expect(message.text).toContain("Rechnung für Q3 2026");
expect(message.text).toContain("Nutzungsnachweis");
expect(message.htmlContent).toContain("Q3 2026");
});
+21
View File
@@ -0,0 +1,21 @@
export function invoiceMessage(periodLabel: string) {
return {
subject: `Ihre Rechnung für ${periodLabel}`,
text: `Hallo,
anbei erhalten Sie Ihre Rechnung für ${periodLabel} sowie den zugehörigen Nutzungsnachweis als PDF-Dokumente.
Bei Fragen zu den Positionen melden Sie sich gerne bei uns.
Viele Grüße,
Ihr Redaktions-Team`,
htmlContent: `Hallo,
anbei erhalten Sie Ihre **Rechnung für ${periodLabel}** sowie den zugehörigen Nutzungsnachweis als PDF-Dokumente.
Bei Fragen zu den Positionen melden Sie sich gerne bei uns.
Viele Grüße,
Ihr Redaktions-Team`,
};
}
+35
View File
@@ -2,6 +2,7 @@ import "server-only";
import nodemailer from "nodemailer";
import { env } from "@/config/env";
import { billingReportMessage } from "./billing-report-message";
import { invoiceMessage } from "./invoice-message";
const transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
@@ -94,6 +95,40 @@ export const emailService = {
});
},
async sendInvoiceBundle(
toEmail: string,
periodLabel: string,
invoicePdf: Buffer,
reportPdf: Buffer,
invoiceNumber: string,
) {
const safeNumber = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") || "rechnung";
const message = invoiceMessage(periodLabel);
await transporter.sendMail({
from: env.SMTP_FROM,
to: toEmail,
subject: message.subject,
text: message.text,
html: buildHtml("Ihre Rechnung", message.htmlContent, {
text: "Zum Portal",
url: `${env.BETTER_AUTH_URL}/anmelden`,
}),
attachments: [
{
filename: `Rechnung-${safeNumber}.pdf`,
content: invoicePdf,
contentType: "application/pdf",
},
{
filename: `Nutzungsnachweis-${safeNumber}.pdf`,
content: reportPdf,
contentType: "application/pdf",
},
],
});
},
async sendNewAlbumNotification(toEmail: string, albumNames: string | string[]) {
const albums = Array.isArray(albumNames) ? albumNames : [albumNames];
+2
View File
@@ -28,6 +28,7 @@ const assetSchema = z
exifInfo: z.object({
exifImageWidth: z.number().optional().nullable(),
exifImageHeight: z.number().optional().nullable(),
description: nullableString,
}).passthrough().optional().nullable(),
})
.passthrough();
@@ -369,6 +370,7 @@ export function createImmichClient({
albumIds: input.albumIds,
...(input.id === undefined ? {} : { id: input.id }),
...(input.description === undefined ? {} : { description: input.description }),
...(input.originalFileName === undefined ? {} : { originalFileName: input.originalFileName }),
type: "IMAGE",
page: input.page,
size: input.size,
+2 -1
View File
@@ -16,6 +16,7 @@ export type ImmichAsset = {
exifInfo?: {
exifImageWidth?: number | null;
exifImageHeight?: number | null;
description?: string | null;
} | null;
albums: Array<{ id: string }>;
};
@@ -46,7 +47,7 @@ export interface ImmichClient {
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
getAsset(assetId: string, signal?: AbortSignal): Promise<ImmichAsset>;
searchPhotos(
input: { albumIds: string[]; id?: string; description?: string; page: number; size: number; type?: "IMAGE"; withExif?: boolean },
input: { albumIds: string[]; id?: string; description?: string; originalFileName?: string; page: number; size: number; type?: "IMAGE"; withExif?: boolean },
signal?: AbortSignal,
): Promise<ImmichSearchPage>;
getThumbnail(assetId: string, signal?: AbortSignal): Promise<ImmichBinary>;
+1 -1
View File
@@ -80,7 +80,7 @@ function paidPositionsTable(snapshot: BillingReportSnapshot) {
body.push([
{ text: pos.filename, style: "tableCell" },
{ text: pos.albumName, style: "tableCell" },
{ text: pos.purpose, style: "tableCell" },
{ text: pos.collab ? `${pos.purpose} (Collab)` : pos.purpose, style: "tableCell" },
{ text: pos.reference ?? "", style: "tableCell" },
{ text: formatGermanDate(pos.createdAt), style: "tableCell", alignment: "right" as const },
{ text: formatCents(pos.priceCents), style: "tableCell", alignment: "right" as const },
+98
View File
@@ -0,0 +1,98 @@
import { expect, test, vi } from "vitest";
import {
createReleaseNoteService,
isValidVersion,
ReleaseNoteServiceError,
type ReleaseNote,
type ReleaseNoteRepository,
} from "./service";
const userUuid = "3333333c-3333-4333-8333-33333333333c";
function note(overrides: Partial<ReleaseNote> = {}): ReleaseNote {
return {
id: "5555555e-5555-4555-8555-55555555555e",
version: "2.1.0",
audience: "editorial",
body: "Neu in 2.1: Sortierung und Kalender.",
createdAt: new Date("2026-11-30T08:00:00.000Z"),
...overrides,
};
}
function setup(options: { insertError?: unknown } = {}) {
const repository: ReleaseNoteRepository = {
insert: vi.fn(async (input) => {
if (options.insertError) throw options.insertError;
return note({ version: input.version, audience: input.audience, body: input.body });
}),
listForEditorial: vi.fn().mockResolvedValue([note()]),
listAll: vi.fn().mockResolvedValue([note(), note({ audience: "admin" })]),
deleteById: vi.fn().mockResolvedValue(note()),
};
const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) };
return { service: createReleaseNoteService({ repository, audit }), repository, audit };
}
test("isValidVersion accepts major.minor and major.minor.patch only", () => {
expect(isValidVersion("2.1")).toBe(true);
expect(isValidVersion("2.1.0")).toBe(true);
expect(isValidVersion("2.10.12")).toBe(true);
expect(isValidVersion("2")).toBe(false);
expect(isValidVersion("2.1.0.4")).toBe(false);
expect(isValidVersion("v2.1")).toBe(false);
expect(isValidVersion("2.x")).toBe(false);
});
test("createReleaseNote validates version, audience and body", async () => {
const { service, repository } = setup();
await expect(
service.createReleaseNote({ version: "abc", audience: "editorial", body: "Text", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_VERSION" });
await expect(
service.createReleaseNote({
version: "2.1",
audience: "everyone" as never,
body: "Text",
adminUserId: userUuid,
}),
).rejects.toMatchObject({ code: "INVALID_AUDIENCE" });
await expect(
service.createReleaseNote({ version: "2.1", audience: "editorial", body: " ", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_BODY" });
expect(repository.insert).not.toHaveBeenCalled();
});
test("createReleaseNote trims input, writes audit and maps duplicate versions", async () => {
const { service, audit } = setup();
const created = await service.createReleaseNote({
version: " 2.1 ",
audience: "both",
body: " Text ",
adminUserId: userUuid,
});
expect(created.version).toBe("2.1");
expect(created.body).toBe("Text");
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "release_note_created", actorType: "admin" }),
);
const duplicate = setup({ insertError: { code: "23505" } });
await expect(
duplicate.service.createReleaseNote({ version: "2.1", audience: "both", body: "Text", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "DUPLICATE_RELEASE_NOTE" });
});
test("deleteReleaseNote reports missing notes and audits deletions", async () => {
const { service, repository, audit } = setup();
await service.deleteReleaseNote({ id: note().id, adminUserId: userUuid });
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "release_note_deleted" }),
);
repository.deleteById = vi.fn().mockResolvedValue(null);
await expect(
service.deleteReleaseNote({ id: note().id, adminUserId: userUuid }),
).rejects.toBeInstanceOf(ReleaseNoteServiceError);
});
+203
View File
@@ -0,0 +1,203 @@
import "server-only";
import { desc, eq, inArray } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { releaseNotes } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
export const RELEASE_NOTE_MAX_BODY_LENGTH = 2000;
export type ReleaseNoteAudience = "admin" | "editorial" | "both";
export type ReleaseNote = {
id: string;
version: string;
audience: ReleaseNoteAudience;
body: string;
createdAt: Date;
};
export type ReleaseNoteError =
| "INVALID_VERSION"
| "INVALID_BODY"
| "INVALID_AUDIENCE"
| "DUPLICATE_RELEASE_NOTE"
| "RELEASE_NOTE_NOT_FOUND";
export class ReleaseNoteServiceError extends Error {
readonly name = "ReleaseNoteServiceError";
constructor(readonly code: ReleaseNoteError) {
super(code);
}
}
export type CreateReleaseNoteInput = {
version: string;
audience: ReleaseNoteAudience;
body: string;
adminUserId: string;
};
export type ReleaseNoteRepository = {
insert(input: {
version: string;
audience: ReleaseNoteAudience;
body: string;
adminUserId: string;
}): Promise<ReleaseNote>;
listForEditorial(): Promise<ReleaseNote[]>;
listAll(): Promise<ReleaseNote[]>;
deleteById(id: string): Promise<ReleaseNote | null>;
};
const VERSION_PATTERN = /^\d+\.\d+(\.\d+)?$/;
const AUDIENCES: ReleaseNoteAudience[] = ["admin", "editorial", "both"];
export function isValidVersion(value: string): boolean {
return VERSION_PATTERN.test(value);
}
export function createReleaseNoteService({
repository,
audit,
}: {
repository: ReleaseNoteRepository;
audit: { writeAudit: typeof writeAudit };
}) {
return {
async createReleaseNote(input: CreateReleaseNoteInput): Promise<ReleaseNote> {
const version = input.version.trim();
if (!isValidVersion(version)) {
throw new ReleaseNoteServiceError("INVALID_VERSION");
}
if (!AUDIENCES.includes(input.audience)) {
throw new ReleaseNoteServiceError("INVALID_AUDIENCE");
}
const body = input.body.trim();
if (body.length === 0 || body.length > RELEASE_NOTE_MAX_BODY_LENGTH) {
throw new ReleaseNoteServiceError("INVALID_BODY");
}
let created: ReleaseNote;
try {
created = await repository.insert({
version,
audience: input.audience,
body,
adminUserId: input.adminUserId,
});
} catch (error) {
if (isUniqueViolation(error)) {
throw new ReleaseNoteServiceError("DUPLICATE_RELEASE_NOTE");
}
throw error;
}
await audit.writeAudit({
type: "release_note_created",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "release_note",
entityId: created.id,
metadata: { version: created.version, audience: created.audience },
});
return created;
},
/** Notes visible to editorial users (their own plus shared ones). */
async listEditorialReleaseNotes(): Promise<ReleaseNote[]> {
return repository.listForEditorial();
},
/** Every note for the admin overview. */
async listReleaseNotes(): Promise<ReleaseNote[]> {
return repository.listAll();
},
async deleteReleaseNote(input: { id: string; adminUserId: string }): Promise<void> {
const deleted = await repository.deleteById(input.id);
if (!deleted) {
throw new ReleaseNoteServiceError("RELEASE_NOTE_NOT_FOUND");
}
await audit.writeAudit({
type: "release_note_deleted",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "release_note",
entityId: deleted.id,
metadata: { version: deleted.version, audience: deleted.audience },
});
},
};
}
function isUniqueViolation(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error as { code?: unknown }).code === "23505"
);
}
export function createReleaseNoteRepository(
database: NodePgDatabase<typeof schema>,
): ReleaseNoteRepository {
const columns = {
id: releaseNotes.id,
version: releaseNotes.version,
audience: releaseNotes.audience,
body: releaseNotes.body,
createdAt: releaseNotes.createdAt,
};
return {
async insert(input) {
const [row] = await database
.insert(releaseNotes)
.values({
version: input.version,
audience: input.audience,
body: input.body,
createdByUserId: input.adminUserId,
})
.returning(columns);
return { ...row, audience: row.audience as ReleaseNoteAudience };
},
async listForEditorial() {
const rows = await database
.select(columns)
.from(releaseNotes)
.where(inArray(releaseNotes.audience, ["editorial", "both"]))
.orderBy(desc(releaseNotes.createdAt));
return rows.map((row) => ({ ...row, audience: row.audience as ReleaseNoteAudience }));
},
async listAll() {
const rows = await database
.select(columns)
.from(releaseNotes)
.orderBy(desc(releaseNotes.createdAt));
return rows.map((row) => ({ ...row, audience: row.audience as ReleaseNoteAudience }));
},
async deleteById(id) {
const [row] = await database
.delete(releaseNotes)
.where(eq(releaseNotes.id, id))
.returning(columns);
return row ? { ...row, audience: row.audience as ReleaseNoteAudience } : null;
},
};
}
export const releaseNoteService = createReleaseNoteService({
repository: createReleaseNoteRepository(db),
audit: { writeAudit },
});
+3
View File
@@ -34,6 +34,9 @@ export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSecon
export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 };
export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
export const calendarSelfGrantPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
export const invoiceUploadPolicy: RateLimitPolicy = { maxAttempts: 10, windowSeconds: 60 };
export const activityPolicy: RateLimitPolicy = { maxAttempts: 240, windowSeconds: 60 };
// ---------------------------------------------------------------------------
// Limiter factory
+60
View File
@@ -0,0 +1,60 @@
import { expect, test } from "vitest";
import {
fillDailySeries,
formatBytes,
normalizeStatsDays,
percentChange,
previousWindow,
statsWindow,
} from "./queries";
test("normalizeStatsDays only accepts the offered periods", () => {
expect(normalizeStatsDays("7")).toBe(7);
expect(normalizeStatsDays("90")).toBe(90);
expect(normalizeStatsDays("30")).toBe(30);
expect(normalizeStatsDays("365")).toBe(30);
expect(normalizeStatsDays(undefined)).toBe(30);
expect(normalizeStatsDays("abc")).toBe(30);
});
test("percentChange returns null without a baseline and rounds otherwise", () => {
expect(percentChange(5, 0)).toBeNull();
expect(percentChange(0, 0)).toBeNull();
expect(percentChange(150, 100)).toBe(50);
expect(percentChange(50, 100)).toBe(-50);
expect(percentChange(100, 100)).toBe(0);
});
test("statsWindow and previousWindow tile the timeline without gaps", () => {
const now = new Date("2026-11-30T12:00:00.000Z");
const window = statsWindow(30, now);
const previous = previousWindow(window);
expect(window.toUtcExclusive).toEqual(now);
expect(previous.toUtcExclusive).toEqual(window.fromUtc);
expect(previous.fromUtc.getTime()).toBe(window.fromUtc.getTime() - 30 * 86_400_000);
});
test("fillDailySeries fills missing days with zeroes and ends with today", () => {
const now = new Date("2026-11-30T12:00:00.000Z");
const window = statsWindow(7, now);
const points = fillDailySeries(
[
{ date: "2026-11-29", downloads: 4, revenueCents: 1500 },
{ date: "2026-11-30", views: 2 },
],
window,
);
expect(points).toHaveLength(7);
expect(points[0].date).toBe("2026-11-24");
expect(points[6].date).toBe("2026-11-30");
expect(points[6]).toMatchObject({ views: 2, downloads: 0 });
expect(points[5]).toMatchObject({ downloads: 4, revenueCents: 1500, views: 0, searches: 0 });
expect(points[4]).toMatchObject({ downloads: 0, views: 0, searches: 0, revenueCents: 0 });
});
test("formatBytes switches from MB to GB", () => {
expect(formatBytes(0)).toBe("0 MB");
expect(formatBytes(5 * 1024 * 1024)).toContain("5");
expect(formatBytes(2 * 1024 * 1024 * 1024)).toContain("GB");
});
+369
View File
@@ -0,0 +1,369 @@
import "server-only";
import { and, desc, eq, gte, lt, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import {
activityEvents,
billingReports,
downloadEvents,
editorialAccounts,
usages,
} from "@/db/schema";
import type * as schema from "@/db/schema";
// ---------------------------------------------------------------------------
// Pure helpers (unit-tested without a database)
// ---------------------------------------------------------------------------
export const STATS_PERIOD_OPTIONS = [7, 30, 90] as const;
export type StatsPeriodDays = (typeof STATS_PERIOD_OPTIONS)[number];
export function normalizeStatsDays(value: unknown): StatsPeriodDays {
const parsed = typeof value === "string" ? Number.parseInt(value, 10) : NaN;
return (STATS_PERIOD_OPTIONS as readonly number[]).includes(parsed)
? (parsed as StatsPeriodDays)
: 30;
}
export type StatsWindow = { fromUtc: Date; toUtcExclusive: Date; days: number };
export function statsWindow(days: number, now: Date = new Date()): StatsWindow {
const toUtcExclusive = new Date(now);
const fromUtc = new Date(now.getTime() - days * 86_400_000);
return { fromUtc, toUtcExclusive, days };
}
export function previousWindow(window: StatsWindow): StatsWindow {
const span = window.toUtcExclusive.getTime() - window.fromUtc.getTime();
return {
fromUtc: new Date(window.fromUtc.getTime() - span),
toUtcExclusive: window.fromUtc,
days: window.days,
};
}
/** Relative change in percent; null when the previous value is 0 (no baseline). */
export function percentChange(current: number, previous: number): number | null {
if (previous === 0) return null;
return Math.round(((current - previous) / previous) * 100);
}
export type DailyPoint = {
date: string;
downloads: number;
views: number;
searches: number;
revenueCents: number;
};
/**
* Fill missing days with zeroes so charts always show the full window.
* The series ends with today's (UTC) date so fresh activity is visible.
* ponytail: the rolling window starts mid-day, so the oldest partial day is
* in the KPIs but not in the chart; align statsWindow to day starts if that matters.
*/
export function fillDailySeries(
rows: Array<Partial<DailyPoint> & { date: string }>,
window: StatsWindow,
): DailyPoint[] {
const byDate = new Map(rows.map((row) => [row.date, row]));
const points: DailyPoint[] = [];
const start = new Date(window.toUtcExclusive.getTime() - (window.days - 1) * 86_400_000);
for (let i = 0; i < window.days; i++) {
const day = new Date(start.getTime() + i * 86_400_000);
const date = day.toISOString().slice(0, 10);
const row = byDate.get(date);
points.push({
date,
downloads: row?.downloads ?? 0,
views: row?.views ?? 0,
searches: row?.searches ?? 0,
revenueCents: row?.revenueCents ?? 0,
});
}
return points;
}
export function formatBytes(bytes: number): string {
if (bytes <= 0) return "0 MB";
const mb = bytes / (1024 * 1024);
if (mb < 1024) return `${mb.toLocaleString("de-DE", { maximumFractionDigits: 1 })} MB`;
return `${(mb / 1024).toLocaleString("de-DE", { maximumFractionDigits: 2 })} GB`;
}
// ---------------------------------------------------------------------------
// Aggregates
// ---------------------------------------------------------------------------
export type StatsKpis = {
downloadsCompleted: number;
downloadsInterrupted: number;
downloadsFailed: number;
transferredBytes: number;
newUsages: number;
collabUsages: number;
revenueCents: number;
albumViews: number;
searches: number;
lightboxViews: number;
activeEditorials: number;
};
export type EditorialStatsRow = {
editorialId: string;
name: string;
downloads: number;
usages: number;
collabUsages: number;
revenueCents: number;
views: number;
searches: number;
};
export type AlbumStatsRow = {
albumKey: string;
albumName: string;
downloads: number;
revenueCents: number;
views: number;
};
export type RecentActivityRow = {
id: string;
editorialName: string;
eventType: string;
query: string | null;
occurredAt: Date;
};
export type StatsOverview = {
window: StatsWindow;
kpis: StatsKpis;
previousKpis: StatsKpis;
daily: DailyPoint[];
topEditorials: EditorialStatsRow[];
topAlbums: AlbumStatsRow[];
openRevenueCents: number;
finalizedReports: number;
recentActivity: RecentActivityRow[];
};
export function createStatsQueries({ database }: { database: NodePgDatabase<typeof schema> }) {
async function kpisFor(window: StatsWindow): Promise<StatsKpis> {
const from = window.fromUtc;
const to = window.toUtcExclusive;
const [downloads] = await database
.select({
completed: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'completed')::int`,
interrupted: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'interrupted')::int`,
failed: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'failed_before_delivery')::int`,
bytes: sql<string>`COALESCE(SUM(${downloadEvents.transferredBytes}) FILTER (WHERE ${downloadEvents.status} = 'completed'), 0)::text`,
activeEditorials: sql<number>`COUNT(DISTINCT ${downloadEvents.editorialAccountId})::int`,
})
.from(downloadEvents)
.where(and(gte(downloadEvents.authorizedAt, from), lt(downloadEvents.authorizedAt, to)));
const [usageStats] = await database
.select({
count: sql<number>`COUNT(*)::int`,
collab: sql<number>`COUNT(*) FILTER (WHERE ${usages.collab})::int`,
revenue: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)));
const [activity] = await database
.select({
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
lightbox: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'lightbox_view')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)));
return {
downloadsCompleted: downloads?.completed ?? 0,
downloadsInterrupted: downloads?.interrupted ?? 0,
downloadsFailed: downloads?.failed ?? 0,
transferredBytes: Number(downloads?.bytes ?? 0),
newUsages: usageStats?.count ?? 0,
collabUsages: usageStats?.collab ?? 0,
revenueCents: usageStats?.revenue ?? 0,
albumViews: activity?.views ?? 0,
searches: activity?.searches ?? 0,
lightboxViews: activity?.lightbox ?? 0,
activeEditorials: downloads?.activeEditorials ?? 0,
};
}
return {
async loadOverview(days: StatsPeriodDays, now: Date = new Date()): Promise<StatsOverview> {
const window = statsWindow(days, now);
const previous = previousWindow(window);
const from = window.fromUtc;
const to = window.toUtcExclusive;
const [kpis, previousKpis, dailyDownloads, dailyActivity, dailyRevenue, editorialUsageRows, editorialActivityRows, albumUsageRows, albumViewRows, openRevenue, finalizedReports, recentActivity] = await Promise.all([
kpisFor(window),
kpisFor(previous),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${downloadEvents.authorizedAt}), 'YYYY-MM-DD')`,
downloads: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'completed')::int`,
})
.from(downloadEvents)
.where(and(gte(downloadEvents.authorizedAt, from), lt(downloadEvents.authorizedAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${downloadEvents.authorizedAt})`),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${activityEvents.occurredAt}), 'YYYY-MM-DD')`,
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${activityEvents.occurredAt})`),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${usages.createdAt}), 'YYYY-MM-DD')`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`),
database
.select({
editorialId: usages.editorialAccountId,
name: editorialAccounts.name,
usages: sql<number>`COUNT(*)::int`,
collabUsages: sql<number>`COUNT(*) FILTER (WHERE ${usages.collab})::int`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(usages.editorialAccountId, editorialAccounts.name),
database
.select({
editorialId: activityEvents.editorialAccountId,
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)))
.groupBy(activityEvents.editorialAccountId),
database
.select({
albumKey: usages.immichAlbumIdSnapshot,
albumName: sql<string>`MAX(${usages.albumNameSnapshot})`,
downloads: sql<number>`COUNT(*)::int`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(usages.immichAlbumIdSnapshot),
database
.select({
albumKey: activityEvents.immichAlbumId,
views: sql<number>`COUNT(*)::int`,
})
.from(activityEvents)
.where(
and(
gte(activityEvents.occurredAt, from),
lt(activityEvents.occurredAt, to),
eq(activityEvents.eventType, "album_view"),
),
)
.groupBy(activityEvents.immichAlbumId),
database
.select({ total: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int` })
.from(usages)
.where(sql`${usages.billingStatus} in ('open', 'reopened')`),
database
.select({ count: sql<number>`COUNT(*)::int` })
.from(billingReports)
.where(
and(
eq(billingReports.status, "final"),
gte(billingReports.finalizedAt, from),
lt(billingReports.finalizedAt, to),
),
),
database
.select({
id: activityEvents.id,
editorialName: editorialAccounts.name,
eventType: activityEvents.eventType,
query: activityEvents.query,
occurredAt: activityEvents.occurredAt,
})
.from(activityEvents)
.innerJoin(editorialAccounts, eq(activityEvents.editorialAccountId, editorialAccounts.id))
.orderBy(desc(activityEvents.occurredAt))
.limit(15),
]);
const dailyMap = new Map<string, Partial<DailyPoint> & { date: string }>();
for (const row of dailyDownloads) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, downloads: row.downloads });
}
for (const row of dailyActivity) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, views: row.views, searches: row.searches });
}
for (const row of dailyRevenue) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, revenueCents: row.revenueCents });
}
const activityByEditorial = new Map(editorialActivityRows.map((row) => [row.editorialId, row]));
const topEditorials: EditorialStatsRow[] = editorialUsageRows
.map((row) => ({
editorialId: row.editorialId,
name: row.name,
downloads: row.usages,
usages: row.usages,
collabUsages: row.collabUsages,
revenueCents: row.revenueCents,
views: activityByEditorial.get(row.editorialId)?.views ?? 0,
searches: activityByEditorial.get(row.editorialId)?.searches ?? 0,
}))
.sort((a, b) => b.downloads - a.downloads)
.slice(0, 8);
const viewsByAlbum = new Map(
albumViewRows.filter((row) => row.albumKey !== null).map((row) => [row.albumKey as string, row.views]),
);
const albumKeys = new Set([...albumUsageRows.map((row) => row.albumKey), ...viewsByAlbum.keys()]);
const usageByAlbum = new Map(albumUsageRows.map((row) => [row.albumKey, row]));
const topAlbums: AlbumStatsRow[] = [...albumKeys]
.map((key) => {
const usage = usageByAlbum.get(key);
return {
albumKey: key,
albumName: usage?.albumName ?? key,
downloads: usage?.downloads ?? 0,
revenueCents: usage?.revenueCents ?? 0,
views: viewsByAlbum.get(key) ?? 0,
};
})
.sort((a, b) => b.downloads + b.views - (a.downloads + a.views))
.slice(0, 8);
return {
window,
kpis,
previousKpis,
daily: fillDailySeries([...dailyMap.values()], window),
topEditorials,
topAlbums,
openRevenueCents: openRevenue[0]?.total ?? 0,
finalizedReports: finalizedReports[0]?.count ?? 0,
recentActivity,
};
},
};
}
export const statsQueries = createStatsQueries({ database: db });
+70
View File
@@ -0,0 +1,70 @@
import { expect, test, vi } from "vitest";
import {
CollabAdminError,
createCollabAdminService,
type CollabAdminRepository,
} from "./collab-admin";
const usageId = "1111111a-1111-4111-8111-11111111111a";
const adminUserId = "2222222b-2222-4222-8222-22222222222b";
function createRepo(overrides: Partial<Awaited<ReturnType<CollabAdminRepository["getUsageForCorrection"]>>> = {}) {
const repo: CollabAdminRepository = {
getUsageForCorrection: vi.fn().mockResolvedValue({
id: usageId,
editorialAccountId: "3333333c-3333-4333-8333-33333333333c",
billingStatus: "open",
collab: false,
priceCents: 1_500,
currentPriceCents: 1_500,
...overrides,
}),
updateUsageCollab: vi.fn().mockResolvedValue(undefined),
};
return repo;
}
test("marking collab zeroes the price", async () => {
const repo = createRepo();
const service = createCollabAdminService({ repo });
const result = await service.setUsageCollab({ usageId, collab: true, adminUserId });
expect(result.priceCents).toBe(0);
expect(repo.updateUsageCollab).toHaveBeenCalledWith(usageId, true, 0);
});
test("unmarking collab restores the editorial price", async () => {
const repo = createRepo({ collab: true, priceCents: 0 });
const service = createCollabAdminService({ repo });
const result = await service.setUsageCollab({ usageId, collab: false, adminUserId });
expect(result.priceCents).toBe(1_500);
expect(repo.updateUsageCollab).toHaveBeenCalledWith(usageId, false, 1_500);
});
test("billed usages cannot be corrected", async () => {
const repo = createRepo({ billingStatus: "billed" });
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: true, adminUserId }),
).rejects.toMatchObject({ code: "USAGE_NOT_EDITABLE" });
expect(repo.updateUsageCollab).not.toHaveBeenCalled();
});
test("unmarking without a valid editorial price fails", async () => {
const repo = createRepo({ collab: true, priceCents: 0, currentPriceCents: null });
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: false, adminUserId }),
).rejects.toBeInstanceOf(CollabAdminError);
});
test("missing usage is reported", async () => {
const repo: CollabAdminRepository = {
getUsageForCorrection: vi.fn().mockResolvedValue(null),
updateUsageCollab: vi.fn(),
};
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: true, adminUserId }),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
+118
View File
@@ -0,0 +1,118 @@
import "server-only";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { editorialAccounts, usages } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
export class CollabAdminError extends Error {
readonly name = "CollabAdminError";
constructor(
readonly code: "USAGE_NOT_FOUND" | "USAGE_NOT_EDITABLE" | "INVALID_PRICE",
) {
super(code);
}
}
export type CollabAdminRepository = {
getUsageForCorrection(usageId: string): Promise<{
id: string;
editorialAccountId: string;
billingStatus: "open" | "billed" | "reopened" | "voided";
collab: boolean;
priceCents: number;
currentPriceCents: number | null;
} | null>;
updateUsageCollab(usageId: string, collab: boolean, priceCents: number): Promise<void>;
};
/**
* Admin correction of the collab flag on open usages, so wrong entries can be
* fixed before the Nutzungsnachweis is finalized and sent. Marking collab sets
* the price to 0; unmarking restores the editorial's current price.
*/
export function createCollabAdminService({ repo }: { repo: CollabAdminRepository }) {
return {
async setUsageCollab(input: {
usageId: string;
collab: boolean;
adminUserId: string;
}): Promise<{ priceCents: number }> {
const usage = await repo.getUsageForCorrection(input.usageId);
if (!usage) throw new CollabAdminError("USAGE_NOT_FOUND");
if (usage.billingStatus !== "open" && usage.billingStatus !== "reopened") {
throw new CollabAdminError("USAGE_NOT_EDITABLE");
}
let priceCents: number;
if (input.collab) {
priceCents = 0;
} else {
if (
!Number.isSafeInteger(usage.currentPriceCents) ||
(usage.currentPriceCents ?? 0) <= 0
) {
throw new CollabAdminError("INVALID_PRICE");
}
priceCents = usage.currentPriceCents!;
}
await repo.updateUsageCollab(input.usageId, input.collab, priceCents);
try {
await writeAudit({
type: "usage_collab_updated",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "usage",
entityId: input.usageId,
metadata: {
from: { collab: usage.collab, priceCents: usage.priceCents },
to: { collab: input.collab, priceCents },
},
});
} catch {
// Audit is observability, not a transaction participant.
}
return { priceCents };
},
};
}
export function createCollabAdminRepository(
database: NodePgDatabase<typeof schema>,
): CollabAdminRepository {
return {
async getUsageForCorrection(usageId) {
const [row] = await database
.select({
id: usages.id,
editorialAccountId: usages.editorialAccountId,
billingStatus: usages.billingStatus,
collab: usages.collab,
priceCents: usages.priceCents,
currentPriceCents: editorialAccounts.currentPriceCents,
})
.from(usages)
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
.where(eq(usages.id, usageId))
.limit(1);
return row ?? null;
},
async updateUsageCollab(usageId, collab, priceCents) {
await database
.update(usages)
.set({ collab, priceCents })
.where(eq(usages.id, usageId));
},
};
}
export const collabAdminService = createCollabAdminService({
repo: createCollabAdminRepository(db),
});
export const setUsageCollab = collabAdminService.setUsageCollab;
+3 -1
View File
@@ -145,7 +145,9 @@ test("returns the exact persisted intent for an equivalent idempotent retry", as
expect(second).toEqual(first);
expect(usages).toHaveLength(1);
expect(immich.getAsset).toHaveBeenCalledTimes(4);
// Authorized retries short-circuit: only the first attempt talks to Immich
// (getAsset once for validation, once for the pre-insert refresh).
expect(immich.getAsset).toHaveBeenCalledTimes(2);
});
test("canonicalizes every UUID before fingerprinting, lookup, Immich calls, and persistence", async () => {
+27 -9
View File
@@ -49,6 +49,7 @@ export type BillableIntentInput = {
maxPriceCents?: number;
idempotencyKey: string;
requestFingerprint: string;
collab?: boolean;
};
export type UsageRepository = {
@@ -95,7 +96,13 @@ export function createUsageService({
});
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
if (existing) resolveIntent(existing, fingerprint, "new_usage");
// Authorized retries return the persisted intent without another Immich
// round-trip (retries keep working while Immich is down). Terminal-status
// intents (completed/failed/…) go through the repository flow so grant
// revocation and eligibility checks run before status resolution.
if (existing && existing.status === "authorized") {
return resolveIntent(existing, fingerprint, "new_usage");
}
const asset = await getValidatedAsset(immich, input.assetId);
const album = await loadRequestedAlbum(immich, input.assetId, input.albumId);
@@ -151,6 +158,7 @@ export function createUsageServiceRepository(
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
collabEnabled: editorialAccounts.collabEnabled,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
@@ -159,6 +167,12 @@ export function createUsageServiceRepository(
if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
// Collab usages are free, but only for editorials the admin enabled.
const collab = input.collab === true;
if (collab && !editorial.collabEnabled) {
throw new UsageAccountingError("COLLAB_NOT_ENABLED");
}
const [grant] = await transaction
.select({ id: albumGrants.id })
.from(albumGrants)
@@ -178,15 +192,16 @@ export function createUsageServiceRepository(
}
if (
!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0
!collab &&
(!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0)
) {
throw new UsageAccountingError("INVALID_PRICE");
}
let priceCents = editorial.currentPriceCents!;
let priceCents = collab ? 0 : editorial.currentPriceCents!;
if (editorial.flatrateActive) {
if (!collab && editorial.flatrateActive) {
if (
!Number.isSafeInteger(editorial.flatratePriceCents) ||
(editorial.flatratePriceCents ?? 0) <= 0
@@ -208,10 +223,10 @@ export function createUsageServiceRepository(
sql`${usages.createdAt} >= ${period.fromUtc}`,
sql`${usages.createdAt} < ${period.toUtcExclusive}`,
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
// For flatrate, we only count usages that were originally free via the flatrate
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?
// Yes, any billable usage this month counts towards the limit.
eq(usages.priceCents, 0)
// Flatrate usages are the free ones (priceCents = 0). Collab
// usages are also free but must NOT consume the flatrate limit.
eq(usages.priceCents, 0),
eq(usages.collab, false)
)
);
@@ -239,6 +254,7 @@ export function createUsageServiceRepository(
purpose: input.purpose,
internalReference: input.reference,
priceCents: priceCents,
collab,
billingStatus: "open",
createdAt,
})
@@ -273,6 +289,7 @@ export function createUsageServiceRepository(
assetId: input.assetId,
albumId: input.albumId,
priceCents: priceCents,
collab,
downloadId: event.id,
},
occurredAt: createdAt,
@@ -352,6 +369,7 @@ function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput
...(reference === undefined ? {} : { reference }),
...(input.maxPriceCents === undefined ? {} : { maxPriceCents: input.maxPriceCents }),
idempotencyKey: normalizeUuid(input.idempotencyKey),
...(input.collab === true ? { collab: true } : {}),
};
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more