Merge v2.1-2.2.0 features onto SakaniUI base
Ports calendar, self-service, sorting, image descriptions, logo (2.1), filename search (2.1.1), statistics page, collab option and bundled invoice PDF delivery (2.2.0) onto the deployed SakaniUI portal. Also fixes the statistics daily series, which ended yesterday and so hid today's activity from the charts, and ignores Playwright test-results/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
c0c2425dda
106 files changed
+10000
-110
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"),
|
||||
|
||||
@@ -173,6 +173,28 @@ export function BillingSelection({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleCollab(position: BillingPosition) {
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
try {
|
||||
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ collab: !position.collab }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Collab-Kennzeichnung fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
|
||||
const quarterHref = quarter
|
||||
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
|
||||
@@ -227,7 +249,25 @@ export function BillingSelection({
|
||||
key: "priceCents",
|
||||
header: "Preis",
|
||||
align: "right",
|
||||
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
|
||||
render: (position) => (
|
||||
<span className="flex flex-col items-end gap-1">
|
||||
<span className="flex items-center gap-2 tabular-nums">
|
||||
{formatCents(position.priceCents)}
|
||||
{position.collab && <Badge variant="neutral">Collab</Badge>}
|
||||
</span>
|
||||
{position.selectable && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleToggleCollab(position)}
|
||||
disabled={actionState.loading}
|
||||
>
|
||||
{position.collab ? "Collab entfernen" : "Als Collab markieren"}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
@@ -330,11 +370,47 @@ export function BillingSelection({
|
||||
<Button asChild variant="outline">
|
||||
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
|
||||
<IconDownload size={16} aria-hidden="true" />
|
||||
PDF herunterladen
|
||||
Nutzungsnachweis herunterladen
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{report.status === "final" && (
|
||||
<div className="flex flex-col gap-3 rounded-[var(--radius-lg)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-subtle)] p-4">
|
||||
<p className="text-sm font-medium">
|
||||
Rechnung:{" "}
|
||||
{report.invoiceEmailStatus === "sent" ? (
|
||||
<>
|
||||
versendet am{" "}
|
||||
<time
|
||||
dateTime={report.invoiceEmailSentAt?.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{report.invoiceEmailSentAt?.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</>
|
||||
) : report.hasInvoicePdf ? (
|
||||
"PDF hinterlegt, Versand fehlgeschlagen"
|
||||
) : (
|
||||
"noch keine PDF hinterlegt"
|
||||
)}
|
||||
</p>
|
||||
<InvoiceUploadForm
|
||||
reportId={report.id}
|
||||
reportNumber={report.reportNumber}
|
||||
hasInvoice={report.hasInvoicePdf}
|
||||
emailFailed={report.hasInvoicePdf && report.invoiceEmailStatus === "failed"}
|
||||
/>
|
||||
{report.hasInvoicePdf && (
|
||||
<Button asChild variant="outline">
|
||||
<a href={`/api/billing-reports/${encodeURIComponent(report.id)}/invoice`} download>
|
||||
<IconDownload size={16} aria-hidden="true" />
|
||||
Rechnungs-PDF herunterladen
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{report.status === "final" && (
|
||||
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
|
||||
)}
|
||||
@@ -389,6 +465,111 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
|
||||
);
|
||||
}
|
||||
|
||||
type InvoiceUploadFormProps = {
|
||||
reportId: string;
|
||||
reportNumber: number;
|
||||
hasInvoice: boolean;
|
||||
emailFailed: boolean;
|
||||
};
|
||||
|
||||
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleUpload(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!file || loading) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.set("invoice", file);
|
||||
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/invoice`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResend() {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-3" onSubmit={handleUpload}>
|
||||
<label className="flex flex-col gap-1 text-sm font-medium">
|
||||
<span>
|
||||
{hasInvoice ? "Rechnungs-PDF ersetzen" : "Rechnungs-PDF hochladen"} (Bericht Nr. {reportNumber})
|
||||
</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
required
|
||||
disabled={loading}
|
||||
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
|
||||
aria-label={`Rechnungs-PDF für Bericht Nr. ${reportNumber}`}
|
||||
className="text-sm text-[var(--color-fg-muted)] file:mr-3 file:rounded-[var(--radius-md)] file:border file:border-[var(--color-border-subtle)] file:bg-[var(--color-bg-surface)] file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-[var(--color-fg-default)]"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" disabled={!file || loading}>
|
||||
{loading ? "Wird gesendet…" : "Hochladen & senden"}
|
||||
</Button>
|
||||
{hasInvoice && (
|
||||
<Button type="button" variant="outline" onClick={handleResend} disabled={loading}>
|
||||
{emailFailed ? "Erneut senden" : "Nochmal senden"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
Nach dem Upload geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per
|
||||
E-Mail an die Redaktion.
|
||||
</p>
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function invoiceErrorMessage(code: unknown): string {
|
||||
switch (code) {
|
||||
case "INVALID_PDF":
|
||||
return "Die Datei ist keine gültige PDF (max. 20 MB).";
|
||||
case "REPORT_NOT_FINAL":
|
||||
return "Der Bericht ist nicht finalisiert.";
|
||||
case "INVOICE_NOT_UPLOADED":
|
||||
return "Es ist noch keine Rechnungs-PDF hinterlegt.";
|
||||
case "RATE_LIMITED":
|
||||
return "Zu viele Versuche. Bitte kurz warten.";
|
||||
default:
|
||||
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
|
||||
}
|
||||
}
|
||||
|
||||
type CancelReportFormProps = {
|
||||
reportId: string;
|
||||
reportNumber: number;
|
||||
|
||||
@@ -15,6 +15,10 @@ export type FinalizedReportSummary = {
|
||||
netTotalCents: number;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
hasInvoicePdf: boolean;
|
||||
invoiceUploadedAt: Date | null;
|
||||
invoiceEmailStatus: string;
|
||||
invoiceEmailSentAt: Date | null;
|
||||
};
|
||||
|
||||
export type BillingSelectionData = {
|
||||
@@ -54,6 +58,10 @@ export async function loadBillingSelection(
|
||||
netTotalCents: billingReports.netTotalCents,
|
||||
status: billingReports.status,
|
||||
createdAt: billingReports.createdAt,
|
||||
invoicePdfSha256: billingReports.invoicePdfSha256,
|
||||
invoiceUploadedAt: billingReports.invoiceUploadedAt,
|
||||
invoiceEmailStatus: billingReports.invoiceEmailStatus,
|
||||
invoiceEmailSentAt: billingReports.invoiceEmailSentAt,
|
||||
})
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.editorialAccountId, editorialId))
|
||||
@@ -77,6 +85,10 @@ export async function loadBillingSelection(
|
||||
netTotalCents: row.netTotalCents,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt,
|
||||
hasInvoicePdf: row.invoicePdfSha256 !== null,
|
||||
invoiceUploadedAt: row.invoiceUploadedAt,
|
||||
invoiceEmailStatus: row.invoiceEmailStatus,
|
||||
invoiceEmailSentAt: row.invoiceEmailSentAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
export function CalendarEventForm({
|
||||
action,
|
||||
defaultEventDate,
|
||||
albums,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
defaultEventDate: string;
|
||||
albums: Array<{ id: string; albumName: string }>;
|
||||
}>) {
|
||||
const titleId = useId();
|
||||
const dateId = useId();
|
||||
const albumId = useId();
|
||||
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [title, setTitle] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
if (result.ok) {
|
||||
setTitle("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
action={handleSubmit}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={titleId} className="text-sm font-medium">
|
||||
Titel (Spielpaarung oder Event)
|
||||
</label>
|
||||
<Input
|
||||
id={titleId}
|
||||
name="title"
|
||||
value={title}
|
||||
onChange={(event) => setTitle(event.target.value)}
|
||||
maxLength={200}
|
||||
required
|
||||
placeholder="z. B. Hamburger SV - VfL Wolfsburg"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ohne direkte Album-Auswahl wird automatisch verknüpft, sobald ein Album exakt
|
||||
{" „{Titel}“ "}oder{" „{Titel} | TT.MM.JJJJ“ "}heißt (Datum dieses Termins).
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={dateId} className="text-sm font-medium">
|
||||
Datum
|
||||
</label>
|
||||
<Input id={dateId} type="date" name="eventDate" defaultValue={defaultEventDate} required className="sm:w-48" />
|
||||
</div>
|
||||
<div className="space-y-2 flex-1">
|
||||
<label htmlFor={albumId} className="text-sm font-medium">
|
||||
Album direkt verknüpfen (optional)
|
||||
</label>
|
||||
<select
|
||||
id={albumId}
|
||||
name="immichAlbumId"
|
||||
defaultValue=""
|
||||
className="flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||
>
|
||||
<option value="">Automatisch über den Namen</option>
|
||||
{albums.map((album) => (
|
||||
<option key={album.id} value={album.id}>
|
||||
{album.albumName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird angelegt…" : "Termin anlegen"}
|
||||
</Button>
|
||||
{state.message ? (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
|
||||
>
|
||||
{state.message}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
// Deleting an event also revokes self-service grants on its linked album, so
|
||||
// the admin confirms once before the action runs.
|
||||
export function DeleteCalendarEventButton({
|
||||
action,
|
||||
eventId,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
eventId: string;
|
||||
}>) {
|
||||
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
if (!window.confirm("Termin löschen? Selbst freigeschaltete Zugriffe auf das verknüpfte Album werden entzogen.")) {
|
||||
return;
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
setState(await action({ ok: true, message: "" }, formData));
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button type="button" variant="outline" size="sm" disabled={pending} onClick={handleClick}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
{state.ok ? null : (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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.";
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, BarChart, Card, DataTable, EmptyState, StatCard } from "@/components/ui/sakani";
|
||||
import {
|
||||
formatBytes,
|
||||
normalizeStatsDays,
|
||||
percentChange,
|
||||
STATS_PERIOD_OPTIONS,
|
||||
statsQueries,
|
||||
} from "@/modules/stats/queries";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
|
||||
const euroFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
const ACTIVITY_LABELS: Record<string, string> = {
|
||||
album_view: "Album geöffnet",
|
||||
search: "Suche",
|
||||
lightbox_view: "Großansicht",
|
||||
};
|
||||
|
||||
export default async function AdminStatsPage({
|
||||
searchParams,
|
||||
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
|
||||
await requireAdminPage();
|
||||
const sp = await searchParams;
|
||||
const rawDays = Array.isArray(sp.zeitraum) ? sp.zeitraum[0] : sp.zeitraum;
|
||||
const days = normalizeStatsDays(rawDays);
|
||||
const stats = await statsQueries.loadOverview(days);
|
||||
const { kpis, previousKpis } = stats;
|
||||
|
||||
const activityData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.downloads,
|
||||
value2: day.views,
|
||||
}));
|
||||
const searchData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.searches,
|
||||
}));
|
||||
const revenueData = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.revenueCents / 100,
|
||||
}));
|
||||
const hasActivity = stats.daily.some((day) => day.downloads + day.views + day.searches > 0);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Statistiken"
|
||||
description="Downloads, Aufrufe, Suchen und Umsatz im Detail. Aufrufe und Suchen werden seit Version 2.2 erfasst."
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<nav
|
||||
aria-label="Zeitraum"
|
||||
className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-subtle)] bg-[var(--color-bg-subtle)] p-1"
|
||||
>
|
||||
{STATS_PERIOD_OPTIONS.map((option) => (
|
||||
<Link
|
||||
key={option}
|
||||
href={`/admin/statistiken?zeitraum=${option}`}
|
||||
aria-current={option === days ? "page" : undefined}
|
||||
className={`rounded-full px-4 py-1.5 text-sm transition-colors ${
|
||||
option === days
|
||||
? "bg-[var(--color-bg-surface)] font-semibold shadow-[var(--shadow-sm)]"
|
||||
: "text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]"
|
||||
}`}
|
||||
>
|
||||
{option} Tage
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Zeitraum: {stats.window.fromUtc.toLocaleDateString("de-DE")} bis{" "}
|
||||
{stats.window.toUtcExclusive.toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatCard
|
||||
title="Downloads"
|
||||
value={String(kpis.downloadsCompleted)}
|
||||
description={`${kpis.downloadsInterrupted} unterbrochen, ${kpis.downloadsFailed} fehlgeschlagen`}
|
||||
{...trendProps(percentChange(kpis.downloadsCompleted, previousKpis.downloadsCompleted))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Datenmenge"
|
||||
value={formatBytes(kpis.transferredBytes)}
|
||||
description="Ausgelieferte Originaldateien"
|
||||
/>
|
||||
<StatCard
|
||||
title="Neue Nutzungen"
|
||||
value={String(kpis.newUsages)}
|
||||
description={`${kpis.collabUsages} davon Collab (kostenfrei)`}
|
||||
{...trendProps(percentChange(kpis.newUsages, previousKpis.newUsages))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Umsatz im Zeitraum"
|
||||
value={euroFormatter.format(kpis.revenueCents / 100)}
|
||||
description="Netto, aus neuen Nutzungen"
|
||||
{...trendProps(percentChange(kpis.revenueCents, previousKpis.revenueCents))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Album-Aufrufe"
|
||||
value={String(kpis.albumViews)}
|
||||
description="Seitenaufrufe der Albumansicht"
|
||||
{...trendProps(percentChange(kpis.albumViews, previousKpis.albumViews))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Suchen"
|
||||
value={String(kpis.searches)}
|
||||
description="In Alben und über alle Alben"
|
||||
{...trendProps(percentChange(kpis.searches, previousKpis.searches))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Großansichten"
|
||||
value={String(kpis.lightboxViews)}
|
||||
description="Lightbox-Öffnungen"
|
||||
{...trendProps(percentChange(kpis.lightboxViews, previousKpis.lightboxViews))}
|
||||
/>
|
||||
<StatCard
|
||||
title="Aktive Redaktionen"
|
||||
value={String(kpis.activeEditorials)}
|
||||
description="Mit mindestens einem Download"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard
|
||||
title="Offener Umsatz gesamt"
|
||||
value={euroFormatter.format(stats.openRevenueCents / 100)}
|
||||
description="Noch nicht abgerechnete Nutzungen"
|
||||
/>
|
||||
<StatCard
|
||||
title="Abrechnungen im Zeitraum"
|
||||
value={String(stats.finalizedReports)}
|
||||
description="Finalisierte Nutzungsnachweise"
|
||||
/>
|
||||
<StatCard
|
||||
title="Collab-Quote"
|
||||
value={kpis.newUsages > 0 ? `${Math.round((kpis.collabUsages / kpis.newUsages) * 100)} %` : "0 %"}
|
||||
description="Anteil kostenfreier Collab-Nutzungen"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card
|
||||
title={`Aktivität der letzten ${days} Tage`}
|
||||
description="Downloads und Album-Aufrufe pro Tag über alle Redaktionen."
|
||||
>
|
||||
{hasActivity ? (
|
||||
<BarChart
|
||||
data={activityData}
|
||||
variant="multiple"
|
||||
seriesLabels={["Downloads", "Album-Aufrufe"]}
|
||||
size="lg"
|
||||
appearance="rich"
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="Noch keine Aktivität"
|
||||
description="Downloads und Aufrufe erscheinen hier, sobald Redaktionen das Portal nutzen."
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Suchen pro Tag" description="Suchanfragen in Alben und über alle Alben.">
|
||||
{stats.daily.some((day) => day.searches > 0) ? (
|
||||
<BarChart data={searchData} seriesLabels={["Suchen"]} size="md" />
|
||||
) : (
|
||||
<EmptyState title="Keine Suchen" description="Im Zeitraum wurden keine Suchen erfasst." />
|
||||
)}
|
||||
</Card>
|
||||
<Card title="Umsatz pro Tag" description="Netto-Umsatz aus neuen Nutzungen in Euro.">
|
||||
{stats.daily.some((day) => day.revenueCents > 0) ? (
|
||||
<BarChart data={revenueData} seriesLabels={["Umsatz (€)"]} size="md" />
|
||||
) : (
|
||||
<EmptyState title="Kein Umsatz" description="Im Zeitraum wurden keine neuen Nutzungen erfasst." />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Redaktionen im Zeitraum" description="Nach Downloads sortiert.">
|
||||
{stats.topEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "name", header: "Redaktion" },
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
{ key: "collab", header: "Collab", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
{ key: "views", header: "Aufrufe", align: "right" },
|
||||
{ key: "searches", header: "Suchen", align: "right" },
|
||||
]}
|
||||
rows={stats.topEditorials.map((row) => ({
|
||||
id: row.editorialId,
|
||||
name: (
|
||||
<Link
|
||||
href={`/admin/redaktionen/${row.editorialId}`}
|
||||
className="font-medium text-[var(--color-brand-fg)] hover:underline"
|
||||
>
|
||||
{row.name}
|
||||
</Link>
|
||||
),
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
collab: row.collabUsages > 0 ? <Badge variant="neutral">{row.collabUsages}</Badge> : <span className="tabular-nums">0</span>,
|
||||
revenue: <span className="tabular-nums">{euroFormatter.format(row.revenueCents / 100)}</span>,
|
||||
views: <span className="tabular-nums">{row.views}</span>,
|
||||
searches: <span className="tabular-nums">{row.searches}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="Alben im Zeitraum" description="Nach Downloads und Aufrufen sortiert.">
|
||||
{stats.topAlbums.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "albumName", header: "Album" },
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
{ key: "views", header: "Aufrufe", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
]}
|
||||
rows={stats.topAlbums.map((row) => ({
|
||||
id: row.albumKey,
|
||||
albumName: row.albumName,
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
views: <span className="tabular-nums">{row.views}</span>,
|
||||
revenue: <span className="tabular-nums">{euroFormatter.format(row.revenueCents / 100)}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card title="Letzte Aktivitäten" description="Die neuesten erfassten Aktionen der Redaktionen.">
|
||||
{stats.recentActivity.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Noch keine Aktivitäten erfasst"
|
||||
description="Aufrufe und Suchen werden ab Version 2.2 gezählt."
|
||||
/>
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{stats.recentActivity.map((event) => (
|
||||
<li key={event.id} className="flex flex-wrap items-center gap-3 py-2.5 text-sm">
|
||||
<Badge variant="neutral">{ACTIVITY_LABELS[event.eventType] ?? event.eventType}</Badge>
|
||||
<span className="font-medium">{event.editorialName}</span>
|
||||
{event.query ? <span className="text-[var(--color-fg-muted)]">„{event.query}“</span> : null}
|
||||
<time
|
||||
className="ml-auto text-xs tabular-nums text-[var(--color-fg-muted)]"
|
||||
dateTime={event.occurredAt.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{event.occurredAt.toLocaleString("de-DE", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</time>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function trendProps(change: number | null): { delta?: string; trend?: "up" | "down" | "flat" } {
|
||||
if (change === null) return {};
|
||||
return {
|
||||
delta: `${change > 0 ? "+" : ""}${change} %`,
|
||||
trend: change > 0 ? "up" : change < 0 ? "down" : "flat",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
|
||||
export function DeleteReleaseNoteButton({
|
||||
action,
|
||||
noteId,
|
||||
}: Readonly<{
|
||||
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
|
||||
noteId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
<input type="hidden" name="noteId" value={noteId} />
|
||||
<Button type="submit" variant="outline" size="sm" disabled={pending}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
{state.ok ? null : (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
|
||||
export function ReleaseNoteForm({
|
||||
action,
|
||||
}: Readonly<{
|
||||
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
|
||||
}>) {
|
||||
const versionId = useId();
|
||||
const audienceId = useId();
|
||||
const bodyId = useId();
|
||||
const [state, setState] = useState<ReleaseNoteActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [body, setBody] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
if (result.ok) {
|
||||
setBody("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
action={handleSubmit}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
|
||||
>
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={versionId} className="text-sm font-medium">
|
||||
Version
|
||||
</label>
|
||||
<Input id={versionId} name="version" placeholder="z. B. 2.1.1" required className="sm:w-36" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={audienceId} className="text-sm font-medium">
|
||||
Zielgruppe
|
||||
</label>
|
||||
<select
|
||||
id={audienceId}
|
||||
name="audience"
|
||||
defaultValue="editorial"
|
||||
className="flex h-10 w-full sm:w-48 rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
|
||||
>
|
||||
<option value="editorial">Redaktionen</option>
|
||||
<option value="admin">Admins</option>
|
||||
<option value="both">Beide</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={bodyId} className="text-sm font-medium">
|
||||
Hinweis
|
||||
</label>
|
||||
<textarea
|
||||
id={bodyId}
|
||||
name="body"
|
||||
rows={4}
|
||||
maxLength={2000}
|
||||
required
|
||||
value={body}
|
||||
onChange={(event) => setBody(event.target.value)}
|
||||
placeholder="Was ist neu in dieser Version?"
|
||||
className="flex w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{body.length}/2000 Zeichen</p>
|
||||
</div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
|
||||
</Button>
|
||||
{state.message ? (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
|
||||
>
|
||||
{state.message}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import {
|
||||
ReleaseNoteServiceError,
|
||||
releaseNoteService,
|
||||
type ReleaseNoteAudience,
|
||||
} from "@/modules/releases/service";
|
||||
|
||||
export type ReleaseNoteActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createReleaseNoteAction(
|
||||
_prevState: ReleaseNoteActionResult,
|
||||
formData: FormData,
|
||||
): Promise<ReleaseNoteActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const version = formData.get("version");
|
||||
const audience = formData.get("audience");
|
||||
const body = formData.get("body");
|
||||
|
||||
if (typeof version !== "string" || typeof body !== "string") {
|
||||
return { ok: false, message: "Bitte Version und Text ausfüllen." };
|
||||
}
|
||||
if (audience !== "admin" && audience !== "editorial" && audience !== "both") {
|
||||
return { ok: false, message: "Bitte Zielgruppe wählen." };
|
||||
}
|
||||
|
||||
try {
|
||||
await releaseNoteService.createReleaseNote({
|
||||
version,
|
||||
audience: audience as ReleaseNoteAudience,
|
||||
body,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: releaseNoteErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/versionen");
|
||||
revalidatePath("/redaktion/neuigkeiten");
|
||||
return { ok: true, message: "Versionshinweis veröffentlicht." };
|
||||
}
|
||||
|
||||
export async function deleteReleaseNoteAction(
|
||||
_prevState: ReleaseNoteActionResult,
|
||||
formData: FormData,
|
||||
): Promise<ReleaseNoteActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const noteId = formData.get("noteId");
|
||||
if (typeof noteId !== "string" || noteId.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await releaseNoteService.deleteReleaseNote({ id: noteId, adminUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: releaseNoteErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/versionen");
|
||||
revalidatePath("/redaktion/neuigkeiten");
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
|
||||
function releaseNoteErrorMessage(error: unknown): string {
|
||||
if (error instanceof ReleaseNoteServiceError) {
|
||||
const messages: Record<ReleaseNoteServiceError["code"], string> = {
|
||||
INVALID_VERSION: "Bitte eine Version wie 2.1 oder 2.1.1 angeben.",
|
||||
INVALID_BODY: "Bitte einen Text mit 1 bis 2000 Zeichen eingeben.",
|
||||
INVALID_AUDIENCE: "Bitte Zielgruppe wählen.",
|
||||
DUPLICATE_RELEASE_NOTE: "Für diese Version und Zielgruppe gibt es bereits einen Hinweis.",
|
||||
RELEASE_NOTE_NOT_FOUND: "Dieser Hinweis existiert nicht mehr.",
|
||||
};
|
||||
return messages[error.code] ?? "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
return "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user