feat: v2.2 batch (calendar, self-service, sort, description, filename search, stats, collab, invoice) on pre-redesign base

This commit is contained in:
Leon Tonhäuser committed 2026-11-30 21:20:13 +01:00
1 parent 453bece72c
commit 7204dd6b60
108 files changed
+10400 -105

No files matched your search

@@ -17,6 +17,7 @@ const openPosition: BillingPosition = {
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
status: "open",
selectable: true,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
@@ -32,6 +33,7 @@ const billedPosition: BillingPosition = {
purpose: "Sportbericht",
reference: null,
priceCents: 1_500,
collab: false,
status: "billed",
selectable: false,
createdAt: new Date("2026-08-06T10:00:00.000Z"),
@@ -47,6 +49,7 @@ const reopenedPosition: BillingPosition = {
purpose: "Reopened",
reference: null,
priceCents: 1_500,
collab: false,
status: "reopened",
selectable: true,
createdAt: new Date("2026-08-07T10:00:00.000Z"),
@@ -162,6 +162,28 @@ export function BillingSelection({
}
}
async function handleToggleCollab(position: BillingPosition) {
setActionState({ loading: true, message: null, isError: false });
try {
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ collab: !position.collab }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
}
window.location.reload();
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Collab-Kennzeichnung fehlgeschlagen",
isError: true,
});
}
}
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
const quarterHref = quarter
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
@@ -228,7 +250,20 @@ export function BillingSelection({
<td>{position.albumName}</td>
<td>{position.purpose}</td>
<td>{position.reference ?? "—"}</td>
<td className="billing-price">{formatCents(position.priceCents)}</td>
<td className="billing-price">
{formatCents(position.priceCents)}
{position.collab && <span className="billing-collab-badge">Collab</span>}
{position.selectable && (
<button
type="button"
className="billing-collab-toggle"
onClick={() => handleToggleCollab(position)}
disabled={actionState.loading}
>
{position.collab ? "Collab entfernen" : "Als Collab markieren"}
</button>
)}
</td>
<td>
<span className="billing-status">
{STATUS_LABELS[position.status]}
@@ -334,13 +369,48 @@ export function BillingSelection({
</div>
{report.status === "final" && (
<>
<div className="billing-invoice-block">
<p className="billing-invoice-status">
Rechnung:{" "}
{report.invoiceEmailStatus === "sent" ? (
<>
versendet am{" "}
<time
dateTime={report.invoiceEmailSentAt?.toISOString()}
suppressHydrationWarning
>
{report.invoiceEmailSentAt?.toLocaleDateString("de-DE")}
</time>
</>
) : report.hasInvoicePdf ? (
"PDF hinterlegt, Versand fehlgeschlagen"
) : (
"noch keine PDF hinterlegt"
)}
</p>
<InvoiceUploadForm
reportId={report.id}
reportNumber={report.reportNumber}
hasInvoice={report.hasInvoicePdf}
emailFailed={report.hasInvoicePdf && report.invoiceEmailStatus === "failed"}
/>
{report.hasInvoicePdf && (
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}/invoice`}
className="billing-report-download"
download
>
Rechnungs-PDF herunterladen
</a>
)}
</div>
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<a
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}`}
className="billing-report-download"
download
>
PDF herunterladen
Nutzungsnachweis herunterladen
</a>
</>
)}
@@ -403,6 +473,114 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
);
}
type InvoiceUploadFormProps = {
reportId: string;
reportNumber: number;
hasInvoice: boolean;
emailFailed: boolean;
};
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleUpload(event: React.FormEvent) {
event.preventDefault();
if (!file || loading) return;
setLoading(true);
setError(null);
try {
const formData = new FormData();
formData.set("invoice", file);
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/invoice`, {
method: "POST",
body: formData,
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
setLoading(false);
}
}
async function handleResend() {
if (loading) return;
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
{ method: "POST" },
);
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
setLoading(false);
}
}
return (
<form className="billing-invoice-form" onSubmit={handleUpload}>
<label>
<span>
{hasInvoice ? "Rechnungs-PDF ersetzen" : "Rechnungs-PDF hochladen"} (Bericht Nr. {reportNumber})
</span>
<input
type="file"
accept="application/pdf,.pdf"
required
disabled={loading}
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
aria-label={`Rechnungs-PDF für Bericht Nr. ${reportNumber}`}
/>
</label>
<div className="billing-invoice-controls">
<button type="submit" disabled={!file || loading}>
{loading ? "Wird gesendet…" : "Hochladen & senden"}
</button>
{hasInvoice && (
<button type="button" onClick={handleResend} disabled={loading}>
{emailFailed ? "Erneut senden" : "Nochmal senden"}
</button>
)}
</div>
<p className="form-note">
Nach dem Upload geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per
E-Mail an die Redaktion.
</p>
{error && (
<p className="billing-status-message" role="alert">
{error}
</p>
)}
</form>
);
}
function invoiceErrorMessage(code: unknown): string {
switch (code) {
case "INVALID_PDF":
return "Die Datei ist keine gültige PDF (max. 20 MB).";
case "REPORT_NOT_FINAL":
return "Der Bericht ist nicht finalisiert.";
case "INVOICE_NOT_UPLOADED":
return "Es ist noch keine Rechnungs-PDF hinterlegt.";
case "RATE_LIMITED":
return "Zu viele Versuche. Bitte kurz warten.";
default:
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
}
}
type CancelReportFormProps = {
reportId: string;
reportNumber: number;
@@ -15,6 +15,10 @@ export type FinalizedReportSummary = {
netTotalCents: number;
status: string;
createdAt: Date;
hasInvoicePdf: boolean;
invoiceUploadedAt: Date | null;
invoiceEmailStatus: string;
invoiceEmailSentAt: Date | null;
};
export type BillingSelectionData = {
@@ -54,6 +58,10 @@ export async function loadBillingSelection(
netTotalCents: billingReports.netTotalCents,
status: billingReports.status,
createdAt: billingReports.createdAt,
invoicePdfSha256: billingReports.invoicePdfSha256,
invoiceUploadedAt: billingReports.invoiceUploadedAt,
invoiceEmailStatus: billingReports.invoiceEmailStatus,
invoiceEmailSentAt: billingReports.invoiceEmailSentAt,
})
.from(billingReports)
.where(eq(billingReports.editorialAccountId, editorialId))
@@ -77,6 +85,10 @@ export async function loadBillingSelection(
netTotalCents: row.netTotalCents,
status: row.status,
createdAt: row.createdAt,
hasInvoicePdf: row.invoicePdfSha256 !== null,
invoiceUploadedAt: row.invoiceUploadedAt,
invoiceEmailStatus: row.invoiceEmailStatus,
invoiceEmailSentAt: row.invoiceEmailSentAt,
})),
};
}
@@ -0,0 +1,99 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { CalendarActionResult } from "./actions";
export function CalendarEventForm({
action,
defaultEventDate,
albums,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
defaultEventDate: string;
albums: Array<{ id: string; albumName: string }>;
}>) {
const titleId = useId();
const dateId = useId();
const albumId = useId();
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [title, setTitle] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setTitle("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="space-y-2">
<label htmlFor={titleId} className="text-sm font-medium">
Titel (Spielpaarung oder Event)
</label>
<Input
id={titleId}
name="title"
value={title}
onChange={(event) => setTitle(event.target.value)}
maxLength={200}
required
placeholder="z. B. Hamburger SV - VfL Wolfsburg"
/>
<p className="text-xs text-muted-foreground">
Ohne direkte Album-Auswahl wird automatisch verknüpft, sobald ein Album exakt
{" „{Titel}“ "}oder{" „{Titel} | TT.MM.JJJJ“ "}heißt (Datum dieses Termins).
</p>
</div>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={dateId} className="text-sm font-medium">
Datum
</label>
<Input id={dateId} type="date" name="eventDate" defaultValue={defaultEventDate} required className="sm:w-48" />
</div>
<div className="space-y-2 flex-1">
<label htmlFor={albumId} className="text-sm font-medium">
Album direkt verknüpfen (optional)
</label>
<select
id={albumId}
name="immichAlbumId"
defaultValue=""
className="flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Automatisch über den Namen</option>
{albums.map((album) => (
<option key={album.id} value={album.id}>
{album.albumName}
</option>
))}
</select>
</div>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird angelegt…" : "Termin anlegen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
@@ -0,0 +1,44 @@
"use client";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import type { CalendarActionResult } from "./actions";
// Deleting an event also revokes self-service grants on its linked album, so
// the admin confirms once before the action runs.
export function DeleteCalendarEventButton({
action,
eventId,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
eventId: string;
}>) {
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const handleClick = () => {
if (!window.confirm("Termin löschen? Selbst freigeschaltete Zugriffe auf das verknüpfte Album werden entzogen.")) {
return;
}
const formData = new FormData();
formData.set("eventId", eventId);
startTransition(async () => {
setState(await action({ ok: true, message: "" }, formData));
});
};
return (
<div className="flex flex-col items-end gap-1">
<Button type="button" variant="outline" size="sm" disabled={pending} onClick={handleClick}>
{pending ? "…" : "Löschen"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { CalendarServiceError, calendarService } from "@/modules/calendar/service";
export type CalendarActionResult = {
ok: boolean;
message: string;
};
export async function createCalendarEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const title = formData.get("title");
const eventDate = formData.get("eventDate");
const immichAlbumId = formData.get("immichAlbumId");
if (typeof title !== "string" || typeof eventDate !== "string") {
return { ok: false, message: "Bitte Titel und Datum ausfüllen." };
}
try {
await calendarService.createEvent({
title,
eventDate,
immichAlbumId: typeof immichAlbumId === "string" && immichAlbumId ? immichAlbumId : null,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/admin/kalender");
revalidatePath("/redaktion/kalender");
return {
ok: true,
message:
"Termin angelegt. Sobald ein passendes Album in Immich erscheint, können Redaktionen es selbst freischalten.",
};
}
export async function deleteCalendarEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const eventId = formData.get("eventId");
if (typeof eventId !== "string" || eventId.length === 0) {
return { ok: false, message: "Ungültige Kennung." };
}
try {
await calendarService.deleteEvent({ id: eventId, adminUserId: principal.userId });
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/admin/kalender");
revalidatePath("/redaktion/kalender");
revalidatePath("/redaktion/alben");
return { ok: true, message: "" };
}
function calendarErrorMessage(error: unknown): string {
if (error instanceof CalendarServiceError) {
const messages: Record<CalendarServiceError["code"], string> = {
INVALID_TITLE: "Bitte geben Sie einen Titel mit 1 bis 200 Zeichen ein.",
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
INVALID_ALBUM: "Das gewählte Album existiert nicht mehr in Immich.",
INVALID_STATUS: "Ungültige Rückmeldung.",
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verknüpft.",
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
};
return messages[error.code] ?? "Der Termin konnte nicht gespeichert werden.";
}
return "Der Termin konnte nicht gespeichert werden.";
}
+107
View File
@@ -0,0 +1,107 @@
import { PageHeader } from "@/components/ui/page-header";
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
import { calendarService } from "@/modules/calendar/service";
import { immichClient } from "@/modules/immich/client";
import { CalendarEventForm } from "./CalendarEventForm";
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
import { createCalendarEventAction, deleteCalendarEventAction } from "./actions";
export default async function AdminCalendarPage() {
const [{ events, immichUnavailable }, albums] = await Promise.all([
calendarService.listAdminEvents(),
immichClient.listAlbums().catch(() => []),
]);
const today = isoDateInBerlin(new Date());
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Planung"
title="Kalender"
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen melden zurück, ob sie da sind, und können das verknüpfte Album selbst freischalten. Alben ohne Kalender-Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
/>
<CalendarEventForm
action={createCalendarEventAction}
defaultEventDate={today}
albums={albums.map((album) => ({ id: album.id, albumName: album.albumName }))}
/>
{immichUnavailable ? (
<p className="bg-muted p-4 rounded-md text-sm" role="status">
Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht.
</p>
) : null}
<section className="space-y-4" aria-labelledby="calendar-list-title">
<div className="flex items-baseline justify-between">
<h2 id="calendar-list-title" className="text-xl font-semibold">
Alle Termine
</h2>
<p className="text-sm text-muted-foreground">{events.length} insgesamt</p>
</div>
{events.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Termine vorhanden. Legen Sie oben den ersten Termin an.
</p>
) : (
<ul className="space-y-3">
{events.map((event) => {
const attending = event.responses.filter((response) => response.status === "attending");
const notAttending = event.responses.filter((response) => response.status === "not_attending");
return (
<li
key={event.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-2 min-w-0">
<p className="font-semibold">
{event.title}
{event.eventDate < today ? (
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
) : null}
</p>
<p className="text-xs text-muted-foreground">
{formatIsoDateGerman(event.eventDate)} ·{" "}
{event.album ? (
<span>Album: {event.album.albumName}</span>
) : (
<span>Noch kein Album verknüpft</span>
)}
</p>
{event.responses.length > 0 ? (
<div className="flex flex-wrap gap-1.5 text-xs">
{attending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-green-600/10 px-2.5 py-1 font-medium text-green-700 dark:text-green-400"
>
{response.editorialName}: da
</span>
))}
{notAttending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-muted px-2.5 py-1 text-muted-foreground"
>
{response.editorialName}: nicht da
</span>
))}
</div>
) : (
<p className="text-xs text-muted-foreground">Noch keine Rückmeldungen.</p>
)}
</div>
<DeleteCalendarEventButton action={deleteCalendarEventAction} eventId={event.id} />
</li>
);
})}
</ul>
)}
</section>
</div>
);
}
+3
View File
@@ -13,9 +13,12 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
sectionLabel="Administration"
nav={[
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/statistiken", label: "Statistiken" },
{ href: "/admin/redaktionen", label: "Redaktionen" },
{ href: "/admin/alben", label: "Alben" },
{ href: "/admin/kalender", label: "Kalender" },
{ href: "/admin/hinweise", label: "Hinweise" },
{ href: "/admin/versionen", label: "Versionen" },
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
{ href: "/admin/audit", label: "Audit" },
]}
+34
View File
@@ -9,6 +9,7 @@ import { editorialAccounts } from "@/db/schema";
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
import { writeAudit } from "@/modules/audit/write";
// Returned to the client form so failures surface as inline German text
// instead of an opaque Next.js error-digest page (a thrown server action
@@ -203,6 +204,39 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
export async function updateCollabAction(editorialId: string, formData: FormData): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const collabEnabled = formData.get("collabEnabled") === "on";
const [previous] = await db
.select({ collabEnabled: editorialAccounts.collabEnabled })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, safeEditorialId))
.limit(1);
if (!previous) throw new Error("EDITORIAL_NOT_FOUND");
await db
.update(editorialAccounts)
.set({ collabEnabled })
.where(eq(editorialAccounts.id, safeEditorialId));
try {
await writeAudit({
type: "editorial_collab_updated",
actorUserId: admin.userId,
actorType: "admin",
entityType: "editorial_account",
entityId: safeEditorialId,
metadata: { from: previous.collabEnabled, to: collabEnabled },
});
} catch {
// Audit is observability, not a transaction participant.
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
function parsePriceCents(
value: unknown,
): { ok: true; cents: number } | { ok: false; message: string } {
@@ -18,6 +18,7 @@ const editorial = {
flatrateActive: false,
flatratePriceCents: null,
flatrateAssetLimit: null,
collabEnabled: false,
archivedAt: null,
};
+1
View File
@@ -21,6 +21,7 @@ export default async function EditorialDetailPage({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
collabEnabled: editorialAccounts.collabEnabled,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
+358
View File
@@ -0,0 +1,358 @@
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
formatBytes,
normalizeStatsDays,
percentChange,
STATS_PERIOD_OPTIONS,
statsQueries,
} from "@/modules/stats/queries";
import { requireAdminPage } from "../access";
import { ActivityChart, RevenueChart } from "./stats-charts-lazy";
const euroFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const ACTIVITY_LABELS: Record<string, string> = {
album_view: "Album geöffnet",
search: "Suche",
lightbox_view: "Großansicht",
};
export default async function AdminStatsPage({
searchParams,
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
await requireAdminPage();
const sp = await searchParams;
const rawDays = Array.isArray(sp.zeitraum) ? sp.zeitraum[0] : sp.zeitraum;
const days = normalizeStatsDays(rawDays);
const stats = await statsQueries.loadOverview(days);
const { kpis, previousKpis } = stats;
return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
title="Statistiken"
description="Downloads, Aufrufe, Suchen und Umsatz im Detail. Aufrufe und Suchen werden seit Version 2.2 erfasst."
/>
<div className="flex flex-wrap items-center justify-between gap-4">
<nav
aria-label="Zeitraum"
className="inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 p-1"
>
{STATS_PERIOD_OPTIONS.map((option) => (
<Link
key={option}
href={`/admin/statistiken?zeitraum=${option}`}
aria-current={option === days ? "page" : undefined}
className={`rounded-full px-4 py-1.5 text-sm transition-colors ${
option === days
? "bg-card font-semibold shadow-sm"
: "text-muted-foreground hover:text-foreground"
}`}
>
{option} Tage
</Link>
))}
</nav>
<p className="text-sm text-muted-foreground">
Zeitraum: {stats.window.fromUtc.toLocaleDateString("de-DE")} bis{" "}
{stats.window.toUtcExclusive.toLocaleDateString("de-DE")}
</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<KpiCard
label="Downloads"
value={String(kpis.downloadsCompleted)}
hint={`${kpis.downloadsInterrupted} unterbrochen, ${kpis.downloadsFailed} fehlgeschlagen`}
change={percentChange(kpis.downloadsCompleted, previousKpis.downloadsCompleted)}
/>
<KpiCard
label="Datenmenge"
value={formatBytes(kpis.transferredBytes)}
hint="Ausgelieferte Originaldateien"
/>
<KpiCard
label="Neue Nutzungen"
value={String(kpis.newUsages)}
hint={`${kpis.collabUsages} davon Collab (kostenfrei)`}
change={percentChange(kpis.newUsages, previousKpis.newUsages)}
/>
<KpiCard
label="Umsatz im Zeitraum"
value={euroFormatter.format(kpis.revenueCents / 100)}
hint="Netto, aus neuen Nutzungen"
change={percentChange(kpis.revenueCents, previousKpis.revenueCents)}
/>
<KpiCard
label="Album-Aufrufe"
value={String(kpis.albumViews)}
hint="Seitenaufrufe der Albumansicht"
change={percentChange(kpis.albumViews, previousKpis.albumViews)}
/>
<KpiCard
label="Suchen"
value={String(kpis.searches)}
hint="In Alben und über alle Alben"
change={percentChange(kpis.searches, previousKpis.searches)}
/>
<KpiCard
label="Großansichten"
value={String(kpis.lightboxViews)}
hint="Lightbox-Öffnungen"
change={percentChange(kpis.lightboxViews, previousKpis.lightboxViews)}
/>
<KpiCard
label="Aktive Redaktionen"
value={String(kpis.activeEditorials)}
hint="Mit mindestens einem Download"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Offener Umsatz gesamt
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">
{euroFormatter.format(stats.openRevenueCents / 100)}
</p>
<p className="mt-1 text-sm text-muted-foreground">
Noch nicht abgerechnete Nutzungen
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Abrechnungen im Zeitraum
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">{stats.finalizedReports}</p>
<p className="mt-1 text-sm text-muted-foreground">Finalisierte Nutzungsnachweise</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Collab-Quote
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">
{kpis.newUsages > 0
? `${Math.round((kpis.collabUsages / kpis.newUsages) * 100)} %`
: "0 %"}
</p>
<p className="mt-1 text-sm text-muted-foreground">
Anteil kostenfreier Collab-Nutzungen
</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Aktivität der letzten {days} Tage</CardTitle>
<CardDescription>
Downloads, Album-Aufrufe und Suchen pro Tag über alle Redaktionen.
</CardDescription>
</CardHeader>
<CardContent>
<ActivityChart data={stats.daily} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Umsatz pro Tag</CardTitle>
<CardDescription>Netto-Umsatz aus neuen Nutzungen im Zeitraum.</CardDescription>
</CardHeader>
<CardContent>
<RevenueChart data={stats.daily} />
</CardContent>
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<Card>
<CardHeader>
<CardTitle>Redaktionen im Zeitraum</CardTitle>
<CardDescription>Nach Downloads sortiert.</CardDescription>
</CardHeader>
<CardContent>
{stats.topEditorials.length === 0 ? (
<p className="text-sm text-muted-foreground">Noch keine Daten vorhanden.</p>
) : (
<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">Redaktion</th>
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-right">Collab</th>
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
<th className="py-3 px-4 font-semibold text-right">Aufrufe</th>
<th className="py-3 px-4 font-semibold text-right">Suchen</th>
</tr>
</thead>
<tbody>
{stats.topEditorials.map((row, index) => (
<tr
key={row.editorialId}
className={index !== stats.topEditorials.length - 1 ? "border-b border-border" : ""}
>
<td className="py-3 px-4">
<Link
href={`/admin/redaktionen/${row.editorialId}`}
className="font-medium text-primary-600 hover:underline dark:text-primary-400"
>
{row.name}
</Link>
</td>
<td className="py-3 px-4 text-right tabular-nums">{row.downloads}</td>
<td className="py-3 px-4 text-right tabular-nums">
{row.collabUsages > 0 ? (
<span className="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground">
{row.collabUsages}
</span>
) : (
"0"
)}
</td>
<td className="py-3 px-4 text-right tabular-nums">
{euroFormatter.format(row.revenueCents / 100)}
</td>
<td className="py-3 px-4 text-right tabular-nums">{row.views}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.searches}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Alben im Zeitraum</CardTitle>
<CardDescription>Nach Downloads und Aufrufen sortiert.</CardDescription>
</CardHeader>
<CardContent>
{stats.topAlbums.length === 0 ? (
<p className="text-sm text-muted-foreground">Noch keine Daten vorhanden.</p>
) : (
<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 text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-right">Aufrufe</th>
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
</tr>
</thead>
<tbody>
{stats.topAlbums.map((row, index) => (
<tr
key={row.albumKey}
className={index !== stats.topAlbums.length - 1 ? "border-b border-border" : ""}
>
<td className="py-3 px-4 font-medium">{row.albumName}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.downloads}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.views}</td>
<td className="py-3 px-4 text-right tabular-nums">
{euroFormatter.format(row.revenueCents / 100)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Letzte Aktivitäten</CardTitle>
<CardDescription>Die neuesten erfassten Aktionen der Redaktionen.</CardDescription>
</CardHeader>
<CardContent>
{stats.recentActivity.length === 0 ? (
<p className="text-sm text-muted-foreground">
Noch keine Aktivitäten erfasst. Aufrufe und Suchen werden ab Version 2.2 gezählt.
</p>
) : (
<ul className="divide-y divide-border">
{stats.recentActivity.map((event) => (
<li key={event.id} className="flex flex-wrap items-center gap-3 py-2.5 text-sm">
<span className="inline-flex items-center rounded-full border border-border px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
{ACTIVITY_LABELS[event.eventType] ?? event.eventType}
</span>
<span className="font-medium">{event.editorialName}</span>
{event.query ? (
<span className="text-muted-foreground">„{event.query}“</span>
) : null}
<time
className="ml-auto text-xs text-muted-foreground tabular-nums"
dateTime={event.occurredAt.toISOString()}
suppressHydrationWarning
>
{event.occurredAt.toLocaleString("de-DE", {
day: "2-digit",
month: "2-digit",
hour: "2-digit",
minute: "2-digit",
})}
</time>
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
);
}
type KpiCardProps = {
label: string;
value: string;
hint: string;
change?: number | null;
};
function KpiCard({ label, value, hint, change }: KpiCardProps) {
return (
<Card className="transition-shadow hover:shadow-md">
<CardContent className="pt-6">
<div className="flex items-start justify-between gap-2">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</p>
{change !== undefined && change !== null ? (
<span
className={`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[11px] font-semibold tabular-nums ${
change > 0
? "border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-400"
: change < 0
? "border-red-300 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-950/40 dark:text-red-400"
: "border-border bg-muted/40 text-muted-foreground"
}`}
title="Veränderung gegenüber dem vorherigen Zeitraum"
>
{change > 0 ? "+" : ""}
{change} %
</span>
) : null}
</div>
<p className="mt-2 text-3xl font-bold tabular-nums">{value}</p>
<p className="mt-1 text-sm text-muted-foreground">{hint}</p>
</CardContent>
</Card>
);
}
@@ -0,0 +1,15 @@
"use client";
import dynamic from "next/dynamic";
const ActivityChart = dynamic(
() => import("./stats-charts").then((mod) => mod.ActivityChart),
{ ssr: false },
);
const RevenueChart = dynamic(
() => import("./stats-charts").then((mod) => mod.RevenueChart),
{ ssr: false },
);
export { ActivityChart, RevenueChart };
+177
View File
@@ -0,0 +1,177 @@
"use client";
import { useTheme } from "next-themes";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { DailyPoint } from "@/modules/stats/queries";
type StatsChartsProps = {
data: DailyPoint[];
};
const euroFormatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
function useChartColors() {
const { theme } = useTheme();
const dark = theme === "dark";
return {
grid: dark ? "#333333" : "#e5e5e5",
axis: "#888888",
tooltip: {
backgroundColor: dark ? "#1f2937" : "#ffffff",
borderColor: dark ? "#374151" : "#e5e7eb",
color: dark ? "#f3f4f6" : "#111827",
},
cursor: dark ? "#ffffff10" : "#00000005",
downloads: dark ? "#6366f1" : "#4f46e5",
views: dark ? "#34d399" : "#059669",
searches: dark ? "#fbbf24" : "#d97706",
};
}
function formatDay(value: string): string {
return new Date(value).toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
}
function formatDayLong(value: string): string {
return new Date(value).toLocaleDateString("de-DE", {
weekday: "long",
day: "2-digit",
month: "long",
year: "numeric",
});
}
export function ActivityChart({ data }: StatsChartsProps) {
const colors = useChartColors();
return (
<div className="h-[300px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="statsDownloads" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={colors.downloads} stopOpacity={0.25} />
<stop offset="100%" stopColor={colors.downloads} stopOpacity={0.02} />
</linearGradient>
<linearGradient id="statsViews" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={colors.views} stopOpacity={0.25} />
<stop offset="100%" stopColor={colors.views} stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={colors.grid} />
<XAxis
dataKey="date"
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={formatDay}
minTickGap={24}
/>
<YAxis
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
allowDecimals={false}
/>
<Tooltip
cursor={{ stroke: colors.grid }}
contentStyle={{
...colors.tooltip,
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
}}
labelFormatter={(label) => formatDayLong(String(label))}
/>
<Legend wrapperStyle={{ fontSize: 12 }} />
<Area
type="monotone"
dataKey="downloads"
name="Downloads"
stroke={colors.downloads}
fill="url(#statsDownloads)"
strokeWidth={2}
/>
<Area
type="monotone"
dataKey="views"
name="Album-Aufrufe"
stroke={colors.views}
fill="url(#statsViews)"
strokeWidth={2}
/>
<Area
type="monotone"
dataKey="searches"
name="Suchen"
stroke={colors.searches}
fill="transparent"
strokeWidth={2}
strokeDasharray="4 3"
/>
</AreaChart>
</ResponsiveContainer>
</div>
);
}
export function RevenueChart({ data }: StatsChartsProps) {
const colors = useChartColors();
return (
<div className="h-[260px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={colors.grid} />
<XAxis
dataKey="date"
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={formatDay}
minTickGap={24}
/>
<YAxis
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value: number) => `${value} €`}
/>
<Tooltip
cursor={{ fill: colors.cursor }}
contentStyle={{
...colors.tooltip,
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
}}
labelFormatter={(label) => formatDayLong(String(label))}
formatter={(value) => [euroFormatter.format(Number(value) / 100), "Umsatz"]}
/>
<Bar
dataKey="revenueCents"
name="Umsatz"
fill={colors.downloads}
radius={[4, 4, 0, 0]}
maxBarSize={40}
/>
</BarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,31 @@
"use client";
import { useActionState } from "react";
import { Button } from "@/components/ui/button";
import type { ReleaseNoteActionResult } from "./actions";
export function DeleteReleaseNoteButton({
action,
noteId,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
noteId: string;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction} className="flex flex-col items-end gap-1">
<input type="hidden" name="noteId" value={noteId} />
<Button type="submit" variant="outline" size="sm" disabled={pending}>
{pending ? "…" : "Löschen"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</form>
);
}
@@ -0,0 +1,91 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ReleaseNoteActionResult } from "./actions";
export function ReleaseNoteForm({
action,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
}>) {
const versionId = useId();
const audienceId = useId();
const bodyId = useId();
const [state, setState] = useState<ReleaseNoteActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [body, setBody] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setBody("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={versionId} className="text-sm font-medium">
Version
</label>
<Input id={versionId} name="version" placeholder="z. B. 2.1.1" required className="sm:w-36" />
</div>
<div className="space-y-2">
<label htmlFor={audienceId} className="text-sm font-medium">
Zielgruppe
</label>
<select
id={audienceId}
name="audience"
defaultValue="editorial"
className="flex h-10 w-full sm:w-48 rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="editorial">Redaktionen</option>
<option value="admin">Admins</option>
<option value="both">Beide</option>
</select>
</div>
</div>
<div className="space-y-2">
<label htmlFor={bodyId} className="text-sm font-medium">
Hinweis
</label>
<textarea
id={bodyId}
name="body"
rows={4}
maxLength={2000}
required
value={body}
onChange={(event) => setBody(event.target.value)}
placeholder="Was ist neu in dieser Version?"
className="flex w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-xs text-muted-foreground">{body.length}/2000 Zeichen</p>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
+83
View File
@@ -0,0 +1,83 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import {
ReleaseNoteServiceError,
releaseNoteService,
type ReleaseNoteAudience,
} from "@/modules/releases/service";
export type ReleaseNoteActionResult = {
ok: boolean;
message: string;
};
export async function createReleaseNoteAction(
_prevState: ReleaseNoteActionResult,
formData: FormData,
): Promise<ReleaseNoteActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const version = formData.get("version");
const audience = formData.get("audience");
const body = formData.get("body");
if (typeof version !== "string" || typeof body !== "string") {
return { ok: false, message: "Bitte Version und Text ausfüllen." };
}
if (audience !== "admin" && audience !== "editorial" && audience !== "both") {
return { ok: false, message: "Bitte Zielgruppe wählen." };
}
try {
await releaseNoteService.createReleaseNote({
version,
audience: audience as ReleaseNoteAudience,
body,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: releaseNoteErrorMessage(error) };
}
revalidatePath("/admin/versionen");
revalidatePath("/redaktion/neuigkeiten");
return { ok: true, message: "Versionshinweis veröffentlicht." };
}
export async function deleteReleaseNoteAction(
_prevState: ReleaseNoteActionResult,
formData: FormData,
): Promise<ReleaseNoteActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const noteId = formData.get("noteId");
if (typeof noteId !== "string" || noteId.length === 0) {
return { ok: false, message: "Ungültige Kennung." };
}
try {
await releaseNoteService.deleteReleaseNote({ id: noteId, adminUserId: principal.userId });
} catch (error) {
return { ok: false, message: releaseNoteErrorMessage(error) };
}
revalidatePath("/admin/versionen");
revalidatePath("/redaktion/neuigkeiten");
return { ok: true, message: "" };
}
function releaseNoteErrorMessage(error: unknown): string {
if (error instanceof ReleaseNoteServiceError) {
const messages: Record<ReleaseNoteServiceError["code"], string> = {
INVALID_VERSION: "Bitte eine Version wie 2.1 oder 2.1.1 angeben.",
INVALID_BODY: "Bitte einen Text mit 1 bis 2000 Zeichen eingeben.",
INVALID_AUDIENCE: "Bitte Zielgruppe wählen.",
DUPLICATE_RELEASE_NOTE: "Für diese Version und Zielgruppe gibt es bereits einen Hinweis.",
RELEASE_NOTE_NOT_FOUND: "Dieser Hinweis existiert nicht mehr.",
};
return messages[error.code] ?? "Der Hinweis konnte nicht gespeichert werden.";
}
return "Der Hinweis konnte nicht gespeichert werden.";
}
+66
View File
@@ -0,0 +1,66 @@
import { PageHeader } from "@/components/ui/page-header";
import { releaseNoteService, type ReleaseNoteAudience } from "@/modules/releases/service";
import { DeleteReleaseNoteButton } from "./DeleteReleaseNoteButton";
import { ReleaseNoteForm } from "./ReleaseNoteForm";
import { createReleaseNoteAction, deleteReleaseNoteAction } from "./actions";
const audienceLabels: Record<ReleaseNoteAudience, string> = {
admin: "Admins",
editorial: "Redaktionen",
both: "Beide",
};
export default async function AdminVersionsPage() {
const notes = await releaseNoteService.listReleaseNotes();
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Portal"
title="Versionshinweise"
description="Was sich im Portal geändert hat, getrennt nach Zielgruppe. Redaktionen sehen ihre Hinweise unter Neuigkeiten. Jede Veröffentlichung im Portal bekommt hier einen Eintrag und eine fortlaufende Versionsnummer."
/>
<ReleaseNoteForm action={createReleaseNoteAction} />
<section className="space-y-4" aria-labelledby="release-notes-list-title">
<div className="flex items-baseline justify-between">
<h2 id="release-notes-list-title" className="text-xl font-semibold">
Alle Hinweise
</h2>
<p className="text-sm text-muted-foreground">{notes.length} insgesamt</p>
</div>
{notes.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Versionshinweise vorhanden.
</p>
) : (
<ul className="space-y-3">
{notes.map((note) => (
<li
key={note.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-1 min-w-0">
<p className="text-sm font-semibold">
Version {note.version}
<span className="ml-2 rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
{audienceLabels[note.audience]}
</span>
</p>
<p className="text-sm whitespace-pre-line break-words">{note.body}</p>
<p className="text-xs text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(note.createdAt)}
</p>
</div>
<DeleteReleaseNoteButton action={deleteReleaseNoteAction} noteId={note.id} />
</li>
))}
</ul>
)}
</section>
</div>
);
}