feat: redesign portal UI with Sakani UI and add release notes

Replace the hand-rolled Tailwind/shadcn look with Sakani UI across the
editorial area, the admin area and all signed-out pages.

- AppShell (Sakani Sidebar + TopBar) for /redaktion and /admin, with a
  mobile drawer, theme toggle, sign-out, legal links and a "Was ist neu"
  button; PublicShell for login, registration, password, 2FA and errors.
- Shared primitives (Button, Card, Input, PageHeader) now render Sakani;
  components/ui/sakani.tsx is the client boundary for Server Components
  (Sakani ships no "use client") and adds FormSelect (native form value)
  and DataTable (element cells from the server).
- Legacy CSS variables map onto Sakani tokens; globals.css shrinks from
  ~2200 to ~700 lines. Geist replaces Inter. recharts/lucide-react dropped
  (charts via Sakani BarChart).
- Release notes popup per area, shown once per version (localStorage) and
  reopenable from the sidebar; native <dialog> for focus trapping.
- Fixes found while testing: TOTP field reused the typed password in
  clear text, modal dialogs sat top-left, invisible unchecked checkboxes
  in dark mode.
- Parallel run: compose.parallel.yaml, AUTO_RULE_SYNC_DISABLED switch and
  docs/operations.md §8 (start, rollback, cutover).

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 18:24:05 +01:00
1 parent 453bece72c
commit 9e938e4d07
79 files changed
+2266 -4316

No files matched your search

