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
# POST /api/cron/album-sync (Authorization: Bearer <CRON_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` |
| `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` |
| `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/ready` -> 200 OK (Database & Immich connectivity).
- **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": {
"@better-auth/drizzle-adapter": "^1.6.26",
"@fontsource-variable/geist": "^5.3.0",
"@js-temporal/polyfill": "^0.5.1",
"@radix-ui/react-slot": "^1.3.3",
"@sakaniui/react": "^0.23.0",
"archiver": "^8.0.0",
"better-auth": "^1.6.26",
"clsx": "^2.1.1",
"drizzle-orm": "^0.45.2",
"lucide-react": "^1.31.0",
"next": "^16.3.0",
"next-themes": "^0.4.6",
"nodemailer": "^9.0.5",
@@ -31,7 +32,6 @@
"pg": "^8.22.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"recharts": "^3.10.1",
"server-only": "^0.0.1",
"sharp": "^0.35.3",
"tailwind-merge": "^3.6.0",
+28 -15
View File
@@ -11,12 +11,18 @@ importers:
'@better-auth/drizzle-adapter':
specifier: ^1.6.26
version: 1.6.26(@better-auth/core@1.6.26(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.8)(kysely@0.29.4)(nanostores@1.4.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0))
'@fontsource-variable/geist':
specifier: ^5.3.0
version: 5.3.0
'@js-temporal/polyfill':
specifier: ^0.5.1
version: 0.5.1
'@radix-ui/react-slot':
specifier: ^1.3.3
version: 1.3.3(@types/react@19.2.18)(react@19.2.8)
'@sakaniui/react':
specifier: ^0.23.0
version: 0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
archiver:
specifier: ^8.0.0
version: 8.0.0
@@ -29,9 +35,6 @@ importers:
drizzle-orm:
specifier: ^0.45.2
version: 0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0)
lucide-react:
specifier: ^1.31.0
version: 1.31.0(react@19.2.8)
next:
specifier: ^16.3.0
version: 16.3.0(@babel/core@7.29.7)(@playwright/test@1.62.1)(@types/node@24.13.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
@@ -53,9 +56,6 @@ importers:
react-dom:
specifier: ^19.2.8
version: 19.2.8(react@19.2.8)
recharts:
specifier: ^3.10.1
version: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
server-only:
specifier: ^0.0.1
version: 0.0.1
@@ -875,6 +875,9 @@ packages:
'@noble/hashes':
optional: true
'@fontsource-variable/geist@5.3.0':
resolution: {integrity: sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA==}
'@grpc/grpc-js@1.14.4':
resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
engines: {node: '>=12.10.0'}
@@ -1492,6 +1495,13 @@ packages:
'@rtsao/scc@1.1.0':
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
'@sakaniui/react@0.23.0':
resolution: {integrity: sha512-9BnsvgacsDaERq0lQZNHuqNwfCSNhiPSkQLQMhH0mRSJ9K0I9Jz0Ht4W5HifuMAWnCwb3J6aZUEV6wpn7hk/kw==}
hasBin: true
peerDependencies:
react: ^19.0.0
react-dom: ^19.0.0
'@standard-schema/spec@1.1.0':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -3462,11 +3472,6 @@ packages:
lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
lucide-react@1.31.0:
resolution: {integrity: sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
lz-string@1.5.0:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
@@ -5090,6 +5095,8 @@ snapshots:
optionalDependencies:
'@noble/hashes': 2.3.0
'@fontsource-variable/geist@5.3.0': {}
'@grpc/grpc-js@1.14.4':
dependencies:
'@grpc/proto-loader': 0.8.1
@@ -5530,6 +5537,16 @@ snapshots:
'@rtsao/scc@1.1.0': {}
'@sakaniui/react@0.23.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)':
dependencies:
react: 19.2.8
react-dom: 19.2.8(react@19.2.8)
recharts: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
transitivePeerDependencies:
- '@types/react'
- react-is
- redux
'@standard-schema/spec@1.1.0': {}
'@standard-schema/utils@0.3.0': {}
@@ -7578,10 +7595,6 @@ snapshots:
dependencies:
yallist: 3.1.1
lucide-react@1.31.0(react@19.2.8):
dependencies:
react: 19.2.8
lz-string@1.5.0: {}
magic-string@0.30.21:
+13 -18
View File
@@ -1,26 +1,21 @@
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { LoginForm } from "@/modules/auth/public-forms";
export default function LoginPage() {
return (
<main className="public-account-page">
<header className="masthead">
<Link className="wordmark" href="/">
Leon Tonhäuser
</Link>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="login-title">
<p className="eyebrow">Zugang</p>
<h1 id="login-title">Anmelden</h1>
<p className="lede">Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an.</p>
<LoginForm />
<nav className="account-links" aria-label="Zugang verwalten">
<Link href="/passwort-vergessen">Passwort vergessen?</Link>
<Link href="/registrieren">Neue Redaktion registrieren</Link>
</nav>
</section>
</main>
<PublicShell
kicker="Zugang"
title="Anmelden"
titleId="login-title"
lede="Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an."
>
<LoginForm />
<nav aria-label="Zugang verwalten" className="flex flex-wrap justify-between gap-x-4 gap-y-2 text-sm">
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/passwort-vergessen">Passwort vergessen?</Link>
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/registrieren">Neue Redaktion registrieren</Link>
</nav>
</PublicShell>
);
}
+7 -17
View File
@@ -1,25 +1,15 @@
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { PasswordResetRequestForm } from "@/modules/auth/public-forms";
export default function ForgotPasswordPage() {
return (
<main className="public-account-page">
<header className="masthead">
<Link className="wordmark" href="/">
Leon Tonhäuser
</Link>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="forgot-password-title">
<p className="eyebrow">Zugang</p>
<h1 id="forgot-password-title">Passwort vergessen?</h1>
<p className="lede">Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.</p>
<PasswordResetRequestForm />
<nav className="account-links" aria-label="Zurück zur Anmeldung">
<Link href="/anmelden">Zur Anmeldung</Link>
</nav>
</section>
</main>
<PublicShell kicker="Zugang" title="Passwort vergessen?" titleId="forgot-password-title" lede="Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.">
<PasswordResetRequestForm />
<nav aria-label="Zurück zur Anmeldung" className="text-sm">
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
</nav>
</PublicShell>
);
}
@@ -1,5 +1,6 @@
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { PasswordResetForm } from "@/modules/auth/public-forms";
export default async function ResetPasswordPage({
@@ -10,22 +11,11 @@ export default async function ResetPasswordPage({
const { token } = await searchParams;
return (
<main className="public-account-page">
<header className="masthead">
<Link className="wordmark" href="/">
Leon Tonhäuser
</Link>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="reset-password-title">
<p className="eyebrow">Zugang</p>
<h1 id="reset-password-title">Neues Passwort setzen</h1>
<p className="lede">Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.</p>
<PasswordResetForm token={token} />
<nav className="account-links" aria-label="Zurück zur Anmeldung">
<Link href="/anmelden">Zur Anmeldung</Link>
</nav>
</section>
</main>
<PublicShell kicker="Zugang" title="Neues Passwort setzen" titleId="reset-password-title" lede="Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.">
<PasswordResetForm token={token} />
<nav aria-label="Zurück zur Anmeldung" className="text-sm">
<Link className="font-medium text-[var(--color-brand-fg)] hover:underline" href="/anmelden">Zur Anmeldung</Link>
</nav>
</PublicShell>
);
}
@@ -1,25 +1,21 @@
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { Button } from "@/components/ui/button";
export default function RegistrationConfirmedPage() {
return (
<main className="public-account-page">
<header className="masthead">
<Link className="wordmark" href="/">
Leon Tonhäuser
</Link>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="confirmation-title">
<p className="eyebrow">Registrierung</p>
<h1 id="confirmation-title">Vielen Dank.</h1>
<p className="lede">
Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach
prüfen wir Ihre Registrierung.
</p>
<Link className="primary-action" href="/anmelden">
Zur Anmeldung
</Link>
</section>
</main>
<PublicShell
kicker="Registrierung"
title="Vielen Dank."
titleId="confirmation-title"
lede="Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach prüfen wir Ihre Registrierung."
>
<div>
<Button asChild>
<Link href="/anmelden">Zur Anmeldung</Link>
</Button>
</div>
</PublicShell>
);
}
+17 -24
View File
@@ -1,7 +1,7 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { PublicShell } from "@/components/layout/public-shell";
import { env } from "@/config/env";
import { registerEditorial } from "@/modules/auth/auth";
import {
@@ -16,29 +16,22 @@ import { RateLimitExceededError } from "@/modules/security/rate-limit-guard";
export default function RegistrationPage() {
return (
<main className="public-account-page">
<header className="masthead">
<Link className="wordmark" href="/">
Leon Tonhäuser
</Link>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel account-panel-wide" aria-labelledby="registration-title">
<p className="eyebrow">B2B-Zugang</p>
<h1 id="registration-title">Redaktion registrieren</h1>
<p className="lede">
Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung.
</p>
<RegistrationForm
action={registerAction}
legalUrls={{
imprint: env.LEGAL_IMPRINT_URL,
privacy: env.LEGAL_PRIVACY_URL,
terms: env.LEGAL_TERMS_URL,
}}
/>
</section>
</main>
<PublicShell
kicker="B2B-Zugang"
title="Redaktion registrieren"
titleId="registration-title"
lede="Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung."
wide
>
<RegistrationForm
action={registerAction}
legalUrls={{
imprint: env.LEGAL_IMPRINT_URL,
privacy: env.LEGAL_PRIVACY_URL,
terms: env.LEGAL_TERMS_URL,
}}
/>
</PublicShell>
);
}
@@ -2,6 +2,11 @@
import { useMemo, useState } from "react";
import Link from "next/link";
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import { Card, FormSelect } from "@/components/ui/sakani";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
import { formatCents } from "@/modules/billing/format";
@@ -40,6 +45,12 @@ const STATUS_LABELS: Record<BillingPosition["status"], string> = {
reopened: "Wiedereröffnet",
};
const STATUS_BADGES: Record<BillingPosition["status"], "warning" | "success"> = {
open: "warning",
billed: "success",
reopened: "warning",
};
const REPORT_STATUS_LABELS: Record<string, string> = {
draft: "Entwurf",
final: "Erstellt",
@@ -172,178 +183,162 @@ export function BillingSelection({
<>
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
<div className="billing-selection-controls">
<button type="button" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
<div className="flex flex-wrap items-center gap-3">
<Button type="button" variant="secondary" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
</button>
{isQuarter ? (
<Link href={monthHref} className="billing-nav-link">
Monatsansicht
</Link>
) : (
<Link href={quarterHref} className="billing-nav-link">
Ganzes Quartal
</Link>
)}
<button type="button" onClick={clearSelection} disabled={selectedCount === 0}>
</Button>
<Button asChild variant="outline">
{isQuarter ? <Link href={monthHref}>Monatsansicht</Link> : <Link href={quarterHref}>Ganzes Quartal</Link>}
</Button>
<Button type="button" variant="ghost" onClick={clearSelection} disabled={selectedCount === 0}>
Auswahl aufheben
</button>
</Button>
<p className="ml-auto text-sm text-[var(--color-fg-muted)]" aria-live="polite">
Zeitraum: {periodLabel}
</p>
</div>
<p className="billing-period-label" aria-live="polite">
Zeitraum: {periodLabel}
</p>
{positions.length === 0 ? (
<p className="billing-empty">Keine abrechenbaren Nutzungen in diesem Zeitraum.</p>
) : (
<table className="billing-table">
<caption className="billing-caption">
Abrechenbare Nutzungen
</caption>
<thead>
<tr>
<th scope="col">Auswahl</th>
<th scope="col">Datei</th>
<th scope="col">Album</th>
<th scope="col">Zweck</th>
<th scope="col">Referenz</th>
<th scope="col">Preis</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{positions.map((position) => (
<tr key={position.id} className={position.selectable ? "" : "billing-row-billed"}>
<td>
<input
type="checkbox"
checked={selectedIds.has(position.id)}
onChange={() => togglePosition(position.id)}
disabled={!position.selectable}
<section className="flex flex-col gap-3" aria-labelledby="positions-title">
<h2 id="positions-title" className="text-lg font-semibold">Abrechenbare Nutzungen</h2>
{positions.length === 0 ? (
<EmptyState title="Keine abrechenbaren Nutzungen in diesem Zeitraum." description="Wählen Sie oben einen anderen Monat oder ein Quartal." />
) : (
<Table<BillingPosition>
rowKey={(position) => position.id}
rows={positions}
columns={[
{
key: "id",
header: "Auswahl",
render: (position) => (
<Checkbox
aria-label={`${position.filename} auswählen`}
checked={selectedIds.has(position.id)}
disabled={!position.selectable}
onChange={() => togglePosition(position.id)}
/>
</td>
<td>{position.filename}</td>
<td>{position.albumName}</td>
<td>{position.purpose}</td>
<td>{position.reference ?? "—"}</td>
<td className="billing-price">{formatCents(position.priceCents)}</td>
<td>
<span className="billing-status">
{STATUS_LABELS[position.status]}
),
},
{ key: "filename", header: "Datei" },
{ key: "albumName", header: "Album" },
{ key: "purpose", header: "Zweck" },
{ key: "reference", header: "Referenz", render: (position) => position.reference ?? "—" },
{
key: "priceCents",
header: "Preis",
align: "right",
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
},
{
key: "status",
header: "Status",
render: (position) => (
<span className="flex flex-wrap items-center gap-2">
<Badge variant={STATUS_BADGES[position.status] ?? "neutral"}>{STATUS_LABELS[position.status]}</Badge>
{position.status === "billed" && position.reportNumber !== null && (
<span className="billing-report-ref">
{" "}· Bericht Nr. {position.reportNumber}
<span className="text-xs text-[var(--color-fg-muted)]">
Bericht Nr. {position.reportNumber}
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
</span>
)}
</span>
</td>
</tr>
))}
</tbody>
</table>
)}
),
},
]}
/>
)}
</section>
{repeatDownloads.length > 0 && (
<section aria-labelledby="repeat-downloads-title" className="billing-repeat-section">
<h2 id="repeat-downloads-title">Kostenlose Wiederabrufe</h2>
<p className="form-note">
<section aria-labelledby="repeat-downloads-title" className="flex flex-col gap-3">
<h2 id="repeat-downloads-title" className="text-lg font-semibold">Kostenlose Wiederabrufe</h2>
<p className="text-sm text-[var(--color-fg-muted)]">
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
abrechenbar.
</p>
<table className="billing-table billing-table-repeat">
<caption className="billing-caption">Wiederabrufe im Zeitraum</caption>
<thead>
<tr>
<th scope="col">Datei</th>
<th scope="col">Datum</th>
<th scope="col">Status</th>
<th scope="col">Notiz</th>
</tr>
</thead>
<tbody>
{repeatDownloads.map((download) => (
<tr key={download.id}>
<td>{download.assetId}</td>
<td>
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
{download.authorizedAt.toLocaleDateString("de-DE")}
</time>
</td>
<td>{download.status}</td>
<td>{download.repeatDownloadNote ?? "—"}</td>
</tr>
))}
</tbody>
</table>
<Table<RepeatDownloadPosition>
rowKey={(download) => download.id}
rows={repeatDownloads}
columns={[
{ key: "assetId", header: "Datei" },
{
key: "authorizedAt",
header: "Datum",
render: (download) => (
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
{download.authorizedAt.toLocaleDateString("de-DE")}
</time>
),
},
{ key: "status", header: "Status" },
{ key: "repeatDownloadNote", header: "Notiz", render: (download) => download.repeatDownloadNote ?? "—" },
]}
/>
</section>
)}
<div className="billing-summary" aria-live="polite">
<p>
<strong>{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
</p>
<p className="billing-summary-total">
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
</p>
</div>
<div className="billing-actions">
<button
type="button"
onClick={handlePreview}
disabled={selectedCount === 0 || actionState.loading}
>
Vorschau
</button>
<button
type="button"
className="billing-action-primary"
onClick={handleFinalize}
disabled={selectedCount === 0 || actionState.loading}
>
Abrechnung erstellen
</button>
</div>
{actionState.message && (
<p className="billing-status-message" role={actionState.isError ? "alert" : "status"}>
{actionState.message}
</p>
)}
<Card>
<div className="flex flex-wrap items-center justify-between gap-4">
<div aria-live="polite" className="billing-summary flex flex-col gap-1">
<p className="text-sm text-[var(--color-fg-muted)]">
<strong className="text-[var(--color-fg-default)]">{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
</p>
<p className="text-2xl font-semibold tabular-nums">
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
</p>
</div>
<div className="flex flex-wrap gap-3">
<Button type="button" variant="outline" onClick={handlePreview} disabled={selectedCount === 0 || actionState.loading}>
Vorschau
</Button>
<Button type="button" onClick={handleFinalize} disabled={selectedCount === 0 || actionState.loading}>
Abrechnung erstellen
</Button>
</div>
</div>
{actionState.message && (
<div role={actionState.isError ? undefined : "status"}>
<Alert color={actionState.isError ? "danger" : "info"} description={actionState.message} />
</div>
)}
</Card>
{reports.length > 0 && (
<section aria-labelledby="reports-title" className="billing-reports-section">
<h2 id="reports-title">Erstellte Abrechnungen</h2>
<ul className="billing-reports-list">
<section aria-labelledby="reports-title" className="flex flex-col gap-3">
<h2 id="reports-title" className="text-lg font-semibold">Erstellte Abrechnungen</h2>
<ul className="flex flex-col gap-3">
{reports.map((report) => (
<li key={report.id}>
<div className="billing-report-meta">
<span>Bericht Nr. {report.reportNumber}</span>
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
<span>Summe: {formatCents(report.netTotalCents)}</span>
<span>Status: {REPORT_STATUS_LABELS[report.status] ?? report.status}</span>
<span>
Erstellt am:{" "}
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
{report.createdAt.toLocaleDateString("de-DE")}
</time>
</span>
</div>
{report.status === "final" && (
<>
<Card>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<span className="inline-flex items-center gap-2 font-semibold">
<IconFileText size={16} aria-hidden="true" />
Bericht Nr. {report.reportNumber}
</span>
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
<span className="tabular-nums">Summe: {formatCents(report.netTotalCents)}</span>
<Badge variant={report.status === "final" ? "success" : "neutral"}>
{REPORT_STATUS_LABELS[report.status] ?? report.status}
</Badge>
<span className="text-[var(--color-fg-muted)]">
Erstellt am:{" "}
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
{report.createdAt.toLocaleDateString("de-DE")}
</time>
</span>
{report.status === "final" && (
<Button asChild variant="outline">
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
<IconDownload size={16} aria-hidden="true" />
PDF herunterladen
</a>
</Button>
)}
</div>
{report.status === "final" && (
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}`}
className="billing-report-download"
download
>
PDF herunterladen
</a>
</>
)}
)}
</Card>
</li>
))}
</ul>
@@ -364,42 +359,33 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
const years = [2025, 2026, 2027];
return (
<form className="billing-period-selector" method="get">
<label>
<span>Jahr</span>
<select name="year" defaultValue={year}>
{years.map((y) => (
<option key={y} value={y}>
{y}
</option>
))}
</select>
</label>
{isQuarter ? (
<label>
<span>Quartal</span>
<select name="quarter" defaultValue={quarter ?? 1}>
{[1, 2, 3, 4].map((q) => (
<option key={q} value={q}>
Q{q}
</option>
))}
</select>
</label>
) : (
<label>
<span>Monat</span>
<select name="month" defaultValue={month ?? 8}>
{MONTHS.map((name, index) => (
<option key={index} value={index + 1}>
{name}
</option>
))}
</select>
</label>
)}
<button type="submit">Zeitraum laden</button>
</form>
<Card>
<form className="flex flex-wrap items-end gap-4" method="get">
<div className="w-32">
<FormSelect name="year" label="Jahr" defaultValue={String(year)} options={years.map((y) => ({ label: String(y), value: String(y) }))} />
</div>
{isQuarter ? (
<div className="w-32">
<FormSelect
name="quarter"
label="Quartal"
defaultValue={String(quarter ?? 1)}
options={[1, 2, 3, 4].map((q) => ({ label: `Q${q}`, value: String(q) }))}
/>
</div>
) : (
<div className="w-40">
<FormSelect
name="month"
label="Monat"
defaultValue={String(month ?? 8)}
options={MONTHS.map((name, index) => ({ label: name, value: String(index + 1) }))}
/>
</div>
)}
<Button type="submit" variant="secondary">Zeitraum laden</Button>
</form>
</Card>
);
}
@@ -440,38 +426,28 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
}
return (
<form className="billing-cancel-form" onSubmit={handleSubmit}>
<label>
<span>Stornierungsgrund (5–500 Zeichen)</span>
<textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
rows={2}
maxLength={500}
<form className="flex flex-col gap-3 border-t border-[var(--color-border-subtle)] pt-4" onSubmit={handleSubmit}>
<Textarea
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
disabled={loading}
label="Stornierungsgrund (5–500 Zeichen)"
maxLength={500}
onChange={(e) => setReason(e.target.value)}
rows={2}
value={reason}
/>
</label>
<div className="billing-cancel-controls">
<label>
<input
type="checkbox"
<div className="flex flex-wrap items-center gap-4">
<Checkbox
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
disabled={loading}
aria-label="Stornierung bestätigen"
label="Stornierung bestätigen"
onChange={(e) => setConfirmed(e.target.checked)}
/>
<span>Stornierung bestätigen</span>
</label>
<button type="submit" disabled={!valid || loading}>
{loading ? "Wird storniert…" : "Stornieren"}
</button>
</div>
{error && (
<p className="billing-status-message" role="alert">
{error}
</p>
)}
</form>
<Button type="submit" variant="destructive" disabled={!valid || loading}>
{loading ? "Wird storniert …" : "Stornieren"}
</Button>
</div>
{error && <Alert color="danger" description={error} />}
</form>
);
}
}
@@ -1,6 +1,9 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { loadBillingSelection } from "./page-content";
import { BillingSelection } from "./BillingSelection";
@@ -17,12 +20,12 @@ export default async function BillingSelectionPage({
if (!data) notFound();
return (
<section className="content-section" aria-labelledby="billing-selection-title">
<p className="eyebrow">Abrechnungen</p>
<h1 id="billing-selection-title">{data.editorial.name}</h1>
<p>
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
</p>
<section className="flex flex-col gap-6" aria-labelledby="billing-selection-title">
<PageHeader kicker="Abrechnungen" title={data.editorial.name} titleId="billing-selection-title">
<Button asChild variant="outline">
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
</Button>
</PageHeader>
<BillingSelection
editorialId={data.editorial.id}
+35 -17
View File
@@ -1,5 +1,9 @@
import { desc } from "drizzle-orm";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { formatCents } from "@/modules/billing/format";
@@ -18,30 +22,44 @@ export default async function BillingOverviewPage() {
.orderBy(desc(editorialAccounts.createdAt));
return (
<section className="content-section" aria-labelledby="billing-title">
<p className="eyebrow">Abrechnungen</p>
<h1 id="billing-title">Redaktionen</h1>
<p className="form-note">
Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal
auszuwählen.
</p>
<section className="flex flex-col gap-6" aria-labelledby="billing-title">
<PageHeader
kicker="Abrechnungen"
title="Redaktionen"
titleId="billing-title"
description="Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal auszuwählen."
/>
{editorials.length === 0 ? (
<p>Noch keine Redaktionen registriert.</p>
<EmptyState title="Noch keine Redaktionen registriert." description="Registrierte Redaktionen erscheinen hier zur Abrechnung." />
) : (
<ul className="billing-editorial-list">
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{editorials.map((editorial) => (
<li key={editorial.id}>
<a href={`/admin/abrechnungen/${editorial.id}`}>{editorial.name}</a>
<p>
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
{editorial.currentPriceCents === null
? " · Preis noch nicht festgelegt"
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
</p>
<Link
className="block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
href={`/admin/abrechnungen/${editorial.id}`}
>
<Card interactive className="h-full">
<div className="flex items-start justify-between gap-3">
<h2 className="text-base font-semibold">{editorial.name}</h2>
<Badge variant={editorial.status === "active" ? "success" : editorial.status === "pending_approval" ? "warning" : "danger"}>
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
</Badge>
</div>
<p className="text-sm text-[var(--color-fg-muted)]">
{editorial.contactName} · {editorial.loginEmail}
</p>
<p className="text-sm font-medium">
{editorial.currentPriceCents === null
? "Preis noch nicht festgelegt"
: `Netto ${formatCents(editorial.currentPriceCents)}`}
</p>
</Card>
</Link>
</li>
))}
</ul>
)}
</section>
);
}
}
+107 -141
View File
@@ -5,9 +5,11 @@
import { useActionState, useMemo, useState, useTransition } from "react";
import Link from "next/link";
import { Alert, Checkbox, EmptyState, Input, Table } from "@sakaniui/react";
import { IconSearch, IconX } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { AlbumAccessActionResult } from "./actions";
type AccessAction = (
@@ -15,6 +17,8 @@ type AccessAction = (
formData: FormData,
) => Promise<AlbumAccessActionResult>;
type OverviewRow = AlbumAccessManagerAlbum;
export type AlbumAccessManagerAlbum = {
id: string;
albumName: string;
@@ -154,10 +158,10 @@ export function AlbumAccessManager({
})`;
return (
<div className="space-y-8">
<div className="flex flex-col gap-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">Bulk-Zuweisung</CardTitle>
<CardTitle>Bulk-Zuweisung</CardTitle>
<CardDescription>
Alben und Redaktionen auswählen und allen ausgewählten Redaktionen mit einem Klick
Zugriff auf alle ausgewählten Alben geben. Bereits bestehende Zuweisungen werden
@@ -165,14 +169,15 @@ export function AlbumAccessManager({
</CardDescription>
</CardHeader>
<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">
<fieldset className="space-y-3 min-w-0">
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
<fieldset className="flex min-w-0 flex-col gap-3">
<legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
Alben ({selectedAlbumIds.size} ausgewählt)
</legend>
<div className="flex flex-col sm:flex-row gap-2">
<Input
leadingIcon={<IconSearch size={16} />}
type="search"
value={bulkSearch}
onChange={(event) => setBulkSearch(event.target.value)}
@@ -190,37 +195,30 @@ export function AlbumAccessManager({
{allBulkAlbumsSelected ? "Auswahl aufheben" : "Alle auswählen"}
</Button>
</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 ? (
<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) => (
<label
key={album.id}
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}
<div key={album.id} className="flex items-center gap-3 px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
<Checkbox
checked={selectedAlbumIds.has(album.id)}
onChange={(event) =>
toggleAlbumSelection(album.id, event.target.checked)
}
className="h-4 w-4 accent-primary-600"
label={album.albumName}
name="immichAlbumIds"
onChange={(event) => toggleAlbumSelection(album.id, event.target.checked)}
value={album.id}
/>
<span className="truncate font-medium">{album.albumName}</span>
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
<span className="ml-auto shrink-0 text-xs text-[var(--color-fg-muted)]">
{album.assetCount} Fotos
</span>
</label>
</div>
))
)}
</div>
</fieldset>
<fieldset className="space-y-3 min-w-0">
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
<fieldset className="flex min-w-0 flex-col gap-3">
<legend className="mb-3 text-sm font-medium text-[var(--color-fg-muted)]">
Redaktionen ({selectedEditorialIds.size} ausgewählt)
</legend>
<div className="flex justify-end">
@@ -234,29 +232,22 @@ export function AlbumAccessManager({
{allEditorialsSelected ? "Auswahl aufheben" : "Alle auswählen"}
</Button>
</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 ? (
<p className="p-4 text-sm text-muted-foreground">
<p className="p-4 text-sm text-[var(--color-fg-muted)]">
Keine aktiven Redaktionen vorhanden.
</p>
) : (
editorials.map((editorial) => (
<label
key={editorial.id}
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}
<div key={editorial.id} className="px-4 py-2.5 hover:bg-[var(--color-bg-subtle)]">
<Checkbox
checked={selectedEditorialIds.has(editorial.id)}
onChange={(event) =>
toggleEditorialSelection(editorial.id, event.target.checked)
}
className="h-4 w-4 accent-primary-600"
label={editorial.name}
name="editorialIds"
onChange={(event) => toggleEditorialSelection(editorial.id, event.target.checked)}
value={editorial.id}
/>
<span className="truncate font-medium">{editorial.name}</span>
</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">
{bulkState.message ? (
<p
role={bulkState.ok ? "status" : "alert"}
className={`text-sm ${
bulkState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
}`}
>
{bulkState.message}
</p>
<Alert color={bulkState.ok ? "success" : "danger"} description={bulkState.message} />
) : (
<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.
</p>
)}
@@ -289,7 +273,7 @@ export function AlbumAccessManager({
<Card>
<CardHeader className="gap-4">
<div>
<CardTitle className="text-lg">Albumzugriffe</CardTitle>
<CardTitle>Albumzugriffe</CardTitle>
<CardDescription>
Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den
Zugriff für die einzelne Redaktion.
@@ -297,6 +281,7 @@ export function AlbumAccessManager({
</div>
<div className="sm:max-w-sm">
<Input
leadingIcon={<IconSearch size={16} />}
type="search"
value={overviewSearch}
onChange={(event) => setOverviewSearch(event.target.value)}
@@ -305,103 +290,84 @@ export function AlbumAccessManager({
/>
</div>
</CardHeader>
<CardContent className="space-y-4">
<CardContent className="flex flex-col gap-4">
{revokeState.message ? (
<p
role={revokeState.ok ? "status" : "alert"}
className={`text-sm ${
revokeState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
}`}
>
{revokeState.message}
</p>
<Alert color={revokeState.ok ? "success" : "danger"} description={revokeState.message} />
) : null}
{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 ? (
<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 className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Album</th>
<th className="py-3 px-4 font-semibold">Redaktionen mit Zugriff</th>
<th className="py-3 px-4 font-semibold text-right">Anzahl</th>
</tr>
</thead>
<tbody>
{overviewAlbums.map((album, index) => (
<tr
key={album.id}
className={index !== overviewAlbums.length - 1 ? "border-b border-border" : ""}
>
<td className="py-3 px-4">
<div className="flex items-center gap-3">
{album.albumThumbnailAssetId ? (
<img
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>
<Table<OverviewRow>
rowKey={(album) => album.id}
rows={overviewAlbums}
columns={[
{
key: "albumName",
header: "Album",
render: (album) => (
<div className="flex items-center gap-3">
{album.albumThumbnailAssetId ? (
<img
className="h-10 w-14 shrink-0 rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] object-cover"
alt=""
loading="lazy"
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
/>
) : (
<div aria-hidden="true" className="grid h-10 w-14 shrink-0 place-items-center rounded-[var(--radius-sm)] bg-[var(--color-bg-subtle)] text-[10px] text-[var(--color-fg-muted)]">
Kein Cover
</div>
</td>
<td className="py-3 px-4">
{album.grants.length === 0 ? (
<span className="text-muted-foreground">Noch keine Redaktion</span>
) : (
<div className="flex flex-wrap gap-1.5">
{album.grants.map((holder) => (
<form
key={holder.editorialId}
action={revokeFormAction}
className="inline-flex items-center overflow-hidden rounded-full border border-primary-200 bg-primary-50 text-primary-700 dark:border-primary-800 dark:bg-primary-900/30 dark:text-primary-300"
>
<input type="hidden" name="immichAlbumId" value={album.id} />
<input type="hidden" name="editorialId" value={holder.editorialId} />
<Link
href={`/admin/redaktionen/${holder.editorialId}`}
className="py-0.5 pl-2.5 text-xs font-medium hover:underline"
>
{holder.editorialName}
{holder.archived ? " (archiviert)" : ""}
</Link>
<button
type="submit"
disabled={revokePending}
aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`}
title={`Zugriff für ${holder.editorialName} entziehen`}
className="px-2 py-0.5 text-xs font-bold hover:bg-primary-100 dark:hover:bg-primary-800/50 disabled:opacity-50"
>
×
</button>
</form>
))}
</div>
)}
</td>
<td className="py-3 px-4 text-right tabular-nums">{album.grants.length}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="min-w-0">
<p className="truncate font-medium" title={album.albumName}>{album.albumName}</p>
<p className="text-xs text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
</div>
</div>
),
},
{
key: "grants",
header: "Redaktionen mit Zugriff",
render: (album) =>
album.grants.length === 0 ? (
<span className="text-[var(--color-fg-muted)]">Noch keine Redaktion</span>
) : (
<div className="flex flex-wrap gap-1.5">
{album.grants.map((holder) => (
<form
key={holder.editorialId}
action={revokeFormAction}
className="inline-flex items-center overflow-hidden rounded-[var(--radius-full)] border border-[var(--color-border-default)] bg-[var(--color-bg-subtle)] text-[var(--color-fg-default)]"
>
<input type="hidden" name="immichAlbumId" value={album.id} />
<input type="hidden" name="editorialId" value={holder.editorialId} />
<Link
href={`/admin/redaktionen/${holder.editorialId}`}
className="py-0.5 pl-2.5 text-xs font-medium hover:underline"
>
{holder.editorialName}
{holder.archived ? " (archiviert)" : ""}
</Link>
<button
type="submit"
disabled={revokePending}
aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`}
title={`Zugriff für ${holder.editorialName} entziehen`}
className="grid place-items-center px-1.5 py-1 hover:bg-[var(--color-bg-muted)] disabled:opacity-50"
>
<IconX size={12} aria-hidden="true" />
</button>
</form>
))}
</div>
),
},
{ key: "assetCount", header: "Anzahl", align: "right", render: (album) => <span className="tabular-nums">{album.grants.length}</span> },
]}
/>
)}
</CardContent>
</Card>
+13 -16
View File
@@ -1,6 +1,8 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { Alert } from "@/components/ui/sakani";
import { loadAlbumAccess, loadAssignableEditorials } from "./page-content";
import { AlbumAccessManager } from "./AlbumAccessManager";
@@ -13,21 +15,22 @@ export default async function AdminAlbumsPage() {
]);
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
kicker="Albumverwaltung"
title="Alben"
description="Alle Immich-Alben mit ihren Redaktionsfreigaben — inklusive Bulk-Zuweisung für mehrere Alben und Redaktionen auf einmal."
/>
>
<Button asChild variant="outline">
<Link href="/admin/redaktionen">Zu den Redaktionen</Link>
</Button>
</PageHeader>
{albumResult.unavailable ? (
<div
className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30"
role="status"
>
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben
unverändert.
</div>
<Alert
color="warning"
description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
/>
) : (
<AlbumAccessManager
albums={albumResult.albums.map((album) => ({
@@ -46,12 +49,6 @@ export default async function AdminAlbumsPage() {
revokeAction={revokeAlbumAccessAction}
/>
)}
<p className="text-sm">
<Link href="/admin/redaktionen" className="text-primary-600 hover:underline">
Zu den Redaktionen
</Link>
</p>
</div>
</section>
);
}
+42 -58
View File
@@ -1,5 +1,8 @@
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 { requireAdminPage } from "../access";
@@ -31,71 +34,52 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
);
return (
<section className="content-section" aria-labelledby="audit-title">
<p className="eyebrow">Administration</p>
<h1 id="audit-title">Audit-Protokoll</h1>
<p className="form-note">
Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach
Zeitstempel (neueste zuerst).
</p>
<section className="flex flex-col gap-6" aria-labelledby="audit-title">
<PageHeader
kicker="Administration"
title="Audit-Protokoll"
titleId="audit-title"
description="Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach Zeitstempel (neueste zuerst)."
/>
<form method="get" className="audit-filters" aria-label="Audit-Filter">
<label>
<span className="field-label">Ereignistyp</span>
<input
name="eventType"
defaultValue={eventType ?? ""}
placeholder="z. B. editorial_approved"
/>
</label>
<label>
<span className="field-label">Datum von (Berlin)</span>
<input type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
</label>
<label>
<span className="field-label">Datum bis (Berlin)</span>
<input type="date" name="dateTo" defaultValue={dateTo ?? ""} />
</label>
<button type="submit">Filtern</button>
</form>
<Card>
<form method="get" className="grid gap-4 sm:grid-cols-[1fr_11rem_11rem_auto] sm:items-end" aria-label="Audit-Filter">
<Input label="Ereignistyp" name="eventType" defaultValue={eventType ?? ""} placeholder="z. B. editorial_approved" />
<Input label="Datum von (Berlin)" type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
<Input label="Datum bis (Berlin)" type="date" name="dateTo" defaultValue={dateTo ?? ""} />
<Button type="submit" variant="secondary">Filtern</Button>
</form>
</Card>
{page.events.length === 0 ? (
<p>Keine Einträge gefunden.</p>
<EmptyState type="no-results" title="Keine Einträge gefunden." description="Passen Sie die Filter an oder setzen Sie sie zurück." />
) : (
<table className="audit-table">
<thead>
<tr>
<th>Zeitstempel</th>
<th>Akteur</th>
<th>Ereignistyp</th>
<th>Betreff</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{page.events.map((event) => (
<tr key={event.id}>
<td>{berlinFormatter.format(new Date(event.occurredAt))}</td>
<td>{actorLabel(event)}</td>
<td>{event.eventType}</td>
<td>{entityLabel(event)}</td>
<td>
<pre className="audit-metadata">{formatMetadata(event)}</pre>
</td>
</tr>
))}
</tbody>
</table>
<DataTable
columns={[
{ key: "at", header: "Zeitstempel" },
{ key: "actor", header: "Akteur" },
{ key: "type", header: "Ereignistyp" },
{ key: "subject", header: "Betreff" },
{ key: "details", header: "Details" },
]}
rows={page.events.map((event) => ({
at: <span className="whitespace-nowrap tabular-nums">{berlinFormatter.format(new Date(event.occurredAt))}</span>,
actor: actorLabel(event),
type: <code className="break-all text-xs">{event.eventType}</code>,
subject: <span className="break-all text-xs">{entityLabel(event)}</span>,
details: <pre className="audit-metadata">{formatMetadata(event)}</pre>,
}))}
/>
)}
{page.nextCursor && (
<p className="audit-pagination">
<Link
href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}
>
Ältere Einträge laden
</Link>
</p>
<div>
<Button asChild variant="outline">
<Link href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}>
Ältere Einträge laden
</Link>
</Button>
</div>
)}
</section>
);
-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 { Alert, Input, Textarea } from "@sakaniui/react";
import { Card } from "@/components/ui/sakani";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { AnnouncementActionResult } from "./actions";
@@ -36,56 +39,42 @@ export function AnnouncementForm({
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="space-y-2">
<label htmlFor={messageId} className="text-sm font-medium">
Nachricht
</label>
<textarea
<Card title="Neuer Hinweis">
<form action={handleSubmit} className="flex flex-col gap-4">
<Textarea
description={`${message.length}/500 Zeichen`}
id={messageId}
name="message"
rows={3}
label="Nachricht"
maxLength={500}
required
value={message}
name="message"
onChange={(event) => setMessage(event.target.value)}
placeholder="z. B. Liebl ist heute beim HSV-Spiel — Freigaben und Downloads sind trotzdem verfügbar, Antworten dauern etwas länger."
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
className="sm:w-48"
rows={3}
value={message}
/>
<p className="text-xs text-muted-foreground">
Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem
Datum.
</p>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
<div className="sm:max-w-xs">
<Input
defaultValue={defaultEventDate}
description="Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem Datum."
id={dateId}
label="Datum des Ereignisses (z. B. Spieltag)"
name="eventDate"
required
type="date"
/>
</div>
<div>
<Button type="submit" disabled={pending}>
{pending ? "Wird veröffentlicht …" : "Hinweis veröffentlichen"}
</Button>
</div>
{state.message ? (
<div aria-live="polite">
<Alert color={state.ok ? "success" : "danger"} description={state.message} />
</div>
) : null}
</form>
</Card>
);
}
@@ -2,6 +2,8 @@
import { useActionState } from "react";
import { IconTrash } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import type { AnnouncementActionResult } from "./actions";
@@ -23,11 +25,11 @@ export function DeleteAnnouncementButton({
return (
<form action={formAction} className="flex flex-col items-end gap-1">
<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"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
<p role="alert" className="text-xs text-[var(--color-danger-fg)]">
{state.message}
</p>
)}
+25 -27
View File
@@ -1,4 +1,5 @@
import { PageHeader } from "@/components/ui/page-header";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
import {
formatIsoDateGerman,
isoDateInBerlin,
@@ -14,7 +15,7 @@ export default async function AdminAnnouncementsPage() {
const activeCount = items.filter((item) => item.isActive).length;
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
kicker="Kommunikation"
title="Hinweise"
@@ -26,46 +27,43 @@ export default async function AdminAnnouncementsPage() {
defaultEventDate={isoDateInBerlin(new Date())}
/>
<section className="space-y-4" aria-labelledby="announcements-list-title">
<div className="flex items-baseline justify-between">
<section className="flex flex-col gap-4" aria-labelledby="announcements-list-title">
<div className="flex items-baseline justify-between gap-4">
<h2 id="announcements-list-title" className="text-xl font-semibold">
Alle Hinweise
</h2>
<p className="text-sm text-muted-foreground">
<p className="text-sm text-[var(--color-fg-muted)]">
{activeCount} aktiv · {items.length} insgesamt
</p>
</div>
{items.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Hinweise vorhanden.
</p>
<EmptyState title="Noch keine Hinweise vorhanden." description="Veröffentlichte Hinweise erscheinen hier und in der Album-Übersicht der Redaktionen." />
) : (
<ul className="space-y-3">
<ul className="flex flex-col gap-3">
{items.map((item) => (
<li
key={item.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-1 min-w-0">
<p className="text-sm whitespace-pre-line break-words">{item.message}</p>
<p className="text-xs text-muted-foreground">
Ereignis: {formatIsoDateGerman(item.eventDate)} ·{" "}
{item.isActive ? (
<span className="text-green-600 dark:text-green-400">
sichtbar bis {formatIsoDateGerman(item.visibleUntil)}
</span>
) : (
<span>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</span>
)}
</p>
</div>
<DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
<li key={item.id}>
<Card>
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-start">
<div className="flex min-w-0 flex-col gap-2">
<p className="whitespace-pre-line break-words text-sm text-[var(--color-fg-default)]">{item.message}</p>
<p className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-fg-muted)]">
Ereignis: {formatIsoDateGerman(item.eventDate)}
{item.isActive ? (
<Badge variant="success">sichtbar bis {formatIsoDateGerman(item.visibleUntil)}</Badge>
) : (
<Badge>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</Badge>
)}
</p>
</div>
<DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
</div>
</Card>
</li>
))}
</ul>
)}
</section>
</div>
</section>
);
}
+6 -14
View File
@@ -1,6 +1,7 @@
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";
@@ -8,20 +9,11 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
await requireAdminPage();
return (
<PortalShell
brandHref="/admin"
sectionLabel="Administration"
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=""
<AppShell
area="admin"
legal={{ imprint: env.LEGAL_IMPRINT_URL, privacy: env.LEGAL_PRIVACY_URL, terms: env.LEGAL_TERMS_URL }}
>
{children}
</PortalShell>
</AppShell>
);
}
+60 -104
View File
@@ -3,10 +3,9 @@ import { db } from "@/db/client";
import { usages, editorialAccounts } from "@/db/schema";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { BarChart, Card, EmptyState, StatCard, DataTable } from "@/components/ui/sakani";
import { requireAdminPage } from "./access";
import { DownloadsChart } from "./downloads-chart-lazy";
export default async function AdminDashboardPage() {
await requireAdminPage();
@@ -74,125 +73,82 @@ export default async function AdminDashboardPage() {
const dateStr = d.toISOString().split('T')[0];
const record = dailyDownloads.find(r => r.date === dateStr);
chartData.push({
date: dateStr,
downloads: record ? record.downloads : 0,
label: d.toLocaleDateString("de-DE", { day: "numeric" }), // ponytail: day only; 30 "dd. MMM" labels overlap
value: record ? record.downloads : 0,
});
}
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
<section className="flex flex-col gap-6">
<PageHeader
title="Admin Dashboard"
description="Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals."
/>
>
<Button asChild>
<Link href="/admin/redaktionen">Redaktionen verwalten</Link>
</Button>
</PageHeader>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium uppercase tracking-wide text-muted-foreground">Umsatz diesen Monat</CardTitle>
</CardHeader>
<CardContent>
<div className="text-4xl font-bold text-primary-600 dark:text-primary-500">
{formatter.format((revenueStats?.totalCents ?? 0) / 100)}
</div>
<p className="text-sm text-muted-foreground mt-1">
{revenueStats?.count ?? 0} lizenzierte Bilder im {now.toLocaleString("de-DE", { month: "long" })}
</p>
</CardContent>
</Card>
<Card className="flex flex-col justify-center items-center bg-primary-50/50 dark:bg-primary-900/10 border-primary-100 dark:border-primary-900/30">
<CardContent className="pt-6">
<Button asChild size="lg" className="w-full">
<Link href="/admin/redaktionen">
Redaktionen verwalten
</Link>
</Button>
</CardContent>
</Card>
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<StatCard
title="Umsatz diesen Monat"
value={formatter.format((revenueStats?.totalCents ?? 0) / 100)}
description={`${revenueStats?.count ?? 0} lizenzierte Bilder im ${now.toLocaleString("de-DE", { month: "long" })}`}
/>
</div>
<Card>
<CardHeader>
<CardTitle>Downloads der letzten 30 Tage</CardTitle>
<CardDescription>Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.</CardDescription>
</CardHeader>
<CardContent>
<DownloadsChart data={chartData} />
</CardContent>
<Card title="Downloads der letzten 30 Tage" description="Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.">
{chartData.every((day) => day.value === 0) ? (
<EmptyState title="Keine Downloads" description="In den letzten 30 Tagen wurden keine Bilder geladen." />
) : (
<BarChart data={chartData} seriesLabels={["Downloads"]} size="lg" />
)}
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<Card>
<CardHeader>
<CardTitle>Aktivste Redaktionen</CardTitle>
<CardDescription>Die Top 5 Redaktionen nach Downloads.</CardDescription>
</CardHeader>
<CardContent>
{topEditorials.length === 0 ? (
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p>
) : (
<div className="overflow-hidden rounded-md border border-border">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Redaktion</th>
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
</tr>
</thead>
<tbody>
{topEditorials.map((ed, i) => (
<tr key={ed.editorialId} className={i !== topEditorials.length - 1 ? "border-b border-border" : ""}>
<td className="py-3 px-4">
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="text-primary-600 dark:text-primary-400 hover:underline font-medium">
{ed.name}
</Link>
</td>
<td className="py-3 px-4 text-right tabular-nums">{ed.downloadCount}</td>
<td className="py-3 px-4 text-right tabular-nums">{formatter.format(ed.revenueCents / 100)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
<Card title="Aktivste Redaktionen" description="Die Top 5 Redaktionen nach Downloads.">
{topEditorials.length === 0 ? (
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
) : (
<DataTable
columns={[
{ key: "name", header: "Redaktion" },
{ key: "downloads", header: "Downloads", align: "right" },
{ key: "revenue", header: "Umsatz", align: "right" },
]}
rows={topEditorials.map((ed) => ({
id: ed.editorialId,
name: (
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="font-medium text-[var(--color-brand-fg)] hover:underline">
{ed.name}
</Link>
),
downloads: <span className="tabular-nums">{ed.downloadCount}</span>,
revenue: <span className="tabular-nums">{formatter.format(ed.revenueCents / 100)}</span>,
}))}
/>
)}
</Card>
<Card>
<CardHeader>
<CardTitle>Beliebteste Alben</CardTitle>
<CardDescription>Die Top 5 Alben nach Nutzung.</CardDescription>
</CardHeader>
<CardContent>
{topAlbums.length === 0 ? (
<p className="text-muted-foreground text-sm">Noch keine Daten vorhanden.</p>
) : (
<div className="overflow-hidden rounded-md border border-border">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Album</th>
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
</tr>
</thead>
<tbody>
{topAlbums.map((album, i) => (
<tr key={album.albumName} className={i !== topAlbums.length - 1 ? "border-b border-border" : ""}>
<td className="py-3 px-4 font-medium">{album.albumName}</td>
<td className="py-3 px-4 text-right tabular-nums">{album.downloadCount}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
<Card title="Beliebteste Alben" description="Die Top 5 Alben nach Nutzung.">
{topAlbums.length === 0 ? (
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
) : (
<DataTable
columns={[
{ key: "albumName", header: "Album" },
{ key: "downloads", header: "Downloads", align: "right" },
]}
rows={topAlbums.map((album) => ({
albumName: album.albumName,
downloads: <span className="tabular-nums">{album.downloadCount}</span>,
}))}
/>
)}
</Card>
</div>
</div>
</section>
);
}
@@ -3,6 +3,10 @@
/* eslint-disable @next/next/no-img-element */
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";
@@ -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 (
<li className={`flex flex-col bg-white border ${album.isGranted ? 'border-green-500 shadow-md ring-1 ring-green-500' : 'border-gray-200'} rounded-xl overflow-hidden transition-all duration-300 hover:shadow-lg`} data-granted={album.isGranted}>
<div className="relative aspect-[3/2] bg-gray-100 overflow-hidden">
{album.albumThumbnailAssetId ? (
<img
className="w-full h-full object-contain transition-transform duration-500 hover:scale-105"
alt={`Titelbild von ${album.albumName}`}
loading="lazy"
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
/>
) : (
<div aria-label="Kein Albumcover verfügbar" className="w-full h-full flex items-center justify-center text-gray-400 text-xs uppercase tracking-widest" role="img">
Kein Cover
</div>
)}
{album.isGranted && (
<div className="absolute top-2 right-2 bg-green-500 text-white text-xs font-bold px-2 py-1 rounded-full shadow-sm">
Zugewiesen
</div>
)}
</div>
<div className="p-4 flex flex-col flex-grow">
<h2 className="text-base font-bold text-gray-900 mb-1 truncate" id={`album-${album.id}`} title={album.albumName}>
{album.albumName}
</h2>
<p className="text-sm text-gray-500 mb-4">{album.assetCount} Fotos</p>
<div className="mt-auto 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>
<li data-granted={album.isGranted}>
<Card className={`h-full ${album.isGranted ? "outline-2 outline-[var(--color-success-solid)]" : ""}`}>
<div className="relative aspect-[3/2] overflow-hidden rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)]">
{album.albumThumbnailAssetId ? (
<img
className="h-full w-full object-contain"
alt={`Titelbild von ${album.albumName}`}
loading="lazy"
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
/>
) : (
<div aria-label="Kein Albumcover verfügbar" className="grid h-full w-full place-items-center text-xs text-[var(--color-fg-muted)]" role="img">
Kein Cover
</div>
)}
{album.isGranted && (
<form action={(formData) => {
setNotifyStatus("pending");
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
setNotifyStatus(res.ok ? "success" : "error");
setTimeout(() => setNotifyStatus("idle"), 3000);
});
}}>
<Badge className="absolute top-2 right-2" emphasis="solid" variant="success">Zugewiesen</Badge>
)}
</div>
<div className="flex flex-col gap-1">
<h2 className="truncate text-base font-semibold" id={`album-${album.id}`} title={album.albumName}>
{album.albumName}
</h2>
<p className="text-sm text-[var(--color-fg-muted)]">{album.assetCount} Fotos</p>
</div>
<div className="mt-auto flex flex-col gap-2">
<form action={handleAction} className="flex flex-col">
<input name="immichAlbumId" type="hidden" value={album.id} />
<Button disabled={isPending} type="submit" variant={album.isGranted ? "outline" : "primary"}>
{isPending ? "Wird verarbeitet …" : album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</Button>
</form>
{album.isGranted && (
<form
className="flex flex-col"
action={(formData) => {
setNotifyStatus("pending");
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
setNotifyStatus(res.ok ? "success" : "error");
setTimeout(() => setNotifyStatus("idle"), 3000);
});
}}
>
<input name="albumName" type="hidden" value={album.albumName} />
<button
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"
}`}
<Button
disabled={notifyStatus === "pending" || notifyStatus === "success"}
leftIcon={<IconMail size={16} />}
type="submit"
variant={notifyStatus === "error" ? "destructive" : "ghost"}
>
{notifyStatus === "pending" ? "Wird gesendet..." :
notifyStatus === "success" ? "E-Mail gesendet!" :
notifyStatus === "error" ? "Fehler beim Senden" :
"Redaktion benachrichtigen"}
</button>
{notifyLabel}
</Button>
</form>
)}
</div>
</div>
</Card>
</li>
);
}
@@ -130,20 +128,22 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction, noti
);
return (
<div>
<input
type="search"
className="album-grid-search"
placeholder="Alben suchen..."
value={search}
onChange={(e) => setSearch(e.target.value)}
aria-label="Alben durchsuchen"
/>
<div className="flex flex-col gap-6">
<div className="max-w-md">
<Input
aria-label="Alben durchsuchen"
leadingIcon={<IconSearch size={16} />}
onChange={(e) => setSearch(e.target.value)}
placeholder="Alben suchen …"
type="search"
value={search}
/>
</div>
{filteredAlbums.length === 0 ? (
<p>Keine Alben gefunden.</p>
<EmptyState type="no-results" title="Keine Alben gefunden." description="Versuchen Sie einen anderen Suchbegriff." />
) : (
<ul className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6" aria-label="Zuweisbare Immich-Alben">
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4" aria-label="Zuweisbare Immich-Alben">
{filteredAlbums.map((album) => (
<AlbumCard
key={album.id}
+31 -29
View File
@@ -1,8 +1,10 @@
import Image from "next/image";
import Link from "next/link";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/ui/page-header";
import { Alert, EmptyState } from "@/components/ui/sakani";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { albumGrantService } from "@/modules/albums/grants";
@@ -26,40 +28,40 @@ export default async function EditorialAlbumsPage({
const albumResult = await loadAssignableAlbums(editorial.id, albumGrantService);
const header = (
<PageHeader
kicker="Redaktion · Albumrechte"
title={`Alben für ${editorial.name}`}
description="Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen."
>
<div className="flex flex-wrap gap-3">
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
</Button>
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln verwalten</Link>
</Button>
</div>
</PageHeader>
);
if (albumResult.unavailable) {
return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p>
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1>
</div>
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status">
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert.
</div>
<div className="flex gap-4">
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
</div>
</div>
<section className="flex flex-col gap-6">
{header}
<Alert
color="warning"
description="Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben unverändert."
/>
</section>
);
}
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion · Albumrechte</p>
<h1 className="text-4xl font-bold tracking-tight">Alben für {editorial.name}</h1>
<p className="text-muted-foreground mt-2">
Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen.
</p>
<div className="flex gap-4 mt-4 text-sm font-medium">
<Link href={`/admin/redaktionen/${editorial.id}`} className="text-primary-600 hover:underline">Zurück zur Redaktion</Link>
<span className="text-muted-foreground">·</span>
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`} className="text-primary-600 hover:underline">Auto-Zuweisungsregeln verwalten</Link>
</div>
</div>
<section className="flex flex-col gap-6">
{header}
{albumResult.albums.length === 0 ? (
<p className="text-muted-foreground">Derzeit sind keine zuweisbaren Alben vorhanden.</p>
<EmptyState title="Keine zuweisbaren Alben" description="Derzeit sind keine zuweisbaren Alben vorhanden." />
) : (
<AlbumGrid
albums={albumResult.albums}
@@ -69,6 +71,6 @@ export default async function EditorialAlbumsPage({
notifyAction={sendAlbumNotificationAction}
/>
)}
</div>
</section>
);
}
@@ -1,5 +1,5 @@
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 { autoRuleService } from "@/modules/albums/auto-rules";
@@ -8,7 +8,7 @@ import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm";
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 { PageHeader } from "@/components/ui/page-header";
@@ -35,21 +35,12 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
const rules = await autoRuleService.listRules(id);
return (
<div className="space-y-8 max-w-4xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Redaktion · Auto-Zuweisungsregeln"
title={`Auto-Regeln für ${editorial.name}`}
/>
<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>
<section className="flex max-w-4xl flex-col gap-6">
<PageHeader kicker="Redaktion · Auto-Zuweisungsregeln" title={`Auto-Regeln für ${editorial.name}`}>
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Zurück zur Album-Verwaltung</Link>
</Button>
</PageHeader>
<div className="grid gap-6">
<Card>
@@ -60,21 +51,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardDescription>
</CardHeader>
<CardContent>
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex gap-4 items-end">
<div className="grid gap-2 flex-grow">
<label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
Schlüsselwort
</label>
<Input
name="keyword"
type="text"
required
placeholder="z.B. FC Bayern"
className="max-w-md"
/>
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex flex-col gap-4 sm:flex-row sm:items-end">
<div className="w-full max-w-md">
<Input label="Schlüsselwort" name="keyword" placeholder="z.B. FC Bayern" required type="text" />
</div>
<Button type="submit">
<Plus className="w-4 h-4 mr-2" />
<Button type="submit" leftIcon={<IconPlus size={16} />}>
Regel hinzufügen
</Button>
</form>
@@ -83,7 +64,7 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
<Card>
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<CardTitle>Bestehende Regeln</CardTitle>
<CardDescription>
@@ -91,8 +72,7 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardDescription>
</div>
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
<Button type="submit" variant="secondary">
<Play className="w-4 h-4 mr-2" />
<Button type="submit" variant="secondary" leftIcon={<IconPlayerPlay size={16} />}>
Regeln jetzt anwenden
</Button>
</form>
@@ -100,20 +80,19 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardHeader>
<CardContent>
{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) => (
<li key={rule.id} className="flex items-center justify-between p-4">
<div className="flex flex-col">
<span className="font-medium">{rule.keyword}</span>
<span className="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')}
</span>
</div>
<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">
<Trash2 className="w-4 h-4 mr-2" />
<Button type="submit" variant="ghost" size="sm" leftIcon={<IconTrash size={16} />}>
Entfernen
</Button>
</form>
@@ -124,6 +103,6 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
</CardContent>
</Card>
</div>
</div>
</section>
);
}
+58 -62
View File
@@ -3,7 +3,8 @@ import Link from "next/link";
import { db } from "@/db/client";
import { editorialAccounts, usages } from "@/db/schema";
import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { IconChevronRight } from "@sakaniui/react/icons";
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
export default async function EditorialsPage() {
const [editorials, openUsageTotals] = await Promise.all([
@@ -40,7 +41,7 @@ export default async function EditorialsPage() {
const archivedEditorials = editorials.filter((e) => e.archivedAt);
return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500 max-w-7xl">
<section className="flex flex-col gap-6">
<PageHeader
kicker="Kontoverwaltung"
title="Redaktionen"
@@ -48,89 +49,84 @@ export default async function EditorialsPage() {
/>
{activeEditorials.length === 0 ? (
<p className="text-muted-foreground">Noch keine aktiven Redaktionen registriert.</p>
<EmptyState title="Noch keine aktiven Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{activeEditorials.map((editorial) => (
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
<Card className="h-full transition-all duration-300 hover:shadow-md hover:border-primary-500/50 hover:-translate-y-1">
<CardContent className="p-6 flex flex-col h-full justify-between">
<div>
<h3 className="text-xl font-semibold mb-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
{editorial.name}
</h3>
<div className="space-y-1 text-sm text-muted-foreground">
<p className="flex items-center gap-2">
<span className="font-medium text-foreground">Kontakt:</span> {editorial.contactName}
</p>
<p className="flex items-center gap-2">
<span className="font-medium text-foreground">E-Mail:</span> {editorial.loginEmail}
</p>
<p className="flex items-center gap-2">
<span className="font-medium text-foreground">Status:</span>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
editorial.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" :
editorial.status === "pending_approval" ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" :
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
}`}>
{editorial.status === "active" ? "Aktiv" : editorial.status === "pending_approval" ? "Ausstehend" : "Gesperrt"}
</span>
</p>
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{activeEditorials.map((editorial) => {
const openCents = openCentsByEditorial.get(editorial.id) ?? 0;
return (
<li key={editorial.id}>
<Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
<Card interactive className="h-full">
<div className="flex items-start justify-between gap-3">
<h2 className="text-base font-semibold text-[var(--color-fg-default)]">{editorial.name}</h2>
<Badge variant={STATUS[editorial.status]?.variant ?? "danger"}>
{STATUS[editorial.status]?.label ?? "Gesperrt"}
</Badge>
</div>
</div>
<div className="mt-6 pt-4 border-t border-border">
<p className="text-sm font-medium">
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm">
<dt className="text-[var(--color-fg-muted)]">Kontakt</dt>
<dd className="truncate">{editorial.contactName}</dd>
<dt className="text-[var(--color-fg-muted)]">E-Mail</dt>
<dd className="truncate">{editorial.loginEmail}</dd>
</dl>
<p className="mt-auto border-t border-[var(--color-border-subtle)] pt-3 text-sm font-medium">
{editorial.currentPriceCents === null
? "Preis noch nicht festgelegt"
: `Netto ${formatCents(editorial.currentPriceCents)}`}
<span
className={`ml-2 ${(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"
>
· Offen {formatCents(openCentsByEditorial.get(editorial.id) ?? 0)}
· Offen {formatCents(openCents)}
</span>
</p>
</div>
</CardContent>
</Card>
</Link>
))}
</div>
</Card>
</Link>
</li>
);
})}
</ul>
)}
{archivedEditorials.length > 0 && (
<details className="mt-12 group">
<summary className="cursor-pointer flex items-center gap-2 text-sm font-semibold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-colors mb-6 list-none">
<span className="bg-muted p-1 rounded-sm group-open:rotate-90 transition-transform">
▶
</span>
<details className="group mt-6">
<summary className="mb-4 flex cursor-pointer list-none items-center gap-2 text-sm font-medium text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]">
<IconChevronRight size={16} aria-hidden="true" className="transition-transform group-open:rotate-90" />
Archivierte Redaktionen ({archivedEditorials.length})
</summary>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 opacity-75 grayscale hover:grayscale-0 transition-all duration-500">
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{archivedEditorials.map((editorial) => (
<Link key={editorial.id} href={`/admin/redaktionen/${editorial.id}`} className="block group">
<Card className="h-full transition-all duration-300 hover:shadow-sm">
<CardContent className="p-6">
<h3 className="text-lg font-semibold mb-2 text-muted-foreground group-hover:text-foreground transition-colors">
{editorial.name}
</h3>
<div className="space-y-1 text-sm text-muted-foreground">
<p>{editorial.contactName} · {editorial.loginEmail}</p>
<p className="pt-2">
Archiviert am: {editorial.archivedAt ? new Date(editorial.archivedAt).toLocaleDateString("de-DE") : ""}
</p>
<li key={editorial.id}>
<Link href={`/admin/redaktionen/${editorial.id}`} className={CARD_LINK}>
<Card interactive className="h-full opacity-80">
<div className="flex items-start justify-between gap-3">
<h2 className="text-base font-semibold text-[var(--color-fg-muted)]">{editorial.name}</h2>
<Badge>Archiviert</Badge>
</div>
</CardContent>
</Card>
</Link>
<p className="text-sm text-[var(--color-fg-muted)]">{editorial.contactName} · {editorial.loginEmail}</p>
<p className="text-sm text-[var(--color-fg-muted)]">
Archiviert am: {editorial.archivedAt ? new Date(editorial.archivedAt).toLocaleDateString("de-DE") : ""}
</p>
</Card>
</Link>
</li>
))}
</div>
</ul>
</details>
)}
</div>
</section>
);
}
const CARD_LINK =
"block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]";
const STATUS: Record<string, { label: string; variant: "success" | "warning" | "danger" }> = {
active: { label: "Aktiv", variant: "success" },
pending_approval: { label: "Ausstehend", variant: "warning" },
};
function formatCents(cents: number): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
}
+16 -22
View File
@@ -2,6 +2,7 @@
import Link from "next/link";
import { PublicShell } from "@/components/layout/public-shell";
import { Button } from "@/components/ui/button";
type PortalErrorProps = {
@@ -11,27 +12,20 @@ type PortalErrorProps = {
export default function PortalError({ reset }: Readonly<PortalErrorProps>) {
return (
<main className="public-account-page">
<header className="masthead">
<span className="wordmark">Leon Tonhäuser</span>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="account-panel" aria-labelledby="error-title">
<p className="eyebrow">Verbindung unterbrochen</p>
<h1 id="error-title">Diese Seite konnte nicht geladen werden.</h1>
<p className="lede">
Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an.
</p>
<div className="mt-8 flex flex-wrap gap-3">
<Button className="min-h-11" size="lg" type="button" onClick={reset}>
Erneut versuchen
</Button>
<Button asChild className="min-h-11" size="lg" variant="outline">
<Link href="/anmelden">Zur Anmeldung</Link>
</Button>
</div>
</section>
</main>
<PublicShell
kicker="Verbindung unterbrochen"
title="Diese Seite konnte nicht geladen werden."
titleId="error-title"
lede="Versuchen Sie es erneut oder melden Sie sich wieder am Redaktionsportal an."
>
<div className="flex flex-wrap gap-3">
<Button size="lg" type="button" onClick={reset}>
Erneut versuchen
</Button>
<Button asChild variant="outline">
<Link href="/anmelden">Zur Anmeldung</Link>
</Button>
</div>
</PublicShell>
);
}
+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 { 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 { LegalFooter } from "@/components/layout/legal-footer";
import { ThemeProvider } from "@/components/theme-provider";
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
export const metadata: Metadata = {
title: "Redaktionsportal | Leon Tonhäuser",
@@ -21,7 +23,7 @@ export const dynamic = "force-dynamic";
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
return (
<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
attribute="class"
defaultTheme="system"
+16 -22
View File
@@ -1,6 +1,10 @@
import { headers } from "next/headers";
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";
// ponytail: redirect authenticated users straight to their portal home instead
@@ -17,27 +21,17 @@ export default async function HomePage() {
}
return (
<main className="landing">
<header className="masthead">
<span className="wordmark">Leon Tonhäuser</span>
<span className="section-label">Redaktionsportal</span>
</header>
<section className="intro" aria-labelledby="intro-title">
<p className="eyebrow">Pressefotografie</p>
<h1 id="intro-title">Bilder für Ihre Redaktion.</h1>
<p className="lede">
Freigegebene Fotoalben durchsuchen, Nutzungen dokumentieren und
Originaldateien herunterladen.
</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>
<PublicShell
kicker="Pressefotografie"
title="Bilder für Ihre Redaktion."
titleId="intro-title"
lede="Freigegebene Fotoalben durchsuchen, Nutzungen dokumentieren und Originaldateien herunterladen."
>
<div>
<Button asChild>
<Link href="/anmelden">Zum Portal</Link>
</Button>
</div>
</PublicShell>
);
}
+66 -97
View File
@@ -3,8 +3,9 @@ import { db } from "@/db/client";
import { billingReports, usages, editorialAccounts } from "@/db/schema";
import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { FileText } from "lucide-react";
import { IconFileTypePdf } from "@sakaniui/react/icons";
import { PageHeader } from "@/components/ui/page-header";
import { Card, EmptyState, Progress, StatCard, DataTable } from "@/components/ui/sakani";
import { requireEditorial } from "../access";
@@ -81,107 +82,75 @@ export default async function AbrechnungenPage() {
// (Optional: Wenn man hier die Flatrate als "offen" anzeigen will)
const openTotalCents = (openUsages?.totalCents ?? 0);
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Finanzen</p>
<h1 className="text-4xl font-bold tracking-tight">Meine Abrechnungen</h1>
</div>
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const month = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" });
return (
<section className="flex flex-col gap-8" aria-labelledby="billing-title">
<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 && (
<Card className="bg-emerald-50/50 dark:bg-emerald-900/10 border-emerald-100 dark:border-emerald-900/30">
<CardHeader className="pb-2">
<CardTitle className="text-emerald-900 dark:text-emerald-100">Aktiver Tarif: Flatrate</CardTitle>
</CardHeader>
<CardContent>
<p className="text-4xl font-bold text-emerald-700 dark:text-emerald-400 flex items-baseline gap-2">
{new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(editorial.flatratePriceCents / 100)}
<span className="text-lg font-normal text-emerald-600/70 dark:text-emerald-400/70">/ Monat</span>
</p>
{editorial.flatrateAssetLimit === null ? (
<p className="text-sm text-emerald-700/80 dark:text-emerald-300/80 mt-2 font-medium">
Unbegrenzte Downloads inklusive
</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>
<Card title="Aktiver Tarif: Flatrate">
<p className="text-3xl font-semibold tabular-nums text-[var(--color-fg-default)]">
{euro.format(editorial.flatratePriceCents / 100)}{" "}
<span className="text-base font-normal text-[var(--color-fg-muted)]">/ Monat</span>
</p>
{editorial.flatrateAssetLimit === null ? (
<p className="text-sm font-medium text-[var(--color-fg-muted)]">Unbegrenzte Downloads inklusive</p>
) : (
<div className="flex flex-col gap-2">
<div className="flex justify-between text-sm font-medium text-[var(--color-fg-muted)]">
<span>Inklusiv-Bilder diesen Monat</span>
<span className="tabular-nums">{usedFlatrateImages} / {editorial.flatrateAssetLimit}</span>
</div>
)}
</CardContent>
<Progress
label="Verbrauchte Inklusiv-Bilder"
value={Math.min(100, (usedFlatrateImages / editorial.flatrateAssetLimit) * 100)}
/>
</div>
)}
</Card>
)}
</div>
<div className="pt-4">
<h2 className="text-2xl font-bold mb-6">Bisherige Rechnungen</h2>
{reports.length === 0 ? (
<Card>
<CardContent className="pt-6">
<p className="text-muted-foreground text-center py-8">Es liegen noch keine abgerechneten Zeiträume vor.</p>
</CardContent>
</Card>
) : (
<Card>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Rechnungsnummer</th>
<th className="py-3 px-4 font-semibold">Zeitraum</th>
<th className="py-3 px-4 font-semibold text-right">Betrag (Netto)</th>
<th className="py-3 px-4 font-semibold text-center">Download</th>
</tr>
</thead>
<tbody>
{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"}>
<td className="py-4 px-4 font-medium">{report.invoiceNumber}</td>
<td className="py-4 px-4 text-muted-foreground">
{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>
<td className="py-4 px-4 text-center">
<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>
<section className="flex flex-col gap-4" aria-labelledby="reports-title">
<h2 id="reports-title" className="text-xl font-semibold">Bisherige Rechnungen</h2>
{reports.length === 0 ? (
<EmptyState title="Noch keine Rechnungen" description="Es liegen noch keine abgerechneten Zeiträume vor." />
) : (
<DataTable
columns={[
{ key: "invoiceNumber", header: "Rechnungsnummer" },
{ key: "period", header: "Zeitraum" },
{ key: "net", header: "Betrag (Netto)", align: "right" },
{ key: "pdf", header: "Download", align: "center" },
]}
rows={reports.map((report) => ({
id: report.id,
invoiceNumber: report.invoiceNumber,
period: month.format(new Date(report.periodStartsAt)),
net: <span className="tabular-nums">{euro.format(report.netTotalCents / 100)}</span>,
pdf: (
<Link
className="inline-flex items-center gap-2 font-medium text-[var(--color-brand-fg)] hover:underline"
href={`/api/editorials/reports/${report.id}/pdf`}
target="_blank"
>
<IconFileTypePdf size={16} aria-hidden="true" />
<span>PDF</span>
</Link>
),
}))}
/>
)}
</section>
</section>
);
}
@@ -1,8 +1,10 @@
import { Spinner } from "@/components/ui/sakani";
export default function AlbumLoading() {
return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p>
<div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
<Spinner size="sm" label="Fotos werden geladen." />
<p>Fotos werden geladen.</p>
</section>
</div>
);
}
+21 -53
View File
@@ -2,14 +2,16 @@ import Link from "next/link";
import { notFound } from "next/navigation";
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 { PhotoGallery } from "@/modules/albums/photo-gallery";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service";
import { requireEditorial } from "../../access";
import { Button } from "@/components/ui/button";
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
// 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 (
<section className="editorial-section" aria-labelledby="album-title">
<section aria-labelledby="album-title">
<PageHeader
kicker={`Bildarchiv · ${result.album.assetCount} freigegebene Fotos`}
title={result.album.albumName}
titleId="album-title"
>
<Link className="quiet-link" href="/redaktion/alben">
Alle Alben
</Link>
<Button asChild variant="outline">
<Link href="/redaktion/alben">Alle Alben</Link>
</Button>
</PageHeader>
<AlbumSearchForm albumId={result.album.id} query={query} format={format} />
<p aria-live="polite" className="result-summary" role="status">
<PhotoSearchForm
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
</p>
<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({
editorialId,
albumId,
@@ -178,19 +152,13 @@ function normalizedQuery(value: string | undefined): string {
function ImmichUnavailable() {
return (
<section className="editorial-section editorial-state" aria-labelledby="album-title">
<PageHeader
kicker="Bildarchiv"
title="Fotos momentan nicht erreichbar"
titleId="album-title"
>
<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>
<section className="flex flex-col gap-6" aria-labelledby="album-title">
<PageHeader kicker="Bildarchiv" title="Fotos momentan nicht erreichbar" titleId="album-title">
<Button asChild variant="outline">
<Link href="/redaktion/alben">Zurück zu den Alben</Link>
</Button>
</PageHeader>
<Alert color="warning" description="Bitte laden Sie diese Seite in wenigen Minuten erneut." />
</section>
);
}
+5 -3
View File
@@ -1,8 +1,10 @@
import { Spinner } from "@/components/ui/sakani";
export default function AlbumsLoading() {
return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p>
<div className="flex items-center gap-3 py-16 text-[var(--color-fg-muted)]" aria-busy="true" aria-live="polite">
<Spinner size="sm" label="Alben werden geladen." />
<p>Alben werden geladen.</p>
</section>
</div>
);
}
+23 -74
View File
@@ -1,15 +1,13 @@
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 { PhotoGallery } from "@/modules/albums/photo-gallery";
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
import { announcementService } from "@/modules/announcements/service";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service";
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Alert, EmptyState } from "@/components/ui/sakani";
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));
return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="albums-title">
<PageHeader
kicker="Bildarchiv · Suche"
title="Suchergebnisse"
titleId="albums-title"
/>
<section className="flex flex-col gap-6" aria-labelledby="albums-title">
<PageHeader kicker="Bildarchiv · Suche" title="Suchergebnisse" titleId="albums-title" />
<AnnouncementBanner items={hints} />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<p aria-live="polite" className="result-summary" role="status">
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
<p aria-live="polite" className="text-sm text-[var(--color-fg-muted)]" role="status">
{formatCount(page.total, "Foto")} gefunden
</p>
<PhotoGallery
@@ -70,7 +64,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
showAlbumName
/>
<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 (
<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
kicker="Bildarchiv · Freigaben"
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."
/>
<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 ? (
<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} />
)}
</div>
</section>
);
}
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
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" />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<p className="bg-muted p-4 rounded-md" role="status">
Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut.
</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>
<PhotoSearchForm action="/redaktion/alben" query={query} format={format} jahr={jahr} withYear placeholder="Alle Alben durchsuchen …" />
<Alert color="warning" description="Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut." />
</section>
);
}
@@ -152,14 +111,10 @@ function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { cu
}
return (
<nav aria-label="Suchergebnisseiten" className="flex justify-between items-center mt-8 pt-4 border-t border-border text-sm font-medium">
{hasPrev ? (
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage - 1, query, format, jahr)}>Vorherige Seite</Link>
) : <div />}
{hasNext ? (
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage + 1, query, format, jahr)}>Nächste Seite</Link>
) : <div />}
</nav>
<PageLinks
prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr) : null}
nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr) : null}
/>
);
}
@@ -191,15 +146,9 @@ async function loadAlbums(editorialId: string) {
function ImmichUnavailable() {
return (
<div className="space-y-6 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="albums-title">
<PageHeader
kicker="Bildarchiv"
title="Alben momentan nicht erreichbar"
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>
<section className="flex flex-col gap-6" aria-labelledby="albums-title">
<PageHeader kicker="Bildarchiv" title="Alben momentan nicht erreichbar" titleId="albums-title" />
<Alert color="danger" description="Bitte laden Sie diese Seite in wenigen Minuten erneut. Ihre Freigaben bleiben unverändert." />
</section>
);
}
+6 -11
View File
@@ -1,6 +1,7 @@
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";
@@ -8,17 +9,11 @@ export default async function EditorialLayout({ children }: Readonly<{ children:
await requireEditorial();
return (
<PortalShell
brandHref="/redaktion/alben"
sectionLabel="Redaktionsarchiv"
nav={[
{ href: "/redaktion/alben", label: "Alben" },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel" },
{ href: "/redaktion/nutzungen", label: "Nutzungen" },
{ href: "/redaktion/profil", label: "Profil" },
]}
<AppShell
area="redaktion"
legal={{ imprint: env.LEGAL_IMPRINT_URL, privacy: env.LEGAL_PRIVACY_URL, terms: env.LEGAL_TERMS_URL }}
>
{children}
</PortalShell>
</AppShell>
);
}
@@ -2,11 +2,14 @@
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { Alert, Button, Input } from "@sakaniui/react";
import { IconDownload } from "@sakaniui/react/icons";
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
const [loading, setLoading] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null);
const [purpose, setPurpose] = useState("");
const [error, setError] = useState<string | null>(null);
const router = useRouter();
async function handleBulkDownload(e: React.FormEvent) {
@@ -14,7 +17,8 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
if (!purpose.trim() || assetIds.length === 0) return;
setLoading(true);
setError(null);
try {
const response = await fetch("/api/lightbox/bulk-download", {
method: "POST",
@@ -53,7 +57,7 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
router.refresh(); // Refresh to update usage history
} catch (err) {
const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
alert(`Bulk-Download fehlgeschlagen: ${message}`);
setError(`Bulk-Download fehlgeschlagen: ${message}`);
console.error(err);
} finally {
setLoading(false);
@@ -62,60 +66,41 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
return (
<>
<button
type="button"
onClick={() => dialogRef.current?.showModal()}
<Button
disabled={assetIds.length === 0}
className="primary-action m-0"
leftIcon={<IconDownload size={16} />}
onClick={() => dialogRef.current?.showModal()}
type="button"
>
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">
<div className="p-6">
<h2 className="text-xl font-bold mb-4">Verwendungszweck angeben</h2>
<p className="text-sm text-muted-foreground mb-6">
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
<form className="flex flex-col gap-4 p-6" onSubmit={handleBulkDownload}>
<h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</h2>
<p className="text-sm text-[var(--color-fg-muted)]">
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
</p>
<form onSubmit={handleBulkDownload}>
<div className="space-y-4">
<div>
<label htmlFor="purpose" className="block text-sm font-medium mb-1">
Verwendungszweck
</label>
<input
id="purpose"
type="text"
required
placeholder="z.B. Webseite, Social Media"
value={purpose}
onChange={(e) => setPurpose(e.target.value)}
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"
disabled={loading}
/>
</div>
</div>
<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>
<Input
disabled={loading}
id="purpose"
label="Verwendungszweck"
onChange={(e) => setPurpose(e.target.value)}
placeholder="z.B. Webseite, Social Media"
required
type="text"
value={purpose}
/>
{error ? <Alert color="danger" description={error} /> : null}
<div className="mt-4 flex justify-end gap-3">
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
Abbrechen
</Button>
<Button disabled={loading || !purpose.trim()} type="submit">
{loading ? "Wird verpackt …" : "Download starten (ZIP)"}
</Button>
</div>
</form>
</dialog>
</>
);
@@ -1,6 +1,8 @@
"use client";
import { useState, useTransition } from "react";
import { IconButton } from "@sakaniui/react";
import { IconBookmark, IconBookmarkFilled } from "@sakaniui/react/icons";
import { toggleLightboxItem } from "./actions";
type LightboxToggleButtonProps = {
@@ -34,27 +36,17 @@ export function LightboxToggleButton({ assetId, initialInLightbox }: LightboxTog
});
}
const label = inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel";
return (
<button
type="button"
onClick={handleClick}
<IconButton
aria-label={label}
aria-pressed={inLightbox}
disabled={isPending}
className={`lightbox-toggle-btn ${inLightbox ? 'in-lightbox' : ''}`}
aria-label={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"}
title={inLightbox ? "Aus dem Merkzettel entfernen" : "Auf den Merkzettel"}
>
<svg
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>
icon={inLightbox ? IconBookmarkFilled : IconBookmark}
onClick={handleClick}
size="sm"
title={label}
variant={inLightbox ? "primary" : "secondary"}
/>
);
}
@@ -1,6 +1,8 @@
"use client";
import { useTransition } from "react";
import { IconButton } from "@sakaniui/react";
import { IconX } from "@sakaniui/react/icons";
import { removeLightboxItemAction } from "./actions";
export function RemoveLightboxItemButton({ assetId }: { assetId: string }) {
@@ -13,26 +15,14 @@ export function RemoveLightboxItemButton({ assetId }: { assetId: string }) {
}
return (
<button
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"
<IconButton
aria-label="Aus Merkzettel entfernen"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="w-4 h-4"
>
<path d="M18 6L6 18M6 6l12 12" />
</svg>
</button>
disabled={isPending}
icon={IconX}
onClick={handleRemove}
size="sm"
title="Aus Merkzettel entfernen"
variant="secondary"
/>
);
}
+19 -16
View File
@@ -1,6 +1,7 @@
/* eslint-disable @next/next/no-img-element */
import { PageHeader } from "@/components/ui/page-header";
import { Card, EmptyState } from "@/components/ui/sakani";
import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client";
import Link from "next/link";
@@ -21,24 +22,26 @@ export default async function LightboxPage() {
const assetMap = new Map(validAssets.map(a => [a.id, a]));
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
kicker="Merkzettel"
title="Dein Leuchtkasten"
/>
{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">
<p className="text-sm font-medium text-muted-foreground">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
</p>
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
</div>
<Card>
<div className="flex flex-wrap items-center justify-between gap-4">
<p className="text-sm font-medium text-[var(--color-fg-muted)]">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
</p>
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
</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) => {
const asset = assetMap.get(item.assetId);
if (!asset) return null;
@@ -48,9 +51,9 @@ export default async function LightboxPage() {
: '#';
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">
<Link href={href} className="block">
<div className="aspect-[3/2] w-full overflow-hidden bg-muted">
<li key={item.assetId} className="group relative overflow-hidden rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] transition-shadow hover:shadow-[var(--shadow-md)]">
<Link href={href} className="block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]">
<div className="aspect-[3/2] w-full overflow-hidden bg-[var(--color-bg-subtle)]">
<img
alt={asset.originalFileName ?? "Bild"}
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`}
/>
</div>
<div className="p-3 border-t border-border bg-card">
<span className="block truncate text-xs font-medium text-muted-foreground" title={asset.originalFileName}>
<div className="border-t border-[var(--color-border-subtle)] p-3">
<span className="block truncate text-xs font-medium text-[var(--color-fg-muted)]" title={asset.originalFileName}>
{asset.originalFileName ?? "Unbekannt"}
</span>
</div>
</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} />
</div>
</li>
@@ -73,6 +76,6 @@ export default async function LightboxPage() {
</ul>
</>
)}
</div>
</section>
);
}
+6 -4
View File
@@ -1,5 +1,8 @@
import { listEditorialUsageHistory } from "@/modules/downloads/stream";
import { PageHeader } from "@/components/ui/page-header";
import { Alert } from "@/components/ui/sakani";
import { requireEditorial } from "../access";
import { UsageHistoryContent } from "./usage-history-content";
@@ -35,10 +38,9 @@ async function loadHistory(
function HistoryUnavailable() {
return (
<section className="editorial-section editorial-state" aria-labelledby="usage-history-title">
<p className="editorial-kicker">Abrechnung</p>
<h1 id="usage-history-title">Nutzungen momentan nicht erreichbar</h1>
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
<section aria-labelledby="usage-history-title">
<PageHeader kicker="Abrechnung" title="Nutzungen momentan nicht erreichbar" titleId="usage-history-title" />
<Alert color="warning" description="Bitte laden Sie diese Seite in wenigen Minuten erneut." />
</section>
);
}
@@ -1,6 +1,9 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
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 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 }>) {
return (
<section className="editorial-section usage-history" aria-labelledby="usage-history-title">
<section className="usage-history" aria-labelledby="usage-history-title">
<PageHeader
kicker="Abrechnung · Downloadprotokoll"
title="Ihre Nutzungen"
@@ -27,16 +30,17 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
/>
{history.items.length === 0 ? (
<div className="usage-history-empty">
<p>Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.</p>
<Link className="quiet-link" href="/redaktion/alben">
Zu den Alben
</Link>
<div className="flex flex-col items-center gap-4">
<EmptyState title="Noch keine Nutzungen erfasst." description="Wählen Sie ein Foto aus einem freigegebenen Album." />
<Button asChild variant="outline">
<Link href="/redaktion/alben">Zu den Alben</Link>
</Button>
</div>
) : (
<ol className="usage-ledger">
{history.items.map((usage) => (
<li key={usage.usageId}>
<Card>
<article className="usage-ledger-entry">
<header>
<p>{formatBerlinDateTime(usage.createdAt)}</p>
@@ -57,7 +61,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
</div>
<div>
<dt>Abrechnungsstatus</dt>
<dd>{billingStatusLabel(usage.billingStatus)}</dd>
<dd><Badge variant={BILLING_BADGE[usage.billingStatus]}>{billingStatusLabel(usage.billingStatus)}</Badge></dd>
</div>
{usage.reference ? (
<div>
@@ -67,6 +71,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
) : null}
</dl>
</article>
</Card>
</li>
))}
</ol>
@@ -77,7 +82,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
<section className="usage-attempt-history" aria-labelledby="usage-attempt-title">
<h2 id="usage-attempt-title">Downloadversuche</h2>
{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">
{history.attempts.map((attempt) => (
@@ -105,7 +110,7 @@ function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
{attempt.reference ? ` · ${attempt.reference}` : ""}
</small>
</span>
<strong>{statusLabel(attempt.status)}</strong>
<Badge variant={ATTEMPT_BADGE[attempt.status]}>{statusLabel(attempt.status)}</Badge>
<span>
{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "}
{byteFormatter.format(attempt.transferredBytes)}
@@ -119,45 +124,50 @@ function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
}
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
if (history.page === 1 && !history.hasNext) return null;
return (
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
{history.page > 1 ? (
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>
Vorherige Nutzungsseite
</Link>
) : (
<span />
)}
{history.hasNext ? (
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>
Nächste Nutzungsseite
</Link>
) : null}
</nav>
<PageLinks
ariaLabel="Seiten der Nutzungshistorie"
prevHref={history.page > 1 ? `/redaktion/nutzungen?page=${history.page - 1}` : null}
prevLabel="Vorherige Nutzungsseite"
nextHref={history.hasNext ? `/redaktion/nutzungen?page=${history.page + 1}` : null}
nextLabel="Nächste Nutzungsseite"
/>
);
}
function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
if (!history.attemptCursor && !history.nextAttemptCursor) return null;
return (
<nav aria-label="Seiten der Auslieferungsversuche" className="photo-pagination">
{history.attemptCursor ? (
<Link href={`/redaktion/nutzungen?page=${history.page}`}>Neueste Auslieferungen</Link>
) : (
<span />
)}
{history.nextAttemptCursor ? (
<Link
href={`/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`}
>
Ältere Auslieferungen
</Link>
) : null}
</nav>
<PageLinks
ariaLabel="Seiten der Auslieferungsversuche"
prevHref={history.attemptCursor ? `/redaktion/nutzungen?page=${history.page}` : null}
prevLabel="Neueste Auslieferungen"
nextHref={
history.nextAttemptCursor
? `/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`
: null
}
nextLabel="Ältere Auslieferungen"
/>
);
}
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 {
const labels: Record<UsageHistoryAttempt["status"], string> = {
authorized: "Autorisiert",
+4 -1
View File
@@ -1,6 +1,7 @@
import { eq } from "drizzle-orm";
import { PageHeader } from "@/components/ui/page-header";
import { Card } from "@/components/ui/sakani";
import { db } from "@/db/client";
import { billingAddressVersions, editorialAccounts } from "@/db/schema";
@@ -35,7 +36,8 @@ export default async function EditorialProfilePage() {
title="Profil"
titleId="profile-title"
/>
<dl>
<Card>
<dl className="!mt-0 !border-t-0 !pt-0">
<dt>Redaktion</dt>
<dd>{editorial?.name}</dd>
<dt>Ansprechperson</dt>
@@ -59,6 +61,7 @@ export default async function EditorialProfilePage() {
)}
</dd>
</dl>
</Card>
</section>
);
}
+12 -12
View File
@@ -1,6 +1,7 @@
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 { requireTwoFactorSetupPage } from "./access";
@@ -14,20 +15,19 @@ export default async function TwoFactorSetupPage() {
(session?.user as { twoFactorEnabled?: unknown } | undefined)?.twoFactorEnabled === true;
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">
<PageHeader kicker="Sicherheit" title="Zwei-Faktor-Authentifizierung" />
<PublicShell kicker="Sicherheit" title="Zwei-Faktor-Authentifizierung" titleId="two-factor-title" wide>
{enabled ? (
<p className="text-sm text-muted-foreground">
Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich
einen Code Ihrer Authenticator-App.
</p>
<Alert
color="success"
description="Zwei-Faktor ist aktiviert. Administrator-Bereiche erfordern bei der Anmeldung zusätzlich einen Code Ihrer Authenticator-App."
/>
) : (
<div className="bg-primary/10 border border-primary/30 p-4 rounded-md text-sm" role="status">
Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie
jetzt ein, um auf den Admin-Bereich zuzugreifen.
</div>
<Alert
color="info"
description="Für Administrator-Konten ist die Zwei-Faktor-Authentifizierung Pflicht. Richten Sie sie jetzt ein, um auf den Admin-Bereich zuzugreifen."
/>
)}
<TwoFactorWizard initiallyEnabled={enabled} />
</div>
</PublicShell>
);
}
+35 -41
View File
@@ -2,6 +2,8 @@
import { type FormEvent, useState } from "react";
import { Alert, Input } from "@sakaniui/react";
import { Button } from "@/components/ui/button";
import { authClient } from "@/modules/auth/client";
@@ -82,19 +84,18 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
}
return (
<div className="space-y-6">
<div className="flex flex-col gap-6">
{!enabled && step === "password" && (
<form onSubmit={startSetup} className="space-y-4">
<label className="block text-sm font-medium">
Passwort bestätigen, um die Einrichtung zu starten
<input
<form onSubmit={startSetup} className="flex flex-col items-start gap-4">
<div className="w-full">
<Input
autoComplete="current-password"
className="mt-1 block w-full"
label="Passwort bestätigen, um die Einrichtung zu starten"
name="password"
required
type="password"
/>
</label>
</div>
<Button disabled={pending} type="submit">
{pending ? "Wird vorbereitet …" : "Einrichtung starten"}
</Button>
@@ -102,12 +103,12 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
)}
{step === "scan" && secret && (
<div className="space-y-4">
<ol className="text-sm space-y-2 list-decimal list-inside text-muted-foreground">
<div className="flex flex-col gap-4">
<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>
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}
</code>
<span className="text-xs mt-1 block">
@@ -118,74 +119,67 @@ export function TwoFactorWizard({ initiallyEnabled }: { initiallyEnabled: boolea
</ol>
{backupCodes.length > 0 && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm">
<p className="font-medium mb-2">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="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">Einmal-Codes (ersatzweise gültig, je einmal nutzbar)</p>
<div className="grid grid-cols-2 gap-1 font-mono text-xs sm:grid-cols-3">
{backupCodes.map((code) => (
<span key={code}>{code}</span>
))}
</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.
</p>
</div>
)}
<form onSubmit={confirmCode} className="space-y-4">
<label className="block text-sm font-medium">
Code aus der App
<input
<form onSubmit={confirmCode} className="flex flex-col items-start gap-4">
<div className="w-48">
<Input
autoComplete="one-time-code"
className="mt-1 block w-full max-w-[12rem]"
inputMode="numeric"
label="Code aus der App"
maxLength={6}
name="code"
pattern="[0-9]*"
required
type="text"
/>
</label>
</div>
<Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Aktivieren"}
</Button>
</Button>
</form>
</div>
)}
{step === "done" && (
<div className="rounded-md border border-emerald-600/40 bg-emerald-600/10 p-4 text-sm" role="status">
Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit
Passwort und Authenticator-Code anmelden.
<a className="primary-action inline-block mt-4" href="/admin">
Weiter zum Admin-Bereich
</a>
<div className="flex flex-col items-start gap-4" role="status">
<Alert
color="success"
description="Zwei-Faktor-Authentifizierung ist aktiviert. Sie können sich ab jetzt nur noch mit Passwort und Authenticator-Code anmelden."
/>
<Button asChild>
<a href="/admin">Weiter zum Admin-Bereich</a>
</Button>
</div>
)}
{enabled && step !== "done" && (
<form onSubmit={disable} className="space-y-4 border-t pt-6">
<p className="text-sm text-muted-foreground">
<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-[var(--color-fg-muted)]">
Zwei-Faktor ist aktiviert. Zum Deaktivieren Ihr Passwort eingeben – danach muss die
Einrichtung neu erfolgen, bevor Admin-Bereiche wieder zugänglich sind.
</p>
<input
autoComplete="current-password"
name="password"
placeholder="Passwort"
required
type="password"
/>
<div className="w-full">
<Input aria-label="Passwort" autoComplete="current-password" name="password" placeholder="Passwort" required type="password" />
</div>
<Button variant="outline" disabled={pending} type="submit">
{pending ? "Wird deaktiviert …" : "Zwei-Faktor deaktivieren"}
</Button>
</form>
)}
{error && (
<p className="field-error" role="alert">
{error}
</p>
)}
{error && <Alert color="danger" description={error} />}
</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";
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 type { DownloadDialogUsage } from "@/modules/downloads/stream";
@@ -115,9 +117,9 @@ export function UsageDialog({
return (
<>
<button className="download-trigger" onClick={openDialog} type="button">
<Button leftIcon={<IconDownload size={16} />} onClick={openDialog} size="sm" type="button" variant="secondary">
Original laden
</button>
</Button>
<dialog
aria-labelledby={`usage-dialog-title-${assetId}`}
className="usage-dialog"
@@ -196,19 +198,19 @@ export function UsageDialog({
/>
</label>
{error ? <p role="alert">{error}</p> : null}
{error ? <Alert color="danger" description={error} /> : null}
<div className="usage-dialog-actions">
<button disabled={pending} onClick={closeDialog} type="button">
<Button disabled={pending} onClick={closeDialog} type="button" variant="ghost">
Abbrechen
</button>
<button className="download-confirm" disabled={pending} type="submit">
</Button>
<Button disabled={pending} type="submit">
{pending
? "Download wird vorbereitet …"
: error
? "Download erneut anfordern"
: "Download anfordern"}
</button>
</Button>
</div>
</form>
</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"
import { Slot } from "@radix-ui/react-slot"
import { cn } from "@/lib/utils"
"use client";
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
asChild?: boolean
variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
size?: "default" | "sm" | "lg" | "icon"
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { Button as SakaniButton } from "@sakaniui/react";
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>(
({ className, variant = "default", size = "default", asChild = false, ...props }, ref) => {
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",
}
const VARIANT = { default: "primary", destructive: "destructive", outline: "outline", secondary: "secondary", ghost: "ghost", link: "ghost" } as const;
const SIZE = { default: "md", sm: "sm", lg: "lg", icon: "sm" } as const;
// 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 (
<Comp
className={cn(baseClasses, variantClasses[variant], sizeClasses[size], className)}
<SakaniButton
className={className}
leftIcon={leftIcon}
loading={loading}
ref={ref}
rightIcon={rightIcon}
size={SIZE[size]}
variant={VARIANT[variant]}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button }
>
{children}
</SakaniButton>
);
},
);
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>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden",
className
)}
{...props}
/>
)
)
Card.displayName = "Card"
// Old shadcn-style composition API on top of Sakani's Card surface. Sakani's
// Card already pads (20px) and stacks children (gap 16px), so the parts below
// add no padding of their own.
export function Card({ className, children }: HTMLAttributes<HTMLDivElement>) {
return <SakaniCard className={className}>{children}</SakaniCard>;
}
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
)
)
CardHeader.displayName = "CardHeader"
export function CardHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn("flex flex-col gap-1", className)} {...props} />;
}
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("text-2xl font-semibold leading-none tracking-tight", className)}
{...props}
/>
)
)
CardTitle.displayName = "CardTitle"
export function CardTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {
return <h3 className={cn("text-base font-semibold text-[var(--color-fg-default)]", className)} {...props} />;
}
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-gray-500 dark:text-gray-400", className)}
{...props}
/>
)
)
CardDescription.displayName = "CardDescription"
export function CardDescription({ className, ...props }: HTMLAttributes<HTMLParagraphElement>) {
return <p className={cn("text-sm text-[var(--color-fg-muted)]", className)} {...props} />;
}
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)
)
CardContent.displayName = "CardContent"
export function CardContent({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn("min-w-0", className)} {...props} />;
}
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
)
)
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
export function CardFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={cn("flex items-center gap-2", className)} {...props} />;
}
+5 -24
View File
@@ -1,25 +1,6 @@
import * as React from "react"
"use client";
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
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 }
// Old API, Sakani rendering. Prefer importing Input from "@/components/ui/sakani"
// in new code to get label/description/icon props.
export { Input } from "@sakaniui/react";
export type { InputProps } from "@sakaniui/react";
+10 -13
View File
@@ -1,26 +1,23 @@
import React from "react";
import type { ReactNode } from "react";
type PageHeaderProps = {
kicker?: string;
title: string;
description?: string;
description?: ReactNode;
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) {
return (
<div className="editorial-section">
{kicker && <p className="editorial-kicker text-sm font-semibold text-muted-foreground tracking-widest uppercase mb-2">{kicker}</p>}
<div className="editorial-title-row mb-6">
<h1 id={titleId} className="text-4xl font-bold tracking-tight text-foreground">{title}</h1>
<header className="mb-8 flex flex-col gap-2">
{kicker ? <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-fg-muted)]">{kicker}</p> : null}
<div className="flex flex-wrap items-end justify-between gap-4">
<h1 id={titleId} className="text-3xl font-semibold tracking-tight text-[var(--color-fg-default)]">{title}</h1>
{children}
</div>
{description && (
<p className="text-lg text-muted-foreground max-w-3xl mb-8">
{description}
</p>
)}
</div>
{description ? <p className="max-w-2xl text-base text-[var(--color-fg-muted)]">{description}</p> : null}
</header>
);
}
+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") {
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 {
const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler");
startAutoRuleScheduler();
+99 -24
View File
@@ -1,37 +1,47 @@
/* eslint-disable @next/next/no-img-element */
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 { VisibleAlbum } from "./catalog";
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
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) => (
<li key={album.id}>
<Link className="album-tile" href={`/redaktion/alben/${encodeURIComponent(album.id)}`}>
<figure className="album-tile-frame">
{album.albumThumbnailAssetId ? (
<img
alt={`Titelbild: ${album.albumName}`}
className="album-tile-image"
loading="lazy"
src={thumbnailUrl(album.albumThumbnailAssetId)}
/>
) : (
<div aria-label={`Kein Titelbild für ${album.albumName}`} className="album-tile-missing" role="img">
Kein Titelbild
</div>
)}
<div className="album-tile-overlay">
<figcaption className="photo-tile-caption">
<span className="photo-tile-name">{album.albumName}</span>
<span className="photo-tile-date">{formatCount(album.assetCount, "Foto")}</span>
<Link
className="block h-full rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
href={`/redaktion/alben/${encodeURIComponent(album.id)}`}
>
<Card interactive className="h-full">
<figure className="flex flex-col gap-3">
{album.albumThumbnailAssetId ? (
<img
alt={`Titelbild: ${album.albumName}`}
className="aspect-[4/3] w-full rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)] object-cover"
loading="lazy"
src={thumbnailUrl(album.albumThumbnailAssetId)}
/>
) : (
<div
aria-label={`Kein Titelbild für ${album.albumName}`}
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)]"
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>
</div>
</figure>
</figure>
</Card>
</Link>
</li>
))}
@@ -63,14 +73,79 @@ export function PhotoPagination({
return null;
}
return <PageLinks prevHref={hasPrev ? pageHref(albumId, currentPage - 1, query, format, jahr) : null} nextHref={hasNext ? pageHref(albumId, currentPage + 1, query, format, jahr) : null} />;
}
// 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 (
<nav aria-label="Suchergebnisseiten" className="photo-pagination">
{hasPrev ? <Link href={pageHref(albumId, currentPage - 1, query, format, jahr)}>Vorherige Seite</Link> : null}
{hasNext ? <Link href={pageHref(albumId, currentPage + 1, query, format, jahr)}>Nächste Seite</Link> : null}
<nav aria-label={ariaLabel} className="mt-6 flex items-center justify-between gap-4 border-t border-[var(--color-border-subtle)] pt-4">
{prevHref ? <Button asChild variant="outline"><Link href={prevHref}>{prevLabel}</Link></Button> : <span />}
{nextHref ? <Button asChild variant="outline"><Link href={nextHref}>{nextLabel}</Link></Button> : <span />}
</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 {
return `/api/assets/${encodeURIComponent(assetId)}/thumbnail`;
}
+10 -12
View File
@@ -3,6 +3,8 @@
/* eslint-disable @next/next/no-img-element */
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 { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton";
@@ -56,9 +58,11 @@ export function PhotoGallery({
if (items.length === 0) {
return (
<p className="catalog-empty">
Keine Fotos passen zu dieser Suche. Ändern Sie den Suchbegriff oder wählen Sie ein anderes Album.
</p>
<EmptyState
type="no-results"
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);
return (
<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">
✕
</button>
<IconButton className="lightbox-close" icon={IconX} variant="secondary" onClick={onClose} aria-label="Schließen" />
{hasPrev ? (
<button className="lightbox-nav lightbox-prev" type="button" onClick={onPrev} aria-label="Vorheriges Bild">
‹
</button>
<IconButton className="lightbox-nav lightbox-prev" icon={IconChevronLeft} variant="secondary" size="lg" onClick={onPrev} aria-label="Vorheriges Bild" />
) : null}
{hasNext ? (
<button className="lightbox-nav lightbox-next" type="button" onClick={onNext} aria-label="Nächstes Bild">
›
</button>
<IconButton className="lightbox-nav lightbox-next" icon={IconChevronRight} variant="secondary" size="lg" onClick={onNext} aria-label="Nächstes Bild" />
) : null}
<figure className="lightbox-figure">
<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";
@@ -10,21 +12,15 @@ export function AnnouncementBanner({ items }: { items: Announcement[] }) {
}
return (
<div className="space-y-3" role="status">
<div className="flex flex-col gap-3 [&_[role=alert]]:whitespace-pre-line">
{items.map((item) => (
<div
<Alert
key={item.id}
className="bg-primary/10 border border-primary/30 rounded-xl p-4 flex gap-3"
>
<Megaphone className="h-5 w-5 shrink-0 text-primary-600 mt-0.5" aria-hidden="true" />
<div className="min-w-0 space-y-0.5">
<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>
color="neutral"
icon={<IconSpeakerphone size={18} />}
title="Hinweis von Leon Tonhäuser Sportfotografie"
description={`${item.message}\nbezogen auf den ${formatIsoDateGerman(item.eventDate)}`}
/>
))}
</div>
);
+15 -3
View File
@@ -3,12 +3,12 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
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", () => ({
authClient: { resetPassword },
authClient: { resetPassword, signIn: { email: signInEmail } },
}));
import { PasswordResetForm, RegistrationForm } from "./public-forms";
import { LoginForm, PasswordResetForm, RegistrationForm } from "./public-forms";
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();
});
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 { Alert, Button, Input } from "@sakaniui/react";
import { authClient } from "./client";
export type RegistrationFormState = {
@@ -47,59 +49,18 @@ export function RegistrationForm({
const [state, formAction, pending] = useActionState(action, initialRegistrationState);
return (
<form action={formAction} className="account-form">
<form action={formAction} className="flex flex-col gap-6">
<FieldError message={state.errors?.form} />
<div className="form-grid">
<label>
Redaktion oder Unternehmen
<input autoComplete="organization" name="companyName" required />
</label>
<FieldError message={state.errors?.companyName} />
<label>
Ansprechpartner:in
<input autoComplete="name" name="contactName" required />
</label>
<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 className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Input label="Redaktion oder Unternehmen" autoComplete="organization" name="companyName" required error={state.errors?.companyName} />
<Input label="Ansprechpartner:in" autoComplete="name" name="contactName" required error={state.errors?.contactName} />
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" error={state.errors?.email} />
<Input label="Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" error={state.errors?.password} />
<Input label="Straße und Hausnummer" autoComplete="address-line1" name="addressLine1" required error={state.errors?.addressLine1} />
<Input label="Adresszusatz" autoComplete="address-line2" name="addressLine2" />
<Input label="Postleitzahl" autoComplete="postal-code" name="postalCode" required error={state.errors?.postalCode} />
<Input label="Ort" autoComplete="address-level2" name="city" required error={state.errors?.city} />
<Input label="Land (ISO-Code)" autoComplete="country" defaultValue="DE" maxLength={2} name="countryCode" required error={state.errors?.countryCode} />
</div>
<fieldset className="acknowledgements">
@@ -133,10 +94,10 @@ export function RegistrationForm({
<FieldError message={state.errors?.privacyAcknowledged} />
</fieldset>
<button className="primary-action" disabled={pending} type="submit">
<Button disabled={pending} type="submit">
{pending ? "Registrierung wird gesendet …" : "Registrierung senden"}
</button>
<p className="form-note">
</Button>
<p className="text-sm text-[var(--color-fg-muted)]">
Wir informieren Sie auf der nächsten Seite über den weiteren Ablauf.
</p>
</form>
@@ -191,46 +152,31 @@ export function LoginForm() {
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) {
return (
<form className="account-form" onSubmit={submit}>
<p className="form-note">
<form className="flex flex-col gap-4" key="totp" onSubmit={submit}>
<p className="text-sm text-[var(--color-fg-muted)]">
Geben Sie den aktuellen 6-stelligen Code aus Ihrer Authenticator-App ein.
</p>
<label>
Zwei-Faktor-Code
<input
autoComplete="one-time-code"
inputMode="numeric"
maxLength={6}
name="totp"
pattern="[0-9]*"
required
type="text"
/>
</label>
<Input label="Zwei-Faktor-Code" autoComplete="one-time-code" inputMode="numeric" maxLength={6} name="totp" pattern="[0-9]*" required type="text" />
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
<Button disabled={pending} type="submit">
{pending ? "Code wird geprüft …" : "Anmelden"}
</button>
</Button>
</form>
);
}
return (
<form className="account-form" onSubmit={submit}>
<label>
E-Mail-Adresse
<input autoComplete="email" name="email" required type="email" />
</label>
<label>
Passwort
<input autoComplete="current-password" name="password" required type="password" />
</label>
<form className="flex flex-col gap-4" key="credentials" onSubmit={submit}>
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
<Input label="Passwort" autoComplete="current-password" name="password" required type="password" />
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
<Button disabled={pending} type="submit">
{pending ? "Anmeldung wird geprüft …" : "Anmelden"}
</button>
</Button>
</form>
);
}
@@ -257,21 +203,18 @@ export function PasswordResetRequestForm() {
if (submitted) {
return (
<p className="form-note" role="status">
Falls ein Zugang zu dieser Adresse gehört, erhalten Sie in Kürze weitere Hinweise.
</p>
<div role="status">
<Alert color="info" description="Falls ein Zugang zu dieser Adresse gehört, erhalten Sie in Kürze weitere Hinweise." />
</div>
);
}
return (
<form className="account-form" onSubmit={submit}>
<label>
E-Mail-Adresse
<input autoComplete="email" name="email" required type="email" />
</label>
<button className="primary-action" disabled={pending} type="submit">
<form className="flex flex-col gap-4" onSubmit={submit}>
<Input label="E-Mail-Adresse" autoComplete="email" name="email" required type="email" />
<Button disabled={pending} type="submit">
{pending ? "Anfrage wird gesendet …" : "Link anfordern"}
</button>
</Button>
</form>
);
}
@@ -306,9 +249,12 @@ export function PasswordResetForm({ token }: { token?: string }) {
if (success) {
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>
<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
</a>
</div>
@@ -316,15 +262,12 @@ export function PasswordResetForm({ token }: { token?: string }) {
}
return (
<form className="account-form" onSubmit={submit}>
<label>
Neues Passwort
<input autoComplete="new-password" minLength={12} name="password" required type="password" />
</label>
<form className="flex flex-col gap-4" onSubmit={submit}>
<Input label="Neues Passwort" autoComplete="new-password" minLength={12} name="password" required type="password" />
<FieldError message={error} />
<button className="primary-action" disabled={pending} type="submit">
<Button disabled={pending} type="submit">
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
</button>
</Button>
</form>
);
}
@@ -353,11 +296,7 @@ function loginErrorMessage(code: string | undefined): string {
}
function FieldError({ message }: { message?: string }) {
return message ? (
<p className="field-error" role="alert">
{message}
</p>
) : null;
return message ? <Alert color="danger" description={message} /> : null;
}
function readText(formData: FormData, name: string): string {
+8 -14
View File
@@ -3,8 +3,8 @@
import { useActionState } from "react";
import { approveEditorialAction, type ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Check } from "lucide-react";
import { Alert, Input } from "@/components/ui/sakani";
import { IconCheck } from "@sakaniui/react/icons";
export function ApproveForm({ editorialId }: { editorialId: string }) {
const [state, formAction, pending] = useActionState<ApproveActionResult, FormData>(
@@ -13,12 +13,9 @@ export function ApproveForm({ editorialId }: { editorialId: string }) {
);
return (
<form action={formAction} className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
<div className="flex gap-2 items-center">
<label htmlFor="priceEuros" className="text-sm font-medium whitespace-nowrap">
Individueller Nettopreis (€)
</label>
<Input
<form action={formAction} className="flex flex-col gap-4 sm:flex-row sm:items-end">
<Input
label="Individueller Nettopreis (€)"
id="priceEuros"
name="priceEuros"
type="number"
@@ -26,15 +23,12 @@ export function ApproveForm({ editorialId }: { editorialId: string }) {
min="0.01"
required
placeholder="z.B. 15.00"
className="w-32 bg-background"
disabled={pending}
/>
</div>
<Button type="submit" disabled={pending}>
<Check className="w-4 h-4 mr-2" />
{pending ? "Wird freigegeben..." : "Redaktion freigeben"}
<Button type="submit" disabled={pending} leftIcon={<IconCheck size={16} />}>
{pending ? "Wird freigegeben …" : "Redaktion freigeben"}
</Button>
{!state.ok && <p className="text-sm text-destructive font-medium">{state.message}</p>}
{!state.ok && <Alert color="danger" description={state.message} />}
</form>
);
}
+8 -18
View File
@@ -4,7 +4,7 @@ import { useState, useTransition } from "react";
import { archiveEditorialAction, hardDeleteEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
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";
type DangerZoneProps = {
@@ -42,29 +42,24 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
}
return (
<Card className="border-destructive/50 bg-destructive/5 dark:bg-destructive/10">
<Card>
<CardHeader>
<CardTitle className="text-destructive">Gefahrenzone</CardTitle>
<CardTitle className="text-[var(--color-danger-fg)]">Gefahrenzone</CardTitle>
<CardDescription>
Archivieren widerruft alle Albumrechte und deaktiviert den Login.
Endgültiges Löschen entfernt den Account inklusive aller verknüpften Daten unwiderruflich!
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">
Redaktionsname zur Bestätigung eingeben:
</label>
<Input
<CardContent className="flex flex-col gap-4">
<Input
label="Redaktionsname zur Bestätigung eingeben:"
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder={editorialName}
disabled={isPending}
className="border-destructive/30 focus-visible:ring-destructive"
/>
</div>
<div className="flex gap-4">
<div className="flex flex-wrap gap-3">
<Button
type="button"
variant="destructive"
@@ -76,18 +71,13 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
<Button
type="button"
variant="outline"
className="border-destructive text-destructive hover:bg-destructive hover:text-white"
disabled={!isConfirmed || isPending}
onClick={handleDelete}
>
{isDeleting ? "Wird gelöscht…" : "Endgültig löschen"}
</Button>
</div>
{result && !result.ok && (
<p className="text-sm text-destructive" role="alert">
{result.message}
</p>
)}
{result && !result.ok && <Alert color="danger" description={result.message} />}
</CardContent>
</Card>
);
+5 -13
View File
@@ -4,7 +4,7 @@ import { useState, useTransition } from "react";
import { resetUsageDataAction } from "@/app/admin/redaktionen/[id]/actions";
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";
type ResetUsageCardProps = {
@@ -39,19 +39,15 @@ export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardPro
bleiben unverändert.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">
Redaktionsname zur Bestätigung eingeben:
</label>
<Input
<CardContent className="flex flex-col gap-4">
<Input
label="Redaktionsname zur Bestätigung eingeben:"
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder={editorialName}
disabled={isPending}
/>
</div>
<div className="flex items-center gap-4">
<Button
type="button"
@@ -61,11 +57,7 @@ export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardPro
>
{isPending ? "Wird zurückgesetzt…" : "Nutzungsdaten zurücksetzen"}
</Button>
{result && (
<p className={`text-sm ${result.ok ? "text-muted-foreground" : "text-destructive"}`}>
{result.message}
</p>
)}
{result && <Alert color={result.ok ? "success" : "danger"} description={result.message} />}
</div>
</CardContent>
</Card>
+59 -60
View File
@@ -1,7 +1,8 @@
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 { 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 { DangerZone } from "./DangerZone";
import { ResetUsageCard } from "./ResetUsageCard";
@@ -26,17 +27,19 @@ export function EditorialDetailContent({
hasActiveGrant,
}: Readonly<{ editorial: EditorialDetail; hasActiveGrant: boolean }>) {
return (
<div className="space-y-8 max-w-4xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<div>
<p className="text-sm font-semibold uppercase tracking-widest text-primary-600 dark:text-primary-500 mb-2">Redaktion</p>
<h1 className="text-4xl font-bold tracking-tight">{editorial.name}</h1>
</div>
<section className="flex max-w-4xl flex-col gap-6">
<PageHeader kicker="Redaktion" title={editorial.name}>
<Button asChild variant="outline">
<Link href="/admin/redaktionen">Alle Redaktionen</Link>
</Button>
</PageHeader>
{editorial.archivedAt && (
<div className="space-y-4">
<div className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30" role="status">
Diese Redaktion wurde am {new Date(editorial.archivedAt).toLocaleDateString('de-DE')} archiviert.
</div>
<Alert
color="danger"
description={`Diese Redaktion wurde am ${new Date(editorial.archivedAt).toLocaleDateString("de-DE")} archiviert.`}
/>
<Card>
<CardHeader>
<CardTitle>Archivierung aufheben</CardTitle>
@@ -73,7 +76,7 @@ export function EditorialDetailContent({
</div>
<div>
<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>
<dt className="text-sm font-medium text-muted-foreground">E-Mail bestätigt</dt>
@@ -108,14 +111,13 @@ export function EditorialDetailContent({
Redaktion freigeben
</Button>
) : null}
<div className="flex gap-4 text-sm font-medium">
<Link href={`/admin/redaktionen/${editorial.id}/alben`} className="text-primary-600 hover:underline">
Albumrechte verwalten
</Link>
<span className="text-muted-foreground">·</span>
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`} className="text-primary-600 hover:underline">
Auto-Zuweisungsregeln
</Link>
<div className="flex flex-wrap gap-3">
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Albumrechte verwalten</Link>
</Button>
<Button asChild variant="outline">
<Link href={`/admin/redaktionen/${editorial.id}/auto-regeln`}>Auto-Zuweisungsregeln</Link>
</Button>
</div>
</CardContent>
</Card>
@@ -127,56 +129,47 @@ export function EditorialDetailContent({
<CardDescription>Pauschalpreis für Downloads aktivieren.</CardDescription>
</CardHeader>
<CardContent>
<form action={updateFlatrateAction.bind(null, editorial.id)} className="space-y-6">
<div className="flex items-center space-x-2">
<input
type="checkbox"
name="flatrateActive"
id="flatrateActive"
defaultChecked={editorial.flatrateActive}
className="w-4 h-4 rounded border-border text-primary-600 focus:ring-primary-500"
<form action={updateFlatrateAction.bind(null, editorial.id)} className="flex flex-col gap-6">
<Checkbox
defaultChecked={editorial.flatrateActive}
id="flatrateActive"
label="Flatrate aktivieren"
name="flatrateActive"
/>
<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 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>
<div>
<Button type="submit">
Speichern
</Button>
</div>
</form>
</CardContent>
</Card>
)}
{!editorial.archivedAt && (
<Card className="border-border">
<Card>
<CardHeader>
<CardTitle>Status-Aktionen</CardTitle>
</CardHeader>
@@ -204,10 +197,16 @@ export function EditorialDetailContent({
{!editorial.archivedAt && (
<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 {
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: {
environment: "node",
setupFiles: ["src/test/dom-shims.ts"],
env: {
DATABASE_URL: "postgres://db/portal",
BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters",