Release 2.4.0: bulk download rework, toasts and Sakani polish
- ZIP download from the Merkzettel: every photo is a new usage by default; only already downloaded photos offer "Neu / Bereits genutzt" (SegmentedControl), with thumbnails and a cost summary. "Bild auslassen" is gone. - Toasts (Sakani Toaster) for admin saves, deletes and errors; billing errors are readable and use router.refresh instead of reloads. Errors inside modal dialogs stay inline (a toast would sit behind the backdrop). - Album overview in blog-listing style, Sakani Pagination for albums, search and usage history, skeleton loading states. - Registration stepper; verification mail lands on step 3. - Editorials as a searchable, filterable table; audit log with event picker, German labels and collapsible details. - Release notes 2.4.0 seeded (migration 0009). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2775b406bf
commit
cba70310f9
48 files changed
+3450
-430
No files matched your search
@@ -26,7 +26,8 @@ Aktueller Stand: siehe neueste Einträge in `release_notes` (Basis `2.0.0`,
|
||||
Kalender/Selbstbedienung/Sortierung/Beschreibung: `2.1.0`,
|
||||
Dateiname-Suche: `2.1.1`, Statistik/Collab/Rechnungsversand: `2.2.0`,
|
||||
Quartalsabrechnung + Sakani-Formulare: `2.2.1`, Versionshistorie: `2.2.2`,
|
||||
Kategorien/Vormerken/Monatskalender/Dashboard: `2.3.0`).
|
||||
Kategorien/Vormerken/Monatskalender/Dashboard: `2.3.0`,
|
||||
Mehrfach-Download/Toasts/Sakani-Feinschliff: `2.4.0`).
|
||||
|
||||
## Sicherheit (bei jeder Änderung mitprüfen)
|
||||
|
||||
|
||||
@@ -92,3 +92,12 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her
|
||||
- **Dashboard (`/admin`):** `src/modules/dashboard/tasks.ts` (rein, getestet) + `queries.ts` (Aufgaben-Zähler), Rest aus `statsQueries.loadOverview(30)` und `calendarService.listAdminEvents()`.
|
||||
- **drizzle-kit generate ohne TTY:** Fragt bei "neue Tabelle + gelöschte Tabelle" interaktiv nach Umbenennung und bricht ohne Terminal ab. Lösung: in zwei Schritten generieren (erst hinzufügen, dann löschen), so entstanden 0006 und 0007.
|
||||
|
||||
## 12. Mehrfach-Download, Toasts, Sakani-Feinschliff (Stand 2026-11, v2.4)
|
||||
- **Toasts:** Ein `<AppToaster />` (Sakani `Toaster`, unten rechts) im Root-Layout. Helfer in `src/components/ui/feedback.tsx`: `notifyResult(result, fallback)` für Actions mit `{ ok, message }`, `useResultToast(state)` für `useActionState`, `ToastForm` für Server-Actions ohne Rückgabe (Speichern + `router.refresh()`). Bei Seiten, die vorher `window.location.reload()` nutzten (Abrechnungen), jetzt `router.refresh()`, sonst wäre der Toast weg.
|
||||
- **Toasts nicht in modalen Dialogen:** Native `<dialog>.showModal()` liegt im Top-Layer; ein Toast landet dahinter. Fehler in Nutzungsdialog und ZIP-Dialog bleiben deshalb als `Alert` im Dialog; Erfolg kommt als Toast nach dem Schließen.
|
||||
- **Mehrfach-Download (`DownloadLightboxForm`):** Standard ist für jedes Bild "Neue Nutzung" (gemeinsamer Zweck, optional eigener je Bild). Nur Bilder mit früheren Nutzungen bekommen einen `SegmentedControl` "Neue Nutzung / Bereits genutzt" (Voreinstellung neue Nutzung, vom Nutzer so gewählt); bei mehreren früheren Nutzungen Auswahl per `Select`, sonst die eine. "Bild auslassen" gibt es nicht mehr (Bilder werden über den Merkzettel entfernt). API-Payload unverändert.
|
||||
- **Pagination:** `UrlPagination` (`src/components/ui/url-pagination.tsx`, Sakani `Pagination`) für Album, Cross-Album-Suche und Nutzungshistorie. Die Quellen liefern nur "hat nächste Seite", daher `total = page + 1` solange es weitergeht. Cursor-basierte Auslieferungsliste bleibt bei `PageLinks`.
|
||||
- **Albenübersicht:** Blog-Listing-Optik (randloses 3:2-Cover, Anzahl, Titel, Beschreibung); Cover ist dekorativ (`alt=""`), der Titel im Link benennt es. Skeletons hinter Covern/Fotokacheln und in `loading.tsx`.
|
||||
- **Registrierung:** `RegistrationSteps` (Sakani `Stepper`, mobil vertikal). Die Bestätigungsmail führt auf `/registrieren/bestaetigt?schritt=freigabe` (Schritt 3), das Formular auf die Seite ohne Parameter (Schritt 2).
|
||||
- **Redaktionen:** `EditorialsTable` (Client, Sakani `Table` + Suche + Statusfilter; "Alle" ohne Archivierte). **Audit:** Ereignis als Auswahl der vorhandenen Typen (`selectDistinct`), deutsche Bezeichnungen (`EVENT_LABELS` in `src/app/admin/audit/page.tsx`, neue Audit-Typen dort ergänzen), Details aufklappbar.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Custom SQL migration file, put your code below! --
|
||||
INSERT INTO "release_notes" ("version", "audience", "body", "created_by_user_id")
|
||||
VALUES
|
||||
('2.4.0', 'admin', 'Neu in 2.4: Speichern und Ändern bestätigt das Portal mit einer kurzen Meldung, Fehler bei Abrechnungen sind verständlich formuliert. Redaktionen erscheinen als Tabelle mit Suche, Statusfilter und offenen Beträgen. Das Audit-Protokoll hat eine Ereignisauswahl, lesbare Bezeichnungen und aufklappbare Details. Die Registrierung zeigt den Ablauf in Schritten.', NULL),
|
||||
('2.4.0', 'editorial', 'Neu in 2.4: Beim ZIP-Download vom Merkzettel laufen alle Bilder als neue Nutzung; nur bei schon geladenen Bildern wählen Sie zwischen neuer Nutzung und kostenloser Wiederholung. Die Albenübersicht zeigt große Vorschaubilder, unter den Fotos gibt es Seitenzahlen, und Bestätigungen erscheinen als kurze Meldung unten rechts.', NULL)
|
||||
ON CONFLICT ("version", "audience") DO NOTHING;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,13 @@
|
||||
"when": 1796077763423,
|
||||
"tag": "0008_release_notes_2_3_0",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1796079496182,
|
||||
"tag": "0009_release_notes_2_4_0",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,16 +1,30 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { RegistrationSteps } from "@/components/layout/registration-steps";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function RegistrationConfirmedPage() {
|
||||
// Two arrivals share this page: right after the form (e-mail still to
|
||||
// confirm) and from the confirmation link (?schritt=freigabe, see auth.ts).
|
||||
export default async function RegistrationConfirmedPage({
|
||||
searchParams,
|
||||
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
|
||||
const { schritt } = await searchParams;
|
||||
const confirmed = schritt === "freigabe";
|
||||
|
||||
return (
|
||||
<PublicShell
|
||||
kicker="Registrierung"
|
||||
title="Vielen Dank."
|
||||
title={confirmed ? "E-Mail bestätigt." : "Vielen Dank."}
|
||||
titleId="confirmation-title"
|
||||
lede="Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach prüfen wir Ihre Registrierung."
|
||||
lede={
|
||||
confirmed
|
||||
? "Wir prüfen jetzt Ihre Registrierung und melden uns per E-Mail, sobald Ihr Zugang freigeschaltet ist."
|
||||
: "Wir haben Ihnen eine E-Mail geschickt. Bitte bestätigen Sie Ihre Adresse über den Link darin. Danach prüfen wir Ihre Registrierung."
|
||||
}
|
||||
wide
|
||||
>
|
||||
<RegistrationSteps current={confirmed ? 2 : 1} />
|
||||
<div>
|
||||
<Button asChild>
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { PublicShell } from "@/components/layout/public-shell";
|
||||
import { RegistrationSteps } from "@/components/layout/registration-steps";
|
||||
import { env } from "@/config/env";
|
||||
import { registerEditorial } from "@/modules/auth/auth";
|
||||
import {
|
||||
@@ -23,6 +24,7 @@ export default function RegistrationPage() {
|
||||
lede="Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung."
|
||||
wide
|
||||
>
|
||||
<RegistrationSteps current={0} />
|
||||
<RegistrationForm
|
||||
action={registerAction}
|
||||
legalUrls={{
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
import { BillingSelection } from "./BillingSelection";
|
||||
import type { FinalizedReportSummary } from "./page-content";
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Badge, Checkbox, EmptyState, Table, Textarea, toast } from "@sakaniui/react";
|
||||
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -49,11 +50,8 @@ export function BillingSelection({
|
||||
reports,
|
||||
}: BillingSelectionProps) {
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
const [actionState, setActionState] = useState<{
|
||||
loading: boolean;
|
||||
message: string | null;
|
||||
isError: boolean;
|
||||
}>({ loading: false, message: null, isError: false });
|
||||
const router = useRouter();
|
||||
const [actionState, setActionState] = useState({ loading: false });
|
||||
|
||||
const selectablePositions = useMemo(
|
||||
() => positions.filter((p) => p.selectable),
|
||||
@@ -91,7 +89,7 @@ export function BillingSelection({
|
||||
|
||||
async function handlePreview() {
|
||||
if (selectedIds.size === 0) return;
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch("/api/billing-reports/preview", {
|
||||
method: "POST",
|
||||
@@ -104,25 +102,22 @@ export function BillingSelection({
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Vorschau fehlgeschlagen");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
window.open(url, "_blank");
|
||||
URL.revokeObjectURL(url);
|
||||
setActionState({ loading: false, message: null, isError: false });
|
||||
setActionState({ loading: false });
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Vorschau fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleFinalize() {
|
||||
if (selectedIds.size === 0) return;
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch("/api/billing-reports", {
|
||||
method: "POST",
|
||||
@@ -135,26 +130,21 @@ export function BillingSelection({
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Abrechnung konnte nicht erstellt werden");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
const result = await response.json();
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: `Abrechnung Nr. ${result.reportNumber} wurde erstellt.`,
|
||||
isError: false,
|
||||
});
|
||||
window.location.reload();
|
||||
setActionState({ loading: false });
|
||||
setSelectedIds(new Set());
|
||||
toast.success(`Abrechnung Nr. ${result.reportNumber} wurde erstellt.`);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Abrechnung fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleCollab(position: BillingPosition) {
|
||||
setActionState({ loading: true, message: null, isError: false });
|
||||
setActionState({ loading: true });
|
||||
try {
|
||||
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
|
||||
method: "POST",
|
||||
@@ -163,15 +153,14 @@ export function BillingSelection({
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
setActionState({ loading: false });
|
||||
toast.success(position.collab ? "Collab-Kennzeichnung entfernt." : "Als Collab-Nutzung markiert.");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setActionState({
|
||||
loading: false,
|
||||
message: error instanceof Error ? error.message : "Collab-Kennzeichnung fehlgeschlagen",
|
||||
isError: true,
|
||||
});
|
||||
setActionState({ loading: false });
|
||||
toast.error(error instanceof Error ? error.message : billingErrorMessage(null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,11 +297,6 @@ export function BillingSelection({
|
||||
</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 && (
|
||||
@@ -432,15 +416,14 @@ type InvoiceUploadFormProps = {
|
||||
};
|
||||
|
||||
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
|
||||
const router = useRouter();
|
||||
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);
|
||||
@@ -452,17 +435,17 @@ function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }:
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
toast.success(`Rechnung zu Bericht Nr. ${reportNumber} hochgeladen. Der Versand an die Redaktion läuft.`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
|
||||
setLoading(false);
|
||||
toast.error(err instanceof Error ? err.message : invoiceErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
async function handleResend() {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
|
||||
@@ -472,11 +455,12 @@ function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }:
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(invoiceErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
toast.success("Rechnung erneut versendet.");
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
|
||||
setLoading(false);
|
||||
toast.error(err instanceof Error ? err.message : invoiceErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -509,7 +493,6 @@ function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }:
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -535,10 +518,10 @@ type CancelReportFormProps = {
|
||||
};
|
||||
|
||||
function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
const router = useRouter();
|
||||
const [reason, setReason] = useState("");
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const trimmed = reason.trim();
|
||||
const valid = trimmed.length >= 5 && trimmed.length <= 500 && confirmed;
|
||||
@@ -547,7 +530,6 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
event.preventDefault();
|
||||
if (!valid) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/cancel`, {
|
||||
method: "POST",
|
||||
@@ -556,13 +538,14 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||
throw new Error(body.code ?? "Stornierung fehlgeschlagen");
|
||||
throw new Error(billingErrorMessage(body.code));
|
||||
}
|
||||
window.location.reload();
|
||||
toast.success(`Bericht Nr. ${reportNumber} storniert. Die Nutzungen sind wieder offen.`);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Stornierung fehlgeschlagen");
|
||||
setLoading(false);
|
||||
toast.error(err instanceof Error ? err.message : billingErrorMessage(null));
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -587,7 +570,30 @@ function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||
{loading ? "Wird storniert …" : "Stornieren"}
|
||||
</Button>
|
||||
</div>
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function billingErrorMessage(code: unknown): string {
|
||||
switch (code) {
|
||||
case "NO_USAGES_SELECTED":
|
||||
return "Bitte mindestens eine offene Nutzung auswählen.";
|
||||
case "USAGE_NOT_ELIGIBLE":
|
||||
case "USAGE_NOT_FOUND":
|
||||
return "Eine der gewählten Nutzungen ist nicht mehr abrechenbar. Bitte die Seite neu laden.";
|
||||
case "ADDRESS_NOT_FOUND":
|
||||
return "Für diese Redaktion fehlt die Rechnungsadresse.";
|
||||
case "EDITORIAL_NOT_FOUND":
|
||||
return "Diese Redaktion existiert nicht mehr.";
|
||||
case "REPORT_NOT_FOUND":
|
||||
return "Dieser Bericht existiert nicht mehr.";
|
||||
case "INVALID_CANCELLATION_REASON":
|
||||
return "Bitte einen Stornierungsgrund mit 5 bis 500 Zeichen angeben.";
|
||||
case "REPORT_NUMBER_COLLISION":
|
||||
return "Die Berichtsnummer war gerade vergeben. Bitte erneut versuchen.";
|
||||
case "RATE_LIMITED":
|
||||
return "Zu viele Versuche. Bitte kurz warten.";
|
||||
default:
|
||||
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,13 @@
|
||||
import { useActionState, useMemo, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Alert, Checkbox, EmptyState, Input, Table } from "@sakaniui/react";
|
||||
import { 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 type { AlbumAccessActionResult } from "./actions";
|
||||
import { notifyResult, useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
type AccessAction = (
|
||||
state: AlbumAccessActionResult,
|
||||
@@ -42,12 +43,12 @@ export function AlbumAccessManager({
|
||||
bulkGrantAction: AccessAction;
|
||||
revokeAction: AccessAction;
|
||||
}>) {
|
||||
const [bulkState, setBulkState] = useState<AlbumAccessActionResult>(INITIAL_RESULT);
|
||||
const [bulkPending, startBulkTransition] = useTransition();
|
||||
const [revokeState, revokeFormAction, revokePending] = useActionState(
|
||||
revokeAction,
|
||||
INITIAL_RESULT,
|
||||
);
|
||||
useResultToast(revokeState);
|
||||
const [selectedAlbumIds, setSelectedAlbumIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [selectedEditorialIds, setSelectedEditorialIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [bulkSearch, setBulkSearch] = useState("");
|
||||
@@ -58,7 +59,7 @@ export function AlbumAccessManager({
|
||||
const handleBulkSubmit = (formData: FormData) => {
|
||||
startBulkTransition(async () => {
|
||||
const result = await bulkGrantAction(INITIAL_RESULT, formData);
|
||||
setBulkState(result);
|
||||
notifyResult(result);
|
||||
if (result.ok && result.grantedCount > 0) {
|
||||
setSelectedAlbumIds(new Set());
|
||||
setSelectedEditorialIds(new Set());
|
||||
@@ -255,13 +256,9 @@ export function AlbumAccessManager({
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
|
||||
{bulkState.message ? (
|
||||
<Alert color={bulkState.ok ? "success" : "danger"} description={bulkState.message} />
|
||||
) : (
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Wähle mindestens ein Album und eine Redaktion aus.
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit || bulkPending} className="shrink-0">
|
||||
{bulkPending ? "Wird verarbeitet…" : submitLabel}
|
||||
</Button>
|
||||
@@ -291,9 +288,6 @@ export function AlbumAccessManager({
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{revokeState.message ? (
|
||||
<Alert color={revokeState.ok ? "success" : "danger"} description={revokeState.message} />
|
||||
) : null}
|
||||
|
||||
{albums.length === 0 ? (
|
||||
<EmptyState title="Derzeit sind keine Alben vorhanden." description="Alben erscheinen hier, sobald der Immich-Zugang sie lesen kann." />
|
||||
|
||||
@@ -2,7 +2,9 @@ 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 { Badge, Card, DataTable, EmptyState, FormSelect, Input } from "@/components/ui/sakani";
|
||||
import { db } from "@/db/client";
|
||||
import { auditEvents } from "@/db/schema";
|
||||
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
@@ -24,14 +26,21 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
const dateTo = firstParam(params, "dateTo");
|
||||
const cursor = firstParam(params, "cursor");
|
||||
|
||||
const page = await listAuditEvents(
|
||||
const [page, typeRows] = await Promise.all([
|
||||
listAuditEvents(
|
||||
{
|
||||
eventType: eventType || undefined,
|
||||
dateFrom: dateFrom ? berlinDateToUtc(dateFrom) : undefined,
|
||||
dateTo: dateTo ? berlinDateToUtcEndOfDay(dateTo) : undefined,
|
||||
},
|
||||
cursor || null,
|
||||
);
|
||||
),
|
||||
db.selectDistinct({ eventType: auditEvents.eventType }).from(auditEvents).orderBy(auditEvents.eventType),
|
||||
]);
|
||||
const typeOptions = [
|
||||
{ label: "Alle Ereignisse", value: "" },
|
||||
...typeRows.map(({ eventType: type }) => ({ label: eventLabel(type), value: type })),
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6" aria-labelledby="audit-title">
|
||||
@@ -44,7 +53,7 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
|
||||
<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" />
|
||||
<FormSelect defaultValue={eventType ?? ""} label="Ereignis" name="eventType" options={typeOptions} />
|
||||
<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>
|
||||
@@ -58,16 +67,30 @@ export default async function AuditPage({ searchParams }: { searchParams: Search
|
||||
columns={[
|
||||
{ key: "at", header: "Zeitstempel" },
|
||||
{ key: "actor", header: "Akteur" },
|
||||
{ key: "type", header: "Ereignistyp" },
|
||||
{ key: "type", header: "Ereignis" },
|
||||
{ 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>,
|
||||
actor: (
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<Badge variant={ACTOR_BADGES[event.actorType]?.variant ?? "neutral"}>
|
||||
{ACTOR_BADGES[event.actorType]?.label ?? event.actorType}
|
||||
</Badge>
|
||||
{event.actorType === "system" ? null : (
|
||||
<span className="break-all text-xs text-[var(--color-fg-muted)]">{actorLabel(event)}</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
type: (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{eventLabel(event.eventType)}</span>
|
||||
<code className="break-all text-xs text-[var(--color-fg-muted)]">{event.eventType}</code>
|
||||
</div>
|
||||
),
|
||||
subject: <span className="break-all text-xs text-[var(--color-fg-muted)]">{entityLabel(event)}</span>,
|
||||
details: <AuditDetails event={event} />,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
@@ -104,10 +127,65 @@ function entityLabel(event: AuditEventRow): string {
|
||||
return `${event.entityType} · ${event.entityId}`;
|
||||
}
|
||||
|
||||
function formatMetadata(event: AuditEventRow): string {
|
||||
const ACTOR_BADGES: Record<string, { label: string; variant: "info" | "accent" | "neutral" }> = {
|
||||
admin: { label: "Admin", variant: "accent" },
|
||||
editorial: { label: "Redaktion", variant: "info" },
|
||||
system: { label: "System", variant: "neutral" },
|
||||
};
|
||||
|
||||
const EVENT_LABELS: Record<string, string> = {
|
||||
album_granted: "Album freigegeben",
|
||||
album_revoked: "Albumzugriff entzogen",
|
||||
album_self_granted: "Album selbst freigeschaltet",
|
||||
announcement_created: "Hinweis veröffentlicht",
|
||||
announcement_deleted: "Hinweis gelöscht",
|
||||
billable_usage_created: "Neue Nutzung",
|
||||
billing_address_replaced: "Rechnungsadresse geändert",
|
||||
billing_report_cancelled: "Abrechnung storniert",
|
||||
billing_report_finalized: "Abrechnung erstellt",
|
||||
calendar_event_created: "Termin angelegt",
|
||||
calendar_event_deleted: "Termin gelöscht",
|
||||
editorial_approved: "Redaktion freigegeben",
|
||||
editorial_collab_updated: "Collab-Einstellung geändert",
|
||||
event_category_created: "Kategorie angelegt",
|
||||
event_category_deleted: "Kategorie gelöscht",
|
||||
event_reservation_removed: "Vormerkung entfernt",
|
||||
event_reserved: "Termin vorgemerkt",
|
||||
event_response_recorded: "Rückmeldung zu Termin",
|
||||
invoice_email_failed: "Rechnungsmail fehlgeschlagen",
|
||||
invoice_email_sent: "Rechnungsmail versendet",
|
||||
invoice_uploaded: "Rechnung hochgeladen",
|
||||
release_note_created: "Versionshinweis angelegt",
|
||||
release_note_deleted: "Versionshinweis gelöscht",
|
||||
usage_collab_updated: "Collab-Kennzeichnung geändert",
|
||||
};
|
||||
|
||||
function eventLabel(type: string): string {
|
||||
return EVENT_LABELS[type] ?? type.replaceAll("_", " ");
|
||||
}
|
||||
|
||||
function AuditDetails({ event }: Readonly<{ event: AuditEventRow }>) {
|
||||
const detail = event.newValues ?? event.previousValues;
|
||||
if (!detail) return "—";
|
||||
return JSON.stringify(detail, null, 2);
|
||||
if (!detail || typeof detail !== "object") {
|
||||
return <span className="text-[var(--color-fg-muted)]">-</span>;
|
||||
}
|
||||
const entries = Object.entries(detail as Record<string, unknown>);
|
||||
if (entries.length === 0) return <span className="text-[var(--color-fg-muted)]">-</span>;
|
||||
return (
|
||||
<details className="group text-xs">
|
||||
<summary className="cursor-pointer select-none font-medium text-[var(--color-fg-muted)] hover:text-[var(--color-fg-default)]">
|
||||
{entries.length === 1 ? "1 Angabe" : `${entries.length} Angaben`}
|
||||
</summary>
|
||||
<dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1">
|
||||
{entries.map(([key, value]) => (
|
||||
<div className="contents" key={key}>
|
||||
<dt className="text-[var(--color-fg-muted)]">{key}</dt>
|
||||
<dd className="break-all font-mono">{typeof value === "string" ? value : JSON.stringify(value)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function berlinDateToUtc(dateStr: string): Date | undefined {
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Alert, Input, Textarea } from "@sakaniui/react";
|
||||
import { Input, Textarea } from "@sakaniui/react";
|
||||
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
// Same direct-call-in-transition pattern as the album bulk grant form so the
|
||||
// message box clears after a successful publish without an effect.
|
||||
@@ -24,14 +25,13 @@ export function AnnouncementForm({
|
||||
}>) {
|
||||
const messageId = useId();
|
||||
const dateId = useId();
|
||||
const [state, setState] = useState<AnnouncementActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [message, setMessage] = useState("");
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setMessage("");
|
||||
}
|
||||
@@ -69,11 +69,6 @@ export function AnnouncementForm({
|
||||
{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>
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IconTrash } from "@sakaniui/react/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
import { useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
// One tiny form per announcement row so every delete button reports its own
|
||||
// result inline (same pattern as AlbumGrantForm).
|
||||
@@ -21,6 +22,7 @@ export function DeleteAnnouncementButton({
|
||||
announcementId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
useResultToast(state, "Hinweis gelöscht.");
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
@@ -28,11 +30,6 @@ export function DeleteAnnouncementButton({
|
||||
<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-[var(--color-danger-fg)]">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Alert, Input } from "@sakaniui/react";
|
||||
import { Input } from "@sakaniui/react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function CalendarEventForm({
|
||||
action,
|
||||
@@ -22,14 +23,13 @@ export function CalendarEventForm({
|
||||
}>) {
|
||||
const titleId = useId();
|
||||
const dateId = 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);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setTitle("");
|
||||
}
|
||||
@@ -80,11 +80,6 @@ export function CalendarEventForm({
|
||||
{pending ? "Wird angelegt …" : "Termin anlegen"}
|
||||
</Button>
|
||||
</div>
|
||||
{state.message ? (
|
||||
<div aria-live="polite">
|
||||
<Alert color={state.ok ? "success" : "danger"} description={state.message} />
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
// Deleting an event also revokes self-service grants on its linked album, so
|
||||
// the admin confirms once before the action runs.
|
||||
@@ -15,7 +16,6 @@ export function DeleteCalendarEventButton({
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
eventId: string;
|
||||
}>) {
|
||||
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
@@ -25,7 +25,7 @@ export function DeleteCalendarEventButton({
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
setState(await action({ ok: true, message: "" }, formData));
|
||||
notifyResult(await action({ ok: true, message: "" }, formData), "Termin gelöscht.");
|
||||
});
|
||||
};
|
||||
|
||||
@@ -34,11 +34,6 @@ export function DeleteCalendarEventButton({
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
import { Alert, Input } from "@sakaniui/react";
|
||||
import { Input } from "@sakaniui/react";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -9,6 +9,7 @@ import { Card } from "@/components/ui/sakani";
|
||||
import { CATEGORY_COLOR_LABELS, CATEGORY_COLORS, type CategoryColor } from "@/modules/calendar/colors";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function CategoryForm({
|
||||
action,
|
||||
@@ -16,13 +17,12 @@ export function CategoryForm({
|
||||
const nameId = useId();
|
||||
const [name, setName] = useState("");
|
||||
const [color, setColor] = useState<CategoryColor>("blue");
|
||||
const [state, setState] = useState<CategoryActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleSubmit = (formData: FormData) => {
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
notifyResult(result);
|
||||
if (result.ok) setName("");
|
||||
});
|
||||
};
|
||||
@@ -73,11 +73,6 @@ export function CategoryForm({
|
||||
{pending ? "Wird gespeichert …" : "Kategorie speichern"}
|
||||
</Button>
|
||||
</div>
|
||||
{state.message ? (
|
||||
<div aria-live="polite">
|
||||
<Alert color={state.ok ? "success" : "danger"} description={state.message} />
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function DeleteCategoryButton({
|
||||
action,
|
||||
@@ -15,13 +16,12 @@ export function DeleteCategoryButton({
|
||||
categoryId: string;
|
||||
inUse: boolean;
|
||||
}>) {
|
||||
const [state, setState] = useState<CategoryActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
const formData = new FormData();
|
||||
formData.set("categoryId", categoryId);
|
||||
startTransition(async () => setState(await action({ ok: true, message: "" }, formData)));
|
||||
startTransition(async () => notifyResult(await action({ ok: true, message: "" }, formData), "Kategorie gelöscht."));
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -36,11 +36,6 @@ export function DeleteCategoryButton({
|
||||
>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
{state.ok ? null : (
|
||||
<p className="text-xs text-[var(--color-danger-fg)]" role="alert">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Badge, EmptyState, Input, SegmentedControl, Table, type TableColumn } from "@sakaniui/react";
|
||||
import { IconSearch } from "@sakaniui/react/icons";
|
||||
|
||||
export type EditorialRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
contactName: string;
|
||||
loginEmail: string;
|
||||
status: string;
|
||||
archived: boolean;
|
||||
priceCents: number | null;
|
||||
openCents: number;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type StatusKey = "active" | "pending" | "suspended" | "archived";
|
||||
|
||||
const STATUS: Record<StatusKey, { label: string; variant: "success" | "warning" | "danger" | "neutral" }> = {
|
||||
active: { label: "Aktiv", variant: "success" },
|
||||
pending: { label: "Ausstehend", variant: "warning" },
|
||||
suspended: { label: "Gesperrt", variant: "danger" },
|
||||
archived: { label: "Archiviert", variant: "neutral" },
|
||||
};
|
||||
|
||||
function statusOf(row: EditorialRow): StatusKey {
|
||||
if (row.archived) return "archived";
|
||||
if (row.status === "active") return "active";
|
||||
if (row.status === "pending_email" || row.status === "pending_approval") return "pending";
|
||||
return "suspended";
|
||||
}
|
||||
|
||||
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
const date = new Intl.DateTimeFormat("de-DE", { dateStyle: "medium", timeZone: "Europe/Berlin" });
|
||||
|
||||
type Row = EditorialRow & { statusCell?: never; priceCell?: never; openCell?: never; createdCell?: never };
|
||||
|
||||
const columns: TableColumn<Row>[] = [
|
||||
{
|
||||
key: "name",
|
||||
header: "Redaktion",
|
||||
render: (row) => (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<Link
|
||||
className="font-medium text-[var(--color-fg-default)] underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
|
||||
href={`/admin/redaktionen/${row.id}`}
|
||||
>
|
||||
{row.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-[var(--color-fg-muted)]">{row.loginEmail}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ key: "contactName", header: "Kontakt" },
|
||||
{
|
||||
key: "statusCell",
|
||||
header: "Status",
|
||||
render: (row) => {
|
||||
const status = STATUS[statusOf(row)];
|
||||
return <Badge variant={status.variant}>{status.label}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: "priceCell",
|
||||
header: "Preis netto",
|
||||
align: "right",
|
||||
render: (row) => (
|
||||
<span className="tabular-nums">{row.priceCents === null ? "offen" : euro.format(row.priceCents / 100)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "openCell",
|
||||
header: "Nicht abgerechnet",
|
||||
align: "right",
|
||||
render: (row) => (
|
||||
<span className={`tabular-nums ${row.openCents > 0 ? "font-medium text-[var(--color-warning-fg)]" : "text-[var(--color-fg-muted)]"}`}>
|
||||
{euro.format(row.openCents / 100)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "createdCell",
|
||||
header: "Registriert",
|
||||
align: "right",
|
||||
render: (row) => <span className="tabular-nums text-[var(--color-fg-muted)]">{date.format(new Date(row.createdAt))}</span>,
|
||||
},
|
||||
];
|
||||
|
||||
const FILTERS = [
|
||||
{ value: "all", label: "Alle" },
|
||||
{ value: "active", label: "Aktiv" },
|
||||
{ value: "pending", label: "Ausstehend" },
|
||||
{ value: "suspended", label: "Gesperrt" },
|
||||
{ value: "archived", label: "Archiviert" },
|
||||
];
|
||||
|
||||
export function EditorialsTable({ rows }: Readonly<{ rows: EditorialRow[] }>) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [filter, setFilter] = useState("all");
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
return rows.filter((row) => {
|
||||
const status = statusOf(row);
|
||||
// "Alle" hides archived accounts; they have their own filter.
|
||||
if (filter === "all" ? status === "archived" : status !== filter) return false;
|
||||
return !needle || [row.name, row.contactName, row.loginEmail].some((value) => value.toLowerCase().includes(needle));
|
||||
});
|
||||
}, [rows, query, filter]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="w-full lg:w-[34rem]">
|
||||
<SegmentedControl aria-label="Nach Status filtern" fullWidth onChange={setFilter} options={FILTERS} value={filter} />
|
||||
</div>
|
||||
<div className="lg:w-80">
|
||||
<Input
|
||||
aria-label="Redaktionen durchsuchen"
|
||||
leadingIcon={<IconSearch size={16} />}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Name, Kontakt oder E-Mail …"
|
||||
type="search"
|
||||
value={query}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<EmptyState
|
||||
description={query ? "Keine Redaktion passt zur Suche." : "In diesem Status gibt es gerade keine Redaktion."}
|
||||
title="Keine Redaktionen"
|
||||
/>
|
||||
) : (
|
||||
<Table<Row> columns={columns} rowKey={(row) => row.id} rows={visible} />
|
||||
)}
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{visible.length} von {rows.length} Redaktionen
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { IconMail, IconSearch } from "@sakaniui/react/icons";
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
|
||||
import type { AlbumActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
type AlbumGridAction = (
|
||||
editorialId: string,
|
||||
@@ -46,9 +47,9 @@ function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction
|
||||
startTransition(async () => {
|
||||
const initial: AlbumActionResult = { ok: true, message: "" };
|
||||
if (album.isGranted) {
|
||||
await revokeAction(editorialId, initial, formData);
|
||||
notifyResult(await revokeAction(editorialId, initial, formData), "Zuweisung aufgehoben.");
|
||||
} else {
|
||||
await grantAction(editorialId, initial, formData);
|
||||
notifyResult(await grantAction(editorialId, initial, formData), "Album zugewiesen.");
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -99,6 +100,7 @@ function AlbumCard({ album, editorialId, grantAction, revokeAction, notifyAction
|
||||
setNotifyStatus("pending");
|
||||
notifyAction(editorialId, { ok: true, message: "" }, formData).then((res) => {
|
||||
setNotifyStatus(res.ok ? "success" : "error");
|
||||
notifyResult(res, "E-Mail an die Redaktion gesendet.");
|
||||
setTimeout(() => setNotifyStatus("idle"), 3000);
|
||||
});
|
||||
}}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }));
|
||||
|
||||
import { EditorialDetailContent } from "@/modules/editorials/admin-detail";
|
||||
import { AlbumGrantError } from "@/modules/albums/grants";
|
||||
import { loadAssignableAlbums } from "./page-content";
|
||||
|
||||
@@ -14,6 +14,7 @@ import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { requireAdminPage } from "../../../access";
|
||||
import { applyAutoRulesAction, createAutoRuleAction, deleteAutoRuleAction } from "./actions";
|
||||
import { ToastForm } from "@/components/ui/feedback";
|
||||
|
||||
type AutoRulesPageProps = Readonly<{
|
||||
params: Promise<{ id: string }>;
|
||||
@@ -51,14 +52,14 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={createAutoRuleAction.bind(null, editorial.id)} className="flex flex-col gap-4 sm:flex-row sm:items-end">
|
||||
<ToastForm action={createAutoRuleAction.bind(null, editorial.id)} failure="Die Regel konnte nicht gespeichert werden. Bitte das Stichwort prüfen." success="Regel gespeichert." 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" leftIcon={<IconPlus size={16} />}>
|
||||
Regel hinzufügen
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -71,11 +72,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
Alle derzeit aktiven automatischen Zuweisungen.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<form action={applyAutoRulesAction.bind(null, editorial.id)}>
|
||||
<ToastForm action={applyAutoRulesAction.bind(null, editorial.id)} success="Regeln angewendet.">
|
||||
<Button type="submit" variant="secondary" leftIcon={<IconPlayerPlay size={16} />}>
|
||||
Regeln jetzt anwenden
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -91,11 +92,11 @@ export default async function AutoRulesPage({ params }: AutoRulesPageProps) {
|
||||
Erstellt am {new Date(rule.createdAt).toLocaleDateString('de-DE')}
|
||||
</span>
|
||||
</div>
|
||||
<form action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)}>
|
||||
<ToastForm action={deleteAutoRuleAction.bind(null, editorial.id, rule.id)} success="Regel gelöscht.">
|
||||
<Button type="submit" variant="ghost" size="sm" leftIcon={<IconTrash size={16} />}>
|
||||
Entfernen
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -3,10 +3,13 @@ import Link from "next/link";
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts, usages } from "@/db/schema";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { IconChevronRight } from "@sakaniui/react/icons";
|
||||
import { Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { EmptyState } from "@/components/ui/sakani";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
import { EditorialsTable } from "./EditorialsTable";
|
||||
|
||||
export default async function EditorialsPage() {
|
||||
await requireAdminPage();
|
||||
const [editorials, openUsageTotals] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
@@ -37,96 +40,31 @@ export default async function EditorialsPage() {
|
||||
openUsageTotals.map((total) => [total.editorialId, total.openCents]),
|
||||
);
|
||||
|
||||
const activeEditorials = editorials.filter((e) => !e.archivedAt);
|
||||
const archivedEditorials = editorials.filter((e) => e.archivedAt);
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Kontoverwaltung"
|
||||
title="Redaktionen"
|
||||
description="Verwalte hier alle registrierten und archivierten Redaktionszugänge."
|
||||
description="Alle registrierten Redaktionszugänge mit Status, Preis und noch nicht abgerechneten Nutzungen."
|
||||
/>
|
||||
|
||||
{activeEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine aktiven Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
|
||||
{editorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Redaktionen registriert." description="Neue Registrierungen erscheinen hier zur Freigabe." />
|
||||
) : (
|
||||
<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>
|
||||
<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 ${openCents > 0 ? "text-[var(--color-warning-fg)]" : "text-[var(--color-fg-muted)]"}`}
|
||||
title="Summe der noch nicht abgerechneten Bildnutzungen"
|
||||
>
|
||||
· Offen {formatCents(openCents)}
|
||||
</span>
|
||||
</p>
|
||||
</Card>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{archivedEditorials.length > 0 && (
|
||||
<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>
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{archivedEditorials.map((editorial) => (
|
||||
<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>
|
||||
<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>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
<EditorialsTable
|
||||
rows={editorials.map((editorial) => ({
|
||||
id: editorial.id,
|
||||
name: editorial.name,
|
||||
contactName: editorial.contactName,
|
||||
loginEmail: editorial.loginEmail,
|
||||
status: editorial.status,
|
||||
archived: Boolean(editorial.archivedAt),
|
||||
priceCents: editorial.currentPriceCents,
|
||||
openCents: openCentsByEditorial.get(editorial.id) ?? 0,
|
||||
createdAt: editorial.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</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);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useActionState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
import { useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
export function DeleteReleaseNoteButton({
|
||||
action,
|
||||
@@ -14,6 +15,7 @@ export function DeleteReleaseNoteButton({
|
||||
noteId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
useResultToast(state, "Versionshinweis gelöscht.");
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
@@ -21,11 +23,6 @@ export function DeleteReleaseNoteButton({
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Alert, Input, Textarea } from "@sakaniui/react";
|
||||
import { Input, Textarea } from "@sakaniui/react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, FormSelect } from "@/components/ui/sakani";
|
||||
|
||||
import type { ReleaseNoteActionResult } from "./actions";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
export function ReleaseNoteForm({
|
||||
action,
|
||||
@@ -16,14 +17,13 @@ export function ReleaseNoteForm({
|
||||
}>) {
|
||||
const versionId = 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);
|
||||
notifyResult(result);
|
||||
if (result.ok) {
|
||||
setBody("");
|
||||
}
|
||||
@@ -67,11 +67,6 @@ export function ReleaseNoteForm({
|
||||
{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>
|
||||
);
|
||||
|
||||
@@ -208,7 +208,15 @@ body:has([data-app-shell]) .legal-footer {
|
||||
background: var(--contact-sheet);
|
||||
}
|
||||
|
||||
.photo-tile-skeleton {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.photo-tile-trigger {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
@@ -220,6 +228,7 @@ body:has([data-app-shell]) .legal-footer {
|
||||
}
|
||||
|
||||
.photo-tile-image {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
|
||||
@@ -10,6 +10,7 @@ import "./globals.css";
|
||||
import { LegalFooter } from "@/components/layout/legal-footer";
|
||||
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { AppToaster } from "@/components/ui/feedback";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Redaktionsportal | Leon Tonhäuser",
|
||||
@@ -34,6 +35,7 @@ export default function RootLayout({ children }: Readonly<{ children: ReactNode
|
||||
{children}
|
||||
</div>
|
||||
<LegalFooter />
|
||||
<AppToaster />
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { Spinner } from "@/components/ui/sakani";
|
||||
import { Skeleton } from "@/components/ui/sakani";
|
||||
|
||||
export default function AlbumLoading() {
|
||||
return (
|
||||
<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>
|
||||
<div aria-busy="true" aria-live="polite" className="flex flex-col gap-6">
|
||||
<span className="sr-only">Fotos werden geladen.</span>
|
||||
<Skeleton height={36} variant="rect" width={320} />
|
||||
<Skeleton height={96} variant="rect" />
|
||||
<ul className="photo-gallery">
|
||||
{Array.from({ length: 8 }, (_, index) => (
|
||||
<li className="aspect-[3/2]" key={index}>
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
import { Spinner } from "@/components/ui/sakani";
|
||||
import { Skeleton } from "@/components/ui/sakani";
|
||||
|
||||
// Sakani's Skeleton sizes itself via width/height props (its CSS outranks
|
||||
// Tailwind sizing classes on its root).
|
||||
export default function AlbumsLoading() {
|
||||
return (
|
||||
<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>
|
||||
<div aria-busy="true" aria-live="polite" className="flex flex-col gap-6">
|
||||
<span className="sr-only">Alben werden geladen.</span>
|
||||
<Skeleton height={36} variant="rect" width={256} />
|
||||
<Skeleton height={96} variant="rect" />
|
||||
<ul className="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<li className="flex flex-col gap-3" key={index}>
|
||||
<div className="aspect-[3/2] w-full">
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</div>
|
||||
<Skeleton width={64} />
|
||||
<Skeleton width="75%" />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { recordActivity } from "@/modules/activity/service";
|
||||
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
|
||||
import { AlbumContactSheet, formatCount, PageLinks, PhotoSearchForm } from "@/modules/albums/catalog-content";
|
||||
import { UrlPagination } from "@/components/ui/url-pagination";
|
||||
import { AlbumContactSheet, formatCount, PhotoSearchForm } from "@/modules/albums/catalog-content";
|
||||
import { filterPhotos, normalizeSort, paginatePhotos, sortPhotos, type InAppPage, type PhotoSort } from "@/modules/albums/filter";
|
||||
import { PhotoGallery } from "@/modules/albums/photo-gallery";
|
||||
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
|
||||
@@ -108,16 +109,12 @@ function SearchRateLimited({ query, format, jahr, sortierung }: { query: string;
|
||||
}
|
||||
|
||||
function GlobalSearchPagination({ currentPage, page, query, format, jahr, sortierung }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
|
||||
const hasPrev = currentPage > 1;
|
||||
const hasNext = page.nextPage !== null;
|
||||
if (!hasPrev && !hasNext) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLinks
|
||||
prevHref={hasPrev ? globalPageHref(currentPage - 1, query, format, jahr, sortierung) : null}
|
||||
nextHref={hasNext ? globalPageHref(currentPage + 1, query, format, jahr, sortierung) : null}
|
||||
<UrlPagination
|
||||
ariaLabel="Suchergebnisseiten"
|
||||
hasNext={page.nextPage !== null}
|
||||
href={globalPageHref(currentPage, query, format, jahr, sortierung)}
|
||||
page={currentPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Badge, Button } from "@sakaniui/react";
|
||||
import { Badge, Button, toast } from "@sakaniui/react";
|
||||
|
||||
import type { EventAccessState } from "@/modules/calendar/service";
|
||||
|
||||
@@ -25,7 +25,6 @@ export function EventAccessAction({
|
||||
unreserveAction: Action;
|
||||
}>) {
|
||||
const router = useRouter();
|
||||
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const run = (action: Action) => {
|
||||
@@ -33,8 +32,12 @@ export function EventAccessAction({
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
if (result.ok) router.refresh();
|
||||
if (result.ok) {
|
||||
toast.success(result.message);
|
||||
router.refresh();
|
||||
} else {
|
||||
toast.error(result.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -71,17 +74,6 @@ export function EventAccessAction({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-start gap-1 sm:items-end">
|
||||
<div className="flex flex-wrap items-center gap-2">{content}</div>
|
||||
{state.message ? (
|
||||
<p
|
||||
aria-live="polite"
|
||||
className={`text-xs ${state.ok ? "text-[var(--color-fg-muted)]" : "text-[var(--color-danger-fg)]"}`}
|
||||
role={state.ok ? "status" : "alert"}
|
||||
>
|
||||
{state.message}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { DownloadLightboxForm } from "./DownloadLightboxForm";
|
||||
@@ -12,33 +12,45 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("confirms new and previous uses separately and preserves the keys after a failed request", async () => {
|
||||
const fetch = vi.fn().mockRejectedValue(new Error("connection lost"));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
render(<DownloadLightboxForm
|
||||
photos={[
|
||||
const photos = [
|
||||
{ assetId: "first", albumId: "allowed", filename: "first.jpg" },
|
||||
{ assetId: "second", albumId: "allowed", filename: "second.jpg" },
|
||||
]}
|
||||
options={{
|
||||
];
|
||||
const options = {
|
||||
priceCents: 1500,
|
||||
collabEnabled: false,
|
||||
priorUsagesByAsset: {
|
||||
second: [{ id: "prior", purpose: "Früherer Artikel", createdAt: "2026-11-01T12:00:00Z" }],
|
||||
},
|
||||
}}
|
||||
/>);
|
||||
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
|
||||
expect((screen.getByRole("button", { name: "ZIP herunterladen" }) as HTMLButtonElement).disabled).toBe(true);
|
||||
};
|
||||
|
||||
test("books every photo as a new usage and offers a choice only for already downloaded ones", () => {
|
||||
render(<DownloadLightboxForm options={options} photos={photos} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
|
||||
|
||||
expect(screen.queryByText("Bild auslassen")).toBeNull();
|
||||
const [firstRow, secondRow] = screen.getAllByRole("listitem");
|
||||
expect(within(firstRow).queryByText("Bereits genutzt")).toBeNull();
|
||||
expect(within(secondRow).getByText("Bereits genutzt")).toBeTruthy();
|
||||
|
||||
fireEvent.change(screen.getByRole("combobox", { name: "first.jpg" }), { target: { value: "new" } });
|
||||
fireEvent.change(screen.getByRole("combobox", { name: "second.jpg" }), { target: { value: "prior" } });
|
||||
const submit = screen.getByRole<HTMLButtonElement>("button", { name: "Nutzungen bestätigen und laden" });
|
||||
expect(submit.disabled).toBe(true);
|
||||
fireEvent.change(screen.getByLabelText("Gemeinsamer Zweck für neue Nutzungen"), {
|
||||
target: { value: "Neuer Artikel" },
|
||||
});
|
||||
expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*15,00/);
|
||||
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
|
||||
expect(submit.disabled).toBe(false);
|
||||
expect(screen.getByRole("status").textContent).toMatch(/2 neue Nutzungen.*30,00/);
|
||||
});
|
||||
|
||||
test("switching to 'Bereits genutzt' repeats the earlier usage and keeps keys after a failed request", async () => {
|
||||
const fetch = vi.fn().mockRejectedValue(new Error("connection lost"));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
render(<DownloadLightboxForm options={options} photos={photos} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
|
||||
|
||||
fireEvent.click(within(screen.getAllByRole("listitem")[1]).getByText("Bereits genutzt"));
|
||||
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
|
||||
expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*1 kostenlos erneut.*15,00/);
|
||||
|
||||
const submit = screen.getByRole<HTMLButtonElement>("button", { name: "Nutzungen bestätigen und laden" });
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() => expect(submit.disabled).toBe(false));
|
||||
fireEvent.click(submit);
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Checkbox, Input } from "@sakaniui/react";
|
||||
import { Alert, Badge, Button, Checkbox, Input, SegmentedControl, Select, toast } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
import { thumbnailUrl } from "@/modules/albums/catalog-content";
|
||||
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
|
||||
type Photo = { assetId: string; albumId: string; filename: string };
|
||||
type Choice = { selection: string; purpose?: string };
|
||||
// Every photo is a new usage unless the editorial switches an already
|
||||
// downloaded one to "Bereits genutzt" (free repeat of an earlier usage).
|
||||
type Choice = { mode: "new" | "repeat"; usageId?: string; purpose?: string; ownPurpose?: boolean };
|
||||
|
||||
const MAX_PHOTOS = 100;
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
const MODE_OPTIONS = [
|
||||
{ value: "new", label: "Neu" },
|
||||
{ value: "repeat", label: "Bereits genutzt" },
|
||||
];
|
||||
|
||||
export function DownloadLightboxForm({
|
||||
photos,
|
||||
@@ -30,25 +40,24 @@ export function DownloadLightboxForm({
|
||||
const intentKeys = useRef(new Map<string, string>());
|
||||
const router = useRouter();
|
||||
|
||||
const selected = photos.filter(({ assetId }) => {
|
||||
const selection = choices[assetId]?.selection;
|
||||
return Boolean(selection && selection !== "skip");
|
||||
});
|
||||
const newPhotos = selected.filter(({ assetId }) => choices[assetId].selection === "new");
|
||||
const priorUsages = (assetId: string) =>
|
||||
[...(options.priorUsagesByAsset[assetId] ?? [])].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||
const choiceFor = (assetId: string): Choice => {
|
||||
const choice = choices[assetId] ?? { mode: "new" };
|
||||
if (choice.mode === "repeat" && !priorUsages(assetId).some(({ id }) => id === choice.usageId)) {
|
||||
return { ...choice, usageId: priorUsages(assetId)[0]?.id };
|
||||
}
|
||||
return choice;
|
||||
};
|
||||
const update = (assetId: string, patch: Partial<Choice>) =>
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { ...choiceFor(assetId), ...patch } }));
|
||||
const purposeFor = (choice: Choice) => (choice.ownPurpose && choice.purpose?.trim()) || commonPurpose.trim();
|
||||
|
||||
const newPhotos = photos.filter(({ assetId }) => choiceFor(assetId).mode === "new");
|
||||
const repeatCount = photos.length - newPhotos.length;
|
||||
const missingPurpose = newPhotos.some(({ assetId }) => [...purposeFor(choiceFor(assetId))].length < 3);
|
||||
const ready = photos.length > 0 && photos.length <= MAX_PHOTOS && !missingPurpose;
|
||||
const price = priceFormatter.format(options.priceCents / 100);
|
||||
const ready = selected.length > 0 && selected.length <= 100 &&
|
||||
photos.every(({ assetId }) => currentSelection(assetId)) &&
|
||||
newPhotos.every(({ assetId }) => [...purposeFor(choices[assetId])].length >= 3);
|
||||
|
||||
function currentSelection(assetId: string) {
|
||||
const selection = choices[assetId]?.selection;
|
||||
if (selection === "new" || selection === "skip") return selection;
|
||||
return options.priorUsagesByAsset[assetId]?.find(({ id }) => id === selection)?.id ?? "";
|
||||
}
|
||||
|
||||
function purposeFor(choice: Choice) {
|
||||
return choice.purpose?.trim() || commonPurpose.trim();
|
||||
}
|
||||
|
||||
async function handleBulkDownload(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
@@ -58,10 +67,10 @@ export function DownloadLightboxForm({
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const items = selected.map(({ assetId, albumId }) => {
|
||||
const choice = choices[assetId];
|
||||
const purpose = choice.selection === "new" ? purposeFor(choice) : undefined;
|
||||
const key = JSON.stringify([assetId, choice.selection, purpose]);
|
||||
const items = photos.map(({ assetId, albumId }) => {
|
||||
const choice = choiceFor(assetId);
|
||||
const purpose = choice.mode === "new" ? purposeFor(choice) : undefined;
|
||||
const key = JSON.stringify([assetId, choice.mode, choice.usageId, purpose]);
|
||||
let idempotencyKey = intentKeys.current.get(key);
|
||||
if (!idempotencyKey) {
|
||||
idempotencyKey = crypto.randomUUID();
|
||||
@@ -69,7 +78,7 @@ export function DownloadLightboxForm({
|
||||
}
|
||||
return purpose
|
||||
? { assetId, albumId, purpose, idempotencyKey }
|
||||
: { assetId, usageId: choice.selection, idempotencyKey };
|
||||
: { assetId, usageId: choice.usageId, idempotencyKey };
|
||||
});
|
||||
|
||||
const response = await fetch("/api/lightbox/bulk-download", {
|
||||
@@ -111,8 +120,10 @@ export function DownloadLightboxForm({
|
||||
setChoices({});
|
||||
setCommonPurpose("");
|
||||
setCollab(false);
|
||||
toast.success(`ZIP mit ${photos.length} ${photos.length === 1 ? "Bild" : "Bildern"} wird heruntergeladen.`);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
// Stays inside the open modal: a toast would sit behind its backdrop.
|
||||
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
@@ -126,82 +137,156 @@ export function DownloadLightboxForm({
|
||||
ZIP-Download vorbereiten
|
||||
</Button>
|
||||
|
||||
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
|
||||
<form className="flex flex-col gap-4 p-6" method="post" onSubmit={handleBulkDownload}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Nutzungen für ZIP-Download</h2>
|
||||
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-2xl">
|
||||
<form className="flex flex-col gap-5 p-6" method="post" onSubmit={handleBulkDownload}>
|
||||
<header className="flex flex-col gap-1">
|
||||
<p className="editorial-kicker">ZIP-Download · {photos.length} {photos.length === 1 ? "Bild" : "Bilder"}</p>
|
||||
<h2 className="text-xl font-semibold" id="bulk-download-title">Nutzungen bestätigen</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Alle Bilder werden als neue Nutzung gebucht. Bilder, die Sie schon einmal geladen haben, können Sie
|
||||
stattdessen kostenlos unter der bisherigen Nutzung erneut laden.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{newPhotos.length > 0 && (
|
||||
<Input
|
||||
description="Gilt für alle neuen Nutzungen, außer Sie geben bei einem Bild einen eigenen Zweck an."
|
||||
disabled={loading}
|
||||
label="Gemeinsamer Zweck für neue Nutzungen"
|
||||
label="Verwendungszweck"
|
||||
maxLength={200}
|
||||
onChange={(event) => setCommonPurpose(event.target.value)}
|
||||
placeholder="z. B. Spielbericht HSV - Wolfsburg, Ausgabe 13.12."
|
||||
value={commonPurpose}
|
||||
/>
|
||||
<ul className="flex flex-col gap-4">
|
||||
)}
|
||||
|
||||
<ul className="flex max-h-[50vh] flex-col divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-[var(--radius-xl)] border border-[var(--color-border-subtle)]">
|
||||
{photos.map(({ assetId, filename }) => {
|
||||
const choice = choices[assetId];
|
||||
const choice = choiceFor(assetId);
|
||||
const prior = priorUsages(assetId);
|
||||
return (
|
||||
<li key={assetId} className="flex flex-col gap-2">
|
||||
<label className="flex flex-col gap-1 text-sm font-medium">
|
||||
{filename}
|
||||
<select
|
||||
className="rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-2 text-[var(--color-fg-default)]"
|
||||
<li className="flex flex-col gap-3 p-3" key={assetId}>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<img
|
||||
alt=""
|
||||
className="aspect-[3/2] w-20 shrink-0 rounded-[var(--radius-md)] bg-[var(--color-bg-subtle)] object-cover"
|
||||
loading="lazy"
|
||||
src={thumbnailUrl(assetId)}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="truncate text-sm font-medium">{filename}</span>
|
||||
{prior.length === 0 ? (
|
||||
<span>
|
||||
<Badge>Neue Nutzung · bis {price}</Badge>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-[var(--color-fg-muted)]">
|
||||
Schon geladen am {formatBerlinDate(new Date(prior[0].createdAt))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{prior.length > 0 && (
|
||||
<div className="w-full sm:w-72">
|
||||
<SegmentedControl
|
||||
aria-label={`Nutzung für ${filename}`}
|
||||
fullWidth
|
||||
onChange={(value) => update(assetId, { mode: value === "repeat" ? "repeat" : "new" })}
|
||||
options={MODE_OPTIONS}
|
||||
value={choice.mode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{choice.mode === "repeat" && prior.length > 1 && (
|
||||
<Select
|
||||
aria-label={`Bisherige Nutzung für ${filename}`}
|
||||
disabled={loading}
|
||||
onChange={(event) => {
|
||||
const selection = event.target.value;
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { selection } }));
|
||||
}}
|
||||
value={currentSelection(assetId)}
|
||||
>
|
||||
<option value="">Nutzung auswählen</option>
|
||||
<option value="new">Neue Nutzung · bis {price} netto</option>
|
||||
{(options.priorUsagesByAsset[assetId] ?? []).map((usage) => (
|
||||
<option key={usage.id} value={usage.id}>
|
||||
{usage.purpose} ({formatBerlinDate(new Date(usage.createdAt))}) · kostenlos wiederholen
|
||||
</option>
|
||||
))}
|
||||
<option value="skip">Bild auslassen</option>
|
||||
</select>
|
||||
</label>
|
||||
{choice?.selection === "new" && (
|
||||
label="Bisherige Nutzung"
|
||||
onChange={(usageId) => update(assetId, { usageId })}
|
||||
options={prior.map((usage) => ({
|
||||
label: `${usage.purpose} (${formatBerlinDate(new Date(usage.createdAt))})`,
|
||||
value: usage.id,
|
||||
}))}
|
||||
value={choice.usageId}
|
||||
/>
|
||||
)}
|
||||
{choice.mode === "repeat" && prior.length === 1 && (
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
Kostenlos unter „{prior[0].purpose}“ erneut laden.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{choice.mode === "new" &&
|
||||
(choice.ownPurpose ? (
|
||||
<Input
|
||||
disabled={loading}
|
||||
label={`Eigener Zweck für ${filename}`}
|
||||
maxLength={200}
|
||||
onChange={(event) => {
|
||||
const purpose = event.target.value;
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } }));
|
||||
}}
|
||||
onChange={(event) => update(assetId, { purpose: event.target.value })}
|
||||
value={choice.purpose ?? ""}
|
||||
/>
|
||||
)}
|
||||
) : (
|
||||
<button
|
||||
className="self-start text-xs font-medium text-[var(--color-fg-muted)] underline underline-offset-4 hover:text-[var(--color-fg-default)]"
|
||||
disabled={loading}
|
||||
onClick={() => update(assetId, { ownPurpose: true })}
|
||||
type="button"
|
||||
>
|
||||
Eigenen Zweck für dieses Bild angeben
|
||||
</button>
|
||||
))}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{options.collabEnabled && newPhotos.length > 0 && (
|
||||
<Checkbox
|
||||
checked={collab}
|
||||
description={
|
||||
newPhotos.length === 1
|
||||
? "Die neue Nutzung wird mit 0,00 € in der Abrechnung geführt."
|
||||
: `Alle ${newPhotos.length} neuen Nutzungen werden mit 0,00 € in der Abrechnung geführt.`
|
||||
}
|
||||
disabled={loading}
|
||||
label="Collab-Nutzung (kostenfrei)"
|
||||
description={`Alle ${newPhotos.length} neuen Nutzungen werden mit 0,00 € in der Abrechnung geführt.`}
|
||||
onChange={(event) => setCollab(event.target.checked)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-[var(--radius-xl)] bg-[var(--color-bg-subtle)] p-3 text-sm" role="status">
|
||||
{newPhotos.length > 0 && (
|
||||
<p className="text-sm" role="status">
|
||||
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} ·{" "}
|
||||
{collab
|
||||
? "kostenfrei als Collab-Nutzung."
|
||||
: `bis ${priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto. Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.`}
|
||||
</p>
|
||||
<Badge variant="info">
|
||||
{newPhotos.length} {newPhotos.length === 1 ? "neue Nutzung" : "neue Nutzungen"}
|
||||
</Badge>
|
||||
)}
|
||||
{repeatCount > 0 && <Badge>{repeatCount} kostenlos erneut</Badge>}
|
||||
<span className="text-[var(--color-fg-muted)]">
|
||||
{newPhotos.length === 0
|
||||
? "Keine neuen Kosten."
|
||||
: collab
|
||||
? "Kostenfrei als Collab-Nutzung."
|
||||
: `Bis ${priceFormatter.format((newPhotos.length * options.priceCents) / 100)} netto; ein Flatrate-Kontingent wird angerechnet.`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{photos.length > MAX_PHOTOS && (
|
||||
<Alert
|
||||
color="warning"
|
||||
description={`Höchstens ${MAX_PHOTOS} Bilder pro ZIP. Entfernen Sie einige Bilder aus dem Merkzettel.`}
|
||||
/>
|
||||
)}
|
||||
{selected.length > 100 && <Alert color="warning" description="Wählen Sie höchstens 100 Bilder pro ZIP aus." />}
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
<div className="mt-4 flex justify-end gap-3">
|
||||
|
||||
{missingPurpose && newPhotos.length > 0 && (
|
||||
<p className="text-right text-xs text-[var(--color-fg-muted)]">Bitte einen Verwendungszweck mit mindestens 3 Zeichen angeben.</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={loading || !ready} type="submit">
|
||||
<Button disabled={loading || !ready} loading={loading} type="submit">
|
||||
{loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }));
|
||||
|
||||
import { UsageHistoryContent } from "./usage-history-content";
|
||||
|
||||
@@ -121,9 +123,7 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
|
||||
expect(screen.getAllByText(/Nutzungspreis\s+15,00\s*€/)).toHaveLength(5);
|
||||
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(7);
|
||||
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(4);
|
||||
expect(screen.getByRole("link", { name: /nächste nutzungsseite/i }).getAttribute("href")).toBe(
|
||||
"/redaktion/nutzungen?page=2",
|
||||
);
|
||||
expect(screen.getByRole("navigation", { name: "Seiten der Nutzungshistorie" })).toBeTruthy();
|
||||
expect(
|
||||
screen.getByRole("link", { name: /neueste auslieferungen/i }).getAttribute("href"),
|
||||
).toBe("/redaktion/nutzungen?page=1");
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { UrlPagination } from "@/components/ui/url-pagination";
|
||||
import { PageLinks } from "@/modules/albums/catalog-content";
|
||||
|
||||
import { formatBerlinDateTime } from "@/modules/downloads/format";
|
||||
@@ -125,12 +126,11 @@ function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
||||
|
||||
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||
return (
|
||||
<PageLinks
|
||||
<UrlPagination
|
||||
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"
|
||||
hasNext={history.hasNext}
|
||||
href={`/redaktion/nutzungen?page=${history.page}`}
|
||||
page={history.page}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { Alert, Button } from "@sakaniui/react";
|
||||
import { Alert, Button, toast } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||
@@ -109,6 +109,9 @@ export function UsageDialog({
|
||||
link.click();
|
||||
dialogRef.current?.close();
|
||||
idempotencyKeyRef.current = null;
|
||||
// Errors stay inside the open modal (a toast would sit behind its
|
||||
// backdrop); success is announced once the dialog is closed.
|
||||
toast.success(`Download gestartet: ${filename}`);
|
||||
} catch {
|
||||
// Network failure / response not JSON — the server-code cases are
|
||||
// handled above; this is only a transport-level failure.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Stepper } from "@/components/ui/sakani";
|
||||
|
||||
const STEPS = [
|
||||
{ label: "Registrieren", description: "Firmen- und Kontaktdaten" },
|
||||
{ label: "E-Mail bestätigen", description: "Link in Ihrem Postfach" },
|
||||
{ label: "Freigabe", description: "Wir prüfen Ihre Angaben" },
|
||||
{ label: "Loslegen", description: "Alben ansehen und laden" },
|
||||
];
|
||||
|
||||
/** Where the editorial stands in the sign-up process (0-based step). */
|
||||
export function RegistrationSteps({ current }: Readonly<{ current: 0 | 1 | 2 | 3 }>) {
|
||||
return (
|
||||
<nav aria-label="Ablauf der Registrierung" className="mb-2">
|
||||
{/* Wrappers switch the layout: Sakani's CSS outranks Tailwind's display on its root. */}
|
||||
<div className="hidden sm:block">
|
||||
<Stepper current={current} steps={STEPS} />
|
||||
</div>
|
||||
<div className="sm:hidden">
|
||||
<Stepper current={current} orientation="vertical" steps={STEPS} />
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -9,22 +9,21 @@ import { IconCheck } from "@sakaniui/react/icons";
|
||||
// then sees the popup once more. ponytail: only the latest release is kept;
|
||||
// add a history list when users ask for older notes.
|
||||
export const RELEASE = {
|
||||
version: "2.3",
|
||||
title: "Kalender mit Kategorien und Vormerken",
|
||||
version: "2.4",
|
||||
title: "Mehrfach-Download und neuer Feinschliff",
|
||||
notes: {
|
||||
redaktion: [
|
||||
"Kalender als Monatsansicht: Termine erscheinen in der Farbe ihrer Kategorie, die Legende steht darunter.",
|
||||
"Mit „Zu meinen Alben hinzufügen“ merken Sie ein Spiel vor. Ist das Album schon da, ist es sofort freigeschaltet, sonst automatisch, sobald es angelegt ist.",
|
||||
"Bekommen Sie ein Album ohnehin über eine automatische Regel, steht das direkt am Termin.",
|
||||
"Die Fotos in einem Album stehen jetzt in gleich großen Kacheln, zeilenweise von links nach rechts.",
|
||||
"Seit 2.2: Collab-Downloads (wenn freigeschaltet), Rechnung und Nutzungsnachweis gebündelt per E-Mail, Suche auch nach Dateinamen.",
|
||||
"ZIP-Download vom Merkzettel: Alle Bilder laufen als neue Nutzung. Nur bei Bildern, die Sie schon geladen haben, wählen Sie zwischen neuer Nutzung und kostenloser Wiederholung.",
|
||||
"Albenübersicht mit großen Vorschaubildern, Seitenzahlen unter den Fotos und Ladeanimationen.",
|
||||
"Bestätigungen und Hinweise erscheinen als kurze Meldung unten rechts.",
|
||||
"Seit 2.3: Kalender als Monatsansicht mit „Zu meinen Alben hinzufügen“.",
|
||||
],
|
||||
admin: [
|
||||
"Kategorien unter Kalender, Kategorien verwalten: Name und Farbe speichern, beim Termin auswählen.",
|
||||
"Kalender als Monatsansicht mit Legende; statt Zusagen sehen Sie je Termin die Vormerkungen der Redaktionen.",
|
||||
"Vorgemerkte Alben werden automatisch freigeschaltet, sobald das Album in Immich erscheint (gleicher Takt wie die Auto-Regeln).",
|
||||
"Neues Dashboard: offene Aufgaben, nächste Termine, Kurzzahlen und letzte Aktivitäten.",
|
||||
"Seit 2.2: Statistiken, Collab, Rechnungsversand, Abrechnung quartalsweise, Versionshistorie.",
|
||||
"Speichern und Ändern bestätigt das Portal mit einer kurzen Meldung; Fehler bei Abrechnungen sind verständlich formuliert.",
|
||||
"Redaktionen als Tabelle mit Suche, Statusfilter und offenen Beträgen.",
|
||||
"Audit-Protokoll mit Ereignisauswahl, lesbaren Bezeichnungen und aufklappbaren Details.",
|
||||
"Die Registrierung zeigt den Ablauf in Schritten: Registrieren, E-Mail bestätigen, Freigabe, Loslegen.",
|
||||
"Seit 2.3: Kategorien, Monatskalender, Vormerkungen und neues Dashboard.",
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useTransition, type ReactNode } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Toaster, toast } from "@sakaniui/react";
|
||||
|
||||
export type ActionFeedback = { ok: boolean; message: string };
|
||||
|
||||
/** One toast stack for the whole app (mounted in the root layout). */
|
||||
export function AppToaster() {
|
||||
return <Toaster closeButton containerAriaLabel="Benachrichtigungen" position="bottom-right" richColors />;
|
||||
}
|
||||
|
||||
/** Shows a result as toast: success or error; nothing when there is no text. */
|
||||
export function notifyResult(result: ActionFeedback | null | undefined, successFallback?: string) {
|
||||
if (!result) return;
|
||||
const message = result.message || (result.ok ? successFallback : undefined);
|
||||
if (!message) return;
|
||||
if (result.ok) toast.success(message);
|
||||
else toast.error(message);
|
||||
}
|
||||
|
||||
/** For useActionState: toast every new result (the initial state stays quiet). */
|
||||
export function useResultToast(state: ActionFeedback, successFallback?: string) {
|
||||
const first = useRef(state);
|
||||
useEffect(() => {
|
||||
if (state === first.current) return;
|
||||
notifyResult(state, successFallback);
|
||||
}, [state, successFallback]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Form for server actions that return nothing (save, then revalidate):
|
||||
* runs the action, then toasts `success` or a generic error.
|
||||
*/
|
||||
export function ToastForm({
|
||||
action,
|
||||
success,
|
||||
failure = "Das hat nicht geklappt. Bitte versuchen Sie es erneut.",
|
||||
className,
|
||||
children,
|
||||
}: Readonly<{
|
||||
action: (formData: FormData) => Promise<void>;
|
||||
success: string;
|
||||
failure?: string;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
const router = useRouter();
|
||||
const [pending, startTransition] = useTransition();
|
||||
return (
|
||||
<form
|
||||
aria-busy={pending}
|
||||
action={(formData) =>
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await action(formData);
|
||||
toast.success(success);
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast.error(failure);
|
||||
}
|
||||
})
|
||||
}
|
||||
className={className}
|
||||
>
|
||||
<fieldset className="contents" disabled={pending}>
|
||||
{children}
|
||||
</fieldset>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
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";
|
||||
export { Alert, Badge, BarChart, Button, Checkbox, EmptyState, Input, Progress, Select, Skeleton, Spinner, StatCard, Stepper, 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.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Pagination } from "@sakaniui/react";
|
||||
|
||||
/**
|
||||
* Sakani pagination driven by the URL. `href` is the current page's URL with
|
||||
* every active filter; a page change swaps only `param` in it.
|
||||
* ponytail: the APIs behind it report "has next page", not a page count, so
|
||||
* the last known page is current + 1. Pass a real total once one exists.
|
||||
*/
|
||||
export function UrlPagination({
|
||||
href,
|
||||
page,
|
||||
hasNext,
|
||||
param = "page",
|
||||
ariaLabel = "Seiten",
|
||||
}: Readonly<{ href: string; page: number; hasNext: boolean; param?: string; ariaLabel?: string }>) {
|
||||
const router = useRouter();
|
||||
const total = hasNext ? page + 1 : page;
|
||||
if (total <= 1) return null;
|
||||
|
||||
return (
|
||||
<nav aria-label={ariaLabel} className="mt-6 flex justify-center border-t border-[var(--color-border-subtle)] pt-4">
|
||||
<Pagination
|
||||
onPageChange={(next) => {
|
||||
const url = new URL(href, window.location.origin);
|
||||
url.searchParams.set(param, String(next));
|
||||
router.push(`${url.pathname}${url.search}`);
|
||||
}}
|
||||
page={page}
|
||||
total={total}
|
||||
/>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -26,9 +26,9 @@ test("renders granted albums as labelled contact-sheet links", () => {
|
||||
const album = screen.getByRole("link", { name: /heimspiel gegen nord/i });
|
||||
expect(album.getAttribute("href")).toBe("/redaktion/alben/heimspiel");
|
||||
expect(screen.getByText("24 Fotos")).not.toBeNull();
|
||||
expect(screen.getByAltText("Titelbild: Heimspiel gegen Nord").getAttribute("src")).toBe(
|
||||
"/api/assets/cover-1/thumbnail",
|
||||
);
|
||||
// The cover is decorative: the title in the same link names it.
|
||||
expect(album.querySelector("img")?.getAttribute("src")).toBe("/api/assets/cover-1/thumbnail");
|
||||
expect(album.querySelector("img")?.getAttribute("alt")).toBe("");
|
||||
});
|
||||
|
||||
const photo = {
|
||||
|
||||
@@ -4,44 +4,52 @@ 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 { Card, FormSelect, Input, Skeleton } from "@/components/ui/sakani";
|
||||
import { UrlPagination } from "@/components/ui/url-pagination";
|
||||
import type { ImmichSearchPage } from "@/modules/immich/types";
|
||||
|
||||
import type { VisibleAlbum } from "./catalog";
|
||||
|
||||
// Blog-listing look: borderless 3:2 cover on top, count and title below.
|
||||
// A skeleton sits behind each cover until the image has loaded.
|
||||
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
|
||||
return (
|
||||
<ul className="grid auto-rows-fr grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-label="Freigegebene Fotoalben">
|
||||
<ul className="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3" aria-label="Freigegebene Fotoalben">
|
||||
{albums.map((album) => (
|
||||
<li key={album.id}>
|
||||
<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)]"
|
||||
className="group flex h-full flex-col gap-3 rounded-[var(--radius-xl)] focus-visible:outline-2 focus-visible:outline-offset-4 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">
|
||||
<div className="relative aspect-[3/2] w-full overflow-hidden rounded-[var(--radius-xl)] bg-[var(--color-bg-subtle)]">
|
||||
{album.albumThumbnailAssetId ? (
|
||||
<>
|
||||
{/* Sakani's CSS outranks Tailwind on its own root, so the wrapper positions it. */}
|
||||
<div aria-hidden="true" className="absolute inset-0">
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</div>
|
||||
<img
|
||||
alt={`Titelbild: ${album.albumName}`}
|
||||
className="aspect-[4/3] w-full rounded-[var(--radius-lg)] bg-[var(--color-bg-subtle)] object-cover"
|
||||
alt=""
|
||||
className="relative h-full w-full object-cover transition-transform duration-300 ease-out group-hover:scale-[1.03]"
|
||||
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>
|
||||
<span className="grid h-full place-items-center text-sm text-[var(--color-fg-muted)]">Kein Titelbild</span>
|
||||
)}
|
||||
<figcaption className="flex items-baseline justify-between gap-3">
|
||||
<span className="min-w-0 wrap-anywhere 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>
|
||||
</figure>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs font-medium uppercase tracking-wider tabular-nums text-[var(--color-fg-muted)]">
|
||||
{formatCount(album.assetCount, "Foto")}
|
||||
</span>
|
||||
<h2 className="wrap-anywhere text-lg font-semibold leading-snug text-[var(--color-fg-default)] underline-offset-4 group-hover:underline">
|
||||
{album.albumName}
|
||||
</h2>
|
||||
{album.description ? (
|
||||
<p className="line-clamp-2 text-sm text-[var(--color-fg-muted)]">{album.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
@@ -49,7 +57,7 @@ export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[]
|
||||
);
|
||||
}
|
||||
|
||||
// Server-rendered pagination. Links thread every active filter (suche,
|
||||
// Sakani pagination. The page URL threads every active filter (suche,
|
||||
// format, jahr) so flipping pages does not silently drop them — that was the
|
||||
// old bug: pageHref only carried `suche`, so "Nächste Seite" reset format/jahr.
|
||||
export function PhotoPagination({
|
||||
@@ -69,13 +77,14 @@ export function PhotoPagination({
|
||||
jahr?: string;
|
||||
sortierung?: string;
|
||||
}>) {
|
||||
const hasPrev = currentPage > 1;
|
||||
const hasNext = page.nextPage !== null;
|
||||
if (!hasPrev && !hasNext) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <PageLinks prevHref={hasPrev ? pageHref(albumId, currentPage - 1, query, format, jahr, sortierung) : null} nextHref={hasNext ? pageHref(albumId, currentPage + 1, query, format, jahr, sortierung) : null} />;
|
||||
return (
|
||||
<UrlPagination
|
||||
ariaLabel="Suchergebnisseiten"
|
||||
hasNext={page.nextPage !== null}
|
||||
href={pageHref(albumId, currentPage, query, format, jahr, sortierung)}
|
||||
page={currentPage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Server-rendered prev/next links (album search, usage history, …).
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { EmptyState, IconButton } from "@sakaniui/react";
|
||||
import { EmptyState, IconButton, Skeleton } from "@sakaniui/react";
|
||||
import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons";
|
||||
|
||||
import { UsageDialog } from "@/components/download/usage-dialog";
|
||||
@@ -91,6 +91,9 @@ export function PhotoGallery({
|
||||
onClick={() => setOpenIndex(index)}
|
||||
aria-label={`${asset.filename} vergrößern`}
|
||||
>
|
||||
<span aria-hidden="true" className="photo-tile-skeleton">
|
||||
<Skeleton height="100%" variant="rect" />
|
||||
</span>
|
||||
<img
|
||||
alt={asset.filename}
|
||||
className="photo-tile-image"
|
||||
|
||||
@@ -159,7 +159,7 @@ export function createPortalAuth({
|
||||
},
|
||||
async sendVerificationEmail({ email }) {
|
||||
await auth.api.sendVerificationEmail({
|
||||
body: { email, callbackURL: "/registrieren/bestaetigt" },
|
||||
body: { email, callbackURL: "/registrieren/bestaetigt?schritt=freigabe" },
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
import { useActionState } from "react";
|
||||
import { approveEditorialAction, type ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, Input } from "@/components/ui/sakani";
|
||||
import { Input } from "@/components/ui/sakani";
|
||||
import { IconCheck } from "@sakaniui/react/icons";
|
||||
import { useResultToast } from "@/components/ui/feedback";
|
||||
|
||||
export function ApproveForm({ editorialId }: { editorialId: string }) {
|
||||
const [state, formAction, pending] = useActionState<ApproveActionResult, FormData>(
|
||||
approveEditorialAction.bind(null, editorialId),
|
||||
{ ok: true, message: "" }
|
||||
);
|
||||
useResultToast(state, "Redaktion freigegeben.");
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col gap-4 sm:flex-row sm:items-end">
|
||||
@@ -28,7 +30,6 @@ export function ApproveForm({ editorialId }: { editorialId: string }) {
|
||||
<Button type="submit" disabled={pending} leftIcon={<IconCheck size={16} />}>
|
||||
{pending ? "Wird freigegeben …" : "Redaktion freigeben"}
|
||||
</Button>
|
||||
{!state.ok && <Alert color="danger" description={state.message} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -4,8 +4,9 @@ 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 { Alert, Input } from "@/components/ui/sakani";
|
||||
import { Input } from "@/components/ui/sakani";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
type DangerZoneProps = {
|
||||
editorialId: string;
|
||||
@@ -16,7 +17,6 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
|
||||
const [confirmText, setConfirmText] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
|
||||
const isConfirmed = confirmText === editorialName;
|
||||
|
||||
function handleArchive() {
|
||||
@@ -25,7 +25,7 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
|
||||
try {
|
||||
await archiveEditorialAction(editorialId);
|
||||
} catch {
|
||||
setResult({ ok: false, message: "Das Archivieren ist fehlgeschlagen." });
|
||||
notifyResult({ ok: false, message: "Das Archivieren ist fehlgeschlagen." });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -36,7 +36,7 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
|
||||
startTransition(async () => {
|
||||
const actionResult = await hardDeleteEditorialAction(editorialId);
|
||||
// On success the action redirects; anything returned here is a failure.
|
||||
setResult(actionResult);
|
||||
notifyResult(actionResult);
|
||||
setIsDeleting(false);
|
||||
});
|
||||
}
|
||||
@@ -77,7 +77,6 @@ export function DangerZone({ editorialId, editorialName }: DangerZoneProps) {
|
||||
{isDeleting ? "Wird gelöscht…" : "Endgültig löschen"}
|
||||
</Button>
|
||||
</div>
|
||||
{result && !result.ok && <Alert color="danger" description={result.message} />}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -4,8 +4,9 @@ import { useState, useTransition } from "react";
|
||||
|
||||
import { resetUsageDataAction } from "@/app/admin/redaktionen/[id]/actions";
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card";
|
||||
import { Alert, Input } from "@/components/ui/sakani";
|
||||
import { Input } from "@/components/ui/sakani";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { notifyResult } from "@/components/ui/feedback";
|
||||
|
||||
type ResetUsageCardProps = {
|
||||
editorialId: string;
|
||||
@@ -15,14 +16,13 @@ type ResetUsageCardProps = {
|
||||
export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardProps) {
|
||||
const [confirmText, setConfirmText] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
|
||||
const isConfirmed = confirmText === editorialName;
|
||||
|
||||
function handleReset() {
|
||||
if (!isConfirmed || isPending) return;
|
||||
startTransition(async () => {
|
||||
const actionResult = await resetUsageDataAction(editorialId);
|
||||
setResult(actionResult);
|
||||
notifyResult(actionResult);
|
||||
if (actionResult.ok) {
|
||||
setConfirmText("");
|
||||
}
|
||||
@@ -57,7 +57,6 @@ export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardPro
|
||||
>
|
||||
{isPending ? "Wird zurückgesetzt…" : "Nutzungsdaten zurücksetzen"}
|
||||
</Button>
|
||||
{result && <Alert color={result.ok ? "success" : "danger"} description={result.message} />}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { archiveEditorialAction, unarchiveEditorialAction, suspendEditorialActio
|
||||
import { DangerZone } from "./DangerZone";
|
||||
import { ResetUsageCard } from "./ResetUsageCard";
|
||||
import { ApproveForm } from "./ApproveForm";
|
||||
import { ToastForm } from "@/components/ui/feedback";
|
||||
|
||||
export type EditorialDetail = {
|
||||
id: string;
|
||||
@@ -51,11 +52,11 @@ export function EditorialDetailContent({
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={unarchiveEditorialAction.bind(null, editorial.id)}>
|
||||
<ToastForm action={unarchiveEditorialAction.bind(null, editorial.id)} success="Archivierung aufgehoben.">
|
||||
<Button type="submit" variant="secondary">
|
||||
Archivierung aufheben & reaktivieren
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -130,7 +131,7 @@ export function EditorialDetailContent({
|
||||
<CardDescription>Pauschalpreis für Downloads aktivieren.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={updateFlatrateAction.bind(null, editorial.id)} className="flex flex-col gap-6">
|
||||
<ToastForm action={updateFlatrateAction.bind(null, editorial.id)} success="Flatrate gespeichert." className="flex flex-col gap-6">
|
||||
<Checkbox
|
||||
defaultChecked={editorial.flatrateActive}
|
||||
id="flatrateActive"
|
||||
@@ -164,7 +165,7 @@ export function EditorialDetailContent({
|
||||
Speichern
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
@@ -179,7 +180,7 @@ export function EditorialDetailContent({
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={updateCollabAction.bind(null, editorial.id)} className="flex flex-col gap-6">
|
||||
<ToastForm action={updateCollabAction.bind(null, editorial.id)} success="Collab-Einstellung gespeichert." className="flex flex-col gap-6">
|
||||
<Checkbox
|
||||
defaultChecked={editorial.collabEnabled}
|
||||
id="collabEnabled"
|
||||
@@ -189,7 +190,7 @@ export function EditorialDetailContent({
|
||||
<div>
|
||||
<Button type="submit">Speichern</Button>
|
||||
</div>
|
||||
</form>
|
||||
</ToastForm>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
@@ -201,18 +202,18 @@ export function EditorialDetailContent({
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{editorial.status === 'active' && (
|
||||
<form action={suspendEditorialAction.bind(null, editorial.id)}>
|
||||
<ToastForm action={suspendEditorialAction.bind(null, editorial.id)} success="Zugang gesperrt.">
|
||||
<Button type="submit" variant="destructive">
|
||||
Zugang sperren
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
)}
|
||||
{editorial.status === 'suspended' && (
|
||||
<form action={reactivateEditorialAction.bind(null, editorial.id)}>
|
||||
<ToastForm action={reactivateEditorialAction.bind(null, editorial.id)} success="Zugang reaktiviert.">
|
||||
<Button type="submit" variant="secondary">
|
||||
Zugang reaktivieren
|
||||
</Button>
|
||||
</form>
|
||||
</ToastForm>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
Reference in new issue
Block a user