+6
View File
@@ -26,3 +26,9 @@ LEGAL_TERMS_URL=https://leon-tonhaeuser.de/agb
# Optional bearer token to trigger the sync externally via # Optional bearer token to trigger the sync externally via
# POST /api/cron/album-sync (Authorization: Bearer <CRON_SECRET>). # POST /api/cron/album-sync (Authorization: Bearer <CRON_SECRET>).
# CRON_SECRET=replace-with-a-long-random-secret # CRON_SECRET=replace-with-a-long-random-secret
# Parallel run of the new UI (see docs/operations.md §8). Only needed while
# compose.parallel.yaml is in use; the parallel container sets
# AUTO_RULE_SYNC_DISABLED=true itself so the sync does not run twice.
# PARALLEL_BASE_URL=https://neu.redaktionen.leon-tonhaeuser.de
# PARALLEL_PORT=3001
+40
View File
@@ -0,0 +1,40 @@
# Parallel run of the new (Sakani) UI next to the live portal: same database,
# same Immich, own subdomain. Run it from the LIVE checkout so the service joins
# the live compose project and its networks — see docs/operations.md §8:
#
# docker compose -f compose.yaml -f ../portal-sakani/compose.parallel.yaml up -d portal-app-next
#
# The image is built beforehand from the Sakani branch checkout:
# docker build -t portal-app:sakani ../portal-sakani
services:
portal-app-next:
image: ${PARALLEL_IMAGE:-portal-app:sakani}
container_name: portal-app-next
restart: unless-stopped
ports:
- "${PARALLEL_PORT:-3001}:3000"
environment:
DATABASE_URL: ${DATABASE_URL:-postgres://portal:change-me@portal-db:5432/portal}
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET}
# Public URL of the parallel instance (links in e-mails, auth callbacks).
BETTER_AUTH_URL: ${PARALLEL_BASE_URL:?set PARALLEL_BASE_URL in .env, e.g. https://neu.redaktionen.leon-tonhaeuser.de}
IMMICH_BASE_URL: ${IMMICH_BASE_URL}
IMMICH_API_KEY: ${IMMICH_API_KEY}
SMTP_HOST: ${SMTP_HOST}
SMTP_PORT: ${SMTP_PORT:-587}
SMTP_USER: ${SMTP_USER}
SMTP_PASSWORD: ${SMTP_PASSWORD}
SMTP_FROM: ${SMTP_FROM}
LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL:-https://leon-tonhaeuser.de/impressum}
LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL:-https://leon-tonhaeuser.de/datenschutz}
LEGAL_TERMS_URL: ${LEGAL_TERMS_URL:-https://leon-tonhaeuser.de/agb}
# The live instance keeps running the album auto-rule sync and the cron
# endpoint; the parallel one must not do either a second time.
AUTO_RULE_SYNC_DISABLED: "true"
CRON_SECRET: ""
depends_on:
portal-db:
condition: service_healthy
networks:
- portal-internal
- immich_default
+63
View File
@@ -36,6 +36,7 @@ All production configuration is provided via environment variables (e.g. `.env`
| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://leon-tonhaeuser.de/agb` | | `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://leon-tonhaeuser.de/agb` |
| `AUTO_RULE_SYNC_INTERVAL_SECONDS` | Interval of the album auto-rule sync in seconds (min 30) | `120` (default) | | `AUTO_RULE_SYNC_INTERVAL_SECONDS` | Interval of the album auto-rule sync in seconds (min 30) | `120` (default) |
| `CRON_SECRET` | Optional bearer token for `POST /api/cron/album-sync`; unset disables the endpoint | `openssl rand -hex 32` | | `CRON_SECRET` | Optional bearer token for `POST /api/cron/album-sync`; unset disables the endpoint | `openssl rand -hex 32` |
| `AUTO_RULE_SYNC_DISABLED` | `true` skips the in-process album auto-rule sync (for a second instance on the same DB, see §8) | unset (sync runs) |
--- ---
@@ -139,3 +140,65 @@ docker compose start portal-app
- `GET /api/health/live` -> 200 OK (Process liveness). - `GET /api/health/live` -> 200 OK (Process liveness).
- `GET /api/health/ready` -> 200 OK (Database & Immich connectivity). - `GET /api/health/ready` -> 200 OK (Database & Immich connectivity).
- **Audit Log Inspection**: Accessible in portal UI under `/admin/audit` (Admin role required). - **Audit Log Inspection**: Accessible in portal UI under `/admin/audit` (Admin role required).
---
## 8. Parallel Run of the New UI (Sakani) and Cutover
The Sakani redesign can run next to the live portal on its own subdomain, against
the **same database and Immich**, until it is accepted. The branch contains no
database migrations, so both versions work on the same schema.
**What "parallel" means in practice**
- Every action in the new UI is real: approvals, album grants, downloads, usages,
billing reports and announcements land in the production database.
- Sessions are per domain: users log in separately on the new subdomain.
- E-mails sent by the parallel instance (verification, password reset, album
notifications) link to the new subdomain (`PARALLEL_BASE_URL`).
- Only the live instance runs the album auto-rule sync and the cron endpoint; the
parallel one has `AUTO_RULE_SYNC_DISABLED=true` and no `CRON_SECRET`.
**Start the parallel instance** (on the server, next to the live checkout):
1. Push the branch, then check it out beside the live checkout:
```bash
git fetch origin && git worktree add ../portal-sakani origin/<sakani-branch>
```
2. Build its image:
```bash
docker build -t portal-app:sakani ../portal-sakani
```
3. In the live `.env`, add the public URL of the new subdomain:
```bash
PARALLEL_BASE_URL=https://neu.redaktionen.leon-tonhaeuser.de
```
4. Start it from the **live** checkout (so it joins the live networks and DB):
```bash
docker compose -f compose.yaml -f ../portal-sakani/compose.parallel.yaml up -d portal-app-next
```
5. DNS: point the subdomain at the server. Reverse proxy (Zoraxy): add a rule
`neu.redaktionen…` → `localhost:3001` with the same settings as the live rule
(no buffering for `/api/downloads/`, `X-Forwarded-For` as described in §3).
6. Smoke test: `GET https://<subdomain>/api/health/ready` → 200, then log in as
admin and as an editorial account.
**Update the parallel instance** after new commits on the branch:
`git -C ../portal-sakani pull`, rebuild the image (step 2), re-run step 4.
**Roll back** at any time: stop only the parallel container — the live portal is
untouched.
```bash
docker compose -f compose.yaml -f ../portal-sakani/compose.parallel.yaml rm -sf portal-app-next
```
**Cutover** (the new UI replaces the old one on the main domain):
1. Merge the Sakani branch into `main`.
2. In the live checkout: `git pull`, then
`docker compose build portal-app && docker compose up -d portal-app`.
(`BETTER_AUTH_URL` stays the main domain; no other env changes are needed.)
3. Stop the parallel container (rollback command above), remove the Zoraxy rule
or turn it into a redirect to the main domain, delete `PARALLEL_BASE_URL` from
`.env`, and `git worktree remove ../portal-sakani`.
+2 -2
View File
@@ -17,13 +17,14 @@
}, },
"dependencies": { "dependencies": {
"@better-auth/drizzle-adapter": "^1.6.26", "@better-auth/drizzle-adapter": "^1.6.26",
"@fontsource-variable/geist": "^5.3.0",
"@js-temporal/polyfill": "^0.5.1", "@js-temporal/polyfill": "^0.5.1",
"@radix-ui/react-slot": "^1.3.3", "@radix-ui/react-slot": "^1.3.3",
"@sakaniui/react": "^0.23.0",
"archiver": "^8.0.0", "archiver": "^8.0.0",
"better-auth": "^1.6.26", "better-auth": "^1.6.26",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"lucide-react": "^1.31.0",
"next": "^16.3.0", "next": "^16.3.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nodemailer": "^9.0.5", "nodemailer": "^9.0.5",
@@ -31,7 +32,6 @@
"pg": "^8.22.0", "pg": "^8.22.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"recharts": "^3.10.1",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"tailwind-merge": "^3.6.0", "tailwind-merge": "^3.6.0",
+28 -15
View File
@@ -11,12 +11,18 @@ importers:
'@better-auth/drizzle-adapter': '@better-auth/drizzle-adapter':
specifier: ^1.6.26 specifier: ^1.6.26
version: 1.6.26(@better-auth/core@1.6.26(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.8)(kysely@0.29.4)(nanostores@1.4.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0)) version: 1.6.26(@better-auth/core@1.6.26(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.8)(kysely@0.29.4)(nanostores@1.4.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0))
'@fontsource-variable/geist':
specifier: ^5.3.0
version: 5.3.0
'@js-temporal/polyfill': '@js-temporal/polyfill':
specifier: ^0.5.1 specifier: ^0.5.1
version: 0.5.1 version: 0.5.1
'@radix-ui/react-slot': '@radix-ui/react-slot':
specifier: ^1.3.3 specifier: ^1.3.3
version: 1.3.3(@types/react@19.2.18)(react@19.2.8) version: 1.3.3(@types/react@19.2.18)(react@19.2.8)
'@sakaniui/react':
specifier: ^0.23.0
version: 0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
archiver: archiver:
specifier: ^8.0.0 specifier: ^8.0.0
version: 8.0.0 version: 8.0.0
@@ -29,9 +35,6 @@ importers:
drizzle-orm: drizzle-orm:
specifier: ^0.45.2 specifier: ^0.45.2
version: 0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0) version: 0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0)
lucide-react:
specifier: ^1.31.0
version: 1.31.0(react@19.2.8)
next: next:
specifier: ^16.3.0 specifier: ^16.3.0
version: 16.3.0(@babel/core@7.29.7)(@playwright/test@1.62.1)(@types/node@24.13.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) version: 16.3.0(@babel/core@7.29.7)(@playwright/test@1.62.1)(@types/node@24.13.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
@@ -53,9 +56,6 @@ importers:
react-dom: react-dom:
specifier: ^19.2.8 specifier: ^19.2.8
version: 19.2.8(react@19.2.8) version: 19.2.8(react@19.2.8)
recharts:
specifier: ^3.10.1
version: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
server-only: server-only:
specifier: ^0.0.1 specifier: ^0.0.1
version: 0.0.1 version: 0.0.1
@@ -875,6 +875,9 @@ packages:
'@noble/hashes': '@noble/hashes':
optional: true optional: true
'@fontsource-variable/geist@5.3.0':
resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==}
'@grpc/grpc-js@1.14.4': '@grpc/grpc-js@1.14.4':
resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==} resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
engines: {node: '>=12.10.0'} engines: {node: '>=12.10.0'}
@@ -1492,6 +1495,13 @@ packages:
'@rtsao/scc@1.1.0': '@rtsao/scc@1.1.0':
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
'@sakaniui/react@0.23.0':
resolution: {integrity: sha512-9BnsvgacsDaERq0lQZNHuqNwfCSNhiPSkQLQMhH0mRSJ9K0I9Jz0Ht4W5HifuMAWnCwb3J6aZUEV6wpn7hk/kw==}
hasBin: true
peerDependencies:
react: ^19.0.0
react-dom: ^19.0.0
'@standard-schema/spec@1.1.0': '@standard-schema/spec@1.1.0':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -3462,11 +3472,6 @@ packages:
lru-cache@5.1.1: lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
lucide-react@1.31.0:
resolution: {integrity: sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
lz-string@1.5.0: lz-string@1.5.0:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true hasBin: true
@@ -5090,6 +5095,8 @@ snapshots:
optionalDependencies: optionalDependencies:
'@noble/hashes': 2.3.0 '@noble/hashes': 2.3.0
'@fontsource-variable/geist@5.3.0': {}
'@grpc/grpc-js@1.14.4': '@grpc/grpc-js@1.14.4':
dependencies: dependencies:
'@grpc/proto-loader': 0.8.1 '@grpc/proto-loader': 0.8.1
@@ -5530,6 +5537,16 @@ snapshots:
'@rtsao/scc@1.1.0': {} '@rtsao/scc@1.1.0': {}
'@sakaniui/react@0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)':
dependencies:
react: 19.2.8
react-dom: 19.2.8(react@19.2.8)
recharts: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
transitivePeerDependencies:
- '@types/react'
- react-is
- redux
'@standard-schema/spec@1.1.0': {} '@standard-schema/spec@1.1.0': {}
'@standard-schema/utils@0.3.0': {} '@standard-schema/utils@0.3.0': {}
@@ -7578,10 +7595,6 @@ snapshots:
dependencies: dependencies:
yallist: 3.1.1 yallist: 3.1.1
lucide-react@1.31.0(react@19.2.8):
dependencies:
react: 19.2.8
lz-string@1.5.0: {} lz-string@1.5.0: {}
magic-string@0.30.21: magic-string@0.30.21:
+13 -18
View File
@@ -1,26 +1,21 @@
import Link from "next/link"; import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { LoginForm } from "@/modules/auth/public-forms"; import { LoginForm } from "@/modules/auth/public-forms";
export default function LoginPage() { export default function LoginPage() {
return ( return (
<main className="public-account-page"> <PublicShell
<header className="masthead"> kicker="Zugang"
<Link className="wordmark" href="/"> title="Anmelden"
Leon Tonhäuser titleId="login-title"
</Link> lede="Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an."
<span className="section-label">Redaktionsportal</span> >
</header> <LoginForm />
<section className="account-panel" aria-labelledby="login-title"> <nav aria-label="Zugang verwalten" className="flex flex-wrap justify-between gap-x-4 gap-y-2 text-sm">
<p className="eyebrow">Zugang</p> <Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/passwort-vergessen">Passwort vergessen?</Link>
<h1 id="login-title">Anmelden</h1> <Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/registrieren">Neue Redaktion registrieren</Link>
<p className="lede">Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an.</p> </nav>
<LoginForm /> </PublicShell>
<nav className="account-links" aria-label="Zugang verwalten">
<Link href="/passwort-vergessen">Passwort vergessen?</Link>
<Link href="/registrieren">Neue Redaktion registrieren</Link>
</nav>
</section>
</main>
); );
} }
+7 -17
View File
@@ -1,25 +1,15 @@
import Link from "next/link"; import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { PasswordResetRequestForm } from "@/modules/auth/public-forms"; import { PasswordResetRequestForm } from "@/modules/auth/public-forms";
export default function ForgotPasswordPage() { export default function ForgotPasswordPage() {
return ( return (
<main className="public-account-page"> <PublicShell kicker="Zugang" title="Passwort vergessen?" titleId="forgot-password-title" lede="Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.">
<header className="masthead"> <PasswordResetRequestForm />
<Link className="wordmark" href="/"> <nav aria-label="Zurück zur Anmeldung" className="text-sm">
Leon Tonhäuser <Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
</Link> </nav>
<span className="section-label">Redaktionsportal</span> </PublicShell>
</header>
<section className="account-panel" aria-labelledby="forgot-password-title">
<p className="eyebrow">Zugang</p>
<h1 id="forgot-password-title">Passwort vergessen?</h1>
<p className="lede">Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.</p>
<PasswordResetRequestForm />
<nav className="account-links" aria-label="Zurück zur Anmeldung">
<Link href="/anmelden">Zur Anmeldung</Link>
</nav>
</section>
</main>
); );
} }
@@ -1,5 +1,6 @@
import Link from "next/link"; import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { PasswordResetForm } from "@/modules/auth/public-forms"; import { PasswordResetForm } from "@/modules/auth/public-forms";
export default async function ResetPasswordPage({ export default async function ResetPasswordPage({
@@ -10,22 +11,11 @@ export default async function ResetPasswordPage({
const { token } = await searchParams; const { token } = await searchParams;
return ( return (
<main className="public-account-page"> <PublicShell kicker="Zugang" title="Neues Passwort setzen" titleId="reset-password-title" lede="Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.">
<header className="masthead"> <PasswordResetForm token={token} />
<Link className="wordmark" href="/"> <nav aria-label="Zurück zur Anmeldung" className="text-sm">
Leon Tonhäuser <Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
</Link> </nav>
<span className="section-label">Redaktionsportal</span> </PublicShell>
</header>
<section className="account-panel" aria-labelledby="reset-password-title">
<p className="eyebrow">Zugang</p>
<h1 id="reset-password-title">Neues Passwort setzen</h1>
<p className="lede">Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.</p>
<PasswordResetForm token={token} />
<nav className="account-links" aria-label="Zurück zur Anmeldung">
<Link href="/anmelden">Zur Anmeldung</Link>
</nav>
</section>
</main>
); );
} }
@@ -1,25 +1,21 @@
import Link from "next/link"; import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { Button } from "@/components/ui/button";
export default function RegistrationConfirmedPage() { export default function RegistrationConfirmedPage() {
return ( return (
<main className="public-account-page"> <PublicShell
<header className="masthead"> kicker="Registrierung"
<Link className="wordmark" href="/"> title="Vielen Dank."
Leon Tonhäuser titleId="confirmation-title"
</Link> lede="Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach prüfen wir Ihre Registrierung."
<span className="section-label">Redaktionsportal</span> >
</header> <div>
<section className="account-panel" aria-labelledby="confirmation-title"> <Button asChild>
<p className="eyebrow">Registrierung</p> <Link href="/anmelden">Zur Anmeldung</Link>
<h1 id="confirmation-title">Vielen Dank.</h1> </Button>
<p className="lede"> </div>
Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach </PublicShell>
prüfen wir Ihre Registrierung.
</p>
<Link className="primary-action" href="/anmelden">
Zur Anmeldung
</Link>
</section>
</main>
); );
} }
+17 -24
View File
@@ -1,7 +1,7 @@
import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { PublicShell } from "@/components/layout/public-shell";
import { env } from "@/config/env"; import { env } from "@/config/env";
import { registerEditorial } from "@/modules/auth/auth"; import { registerEditorial } from "@/modules/auth/auth";
import { import {
@@ -16,29 +16,22 @@ import { RateLimitExceededError } from "@/modules/security/rate-limit-guard";
export default function RegistrationPage() { export default function RegistrationPage() {
return ( return (
<main className="public-account-page"> <PublicShell
<header className="masthead"> kicker="B2B-Zugang"
<Link className="wordmark" href="/"> title="Redaktion registrieren"
Leon Tonhäuser titleId="registration-title"
</Link> lede="Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung."
<span className="section-label">Redaktionsportal</span> wide
</header> >
<section className="account-panel account-panel-wide" aria-labelledby="registration-title"> <RegistrationForm
<p className="eyebrow">B2B-Zugang</p> action={registerAction}
<h1 id="registration-title">Redaktion registrieren</h1> legalUrls={{
<p className="lede"> imprint: env.LEGAL_IMPRINT_URL,
Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung. privacy: env.LEGAL_PRIVACY_URL,
</p> terms: env.LEGAL_TERMS_URL,
<RegistrationForm }}
action={registerAction} />
legalUrls={{ </PublicShell>
imprint: env.LEGAL_IMPRINT_URL,
privacy: env.LEGAL_PRIVACY_URL,
terms: env.LEGAL_TERMS_URL,
}}
/>
</section>
</main>
); );
} }
@@ -2,6 +2,11 @@
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import { Card, FormSelect } from "@/components/ui/sakani";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries"; import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
import { formatCents } from "@/modules/billing/format"; import { formatCents } from "@/modules/billing/format";
@@ -40,6 +45,12 @@ const STATUS_LABELS: Record<BillingPosition["status"], string> = {
reopened: "Wiedereröffnet", reopened: "Wiedereröffnet",
}; };
const STATUS_BADGES: Record<BillingPosition["status"], "warning" | "success"> = {
open: "warning",
billed: "success",
reopened: "warning",
};
const REPORT_STATUS_LABELS: Record<string, string> = { const REPORT_STATUS_LABELS: Record<string, string> = {
draft: "Entwurf", draft: "Entwurf",
final: "Erstellt", final: "Erstellt",
@@ -172,178 +183,162 @@ export function BillingSelection({
<> <>
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} /> <PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
<div className="billing-selection-controls"> <div className="flex flex-wrap items-center gap-3">
<button type="button" onClick={selectAllOpen} disabled={selectablePositions.length === 0}> <Button type="button" variant="secondary" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"} {isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
</button> </Button>
{isQuarter ? ( <Button asChild variant="outline">
<Link href={monthHref} className="billing-nav-link"> {isQuarter ? <Link href={monthHref}>Monatsansicht</Link> : <Link href={quarterHref}>Ganzes Quartal</Link>}
Monatsansicht </Button>
</Link> <Button type="button" variant="ghost" onClick={clearSelection} disabled={selectedCount === 0}>
) : (
<Link href={quarterHref} className="billing-nav-link">
Ganzes Quartal
</Link>
)}
<button type="button" onClick={clearSelection} disabled={selectedCount === 0}>
Auswahl aufheben Auswahl aufheben
</button> </Button>
<p className="ml-auto text-sm text-[var(--color-fg-muted)]" aria-live="polite">
Zeitraum: {periodLabel}
</p>
</div> </div>
<p className="billing-period-label" aria-live="polite"> <section className="flex flex-col gap-3" aria-labelledby="positions-title">
Zeitraum: {periodLabel} <h2 id="positions-title" className="text-lg font-semibold">Abrechenbare Nutzungen</h2>
</p> {positions.length === 0 ? (
<EmptyState title="Keine abrechenbaren Nutzungen in diesem Zeitraum." description="Wählen Sie oben einen anderen Monat oder ein Quartal." />
{positions.length === 0 ? ( ) : (
<p className="billing-empty">Keine abrechenbaren Nutzungen in diesem Zeitraum.</p> <Table<BillingPosition>
) : ( rowKey={(position) => position.id}
<table className="billing-table"> rows={positions}
<caption className="billing-caption"> columns={[
Abrechenbare Nutzungen {
</caption> key: "id",
<thead> header: "Auswahl",
<tr> render: (position) => (
<th scope="col">Auswahl</th> <Checkbox
<th scope="col">Datei</th>
<th scope="col">Album</th>
<th scope="col">Zweck</th>
<th scope="col">Referenz</th>
<th scope="col">Preis</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{positions.map((position) => (
<tr key={position.id} className={position.selectable ? "" : "billing-row-billed"}>
<td>
<input
type="checkbox"
checked={selectedIds.has(position.id)}
onChange={() => togglePosition(position.id)}
disabled={!position.selectable}
aria-label={`${position.filename} auswählen`} aria-label={`${position.filename} auswählen`}
checked={selectedIds.has(position.id)}
disabled={!position.selectable}
onChange={() => togglePosition(position.id)}
/> />
</td> ),
<td>{position.filename}</td> },
<td>{position.albumName}</td> { key: "filename", header: "Datei" },
<td>{position.purpose}</td> { key: "albumName", header: "Album" },
<td>{position.reference ?? "—"}</td> { key: "purpose", header: "Zweck" },
<td className="billing-price">{formatCents(position.priceCents)}</td> { key: "reference", header: "Referenz", render: (position) => position.reference ?? "—" },
<td> {
<span className="billing-status"> key: "priceCents",
{STATUS_LABELS[position.status]} header: "Preis",
align: "right",
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
},
{
key: "status",
header: "Status",
render: (position) => (
<span className="flex flex-wrap items-center gap-2">
<Badge variant={STATUS_BADGES[position.status] ?? "neutral"}>{STATUS_LABELS[position.status]}</Badge>
{position.status === "billed" && position.reportNumber !== null && ( {position.status === "billed" && position.reportNumber !== null && (
<span className="billing-report-ref"> <span className="text-xs text-[var(--color-fg-muted)]">
{" "}· Bericht Nr. {position.reportNumber} Bericht Nr. {position.reportNumber}
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""} {position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
</span> </span>
)} )}
</span> </span>
</td> ),
</tr> },
))} ]}
</tbody> />
</table> )}
)} </section>
{repeatDownloads.length > 0 && ( {repeatDownloads.length > 0 && (
<section aria-labelledby="repeat-downloads-title" className="billing-repeat-section"> <section aria-labelledby="repeat-downloads-title" className="flex flex-col gap-3">
<h2 id="repeat-downloads-title">Kostenlose Wiederabrufe</h2> <h2 id="repeat-downloads-title" className="text-lg font-semibold">Kostenlose Wiederabrufe</h2>
<p className="form-note"> <p className="text-sm text-[var(--color-fg-muted)]">
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
abrechenbar. abrechenbar.
</p> </p>
<table className="billing-table billing-table-repeat"> <Table<RepeatDownloadPosition>
<caption className="billing-caption">Wiederabrufe im Zeitraum</caption> rowKey={(download) => download.id}
<thead> rows={repeatDownloads}
<tr> columns={[
<th scope="col">Datei</th> { key: "assetId", header: "Datei" },
<th scope="col">Datum</th> {
<th scope="col">Status</th> key: "authorizedAt",
<th scope="col">Notiz</th> header: "Datum",
</tr> render: (download) => (
</thead> <time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
<tbody> {download.authorizedAt.toLocaleDateString("de-DE")}
{repeatDownloads.map((download) => ( </time>
<tr key={download.id}> ),
<td>{download.assetId}</td> },
<td> { key: "status", header: "Status" },
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning> { key: "repeatDownloadNote", header: "Notiz", render: (download) => download.repeatDownloadNote ?? "—" },
{download.authorizedAt.toLocaleDateString("de-DE")} ]}
</time> />
</td>
<td>{download.status}</td>
<td>{download.repeatDownloadNote ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</section> </section>
)} )}
<div className="billing-summary" aria-live="polite"> <Card>
<p> <div className="flex flex-wrap items-center justify-between gap-4">
<strong>{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt <div aria-live="polite" className="billing-summary flex flex-col gap-1">
</p> <p className="text-sm text-[var(--color-fg-muted)]">
<p className="billing-summary-total"> <strong className="text-[var(--color-fg-default)]">{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
Summe: <strong>{formatCents(selectedTotalCents)}</strong> </p>
</p> <p className="text-2xl font-semibold tabular-nums">
</div> Summe: <strong>{formatCents(selectedTotalCents)}</strong>
</p>
<div className="billing-actions"> </div>
<button <div className="flex flex-wrap gap-3">
type="button" <Button type="button" variant="outline" onClick={handlePreview} disabled={selectedCount === 0 || actionState.loading}>
onClick={handlePreview} Vorschau
disabled={selectedCount === 0 || actionState.loading} </Button>
> <Button type="button" onClick={handleFinalize} disabled={selectedCount === 0 || actionState.loading}>
Vorschau Abrechnung erstellen
</button> </Button>
<button </div>
type="button" </div>
className="billing-action-primary" {actionState.message && (
onClick={handleFinalize} <div role={actionState.isError ? undefined : "status"}>
disabled={selectedCount === 0 || actionState.loading} <Alert color={actionState.isError ? "danger" : "info"} description={actionState.message} />
> </div>
Abrechnung erstellen )}
</button> </Card>
</div>
{actionState.message && (
<p className="billing-status-message" role={actionState.isError ? "alert" : "status"}>
{actionState.message}
</p>
)}
{reports.length > 0 && ( {reports.length > 0 && (
<section aria-labelledby="reports-title" className="billing-reports-section"> <section aria-labelledby="reports-title" className="flex flex-col gap-3">
<h2 id="reports-title">Erstellte Abrechnungen</h2> <h2 id="reports-title" className="text-lg font-semibold">Erstellte Abrechnungen</h2>
<ul className="billing-reports-list"> <ul className="flex flex-col gap-3">
{reports.map((report) => ( {reports.map((report) => (
<li key={report.id}> <li key={report.id}>
<div className="billing-report-meta"> <Card>
<span>Bericht Nr. {report.reportNumber}</span> <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
{report.invoiceNumber && <span>{report.invoiceNumber}</span>} <span className="inline-flex items-center gap-2 font-semibold">
<span>Summe: {formatCents(report.netTotalCents)}</span> <IconFileText size={16} aria-hidden="true" />
<span>Status: {REPORT_STATUS_LABELS[report.status] ?? report.status}</span> Bericht Nr. {report.reportNumber}
<span> </span>
Erstellt am:{" "} {report.invoiceNumber && <span>{report.invoiceNumber}</span>}
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning> <span className="tabular-nums">Summe: {formatCents(report.netTotalCents)}</span>
{report.createdAt.toLocaleDateString("de-DE")} <Badge variant={report.status === "final" ? "success" : "neutral"}>
</time> {REPORT_STATUS_LABELS[report.status] ?? report.status}
</span> </Badge>
</div> <span className="text-[var(--color-fg-muted)]">
{report.status === "final" && ( Erstellt am:{" "}
<> <time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
{report.createdAt.toLocaleDateString("de-DE")}
</time>
</span>
{report.status === "final" && (
<Button asChild variant="outline">
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
<IconDownload size={16} aria-hidden="true" />
PDF herunterladen
</a>
</Button>
)}
</div>
{report.status === "final" && (
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} /> <CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<a )}
href={`/api/billing-reports/${encodeURIComponent(report.id)}`} </Card>
className="billing-report-download"
download
>
PDF herunterladen
</a>
</>
)}
</li> </li>
))} ))}
</ul> </ul>
@@ -364,42 +359,33 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
const years = [2025, 2026, 2027]; const years = [2025, 2026, 2027];
return ( return (
<form className="billing-period-selector" method="get"> <Card>
<label> <form className="flex flex-wrap items-end gap-4" method="get">
<span>Jahr</span> <div className="w-32">
<select name="year" defaultValue={year}> <FormSelect name="year" label="Jahr" defaultValue={String(year)} options={years.map((y) => ({ label: String(y), value: String(y) }))} />
{years.map((y) => ( </div>
<option key={y} value={y}> {isQuarter ? (
{y} <div className="w-32">
</option> <FormSelect
))} name="quarter"
</select> label="Quartal"
</label> defaultValue={String(quarter ?? 1)}
{isQuarter ? ( options={[1, 2, 3, 4].map((q) => ({ label: `Q${q}`, value: String(q) }))}
<label> />
<span>Quartal</span> </div>
<select name="quarter" defaultValue={quarter ?? 1}> ) : (
{[1, 2, 3, 4].map((q) => ( <div className="w-40">
<option key={q} value={q}> <FormSelect
Q{q} name="month"
</option> label="Monat"
))} defaultValue={String(month ?? 8)}
</select> options={MONTHS.map((name, index) => ({ label: name, value: String(index + 1) }))}
</label> />
) : ( </div>
<label> )}
<span>Monat</span> <Button type="submit" variant="secondary">Zeitraum laden</Button>
<select name="month" defaultValue={month ?? 8}> </form>
{MONTHS.map((name, index) => ( </Card>
<option key={index} value={index + 1}>
{name}
</option>
))}
</select>
</label>
)}
<button type="submit">Zeitraum laden</button>
</form>
); );
} }
@@ -440,38 +426,28 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
} }
return ( return (
<form className="billing-cancel-form" onSubmit={handleSubmit}> <form className="flex flex-col gap-3 border-t border-[var(--color-border-subtle)] pt-4" onSubmit={handleSubmit}>
<label> <Textarea
<span>Stornierungsgrund (5–500 Zeichen)</span>
<textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={2}
maxLength={500}
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`} aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
disabled={loading} disabled={loading}
label="Stornierungsgrund (5–500 Zeichen)"
maxLength={500}
onChange={(e) => setReason(e.target.value)}
rows={2}
value={reason}
/> />
</label> <div className="flex flex-wrap items-center gap-4">
<div className="billing-cancel-controls"> <Checkbox
<label>
<input
type="checkbox"
checked={confirmed} checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
disabled={loading} disabled={loading}
aria-label="Stornierung bestätigen" label="Stornierung bestätigen"
onChange={(e) => setConfirmed(e.target.checked)}
/> />
<span>Stornierung bestätigen</span> <Button type="submit" variant="destructive" disabled={!valid || loading}>
</label> {loading ? "Wird storniert …" : "Stornieren"}
<button type="submit" disabled={!valid || loading}> </Button>
{loading ? "Wird storniert…" : "Stornieren"} </div>
</button> {error && <Alert color="danger" description={error} />}
</div> </form>
{error && (
<p className="billing-status-message" role="alert">
{error}
</p>
)}
</form>
); );
} }
@@ -1,6 +1,9 @@
import Link from "next/link"; import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { loadBillingSelection } from "./page-content"; import { loadBillingSelection } from "./page-content";
import { BillingSelection } from "./BillingSelection"; import { BillingSelection } from "./BillingSelection";
@@ -17,12 +20,12 @@ export default async function BillingSelectionPage({
if (!data) notFound(); if (!data) notFound();
return ( return (
<section className="content-section" aria-labelledby="billing-selection-title"> <section className="flex flex-col gap-6" aria-labelledby="billing-selection-title">
<p className="eyebrow">Abrechnungen</p> <PageHeader kicker="Abrechnungen" title={data.editorial.name} titleId="billing-selection-title">
<h1 id="billing-selection-title">{data.editorial.name}</h1> <Button asChild variant="outline">
<p> <Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link> </Button>
</p> </PageHeader>
<BillingSelection <BillingSelection
editorialId={data.editorial.id} editorialId={data.editorial.id}
+35 -17
View File
@@ -1,5 +1,9 @@
import { desc } from "drizzle-orm"; import { desc } from "drizzle-orm";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema"; import { editorialAccounts } from "@/db/schema";
import { formatCents } from "@/modules/billing/format"; import { formatCents } from "@/modules/billing/format";
@@ -18,30 +22,44 @@ export default async function BillingOverviewPage() {
.orderBy(desc(editorialAccounts.createdAt)); .orderBy(desc(editorialAccounts.createdAt));
return ( return (
<section className="content-section" aria-labelledby="billing-title"> <section className="flex flex-col gap-6" aria-labelledby="billing-title">
<p className="eyebrow">Abrechnungen</p> <PageHeader
<h1 id="billing-title">Redaktionen</h1> kicker="Abrechnungen"
<p className="form-note"> title="Redaktionen"
Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal titleId="billing-title"
auszuwählen. description="Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal auszuwählen."
</p> />
{editorials.length === 0 ? ( {editorials.length === 0 ? (
<p>Noch keine Redaktionen registriert.</p> <EmptyState title="Noch keine Redaktionen registriert." description="Registrierte Redaktionen erscheinen hier zur Abrechnung." />
) : ( ) : (
<ul className="billing-editorial-list"> <ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{editorials.map((editorial) => ( {editorials.map((editorial) => (
<li key={editorial.id}> <li key={editorial.id}>
<a href={`/admin/abrechnungen/${editorial.id}`}>{editorial.name}</a> <Link
<p> className="block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status} href={`/admin/abrechnungen/${editorial.id}`}
{editorial.currentPriceCents === null >
? " · Preis noch nicht festgelegt" <Card interactive className="h-full">
: ` · Netto ${formatCents(editorial.currentPriceCents)}`} <div className="flex items-start justify-between gap-3">
</p> <h2 className="text-base font-semibold">{editorial.name}</h2>
<Badge variant={editorial.status === "active" ? "success" : editorial.status === "pending_approval" ? "warning" : "danger"}>
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
</Badge>
</div>
<p className="text-sm text-[var(--color-fg-muted)]">
{editorial.contactName} · {editorial.loginEmail}
</p>
<p className="text-sm font-medium">
{editorial.currentPriceCents === null
? "Preis noch nicht festgelegt"
: `Netto ${formatCents(editorial.currentPriceCents)}`}
</p>
</Card>
</Link>
</li> </li>
))} ))}
</ul> </ul>
)} )}
</section> </section>
); );
} }
+107 -141
View File
@@ -5,9 +5,11 @@
import { useActionState, useMemo, useState, useTransition } from "react"; import { useActionState, useMemo, useState, useTransition } from "react";
import Link from "next/link"; import Link from "next/link";
import { Alert, Checkbox, EmptyState, Input, Table } from "@sakaniui/react";
import { IconSearch, IconX } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { AlbumAccessActionResult } from "./actions"; import type { AlbumAccessActionResult } from "./actions";
type AccessAction = ( type AccessAction = (
@@ -15,6 +17,8 @@ type AccessAction = (
formData: FormData, formData: FormData,
) => Promise<AlbumAccessActionResult>; ) => Promise<AlbumAccessActionResult>;
type OverviewRow = AlbumAccessManagerAlbum;
export type AlbumAccessManagerAlbum = { export type AlbumAccessManagerAlbum = {
id: string; id: string;
albumName: string; albumName: string;
@@ -154,10 +158,10 @@ export function AlbumAccessManager({
})`; })`;
return ( return (
<div className="space-y-8"> <div className="flex flex-col gap-6">
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-lg">Bulk-Zuweisung</CardTitle> <CardTitle>Bulk-Zuweisung</CardTitle>
<CardDescription> <CardDescription>
Alben und Redaktionen auswählen und allen ausgewählten Redaktionen mit einem Klick Alben und Redaktionen auswählen und allen ausgewählten Redaktionen mit einem Klick
Zugriff auf alle ausgewählten Alben geben. Bereits bestehende Zuweisungen werden Zugriff auf alle ausgewählten Alben geben. Bereits bestehende Zuweisungen werden
@@ -165,14 +169,15 @@ export function AlbumAccessManager({
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form action={handleBulkSubmit} className="space-y-6"> <form action={handleBulkSubmit} className="flex flex-col gap-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<fieldset className="space-y-3 min-w-0"> <fieldset className="flex min-w-0 flex-col gap-3">
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground"> <legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
Alben ({selectedAlbumIds.size} ausgewählt) Alben ({selectedAlbumIds.size} ausgewählt)
</legend> </legend>
<div className="flex flex-col sm:flex-row gap-2"> <div className="flex flex-col sm:flex-row gap-2">
<Input <Input
leadingIcon={<IconSearch size={16} />}
type="search" type="search"
value={bulkSearch} value={bulkSearch}
onChange={(event) => setBulkSearch(event.target.value)} onChange={(event) => setBulkSearch(event.target.value)}
@@ -190,37 +195,30 @@ export function AlbumAccessManager({
{allBulkAlbumsSelected ? "Auswahl aufheben" : "Alle auswählen"} {allBulkAlbumsSelected ? "Auswahl aufheben" : "Alle auswählen"}
</Button> </Button>
</div> </div>
<div className="max-h-80 overflow-y-auto rounded-md border border-border divide-y divide-border"> <div className="max-h-80 divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
{bulkAlbums.length === 0 ? ( {bulkAlbums.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">Keine Alben gefunden.</p> <p className="p-4 text-sm text-[var(--color-fg-muted)]">Keine Alben gefunden.</p>
) : ( ) : (
bulkAlbums.map((album) => ( bulkAlbums.map((album) => (
<label <div key={album.id} className="flex items-center gap-3 px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
key={album.id} <Checkbox
className="flex items-center gap-3 px-4 py-2.5 text-sm cursor-pointer hover:bg-accent/50"
>
<input
type="checkbox"
name="immichAlbumIds"
value={album.id}
checked={selectedAlbumIds.has(album.id)} checked={selectedAlbumIds.has(album.id)}
onChange={(event) => label={album.albumName}
toggleAlbumSelection(album.id, event.target.checked) name="immichAlbumIds"
} onChange={(event) => toggleAlbumSelection(album.id, event.target.checked)}
className="h-4 w-4 accent-primary-600" value={album.id}
/> />
<span className="truncate font-medium">{album.albumName}</span> <span className="ml-auto shrink-0 text-xs text-[var(--color-fg-muted)]">
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
{album.assetCount} Fotos {album.assetCount} Fotos
</span> </span>
</label> </div>
)) ))
)} )}
</div> </div>
</fieldset> </fieldset>
<fieldset className="space-y-3 min-w-0"> <fieldset className="flex min-w-0 flex-col gap-3">
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground"> <legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
Redaktionen ({selectedEditorialIds.size} ausgewählt) Redaktionen ({selectedEditorialIds.size} ausgewählt)
</legend> </legend>
<div className="flex justify-end"> <div className="flex justify-end">
@@ -234,29 +232,22 @@ export function AlbumAccessManager({
{allEditorialsSelected ? "Auswahl aufheben" : "Alle auswählen"} {allEditorialsSelected ? "Auswahl aufheben" : "Alle auswählen"}
</Button> </Button>
</div> </div>
<div className="max-h-80 overflow-y-auto rounded-md border border-border divide-y divide-border"> <div className="max-h-80 divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
{editorials.length === 0 ? ( {editorials.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground"> <p className="p-4 text-sm text-[var(--color-fg-muted)]">
Keine aktiven Redaktionen vorhanden. Keine aktiven Redaktionen vorhanden.
</p> </p>
) : ( ) : (
editorials.map((editorial) => ( editorials.map((editorial) => (
<label <div key={editorial.id} className="px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
key={editorial.id} <Checkbox
className="flex items-center gap-3 px-4 py-2.5 text-sm cursor-pointer hover:bg-accent/50"
>
<input
type="checkbox"
name="editorialIds"
value={editorial.id}
checked={selectedEditorialIds.has(editorial.id)} checked={selectedEditorialIds.has(editorial.id)}
onChange={(event) => label={editorial.name}
toggleEditorialSelection(editorial.id, event.target.checked) name="editorialIds"
} onChange={(event) => toggleEditorialSelection(editorial.id, event.target.checked)}
className="h-4 w-4 accent-primary-600" value={editorial.id}
/> />
<span className="truncate font-medium">{editorial.name}</span> </div>
</label>
)) ))
)} )}
</div> </div>
@@ -265,16 +256,9 @@ export function AlbumAccessManager({
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between"> <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
{bulkState.message ? ( {bulkState.message ? (
<p <Alert color={bulkState.ok ? "success" : "danger"} description={bulkState.message} />
role={bulkState.ok ? "status" : "alert"}
className={`text-sm ${
bulkState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
}`}
>
{bulkState.message}
</p>
) : ( ) : (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-[var(--color-fg-muted)]">
Wähle mindestens ein Album und eine Redaktion aus. Wähle mindestens ein Album und eine Redaktion aus.
</p> </p>
)} )}
@@ -289,7 +273,7 @@ export function AlbumAccessManager({
<Card> <Card>
<CardHeader className="gap-4"> <CardHeader className="gap-4">
<div> <div>
<CardTitle className="text-lg">Albumzugriffe</CardTitle> <CardTitle>Albumzugriffe</CardTitle>
<CardDescription> <CardDescription>
Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den
Zugriff für die einzelne Redaktion. Zugriff für die einzelne Redaktion.
@@ -297,6 +281,7 @@ export function AlbumAccessManager({
</div> </div>
<div className="sm:max-w-sm"> <div className="sm:max-w-sm">
<Input <Input
leadingIcon={<IconSearch size={16} />}
type="search" type="search"
value={overviewSearch} value={overviewSearch}
onChange={(event) => setOverviewSearch(event.target.value)} onChange={(event) => setOverviewSearch(event.target.value)}
@@ -305,103 +290,84 @@ export function AlbumAccessManager({
/> />
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="flex flex-col gap-4">
{revokeState.message ? ( {revokeState.message ? (
<p <Alert color={revokeState.ok ? "success" : "danger"} description={revokeState.message} />
role={revokeState.ok ? "status" : "alert"}
className={`text-sm ${
revokeState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
}`}
>
{revokeState.message}
</p>
) : null} ) : null}
{albums.length === 0 ? ( {albums.length === 0 ? (
<p className="text-muted-foreground text-sm">Derzeit sind keine Alben vorhanden.</p> <EmptyState title="Derzeit sind keine Alben vorhanden." description="Alben erscheinen hier, sobald der Immich-Zugang sie lesen kann." />
) : overviewAlbums.length === 0 ? ( ) : overviewAlbums.length === 0 ? (
<p className="text-muted-foreground text-sm">Keine Alben gefunden.</p> <EmptyState type="no-results" title="Keine Alben gefunden." description="Versuchen Sie einen anderen Suchbegriff." />
) : ( ) : (
<div className="overflow-x-auto rounded-md border border-border"> <Table<OverviewRow>
<table className="w-full text-left text-sm"> rowKey={(album) => album.id}
<thead className="bg-muted/50 border-b border-border"> rows={overviewAlbums}
<tr> columns={[
<th className="py-3 px-4 font-semibold">Album</th> {
<th className="py-3 px-4 font-semibold">Redaktionen mit Zugriff</th> key: "albumName",
<th className="py-3 px-4 font-semibold text-right">Anzahl</th> header: "Album",
</tr> render: (album) => (
</thead> <div className="flex items-center gap-3">
<tbody> {album.albumThumbnailAssetId ? (
{overviewAlbums.map((album, index) => ( <img
<tr className="h-10 w-14 shrink-0 rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] object-cover"
key={album.id} alt=""
className={index !== overviewAlbums.length - 1 ? "border-b border-border" : ""} loading="lazy"
> src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
<td className="py-3 px-4"> />
<div className="flex items-center gap-3"> ) : (
{album.albumThumbnailAssetId ? ( <div aria-hidden="true" className="grid h-10 w-14 shrink-0 place-items-center rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] text-[10px] text-[var(--color-fg-muted)]">
<img Kein Cover
className="h-10 w-14 rounded object-cover bg-muted shrink-0"
alt=""
loading="lazy"
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
/>
) : (
<div
aria-hidden="true"
className="h-10 w-14 rounded bg-muted shrink-0 flex items-center justify-center text-[10px] uppercase tracking-widest text-muted-foreground"
>
Kein Cover
</div>
)}
<div className="min-w-0">
<p className="font-medium truncate" title={album.albumName}>
{album.albumName}
</p>
<p className="text-xs text-muted-foreground">{album.assetCount} Fotos</p>
</div>
</div> </div>
</td> )}
<td className="py-3 px-4"> <div className="min-w-0">
{album.grants.length === 0 ? ( <p className="truncate font-medium" title={album.albumName}>{album.albumName}</p>
<span className="text-muted-foreground">Noch keine Redaktion</span> <p className="text-xs text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
) : ( </div>
<div className="flex flex-wrap gap-1.5"> </div>
{album.grants.map((holder) => ( ),
<form },
key={holder.editorialId} {
action={revokeFormAction} key: "grants",
className="inline-flex items-center overflow-hidden rounded-full border border-primary-200 bg-primary-50 text-primary-700 dark:border-primary-800 dark:bg-primary-900/30 dark:text-primary-300" header: "Redaktionen mit Zugriff",
> render: (album) =>
<input type="hidden" name="immichAlbumId" value={album.id} /> album.grants.length === 0 ? (
<input type="hidden" name="editorialId" value={holder.editorialId} /> <span className="text-[var(--color-fg-muted)]">Noch keine Redaktion</span>
<Link ) : (
href={`/admin/redaktionen/${holder.editorialId}`} <div className="flex flex-wrap gap-1.5">
className="py-0.5 pl-2.5 text-xs font-medium hover:underline" {album.grants.map((holder) => (
> <form
{holder.editorialName} key={holder.editorialId}
{holder.archived ? " (archiviert)" : ""} action={revokeFormAction}
</Link> className="inline-flex items-center overflow-hidden rounded-[var(--radius-full)] border border-[var(--color-border-default)] bg-[var(--color-bg-subtle)] text-[var(--color-fg-default)]"
<button >
type="submit" <input type="hidden" name="immichAlbumId" value={album.id} />
disabled={revokePending} <input type="hidden" name="editorialId" value={holder.editorialId} />
aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`} <Link
title={`Zugriff für ${holder.editorialName} entziehen`} href={`/admin/redaktionen/${holder.editorialId}`}
className="px-2 py-0.5 text-xs font-bold hover:bg-primary-100 dark:hover:bg-primary-800/50 disabled:opacity-50" className="py-0.5 pl-2.5 text-xs font-medium hover:underline"
> >
× {holder.editorialName}
</button> {holder.archived ? " (archiviert)" : ""}
</form> </Link>
))} <button
</div> type="submit"
)} disabled={revokePending}
</td> aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`}
<td className="py-3 px-4 text-right tabular-nums">{album.grants.length}</td> title={`Zugriff für ${holder.editorialName} entziehen`}
</tr> className="grid place-items-center px-1.5 py-1 hover:bg-[var(--color-bg-muted)] disabled:opacity-50"
))} >
</tbody> <IconX size={12} aria-hidden="true" />
</table> </button>
</div> </form>
))}
</div>
),
},
{ key: "assetCount", header: "Anzahl", align: "right", render: (album) => <span className="tabular-nums">{album.grants.length}</span> },
]}
/>
)} )}
</CardContent> </CardContent>
</Card> </Card>
+13 -16
View File
@@ -1,6 +1,8 @@
import Link from "next/link"; import Link from "next/link";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Alert } from "@/components/ui/sakani";
import { loadAlbumAccess, loadAssignableEditorials } from "./page-content"; import { loadAlbumAccess, loadAssignableEditorials } from "./page-content";
import { AlbumAccessManager } from "./AlbumAccessManager"; import { AlbumAccessManager } from "./AlbumAccessManager";
@@ -13,21 +15,22 @@ export default async function AdminAlbumsPage() {
]); ]);
return ( return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<PageHeader <PageHeader
kicker="Albumverwaltung" kicker="Albumverwaltung"
title="Alben" title="Alben"
description="Alle Immich-Alben mit ihren Redaktionsfreigaben — inklusive Bulk-Zuweisung für mehrere Alben und Redaktionen auf einmal." description="Alle Immich-Alben mit ihren Redaktionsfreigaben — inklusive Bulk-Zuweisung für mehrere Alben und Redaktionen auf einmal."
/> >
<Button asChild variant="outline">
<Link href="/admin/redaktionen">Zu den Redaktionen</Link>
</Button>
</PageHeader>
{albumResult.unavailable ? ( {albumResult.unavailable ? (
<div <Alert
className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" color="warning"
role="status" description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
> />
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben
unverändert.
</div>
) : ( ) : (
<AlbumAccessManager <AlbumAccessManager
albums={albumResult.albums.map((album) => ({ albums={albumResult.albums.map((album) => ({
@@ -46,12 +49,6 @@ export default async function AdminAlbumsPage() {
revokeAction={revokeAlbumAccessAction} revokeAction={revokeAlbumAccessAction}
/> />
)} )}
</section>
<p className="text-sm">
<Link href="/admin/redaktionen" className="text-primary-600 hover:underline">
Zu den Redaktionen
</Link>
</p>
</div>
); );
} }
+42 -58
View File
@@ -1,5 +1,8 @@
import Link from "next/link"; import Link from "next/link";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { Card, DataTable, EmptyState, Input } from "@/components/ui/sakani";
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries"; import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
import { requireAdminPage } from "../access"; import { requireAdminPage } from "../access";
@@ -31,71 +34,52 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
); );
return ( return (
<section className="content-section" aria-labelledby="audit-title"> <section className="flex flex-col gap-6" aria-labelledby="audit-title">
<p className="eyebrow">Administration</p> <PageHeader
<h1 id="audit-title">Audit-Protokoll</h1> kicker="Administration"
<p className="form-note"> title="Audit-Protokoll"
Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach titleId="audit-title"
Zeitstempel (neueste zuerst). description="Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach Zeitstempel (neueste zuerst)."
</p> />
<form method="get" className="audit-filters" aria-label="Audit-Filter"> <Card>
<label> <form method="get" className="grid gap-4 sm:grid-cols-[1fr_11rem_11rem_auto] sm:items-end" aria-label="Audit-Filter">
<span className="field-label">Ereignistyp</span> <Input label="Ereignistyp" name="eventType" defaultValue={eventType ?? ""} placeholder="z. B. editorial_approved" />
<input <Input label="Datum von (Berlin)" type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
name="eventType" <Input label="Datum bis (Berlin)" type="date" name="dateTo" defaultValue={dateTo ?? ""} />
defaultValue={eventType ?? ""} <Button type="submit" variant="secondary">Filtern</Button>
placeholder="z. B. editorial_approved" </form>
/> </Card>
</label>
<label>
<span className="field-label">Datum von (Berlin)</span>
<input type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
</label>
<label>
<span className="field-label">Datum bis (Berlin)</span>
<input type="date" name="dateTo" defaultValue={dateTo ?? ""} />
</label>
<button type="submit">Filtern</button>
</form>
{page.events.length === 0 ? ( {page.events.length === 0 ? (
<p>Keine Einträge gefunden.</p> <EmptyState type="no-results" title="Keine Einträge gefunden." description="Passen Sie die Filter an oder setzen Sie sie zurück." />
) : ( ) : (
<table className="audit-table"> <DataTable
<thead> columns={[
<tr> { key: "at", header: "Zeitstempel" },
<th>Zeitstempel</th> { key: "actor", header: "Akteur" },
<th>Akteur</th> { key: "type", header: "Ereignistyp" },
<th>Ereignistyp</th> { key: "subject", header: "Betreff" },
<th>Betreff</th> { key: "details", header: "Details" },
<th>Details</th> ]}
</tr> rows={page.events.map((event) => ({
</thead> at: <span className="whitespace-nowrap tabular-nums">{berlinFormatter.format(new Date(event.occurredAt))}</span>,
<tbody> actor: actorLabel(event),
{page.events.map((event) => ( type: <code className="break-all text-xs">{event.eventType}</code>,
<tr key={event.id}> subject: <span className="break-all text-xs">{entityLabel(event)}</span>,
<td>{berlinFormatter.format(new Date(event.occurredAt))}</td> details: <pre className="audit-metadata">{formatMetadata(event)}</pre>,
<td>{actorLabel(event)}</td> }))}
<td>{event.eventType}</td> />
<td>{entityLabel(event)}</td>
<td>
<pre className="audit-metadata">{formatMetadata(event)}</pre>
</td>
</tr>
))}
</tbody>
</table>
)} )}
{page.nextCursor && ( {page.nextCursor && (
<p className="audit-pagination"> <div>
<Link <Button asChild variant="outline">
href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`} <Link href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}>
> Ältere Einträge laden
Ältere Einträge laden </Link>
</Link> </Button>
</p> </div>
)} )}
</section> </section>
); );
-10
View File
@@ -1,10 +0,0 @@
"use client";
import dynamic from "next/dynamic";
const DownloadsChart = dynamic(
() => import("./downloads-chart").then((mod) => mod.DownloadsChart),
{ ssr: false }
);
export { DownloadsChart };
-80
View File
@@ -1,80 +0,0 @@
"use client";
import { useTheme } from "next-themes";
import {
Bar,
BarChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
CartesianGrid,
} from "recharts";
type DownloadsChartProps = {
data: { date: string; downloads: number }[];
};
export function DownloadsChart({ data }: DownloadsChartProps) {
const { theme } = useTheme();
// Indigo primary color variables
const primaryColor = theme === "dark" ? "#6366f1" : "#4f46e5"; // indigo-500 : indigo-600
return (
<div className="h-[300px] w-full mt-4">
{data.length === 0 ? (
<div className="flex h-full items-center justify-center text-muted-foreground">
Keine Download-Daten in den letzten 30 Tagen verfügbar.
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={theme === "dark" ? "#333" : "#e5e5e5"} />
<XAxis
dataKey="date"
stroke="#888888"
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value) => {
const date = new Date(value);
return date.toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
}}
/>
<YAxis
stroke="#888888"
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value) => `${value}`}
allowDecimals={false}
/>
<Tooltip
cursor={{ fill: theme === "dark" ? "#ffffff10" : "#00000005" }}
contentStyle={{
backgroundColor: theme === "dark" ? "#1f2937" : "#ffffff",
borderColor: theme === "dark" ? "#374151" : "#e5e7eb",
borderRadius: "8px",
color: theme === "dark" ? "#f3f4f6" : "#111827",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
}}
labelFormatter={(label: any) => {
const date = new Date(label as string);
return date.toLocaleDateString("de-DE", { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });
}}
formatter={(value: any) => [value as number, "Downloads"]}
/>
<Bar
dataKey="downloads"
fill={primaryColor}
radius={[4, 4, 0, 0]}
maxBarSize={40}
animationDuration={1000}
/>
</BarChart>
</ResponsiveContainer>
)}
</div>
);
}
+35 -46
View File
@@ -2,8 +2,11 @@
import { useId, useState, useTransition } from "react"; import { useId, useState, useTransition } from "react";
import { Alert, Input, Textarea } from "@sakaniui/react";
import { Card } from "@/components/ui/sakani";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { AnnouncementActionResult } from "./actions"; import type { AnnouncementActionResult } from "./actions";
@@ -36,56 +39,42 @@ export function AnnouncementForm({
}; };
return ( return (
<form <Card title="Neuer Hinweis">
action={handleSubmit} <form action={handleSubmit} className="flex flex-col gap-4">
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4" <Textarea
> description={`${message.length}/500 Zeichen`}
<div className="space-y-2">
<label htmlFor={messageId} className="text-sm font-medium">
Nachricht
</label>
<textarea
id={messageId} id={messageId}
name="message" label="Nachricht"
rows={3}
maxLength={500} maxLength={500}
required name="message"
value={message}
onChange={(event) => setMessage(event.target.value)} onChange={(event) => setMessage(event.target.value)}
placeholder="z. B. Liebl ist heute beim HSV-Spiel — Freigaben und Downloads sind trotzdem verfügbar, Antworten dauern etwas länger." placeholder="z. B. Liebl ist heute beim HSV-Spiel — Freigaben und Downloads sind trotzdem verfügbar, Antworten dauern etwas länger."
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">{message.length}/500 Zeichen</p>
</div>
<div className="space-y-2">
<label htmlFor={dateId} className="text-sm font-medium">
Datum des Ereignisses (z. B. Spieltag)
</label>
<Input
id={dateId}
type="date"
name="eventDate"
defaultValue={defaultEventDate}
required required
className="sm:w-48" rows={3}
value={message}
/> />
<p className="text-xs text-muted-foreground"> <div className="sm:max-w-xs">
Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem <Input
Datum. defaultValue={defaultEventDate}
</p> description="Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem Datum."
</div> id={dateId}
<Button type="submit" disabled={pending}> label="Datum des Ereignisses (z. B. Spieltag)"
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"} name="eventDate"
</Button> required
{state.message ? ( type="date"
<p />
role="status" </div>
aria-live="polite" <div>
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"} <Button type="submit" disabled={pending}>
> {pending ? "Wird veröffentlicht …" : "Hinweis veröffentlichen"}
{state.message} </Button>
</p> </div>
) : null} {state.message ? (
</form> <div aria-live="polite">
<Alert color={state.ok ? "success" : "danger"} description={state.message} />
</div>
) : null}
</form>
</Card>
); );
} }
@@ -2,6 +2,8 @@
import { useActionState } from "react"; import { useActionState } from "react";
import { IconTrash } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import type { AnnouncementActionResult } from "./actions"; import type { AnnouncementActionResult } from "./actions";
@@ -23,11 +25,11 @@ export function DeleteAnnouncementButton({
return ( return (
<form action={formAction} className="flex flex-col items-end gap-1"> <form action={formAction} className="flex flex-col items-end gap-1">
<input type="hidden" name="announcementId" value={announcementId} /> <input type="hidden" name="announcementId" value={announcementId} />
<Button type="submit" variant="outline" size="sm" disabled={pending}> <Button type="submit" variant="ghost" size="sm" disabled={pending} leftIcon={<IconTrash size={16} />}>
{pending ? "…" : "Löschen"} {pending ? "…" : "Löschen"}
</Button> </Button>
{state.ok ? null : ( {state.ok ? null : (
<p role="alert" className="text-xs text-destructive"> <p role="alert" className="text-xs text-[var(--color-danger-fg)]">
{state.message} {state.message}
</p> </p>
)} )}
+25 -27
View File
@@ -1,4 +1,5 @@
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
import { import {
formatIsoDateGerman, formatIsoDateGerman,
isoDateInBerlin, isoDateInBerlin,
@@ -14,7 +15,7 @@ export default async function AdminAnnouncementsPage() {
const activeCount = items.filter((item) => item.isActive).length; const activeCount = items.filter((item) => item.isActive).length;
return ( return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<PageHeader <PageHeader
kicker="Kommunikation" kicker="Kommunikation"
title="Hinweise" title="Hinweise"
@@ -26,46 +27,43 @@ export default async function AdminAnnouncementsPage() {
defaultEventDate={isoDateInBerlin(new Date())} defaultEventDate={isoDateInBerlin(new Date())}
/> />
<section className="space-y-4" aria-labelledby="announcements-list-title"> <section className="flex flex-col gap-4" aria-labelledby="announcements-list-title">
<div className="flex items-baseline justify-between"> <div className="flex items-baseline justify-between gap-4">
<h2 id="announcements-list-title" className="text-xl font-semibold"> <h2 id="announcements-list-title" className="text-xl font-semibold">
Alle Hinweise Alle Hinweise
</h2> </h2>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-[var(--color-fg-muted)]">
{activeCount} aktiv · {items.length} insgesamt {activeCount} aktiv · {items.length} insgesamt
</p> </p>
</div> </div>
{items.length === 0 ? ( {items.length === 0 ? (
<p className="text-muted-foreground py-8 text-center"> <EmptyState title="Noch keine Hinweise vorhanden." description="Veröffentlichte Hinweise erscheinen hier und in der Album-Übersicht der Redaktionen." />
Noch keine Hinweise vorhanden.
</p>
) : ( ) : (
<ul className="space-y-3"> <ul className="flex flex-col gap-3">
{items.map((item) => ( {items.map((item) => (
<li <li key={item.id}>
key={item.id} <Card>
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="flex flex-col justify-between gap-4 sm:flex-row sm:items-start">
> <div className="flex min-w-0 flex-col gap-2">
<div className="space-y-1 min-w-0"> <p className="whitespace-pre-line break-words text-sm text-[var(--color-fg-default)]">{item.message}</p>
<p className="text-sm whitespace-pre-line break-words">{item.message}</p> <p className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-fg-muted)]">
<p className="text-xs text-muted-foreground"> Ereignis: {formatIsoDateGerman(item.eventDate)}
Ereignis: {formatIsoDateGerman(item.eventDate)} ·{" "} {item.isActive ? (
{item.isActive ? ( <Badge variant="success">sichtbar bis {formatIsoDateGerman(item.visibleUntil)}</Badge>
<span className="text-green-600 dark:text-green-400"> ) : (
sichtbar bis {formatIsoDateGerman(item.visibleUntil)} <Badge>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</Badge>
</span> )}
) : ( </p>
<span>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</span> </div>
)} <DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
</p> </div>
</div> </Card>
<DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
</li> </li>
))} ))}
</ul> </ul>
)} )}
</section> </section>
</div> </section>
); );
} }
+6 -14
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { PortalShell } from "@/components/layout/portal-shell"; import { AppShell } from "@/components/layout/app-shell";
import { env } from "@/config/env";
import { requireAdminPage } from "./access"; import { requireAdminPage } from "./access";
@@ -8,20 +9,11 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
await requireAdminPage(); await requireAdminPage();
return ( return (
<PortalShell <AppShell
brandHref="/admin" area="admin"
sectionLabel="Administration" legal={{ imprint: env.LEGAL_IMPRINT_URL, privacy: env.LEGAL_PRIVACY_URL, terms: env.LEGAL_TERMS_URL }}
nav={[
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/redaktionen", label: "Redaktionen" },
{ href: "/admin/alben", label: "Alben" },
{ href: "/admin/hinweise", label: "Hinweise" },
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
{ href: "/admin/audit", label: "Audit" },
]}
mainClassName=""
> >
{children} {children}
</PortalShell> </AppShell>
); );
} }
+60 -104
View File
@@ -3,10 +3,9 @@ import { db } from "@/db/client";
import { usages, editorialAccounts } from "@/db/schema"; import { usages, editorialAccounts } from "@/db/schema";
import Link from "next/link"; import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { BarChart, Card, EmptyState, StatCard, DataTable } from "@/components/ui/sakani";
import { requireAdminPage } from "./access"; import { requireAdminPage } from "./access";
import { DownloadsChart } from "./downloads-chart-lazy";
export default async function AdminDashboardPage() { export default async function AdminDashboardPage() {
await requireAdminPage(); await requireAdminPage();
@@ -74,125 +73,82 @@ export default async function AdminDashboardPage() {
const dateStr = d.toISOString().split('T')[0]; const dateStr = d.toISOString().split('T')[0];
const record = dailyDownloads.find(r => r.date === dateStr); const record = dailyDownloads.find(r => r.date === dateStr);
chartData.push({ chartData.push({
date: dateStr, label: d.toLocaleDateString("de-DE", { day: "numeric" }), // ponytail: day only; 30 "dd. MMM" labels overlap
downloads: record ? record.downloads : 0, value: record ? record.downloads : 0,
}); });
} }
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
return ( return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<PageHeader <PageHeader
title="Admin Dashboard" title="Admin Dashboard"
description="Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals." description="Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals."
/> >
<Button asChild>
<Link href="/admin/redaktionen">Redaktionen verwalten</Link>
</Button>
</PageHeader>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6"> <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<Card> <StatCard
<CardHeader className="pb-2"> title="Umsatz diesen Monat"
<CardTitle className="text-sm font-medium uppercase tracking-wide text-muted-foreground">Umsatz diesen Monat</CardTitle> value={formatter.format((revenueStats?.totalCents ?? 0) / 100)}
</CardHeader> description={`${revenueStats?.count ?? 0} lizenzierte Bilder im ${now.toLocaleString("de-DE", { month: "long" })}`}
<CardContent> />
<div className="text-4xl font-bold text-primary-600 dark:text-primary-500">
{formatter.format((revenueStats?.totalCents ?? 0) / 100)}
</div>
<p className="text-sm text-muted-foreground mt-1">
{revenueStats?.count ?? 0} lizenzierte Bilder im {now.toLocaleString("de-DE", { month: "long" })}
</p>
</CardContent>
</Card>
<Card className="flex flex-col justify-center items-center bg-primary-50/50 dark:bg-primary-900/10 border-primary-100 dark:border-primary-900/30">
<CardContent className="pt-6">
<Button asChild size="lg" className="w-full">
<Link href="/admin/redaktionen">
Redaktionen verwalten
</Link>
</Button>
</CardContent>
</Card>
</div> </div>
<Card> <Card title="Downloads der letzten 30 Tage" description="Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.">
<CardHeader> {chartData.every((day) => day.value === 0) ? (
<CardTitle>Downloads der letzten 30 Tage</CardTitle> <EmptyState title="Keine Downloads" description="In den letzten 30 Tagen wurden keine Bilder geladen." />
<CardDescription>Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.</CardDescription> ) : (
</CardHeader> <BarChart data={chartData} seriesLabels={["Downloads"]} size="lg" />
<CardContent> )}
<DownloadsChart data={chartData} />
</CardContent>
</Card> </Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<Card> <Card title="Aktivste Redaktionen" description="Die Top 5 Redaktionen nach Downloads.">
<CardHeader> {topEditorials.length === 0 ? (
<CardTitle>Aktivste Redaktionen</CardTitle> <EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
<CardDescription>Die Top 5 Redaktionen nach Downloads.</CardDescription> ) : (
</CardHeader> <DataTable
<CardContent> columns={[
{topEditorials.length === 0 ? ( { key: "name", header: "Redaktion" },
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p> { key: "downloads", header: "Downloads", align: "right" },
) : ( { key: "revenue", header: "Umsatz", align: "right" },
<div className="overflow-hidden rounded-md border border-border"> ]}
<table className="w-full text-left text-sm"> rows={topEditorials.map((ed) => ({
<thead className="bg-muted/50 border-b border-border"> id: ed.editorialId,
<tr> name: (
<th className="py-3 px-4 font-semibold">Redaktion</th> <Link href={`/admin/redaktionen/${ed.editorialId}`} className="font-medium text-[var(--color-brand-fg)] hover:underline">
<th className="py-3 px-4 font-semibold text-right">Downloads</th> {ed.name}
<th className="py-3 px-4 font-semibold text-right">Umsatz</th> </Link>
</tr> ),
</thead> downloads: <span className="tabular-nums">{ed.downloadCount}</span>,
<tbody> revenue: <span className="tabular-nums">{formatter.format(ed.revenueCents / 100)}</span>,
{topEditorials.map((ed, i) => ( }))}
<tr key={ed.editorialId} className={i !== topEditorials.length - 1 ? "border-b border-border" : ""}> />
<td className="py-3 px-4"> )}
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="text-primary-600 dark:text-primary-400 hover:underline font-medium">
{ed.name}
</Link>
</td>
<td className="py-3 px-4 text-right tabular-nums">{ed.downloadCount}</td>
<td className="py-3 px-4 text-right tabular-nums">{formatter.format(ed.revenueCents / 100)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card> </Card>
<Card> <Card title="Beliebteste Alben" description="Die Top 5 Alben nach Nutzung.">
<CardHeader> {topAlbums.length === 0 ? (
<CardTitle>Beliebteste Alben</CardTitle> <EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
<CardDescription>Die Top 5 Alben nach Nutzung.</CardDescription> ) : (
</CardHeader> <DataTable
<CardContent> columns={[
{topAlbums.length === 0 ? ( { key: "albumName", header: "Album" },
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p> { key: "downloads", header: "Downloads", align: "right" },
) : ( ]}
<div className="overflow-hidden rounded-md border border-border"> rows={topAlbums.map((album) => ({
<table className="w-full text-left text-sm"> albumName: album.albumName,
<thead className="bg-muted/50 border-b border-border"> downloads: <span className="tabular-nums">{album.downloadCount}</span>,
<tr> }))}
<th className="py-3 px-4 font-semibold">Album</th> />
<th className="py-3 px-4 font-semibold text-right">Downloads</th> )}
</tr>
</thead>
<tbody>
{topAlbums.map((album, i) => (
<tr key={album.albumName} className={i !== topAlbums.length - 1 ? "border-b border-border" : ""}>
<td className="py-3 px-4 font-medium">{album.albumName}</td>
<td className="py-3 px-4 text-right tabular-nums">{album.downloadCount}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card> </Card>
</div> </div>
</div> </section>
); );
} }
@@ -3,6 +3,10 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { useState, useTransition } from "react"; import { useState, useTransition } from "react";
import { Badge, Button, EmptyState, Input } from "@sakaniui/react";
import { IconMail, IconSearch } from "@sakaniui/react/icons";
import { Card } from "@/components/ui/sakani";
import type { AlbumActionResult } from "./actions"; import type { AlbumActionResult } from "./actions";
@@ -49,75 +53,69 @@ function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction
}); });
}; };
const notifyLabel =
notifyStatus === "pending" ? "Wird gesendet …" :
notifyStatus === "success" ? "E-Mail gesendet!" :
notifyStatus === "error" ? "Fehler beim Senden" :
"Redaktion benachrichtigen";
return ( return (
<li className={`flex flex-col bg-white border ${album.isGranted ? 'border-green-500 shadow-md ring-1 ring-green-500' : 'border-gray-200'} rounded-xl overflow-hidden transition-all duration-300 hover:shadow-lg`} data-granted={album.isGranted}> <li data-granted={album.isGranted}>
<div className="relative aspect-[3/2] bg-gray-100 overflow-hidden"> <Card className={`h-full ${album.isGranted ? "outline-2 outline-[var(--color-success-solid)]" : ""}`}>
{album.albumThumbnailAssetId ? ( <div className="relative aspect-[3/2] overflow-hidden rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)]">
<img {album.albumThumbnailAssetId ? (
className="w-full h-full object-contain transition-transform duration-500 hover:scale-105" <img
alt={`Titelbild von ${album.albumName}`} className="h-full w-full object-contain"
loading="lazy" alt={`Titelbild von ${album.albumName}`}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`} loading="lazy"
/> src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
) : ( />
<div aria-label="Kein Albumcover verfügbar" className="w-full h-full flex items-center justify-center text-gray-400 text-xs uppercase tracking-widest" role="img"> ) : (
Kein Cover <div aria-label="Kein Albumcover verfügbar" className="grid h-full w-full place-items-center text-xs text-[var(--color-fg-muted)]" role="img">
</div> Kein Cover
)} </div>
{album.isGranted && ( )}
<div className="absolute top-2 right-2 bg-green-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-sm">
Zugewiesen
</div>
)}
</div>
<div className="p-4 flex flex-col flex-grow">
<h2 className="text-base font-bold text-gray-900 mb-1 truncate" id={`album-${album.id}`} title={album.albumName}>
{album.albumName}
</h2>
<p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p>
<div className="mt-auto space-y-2">
<form action={handleAction}>
<input name="immichAlbumId" type="hidden" value={album.id} />
<button
type="submit"
className={`w-full py-2 px-4 rounded-lg font-semibold text-sm transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-1 ${
album.isGranted
? "bg-red-50 text-red-600 hover:bg-red-100 focus:ring-red-500 border border-red-200"
: "bg-gray-900 text-white hover:bg-gray-800 focus:ring-gray-900"
}`}
disabled={isPending}
>
{isPending ? "Wird verarbeitet..." : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
</form>
{album.isGranted && ( {album.isGranted && (
<form action={(formData) => { <Badge className="absolute top-2 right-2" emphasis="solid" variant="success">Zugewiesen</Badge>
setNotifyStatus("pending"); )}
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => { </div>
setNotifyStatus(res.ok ? "success" : "error"); <div className="flex flex-col gap-1">
setTimeout(() => setNotifyStatus("idle"), 3000); <h2 className="truncate text-base font-semibold" id={`album-${album.id}`} title={album.albumName}>
}); {album.albumName}
}}> </h2>
<p className="text-sm text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
</div>
<div className="mt-auto flex flex-col gap-2">
<form action={handleAction} className="flex flex-col">
<input name="immichAlbumId" type="hidden" value={album.id} />
<Button disabled={isPending} type="submit" variant={album.isGranted ? "outline" : "primary"}>
{isPending ? "Wird verarbeitet …" : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</Button>
</form>
{album.isGranted && (
<form
className="flex flex-col"
action={(formData) => {
setNotifyStatus("pending");
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
setNotifyStatus(res.ok ? "success" : "error");
setTimeout(() => setNotifyStatus("idle"), 3000);
});
}}
>
<input name="albumName" type="hidden" value={album.albumName} /> <input name="albumName" type="hidden" value={album.albumName} />
<button <Button
type="submit"
className={`w-full py-2 px-4 rounded-lg font-semibold text-sm transition-colors duration-200 border ${
notifyStatus === "success" ? "bg-green-50 text-green-700 border-green-200" :
notifyStatus === "error" ? "bg-red-50 text-red-700 border-red-200" :
"bg-white text-gray-700 hover:bg-gray-50 border-gray-200 focus:ring-2 focus:ring-gray-200 focus:outline-none"
}`}
disabled={notifyStatus === "pending" || notifyStatus === "success"} disabled={notifyStatus === "pending" || notifyStatus === "success"}
leftIcon={<IconMail size={16} />}
type="submit"
variant={notifyStatus === "error" ? "destructive" : "ghost"}
> >
{notifyStatus === "pending" ? "Wird gesendet..." : {notifyLabel}
notifyStatus === "success" ? "E-Mail gesendet!" : </Button>
notifyStatus === "error" ? "Fehler beim Senden" :
"Redaktion benachrichtigen"}
</button>
</form> </form>
)} )}
</div> </div>
</div> </Card>
</li> </li>
); );
} }
@@ -130,20 +128,22 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction, noti
); );
return ( return (
<div> <div className="flex flex-col gap-6">
<input <div className="max-w-md">
type="search" <Input
className="album-grid-search" aria-label="Alben durchsuchen"
placeholder="Alben suchen..." leadingIcon={<IconSearch size={16} />}
value={search} onChange={(e) => setSearch(e.target.value)}
onChange={(e) => setSearch(e.target.value)} placeholder="Alben suchen …"
aria-label="Alben durchsuchen" type="search"
/> value={search}
/>
</div>
{filteredAlbums.length === 0 ? ( {filteredAlbums.length === 0 ? (
<p>Keine Alben gefunden.</p> <EmptyState type="no-results" title="Keine Alben gefunden." description="Versuchen Sie einen anderen Suchbegriff." />
) : ( ) : (
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6" aria-label="Zuweisbare Immich-Alben"> <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4" aria-label="Zuweisbare Immich-Alben">
{filteredAlbums.map((album) => ( {filteredAlbums.map((album) => (
<AlbumCard <AlbumCard
key={album.id} key={album.id}
+31 -29
View File
@@ -1,8 +1,10 @@
import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { Alert, EmptyState } from "@/components/ui/sakani";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema"; import { editorialAccounts } from "@/db/schema";
import { albumGrantService } from "@/modules/albums/grants"; import { albumGrantService } from "@/modules/albums/grants";
@@ -26,40 +28,40 @@ export default async function EditorialAlbumsPage({
const albumResult = await loadAssignableAlbums(editorial.id, albumGrantService); const albumResult = await loadAssignableAlbums(editorial.id, albumGrantService);
const header = (
<PageHeader
kicker="Redaktion · Albumrechte"
title={`Alben für ${editorial.name}`}
description="Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen."
>
<div className="flex flex-wrap gap-3">
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
</Button>
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln verwalten</Link>
</Button>
</div>
</PageHeader>
);
if (albumResult.unavailable) { if (albumResult.unavailable) {
return ( return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<div> {header}
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p> <Alert
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1> color="warning"
</div> description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status"> />
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert. </section>
</div>
<div className="flex gap-4">
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
</div>
</div>
); );
} }
return ( return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<div> {header}
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p>
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1>
<p className="text-muted-foreground mt-2">
Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen.
</p>
<div className="flex gap-4 mt-4 text-sm font-medium">
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
<span className="text-muted-foreground">·</span>
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`} className="text-primary-600 hover:underline">Auto-Zuweisungsregeln verwalten</Link>
</div>
</div>
{albumResult.albums.length === 0 ? ( {albumResult.albums.length === 0 ? (
<p className="text-muted-foreground">Derzeit sind keine zuweisbaren Alben vorhanden.</p> <EmptyState title="Keine zuweisbaren Alben" description="Derzeit sind keine zuweisbaren Alben vorhanden." />
) : ( ) : (
<AlbumGrid <AlbumGrid
albums={albumResult.albums} albums={albumResult.albums}
@@ -69,6 +71,6 @@ export default async function EditorialAlbumsPage({
notifyAction={sendAlbumNotificationAction} notifyAction={sendAlbumNotificationAction}
/> />
)} )}
</div> </section>
); );
} }
@@ -1,5 +1,5 @@
import Link from "next/link"; import Link from "next/link";
import { Plus, Play, Trash2, ArrowLeft } from "lucide-react"; import { IconPlayerPlay, IconPlus, IconTrash } from "@sakaniui/react/icons";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { autoRuleService } from "@/modules/albums/auto-rules"; import { autoRuleService } from "@/modules/albums/auto-rules";
@@ -8,7 +8,7 @@ import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { EmptyState, Input } from "@/components/ui/sakani";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
@@ -35,21 +35,12 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
const rules = await autoRuleService.listRules(id); const rules = await autoRuleService.listRules(id);
return ( return (
<div className="space-y-8 max-w-4xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex max-w-4xl flex-col gap-6">
<PageHeader <PageHeader kicker="Redaktion · Auto-Zuweisungsregeln" title={`Auto-Regeln für ${editorial.name}`}>
kicker="Redaktion · Auto-Zuweisungsregeln" <Button asChild variant="outline">
title={`Auto-Regeln für ${editorial.name}`} <Link href={`/admin/redaktionen/${editorial.id}/alben`}>Zurück zur Album-Verwaltung</Link>
/> </Button>
</PageHeader>
<div className="flex gap-4 mb-6">
<Link
href={`/admin/redaktionen/${editorial.id}/alben`}
className="inline-flex items-center text-sm font-medium text-primary-600 hover:underline"
>
<ArrowLeft className="w-4 h-4 mr-1" />
Zurück zur Album-Verwaltung
</Link>
</div>
<div className="grid gap-6"> <div className="grid gap-6">
<Card> <Card>
@@ -60,21 +51,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex gap-4 items-end"> <form action={createAutoRuleAction.bind(null, editorial.id)} className="flex flex-col gap-4 sm:flex-row sm:items-end">
<div className="grid gap-2 flex-grow"> <div className="w-full max-w-md">
<label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"> <Input label="Schlüsselwort" name="keyword" placeholder="z.B. FC Bayern" required type="text" />
Schlüsselwort
</label>
<Input
name="keyword"
type="text"
required
placeholder="z.B. FC Bayern"
className="max-w-md"
/>
</div> </div>
<Button type="submit"> <Button type="submit" leftIcon={<IconPlus size={16} />}>
<Plus className="w-4 h-4 mr-2" />
Regel hinzufügen Regel hinzufügen
</Button> </Button>
</form> </form>
@@ -83,7 +64,7 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
<Card> <Card>
<CardHeader> <CardHeader>
<div className="flex items-start justify-between"> <div className="flex flex-wrap items-start justify-between gap-4">
<div> <div>
<CardTitle>Bestehende Regeln</CardTitle> <CardTitle>Bestehende Regeln</CardTitle>
<CardDescription> <CardDescription>
@@ -91,8 +72,7 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardDescription> </CardDescription>
</div> </div>
<form action={applyAutoRulesAction.bind(null, editorial.id)}> <form action={applyAutoRulesAction.bind(null, editorial.id)}>
<Button type="submit" variant="secondary"> <Button type="submit" variant="secondary" leftIcon={<IconPlayerPlay size={16} />}>
<Play className="w-4 h-4 mr-2" />
Regeln jetzt anwenden Regeln jetzt anwenden
</Button> </Button>
</form> </form>
@@ -100,20 +80,19 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{rules.length === 0 ? ( {rules.length === 0 ? (
<p className="text-muted-foreground text-sm">Noch keine Auto-Regeln angelegt.</p> <EmptyState title="Noch keine Auto-Regeln angelegt." description="Legen Sie oben ein Schlüsselwort an." />
) : ( ) : (
<ul className="divide-y divide-border border rounded-md"> <ul className="divide-y divide-[var(--color-border-subtle)] rounded-[var(--radius-md)] border border-[var(--color-border-subtle)]">
{rules.map((rule) => ( {rules.map((rule) => (
<li key={rule.id} className="flex items-center justify-between p-4"> <li key={rule.id} className="flex items-center justify-between p-4">
<div className="flex flex-col"> <div className="flex flex-col">
<span className="font-medium">{rule.keyword}</span> <span className="font-medium">{rule.keyword}</span>
<span className="text-xs text-muted-foreground mt-1"> <span className="mt-1 text-xs text-[var(--color-fg-muted)]">
Erstellt am {new Date(rule.createdAt).toLocaleDateString('de-DE')} Erstellt am {new Date(rule.createdAt).toLocaleDateString('de-DE')}
</span> </span>
</div> </div>
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}> <form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
<Button type="submit" variant="ghost" size="sm" className="text-destructive hover:bg-destructive/10 hover:text-destructive"> <Button type="submit" variant="ghost" size="sm" leftIcon={<IconTrash size={16} />}>
<Trash2 className="w-4 h-4 mr-2" />
Entfernen Entfernen
</Button> </Button>
</form> </form>
@@ -124,6 +103,6 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
</div> </section>
); );
} }
+58 -62
View File
@@ -3,7 +3,8 @@ import Link from "next/link";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { editorialAccounts, usages } from "@/db/schema"; import { editorialAccounts, usages } from "@/db/schema";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent } from "@/components/ui/card"; import { IconChevronRight } from "@sakaniui/react/icons";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
export default async function EditorialsPage() { export default async function EditorialsPage() {
const [editorials, openUsageTotals] = await Promise.all([ const [editorials, openUsageTotals] = await Promise.all([
@@ -40,7 +41,7 @@ export default async function EditorialsPage() {
const archivedEditorials = editorials.filter((e) => e.archivedAt); const archivedEditorials = editorials.filter((e) => e.archivedAt);
return ( return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500 max-w-7xl"> <section className="flex flex-col gap-6">
<PageHeader <PageHeader
kicker="Kontoverwaltung" kicker="Kontoverwaltung"
title="Redaktionen" title="Redaktionen"
@@ -48,89 +49,84 @@ export default async function EditorialsPage() {
/> />
{activeEditorials.length === 0 ? ( {activeEditorials.length === 0 ? (
<p className="text-muted-foreground">Noch keine aktiven Redaktionen registriert.</p> <EmptyState title="Noch keine aktiven Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
) : ( ) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{activeEditorials.map((editorial) => ( {activeEditorials.map((editorial) => {
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group"> const openCents = openCentsByEditorial.get(editorial.id) ?? 0;
<Card className="h-full transition-all duration-300 hover:shadow-md hover:border-primary-500/50 hover:-translate-y-1"> return (
<CardContent className="p-6 flex flex-col h-full justify-between"> <li key={editorial.id}>
<div> <Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
<h3 className="text-xl font-semibold mb-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors"> <Card interactive className="h-full">
{editorial.name} <div className="flex items-start justify-between gap-3">
</h3> <h2 className="text-base font-semibold text-[var(--color-fg-default)]">{editorial.name}</h2>
<div className="space-y-1 text-sm text-muted-foreground"> <Badge variant={STATUS[editorial.status]?.variant ?? "danger"}>
<p className="flex items-center gap-2"> {STATUS[editorial.status]?.label ?? "Gesperrt"}
<span className="font-medium text-foreground">Kontakt:</span> {editorial.contactName} </Badge>
</p>
<p className="flex items-center gap-2">
<span className="font-medium text-foreground">E-Mail:</span> {editorial.loginEmail}
</p>
<p className="flex items-center gap-2">
<span className="font-medium text-foreground">Status:</span>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
editorial.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" :
editorial.status === "pending_approval" ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" :
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
}`}>
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
</span>
</p>
</div> </div>
</div> <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm">
<div className="mt-6 pt-4 border-t border-border"> <dt className="text-[var(--color-fg-muted)]">Kontakt</dt>
<p className="text-sm font-medium"> <dd className="truncate">{editorial.contactName}</dd>
<dt className="text-[var(--color-fg-muted)]">E-Mail</dt>
<dd className="truncate">{editorial.loginEmail}</dd>
</dl>
<p className="mt-auto border-t border-[var(--color-border-subtle)] pt-3 text-sm font-medium">
{editorial.currentPriceCents === null {editorial.currentPriceCents === null
? "Preis noch nicht festgelegt" ? "Preis noch nicht festgelegt"
: `Netto ${formatCents(editorial.currentPriceCents)}`} : `Netto ${formatCents(editorial.currentPriceCents)}`}
<span <span
className={`ml-2 ${(openCentsByEditorial.get(editorial.id) ?? 0) > 0 ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground"}`} className={`ml-2 ${openCents > 0 ? "text-[var(--color-warning-fg)]" : "text-[var(--color-fg-muted)]"}`}
title="Summe der noch nicht abgerechneten Bildnutzungen" title="Summe der noch nicht abgerechneten Bildnutzungen"
> >
· Offen {formatCents(openCentsByEditorial.get(editorial.id) ?? 0)} · Offen {formatCents(openCents)}
</span> </span>
</p> </p>
</div> </Card>
</CardContent> </Link>
</Card> </li>
</Link> );
))} })}
</div> </ul>
)} )}
{archivedEditorials.length > 0 && ( {archivedEditorials.length > 0 && (
<details className="mt-12 group"> <details className="group mt-6">
<summary className="cursor-pointer flex items-center gap-2 text-sm font-semibold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-colors mb-6 list-none"> <summary className="mb-4 flex cursor-pointer list-none items-center gap-2 text-sm font-medium text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]">
<span className="bg-muted p-1 rounded-sm group-open:rotate-90 transition-transform"> <IconChevronRight size={16} aria-hidden="true" className="transition-transform group-open:rotate-90" />
▶
</span>
Archivierte Redaktionen ({archivedEditorials.length}) Archivierte Redaktionen ({archivedEditorials.length})
</summary> </summary>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 opacity-75 grayscale hover:grayscale-0 transition-all duration-500"> <ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{archivedEditorials.map((editorial) => ( {archivedEditorials.map((editorial) => (
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group"> <li key={editorial.id}>
<Card className="h-full transition-all duration-300 hover:shadow-sm"> <Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
<CardContent className="p-6"> <Card interactive className="h-full opacity-80">
<h3 className="text-lg font-semibold mb-2 text-muted-foreground group-hover:text-foreground transition-colors"> <div className="flex items-start justify-between gap-3">
{editorial.name} <h2 className="text-base font-semibold text-[var(--color-fg-muted)]">{editorial.name}</h2>
</h3> <Badge>Archiviert</Badge>
<div className="space-y-1 text-sm text-muted-foreground">
<p>{editorial.contactName} · {editorial.loginEmail}</p>
<p className="pt-2">
Archiviert am: {editorial.archivedAt ? new Date(editorial.archivedAt).toLocaleDateString("de-DE") : ""}
</p>
</div> </div>
</CardContent> <p className="text-sm text-[var(--color-fg-muted)]">{editorial.contactName} · {editorial.loginEmail}</p>
</Card> <p className="text-sm text-[var(--color-fg-muted)]">
</Link> Archiviert am: {editorial.archivedAt ? new Date(editorial.archivedAt).toLocaleDateString("de-DE") : ""}
</p>
</Card>
</Link>
</li>
))} ))}
</div> </ul>
</details> </details>
)} )}
</div> </section>
); );
} }
const CARD_LINK =
"block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]";
const STATUS: Record<string, { label: string; variant: "success" | "warning" | "danger" }> = {
active: { label: "Aktiv", variant: "success" },
pending_approval: { label: "Ausstehend", variant: "warning" },
};
function formatCents(cents: number): string { function formatCents(cents: number): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100); return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
} }
+16 -22
View File
@@ -2,6 +2,7 @@
import Link from "next/link"; import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
type PortalErrorProps = { type PortalErrorProps = {
@@ -11,27 +12,20 @@ type PortalErrorProps = {
export default function PortalError({ reset }: Readonly<PortalErrorProps>) { export default function PortalError({ reset }: Readonly<PortalErrorProps>) {
return ( return (
<main className="public-account-page"> <PublicShell
<header className="masthead"> kicker="Verbindung unterbrochen"
<span className="wordmark">Leon Tonhäuser</span> title="Diese Seite konnte nicht geladen werden."
<span className="section-label">Redaktionsportal</span> titleId="error-title"
</header> lede="Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an."
>
<section className="account-panel" aria-labelledby="error-title"> <div className="flex flex-wrap gap-3">
<p className="eyebrow">Verbindung unterbrochen</p> <Button size="lg" type="button" onClick={reset}>
<h1 id="error-title">Diese Seite konnte nicht geladen werden.</h1> Erneut versuchen
<p className="lede"> </Button>
Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an. <Button asChild variant="outline">
</p> <Link href="/anmelden">Zur Anmeldung</Link>
<div className="mt-8 flex flex-wrap gap-3"> </Button>
<Button className="min-h-11" size="lg" type="button" onClick={reset}> </div>
Erneut versuchen </PublicShell>
</Button>
<Button asChild className="min-h-11" size="lg" variant="outline">
<Link href="/anmelden">Zur Anmeldung</Link>
</Button>
</div>
</section>
</main>
); );
} }
+89 -1912
View File
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -1,13 +1,15 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
// Sakani first: its unlayered :root tokens (--font-sans, --color-primary-*,
// --radius-*, --shadow-*) override Tailwind's layered @theme values app-wide.
import "@fontsource-variable/geist";
import "@sakaniui/react/tokens.css";
import "@sakaniui/react/style.css";
import "./globals.css"; import "./globals.css";
import { LegalFooter } from "@/components/layout/legal-footer"; import { LegalFooter } from "@/components/layout/legal-footer";
import { ThemeProvider } from "@/components/theme-provider"; import { ThemeProvider } from "@/components/theme-provider";
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Redaktionsportal | Leon Tonhäuser", title: "Redaktionsportal | Leon Tonhäuser",
@@ -21,7 +23,7 @@ export const dynamic = "force-dynamic";
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) { export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
return ( return (
<html lang="de" suppressHydrationWarning> <html lang="de" suppressHydrationWarning>
<body className={`${inter.variable} font-sans antialiased bg-background text-foreground transition-colors duration-300 min-h-screen flex flex-col`}> <body className={`font-sans antialiased bg-background text-foreground transition-colors duration-300 min-h-screen flex flex-col`}>
<ThemeProvider <ThemeProvider
attribute="class" attribute="class"
defaultTheme="system" defaultTheme="system"
+16 -22
View File
@@ -1,6 +1,10 @@
import { headers } from "next/headers"; import { headers } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { Button } from "@/components/ui/button";
import { auth } from "@/modules/auth/auth"; import { auth } from "@/modules/auth/auth";
// ponytail: redirect authenticated users straight to their portal home instead // ponytail: redirect authenticated users straight to their portal home instead
@@ -17,27 +21,17 @@ export default async function HomePage() {
} }
return ( return (
<main className="landing"> <PublicShell
<header className="masthead"> kicker="Pressefotografie"
<span className="wordmark">Leon Tonhäuser</span> title="Bilder für Ihre Redaktion."
<span className="section-label">Redaktionsportal</span> titleId="intro-title"
</header> lede="Freigegebene Fotoalben durchsuchen, Nutzungen dokumentieren und Originaldateien herunterladen."
>
<section className="intro" aria-labelledby="intro-title"> <div>
<p className="eyebrow">Pressefotografie</p> <Button asChild>
<h1 id="intro-title">Bilder für Ihre Redaktion.</h1> <Link href="/anmelden">Zum Portal</Link>
<p className="lede"> </Button>
Freigegebene Fotoalben durchsuchen, Nutzungen dokumentieren und </div>
Originaldateien herunterladen. </PublicShell>
</p>
<a className="primary-action" href="/anmelden">
Zum Portal
</a>
</section>
<footer className="landing-footer">
<p>Der geschützte Zugang wird im nächsten Schritt eingerichtet.</p>
</footer>
</main>
); );
} }
+66 -97
View File
@@ -3,8 +3,9 @@ import { db } from "@/db/client";
import { billingReports, usages, editorialAccounts } from "@/db/schema"; import { billingReports, usages, editorialAccounts } from "@/db/schema";
import Link from "next/link"; import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format"; import { formatBerlinDateTime } from "@/modules/downloads/format";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; import { IconFileTypePdf } from "@sakaniui/react/icons";
import { FileText } from "lucide-react"; import { PageHeader } from "@/components/ui/page-header";
import { Card, EmptyState, Progress, StatCard, DataTable } from "@/components/ui/sakani";
import { requireEditorial } from "../access"; import { requireEditorial } from "../access";
@@ -81,107 +82,75 @@ export default async function AbrechnungenPage() {
// (Optional: Wenn man hier die Flatrate als "offen" anzeigen will) // (Optional: Wenn man hier die Flatrate als "offen" anzeigen will)
const openTotalCents = (openUsages?.totalCents ?? 0); const openTotalCents = (openUsages?.totalCents ?? 0);
return ( const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> const month = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" });
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Finanzen</p> return (
<h1 className="text-4xl font-bold tracking-tight">Meine Abrechnungen</h1> <section className="flex flex-col gap-8" aria-labelledby="billing-title">
</div> <PageHeader kicker="Finanzen" title="Meine Abrechnungen" titleId="billing-title" />
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<StatCard
title="Offener Betrag (Einzelabrufe)"
value={euro.format(openTotalCents / 100)}
description={`Für ${openUsages?.count ?? 0} kostenpflichtige Bilder (noch nicht in Rechnung gestellt)`}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 my-8">
<Card className="bg-primary-50/50 dark:bg-primary-900/10 border-primary-100 dark:border-primary-900/30">
<CardHeader className="pb-2">
<CardTitle className="text-primary-900 dark:text-primary-100">Offener Betrag (Einzelabrufe)</CardTitle>
</CardHeader>
<CardContent>
<p className="text-4xl font-bold text-primary-700 dark:text-primary-400">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(openTotalCents / 100)}
</p>
<p className="text-sm text-primary-600/80 dark:text-primary-300/80 mt-2">
Für {openUsages?.count ?? 0} kostenpflichtige Bilder (noch nicht in Rechnung gestellt)
</p>
</CardContent>
</Card>
{editorial?.flatrateActive && editorial.flatratePriceCents !== null && ( {editorial?.flatrateActive && editorial.flatratePriceCents !== null && (
<Card className="bg-emerald-50/50 dark:bg-emerald-900/10 border-emerald-100 dark:border-emerald-900/30"> <Card title="Aktiver Tarif: Flatrate">
<CardHeader className="pb-2"> <p className="text-3xl font-semibold tabular-nums text-[var(--color-fg-default)]">
<CardTitle className="text-emerald-900 dark:text-emerald-100">Aktiver Tarif: Flatrate</CardTitle> {euro.format(editorial.flatratePriceCents / 100)}{" "}
</CardHeader> <span className="text-base font-normal text-[var(--color-fg-muted)]">/ Monat</span>
<CardContent> </p>
<p className="text-4xl font-bold text-emerald-700 dark:text-emerald-400 flex items-baseline gap-2"> {editorial.flatrateAssetLimit === null ? (
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(editorial.flatratePriceCents / 100)} <p className="text-sm font-medium text-[var(--color-fg-muted)]">Unbegrenzte Downloads inklusive</p>
<span className="text-lg font-normal text-emerald-600/70 dark:text-emerald-400/70">/ Monat</span> ) : (
</p> <div className="flex flex-col gap-2">
{editorial.flatrateAssetLimit === null ? ( <div className="flex justify-between text-sm font-medium text-[var(--color-fg-muted)]">
<p className="text-sm text-emerald-700/80 dark:text-emerald-300/80 mt-2 font-medium"> <span>Inklusiv-Bilder diesen Monat</span>
Unbegrenzte Downloads inklusive <span className="tabular-nums">{usedFlatrateImages} / {editorial.flatrateAssetLimit}</span>
</p>
) : (
<div className="mt-4">
<div className="flex justify-between text-sm text-emerald-700 dark:text-emerald-300 font-medium mb-1.5">
<span>Inklusiv-Bilder diesen Monat</span>
<span>{usedFlatrateImages} / {editorial.flatrateAssetLimit}</span>
</div>
<div className="w-full bg-emerald-200/50 dark:bg-emerald-800/50 rounded-full h-2.5 overflow-hidden">
<div className="bg-emerald-500 dark:bg-emerald-400 h-full rounded-full transition-all duration-500" style={{ width: `${Math.min(100, (usedFlatrateImages / editorial.flatrateAssetLimit) * 100)}%` }} />
</div>
</div> </div>
)} <Progress
</CardContent> label="Verbrauchte Inklusiv-Bilder"
value={Math.min(100, (usedFlatrateImages / editorial.flatrateAssetLimit) * 100)}
/>
</div>
)}
</Card> </Card>
)} )}
</div> </div>
<div className="pt-4"> <section className="flex flex-col gap-4" aria-labelledby="reports-title">
<h2 className="text-2xl font-bold mb-6">Bisherige Rechnungen</h2> <h2 id="reports-title" className="text-xl font-semibold">Bisherige Rechnungen</h2>
{reports.length === 0 ? (
{reports.length === 0 ? ( <EmptyState title="Noch keine Rechnungen" description="Es liegen noch keine abgerechneten Zeiträume vor." />
<Card> ) : (
<CardContent className="pt-6"> <DataTable
<p className="text-muted-foreground text-center py-8">Es liegen noch keine abgerechneten Zeiträume vor.</p> columns={[
</CardContent> { key: "invoiceNumber", header: "Rechnungsnummer" },
</Card> { key: "period", header: "Zeitraum" },
) : ( { key: "net", header: "Betrag (Netto)", align: "right" },
<Card> { key: "pdf", header: "Download", align: "center" },
<div className="overflow-x-auto"> ]}
<table className="w-full text-left text-sm"> rows={reports.map((report) => ({
<thead className="bg-muted/50 border-b border-border"> id: report.id,
<tr> invoiceNumber: report.invoiceNumber,
<th className="py-3 px-4 font-semibold">Rechnungsnummer</th> period: month.format(new Date(report.periodStartsAt)),
<th className="py-3 px-4 font-semibold">Zeitraum</th> net: <span className="tabular-nums">{euro.format(report.netTotalCents / 100)}</span>,
<th className="py-3 px-4 font-semibold text-right">Betrag (Netto)</th> pdf: (
<th className="py-3 px-4 font-semibold text-center">Download</th> <Link
</tr> className="inline-flex items-center gap-2 font-medium text-[var(--color-brand-fg)] hover:underline"
</thead> href={`/api/editorials/reports/${report.id}/pdf`}
<tbody> target="_blank"
{reports.map((report, i) => ( >
<tr key={report.id} className={i !== reports.length - 1 ? "border-b border-border hover:bg-muted/30 transition-colors" : "hover:bg-muted/30 transition-colors"}> <IconFileTypePdf size={16} aria-hidden="true" />
<td className="py-4 px-4 font-medium">{report.invoiceNumber}</td> <span>PDF</span>
<td className="py-4 px-4 text-muted-foreground"> </Link>
{new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" }).format(new Date(report.periodStartsAt))} ),
</td> }))}
<td className="py-4 px-4 font-medium text-right tabular-nums"> />
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(report.netTotalCents / 100)} )}
</td> </section>
<td className="py-4 px-4 text-center"> </section>
<Link
href={`/api/editorials/reports/${report.id}/pdf`}
target="_blank"
className="inline-flex items-center gap-2 text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300 font-medium transition-colors"
>
<FileText className="w-4 h-4" />
<span>PDF</span>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
)}
</div>
</div>
); );
} }
@@ -1,8 +1,10 @@
import { Spinner } from "@/components/ui/sakani";
export default function AlbumLoading() { export default function AlbumLoading() {
return ( return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite"> <div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p> <Spinner size="sm" label="Fotos werden geladen." />
<p>Fotos werden geladen.</p> <p>Fotos werden geladen.</p>
</section> </div>
); );
} }
+21 -53
View File
@@ -2,14 +2,16 @@ import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog"; import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
import { formatCount, PhotoPagination } from "@/modules/albums/catalog-content"; import { formatCount, PhotoPagination, PhotoSearchForm } from "@/modules/albums/catalog-content";
import { filterPhotos, paginatePhotos } from "@/modules/albums/filter"; import { filterPhotos, paginatePhotos } from "@/modules/albums/filter";
import { PhotoGallery } from "@/modules/albums/photo-gallery"; import { PhotoGallery } from "@/modules/albums/photo-gallery";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream"; import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service"; import { lightboxService } from "@/modules/lightbox/service";
import { requireEditorial } from "../../access"; import { requireEditorial } from "../../access";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Alert } from "@/components/ui/sakani";
// ponytail: fetch the whole album in one request so hoch/quer and jahr filters // ponytail: fetch the whole album in one request so hoch/quer and jahr filters
// can be applied across the full set before paginating, instead of over a // can be applied across the full set before paginating, instead of over a
@@ -48,18 +50,24 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
} }
return ( return (
<section className="editorial-section" aria-labelledby="album-title"> <section aria-labelledby="album-title">
<PageHeader <PageHeader
kicker={`Bildarchiv · ${result.album.assetCount} freigegebene Fotos`} kicker={`Bildarchiv · ${result.album.assetCount} freigegebene Fotos`}
title={result.album.albumName} title={result.album.albumName}
titleId="album-title" titleId="album-title"
> >
<Link className="quiet-link" href="/redaktion/alben"> <Button asChild variant="outline">
Alle Alben <Link href="/redaktion/alben">Alle Alben</Link>
</Link> </Button>
</PageHeader> </PageHeader>
<AlbumSearchForm albumId={result.album.id} query={query} format={format} /> <PhotoSearchForm
<p aria-live="polite" className="result-summary" role="status"> action={`/redaktion/alben/${result.album.id}`}
ariaLabel="Fotos in diesem Album durchsuchen"
query={query}
format={format}
placeholder="Dieses Album durchsuchen …"
/>
<p aria-live="polite" className="my-4 text-sm text-[var(--color-fg-muted)]" role="status">
{formatCount(result.page.total, "Foto")} gefunden {formatCount(result.page.total, "Foto")} gefunden
</p> </p>
<PhotoGallery <PhotoGallery
@@ -81,40 +89,6 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
); );
} }
function AlbumSearchForm({ albumId, query, format }: { albumId: string; query: string; format?: string; }) {
return (
<form
action={`/redaktion/alben/${albumId}`}
className="album-search-form"
role="search"
aria-label={`Fotos in diesem Album durchsuchen`}
>
<div className="album-search-input">
<label className="album-search-label" htmlFor="album-search-suche">Suchbegriff</label>
<input
id="album-search-suche"
type="search"
name="suche"
defaultValue={query}
placeholder="Dieses Album durchsuchen..."
aria-label="Suchbegriff"
/>
</div>
<div className="album-search-filters">
<label className="album-search-select">
<span>Format</span>
<select name="format" defaultValue={format || ""}>
<option value="">Alle Formate</option>
<option value="quer">Querformat</option>
<option value="hoch">Hochformat</option>
</select>
</label>
<button type="submit">Suchen</button>
</div>
</form>
);
}
async function loadAlbumPage({ async function loadAlbumPage({
editorialId, editorialId,
albumId, albumId,
@@ -178,19 +152,13 @@ function normalizedQuery(value: string | undefined): string {
function ImmichUnavailable() { function ImmichUnavailable() {
return ( return (
<section className="editorial-section editorial-state" aria-labelledby="album-title"> <section className="flex flex-col gap-6" aria-labelledby="album-title">
<PageHeader <PageHeader kicker="Bildarchiv" title="Fotos momentan nicht erreichbar" titleId="album-title">
kicker="Bildarchiv" <Button asChild variant="outline">
title="Fotos momentan nicht erreichbar" <Link href="/redaktion/alben">Zurück zu den Alben</Link>
titleId="album-title" </Button>
>
<div className="flex flex-col gap-2 items-end">
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
<Link className="quiet-link" href="/redaktion/alben">
Zurück zu den Alben
</Link>
</div>
</PageHeader> </PageHeader>
<Alert color="warning" description="Bitte laden Sie diese Seite in wenigen Minuten erneut." />
</section> </section>
); );
} }
+5 -3
View File
@@ -1,8 +1,10 @@
import { Spinner } from "@/components/ui/sakani";
export default function AlbumsLoading() { export default function AlbumsLoading() {
return ( return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite"> <div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p> <Spinner size="sm" label="Alben werden geladen." />
<p>Alben werden geladen.</p> <p>Alben werden geladen.</p>
</section> </div>
); );
} }
+23 -74
View File
@@ -1,15 +1,13 @@
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog"; import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
import { AlbumContactSheet, formatCount } from "@/modules/albums/catalog-content"; import { AlbumContactSheet, formatCount, PageLinks, PhotoSearchForm } from "@/modules/albums/catalog-content";
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter"; import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
import { PhotoGallery } from "@/modules/albums/photo-gallery"; import { PhotoGallery } from "@/modules/albums/photo-gallery";
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner"; import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
import { announcementService } from "@/modules/announcements/service"; import { announcementService } from "@/modules/announcements/service";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream"; import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service"; import { lightboxService } from "@/modules/lightbox/service";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Input } from "@/components/ui/input"; import { Alert, EmptyState } from "@/components/ui/sakani";
import { Button } from "@/components/ui/button";
import { requireEditorial } from "../access"; import { requireEditorial } from "../access";
@@ -51,15 +49,11 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId)); const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId));
return ( return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="albums-title"> <section className="flex flex-col gap-6" aria-labelledby="albums-title">
<PageHeader <PageHeader kicker="Bildarchiv · Suche" title="Suchergebnisse" titleId="albums-title" />
kicker="Bildarchiv · Suche"
title="Suchergebnisse"
titleId="albums-title"
/>
<AnnouncementBanner items={hints} /> <AnnouncementBanner items={hints} />
<GlobalSearchForm query={query} format={format} jahr={jahr} /> <PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
<p aria-live="polite" className="result-summary" role="status"> <p aria-live="polite" className="text-sm text-[var(--color-fg-muted)]" role="status">
{formatCount(page.total, "Foto")} gefunden {formatCount(page.total, "Foto")} gefunden
</p> </p>
<PhotoGallery <PhotoGallery
@@ -70,7 +64,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
showAlbumName showAlbumName
/> />
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} /> <GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} />
</div> </section>
); );
} }
@@ -81,7 +75,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
} }
return ( return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="albums-title"> <section className="flex flex-col gap-8" aria-labelledby="albums-title">
<PageHeader <PageHeader
kicker="Bildarchiv · Freigaben" kicker="Bildarchiv · Freigaben"
title="Ihre Alben" title="Ihre Alben"
@@ -89,58 +83,23 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen." description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen."
/> />
<AnnouncementBanner items={hints} /> <AnnouncementBanner items={hints} />
<GlobalSearchForm query={query} format={format} jahr={jahr} /> <PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
{result.albums.length === 0 ? ( {result.albums.length === 0 ? (
<p className="text-muted-foreground text-center py-12">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p> <EmptyState title="Noch keine Alben" description="Für Ihre Redaktion sind noch keine Fotoalben freigegeben." />
) : ( ) : (
<AlbumContactSheet albums={result.albums} /> <AlbumContactSheet albums={result.albums} />
)} )}
</div> </section>
); );
} }
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) { function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
return ( return (
<div className="space-y-6 max-w-7xl" aria-labelledby="albums-title"> <section className="flex flex-col gap-6" aria-labelledby="albums-title">
<PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" /> <PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" />
<GlobalSearchForm query={query} format={format} jahr={jahr} /> <PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
<p className="bg-muted p-4 rounded-md" role="status"> <Alert color="warning" description="Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut." />
Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut. </section>
</p>
</div>
);
}
function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
return (
<form action="/redaktion/alben" className="flex flex-col sm:flex-row gap-4 items-center bg-card p-4 rounded-xl border border-border shadow-sm w-full" role="search">
<div className="flex-grow w-full sm:w-auto">
<Input
type="search"
name="suche"
defaultValue={query}
placeholder="Alle Alben durchsuchen..."
aria-label="Alle Alben durchsuchen"
/>
</div>
<div className="flex gap-3 w-full sm:w-auto">
<select name="format" defaultValue={format || ""} className="flex h-10 w-full items-center justify-between rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50">
<option value="">Alle Formate</option>
<option value="quer">Querformat</option>
<option value="hoch">Hochformat</option>
</select>
<select name="jahr" defaultValue={jahr || ""} className="flex h-10 w-full items-center justify-between rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50">
<option value="">Alle Jahre</option>
{years.map(y => (
<option key={y} value={y.toString()}>{y}</option>
))}
</select>
<Button type="submit" variant="default">Suchen</Button>
</div>
</form>
); );
} }
@@ -152,14 +111,10 @@ function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { cu
} }
return ( return (
<nav aria-label="Suchergebnisseiten" className="flex justify-between items-center mt-8 pt-4 border-t border-border text-sm font-medium"> <PageLinks
{hasPrev ? ( prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr) : null}
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage - 1, query, format, jahr)}>Vorherige Seite</Link> nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr) : null}
) : <div />} />
{hasNext ? (
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage + 1, query, format, jahr)}>Nächste Seite</Link>
) : <div />}
</nav>
); );
} }
@@ -191,15 +146,9 @@ async function loadAlbums(editorialId: string) {
function ImmichUnavailable() { function ImmichUnavailable() {
return ( return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="albums-title"> <section className="flex flex-col gap-6" aria-labelledby="albums-title">
<PageHeader <PageHeader kicker="Bildarchiv" title="Alben momentan nicht erreichbar" titleId="albums-title" />
kicker="Bildarchiv" <Alert color="danger" description="Bitte laden Sie diese Seite in wenigen Minuten erneut. Ihre Freigaben bleiben unverändert." />
title="Alben momentan nicht erreichbar" </section>
titleId="albums-title"
/>
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status">
Bitte laden Sie diese Seite in wenigen Minuten erneut. Ihre Freigaben bleiben unverändert.
</div>
</div>
); );
} }
+6 -11
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { PortalShell } from "@/components/layout/portal-shell"; import { AppShell } from "@/components/layout/app-shell";
import { env } from "@/config/env";
import { requireEditorial } from "./access"; import { requireEditorial } from "./access";
@@ -8,17 +9,11 @@ export default async function EditorialLayout({ children }: Readonly<{ children:
await requireEditorial(); await requireEditorial();
return ( return (
<PortalShell <AppShell
brandHref="/redaktion/alben" area="redaktion"
sectionLabel="Redaktionsarchiv" legal={{ imprint: env.LEGAL_IMPRINT_URL, privacy: env.LEGAL_PRIVACY_URL, terms: env.LEGAL_TERMS_URL }}
nav={[
{ href: "/redaktion/alben", label: "Alben" },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel" },
{ href: "/redaktion/nutzungen", label: "Nutzungen" },
{ href: "/redaktion/profil", label: "Profil" },
]}
> >
{children} {children}
</PortalShell> </AppShell>
); );
} }
@@ -2,11 +2,14 @@
import { useState, useRef } from "react"; import { useState, useRef } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Alert, Button, Input } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons";
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) { export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
const [purpose, setPurpose] = useState(""); const [purpose, setPurpose] = useState("");
const [error, setError] = useState<string | null>(null);
const router = useRouter(); const router = useRouter();
async function handleBulkDownload(e: React.FormEvent) { async function handleBulkDownload(e: React.FormEvent) {
@@ -14,7 +17,8 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
if (!purpose.trim() || assetIds.length === 0) return; if (!purpose.trim() || assetIds.length === 0) return;
setLoading(true); setLoading(true);
setError(null);
try { try {
const response = await fetch("/api/lightbox/bulk-download", { const response = await fetch("/api/lightbox/bulk-download", {
method: "POST", method: "POST",
@@ -53,7 +57,7 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
router.refresh(); // Refresh to update usage history router.refresh(); // Refresh to update usage history
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : "Download fehlgeschlagen"; const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
alert(`Bulk-Download fehlgeschlagen: ${message}`); setError(`Bulk-Download fehlgeschlagen: ${message}`);
console.error(err); console.error(err);
} finally { } finally {
setLoading(false); setLoading(false);
@@ -62,60 +66,41 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
return ( return (
<> <>
<button <Button
type="button"
onClick={() => dialogRef.current?.showModal()}
disabled={assetIds.length === 0} disabled={assetIds.length === 0}
className="primary-action m-0" leftIcon={<IconDownload size={16} />}
onClick={() => dialogRef.current?.showModal()}
type="button"
> >
Alle herunterladen Alle herunterladen
</button> </Button>
<dialog ref={dialogRef} className="rounded-xl p-0 backdrop:bg-black/50 shadow-2xl border border-border bg-card text-card-foreground overflow-hidden max-w-md w-full"> <dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
<div className="p-6"> <form className="flex flex-col gap-4 p-6" onSubmit={handleBulkDownload}>
<h2 className="text-xl font-bold mb-4">Verwendungszweck angeben</h2> <h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</h2>
<p className="text-sm text-muted-foreground mb-6"> <p className="text-sm text-[var(--color-fg-muted)]">
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen. Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
</p> </p>
<Input
<form onSubmit={handleBulkDownload}> disabled={loading}
<div className="space-y-4"> id="purpose"
<div> label="Verwendungszweck"
<label htmlFor="purpose" className="block text-sm font-medium mb-1"> onChange={(e) => setPurpose(e.target.value)}
Verwendungszweck placeholder="z.B. Webseite, Social Media"
</label> required
<input type="text"
id="purpose" value={purpose}
type="text" />
required {error ? <Alert color="danger" description={error} /> : null}
placeholder="z.B. Webseite, Social Media" <div className="mt-4 flex justify-end gap-3">
value={purpose} <Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
onChange={(e) => setPurpose(e.target.value)} Abbrechen
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50" </Button>
disabled={loading} <Button disabled={loading || !purpose.trim()} type="submit">
/> {loading ? "Wird verpackt …" : "Download starten (ZIP)"}
</div> </Button>
</div> </div>
</form>
<div className="mt-8 flex justify-end gap-3">
<button
type="button"
onClick={() => dialogRef.current?.close()}
className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2"
disabled={loading}
>
Abbrechen
</button>
<button
type="submit"
className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2"
disabled={loading || !purpose.trim()}
>
{loading ? "Wird verpackt..." : "Download starten (ZIP)"}
</button>
</div>
</form>
</div>
</dialog> </dialog>
</> </>
); );
@@ -1,6 +1,8 @@
"use client"; "use client";
import { useState, useTransition } from "react"; import { useState, useTransition } from "react";
import { IconButton } from "@sakaniui/react";
import { IconBookmark, IconBookmarkFilled } from "@sakaniui/react/icons";
import { toggleLightboxItem } from "./actions"; import { toggleLightboxItem } from "./actions";
type LightboxToggleButtonProps = { type LightboxToggleButtonProps = {
@@ -34,27 +36,17 @@ export function LightboxToggleButton({ assetId, initialInLightbox }: LightboxTog
}); });
} }
const label = inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel";
return ( return (
<button <IconButton
type="button" aria-label={label}
onClick={handleClick} aria-pressed={inLightbox}
disabled={isPending} disabled={isPending}
className={`lightbox-toggle-btn ${inLightbox ? 'in-lightbox' : ''}`} icon={inLightbox ? IconBookmarkFilled : IconBookmark}
aria-label={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"} onClick={handleClick}
title={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"} size="sm"
> title={label}
<svg variant={inLightbox ? "primary" : "secondary"}
xmlns="http://www.w3.org/2000/svg" />
viewBox="0 0 24 24"
fill={inLightbox ? "currentColor" : "none"}
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-5 h-5"
>
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
</button>
); );
} }
@@ -1,6 +1,8 @@
"use client"; "use client";
import { useTransition } from "react"; import { useTransition } from "react";
import { IconButton } from "@sakaniui/react";
import { IconX } from "@sakaniui/react/icons";
import { removeLightboxItemAction } from "./actions"; import { removeLightboxItemAction } from "./actions";
export function RemoveLightboxItemButton({ assetId }: { assetId: string }) { export function RemoveLightboxItemButton({ assetId }: { assetId: string }) {
@@ -13,26 +15,14 @@ export function RemoveLightboxItemButton({ assetId }: { assetId: string }) {
} }
return ( return (
<button <IconButton
type="button"
onClick={handleRemove}
disabled={isPending}
className="p-1.5 bg-white rounded-full shadow hover:bg-gray-100 text-gray-500 hover:text-red-500 transition-colors"
title="Aus Merkzettel entfernen"
aria-label="Aus Merkzettel entfernen" aria-label="Aus Merkzettel entfernen"
> disabled={isPending}
<svg icon={IconX}
xmlns="http://www.w3.org/2000/svg" onClick={handleRemove}
viewBox="0 0 24 24" size="sm"
fill="none" title="Aus Merkzettel entfernen"
stroke="currentColor" variant="secondary"
strokeWidth="2" />
strokeLinecap="round"
strokeLinejoin="round"
className="w-4 h-4"
>
<path d="M18 6L6 18M6 6l12 12" />
</svg>
</button>
); );
} }
+19 -16
View File
@@ -1,6 +1,7 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Card, EmptyState } from "@/components/ui/sakani";
import { lightboxService } from "@/modules/lightbox/service"; import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client"; import { immichClient } from "@/modules/immich/client";
import Link from "next/link"; import Link from "next/link";
@@ -21,24 +22,26 @@ export default async function LightboxPage() {
const assetMap = new Map(validAssets.map(a => [a.id, a])); const assetMap = new Map(validAssets.map(a => [a.id, a]));
return ( return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex flex-col gap-6">
<PageHeader <PageHeader
kicker="Merkzettel" kicker="Merkzettel"
title="Dein Leuchtkasten" title="Dein Leuchtkasten"
/> />
{items.length === 0 ? ( {items.length === 0 ? (
<p className="text-muted-foreground text-center py-12">Dein Leuchtkasten ist leer.</p> <EmptyState title="Dein Leuchtkasten ist leer" description="Merke dir Fotos in einem Album über das Lesezeichen-Symbol." />
) : ( ) : (
<> <>
<div className="flex justify-between items-center bg-card p-4 rounded-xl border border-border shadow-sm"> <Card>
<p className="text-sm font-medium text-muted-foreground"> <div className="flex flex-wrap items-center justify-between gap-4">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt <p className="text-sm font-medium text-[var(--color-fg-muted)]">
</p> {items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} /> </p>
</div> <DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
</div>
</Card>
<ul className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6"> <ul className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
{items.map((item) => { {items.map((item) => {
const asset = assetMap.get(item.assetId); const asset = assetMap.get(item.assetId);
if (!asset) return null; if (!asset) return null;
@@ -48,9 +51,9 @@ export default async function LightboxPage() {
: '#'; : '#';
return ( return (
<li key={item.assetId} className="relative group rounded-xl overflow-hidden border border-border bg-card shadow-sm transition-all hover:shadow-md hover:-translate-y-1"> <li key={item.assetId} className="group relative overflow-hidden rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] transition-shadow hover:shadow-[var(--shadow-md)]">
<Link href={href} className="block"> <Link href={href} className="block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]">
<div className="aspect-[3/2] w-full overflow-hidden bg-muted"> <div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]">
<img <img
alt={asset.originalFileName ?? "Bild"} alt={asset.originalFileName ?? "Bild"}
className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105" className="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
@@ -58,13 +61,13 @@ export default async function LightboxPage() {
src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`} src={`/api/assets/${encodeURIComponent(item.assetId)}/thumbnail`}
/> />
</div> </div>
<div className="p-3 border-t border-border bg-card"> <div className="border-t border-[var(--color-border-subtle)] p-3">
<span className="block truncate text-xs font-medium text-muted-foreground" title={asset.originalFileName}> <span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={asset.originalFileName}>
{asset.originalFileName ?? "Unbekannt"} {asset.originalFileName ?? "Unbekannt"}
</span> </span>
</div> </div>
</Link> </Link>
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"> <div className="absolute top-2 right-2 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100">
<RemoveLightboxItemButton assetId={item.assetId} /> <RemoveLightboxItemButton assetId={item.assetId} />
</div> </div>
</li> </li>
@@ -73,6 +76,6 @@ export default async function LightboxPage() {
</ul> </ul>
</> </>
)} )}
</div> </section>
); );
} }
+6 -4
View File
@@ -1,5 +1,8 @@
import { listEditorialUsageHistory } from "@/modules/downloads/stream"; import { listEditorialUsageHistory } from "@/modules/downloads/stream";
import { PageHeader } from "@/components/ui/page-header";
import { Alert } from "@/components/ui/sakani";
import { requireEditorial } from "../access"; import { requireEditorial } from "../access";
import { UsageHistoryContent } from "./usage-history-content"; import { UsageHistoryContent } from "./usage-history-content";
@@ -35,10 +38,9 @@ async function loadHistory(
function HistoryUnavailable() { function HistoryUnavailable() {
return ( return (
<section className="editorial-section editorial-state" aria-labelledby="usage-history-title"> <section aria-labelledby="usage-history-title">
<p className="editorial-kicker">Abrechnung</p> <PageHeader kicker="Abrechnung" title="Nutzungen momentan nicht erreichbar" titleId="usage-history-title" />
<h1 id="usage-history-title">Nutzungen momentan nicht erreichbar</h1> <Alert color="warning" description="Bitte laden Sie diese Seite in wenigen Minuten erneut." />
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
</section> </section>
); );
} }
@@ -1,6 +1,9 @@
import Link from "next/link"; import Link from "next/link";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
import { PageLinks } from "@/modules/albums/catalog-content";
import { formatBerlinDateTime } from "@/modules/downloads/format"; import { formatBerlinDateTime } from "@/modules/downloads/format";
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream"; import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
@@ -18,7 +21,7 @@ const byteFormatter = new Intl.NumberFormat("de-DE", {
export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) { export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) {
return ( return (
<section className="editorial-section usage-history" aria-labelledby="usage-history-title"> <section className="usage-history" aria-labelledby="usage-history-title">
<PageHeader <PageHeader
kicker="Abrechnung · Downloadprotokoll" kicker="Abrechnung · Downloadprotokoll"
title="Ihre Nutzungen" title="Ihre Nutzungen"
@@ -27,16 +30,17 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
/> />
{history.items.length === 0 ? ( {history.items.length === 0 ? (
<div className="usage-history-empty"> <div className="flex flex-col items-center gap-4">
<p>Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.</p> <EmptyState title="Noch keine Nutzungen erfasst." description="Wählen Sie ein Foto aus einem freigegebenen Album." />
<Link className="quiet-link" href="/redaktion/alben"> <Button asChild variant="outline">
Zu den Alben <Link href="/redaktion/alben">Zu den Alben</Link>
</Link> </Button>
</div> </div>
) : ( ) : (
<ol className="usage-ledger"> <ol className="usage-ledger">
{history.items.map((usage) => ( {history.items.map((usage) => (
<li key={usage.usageId}> <li key={usage.usageId}>
<Card>
<article className="usage-ledger-entry"> <article className="usage-ledger-entry">
<header> <header>
<p>{formatBerlinDateTime(usage.createdAt)}</p> <p>{formatBerlinDateTime(usage.createdAt)}</p>
@@ -57,7 +61,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
</div> </div>
<div> <div>
<dt>Abrechnungsstatus</dt> <dt>Abrechnungsstatus</dt>
<dd>{billingStatusLabel(usage.billingStatus)}</dd> <dd><Badge variant={BILLING_BADGE[usage.billingStatus]}>{billingStatusLabel(usage.billingStatus)}</Badge></dd>
</div> </div>
{usage.reference ? ( {usage.reference ? (
<div> <div>
@@ -67,6 +71,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
) : null} ) : null}
</dl> </dl>
</article> </article>
</Card>
</li> </li>
))} ))}
</ol> </ol>
@@ -77,7 +82,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
<section className="usage-attempt-history" aria-labelledby="usage-attempt-title"> <section className="usage-attempt-history" aria-labelledby="usage-attempt-title">
<h2 id="usage-attempt-title">Downloadversuche</h2> <h2 id="usage-attempt-title">Downloadversuche</h2>
{history.attempts.length === 0 ? ( {history.attempts.length === 0 ? (
<p className="usage-attempt-empty">Noch keine Downloadversuche erfasst.</p> <p className="usage-attempt-empty text-[var(--color-fg-muted)]">Noch keine Downloadversuche erfasst.</p>
) : ( ) : (
<ol className="usage-attempts" aria-label="Downloadversuche Ihrer Redaktion"> <ol className="usage-attempts" aria-label="Downloadversuche Ihrer Redaktion">
{history.attempts.map((attempt) => ( {history.attempts.map((attempt) => (
@@ -105,7 +110,7 @@ function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
{attempt.reference ? ` · ${attempt.reference}` : ""} {attempt.reference ? ` · ${attempt.reference}` : ""}
</small> </small>
</span> </span>
<strong>{statusLabel(attempt.status)}</strong> <Badge variant={ATTEMPT_BADGE[attempt.status]}>{statusLabel(attempt.status)}</Badge>
<span> <span>
{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "} {attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "}
{byteFormatter.format(attempt.transferredBytes)} {byteFormatter.format(attempt.transferredBytes)}
@@ -119,45 +124,50 @@ function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
} }
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) { function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
if (history.page === 1 && !history.hasNext) return null;
return ( return (
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination"> <PageLinks
{history.page > 1 ? ( ariaLabel="Seiten der Nutzungshistorie"
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}> prevHref={history.page > 1 ? `/redaktion/nutzungen?page=${history.page - 1}` : null}
Vorherige Nutzungsseite prevLabel="Vorherige Nutzungsseite"
</Link> nextHref={history.hasNext ? `/redaktion/nutzungen?page=${history.page + 1}` : null}
) : ( nextLabel="Nächste Nutzungsseite"
<span /> />
)}
{history.hasNext ? (
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>
Nächste Nutzungsseite
</Link>
) : null}
</nav>
); );
} }
function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) { function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
if (!history.attemptCursor && !history.nextAttemptCursor) return null;
return ( return (
<nav aria-label="Seiten der Auslieferungsversuche" className="photo-pagination"> <PageLinks
{history.attemptCursor ? ( ariaLabel="Seiten der Auslieferungsversuche"
<Link href={`/redaktion/nutzungen?page=${history.page}`}>Neueste Auslieferungen</Link> prevHref={history.attemptCursor ? `/redaktion/nutzungen?page=${history.page}` : null}
) : ( prevLabel="Neueste Auslieferungen"
<span /> nextHref={
)} history.nextAttemptCursor
{history.nextAttemptCursor ? ( ? `/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`
<Link : null
href={`/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`} }
> nextLabel="Ältere Auslieferungen"
Ältere Auslieferungen />
</Link>
) : null}
</nav>
); );
} }
type BadgeVariant = "info" | "success" | "warning" | "danger" | "neutral";
const ATTEMPT_BADGE: Record<UsageHistoryAttempt["status"], BadgeVariant> = {
authorized: "info",
streaming: "info",
completed: "success",
interrupted: "warning",
failed_before_delivery: "danger",
};
const BILLING_BADGE: Record<UsageHistoryPage["items"][number]["billingStatus"], BadgeVariant> = {
open: "warning",
billed: "success",
reopened: "warning",
voided: "neutral",
};
function statusLabel(status: UsageHistoryAttempt["status"]): string { function statusLabel(status: UsageHistoryAttempt["status"]): string {
const labels: Record<UsageHistoryAttempt["status"], string> = { const labels: Record<UsageHistoryAttempt["status"], string> = {
authorized: "Autorisiert", authorized: "Autorisiert",
+4 -1
View File
@@ -1,6 +1,7 @@
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { PageHeader } from "@/components/ui/page-header"; import { PageHeader } from "@/components/ui/page-header";
import { Card } from "@/components/ui/sakani";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { billingAddressVersions, editorialAccounts } from "@/db/schema"; import { billingAddressVersions, editorialAccounts } from "@/db/schema";
@@ -35,7 +36,8 @@ export default async function EditorialProfilePage() {
title="Profil" title="Profil"
titleId="profile-title" titleId="profile-title"
/> />
<dl> <Card>
<dl className="!mt-0 !border-t-0 !pt-0">
<dt>Redaktion</dt> <dt>Redaktion</dt>
<dd>{editorial?.name}</dd> <dd>{editorial?.name}</dd>
<dt>Ansprechperson</dt> <dt>Ansprechperson</dt>
@@ -59,6 +61,7 @@ export default async function EditorialProfilePage() {
)} )}
</dd> </dd>
</dl> </dl>
</Card>
</section> </section>
); );
} }
+12 -12
View File
@@ -1,6 +1,7 @@
import { headers } from "next/headers"; import { headers } from "next/headers";
import { PageHeader } from "@/components/ui/page-header"; import { PublicShell } from "@/components/layout/public-shell";
import { Alert } from "@/components/ui/sakani";
import { auth } from "@/modules/auth/auth"; import { auth } from "@/modules/auth/auth";
import { requireTwoFactorSetupPage } from "./access"; import { requireTwoFactorSetupPage } from "./access";
@@ -14,20 +15,19 @@ export default async function TwoFactorSetupPage() {
(session?.user as { twoFactorEnabled?: unknown } | undefined)?.twoFactorEnabled === true; (session?.user as { twoFactorEnabled?: unknown } | undefined)?.twoFactorEnabled === true;
return ( return (
<div className="space-y-8 max-w-2xl mx-auto px-4 py-10 animate-in fade-in slide-in-from-bottom-4 duration-500"> <PublicShell kicker="Sicherheit" title="Zwei-Faktor-Authentifizierung" titleId="two-factor-title" wide>
<PageHeader kicker="Sicherheit" title="Zwei-Faktor-Authentifizierung" />
{enabled ? ( {enabled ? (
<p className="text-sm text-muted-foreground"> <Alert
Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich color="success"
einen Code Ihrer Authenticator-App. description="Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich einen Code Ihrer Authenticator-App."
</p> />
) : ( ) : (
<div className="bg-primary/10 border border-primary/30 p-4 rounded-md text-sm" role="status"> <Alert
Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie color="info"
jetzt ein, um auf den Admin-Bereich zuzugreifen. description="Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie jetzt ein, um auf den Admin-Bereich zuzugreifen."
</div> />
)} )}
<TwoFactorWizard initiallyEnabled={enabled} /> <TwoFactorWizard initiallyEnabled={enabled} />
</div> </PublicShell>
); );
} }
+35 -41
View File
@@ -2,6 +2,8 @@
import { type FormEvent, useState } from "react"; import { type FormEvent, useState } from "react";
import { Alert, Input } from "@sakaniui/react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { authClient } from "@/modules/auth/client"; import { authClient } from "@/modules/auth/client";
@@ -82,19 +84,18 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
} }
return ( return (
<div className="space-y-6"> <div className="flex flex-col gap-6">
{!enabled && step === "password" && ( {!enabled && step === "password" && (
<form onSubmit={startSetup} className="space-y-4"> <form onSubmit={startSetup} className="flex flex-col items-start gap-4">
<label className="block text-sm font-medium"> <div className="w-full">
Passwort bestätigen, um die Einrichtung zu starten <Input
<input
autoComplete="current-password" autoComplete="current-password"
className="mt-1 block w-full" label="Passwort bestätigen, um die Einrichtung zu starten"
name="password" name="password"
required required
type="password" type="password"
/> />
</label> </div>
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Wird vorbereitet …" : "Einrichtung starten"} {pending ? "Wird vorbereitet …" : "Einrichtung starten"}
</Button> </Button>
@@ -102,12 +103,12 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
)} )}
{step === "scan" && secret && ( {step === "scan" && secret && (
<div className="space-y-4"> <div className="flex flex-col gap-4">
<ol className="text-sm space-y-2 list-decimal list-inside text-muted-foreground"> <ol className="flex list-inside list-decimal flex-col gap-2 text-sm text-[var(--color-fg-muted)]">
<li>Öffnen Sie Ihre Authenticator-App (z. B. Google Authenticator, Aegis, 1Password).</li> <li>Öffnen Sie Ihre Authenticator-App (z. B. Google Authenticator, Aegis, 1Password).</li>
<li> <li>
Fügen Sie einen neuen Eintrag hinzu und geben Sie diesen Schlüssel manuell ein: Fügen Sie einen neuen Eintrag hinzu und geben Sie diesen Schlüssel manuell ein:
<code className="block mt-2 rounded-md bg-muted p-3 font-mono text-base tracking-widest select-all break-all"> <code className="mt-2 block select-all break-all rounded-[var(--radius-md)] bg-[var(--color-bg-subtle)] p-3 font-mono text-base tracking-widest text-[var(--color-fg-default)]">
{secret} {secret}
</code> </code>
<span className="text-xs mt-1 block"> <span className="text-xs mt-1 block">
@@ -118,74 +119,67 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
</ol> </ol>
{backupCodes.length > 0 && ( {backupCodes.length > 0 && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm"> <div className="flex flex-col gap-2 rounded-[var(--radius-lg)] border border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] p-4 text-sm">
<p className="font-medium mb-2">Einmal-Codes (ersatzweise gültig, je einmal nutzbar)</p> <p className="font-medium">Einmal-Codes (ersatzweise gültig, je einmal nutzbar)</p>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-1 font-mono text-xs"> <div className="grid grid-cols-2 gap-1 font-mono text-xs sm:grid-cols-3">
{backupCodes.map((code) => ( {backupCodes.map((code) => (
<span key={code}>{code}</span> <span key={code}>{code}</span>
))} ))}
</div> </div>
<p className="text-xs mt-2 text-muted-foreground"> <p className="text-xs text-[var(--color-fg-muted)]">
Bewahren Sie diese Codes sicher auf – sie werden nur jetzt angezeigt. Bewahren Sie diese Codes sicher auf – sie werden nur jetzt angezeigt.
</p> </p>
</div> </div>
)} )}
<form onSubmit={confirmCode} className="space-y-4"> <form onSubmit={confirmCode} className="flex flex-col items-start gap-4">
<label className="block text-sm font-medium"> <div className="w-48">
Code aus der App <Input
<input
autoComplete="one-time-code" autoComplete="one-time-code"
className="mt-1 block w-full max-w-[12rem]"
inputMode="numeric" inputMode="numeric"
label="Code aus der App"
maxLength={6} maxLength={6}
name="code" name="code"
pattern="[0-9]*" pattern="[0-9]*"
required required
type="text" type="text"
/> />
</label> </div>
<Button disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Aktivieren"} {pending ? "Code wird geprüft …" : "Aktivieren"}
</Button> </Button>
</form> </form>
</div> </div>
)} )}
{step === "done" && ( {step === "done" && (
<div className="rounded-md border border-emerald-600/40 bg-emerald-600/10 p-4 text-sm" role="status"> <div className="flex flex-col items-start gap-4" role="status">
Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit <Alert
Passwort und Authenticator-Code anmelden. color="success"
<a className="primary-action inline-block mt-4" href="/admin"> description="Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit Passwort und Authenticator-Code anmelden."
Weiter zum Admin-Bereich />
</a> <Button asChild>
<a href="/admin">Weiter zum Admin-Bereich</a>
</Button>
</div> </div>
)} )}
{enabled && step !== "done" && ( {enabled && step !== "done" && (
<form onSubmit={disable} className="space-y-4 border-t pt-6"> <form onSubmit={disable} className="flex flex-col items-start gap-4 border-t border-[var(--color-border-subtle)] pt-6">
<p className="text-sm text-muted-foreground"> <p className="text-sm text-[var(--color-fg-muted)]">
Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die
Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind. Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.
</p> </p>
<input <div className="w-full">
autoComplete="current-password" <Input aria-label="Passwort" autoComplete="current-password" name="password" placeholder="Passwort" required type="password" />
name="password" </div>
placeholder="Passwort"
required
type="password"
/>
<Button variant="outline" disabled={pending} type="submit"> <Button variant="outline" disabled={pending} type="submit">
{pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"} {pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"}
</Button> </Button>
</form> </form>
)} )}
{error && ( {error && <Alert color="danger" description={error} />}
<p className="field-error" role="alert">
{error}
</p>
)}
</div> </div>
); );
} }
-30
View File
@@ -1,30 +0,0 @@
"use client";
import { useActionState } from "react";
import type { AlbumActionResult } from "@/app/admin/redaktionen/[id]/alben/actions";
// Client wrapper so the grant/revoke result (a returned object, not a thrown
// error) surfaces as inline German text via useActionState. The page picks the
// bound server action (grant or revoke) based on `isGranted`.
export function AlbumGrantForm({
action,
isGranted,
albumId,
}: Readonly<{
action: (state: AlbumActionResult, formData: FormData) => Promise<AlbumActionResult>;
isGranted: boolean;
albumId: string;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction}>
<input name="immichAlbumId" type="hidden" value={albumId} />
<button type="submit" disabled={pending}>
{pending ? "…" : isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
{state.ok ? null : <p role="alert">{state.message}</p>}
</form>
);
}
-38
View File
@@ -1,38 +0,0 @@
"use client";
import { useActionState } from "react";
import type { ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions";
// Client wrapper so the approve result (a returned object, not a thrown
// error) surfaces as inline German text via useActionState. `canApprove`
// mirrors the server-side gate (email verified + active album grant).
export function ApproveForm({
action,
canApprove,
}: Readonly<{
action: (state: ApproveActionResult, formData: FormData) => Promise<ApproveActionResult>;
canApprove: boolean;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction} className="account-form">
<label>
Individueller Nettopreis (EUR)
<input
inputMode="decimal"
min="0.01"
name="priceEuros"
required
step="0.01"
type="number"
/>
</label>
<button type="submit" disabled={!canApprove || pending}>
{pending ? "…" : "Redaktion freigeben"}
</button>
{state.ok ? null : <p role="alert">{state.message}</p>}
</form>
);
}
-52
View File
@@ -1,52 +0,0 @@
// @vitest-environment jsdom
import { readFileSync } from "node:fs";
import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
vi.mock("next/navigation", () => ({
usePathname: () => "/redaktion/alben",
}));
import { PortalShell } from "@/components/layout/portal-shell";
import { BrandLogo } from "./logo";
test("lets CSS constrain both supplied logo variants without oversized intrinsic attributes", () => {
render(<BrandLogo />);
const logos = screen.getAllByAltText("Leon Tonhäuser Sportfotografie");
expect(logos).toHaveLength(2);
expect(logos[0].getAttribute("width")).toBeNull();
expect(logos[0].getAttribute("height")).toBeNull();
expect(logos[0].className).toContain("brand-logo-light");
expect(logos[1].getAttribute("width")).toBeNull();
expect(logos[1].getAttribute("height")).toBeNull();
expect(logos[1].className).toContain("brand-logo-dark");
});
test("keeps masthead controls keyboard-focusable with a paper-coloured focus outline", () => {
render(
<PortalShell
brandHref="/redaktion/alben"
sectionLabel="Redaktionsarchiv"
nav={[{ href: "/redaktion/alben", label: "Alben" }]}
>
<p>Archiv</p>
</PortalShell>,
);
// The brand link's accessible name is the section label (aria-label).
expect(screen.getByRole("link", { name: /redaktionsarchiv/i }).tagName).toBe("A");
expect(screen.getByRole("link", { name: "Alben" }).tagName).toBe("A");
const menuTrigger = screen.getByRole("button", { name: /menü öffnen/i });
expect(menuTrigger.parentElement?.className).toContain("sm:hidden");
fireEvent.click(menuTrigger);
expect(screen.getAllByRole("link", { name: "Alben" })).toHaveLength(2);
expect(screen.getByRole("navigation", { name: /mobile navigation/i })).toBeTruthy();
const styles = readFileSync("src/app/globals.css", "utf8");
expect(styles).toContain(".portal-masthead :focus-visible");
expect(styles).toContain("outline-color: var(--paper)");
});
-18
View File
@@ -1,18 +0,0 @@
/* eslint-disable @next/next/no-img-element */
export function BrandLogo() {
return (
<>
<img
alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-light"
src="/brand/logo-black.png"
/>
<img
alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-dark"
src="/brand/logo-white.png"
/>
</>
);
}
+9 -7
View File
@@ -1,6 +1,8 @@
"use client"; "use client";
import { useRef, useState, type FormEvent } from "react"; import { useRef, useState, type FormEvent } from "react";
import { Alert, Button } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons";
import { formatBerlinDate } from "@/modules/downloads/format"; import { formatBerlinDate } from "@/modules/downloads/format";
import type { DownloadDialogUsage } from "@/modules/downloads/stream"; import type { DownloadDialogUsage } from "@/modules/downloads/stream";
@@ -115,9 +117,9 @@ export function UsageDialog({
return ( return (
<> <>
<button className="download-trigger" onClick={openDialog} type="button"> <Button leftIcon={<IconDownload size={16} />} onClick={openDialog} size="sm" type="button" variant="secondary">
Original laden Original laden
</button> </Button>
<dialog <dialog
aria-labelledby={`usage-dialog-title-${assetId}`} aria-labelledby={`usage-dialog-title-${assetId}`}
className="usage-dialog" className="usage-dialog"
@@ -196,19 +198,19 @@ export function UsageDialog({
/> />
</label> </label>
{error ? <p role="alert">{error}</p> : null} {error ? <Alert color="danger" description={error} /> : null}
<div className="usage-dialog-actions"> <div className="usage-dialog-actions">
<button disabled={pending} onClick={closeDialog} type="button"> <Button disabled={pending} onClick={closeDialog} type="button" variant="ghost">
Abbrechen Abbrechen
</button> </Button>
<button className="download-confirm" disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending {pending
? "Download wird vorbereitet …" ? "Download wird vorbereitet …"
: error : error
? "Download erneut anfordern" ? "Download erneut anfordern"
: "Download anfordern"} : "Download anfordern"}
</button> </Button>
</div> </div>
</form> </form>
</dialog> </dialog>
+76
View File
@@ -0,0 +1,76 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
const { push } = vi.hoisted(() => ({ push: vi.fn() }));
vi.mock("next/navigation", () => ({
usePathname: () => "/redaktion/alben/abc",
useRouter: () => ({ push }),
}));
vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "light", setTheme: vi.fn() }) }));
vi.mock("@/modules/auth/client", () => ({ authClient: { signOut: vi.fn() } }));
import { AppShell } from "./app-shell";
import { RELEASE } from "./release-notes";
const legal = {
imprint: "https://example.com/impressum",
privacy: "https://example.com/datenschutz",
terms: "https://example.com/agb",
};
beforeEach(() => {
// The release-notes popup is not under test here unless a test clears this.
localStorage.setItem("release-notes-seen:redaktion", RELEASE.version);
});
afterEach(() => {
cleanup();
localStorage.clear();
push.mockClear();
});
test("marks the active section and routes sidebar links client-side", () => {
render(<AppShell area="redaktion" legal={legal}>Inhalt</AppShell>);
const albums = screen.getByRole("link", { name: "Alben" });
expect(albums.getAttribute("aria-current")).toBe("page");
const lightbox = screen.getByRole("link", { name: "Merkzettel" });
expect(fireEvent.click(lightbox)).toBe(false); // default (full reload) prevented
expect(push).toHaveBeenCalledWith("/redaktion/leuchtkasten");
push.mockClear();
fireEvent.click(lightbox, { metaKey: true }); // new-tab clicks stay native
expect(push).not.toHaveBeenCalled();
});
test("legal links sit in the sidebar and open natively in a new tab", () => {
render(<AppShell area="redaktion" legal={legal}>Inhalt</AppShell>);
const imprint = screen.getByRole("link", { name: "Impressum" });
expect(imprint.getAttribute("href")).toBe(legal.imprint);
expect(imprint.getAttribute("target")).toBe("_blank");
expect(fireEvent.click(imprint)).toBe(true); // not intercepted
expect(push).not.toHaveBeenCalled();
expect(screen.getByRole("link", { name: "Datenschutz" })).toBeTruthy();
expect(screen.getByRole("link", { name: "Nutzungsbedingungen" })).toBeTruthy();
});
test("release notes pop up once per version and reopen from the sidebar", async () => {
localStorage.clear();
const { unmount } = render(<AppShell area="admin" legal={legal}>Inhalt</AppShell>);
expect(await screen.findByRole("dialog", { name: "Was ist neu?" })).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Verstanden" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(localStorage.getItem("release-notes-seen:admin")).toBe(RELEASE.version);
unmount();
render(<AppShell area="admin" legal={legal}>Inhalt</AppShell>);
expect(screen.queryByRole("dialog")).toBeNull(); // seen: stays closed
fireEvent.click(screen.getByRole("button", { name: new RegExp(`Was ist neu · v${RELEASE.version}`) }));
expect(await screen.findByRole("dialog", { name: "Was ist neu?" })).toBeTruthy();
});
+191
View File
@@ -0,0 +1,191 @@
"use client";
/* eslint-disable @next/next/no-img-element */
import { useEffect, useState, type MouseEvent, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { Button, IconButton, Sidebar, SidebarHeader, SidebarItem, TopBar } from "@sakaniui/react";
import {
IconBookmark,
IconChecklist,
IconLayoutDashboard,
IconLibraryPhoto,
IconLogout,
IconMenu2,
IconReceipt,
IconSparkles,
IconSpeakerphone,
IconSunMoon,
IconUserCircle,
IconUsers,
IconX,
} from "@sakaniui/react/icons";
import { authClient } from "@/modules/auth/client";
import { RELEASE, ReleaseNotesDialog } from "./release-notes";
export type LegalUrls = { imprint: string; privacy: string; terms: string };
// Nav lives here, not in the (server) layouts: icon components cannot cross
// the server→client boundary as props.
const AREAS = {
redaktion: {
label: "Redaktionsarchiv",
nav: [
{ href: "/redaktion/alben", label: "Alben", icon: IconLibraryPhoto },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel", icon: IconBookmark },
{ href: "/redaktion/nutzungen", label: "Nutzungen", icon: IconReceipt },
{ href: "/redaktion/profil", label: "Profil", icon: IconUserCircle },
],
},
admin: {
label: "Administration",
nav: [
{ href: "/admin", label: "Dashboard", icon: IconLayoutDashboard },
{ href: "/admin/redaktionen", label: "Redaktionen", icon: IconUsers },
{ href: "/admin/alben", label: "Alben", icon: IconLibraryPhoto },
{ href: "/admin/hinweise", label: "Hinweise", icon: IconSpeakerphone },
{ href: "/admin/abrechnungen", label: "Abrechnungen", icon: IconReceipt },
{ href: "/admin/audit", label: "Audit", icon: IconChecklist },
],
},
};
export function AppShell({
area,
legal,
children,
}: Readonly<{ area: keyof typeof AREAS; legal: LegalUrls; children: ReactNode }>) {
const { label: SECTION_LABEL, nav: NAV } = AREAS[area];
const pathname = usePathname();
const router = useRouter();
const { resolvedTheme, setTheme } = useTheme();
const [menuOpen, setMenuOpen] = useState(false);
const [signingOut, setSigningOut] = useState(false);
const [notesOpen, setNotesOpen] = useState(false);
const active = NAV.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`))
.sort((a, b) => b.href.length - a.href.length)[0];
useEffect(() => {
if (!menuOpen) return;
const close = (event: KeyboardEvent) => event.key === "Escape" && setMenuOpen(false);
document.addEventListener("keydown", close);
return () => document.removeEventListener("keydown", close);
}, [menuOpen]);
// ponytail: SidebarItem renders a plain <a href>, which would reload the
// whole page. Catch plain left-clicks and route client-side instead; no
// prefetch. Swap for a Link-aware item if Sakani ever accepts one.
function navigate(event: MouseEvent) {
const link = (event.target as HTMLElement).closest("a");
const href = link?.getAttribute("href");
// Only internal nav links; legal links open in a new tab as usual.
if (!link || link.target || !href?.startsWith("/")) return;
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
setMenuOpen(false);
router.push(href);
}
async function signOut() {
setSigningOut(true);
try {
await authClient.signOut();
} finally {
window.location.replace("/anmelden");
}
}
return (
<div data-app-shell className="flex min-h-dvh bg-[var(--color-bg-canvas)] text-[var(--color-fg-default)]">
<ReleaseNotesDialog area={area} open={notesOpen} onOpenChange={setNotesOpen} />
{menuOpen ? (
<div aria-hidden="true" className="fixed inset-0 z-40 bg-black/40 md:hidden" onClick={() => setMenuOpen(false)} />
) : null}
<div
id="editorial-sidebar"
onClick={navigate}
className={`${menuOpen ? "max-md:flex" : "max-md:hidden"} fixed inset-y-0 left-0 z-50 flex border-r bg-[var(--color-bg-canvas)] border-[var(--color-border-subtle)] md:sticky md:top-0 md:h-dvh`}
>
{/* Sakani drops aria-label on Sidebar; its <nav> stays the main nav landmark. */}
<Sidebar>
<SidebarHeader
title={SECTION_LABEL}
subtitle="Leon Tonhäuser Sportfotografie"
logo={
// Decorative: the header title next to it names the portal.
// brand-logo-light/-dark only toggle display via the .dark class.
<>
<img alt="" className="brand-logo-light" height={32} src="/brand/logo-black.png" width={32} />
<img alt="" className="brand-logo-dark" height={32} src="/brand/logo-white.png" width={32} />
</>
}
/>
<div className="mt-4 flex flex-col gap-1">
{NAV.map((item) => (
<SidebarItem
key={item.href}
href={item.href}
label={item.label}
icon={item.icon}
active={item.href === active?.href}
/>
))}
</div>
<div className="mt-auto flex flex-col items-start gap-1 border-t border-[var(--color-border-subtle)] pt-3 pb-3">
<Button variant="ghost" size="sm" leftIcon={<IconSparkles size={16} />} onClick={() => setNotesOpen(true)}>
Was ist neu · v{RELEASE.version}
</Button>
<nav aria-label="Rechtliches" className="flex flex-wrap gap-x-3 gap-y-1 px-3 py-1 text-xs text-[var(--color-fg-muted)]">
<a className="hover:text-[var(--color-fg-default)] hover:underline" href={legal.imprint} rel="noreferrer noopener" target="_blank">Impressum</a>
<a className="hover:text-[var(--color-fg-default)] hover:underline" href={legal.privacy} rel="noreferrer noopener" target="_blank">Datenschutz</a>
<a className="hover:text-[var(--color-fg-default)] hover:underline" href={legal.terms} rel="noreferrer noopener" target="_blank">Nutzungsbedingungen</a>
</nav>
<Button variant="ghost" size="sm" leftIcon={<IconLogout size={16} />} loading={signingOut} onClick={signOut}>
Abmelden
</Button>
</div>
</Sidebar>
</div>
<div className="flex min-w-0 flex-1 flex-col">
<div className="sticky top-0 z-30 border-b border-[var(--color-border-subtle)] bg-[var(--color-bg-canvas)]">
<TopBar
type="minimal"
density="sm"
showToggle={false}
showActions={false}
left={
<div className="flex items-center gap-2">
<span className="md:hidden">
<IconButton
variant="ghost"
size="sm"
icon={menuOpen ? IconX : IconMenu2}
aria-label={menuOpen ? "Menü schließen" : "Menü öffnen"}
aria-expanded={menuOpen}
aria-controls="editorial-sidebar"
onClick={() => setMenuOpen((open) => !open)}
/>
</span>
<span className="text-sm font-medium">{active?.label ?? SECTION_LABEL}</span>
</div>
}
rightSlot={
<IconButton
variant="ghost"
size="sm"
icon={IconSunMoon}
aria-label="Hell/Dunkel umschalten"
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
/>
}
/>
</div>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-8 sm:px-8 lg:py-12">{children}</main>
</div>
</div>
);
}
-33
View File
@@ -1,33 +0,0 @@
"use client";
import { useState } from "react";
import { authClient } from "@/modules/auth/client";
import { Button } from "@/components/ui/button";
// Renders into the portal masthead. Better Auth's signOut clears the session
// cookie server-side; a hard replacement clears any stale router cache.
export function LogoutButton() {
const [pending, setPending] = useState(false);
async function signOut() {
setPending(true);
try {
await authClient.signOut();
} finally {
window.location.replace("/anmelden");
}
}
return (
<Button
variant="outline"
size="sm"
disabled={pending}
onClick={signOut}
type="button"
>
{pending ? "…" : "Abmelden"}
</Button>
);
}
@@ -1,94 +0,0 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
const { usePathname } = vi.hoisted(() => ({
usePathname: vi.fn(),
}));
vi.mock("next/navigation", () => ({ usePathname }));
import { MobilePortalMenu } from "./mobile-portal-menu";
const nav = [
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/redaktionen", label: "Redaktionen" },
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
{ href: "/admin/audit", label: "Audit" },
];
beforeEach(() => usePathname.mockReturnValue("/admin/redaktionen/abc"));
afterEach(cleanup);
test("opens every mobile portal action and marks the most specific active route", () => {
render(<MobilePortalMenu nav={nav} sectionLabel="Administration" />);
const trigger = screen.getByRole("button", { name: /menü öffnen/i });
expect(trigger.getAttribute("aria-expanded")).toBe("false");
expect(screen.queryByRole("navigation", { name: /mobile navigation/i })).toBeNull();
fireEvent.click(trigger);
expect(trigger.getAttribute("aria-expanded")).toBe("true");
const inactiveLink = screen.getByRole("link", { name: "Dashboard" });
const activeLink = screen.getByRole("link", { name: "Redaktionen" });
expect(inactiveLink).toBeTruthy();
expect(activeLink.getAttribute("aria-current")).toBe("page");
expect(activeLink.getAttribute("class")).toContain("mobile-portal-menu-active");
expect(inactiveLink.getAttribute("class")).not.toContain("mobile-portal-menu-active");
expect(screen.getByRole("link", { name: "Abrechnungen" })).toBeTruthy();
expect(screen.getByRole("link", { name: "Audit" })).toBeTruthy();
expect(screen.getByRole("button", { name: /design umschalten/i })).toBeTruthy();
expect(screen.getByRole("button", { name: /abmelden/i })).toBeTruthy();
});
test("keeps nested theme and logout buttons at least 44px tall", () => {
render(<MobilePortalMenu nav={nav} sectionLabel="Administration" />);
fireEvent.click(screen.getByRole("button", { name: /menü öffnen/i }));
const themeToggle = screen.getByRole("button", { name: /design umschalten/i });
const logoutButton = screen.getByRole("button", { name: /abmelden/i });
expect(themeToggle.parentElement?.getAttribute("class")).toContain("[&>button]:min-h-11");
expect(themeToggle.parentElement?.getAttribute("class")).toContain("[&>button]:min-w-11");
expect(logoutButton.parentElement?.getAttribute("class")).toContain("[&>button]:min-h-11");
});
test("caps the open panel to the dynamic viewport and keeps every action scrollable", () => {
render(<MobilePortalMenu nav={nav} sectionLabel="Administration" />);
fireEvent.click(screen.getByRole("button", { name: /menü öffnen/i }));
const panel = screen.getByRole("navigation", { name: /mobile navigation/i }).parentElement;
expect(panel?.getAttribute("class")).toContain("max-h-[calc(100dvh-5.5rem)]");
expect(panel?.getAttribute("class")).toContain("overflow-y-auto");
expect(panel?.getAttribute("class")).toContain("overscroll-contain");
});
test("closes after navigation, Escape and an outside pointer interaction", () => {
render(
<div>
<MobilePortalMenu nav={nav} sectionLabel="Administration" />
<button type="button">Außerhalb</button>
</div>,
);
const trigger = screen.getByRole("button", { name: /menü öffnen/i });
fireEvent.click(trigger);
const auditLink = screen.getByRole("link", { name: "Audit" });
auditLink.addEventListener("click", (event) => event.preventDefault(), { once: true });
fireEvent.click(auditLink);
expect(trigger.getAttribute("aria-expanded")).toBe("false");
fireEvent.click(trigger);
fireEvent.keyDown(document, { key: "Escape" });
expect(trigger.getAttribute("aria-expanded")).toBe("false");
expect(document.activeElement).toBe(trigger);
fireEvent.click(trigger);
fireEvent.pointerDown(screen.getByRole("button", { name: "Außerhalb" }));
expect(trigger.getAttribute("aria-expanded")).toBe("false");
});
@@ -1,104 +0,0 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Menu, X } from "lucide-react";
import type { NavItem } from "@/components/layout/portal-shell";
import { LogoutButton } from "@/components/layout/logout-button";
import { ThemeToggle } from "@/components/theme-toggle";
type MobilePortalMenuProps = {
nav: NavItem[];
sectionLabel: string;
};
export function MobilePortalMenu({ nav, sectionLabel }: Readonly<MobilePortalMenuProps>) {
const pathname = usePathname();
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const menuId = "mobile-portal-menu";
const activeHref = useMemo(
() => nav
.filter(({ href }) => pathname === href || pathname.startsWith(`${href}/`))
.sort((left, right) => right.href.length - left.href.length)[0]?.href,
[nav, pathname],
);
useEffect(() => {
if (!open) return;
function closeOnOutsidePointer(event: PointerEvent) {
if (!containerRef.current?.contains(event.target as Node)) setOpen(false);
}
function closeOnEscape(event: KeyboardEvent) {
if (event.key !== "Escape") return;
setOpen(false);
triggerRef.current?.focus();
}
document.addEventListener("pointerdown", closeOnOutsidePointer);
document.addEventListener("keydown", closeOnEscape);
return () => {
document.removeEventListener("pointerdown", closeOnOutsidePointer);
document.removeEventListener("keydown", closeOnEscape);
};
}, [open]);
return (
<div ref={containerRef} className="relative sm:hidden">
<button
ref={triggerRef}
type="button"
aria-controls={menuId}
aria-expanded={open}
aria-label={open ? "Menü schließen" : "Menü öffnen"}
className="inline-flex min-h-11 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm font-semibold"
onClick={() => setOpen((current) => !current)}
>
{open ? <X aria-hidden="true" className="size-5" /> : <Menu aria-hidden="true" className="size-5" />}
Menü
</button>
{open ? (
<div
id={menuId}
className="mobile-portal-menu-panel absolute right-0 top-[calc(100%+0.75rem)] z-50 max-h-[calc(100dvh-5.5rem)] w-[min(22rem,calc(100vw-2rem))] overflow-y-auto overscroll-contain rounded-xl border border-border bg-background p-2 shadow-xl"
>
<p className="px-3 py-2 text-xs font-bold uppercase tracking-widest text-[var(--muted)]">
{sectionLabel}
</p>
<nav aria-label="Mobile Navigation" className="grid gap-1">
{nav.map((item) => {
const active = item.href === activeHref;
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? "page" : undefined}
className={active
? "mobile-portal-menu-active flex min-h-11 items-center rounded-lg px-3 font-semibold"
: "flex min-h-11 items-center rounded-lg px-3 font-medium hover:bg-[var(--soft)]"}
onClick={() => setOpen(false)}
>
{item.label}
</Link>
);
})}
</nav>
<div className="mt-2 flex min-h-11 items-center justify-between border-t border-border px-3 pt-2 [&>button]:min-h-11 [&>button]:min-w-11">
<span className="text-sm text-[var(--muted)]">Darstellung</span>
<ThemeToggle />
</div>
<div className="mt-2 border-t border-border px-3 pt-2 [&>button]:min-h-11">
<LogoutButton />
</div>
</div>
) : null}
</div>
);
}
-62
View File
@@ -1,62 +0,0 @@
import type { ReactNode } from "react";
import Link from "next/link";
import { BrandLogo } from "@/components/brand/logo";
import { LogoutButton } from "@/components/layout/logout-button";
import { MobilePortalMenu } from "@/components/layout/mobile-portal-menu";
import { ThemeToggle } from "@/components/theme-toggle";
export type NavItem = { href: string; label: string };
type PortalShellProps = {
brandHref: string;
sectionLabel: string;
nav: NavItem[];
// Editorial pages are wrapped in `.editorial-work-surface` (width + padding),
// so their content uses `.editorial-section` (max-width: 100%). Admin pages
// bring their own `.content-section` container (width + padding), so the
// shell must not add a second width wrapper — pass an empty string here.
mainClassName?: string;
children: ReactNode;
};
export function PortalShell({
brandHref,
sectionLabel,
nav,
mainClassName = "editorial-work-surface",
children,
}: Readonly<PortalShellProps>) {
return (
<div className="min-h-screen bg-background flex flex-col">
<header className="sticky top-0 z-50 w-full border-b border-border/40 bg-background/80 backdrop-blur-md transition-colors duration-300">
<div className="flex h-16 items-center justify-between px-4 sm:px-6 lg:px-12">
<Link aria-label={sectionLabel} className="flex items-center gap-2 transition-opacity hover:opacity-80" href={brandHref}>
<div className="flex items-center"><BrandLogo /></div>
</Link>
<div className="flex items-center gap-6 text-sm font-medium">
<span className="hidden md:inline-block text-muted-foreground uppercase tracking-widest text-xs font-bold">{sectionLabel}</span>
<nav aria-label={sectionLabel} className="hidden sm:flex items-center gap-6">
{nav.map((item) => (
<Link
key={item.href}
href={item.href}
className="transition-colors hover:text-primary-500 text-foreground"
>
{item.label}
</Link>
))}
</nav>
<div className="hidden items-center gap-4 sm:flex">
<ThemeToggle />
<LogoutButton />
</div>
<MobilePortalMenu nav={nav} sectionLabel={sectionLabel} />
</div>
</div>
</header>
<main className="flex-1 w-full max-w-7xl mx-auto px-6 py-12 lg:px-12 lg:py-16">{children}</main>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
/* eslint-disable @next/next/no-img-element */
import type { ReactNode } from "react";
import Link from "next/link";
import { Card } from "@/components/ui/sakani";
// Frame for the signed-out pages (landing, login, registration, password,
// 2FA, error): brand bar on top, one centred Sakani card with the content.
export function PublicShell({
kicker,
title,
titleId,
lede,
wide = false,
children,
}: Readonly<{
kicker: string;
title: string;
titleId: string;
lede?: ReactNode;
wide?: boolean;
children?: ReactNode;
}>) {
return (
<main className="flex min-h-dvh flex-col bg-[var(--color-bg-canvas)] text-[var(--color-fg-default)]">
<header className="flex items-center justify-between gap-4 border-b border-[var(--color-border-subtle)] px-4 py-3 sm:px-8">
<Link className="flex items-center gap-3 rounded-[var(--radius-md)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]" href="/">
<img alt="" className="brand-logo-light" height={32} src="/brand/logo-black.png" width={32} />
<img alt="" className="brand-logo-dark" height={32} src="/brand/logo-white.png" width={32} />
<span className="text-sm font-semibold">Leon Tonhäuser</span>
</Link>
<span className="text-xs font-medium uppercase tracking-wider text-[var(--color-fg-muted)]">Redaktionsportal</span>
</header>
<div className="flex flex-1 items-start justify-center px-4 py-10 sm:py-16">
<section aria-labelledby={titleId} className={`w-full ${wide ? "max-w-3xl" : "max-w-md"}`}>
<Card>
{/* Sakani's card body mutes text and adds no gap; this wrapper restores both. */}
<div className="flex flex-col gap-6 text-base text-[var(--color-fg-default)]">
<header className="flex flex-col gap-2">
<p className="text-xs font-medium uppercase tracking-wider text-[var(--color-fg-muted)]">{kicker}</p>
<h1 id={titleId} className="text-2xl font-semibold tracking-tight">{title}</h1>
{lede ? <p className="text-[var(--color-fg-muted)]">{lede}</p> : null}
</header>
{children}
</div>
</Card>
</section>
</div>
</main>
);
}
+106
View File
@@ -0,0 +1,106 @@
"use client";
import { useEffect, useRef } from "react";
import { Button } from "@sakaniui/react";
import { IconCheck } from "@sakaniui/react/icons";
// Bump RELEASE.version for the next release and replace the notes: every user
// 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",
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.",
],
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.",
],
},
} as const;
export type ReleaseArea = keyof typeof RELEASE.notes;
const seenKey = (area: ReleaseArea) => `release-notes-seen:${area}`;
// Per browser, not per account: a courtesy popup, not a record of consent.
function readSeen(area: ReleaseArea): string | null {
try {
return window.localStorage.getItem(seenKey(area));
} catch {
return RELEASE.version; // storage blocked: don't nag on every page load
}
}
function markSeen(area: ReleaseArea) {
try {
window.localStorage.setItem(seenKey(area), RELEASE.version);
} catch {
/* storage blocked — nothing to persist */
}
}
// Native <dialog>.showModal() instead of Sakani's Modal: it traps focus, makes
// the page inert and handles Escape; Sakani's Modal left focus on the page.
export function ReleaseNotesDialog({
area,
open,
onOpenChange,
}: Readonly<{ area: ReleaseArea; open: boolean; onOpenChange: (open: boolean) => void }>) {
const ref = useRef<HTMLDialogElement>(null);
// Open once per version, after hydration (localStorage is client-only).
useEffect(() => {
if (readSeen(area) !== RELEASE.version) onOpenChange(true);
}, [area, onOpenChange]);
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
// Runs for the button, Escape and dialog.close() alike.
function handleClose() {
markSeen(area);
onOpenChange(false);
}
return (
<dialog ref={ref} aria-labelledby="release-notes-title" className="usage-dialog max-w-lg" onClose={handleClose}>
<div className="flex flex-col gap-5 p-6">
<header className="flex flex-col gap-1">
<p className="text-xs font-medium uppercase tracking-wider text-[var(--color-fg-muted)]">
Version {RELEASE.version} – {RELEASE.title}
</p>
<h2 id="release-notes-title" className="text-xl font-semibold">Was ist neu?</h2>
</header>
<ul className="flex flex-col gap-3 text-sm">
{RELEASE.notes[area].map((note) => (
<li key={note} className="flex gap-3">
<IconCheck aria-hidden="true" className="mt-0.5 shrink-0 text-[var(--color-success-fg)]" size={16} />
<span>{note}</span>
</li>
))}
</ul>
<div className="flex justify-end">
<Button autoFocus onClick={() => ref.current?.close()} type="button">
Verstanden
</Button>
</div>
</div>
</dialog>
);
}
-23
View File
@@ -1,23 +0,0 @@
"use client"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
export function ThemeToggle() {
const { resolvedTheme, setTheme } = useTheme()
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
title="Design umschalten"
>
<Sun className="h-[1.2rem] w-[1.2rem] transition-all dark:hidden" />
<Moon className="hidden h-[1.2rem] w-[1.2rem] transition-all dark:block" />
<span className="sr-only">Design umschalten</span>
</Button>
)
}
+51 -39
View File
@@ -1,46 +1,58 @@
import * as React from "react" "use client";
import { Slot } from "@radix-ui/react-slot"
import { cn } from "@/lib/utils"
export interface ButtonProps import * as React from "react";
extends React.ButtonHTMLAttributes<HTMLButtonElement> { import { Slot } from "@radix-ui/react-slot";
asChild?: boolean import { Button as SakaniButton } from "@sakaniui/react";
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
size?: "default" | "sm" | "lg" | "icon" import { cn } from "@/lib/utils";
// Keeps the old shadcn-style API so call sites stay untouched; renders Sakani.
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
asChild?: boolean;
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link";
size?: "default" | "sm" | "lg" | "icon";
loading?: boolean;
leftIcon?: React.ReactNode;
rightIcon?: React.ReactNode;
} }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( const VARIANT = { default: "primary", destructive: "destructive", outline: "outline", secondary: "secondary", ghost: "ghost", link: "ghost" } as const;
({ className, variant = "default", size = "default", asChild = false, ...props }, ref) => { const SIZE = { default: "md", sm: "sm", lg: "lg", icon: "sm" } as const;
const Comp = asChild ? Slot : "button"
// Wir nutzen hier klassische Tailwind-Klassen kombiniert mit unseren CSS Variablen
const baseClasses = "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary-500 disabled:pointer-events-none disabled:opacity-50"
const variantClasses = {
default: "bg-primary-600 text-white hover:bg-primary-700 shadow-sm",
destructive: "bg-red-500 text-white hover:bg-red-600 shadow-sm",
outline: "border border-border bg-background hover:bg-accent hover:text-accent-foreground shadow-sm",
secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700",
ghost: "hover:bg-gray-100 hover:text-gray-900 dark:hover:bg-gray-800 dark:hover:text-gray-100",
link: "text-primary-600 underline-offset-4 hover:underline",
}
const sizeClasses = {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
}
// ponytail: Sakani's Button only renders <button>. For `asChild` (a Link that
// looks like a button) we mirror the primary button with tokens on the child.
const LINK_BUTTON =
"inline-flex h-10 items-center justify-center gap-2 rounded-[var(--radius-md)] px-4 text-sm font-medium no-underline transition-colors " +
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]";
const LINK_VARIANT = {
primary: "bg-[var(--color-accent-default)] text-[var(--color-accent-fg)] hover:bg-[var(--color-accent-hover)]",
outline: "border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-fg-default)] hover:bg-[var(--color-bg-subtle)]",
};
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = "default", size = "default", asChild = false, leftIcon, rightIcon, loading, children, ...props }, ref) => {
if (asChild) {
const tone = variant === "outline" || variant === "ghost" || variant === "secondary" ? "outline" : "primary";
return (
<Slot className={cn(LINK_BUTTON, LINK_VARIANT[tone], className)} ref={ref} {...props}>
{children}
</Slot>
);
}
return ( return (
<Comp <SakaniButton
className={cn(baseClasses, variantClasses[variant], sizeClasses[size], className)} className={className}
leftIcon={leftIcon}
loading={loading}
ref={ref} ref={ref}
rightIcon={rightIcon}
size={SIZE[size]}
variant={VARIANT[variant]}
{...props} {...props}
/> >
) {children}
} </SakaniButton>
) );
Button.displayName = "Button" },
);
export { Button } Button.displayName = "Button";
+24 -63
View File
@@ -1,70 +1,31 @@
import * as React from "react" import type { HTMLAttributes } from "react";
import { cn } from "@/lib/utils" import { Card as SakaniCard } from "@/components/ui/sakani";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( // Old shadcn-style composition API on top of Sakani's Card surface. Sakani's
({ className, ...props }, ref) => ( // Card already pads (20px) and stacks children (gap 16px), so the parts below
<div // add no padding of their own.
ref={ref} export function Card({ className, children }: HTMLAttributes<HTMLDivElement>) {
className={cn( return <SakaniCard className={className}>{children}</SakaniCard>;
"rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden", }
className
)}
{...props}
/>
)
)
Card.displayName = "Card"
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( export function CardHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
({ className, ...props }, ref) => ( return <div className={cn("flex flex-col gap-1", className)} {...props} />;
<div }
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
)
)
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>( export function CardTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {
({ className, ...props }, ref) => ( return <h3 className={cn("text-base font-semibold text-[var(--color-fg-default)]", className)} {...props} />;
<h3 }
ref={ref}
className={cn("text-2xl font-semibold leading-none tracking-tight", className)}
{...props}
/>
)
)
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>( export function CardDescription({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
({ className, ...props }, ref) => ( return <p className={cn("text-sm text-[var(--color-fg-muted)]", className)} {...props} />;
<p }
ref={ref}
className={cn("text-sm text-gray-500 dark:text-gray-400", className)}
{...props}
/>
)
)
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( export function CardContent({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
({ className, ...props }, ref) => ( return <div className={cn("min-w-0", className)} {...props} />;
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} /> }
)
)
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( export function CardFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
({ className, ...props }, ref) => ( return <div className={cn("flex items-center gap-2", className)} {...props} />;
<div }
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
)
)
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+5 -24
View File
@@ -1,25 +1,6 @@
import * as React from "react" "use client";
import { cn } from "@/lib/utils" // Old API, Sakani rendering. Prefer importing Input from "@/components/ui/sakani"
// in new code to get label/description/icon props.
export interface InputProps export { Input } from "@sakaniui/react";
extends React.InputHTMLAttributes<HTMLInputElement> {} export type { InputProps } from "@sakaniui/react";
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-gray-500 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 dark:placeholder:text-gray-400",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+10 -13
View File
@@ -1,26 +1,23 @@
import React from "react"; import type { ReactNode } from "react";
type PageHeaderProps = { type PageHeaderProps = {
kicker?: string; kicker?: string;
title: string; title: string;
description?: string; description?: ReactNode;
titleId?: string; titleId?: string;
children?: React.ReactNode; children?: ReactNode;
}; };
// Page title block in Sakani tokens; `children` sit right of the title (actions).
export function PageHeader({ kicker, title, description, titleId, children }: PageHeaderProps) { export function PageHeader({ kicker, title, description, titleId, children }: PageHeaderProps) {
return ( return (
<div className="editorial-section"> <header className="mb-8 flex flex-col gap-2">
{kicker && <p className="editorial-kicker text-sm font-semibold text-muted-foreground tracking-widest uppercase mb-2">{kicker}</p>} {kicker ? <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-fg-muted)]">{kicker}</p> : null}
<div className="editorial-title-row mb-6"> <div className="flex flex-wrap items-end justify-between gap-4">
<h1 id={titleId} className="text-4xl font-bold tracking-tight text-foreground">{title}</h1> <h1 id={titleId} className="text-3xl font-semibold tracking-tight text-[var(--color-fg-default)]">{title}</h1>
{children} {children}
</div> </div>
{description && ( {description ? <p className="max-w-2xl text-base text-[var(--color-fg-muted)]">{description}</p> : null}
<p className="text-lg text-muted-foreground max-w-3xl mb-8"> </header>
{description}
</p>
)}
</div>
); );
} }
+24
View File
@@ -0,0 +1,24 @@
// @vitest-environment jsdom
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, expect, test } from "vitest";
import { DataTable, FormSelect } from "./sakani";
afterEach(cleanup);
test("DataTable renders element cells instead of stringifying them", () => {
render(<DataTable columns={[{ key: "name", header: "Name" }]} rows={[{ name: <a href="/x">Kicker</a> }]} />);
expect(screen.getByRole("link", { name: "Kicker" }).getAttribute("href")).toBe("/x");
expect(screen.queryByText("[object Object]")).toBeNull();
});
test("FormSelect submits its value through a named hidden input", () => {
const { container } = render(
<form>
<FormSelect name="format" label="Format" defaultValue="quer" options={[{ label: "Quer", value: "quer" }]} />
</form>,
);
const data = new FormData(container.querySelector("form")!);
expect(data.get("format")).toBe("quer");
});
+55
View File
@@ -0,0 +1,55 @@
"use client";
// @sakaniui/react ships without a "use client" directive and uses hooks and
// context, so Server Components import Sakani through this client boundary.
// Props crossing it must be serialisable: pass icons as elements
// (leftIcon={<IconX />}), never as components (icon={IconX}).
import { useState, type ComponentProps, type ReactNode } from "react";
import { Card as SakaniCard, Select, Table, type SelectOption } from "@sakaniui/react";
export { Alert, Badge, BarChart, Button, Checkbox, EmptyState, Input, Progress, Select, Spinner, StatCard, Textarea } from "@sakaniui/react";
// Sakani's card body mutes its text (fg-muted, 14px) and stacks children with
// no gap — meant for a one-line description. Our cards hold real content.
export function Card({ children, ...props }: ComponentProps<typeof SakaniCard>) {
return (
<SakaniCard {...props}>
<div className="flex flex-col gap-4 text-sm text-[var(--color-fg-default)]">{children}</div>
</SakaniCard>
);
}
// Sakani's Select is a custom combobox without a `name`, so it does not take
// part in a native <form> submit. The hidden input carries the value.
export function FormSelect({
name,
label,
options,
defaultValue = "",
}: Readonly<{ name: string; label: string; options: SelectOption[]; defaultValue?: string }>) {
const [value, setValue] = useState(defaultValue);
return (
<>
<Select label={label} options={options} value={value} onChange={setValue} />
<input type="hidden" name={name} value={value} />
</>
);
}
type Cell = ReactNode;
type DataColumn = { key: string; header: string; align?: "left" | "center" | "right"; width?: string };
// Sakani's Table stringifies cells unless a column has `render`, and render
// functions cannot cross the server→client boundary. Server pages pass rows of
// ready-made cells (strings or elements); this adds the render step.
export function DataTable({
columns,
rows,
}: Readonly<{ columns: DataColumn[]; rows: Array<Record<string, Cell>> }>) {
return (
<Table<Record<string, Cell>>
columns={columns.map((column) => ({ ...column, render: (row) => row[column.key] }))}
rows={rows}
/>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { afterEach, expect, test, vi } from "vitest";
const { startAutoRuleScheduler } = vi.hoisted(() => ({ startAutoRuleScheduler: vi.fn() }));
vi.mock("@/modules/albums/auto-rule-scheduler", () => ({ startAutoRuleScheduler }));
import { register } from "./instrumentation";
afterEach(() => {
vi.unstubAllEnvs();
startAutoRuleScheduler.mockClear();
});
test("starts the auto-rule sync on the node runtime", async () => {
vi.stubEnv("NEXT_RUNTIME", "nodejs");
await register();
expect(startAutoRuleScheduler).toHaveBeenCalledOnce();
});
test("AUTO_RULE_SYNC_DISABLED=true keeps a second instance from syncing", async () => {
vi.stubEnv("NEXT_RUNTIME", "nodejs");
vi.stubEnv("AUTO_RULE_SYNC_DISABLED", "true");
await register();
expect(startAutoRuleScheduler).not.toHaveBeenCalled();
});
+6
View File
@@ -5,6 +5,12 @@ export async function register(): Promise<void> {
if (process.env.NEXT_RUNTIME !== "nodejs") { if (process.env.NEXT_RUNTIME !== "nodejs") {
return; return;
} }
// A second instance on the same DB (e.g. the parallel Sakani UI) must not
// run the sync a second time; the live instance keeps doing it.
if (process.env.AUTO_RULE_SYNC_DISABLED === "true") {
console.log("[auto-rule-sync] disabled via AUTO_RULE_SYNC_DISABLED");
return;
}
try { try {
const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler"); const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler");
startAutoRuleScheduler(); startAutoRuleScheduler();
+99 -24
View File
@@ -1,37 +1,47 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import Link from "next/link"; import Link from "next/link";
import { IconSearch } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import { Card, FormSelect, Input } from "@/components/ui/sakani";
import type { ImmichSearchPage } from "@/modules/immich/types"; import type { ImmichSearchPage } from "@/modules/immich/types";
import type { VisibleAlbum } from "./catalog"; import type { VisibleAlbum } from "./catalog";
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) { export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
return ( return (
<ul className="album-gallery" aria-label="Freigegebene Fotoalben"> <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-label="Freigegebene Fotoalben">
{albums.map((album) => ( {albums.map((album) => (
<li key={album.id}> <li key={album.id}>
<Link className="album-tile" href={`/redaktion/alben/${encodeURIComponent(album.id)}`}> <Link
<figure className="album-tile-frame"> className="block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
{album.albumThumbnailAssetId ? ( href={`/redaktion/alben/${encodeURIComponent(album.id)}`}
<img >
alt={`Titelbild: ${album.albumName}`} <Card interactive className="h-full">
className="album-tile-image" <figure className="flex flex-col gap-3">
loading="lazy" {album.albumThumbnailAssetId ? (
src={thumbnailUrl(album.albumThumbnailAssetId)} <img
/> alt={`Titelbild: ${album.albumName}`}
) : ( className="aspect-[4/3] w-full rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)] object-cover"
<div aria-label={`Kein Titelbild für ${album.albumName}`} className="album-tile-missing" role="img"> loading="lazy"
Kein Titelbild src={thumbnailUrl(album.albumThumbnailAssetId)}
</div> />
)} ) : (
<div className="album-tile-overlay"> <div
<figcaption className="photo-tile-caption"> aria-label={`Kein Titelbild für ${album.albumName}`}
<span className="photo-tile-name">{album.albumName}</span> className="grid aspect-[4/3] w-full place-items-center rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)] text-sm text-[var(--color-fg-muted)]"
<span className="photo-tile-date">{formatCount(album.assetCount, "Foto")}</span> role="img"
>
Kein Titelbild
</div>
)}
<figcaption className="flex items-baseline justify-between gap-3">
<span className="truncate text-base font-medium text-[var(--color-fg-default)]">{album.albumName}</span>
<span className="shrink-0 text-sm tabular-nums text-[var(--color-fg-muted)]">{formatCount(album.assetCount, "Foto")}</span>
</figcaption> </figcaption>
</div> </figure>
</figure> </Card>
</Link> </Link>
</li> </li>
))} ))}
@@ -63,14 +73,79 @@ export function PhotoPagination({
return null; return null;
} }
return <PageLinks prevHref={hasPrev ? pageHref(albumId, currentPage - 1, query, format, jahr) : null} nextHref={hasNext ? pageHref(albumId, currentPage + 1, query, format, jahr) : null} />;
}
// Server-rendered prev/next links (album search, usage history, …).
export function PageLinks({
prevHref,
nextHref,
prevLabel = "Vorherige Seite",
nextLabel = "Nächste Seite",
ariaLabel = "Suchergebnisseiten",
}: Readonly<{ prevHref: string | null; nextHref: string | null; prevLabel?: string; nextLabel?: string; ariaLabel?: string }>) {
if (!prevHref && !nextHref) {
return null;
}
return ( return (
<nav aria-label="Suchergebnisseiten" className="photo-pagination"> <nav aria-label={ariaLabel} className="mt-6 flex items-center justify-between gap-4 border-t border-[var(--color-border-subtle)] pt-4">
{hasPrev ? <Link href={pageHref(albumId, currentPage - 1, query, format, jahr)}>Vorherige Seite</Link> : null} {prevHref ? <Button asChild variant="outline"><Link href={prevHref}>{prevLabel}</Link></Button> : <span />}
{hasNext ? <Link href={pageHref(albumId, currentPage + 1, query, format, jahr)}>Nächste Seite</Link> : null} {nextHref ? <Button asChild variant="outline"><Link href={nextHref}>{nextLabel}</Link></Button> : <span />}
</nav> </nav>
); );
} }
const FORMAT_OPTIONS = [
{ label: "Alle Formate", value: "" },
{ label: "Querformat", value: "quer" },
{ label: "Hochformat", value: "hoch" },
];
// Plain GET form (works without JS) for the album overview and album detail.
// `withYear` adds the year filter the overview offers.
export function PhotoSearchForm({
action,
query,
format,
jahr,
withYear = false,
placeholder,
ariaLabel,
}: Readonly<{
action: string;
query: string;
format?: string;
jahr?: string;
withYear?: boolean;
placeholder: string;
ariaLabel?: string;
}>) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => String(currentYear - i));
return (
<Card>
<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]"}`}
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} />
{withYear ? (
<FormSelect
name="jahr"
label="Jahr"
defaultValue={jahr ?? ""}
options={[{ label: "Alle Jahre", value: "" }, ...years.map((y) => ({ label: y, value: y }))]}
/>
) : null}
<Button type="submit">Suchen</Button>
</form>
</Card>
);
}
export function thumbnailUrl(assetId: string): string { export function thumbnailUrl(assetId: string): string {
return `/api/assets/${encodeURIComponent(assetId)}/thumbnail`; return `/api/assets/${encodeURIComponent(assetId)}/thumbnail`;
} }
+10 -12
View File
@@ -3,6 +3,8 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { useEffect, useState, type CSSProperties } from "react"; import { useEffect, useState, type CSSProperties } from "react";
import { EmptyState, IconButton } from "@sakaniui/react";
import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons";
import { UsageDialog } from "@/components/download/usage-dialog"; import { UsageDialog } from "@/components/download/usage-dialog";
import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton"; import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
@@ -56,9 +58,11 @@ export function PhotoGallery({
if (items.length === 0) { if (items.length === 0) {
return ( return (
<p className="catalog-empty"> <EmptyState
Keine Fotos passen zu dieser Suche. Ändern Sie den Suchbegriff oder wählen Sie ein anderes Album. type="no-results"
</p> title="Keine Treffer"
description="Keine Fotos passen zu dieser Suche. Ändern Sie den Suchbegriff oder wählen Sie ein anderes Album."
/>
); );
} }
@@ -152,18 +156,12 @@ function PhotoLightbox({
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined); const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
return ( return (
<div className="photo-lightbox" role="dialog" aria-modal="true" aria-label={asset.originalFileName}> <div className="photo-lightbox" role="dialog" aria-modal="true" aria-label={asset.originalFileName}>
<button className="lightbox-close" type="button" onClick={onClose} aria-label="Schließen"> <IconButton className="lightbox-close" icon={IconX} variant="secondary" onClick={onClose} aria-label="Schließen" />
✕
</button>
{hasPrev ? ( {hasPrev ? (
<button className="lightbox-nav lightbox-prev" type="button" onClick={onPrev} aria-label="Vorheriges Bild"> <IconButton className="lightbox-nav lightbox-prev" icon={IconChevronLeft} variant="secondary" size="lg" onClick={onPrev} aria-label="Vorheriges Bild" />
‹
</button>
) : null} ) : null}
{hasNext ? ( {hasNext ? (
<button className="lightbox-nav lightbox-next" type="button" onClick={onNext} aria-label="Nächstes Bild"> <IconButton className="lightbox-nav lightbox-next" icon={IconChevronRight} variant="secondary" size="lg" onClick={onNext} aria-label="Nächstes Bild" />
›
</button>
) : null} ) : null}
<figure className="lightbox-figure"> <figure className="lightbox-figure">
<img alt={asset.originalFileName} className="lightbox-image" src={thumbnailUrl(asset.id)} /> <img alt={asset.originalFileName} className="lightbox-image" src={thumbnailUrl(asset.id)} />
@@ -1,4 +1,6 @@
import { Megaphone } from "lucide-react"; import { IconSpeakerphone } from "@sakaniui/react/icons";
import { Alert } from "@/components/ui/sakani";
import { formatIsoDateGerman, type Announcement } from "./service"; import { formatIsoDateGerman, type Announcement } from "./service";
@@ -10,21 +12,15 @@ export function AnnouncementBanner({ items }: { items: Announcement[] }) {
} }
return ( return (
<div className="space-y-3" role="status"> <div className="flex flex-col gap-3 [&_[role=alert]]:whitespace-pre-line">
{items.map((item) => ( {items.map((item) => (
<div <Alert
key={item.id} key={item.id}
className="bg-primary/10 border border-primary/30 rounded-xl p-4 flex gap-3" color="neutral"
> icon={<IconSpeakerphone size={18} />}
<Megaphone className="h-5 w-5 shrink-0 text-primary-600 mt-0.5" aria-hidden="true" /> title="Hinweis von Leon Tonhäuser Sportfotografie"
<div className="min-w-0 space-y-0.5"> description={`${item.message}\nbezogen auf den ${formatIsoDateGerman(item.eventDate)}`}
<p className="text-sm font-semibold">Hinweis von Leon Tonhäuser Sportfotografie</p> />
<p className="text-sm whitespace-pre-line break-words">{item.message}</p>
<p className="text-xs text-muted-foreground">
bezogen auf den {formatIsoDateGerman(item.eventDate)}
</p>
</div>
</div>
))} ))}
</div> </div>
); );
+15 -3
View File
@@ -3,12 +3,12 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest"; import { afterEach, expect, test, vi } from "vitest";
const { resetPassword } = vi.hoisted(() => ({ resetPassword: vi.fn() })); const { resetPassword, signInEmail } = vi.hoisted(() => ({ resetPassword: vi.fn(), signInEmail: vi.fn() }));
vi.mock("./client", () => ({ vi.mock("./client", () => ({
authClient: { resetPassword }, authClient: { resetPassword, signIn: { email: signInEmail } },
})); }));
import { PasswordResetForm, RegistrationForm } from "./public-forms"; import { LoginForm, PasswordResetForm, RegistrationForm } from "./public-forms";
afterEach(cleanup); afterEach(cleanup);
@@ -77,3 +77,15 @@ test("does not claim success when the reset link is invalid", async () => {
); );
expect(screen.queryByText(/erfolgreich aktualisiert/i)).toBeNull(); expect(screen.queryByText(/erfolgreich aktualisiert/i)).toBeNull();
}); });
test("the two-factor step starts with an empty code field, never the typed password", async () => {
signInEmail.mockResolvedValueOnce({ data: { twoFactorRedirect: true }, error: null });
render(<LoginForm />);
fireEvent.change(screen.getByLabelText("E-Mail-Adresse"), { target: { value: "admin@example.test" } });
fireEvent.change(screen.getByLabelText("Passwort"), { target: { value: "geheim-passwort" } });
fireEvent.submit(screen.getByLabelText("Passwort").closest("form")!);
const code = (await screen.findByLabelText("Zwei-Faktor-Code")) as HTMLInputElement;
expect(code.value).toBe("");
});
+45 -106
View File
@@ -2,6 +2,8 @@
import { type FormEvent, useActionState, useState } from "react"; import { type FormEvent, useActionState, useState } from "react";
import { Alert, Button, Input } from "@sakaniui/react";
import { authClient } from "./client"; import { authClient } from "./client";
export type RegistrationFormState = { export type RegistrationFormState = {
@@ -47,59 +49,18 @@ export function RegistrationForm({
const [state, formAction, pending] = useActionState(action, initialRegistrationState); const [state, formAction, pending] = useActionState(action, initialRegistrationState);
return ( return (
<form action={formAction} className="account-form"> <form action={formAction} className="flex flex-col gap-6">
<FieldError message={state.errors?.form} /> <FieldError message={state.errors?.form} />
<div className="form-grid"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<label> <Input label="Redaktion oder Unternehmen" autoComplete="organization" name="companyName" required error={state.errors?.companyName} />
Redaktion oder Unternehmen <Input label="Ansprechpartner:in" autoComplete="name" name="contactName" required error={state.errors?.contactName} />
<input autoComplete="organization" name="companyName" required /> <Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" error={state.errors?.email} />
</label> <Input label="Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" error={state.errors?.password} />
<FieldError message={state.errors?.companyName} /> <Input label="Straße und Hausnummer" autoComplete="address-line1" name="addressLine1" required error={state.errors?.addressLine1} />
<label> <Input label="Adresszusatz" autoComplete="address-line2" name="addressLine2" />
Ansprechpartner:in <Input label="Postleitzahl" autoComplete="postal-code" name="postalCode" required error={state.errors?.postalCode} />
<input autoComplete="name" name="contactName" required /> <Input label="Ort" autoComplete="address-level2" name="city" required error={state.errors?.city} />
</label> <Input label="Land (ISO-Code)" autoComplete="country" defaultValue="DE" maxLength={2} name="countryCode" required error={state.errors?.countryCode} />
<FieldError message={state.errors?.contactName} />
<label>
E-Mail-Adresse
<input autoComplete="email" name="email" required type="email" />
</label>
<FieldError message={state.errors?.email} />
<label>
Passwort
<input autoComplete="new-password" minLength={12} name="password" required type="password" />
</label>
<FieldError message={state.errors?.password} />
<label>
Straße und Hausnummer
<input autoComplete="address-line1" name="addressLine1" required />
</label>
<FieldError message={state.errors?.addressLine1} />
<label>
Adresszusatz
<input autoComplete="address-line2" name="addressLine2" />
</label>
<label>
Postleitzahl
<input autoComplete="postal-code" name="postalCode" required />
</label>
<FieldError message={state.errors?.postalCode} />
<label>
Ort
<input autoComplete="address-level2" name="city" required />
</label>
<FieldError message={state.errors?.city} />
<label>
Land (ISO-Code)
<input
autoComplete="country"
defaultValue="DE"
maxLength={2}
name="countryCode"
required
/>
</label>
<FieldError message={state.errors?.countryCode} />
</div> </div>
<fieldset className="acknowledgements"> <fieldset className="acknowledgements">
@@ -133,10 +94,10 @@ export function RegistrationForm({
<FieldError message={state.errors?.privacyAcknowledged} /> <FieldError message={state.errors?.privacyAcknowledged} />
</fieldset> </fieldset>
<button className="primary-action" disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Registrierung wird gesendet …" : "Registrierung senden"} {pending ? "Registrierung wird gesendet …" : "Registrierung senden"}
</button> </Button>
<p className="form-note"> <p className="text-sm text-[var(--color-fg-muted)]">
Wir informieren Sie auf der nächsten Seite über den weiteren Ablauf. Wir informieren Sie auf der nächsten Seite über den weiteren Ablauf.
</p> </p>
</form> </form>
@@ -191,46 +152,31 @@ export function LoginForm() {
window.location.assign(result.data?.url ?? "/"); window.location.assign(result.data?.url ?? "/");
} }
// Distinct keys: without them React reuses the password <input> for the
// TOTP field and would show the typed password in clear text.
if (awaitingTwoFactor) { if (awaitingTwoFactor) {
return ( return (
<form className="account-form" onSubmit={submit}> <form className="flex flex-col gap-4" key="totp" onSubmit={submit}>
<p className="form-note"> <p className="text-sm text-[var(--color-fg-muted)]">
Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein. Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein.
</p> </p>
<label> <Input label="Zwei-Faktor-Code" autoComplete="one-time-code" inputMode="numeric" maxLength={6} name="totp" pattern="[0-9]*" required type="text" />
Zwei-Faktor-Code
<input
autoComplete="one-time-code"
inputMode="numeric"
maxLength={6}
name="totp"
pattern="[0-9]*"
required
type="text"
/>
</label>
<FieldError message={error} /> <FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Anmelden"} {pending ? "Code wird geprüft …" : "Anmelden"}
</button> </Button>
</form> </form>
); );
} }
return ( return (
<form className="account-form" onSubmit={submit}> <form className="flex flex-col gap-4" key="credentials" onSubmit={submit}>
<label> <Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
E-Mail-Adresse <Input label="Passwort" autoComplete="current-password" name="password" required type="password" />
<input autoComplete="email" name="email" required type="email" />
</label>
<label>
Passwort
<input autoComplete="current-password" name="password" required type="password" />
</label>
<FieldError message={error} /> <FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Anmeldung wird geprüft …" : "Anmelden"} {pending ? "Anmeldung wird geprüft …" : "Anmelden"}
</button> </Button>
</form> </form>
); );
} }
@@ -257,21 +203,18 @@ export function PasswordResetRequestForm() {
if (submitted) { if (submitted) {
return ( return (
<p className="form-note" role="status"> <div role="status">
Falls ein Zugang zu dieser Adresse gehört, erhalten Sie in Kürze weitere Hinweise. <Alert color="info" description="Falls ein Zugang zu dieser Adresse gehört, erhalten Sie in Kürze weitere Hinweise." />
</p> </div>
); );
} }
return ( return (
<form className="account-form" onSubmit={submit}> <form className="flex flex-col gap-4" onSubmit={submit}>
<label> <Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
E-Mail-Adresse <Button disabled={pending} type="submit">
<input autoComplete="email" name="email" required type="email" />
</label>
<button className="primary-action" disabled={pending} type="submit">
{pending ? "Anfrage wird gesendet …" : "Link anfordern"} {pending ? "Anfrage wird gesendet …" : "Link anfordern"}
</button> </Button>
</form> </form>
); );
} }
@@ -306,9 +249,12 @@ export function PasswordResetForm({ token }: { token?: string }) {
if (success) { if (success) {
return ( return (
<div className="form-note" role="status"> <div className="flex flex-col items-start gap-4" role="status">
<p>Ihr Passwort wurde erfolgreich aktualisiert. Sie können sich jetzt damit anmelden.</p> <p>Ihr Passwort wurde erfolgreich aktualisiert. Sie können sich jetzt damit anmelden.</p>
<a className="primary-action" href="/anmelden"> <a
className="inline-flex h-10 items-center rounded-[var(--radius-md)] bg-[var(--color-accent-default)] px-4 text-sm font-medium text-[var(--color-accent-fg)] hover:bg-[var(--color-accent-hover)]"
href="/anmelden"
>
Jetzt anmelden Jetzt anmelden
</a> </a>
</div> </div>
@@ -316,15 +262,12 @@ export function PasswordResetForm({ token }: { token?: string }) {
} }
return ( return (
<form className="account-form" onSubmit={submit}> <form className="flex flex-col gap-4" onSubmit={submit}>
<label> <Input label="Neues Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" />
Neues Passwort
<input autoComplete="new-password" minLength={12} name="password" required type="password" />
</label>
<FieldError message={error} /> <FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit"> <Button disabled={pending} type="submit">
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"} {pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
</button> </Button>
</form> </form>
); );
} }
@@ -353,11 +296,7 @@ function loginErrorMessage(code: string | undefined): string {
} }
function FieldError({ message }: { message?: string }) { function FieldError({ message }: { message?: string }) {
return message ? ( return message ? <Alert color="danger" description={message} /> : null;
<p className="field-error" role="alert">
{message}
</p>
) : null;
} }
function readText(formData: FormData, name: string): string { function readText(formData: FormData, name: string): string {
+8 -14
View File
@@ -3,8 +3,8 @@
import { useActionState } from "react"; import { useActionState } from "react";
import { approveEditorialAction, type ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions"; import { approveEditorialAction, type ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Alert, Input } from "@/components/ui/sakani";
import { Check } from "lucide-react"; import { IconCheck } from "@sakaniui/react/icons";
export function ApproveForm({ editorialId }: { editorialId: string }) { export function ApproveForm({ editorialId }: { editorialId: string }) {
const [state, formAction, pending] = useActionState<ApproveActionResult, FormData>( const [state, formAction, pending] = useActionState<ApproveActionResult, FormData>(
@@ -13,12 +13,9 @@ export function ApproveForm({ editorialId }: { editorialId: string }) {
); );
return ( return (
<form action={formAction} className="flex flex-col sm:flex-row gap-4 items-start sm:items-center"> <form action={formAction} className="flex flex-col gap-4 sm:flex-row sm:items-end">
<div className="flex gap-2 items-center"> <Input
<label htmlFor="priceEuros" className="text-sm font-medium whitespace-nowrap"> label="Individueller Nettopreis (€)"
Individueller Nettopreis (€)
</label>
<Input
id="priceEuros" id="priceEuros"
name="priceEuros" name="priceEuros"
type="number" type="number"
@@ -26,15 +23,12 @@ export function ApproveForm({ editorialId }: { editorialId: string }) {
min="0.01" min="0.01"
required required
placeholder="z.B. 15.00" placeholder="z.B. 15.00"
className="w-32 bg-background"
disabled={pending} disabled={pending}
/> />
</div> <Button type="submit" disabled={pending} leftIcon={<IconCheck size={16} />}>
<Button type="submit" disabled={pending}> {pending ? "Wird freigegeben …" : "Redaktion freigeben"}
<Check className="w-4 h-4 mr-2" />
{pending ? "Wird freigegeben..." : "Redaktion freigeben"}
</Button> </Button>
{!state.ok && <p className="text-sm text-destructive font-medium">{state.message}</p>} {!state.ok && <Alert color="danger" description={state.message} />}
</form> </form>
); );
} }
+8 -18
View File
@@ -4,7 +4,7 @@ import { useState, useTransition } from "react";
import { archiveEditorialAction, hardDeleteEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; import { archiveEditorialAction, hardDeleteEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Alert, Input } from "@/components/ui/sakani";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
type DangerZoneProps = { type DangerZoneProps = {
@@ -42,29 +42,24 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
} }
return ( return (
<Card className="border-destructive/50 bg-destructive/5 dark:bg-destructive/10"> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-destructive">Gefahrenzone</CardTitle> <CardTitle className="text-[var(--color-danger-fg)]">Gefahrenzone</CardTitle>
<CardDescription> <CardDescription>
Archivieren widerruft alle Albumrechte und deaktiviert den Login. Archivieren widerruft alle Albumrechte und deaktiviert den Login.
Endgültiges Löschen entfernt den Account inklusive aller verknüpften Daten unwiderruflich! Endgültiges Löschen entfernt den Account inklusive aller verknüpften Daten unwiderruflich!
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="flex flex-col gap-4">
<div className="space-y-2"> <Input
<label className="text-sm font-medium"> label="Redaktionsname zur Bestätigung eingeben:"
Redaktionsname zur Bestätigung eingeben:
</label>
<Input
type="text" type="text"
value={confirmText} value={confirmText}
onChange={(e) => setConfirmText(e.target.value)} onChange={(e) => setConfirmText(e.target.value)}
placeholder={editorialName} placeholder={editorialName}
disabled={isPending} disabled={isPending}
className="border-destructive/30 focus-visible:ring-destructive"
/> />
</div> <div className="flex flex-wrap gap-3">
<div className="flex gap-4">
<Button <Button
type="button" type="button"
variant="destructive" variant="destructive"
@@ -76,18 +71,13 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
className="border-destructive text-destructive hover:bg-destructive hover:text-white"
disabled={!isConfirmed || isPending} disabled={!isConfirmed || isPending}
onClick={handleDelete} onClick={handleDelete}
> >
{isDeleting ? "Wird gelöscht…" : "Endgültig löschen"} {isDeleting ? "Wird gelöscht…" : "Endgültig löschen"}
</Button> </Button>
</div> </div>
{result && !result.ok && ( {result && !result.ok && <Alert color="danger" description={result.message} />}
<p className="text-sm text-destructive" role="alert">
{result.message}
</p>
)}
</CardContent> </CardContent>
</Card> </Card>
); );
+5 -13
View File
@@ -4,7 +4,7 @@ import { useState, useTransition } from "react";
import { resetUsageDataAction } from "@/app/admin/redaktionen/[id]/actions"; import { resetUsageDataAction } from "@/app/admin/redaktionen/[id]/actions";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Alert, Input } from "@/components/ui/sakani";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
type ResetUsageCardProps = { type ResetUsageCardProps = {
@@ -39,19 +39,15 @@ export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardPro
bleiben unverändert. bleiben unverändert.
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="flex flex-col gap-4">
<div className="space-y-2"> <Input
<label className="text-sm font-medium"> label="Redaktionsname zur Bestätigung eingeben:"
Redaktionsname zur Bestätigung eingeben:
</label>
<Input
type="text" type="text"
value={confirmText} value={confirmText}
onChange={(e) => setConfirmText(e.target.value)} onChange={(e) => setConfirmText(e.target.value)}
placeholder={editorialName} placeholder={editorialName}
disabled={isPending} disabled={isPending}
/> />
</div>
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button <Button
type="button" type="button"
@@ -61,11 +57,7 @@ export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardPro
> >
{isPending ? "Wird zurückgesetzt…" : "Nutzungsdaten zurücksetzen"} {isPending ? "Wird zurückgesetzt…" : "Nutzungsdaten zurücksetzen"}
</Button> </Button>
{result && ( {result && <Alert color={result.ok ? "success" : "danger"} description={result.message} />}
<p className={`text-sm ${result.ok ? "text-muted-foreground" : "text-destructive"}`}>
{result.message}
</p>
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
+59 -60
View File
@@ -1,7 +1,8 @@
import Link from "next/link"; import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; 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 } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone"; import { DangerZone } from "./DangerZone";
import { ResetUsageCard } from "./ResetUsageCard"; import { ResetUsageCard } from "./ResetUsageCard";
@@ -26,17 +27,19 @@ export function EditorialDetailContent({
hasActiveGrant, hasActiveGrant,
}: Readonly<{ editorial: EditorialDetail; hasActiveGrant: boolean }>) { }: Readonly<{ editorial: EditorialDetail; hasActiveGrant: boolean }>) {
return ( return (
<div className="space-y-8 max-w-4xl animate-in fade-in slide-in-from-bottom-4 duration-500"> <section className="flex max-w-4xl flex-col gap-6">
<div> <PageHeader kicker="Redaktion" title={editorial.name}>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion</p> <Button asChild variant="outline">
<h1 className="text-4xl font-bold tracking-tight">{editorial.name}</h1> <Link href="/admin/redaktionen">Alle Redaktionen</Link>
</div> </Button>
</PageHeader>
{editorial.archivedAt && ( {editorial.archivedAt && (
<div className="space-y-4"> <div className="space-y-4">
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status"> <Alert
Diese Redaktion wurde am {new Date(editorial.archivedAt).toLocaleDateString('de-DE')} archiviert. color="danger"
</div> description={`Diese Redaktion wurde am ${new Date(editorial.archivedAt).toLocaleDateString("de-DE")} archiviert.`}
/>
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Archivierung aufheben</CardTitle> <CardTitle>Archivierung aufheben</CardTitle>
@@ -73,7 +76,7 @@ export function EditorialDetailContent({
</div> </div>
<div> <div>
<dt className="text-sm font-medium text-muted-foreground">Status</dt> <dt className="text-sm font-medium text-muted-foreground">Status</dt>
<dd className="mt-1 font-medium capitalize">{editorial.status}</dd> <dd className="mt-1"><Badge variant={STATUS[editorial.status]?.variant ?? "neutral"}>{STATUS[editorial.status]?.label ?? editorial.status}</Badge></dd>
</div> </div>
<div> <div>
<dt className="text-sm font-medium text-muted-foreground">E-Mail bestätigt</dt> <dt className="text-sm font-medium text-muted-foreground">E-Mail bestätigt</dt>
@@ -108,14 +111,13 @@ export function EditorialDetailContent({
Redaktion freigeben Redaktion freigeben
</Button> </Button>
) : null} ) : null}
<div className="flex gap-4 text-sm font-medium"> <div className="flex flex-wrap gap-3">
<Link href={`/admin/redaktionen/${editorial.id}/alben`} className="text-primary-600 hover:underline"> <Button asChild variant="outline">
Albumrechte verwalten <Link href={`/admin/redaktionen/${editorial.id}/alben`}>Albumrechte verwalten</Link>
</Link> </Button>
<span className="text-muted-foreground">·</span> <Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`} className="text-primary-600 hover:underline"> <Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln</Link>
Auto-Zuweisungsregeln </Button>
</Link>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -127,56 +129,47 @@ export function EditorialDetailContent({
<CardDescription>Pauschalpreis für Downloads aktivieren.</CardDescription> <CardDescription>Pauschalpreis für Downloads aktivieren.</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form action={updateFlatrateAction.bind(null, editorial.id)} className="space-y-6"> <form action={updateFlatrateAction.bind(null, editorial.id)} className="flex flex-col gap-6">
<div className="flex items-center space-x-2"> <Checkbox
<input defaultChecked={editorial.flatrateActive}
type="checkbox" id="flatrateActive"
name="flatrateActive" label="Flatrate aktivieren"
id="flatrateActive" name="flatrateActive"
defaultChecked={editorial.flatrateActive} />
className="w-4 h-4 rounded border-border text-primary-600 focus:ring-primary-500" <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Input
defaultValue={editorial.flatratePriceCents ? (editorial.flatratePriceCents / 100).toFixed(2) : ""}
id="flatratePriceEuros"
label="Flatrate-Preis (Netto €)"
min="0"
name="flatratePriceEuros"
step="0.01"
type="number"
/>
<Input
defaultValue={editorial.flatrateAssetLimit ?? ""}
description="Leer lassen für unbegrenzte Flatrate."
id="flatrateAssetLimit"
label="Bild-Limit (pro Monat)"
min="1"
name="flatrateAssetLimit"
placeholder="Unbegrenzt"
type="number"
/> />
<label htmlFor="flatrateActive" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
Flatrate aktivieren
</label>
</div> </div>
<div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="flatratePriceEuros">Flatrate-Preis (Netto €)</label>
<Input
type="number"
id="flatratePriceEuros"
name="flatratePriceEuros"
step="0.01"
min="0"
defaultValue={editorial.flatratePriceCents ? (editorial.flatratePriceCents / 100).toFixed(2) : ""}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="flatrateAssetLimit">Bild-Limit (pro Monat)</label>
<Input
type="number"
id="flatrateAssetLimit"
name="flatrateAssetLimit"
min="1"
placeholder="Unbegrenzt"
defaultValue={editorial.flatrateAssetLimit ?? ""}
/>
<p className="text-xs text-muted-foreground">Leer lassen für unbegrenzte Flatrate.</p>
</div>
</div>
<Button type="submit"> <Button type="submit">
Speichern Speichern
</Button> </Button>
</div>
</form> </form>
</CardContent> </CardContent>
</Card> </Card>
)} )}
{!editorial.archivedAt && ( {!editorial.archivedAt && (
<Card className="border-border"> <Card>
<CardHeader> <CardHeader>
<CardTitle>Status-Aktionen</CardTitle> <CardTitle>Status-Aktionen</CardTitle>
</CardHeader> </CardHeader>
@@ -204,10 +197,16 @@ export function EditorialDetailContent({
{!editorial.archivedAt && ( {!editorial.archivedAt && (
<DangerZone editorialId={editorial.id} editorialName={editorial.name} /> <DangerZone editorialId={editorial.id} editorialName={editorial.name} />
)} )}
</div> </section>
); );
} }
const STATUS: Record<string, { label: string; variant: "success" | "warning" | "danger" }> = {
active: { label: "Aktiv", variant: "success" },
pending_approval: { label: "Ausstehend", variant: "warning" },
suspended: { label: "Gesperrt", variant: "danger" },
};
function formatCents(cents: number): string { function formatCents(cents: number): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100); return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
} }
+37
View File
@@ -0,0 +1,37 @@
// Browser APIs Sakani components call that jsdom lacks. No-op in node tests.
if (typeof window !== "undefined") {
window.matchMedia ??= (query: string) =>
({
matches: false,
media: query,
onchange: null,
addEventListener() {},
removeEventListener() {},
addListener() {},
removeListener() {},
dispatchEvent: () => false,
}) as MediaQueryList;
// jsdom has <dialog> but not its modal API.
if (typeof HTMLDialogElement !== "undefined" && !HTMLDialogElement.prototype.showModal) {
Object.defineProperty(HTMLDialogElement.prototype, "showModal", {
configurable: true,
value(this: HTMLDialogElement) {
this.setAttribute("open", "");
},
});
Object.defineProperty(HTMLDialogElement.prototype, "close", {
configurable: true,
value(this: HTMLDialogElement) {
this.removeAttribute("open");
this.dispatchEvent(new Event("close"));
},
});
}
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
};
}
+1
View File
@@ -13,6 +13,7 @@ export default defineConfig({
}, },
test: { test: {
environment: "node", environment: "node",
setupFiles: ["src/test/dom-shims.ts"],
env: { env: {
DATABASE_URL: "postgres://db/portal", DATABASE_URL: "postgres://db/portal",
BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters", BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters",