feat: admin hints with auto-expiry shown in album overview
This commit is contained in:
1 parent
2a5a2f3815
commit
abe072b2d1
15 files changed
+2946
-1
No files matched your search
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
|
||||
// Same direct-call-in-transition pattern as the album bulk grant form so the
|
||||
// message box clears after a successful publish without an effect.
|
||||
export function AnnouncementForm({
|
||||
action,
|
||||
defaultEventDate,
|
||||
}: Readonly<{
|
||||
action: (
|
||||
state: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
) => Promise<AnnouncementActionResult>;
|
||||
defaultEventDate: string;
|
||||
}>) {
|
||||
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);
|
||||
if (result.ok) {
|
||||
setMessage("");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
action={handleSubmit}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={messageId} className="text-sm font-medium">
|
||||
Nachricht
|
||||
</label>
|
||||
<textarea
|
||||
id={messageId}
|
||||
name="message"
|
||||
rows={3}
|
||||
maxLength={500}
|
||||
required
|
||||
value={message}
|
||||
onChange={(event) => setMessage(event.target.value)}
|
||||
placeholder="z. B. Liebl ist heute beim HSV-Spiel — Freigaben und Downloads sind trotzdem verfügbar, Antworten dauern etwas länger."
|
||||
className="flex w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{message.length}/500 Zeichen</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor={dateId} className="text-sm font-medium">
|
||||
Datum des Ereignisses (z. B. Spieltag)
|
||||
</label>
|
||||
<Input
|
||||
id={dateId}
|
||||
type="date"
|
||||
name="eventDate"
|
||||
defaultValue={defaultEventDate}
|
||||
required
|
||||
className="sm:w-48"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Der Hinweis wird sofort sichtbar und verschwindet automatisch drei Tage nach diesem
|
||||
Datum.
|
||||
</p>
|
||||
</div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
|
||||
</Button>
|
||||
{state.message ? (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
|
||||
>
|
||||
{state.message}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { AnnouncementActionResult } from "./actions";
|
||||
|
||||
// One tiny form per announcement row so every delete button reports its own
|
||||
// result inline (same pattern as AlbumGrantForm).
|
||||
export function DeleteAnnouncementButton({
|
||||
action,
|
||||
announcementId,
|
||||
}: Readonly<{
|
||||
action: (
|
||||
state: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
) => Promise<AnnouncementActionResult>;
|
||||
announcementId: string;
|
||||
}>) {
|
||||
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
|
||||
|
||||
return (
|
||||
<form action={formAction} className="flex flex-col items-end gap-1">
|
||||
<input type="hidden" name="announcementId" value={announcementId} />
|
||||
<Button type="submit" variant="outline" size="sm" disabled={pending}>
|
||||
{pending ? "…" : "Löschen"}
|
||||
</Button>
|
||||
{state.ok ? null : (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{state.message}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createAnnouncement: vi.fn(),
|
||||
deleteAnnouncement: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
requireAdmin: vi.fn(),
|
||||
revalidatePath: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||
vi.mock("@/modules/announcements/service", () => ({
|
||||
AnnouncementServiceError: class AnnouncementServiceError extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
},
|
||||
announcementService: {
|
||||
createAnnouncement: mocks.createAnnouncement,
|
||||
deleteAnnouncement: mocks.deleteAnnouncement,
|
||||
},
|
||||
}));
|
||||
|
||||
import { AnnouncementServiceError } from "@/modules/announcements/service";
|
||||
|
||||
import { createAnnouncementAction, deleteAnnouncementAction } from "./actions";
|
||||
|
||||
const initial = { ok: true, message: "" };
|
||||
|
||||
test("the create action rejects unauthenticated callers before touching the service", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
|
||||
|
||||
await expect(createAnnouncementAction(initial, new FormData())).rejects.toThrow(
|
||||
"ADMIN_REQUIRED",
|
||||
);
|
||||
expect(mocks.createAnnouncement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the create action publishes a hint with the authenticated admin and revalidates both pages", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.createAnnouncement.mockResolvedValue({
|
||||
id: "announcement-1",
|
||||
message: "Hinweis",
|
||||
eventDate: "2026-09-14",
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("message", "Liebl ist beim HSV-Spiel.");
|
||||
formData.set("eventDate", "2026-09-14");
|
||||
|
||||
const result = await createAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(mocks.createAnnouncement).toHaveBeenCalledWith({
|
||||
message: "Liebl ist beim HSV-Spiel.",
|
||||
eventDate: "2026-09-14",
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/hinweise");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/redaktion/alben");
|
||||
});
|
||||
|
||||
test("the create action maps service errors to inline German messages", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.createAnnouncement.mockRejectedValue(
|
||||
new AnnouncementServiceError("INVALID_EVENT_DATE"),
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("message", "Hallo");
|
||||
formData.set("eventDate", "2026-02-30");
|
||||
|
||||
const result = await createAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
message: "Bitte wählen Sie ein gültiges Datum.",
|
||||
});
|
||||
expect(mocks.revalidatePath).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the delete action reports a vanished announcement in German", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.deleteAnnouncement.mockRejectedValue(
|
||||
new AnnouncementServiceError("ANNOUNCEMENT_NOT_FOUND"),
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("announcementId", "11111111-1111-4111-8111-111111111111");
|
||||
|
||||
const result = await deleteAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.message).toContain("existiert nicht mehr");
|
||||
});
|
||||
|
||||
test("the delete action revalidates both pages after a successful removal", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.deleteAnnouncement.mockResolvedValue(undefined);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("announcementId", "11111111-1111-4111-8111-111111111111");
|
||||
|
||||
const result = await deleteAnnouncementAction(initial, formData);
|
||||
|
||||
expect(result).toEqual({ ok: true, message: "" });
|
||||
expect(mocks.deleteAnnouncement).toHaveBeenCalledWith({
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
adminUserId: "admin-1",
|
||||
});
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/hinweise");
|
||||
expect(mocks.revalidatePath).toHaveBeenCalledWith("/redaktion/alben");
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import {
|
||||
AnnouncementServiceError,
|
||||
announcementService,
|
||||
} from "@/modules/announcements/service";
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
|
||||
// Returned to the client form so failures surface as inline German text
|
||||
// instead of an opaque Next.js error-digest page (same pattern as the album
|
||||
// access actions).
|
||||
export type AnnouncementActionResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createAnnouncementAction(
|
||||
_prevState: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AnnouncementActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const message = formData.get("message");
|
||||
const eventDate = formData.get("eventDate");
|
||||
|
||||
if (typeof message !== "string" || typeof eventDate !== "string") {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Bitte Nachricht und Datum ausfüllen.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
await announcementService.createAnnouncement({
|
||||
message,
|
||||
eventDate,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: announcementErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/hinweise");
|
||||
revalidatePath("/redaktion/alben");
|
||||
return {
|
||||
ok: true,
|
||||
message:
|
||||
"Hinweis veröffentlicht. Er ist für die Redaktionen sichtbar und verschwindet drei Tage nach dem Datum automatisch.",
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteAnnouncementAction(
|
||||
_prevState: AnnouncementActionResult,
|
||||
formData: FormData,
|
||||
): Promise<AnnouncementActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const announcementId = formData.get("announcementId");
|
||||
if (typeof announcementId !== "string" || announcementId.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await announcementService.deleteAnnouncement({
|
||||
id: announcementId,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: announcementErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/admin/hinweise");
|
||||
revalidatePath("/redaktion/alben");
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
|
||||
function announcementErrorMessage(error: unknown): string {
|
||||
if (error instanceof AnnouncementServiceError) {
|
||||
const messages: Record<AnnouncementServiceError["code"], string> = {
|
||||
INVALID_MESSAGE: "Bitte geben Sie einen Text mit 1 bis 500 Zeichen ein.",
|
||||
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
|
||||
ANNOUNCEMENT_NOT_FOUND: "Dieser Hinweis existiert nicht mehr.",
|
||||
};
|
||||
return messages[error.code] ?? "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
return "Der Hinweis konnte nicht gespeichert werden.";
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import {
|
||||
formatIsoDateGerman,
|
||||
isoDateInBerlin,
|
||||
announcementService,
|
||||
} from "@/modules/announcements/service";
|
||||
|
||||
import { AnnouncementForm } from "./AnnouncementForm";
|
||||
import { DeleteAnnouncementButton } from "./DeleteAnnouncementButton";
|
||||
import { createAnnouncementAction, deleteAnnouncementAction } from "./actions";
|
||||
|
||||
export default async function AdminAnnouncementsPage() {
|
||||
const items = await announcementService.listAnnouncements(new Date());
|
||||
const activeCount = items.filter((item) => item.isActive).length;
|
||||
|
||||
return (
|
||||
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<PageHeader
|
||||
kicker="Kommunikation"
|
||||
title="Hinweise"
|
||||
description="Kurze Meldungen für alle Redaktionen — z. B. wenn Sie bei einem Spiel nicht erreichbar sind. Ein Hinweis erscheint sofort in der Album-Übersicht und verschwindet drei Tage nach dem Ereignisdatum automatisch."
|
||||
/>
|
||||
|
||||
<AnnouncementForm
|
||||
action={createAnnouncementAction}
|
||||
defaultEventDate={isoDateInBerlin(new Date())}
|
||||
/>
|
||||
|
||||
<section className="space-y-4" aria-labelledby="announcements-list-title">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h2 id="announcements-list-title" className="text-xl font-semibold">
|
||||
Alle Hinweise
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{activeCount} aktiv · {items.length} insgesamt
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">
|
||||
Noch keine Hinweise vorhanden.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
|
||||
>
|
||||
<div className="space-y-1 min-w-0">
|
||||
<p className="text-sm whitespace-pre-line break-words">{item.message}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ereignis: {formatIsoDateGerman(item.eventDate)} ·{" "}
|
||||
{item.isActive ? (
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
sichtbar bis {formatIsoDateGerman(item.visibleUntil)}
|
||||
</span>
|
||||
) : (
|
||||
<span>abgelaufen (war sichtbar bis {formatIsoDateGerman(item.visibleUntil)})</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<DeleteAnnouncementButton action={deleteAnnouncementAction} announcementId={item.id} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
|
||||
{ href: "/admin", label: "Dashboard" },
|
||||
{ href: "/admin/redaktionen", label: "Redaktionen" },
|
||||
{ href: "/admin/alben", label: "Alben" },
|
||||
{ href: "/admin/hinweise", label: "Hinweise" },
|
||||
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
|
||||
{ href: "/admin/audit", label: "Audit" },
|
||||
]}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albu
|
||||
import { AlbumContactSheet, formatCount } from "@/modules/albums/catalog-content";
|
||||
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
|
||||
import { PhotoGallery } from "@/modules/albums/photo-gallery";
|
||||
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
|
||||
import { announcementService } from "@/modules/announcements/service";
|
||||
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
import { lightboxService } from "@/modules/lightbox/service";
|
||||
import Link from "next/link";
|
||||
@@ -21,6 +23,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
||||
const format = singleValue(rawSearchParams.format);
|
||||
const jahr = singleValue(rawSearchParams.jahr);
|
||||
const hints = await announcementService.listActiveAnnouncements(new Date());
|
||||
|
||||
if (query) {
|
||||
let results;
|
||||
@@ -54,6 +57,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
title="Suchergebnisse"
|
||||
titleId="albums-title"
|
||||
/>
|
||||
<AnnouncementBanner items={hints} />
|
||||
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
||||
<p aria-live="polite" className="result-summary" role="status">
|
||||
{formatCount(page.total, "Foto")} gefunden
|
||||
@@ -84,6 +88,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
titleId="albums-title"
|
||||
description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen."
|
||||
/>
|
||||
<AnnouncementBanner items={hints} />
|
||||
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
||||
{result.albums.length === 0 ? (
|
||||
<p className="text-muted-foreground text-center py-12">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
|
||||
|
||||
Reference in new issue
Block a user