feat: admin hints with auto-expiry shown in album overview
This commit is contained in:
1 parent
2a5a2f3815
commit
abe072b2d1
15 files changed
+2945
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE "announcements" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"message" text NOT NULL,
|
||||||
|
"event_date" date NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"created_by_user_id" uuid
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "announcements" ADD CONSTRAINT "announcements_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,13 @@
|
|||||||
"when": 1786299825190,
|
"when": 1786299825190,
|
||||||
"tag": "0000_baseline",
|
"tag": "0000_baseline",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 1,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1789139950413,
|
||||||
|
"tag": "0001_add_announcements",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -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", label: "Dashboard" },
|
||||||
{ href: "/admin/redaktionen", label: "Redaktionen" },
|
{ href: "/admin/redaktionen", label: "Redaktionen" },
|
||||||
{ href: "/admin/alben", label: "Alben" },
|
{ href: "/admin/alben", label: "Alben" },
|
||||||
|
{ href: "/admin/hinweise", label: "Hinweise" },
|
||||||
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
|
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
|
||||||
{ href: "/admin/audit", label: "Audit" },
|
{ 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 { AlbumContactSheet, formatCount } from "@/modules/albums/catalog-content";
|
||||||
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
|
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
|
||||||
import { PhotoGallery } from "@/modules/albums/photo-gallery";
|
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 { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||||
import { lightboxService } from "@/modules/lightbox/service";
|
import { lightboxService } from "@/modules/lightbox/service";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -21,6 +23,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
|||||||
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
||||||
const format = singleValue(rawSearchParams.format);
|
const format = singleValue(rawSearchParams.format);
|
||||||
const jahr = singleValue(rawSearchParams.jahr);
|
const jahr = singleValue(rawSearchParams.jahr);
|
||||||
|
const hints = await announcementService.listActiveAnnouncements(new Date());
|
||||||
|
|
||||||
if (query) {
|
if (query) {
|
||||||
let results;
|
let results;
|
||||||
@@ -54,6 +57,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
|||||||
title="Suchergebnisse"
|
title="Suchergebnisse"
|
||||||
titleId="albums-title"
|
titleId="albums-title"
|
||||||
/>
|
/>
|
||||||
|
<AnnouncementBanner items={hints} />
|
||||||
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
||||||
<p aria-live="polite" className="result-summary" role="status">
|
<p aria-live="polite" className="result-summary" role="status">
|
||||||
{formatCount(page.total, "Foto")} gefunden
|
{formatCount(page.total, "Foto")} gefunden
|
||||||
@@ -84,6 +88,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
|||||||
titleId="albums-title"
|
titleId="albums-title"
|
||||||
description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen."
|
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} />
|
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
||||||
{result.albums.length === 0 ? (
|
{result.albums.length === 0 ? (
|
||||||
<p className="text-muted-foreground text-center py-12">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
|
<p className="text-muted-foreground text-center py-12">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { date, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
|
import { users } from "./auth";
|
||||||
|
|
||||||
|
// Time-limited hints for editorial users (e.g. "photographer is away at a
|
||||||
|
// match today"). Visible from creation until `eventDate` plus the service
|
||||||
|
// layer's visibility window, so expired hints never need a cleanup job.
|
||||||
|
export const announcements = pgTable("announcements", {
|
||||||
|
id: uuid("id").defaultRandom().primaryKey(),
|
||||||
|
message: text("message").notNull(),
|
||||||
|
eventDate: date("event_date").notNull(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
|
||||||
|
onDelete: "restrict",
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from "./albums";
|
export * from "./albums";
|
||||||
|
export * from "./announcements";
|
||||||
export * from "./audit";
|
export * from "./audit";
|
||||||
export * from "./auth";
|
export * from "./auth";
|
||||||
export * from "./auto-rules";
|
export * from "./auto-rules";
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { Megaphone } from "lucide-react";
|
||||||
|
|
||||||
|
import { formatIsoDateGerman, type Announcement } from "./service";
|
||||||
|
|
||||||
|
// Time-limited admin hints (e.g. "away at a match today"), shown at the top
|
||||||
|
// of the editorial album overview. Renders nothing when nothing is active.
|
||||||
|
export function AnnouncementBanner({ items }: { items: Announcement[] }) {
|
||||||
|
if (items.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3" role="status">
|
||||||
|
{items.map((item) => (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className="bg-primary/10 border border-primary/30 rounded-xl p-4 flex gap-3"
|
||||||
|
>
|
||||||
|
<Megaphone className="h-5 w-5 shrink-0 text-primary-600 mt-0.5" aria-hidden="true" />
|
||||||
|
<div className="min-w-0 space-y-0.5">
|
||||||
|
<p className="text-sm font-semibold">Hinweis von Leon Tonhäuser Sportfotografie</p>
|
||||||
|
<p className="text-sm whitespace-pre-line break-words">{item.message}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
bezogen auf den {formatIsoDateGerman(item.eventDate)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import { beforeEach, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import type { Announcement, AnnouncementRepository } from "./service";
|
||||||
|
import {
|
||||||
|
ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT,
|
||||||
|
AnnouncementServiceError,
|
||||||
|
createAnnouncementService,
|
||||||
|
formatIsoDateGerman,
|
||||||
|
isValidIsoDate,
|
||||||
|
isoDateInBerlin,
|
||||||
|
minVisibleEventDate,
|
||||||
|
shiftIsoDate,
|
||||||
|
} from "./service";
|
||||||
|
|
||||||
|
vi.mock("@/db/client", () => ({ db: {} }));
|
||||||
|
|
||||||
|
const adminUserId = "3333333c-3333-4333-8333-33333333333c";
|
||||||
|
|
||||||
|
function announcement(id: string, eventDate: string, message = "Hinweis"): Announcement {
|
||||||
|
return { id, message, eventDate, createdAt: new Date("2026-09-01T12:00:00Z") };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFakeRepository(rows: Announcement[] = []) {
|
||||||
|
const inserted: Array<{ message: string; eventDate: string; adminUserId: string }> = [];
|
||||||
|
const deletedIds: string[] = [];
|
||||||
|
let visibleOnToday: string | undefined;
|
||||||
|
|
||||||
|
const repository: AnnouncementRepository = {
|
||||||
|
async insert(input) {
|
||||||
|
inserted.push(input);
|
||||||
|
const row = announcement(`announcement-${inserted.length}`, input.eventDate, input.message);
|
||||||
|
rows.push(row);
|
||||||
|
return row;
|
||||||
|
},
|
||||||
|
async listVisibleOn(today) {
|
||||||
|
visibleOnToday = today;
|
||||||
|
return rows.filter((row) => row.eventDate >= minVisibleEventDate(today));
|
||||||
|
},
|
||||||
|
async listAll() {
|
||||||
|
return [...rows];
|
||||||
|
},
|
||||||
|
async deleteById(id) {
|
||||||
|
const index = rows.findIndex((row) => row.id === id);
|
||||||
|
if (index === -1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
deletedIds.push(id);
|
||||||
|
const [row] = rows.splice(index, 1);
|
||||||
|
return row;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
repository,
|
||||||
|
inserted,
|
||||||
|
deletedIds,
|
||||||
|
lastVisibleOnToday: () => visibleOnToday,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFakeAudit() {
|
||||||
|
const events: Array<{ type: string; actorUserId?: string; actorType?: string; entityId: string }> = [];
|
||||||
|
return {
|
||||||
|
events,
|
||||||
|
writeAudit: vi.fn(async (input: (typeof events)[number]) => {
|
||||||
|
events.push(input);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createService(rows?: Announcement[]) {
|
||||||
|
const fake = createFakeRepository(rows);
|
||||||
|
const audit = createFakeAudit();
|
||||||
|
const service = createAnnouncementService({ repository: fake.repository, audit });
|
||||||
|
return { service, ...fake, audit };
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the visibility window keeps a hint visible until three days after the event", () => {
|
||||||
|
expect(ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT).toBe(3);
|
||||||
|
expect(minVisibleEventDate("2026-09-14")).toBe("2026-09-11");
|
||||||
|
// Month and year rollovers stay correct.
|
||||||
|
expect(minVisibleEventDate("2026-09-02")).toBe("2026-08-30");
|
||||||
|
expect(minVisibleEventDate("2026-01-02")).toBe("2025-12-30");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shiftIsoDate moves ISO dates across boundaries without timezone drift", () => {
|
||||||
|
expect(shiftIsoDate("2026-09-14", 3)).toBe("2026-09-17");
|
||||||
|
expect(shiftIsoDate("2026-02-28", 1)).toBe("2026-03-01");
|
||||||
|
expect(shiftIsoDate("2024-02-28", 1)).toBe("2024-02-29");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("isoDateInBerlin resolves the Berlin calendar date, not the server's UTC date", () => {
|
||||||
|
// 2026-09-14 00:30 UTC is still 2026-09-14 02:30 in Berlin.
|
||||||
|
expect(isoDateInBerlin(new Date("2026-09-14T00:30:00Z"))).toBe("2026-09-14");
|
||||||
|
// 2026-09-14 22:30 UTC is already 2026-09-15 in Berlin.
|
||||||
|
expect(isoDateInBerlin(new Date("2026-09-14T22:30:00Z"))).toBe("2026-09-15");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("isValidIsoDate rejects malformed or impossible dates", () => {
|
||||||
|
expect(isValidIsoDate("2026-09-14")).toBe(true);
|
||||||
|
expect(isValidIsoDate("2026-02-30")).toBe(false);
|
||||||
|
expect(isValidIsoDate("14.09.2026")).toBe(false);
|
||||||
|
expect(isValidIsoDate("")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("formatIsoDateGerman renders a timezone-safe German date", () => {
|
||||||
|
expect(formatIsoDateGerman("2026-09-14")).toBe("14.09.2026");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("createAnnouncement trims the message and attributes the audit event to the admin", async () => {
|
||||||
|
const fake = createService();
|
||||||
|
const created = await fake.service.createAnnouncement({
|
||||||
|
message: " Heute kein Büro — Liebl ist beim HSV-Spiel. ",
|
||||||
|
eventDate: "2026-09-14",
|
||||||
|
adminUserId,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fake.inserted).toEqual([
|
||||||
|
{ message: "Heute kein Büro — Liebl ist beim HSV-Spiel.", eventDate: "2026-09-14", adminUserId },
|
||||||
|
]);
|
||||||
|
expect(created.eventDate).toBe("2026-09-14");
|
||||||
|
expect(fake.audit.writeAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: "announcement_created",
|
||||||
|
actorUserId: adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "announcement",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("createAnnouncement rejects an empty, whitespace-only or oversized message", async () => {
|
||||||
|
const fake = createService();
|
||||||
|
await expect(
|
||||||
|
fake.service.createAnnouncement({ message: " ", eventDate: "2026-09-14", adminUserId }),
|
||||||
|
).rejects.toMatchObject({ code: "INVALID_MESSAGE" });
|
||||||
|
await expect(
|
||||||
|
fake.service.createAnnouncement({ message: "x".repeat(501), eventDate: "2026-09-14", adminUserId }),
|
||||||
|
).rejects.toMatchObject({ code: "INVALID_MESSAGE" });
|
||||||
|
expect(fake.inserted).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("createAnnouncement rejects an impossible event date", async () => {
|
||||||
|
const fake = createService();
|
||||||
|
await expect(
|
||||||
|
fake.service.createAnnouncement({ message: "Hallo", eventDate: "2026-02-30", adminUserId }),
|
||||||
|
).rejects.toMatchObject({ code: "INVALID_EVENT_DATE" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("listActiveAnnouncements asks the repository for the current Berlin date", async () => {
|
||||||
|
const now = new Date("2026-09-14T10:00:00Z");
|
||||||
|
const rows = [announcement("a", "2026-09-14")];
|
||||||
|
const fake = createService(rows);
|
||||||
|
|
||||||
|
const result = await fake.service.listActiveAnnouncements(now);
|
||||||
|
|
||||||
|
expect(fake.lastVisibleOnToday()).toBe("2026-09-14");
|
||||||
|
expect(result.map((row) => row.id)).toEqual(["a"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("listAnnouncements marks hints three days after the event as still active, four days as expired", async () => {
|
||||||
|
const now = new Date("2026-09-14T10:00:00Z");
|
||||||
|
const rows = [
|
||||||
|
announcement("game-day", "2026-09-14"),
|
||||||
|
announcement("three-days-after", "2026-09-11"),
|
||||||
|
announcement("four-days-after", "2026-09-10"),
|
||||||
|
];
|
||||||
|
const fake = createService(rows);
|
||||||
|
|
||||||
|
const result = await fake.service.listAnnouncements(now);
|
||||||
|
|
||||||
|
const byId = new Map(result.map((row) => [row.id, row]));
|
||||||
|
expect(byId.get("game-day")).toMatchObject({ isActive: true, visibleUntil: "2026-09-17" });
|
||||||
|
expect(byId.get("three-days-after")).toMatchObject({ isActive: true, visibleUntil: "2026-09-14" });
|
||||||
|
expect(byId.get("four-days-after")).toMatchObject({ isActive: false, visibleUntil: "2026-09-13" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("deleteAnnouncement removes the row and writes a deletion audit event", async () => {
|
||||||
|
const row = announcement("11111111-1111-4111-8111-111111111111", "2026-09-14");
|
||||||
|
const fake = createService([row]);
|
||||||
|
|
||||||
|
await fake.service.deleteAnnouncement({ id: row.id, adminUserId });
|
||||||
|
|
||||||
|
expect(fake.deletedIds).toEqual([row.id]);
|
||||||
|
expect(fake.audit.writeAudit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ type: "announcement_deleted", actorUserId: adminUserId }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("deleteAnnouncement reports a missing announcement instead of failing silently", async () => {
|
||||||
|
const fake = createService();
|
||||||
|
await expect(
|
||||||
|
fake.service.deleteAnnouncement({ id: "11111111-1111-4111-8111-111111111111", adminUserId }),
|
||||||
|
).rejects.toMatchObject({ code: "ANNOUNCEMENT_NOT_FOUND" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the AnnouncementServiceError exposes a code for action-level German messages", () => {
|
||||||
|
const error = new AnnouncementServiceError("INVALID_EVENT_DATE");
|
||||||
|
expect(error.code).toBe("INVALID_EVENT_DATE");
|
||||||
|
});
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { desc, eq, gte } from "drizzle-orm";
|
||||||
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { announcements } from "@/db/schema";
|
||||||
|
import type * as schema from "@/db/schema";
|
||||||
|
import { writeAudit } from "@/modules/audit/write";
|
||||||
|
|
||||||
|
// A hint for an event (e.g. a match) stays visible until three days after the
|
||||||
|
// event date, so it covers match day plus the following days without any
|
||||||
|
// manual cleanup.
|
||||||
|
export const ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT = 3;
|
||||||
|
|
||||||
|
export const ANNOUNCEMENT_MAX_MESSAGE_LENGTH = 500;
|
||||||
|
|
||||||
|
export type Announcement = {
|
||||||
|
id: string;
|
||||||
|
message: string;
|
||||||
|
eventDate: string;
|
||||||
|
createdAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminAnnouncement = Announcement & {
|
||||||
|
/** Last day (ISO date) on which editorial users still see the hint. */
|
||||||
|
visibleUntil: string;
|
||||||
|
isActive: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AnnouncementError =
|
||||||
|
| "INVALID_MESSAGE"
|
||||||
|
| "INVALID_EVENT_DATE"
|
||||||
|
| "ANNOUNCEMENT_NOT_FOUND";
|
||||||
|
|
||||||
|
export class AnnouncementServiceError extends Error {
|
||||||
|
readonly name = "AnnouncementServiceError";
|
||||||
|
|
||||||
|
constructor(readonly code: AnnouncementError) {
|
||||||
|
super(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CreateAnnouncementInput = {
|
||||||
|
message: string;
|
||||||
|
eventDate: string;
|
||||||
|
adminUserId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AnnouncementRepository = {
|
||||||
|
insert(input: {
|
||||||
|
message: string;
|
||||||
|
eventDate: string;
|
||||||
|
adminUserId: string;
|
||||||
|
}): Promise<Announcement>;
|
||||||
|
listVisibleOn(today: string): Promise<Announcement[]>;
|
||||||
|
listAll(): Promise<Announcement[]>;
|
||||||
|
deleteById(
|
||||||
|
id: string,
|
||||||
|
): Promise<{ id: string; message: string; eventDate: string } | null>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Date helpers (pure, so the visibility window is unit-testable)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Today's calendar date in the portal's timezone (Europe/Berlin). */
|
||||||
|
export function isoDateInBerlin(instant: Date): string {
|
||||||
|
return new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Berlin" }).format(instant);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shifts an ISO date (YYYY-MM-DD) by a whole number of days. */
|
||||||
|
export function shiftIsoDate(isoDate: string, days: number): string {
|
||||||
|
const [year, month, day] = isoDate.split("-").map(Number);
|
||||||
|
const shifted = new Date(Date.UTC(year, month - 1, day + days));
|
||||||
|
return shifted.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Event dates from this day on are still visible on `today`. */
|
||||||
|
export function minVisibleEventDate(today: string): string {
|
||||||
|
return shiftIsoDate(today, -ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidIsoDate(value: string): boolean {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const [year, month, day] = value.split("-").map(Number);
|
||||||
|
const parsed = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
return (
|
||||||
|
parsed.getUTCFullYear() === year &&
|
||||||
|
parsed.getUTCMonth() === month - 1 &&
|
||||||
|
parsed.getUTCDate() === day
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Formats an ISO date (YYYY-MM-DD) as TT.MM.JJJJ without timezone round-trips. */
|
||||||
|
export function formatIsoDateGerman(isoDate: string): string {
|
||||||
|
const [year, month, day] = isoDate.split("-");
|
||||||
|
return `${day}.${month}.${year}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Service
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAnnouncementService({
|
||||||
|
repository,
|
||||||
|
audit,
|
||||||
|
}: {
|
||||||
|
repository: AnnouncementRepository;
|
||||||
|
audit: { writeAudit: typeof writeAudit };
|
||||||
|
}) {
|
||||||
|
return {
|
||||||
|
async createAnnouncement(input: CreateAnnouncementInput): Promise<Announcement> {
|
||||||
|
const message = input.message.trim();
|
||||||
|
if (message.length === 0 || message.length > ANNOUNCEMENT_MAX_MESSAGE_LENGTH) {
|
||||||
|
throw new AnnouncementServiceError("INVALID_MESSAGE");
|
||||||
|
}
|
||||||
|
if (!isValidIsoDate(input.eventDate)) {
|
||||||
|
throw new AnnouncementServiceError("INVALID_EVENT_DATE");
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = await repository.insert({
|
||||||
|
message,
|
||||||
|
eventDate: input.eventDate,
|
||||||
|
adminUserId: input.adminUserId,
|
||||||
|
});
|
||||||
|
|
||||||
|
await audit.writeAudit({
|
||||||
|
type: "announcement_created",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "announcement",
|
||||||
|
entityId: created.id,
|
||||||
|
metadata: { eventDate: created.eventDate, message: created.message },
|
||||||
|
});
|
||||||
|
|
||||||
|
return created;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Hints currently visible to editorial users. */
|
||||||
|
async listActiveAnnouncements(now: Date): Promise<Announcement[]> {
|
||||||
|
return repository.listVisibleOn(isoDateInBerlin(now));
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Every hint for the admin overview with its computed visibility. */
|
||||||
|
async listAnnouncements(now: Date): Promise<AdminAnnouncement[]> {
|
||||||
|
const today = isoDateInBerlin(now);
|
||||||
|
const rows = await repository.listAll();
|
||||||
|
return rows.map((row) => ({
|
||||||
|
...row,
|
||||||
|
// Visible while eventDate >= today - 3d ⇔ today <= eventDate + 3d.
|
||||||
|
visibleUntil: shiftIsoDate(row.eventDate, ANNOUNCEMENT_VISIBLE_DAYS_AFTER_EVENT),
|
||||||
|
isActive: row.eventDate >= minVisibleEventDate(today),
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteAnnouncement(input: {
|
||||||
|
id: string;
|
||||||
|
adminUserId: string;
|
||||||
|
}): Promise<void> {
|
||||||
|
const deleted = await repository.deleteById(input.id);
|
||||||
|
if (!deleted) {
|
||||||
|
throw new AnnouncementServiceError("ANNOUNCEMENT_NOT_FOUND");
|
||||||
|
}
|
||||||
|
|
||||||
|
await audit.writeAudit({
|
||||||
|
type: "announcement_deleted",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "announcement",
|
||||||
|
entityId: deleted.id,
|
||||||
|
metadata: { eventDate: deleted.eventDate, message: deleted.message },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Drizzle repository
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAnnouncementRepository(
|
||||||
|
database: NodePgDatabase<typeof schema>,
|
||||||
|
): AnnouncementRepository {
|
||||||
|
return {
|
||||||
|
async insert(input) {
|
||||||
|
const [row] = await database
|
||||||
|
.insert(announcements)
|
||||||
|
.values({
|
||||||
|
message: input.message,
|
||||||
|
eventDate: input.eventDate,
|
||||||
|
createdByUserId: input.adminUserId,
|
||||||
|
})
|
||||||
|
.returning({
|
||||||
|
id: announcements.id,
|
||||||
|
message: announcements.message,
|
||||||
|
eventDate: announcements.eventDate,
|
||||||
|
createdAt: announcements.createdAt,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
},
|
||||||
|
|
||||||
|
async listVisibleOn(today) {
|
||||||
|
return database
|
||||||
|
.select({
|
||||||
|
id: announcements.id,
|
||||||
|
message: announcements.message,
|
||||||
|
eventDate: announcements.eventDate,
|
||||||
|
createdAt: announcements.createdAt,
|
||||||
|
})
|
||||||
|
.from(announcements)
|
||||||
|
.where(gte(announcements.eventDate, minVisibleEventDate(today)))
|
||||||
|
.orderBy(desc(announcements.eventDate), desc(announcements.createdAt));
|
||||||
|
},
|
||||||
|
|
||||||
|
async listAll() {
|
||||||
|
return database
|
||||||
|
.select({
|
||||||
|
id: announcements.id,
|
||||||
|
message: announcements.message,
|
||||||
|
eventDate: announcements.eventDate,
|
||||||
|
createdAt: announcements.createdAt,
|
||||||
|
})
|
||||||
|
.from(announcements)
|
||||||
|
.orderBy(desc(announcements.createdAt));
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteById(id) {
|
||||||
|
const [row] = await database
|
||||||
|
.delete(announcements)
|
||||||
|
.where(eq(announcements.id, id))
|
||||||
|
.returning({
|
||||||
|
id: announcements.id,
|
||||||
|
message: announcements.message,
|
||||||
|
eventDate: announcements.eventDate,
|
||||||
|
});
|
||||||
|
return row ?? null;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const announcementService = createAnnouncementService({
|
||||||
|
repository: createAnnouncementRepository(db),
|
||||||
|
audit: { writeAudit },
|
||||||
|
});
|
||||||
Reference in new issue
Block a user