Release 2.3.0: calendar categories, reservations, month view, dashboard
- Admin-managed event categories (name + one of Sakani's 8 calendar colors) at /admin/kalender/kategorien; events pick a category. - Calendar as Sakani MonthCalendar with a German header and a color legend, for editorials and admins. - "Zu meinen Alben hinzufügen" replaces RSVP: grants the event album at once when it exists, otherwise reserves it; the auto-rule scheduler grants pending reservations once the album appears. Editorials see when an auto rule already covers the event. event_responses is dropped. - New admin dashboard: to-dos, next events, 30-day figures, activity. - Photo grid reads left to right in uniform 3:2 tiles. - Release notes 2.3.0 seeded (migration 0008). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4fb6f2d373
commit
2775b406bf
39 files changed
+9754
-701
No files matched your search
@@ -13,10 +13,12 @@ export function CalendarEventForm({
|
||||
action,
|
||||
defaultEventDate,
|
||||
albums,
|
||||
categories,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
defaultEventDate: string;
|
||||
albums: Array<{ id: string; albumName: string }>;
|
||||
categories: Array<{ id: string; name: string }>;
|
||||
}>) {
|
||||
const titleId = useId();
|
||||
const dateId = useId();
|
||||
@@ -49,6 +51,16 @@ export function CalendarEventForm({
|
||||
value={title}
|
||||
/>
|
||||
<div className="flex flex-col gap-4 sm:flex-row">
|
||||
<div className="sm:w-64">
|
||||
<FormSelect
|
||||
label="Kategorie"
|
||||
name="categoryId"
|
||||
options={[
|
||||
{ label: "Ohne Kategorie", value: "" },
|
||||
...categories.map((category) => ({ label: category.name, value: category.id })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:w-48">
|
||||
<Input defaultValue={defaultEventDate} id={dateId} label="Datum" name="eventDate" required type="date" />
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,7 @@ export async function createCalendarEventAction(
|
||||
const title = formData.get("title");
|
||||
const eventDate = formData.get("eventDate");
|
||||
const immichAlbumId = formData.get("immichAlbumId");
|
||||
const categoryId = formData.get("categoryId");
|
||||
|
||||
if (typeof title !== "string" || typeof eventDate !== "string") {
|
||||
return { ok: false, message: "Bitte Titel und Datum ausfüllen." };
|
||||
@@ -29,6 +30,7 @@ export async function createCalendarEventAction(
|
||||
title,
|
||||
eventDate,
|
||||
immichAlbumId: typeof immichAlbumId === "string" && immichAlbumId ? immichAlbumId : null,
|
||||
categoryId: typeof categoryId === "string" && categoryId ? categoryId : null,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -40,7 +42,7 @@ export async function createCalendarEventAction(
|
||||
return {
|
||||
ok: true,
|
||||
message:
|
||||
"Termin angelegt. Sobald ein passendes Album in Immich erscheint, können Redaktionen es selbst freischalten.",
|
||||
"Termin angelegt. Redaktionen können ihn sofort vormerken; das Album wird freigeschaltet, sobald es in Immich erscheint.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,13 +74,13 @@ function calendarErrorMessage(error: unknown): string {
|
||||
INVALID_TITLE: "Bitte geben Sie einen Titel mit 1 bis 200 Zeichen ein.",
|
||||
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
|
||||
INVALID_ALBUM: "Das gewählte Album existiert nicht mehr in Immich.",
|
||||
INVALID_STATUS: "Ungültige Rückmeldung.",
|
||||
INVALID_CATEGORY: "Die gewählte Kategorie existiert nicht mehr.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verknüpft.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung existiert nicht mehr.",
|
||||
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
|
||||
};
|
||||
return messages[error.code] ?? "Der Termin konnte nicht gespeichert werden.";
|
||||
return messages[error.code];
|
||||
}
|
||||
return "Der Termin konnte nicht gespeichert werden.";
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, useTransition } from "react";
|
||||
import { Alert, Input } from "@sakaniui/react";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/sakani";
|
||||
import { CATEGORY_COLOR_LABELS, CATEGORY_COLORS, type CategoryColor } from "@/modules/calendar/colors";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
|
||||
export function CategoryForm({
|
||||
action,
|
||||
}: Readonly<{ action: (state: CategoryActionResult, formData: FormData) => Promise<CategoryActionResult> }>) {
|
||||
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);
|
||||
if (result.ok) setName("");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title="Neue Kategorie">
|
||||
<form action={handleSubmit} className="flex flex-col gap-4">
|
||||
<div className="sm:max-w-md">
|
||||
<Input
|
||||
id={nameId}
|
||||
label="Name"
|
||||
maxLength={80}
|
||||
name="name"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="z. B. Fußball - 1. Bundesliga"
|
||||
required
|
||||
value={name}
|
||||
/>
|
||||
</div>
|
||||
<fieldset className="flex flex-col gap-2">
|
||||
<legend className="mb-2 text-sm font-medium text-[var(--color-fg-default)]">Farbe</legend>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{CATEGORY_COLORS.map((option) => (
|
||||
<label
|
||||
className={`flex min-h-10 cursor-pointer items-center gap-2 rounded-full border px-3 text-sm transition-colors has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 ${
|
||||
color === option
|
||||
? "border-[var(--color-fg-default)] bg-[var(--color-bg-subtle)] font-medium"
|
||||
: "border-[var(--color-border-subtle)] text-[var(--color-fg-muted)] hover:bg-[var(--color-bg-subtle)]"
|
||||
}`}
|
||||
key={option}
|
||||
>
|
||||
<input
|
||||
checked={color === option}
|
||||
className="sr-only"
|
||||
name="color"
|
||||
onChange={() => setColor(option)}
|
||||
type="radio"
|
||||
value={option}
|
||||
/>
|
||||
<CategoryDot color={option} />
|
||||
{CATEGORY_COLOR_LABELS[option]}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CategoryActionResult } from "./actions";
|
||||
|
||||
export function DeleteCategoryButton({
|
||||
action,
|
||||
categoryId,
|
||||
inUse,
|
||||
}: Readonly<{
|
||||
action: (state: CategoryActionResult, formData: FormData) => Promise<CategoryActionResult>;
|
||||
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)));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<Button
|
||||
disabled={pending || inUse}
|
||||
onClick={handleClick}
|
||||
size="sm"
|
||||
title={inUse ? "Wird noch von Terminen genutzt" : undefined}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
{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,65 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireAdmin } from "@/modules/auth/principal";
|
||||
import { CategoryServiceError, categoryService } from "@/modules/calendar/categories";
|
||||
|
||||
export type CategoryActionResult = { ok: boolean; message: string };
|
||||
|
||||
const MESSAGES: Record<CategoryServiceError["code"], string> = {
|
||||
INVALID_NAME: "Bitte geben Sie einen Namen mit 1 bis 80 Zeichen ein.",
|
||||
INVALID_COLOR: "Bitte wählen Sie eine Farbe aus der Liste.",
|
||||
DUPLICATE_NAME: "Diese Kategorie gibt es schon.",
|
||||
CATEGORY_IN_USE: "Die Kategorie wird noch von Terminen genutzt und kann nicht gelöscht werden.",
|
||||
CATEGORY_NOT_FOUND: "Diese Kategorie existiert nicht mehr.",
|
||||
};
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof CategoryServiceError ? MESSAGES[error.code] : fallback;
|
||||
}
|
||||
|
||||
function revalidate() {
|
||||
revalidatePath("/admin/kalender/kategorien");
|
||||
revalidatePath("/admin/kalender");
|
||||
revalidatePath("/redaktion/kalender");
|
||||
}
|
||||
|
||||
export async function createCategoryAction(
|
||||
_prevState: CategoryActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CategoryActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const name = formData.get("name");
|
||||
const color = formData.get("color");
|
||||
try {
|
||||
await categoryService.createCategory({
|
||||
name: typeof name === "string" ? name : "",
|
||||
color: typeof color === "string" ? color : "",
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: errorMessage(error, "Die Kategorie konnte nicht gespeichert werden.") };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "Kategorie gespeichert." };
|
||||
}
|
||||
|
||||
export async function deleteCategoryAction(
|
||||
_prevState: CategoryActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CategoryActionResult> {
|
||||
const principal = await requireAdmin(new Headers(await headers()));
|
||||
const id = formData.get("categoryId");
|
||||
if (typeof id !== "string" || id.length === 0) {
|
||||
return { ok: false, message: "Ungültige Kennung." };
|
||||
}
|
||||
try {
|
||||
await categoryService.deleteCategory({ id, adminUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: errorMessage(error, "Die Kategorie konnte nicht gelöscht werden.") };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "" };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { CATEGORY_COLOR_LABELS } from "@/modules/calendar/colors";
|
||||
|
||||
import { requireAdminPage } from "../../access";
|
||||
import { CategoryForm } from "./CategoryForm";
|
||||
import { DeleteCategoryButton } from "./DeleteCategoryButton";
|
||||
import { createCategoryAction, deleteCategoryAction } from "./actions";
|
||||
|
||||
export default async function AdminCategoriesPage() {
|
||||
await requireAdminPage();
|
||||
const categories = await categoryService.listCategories();
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Planung · Kalender"
|
||||
title="Kategorien"
|
||||
description="Sportarten und Ligen für den Kalender. Die Farbe erscheint bei den Terminen und in der Legende."
|
||||
>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/kalender">Zum Kalender</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<CategoryForm action={createCategoryAction} />
|
||||
|
||||
<Card title="Gespeicherte Kategorien">
|
||||
{categories.length === 0 ? (
|
||||
<EmptyState title="Noch keine Kategorien" description="Legen Sie oben die erste Kategorie an." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{categories.map((category) => (
|
||||
<li className="flex items-center justify-between gap-4 py-3" key={category.id}>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<CategoryDot color={category.color} />
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium break-words">{category.name}</p>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{CATEGORY_COLOR_LABELS[category.color]} ·{" "}
|
||||
{category.eventCount === 1 ? "1 Termin" : `${category.eventCount} Termine`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DeleteCategoryButton
|
||||
action={deleteCategoryAction}
|
||||
categoryId={category.id}
|
||||
inUse={category.eventCount > 0}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,97 +1,118 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { CategoryDot, CategoryLegend } from "@/components/calendar/category-legend";
|
||||
import { EventMonth } from "@/components/calendar/event-month";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
|
||||
import { requireAdminPage } from "../access";
|
||||
import { CalendarEventForm } from "./CalendarEventForm";
|
||||
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
|
||||
import { createCalendarEventAction, deleteCalendarEventAction } from "./actions";
|
||||
|
||||
export default async function AdminCalendarPage() {
|
||||
const [{ events, immichUnavailable }, albums] = await Promise.all([
|
||||
await requireAdminPage();
|
||||
const [{ events, immichUnavailable }, albums, categories] = await Promise.all([
|
||||
calendarService.listAdminEvents(),
|
||||
immichClient.listAlbums().catch(() => []),
|
||||
categoryService.listCategories(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
|
||||
return (
|
||||
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Planung"
|
||||
title="Kalender"
|
||||
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen melden zurück, ob sie da sind, und können das verknüpfte Album selbst freischalten. Alben ohne Kalender-Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
|
||||
/>
|
||||
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen merken Termine vor und bekommen das verknüpfte Album automatisch, sobald es da ist. Alben ohne Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
|
||||
>
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/kalender/kategorien">Kategorien verwalten</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<CalendarEventForm
|
||||
action={createCalendarEventAction}
|
||||
defaultEventDate={today}
|
||||
albums={albums.map((album) => ({ id: album.id, albumName: album.albumName }))}
|
||||
categories={categories.map((category) => ({ id: category.id, name: category.name }))}
|
||||
defaultEventDate={today}
|
||||
/>
|
||||
|
||||
{immichUnavailable ? (
|
||||
<p className="bg-muted p-4 rounded-md text-sm" role="status">
|
||||
Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht.
|
||||
</p>
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht."
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<section className="space-y-4" aria-labelledby="calendar-list-title">
|
||||
<Card title="Monatsübersicht">
|
||||
<EventMonth
|
||||
events={events.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.title,
|
||||
eventDate: event.eventDate,
|
||||
color: event.category?.color ?? null,
|
||||
}))}
|
||||
/>
|
||||
<CategoryLegend categories={categories} showUncategorized={events.some((event) => !event.category)} />
|
||||
</Card>
|
||||
|
||||
<section aria-labelledby="calendar-list-title" className="flex flex-col gap-4">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h2 id="calendar-list-title" className="text-xl font-semibold">
|
||||
<h2 className="text-xl font-semibold" id="calendar-list-title">
|
||||
Alle Termine
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground">{events.length} insgesamt</p>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">{events.length} insgesamt</p>
|
||||
</div>
|
||||
|
||||
{events.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">
|
||||
Noch keine Termine vorhanden. Legen Sie oben den ersten Termin an.
|
||||
</p>
|
||||
<EmptyState title="Noch keine Termine" description="Legen Sie oben den ersten Termin an." />
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
<ul className="flex flex-col gap-3">
|
||||
{events.map((event) => {
|
||||
const attending = event.responses.filter((response) => response.status === "attending");
|
||||
const notAttending = event.responses.filter((response) => response.status === "not_attending");
|
||||
const granted = event.reservations.filter((row) => row.grantedAt).length;
|
||||
return (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] sm:flex-row sm:items-start"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="space-y-2 min-w-0">
|
||||
<p className="font-semibold">
|
||||
<div className="flex min-w-0 flex-col gap-2">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? (
|
||||
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
<span>· {event.album ? `Album: ${event.album.albumName}` : "Noch kein Album verknüpft"}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatIsoDateGerman(event.eventDate)} ·{" "}
|
||||
{event.album ? (
|
||||
<span>Album: {event.album.albumName}</span>
|
||||
) : (
|
||||
<span>Noch kein Album verknüpft</span>
|
||||
)}
|
||||
</p>
|
||||
{event.responses.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5 text-xs">
|
||||
{attending.map((response) => (
|
||||
<span
|
||||
key={response.editorialId}
|
||||
className="rounded-full bg-green-600/10 px-2.5 py-1 font-medium text-green-700 dark:text-green-400"
|
||||
>
|
||||
{response.editorialName}: da
|
||||
</span>
|
||||
))}
|
||||
{notAttending.map((response) => (
|
||||
<span
|
||||
key={response.editorialId}
|
||||
className="rounded-full bg-muted px-2.5 py-1 text-muted-foreground"
|
||||
>
|
||||
{response.editorialName}: nicht da
|
||||
</span>
|
||||
))}
|
||||
{event.reservations.length > 0 ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">
|
||||
{event.reservations.length === 1 ? "1 Vormerkung" : `${event.reservations.length} Vormerkungen`}
|
||||
{granted > 0 ? `, ${granted} freigeschaltet` : ""}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{event.reservations.map((row) => (
|
||||
<Badge key={row.editorialId} variant={row.grantedAt ? "success" : "neutral"}>
|
||||
{row.editorialName}: {row.grantedAt ? "freigeschaltet" : "vorgemerkt"}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">Noch keine Rückmeldungen.</p>
|
||||
<p className="text-xs text-[var(--color-fg-muted)]">Noch keine Vormerkungen.</p>
|
||||
)}
|
||||
</div>
|
||||
<DeleteCalendarEventButton action={deleteCalendarEventAction} eventId={event.id} />
|
||||
@@ -101,7 +122,6 @@ export default async function AdminCalendarPage() {
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
+122
-110
@@ -1,116 +1,116 @@
|
||||
import { eq, sql, and, desc, gte } from "drizzle-orm";
|
||||
import { db } from "@/db/client";
|
||||
import { usages, editorialAccounts } from "@/db/schema";
|
||||
import Link from "next/link";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
|
||||
import { CategoryDot } from "@/components/calendar/category-legend";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { BarChart, Card, EmptyState, StatCard, DataTable } from "@/components/ui/sakani";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Badge, BarChart, Card, DataTable, EmptyState, StatCard } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
import { loadDashboardCounts } from "@/modules/dashboard/queries";
|
||||
import { dashboardTasks } from "@/modules/dashboard/tasks";
|
||||
import { statsQueries } from "@/modules/stats/queries";
|
||||
|
||||
import { requireAdminPage } from "./access";
|
||||
|
||||
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
const ACTIVITY_LABELS: Record<string, string> = {
|
||||
album_view: "Album geöffnet",
|
||||
search: "Suche",
|
||||
lightbox_view: "Großansicht",
|
||||
};
|
||||
|
||||
const linkClass = "font-medium text-[var(--color-fg-default)] underline-offset-4 hover:underline";
|
||||
|
||||
export default async function AdminDashboardPage() {
|
||||
await requireAdminPage();
|
||||
|
||||
const now = new Date();
|
||||
const firstDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth(), 1));
|
||||
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||
|
||||
const [revenueStatsResult, topEditorials, topAlbums, dailyDownloads] = await Promise.all([
|
||||
// 1. Umsatz diesen Monat (Offen + Abgerechnet, aber nur usages aus diesem Monat)
|
||||
db
|
||||
.select({
|
||||
totalCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
count: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, firstDayOfMonth)),
|
||||
|
||||
// 2. Aktivste Redaktionen (nach Anzahl an Downloads insgesamt)
|
||||
db
|
||||
.select({
|
||||
editorialId: usages.editorialAccountId,
|
||||
name: editorialAccounts.name,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
|
||||
.groupBy(usages.editorialAccountId, editorialAccounts.name)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5),
|
||||
|
||||
// 3. Beliebteste Alben
|
||||
db
|
||||
.select({
|
||||
albumName: usages.albumNameSnapshot,
|
||||
downloadCount: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.groupBy(usages.albumNameSnapshot)
|
||||
.orderBy(desc(sql`COUNT(${usages.id})`))
|
||||
.limit(5),
|
||||
|
||||
// 4. Time-series data for the last 30 days
|
||||
db
|
||||
.select({
|
||||
date: sql<string>`DATE_TRUNC('day', ${usages.createdAt})::date::text`,
|
||||
downloads: sql<number>`COUNT(${usages.id})::int`,
|
||||
})
|
||||
.from(usages)
|
||||
.where(gte(usages.createdAt, thirtyDaysAgo))
|
||||
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
.orderBy(sql`DATE_TRUNC('day', ${usages.createdAt})`)
|
||||
const [counts, stats, calendar] = await Promise.all([
|
||||
loadDashboardCounts(now),
|
||||
statsQueries.loadOverview(30),
|
||||
calendarService.listAdminEvents(),
|
||||
]);
|
||||
|
||||
const revenueStats = revenueStatsResult[0];
|
||||
|
||||
// Fill in missing days
|
||||
const chartData = [];
|
||||
for (let i = 29; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const dateStr = d.toISOString().split('T')[0];
|
||||
const record = dailyDownloads.find(r => r.date === dateStr);
|
||||
chartData.push({
|
||||
label: d.toLocaleDateString("de-DE", { day: "numeric" }), // ponytail: day only; 30 "dd. MMM" labels overlap
|
||||
value: record ? record.downloads : 0,
|
||||
});
|
||||
}
|
||||
|
||||
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
const tasks = dashboardTasks(counts);
|
||||
const today = isoDateInBerlin(now);
|
||||
const nextEvents = calendar.events.filter((event) => event.eventDate >= today).slice(0, 5);
|
||||
const { kpis } = stats;
|
||||
const downloads = stats.daily.map((day) => ({
|
||||
label: new Date(day.date).toLocaleDateString("de-DE", { day: "numeric" }),
|
||||
value: day.downloads,
|
||||
}));
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Admin Dashboard"
|
||||
description="Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals."
|
||||
>
|
||||
<Button asChild>
|
||||
<Link href="/admin/redaktionen">Redaktionen verwalten</Link>
|
||||
<PageHeader title="Dashboard" description="Was ansteht, was als Nächstes kommt und wie das Portal genutzt wird.">
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/admin/statistiken">Alle Statistiken</Link>
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard
|
||||
title="Umsatz diesen Monat"
|
||||
value={formatter.format((revenueStats?.totalCents ?? 0) / 100)}
|
||||
description={`${revenueStats?.count ?? 0} lizenzierte Bilder im ${now.toLocaleString("de-DE", { month: "long" })}`}
|
||||
/>
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Zu erledigen">
|
||||
{tasks.length === 0 ? (
|
||||
<EmptyState title="Alles erledigt" description="Keine offenen Freigaben, Rechnungen oder Fehler." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{tasks.map((task) => (
|
||||
<li className="flex items-center justify-between gap-4 py-3" key={task.id}>
|
||||
<Link className={linkClass} href={task.href}>
|
||||
{task.label}
|
||||
</Link>
|
||||
<Badge variant={task.tone}>{task.value}</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="Nächste Termine">
|
||||
{nextEvents.length === 0 ? (
|
||||
<EmptyState title="Keine Termine geplant" description="Neue Spiele legen Sie im Kalender an." />
|
||||
) : (
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{nextEvents.map((event) => (
|
||||
<li className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 py-3" key={event.id}>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{event.category ? <CategoryDot color={event.category.color} /> : <CategoryDot color="neutral" />}
|
||||
<span className="truncate font-medium">{event.title}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-[var(--color-fg-muted)]">
|
||||
<span className="tabular-nums">{formatIsoDateGerman(event.eventDate)}</span>
|
||||
<Badge>
|
||||
{event.reservations.length === 1 ? "1 Vormerkung" : `${event.reservations.length} Vormerkungen`}
|
||||
</Badge>
|
||||
<Badge variant={event.album ? "success" : "neutral"}>{event.album ? "Album da" : "Kein Album"}</Badge>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<Link className={`${linkClass} text-sm`} href="/admin/kalender">
|
||||
Zum Kalender
|
||||
</Link>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card title="Downloads der letzten 30 Tage" description="Tägliche Nutzung des Bildarchivs über alle Redaktionen hinweg.">
|
||||
{chartData.every((day) => day.value === 0) ? (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<StatCard title="Downloads (30 Tage)" value={String(kpis.downloadsCompleted)} description="Ausgelieferte Originale" />
|
||||
<StatCard title="Umsatz (30 Tage)" value={euro.format(kpis.revenueCents / 100)} description="Netto, aus neuen Nutzungen" />
|
||||
<StatCard title="Album-Aufrufe (30 Tage)" value={String(kpis.albumViews)} description="Seit Version 2.2 erfasst" />
|
||||
</div>
|
||||
|
||||
<Card title="Downloads der letzten 30 Tage" description="Tägliche Downloads über alle Redaktionen.">
|
||||
{downloads.every((day) => day.value === 0) ? (
|
||||
<EmptyState title="Keine Downloads" description="In den letzten 30 Tagen wurden keine Bilder geladen." />
|
||||
) : (
|
||||
<BarChart data={chartData} seriesLabels={["Downloads"]} size="lg" />
|
||||
<BarChart data={downloads} seriesLabels={["Downloads"]} size="lg" />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card title="Aktivste Redaktionen" description="Die Top 5 Redaktionen nach Downloads.">
|
||||
{topEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
<Card title="Aktivste Redaktionen" description="Nach Downloads in den letzten 30 Tagen.">
|
||||
{stats.topEditorials.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten" description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
@@ -118,34 +118,46 @@ export default async function AdminDashboardPage() {
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
{ key: "revenue", header: "Umsatz", align: "right" },
|
||||
]}
|
||||
rows={topEditorials.map((ed) => ({
|
||||
id: ed.editorialId,
|
||||
rows={stats.topEditorials.slice(0, 5).map((row) => ({
|
||||
id: row.editorialId,
|
||||
name: (
|
||||
<Link href={`/admin/redaktionen/${ed.editorialId}`} className="font-medium text-[var(--color-brand-fg)] hover:underline">
|
||||
{ed.name}
|
||||
<Link className={linkClass} href={`/admin/redaktionen/${row.editorialId}`}>
|
||||
{row.name}
|
||||
</Link>
|
||||
),
|
||||
downloads: <span className="tabular-nums">{ed.downloadCount}</span>,
|
||||
revenue: <span className="tabular-nums">{formatter.format(ed.revenueCents / 100)}</span>,
|
||||
downloads: <span className="tabular-nums">{row.downloads}</span>,
|
||||
revenue: <span className="tabular-nums">{euro.format(row.revenueCents / 100)}</span>,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="Beliebteste Alben" description="Die Top 5 Alben nach Nutzung.">
|
||||
{topAlbums.length === 0 ? (
|
||||
<EmptyState title="Noch keine Daten vorhanden." description="Sobald Bilder geladen werden, erscheint hier die Auswertung." />
|
||||
<Card title="Letzte Aktivitäten" description="Aufrufe, Suchen und Großansichten der Redaktionen.">
|
||||
{stats.recentActivity.length === 0 ? (
|
||||
<EmptyState title="Noch keine Aktivitäten" description="Aufrufe und Suchen werden seit Version 2.2 erfasst." />
|
||||
) : (
|
||||
<DataTable
|
||||
columns={[
|
||||
{ key: "albumName", header: "Album" },
|
||||
{ key: "downloads", header: "Downloads", align: "right" },
|
||||
]}
|
||||
rows={topAlbums.map((album) => ({
|
||||
albumName: album.albumName,
|
||||
downloads: <span className="tabular-nums">{album.downloadCount}</span>,
|
||||
}))}
|
||||
/>
|
||||
<ul className="flex flex-col divide-y divide-[var(--color-border-subtle)]">
|
||||
{stats.recentActivity.slice(0, 8).map((event) => (
|
||||
<li className="flex flex-wrap items-center gap-3 py-2.5 text-sm" key={event.id}>
|
||||
<Badge>{ACTIVITY_LABELS[event.eventType] ?? event.eventType}</Badge>
|
||||
<span className="font-medium">{event.editorialName}</span>
|
||||
{event.query ? <span className="text-[var(--color-fg-muted)]">„{event.query}“</span> : null}
|
||||
<time
|
||||
className="ml-auto text-xs tabular-nums text-[var(--color-fg-muted)]"
|
||||
dateTime={event.occurredAt.toISOString()}
|
||||
suppressHydrationWarning
|
||||
>
|
||||
{event.occurredAt.toLocaleString("de-DE", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: "Europe/Berlin",
|
||||
})}
|
||||
</time>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
+27
-15
@@ -180,29 +180,25 @@ body:has([data-app-shell]) .legal-footer {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
/* --- Photo overview: masonry grid + hover overlay + lightbox --------------
|
||||
Replaces the old contact-sheet (forced 3:2 tiles, object-fit: contain,
|
||||
permanent monospace caption strips). Each photo keeps its native aspect
|
||||
ratio via an inline `aspect-ratio` set from EXIF dimensions; the grid uses
|
||||
CSS columns for a dense masonry layout. Captions and actions appear on
|
||||
hover/focus, and a full-screen lightbox opens on click. */
|
||||
/* --- Photo overview: uniform grid + hover overlay + lightbox --------------
|
||||
Rows read left to right, then down (CSS grid, not columns: a masonry made
|
||||
people scroll up and down to follow the order). Every tile is 3:2 with
|
||||
object-fit: cover, so rows line up; the lightbox shows the full photo.
|
||||
Portraits keep their upper part (faces) via object-position. */
|
||||
.photo-gallery {
|
||||
columns: 4 17rem;
|
||||
column-gap: clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
|
||||
gap: clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
@media (max-width: 64rem) {
|
||||
.photo-gallery { columns: 3 14rem; }
|
||||
}
|
||||
@media (max-width: 48rem) {
|
||||
.photo-gallery { columns: 2 9rem; }
|
||||
.photo-gallery { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
.photo-tile {
|
||||
break-inside: avoid;
|
||||
margin: 0 0 clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.photo-tile-frame {
|
||||
@@ -227,8 +223,9 @@ body:has([data-app-shell]) .legal-footer {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
min-height: 6rem;
|
||||
aspect-ratio: 3 / 2;
|
||||
object-fit: cover;
|
||||
object-position: center 30%;
|
||||
background: var(--contact-sheet);
|
||||
transition: transform 200ms ease-out;
|
||||
}
|
||||
@@ -710,3 +707,18 @@ body:has([data-app-shell]) .legal-footer {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Event calendar: German weekday labels ---------------------------------
|
||||
ponytail: Sakani's MonthCalendar hard-codes English weekday names and has
|
||||
no locale prop. With weekStartsOn={1} the row is always Mon..Sun, so the
|
||||
labels are swapped here. Breaks if Sakani renames its hashed "_weekdays_"
|
||||
class; drop this once Sakani ships a locale option. */
|
||||
.event-month [class*="_weekdays_"] > span { font-size: 0; }
|
||||
.event-month [class*="_weekdays_"] > span::after { font-size: 0.75rem; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(1)::after { content: "Mo"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(2)::after { content: "Di"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(3)::after { content: "Mi"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(4)::after { content: "Do"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(5)::after { content: "Fr"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(6)::after { content: "Sa"; }
|
||||
.event-month [class*="_weekdays_"] > span:nth-child(7)::after { content: "So"; }
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Badge, Button } from "@sakaniui/react";
|
||||
|
||||
import type { EventAccessState } from "@/modules/calendar/service";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
type Action = (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
|
||||
export function EventAccessAction({
|
||||
eventId,
|
||||
access,
|
||||
albumId,
|
||||
reserveAction,
|
||||
unreserveAction,
|
||||
}: Readonly<{
|
||||
eventId: string;
|
||||
access: EventAccessState;
|
||||
albumId: string | null;
|
||||
reserveAction: Action;
|
||||
unreserveAction: Action;
|
||||
}>) {
|
||||
const router = useRouter();
|
||||
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const run = (action: Action) => {
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
setState(result);
|
||||
if (result.ok) router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
let content: React.ReactNode;
|
||||
if ((access === "granted" || access === "auto_granted") && albumId) {
|
||||
content = (
|
||||
<>
|
||||
<Badge variant="success">{access === "auto_granted" ? "Automatisch freigegeben" : "Freigeschaltet"}</Badge>
|
||||
<Link
|
||||
className="inline-flex min-h-10 items-center justify-center rounded-md border border-[var(--color-border-default)] px-4 text-sm font-medium transition-colors hover:bg-[var(--color-bg-subtle)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-border-focus)]"
|
||||
href={`/redaktion/alben/${encodeURIComponent(albumId)}`}
|
||||
>
|
||||
Album öffnen
|
||||
</Link>
|
||||
</>
|
||||
);
|
||||
} else if (access === "auto_rule" || access === "auto_granted") {
|
||||
content = <Badge variant="info">Automatisch freigegeben (Auto-Regel)</Badge>;
|
||||
} else if (access === "reserved") {
|
||||
content = (
|
||||
<>
|
||||
<Badge variant="accent">Vorgemerkt</Badge>
|
||||
<Button disabled={pending} onClick={() => run(unreserveAction)} size="sm" type="button" variant="ghost">
|
||||
Vormerkung entfernen
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
content = (
|
||||
<Button disabled={pending} onClick={() => run(reserveAction)} type="button" variant="primary">
|
||||
{pending ? "Wird hinzugefügt …" : "Zu meinen Alben hinzufügen"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
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,67 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Button } from "@sakaniui/react";
|
||||
|
||||
import type { EventResponseStatus } from "@/modules/calendar/service";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
export function EventRsvpButtons({
|
||||
action,
|
||||
eventId,
|
||||
initialResponse,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
eventId: string;
|
||||
initialResponse: EventResponseStatus | null;
|
||||
}>) {
|
||||
const [response, setResponse] = useState<EventResponseStatus | null>(initialResponse);
|
||||
const [error, setError] = useState("");
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const respond = (status: EventResponseStatus) => {
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
formData.set("status", status);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
if (result.ok) {
|
||||
setResponse(status);
|
||||
setError("");
|
||||
} else {
|
||||
setError(result.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-wrap gap-2" role="group" aria-label="Rückmeldung zu diesem Termin">
|
||||
<Button
|
||||
type="button"
|
||||
variant={response === "attending" ? "primary" : "outline"}
|
||||
aria-pressed={response === "attending"}
|
||||
disabled={pending}
|
||||
onClick={() => respond("attending")}
|
||||
>
|
||||
Bin da
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={response === "not_attending" ? "primary" : "outline"}
|
||||
aria-pressed={response === "not_attending"}
|
||||
disabled={pending}
|
||||
onClick={() => respond("not_attending")}
|
||||
>
|
||||
Bin nicht da
|
||||
</Button>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-xs text-[var(--color-danger-fg)]">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import type { CalendarActionResult } from "./actions";
|
||||
|
||||
// Grants access to the event's linked album and jumps straight into it.
|
||||
export function SelfGrantButton({
|
||||
action,
|
||||
eventId,
|
||||
}: Readonly<{
|
||||
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
|
||||
eventId: string;
|
||||
}>) {
|
||||
const router = useRouter();
|
||||
const [error, setError] = useState("");
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const handleClick = () => {
|
||||
const formData = new FormData();
|
||||
formData.set("eventId", eventId);
|
||||
startTransition(async () => {
|
||||
const result = await action({ ok: true, message: "" }, formData);
|
||||
if (result.ok && result.albumId) {
|
||||
router.push(`/redaktion/alben/${encodeURIComponent(result.albumId)}`);
|
||||
} else {
|
||||
setError(result.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button type="button" className="min-h-11" disabled={pending} onClick={handleClick}>
|
||||
{pending ? "Wird freigeschaltet…" : "Zugriff freischalten"}
|
||||
</Button>
|
||||
{error ? (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,11 +4,7 @@ import { revalidatePath } from "next/cache";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import {
|
||||
CalendarServiceError,
|
||||
calendarService,
|
||||
type EventResponseStatus,
|
||||
} from "@/modules/calendar/service";
|
||||
import { CalendarServiceError, calendarService } from "@/modules/calendar/service";
|
||||
|
||||
export type CalendarActionResult = {
|
||||
ok: boolean;
|
||||
@@ -16,59 +12,57 @@ export type CalendarActionResult = {
|
||||
albumId?: string;
|
||||
};
|
||||
|
||||
export async function respondToEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireActiveEditorial(new Headers(await headers()));
|
||||
function eventIdFrom(formData: FormData): string | null {
|
||||
const eventId = formData.get("eventId");
|
||||
const status = formData.get("status");
|
||||
if (typeof eventId !== "string" || (status !== "attending" && status !== "not_attending")) {
|
||||
return { ok: false, message: "Ungültige Rückmeldung." };
|
||||
}
|
||||
|
||||
try {
|
||||
await calendarService.respond({
|
||||
eventId,
|
||||
editorialId: principal.editorialId,
|
||||
actorUserId: principal.userId,
|
||||
status: status as EventResponseStatus,
|
||||
});
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
|
||||
revalidatePath("/redaktion/kalender");
|
||||
revalidatePath("/admin/kalender");
|
||||
return { ok: true, message: "" };
|
||||
return typeof eventId === "string" && eventId.length > 0 ? eventId : null;
|
||||
}
|
||||
|
||||
export async function selfGrantAlbumAction(
|
||||
function revalidate(albumId?: string) {
|
||||
revalidatePath("/redaktion/kalender");
|
||||
revalidatePath("/redaktion/alben");
|
||||
revalidatePath("/admin/kalender");
|
||||
if (albumId) revalidatePath(`/redaktion/alben/${albumId}`);
|
||||
}
|
||||
|
||||
/** "Zu meinen Alben hinzufügen": grants at once if the album exists, else reserves. */
|
||||
export async function reserveEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireActiveEditorial(new Headers(await headers()));
|
||||
const eventId = formData.get("eventId");
|
||||
if (typeof eventId !== "string" || eventId.length === 0) {
|
||||
return { ok: false, message: "Ungültiger Termin." };
|
||||
}
|
||||
const eventId = eventIdFrom(formData);
|
||||
if (!eventId) return { ok: false, message: "Ungültiger Termin." };
|
||||
|
||||
let albumId: string;
|
||||
try {
|
||||
const album = await calendarService.selfGrantAlbum({
|
||||
const result = await calendarService.reserve({
|
||||
eventId,
|
||||
editorialId: principal.editorialId,
|
||||
actorUserId: principal.userId,
|
||||
});
|
||||
albumId = album.id;
|
||||
revalidate(result.album?.id);
|
||||
return result.status === "granted"
|
||||
? { ok: true, message: "Album freigeschaltet.", albumId: result.album!.id }
|
||||
: { ok: true, message: "Vorgemerkt. Das Album erscheint automatisch in Ihren Alben, sobald es da ist." };
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/redaktion/kalender");
|
||||
revalidatePath("/redaktion/alben");
|
||||
revalidatePath(`/redaktion/alben/${albumId}`);
|
||||
return { ok: true, message: "", albumId };
|
||||
export async function unreserveEventAction(
|
||||
_prevState: CalendarActionResult,
|
||||
formData: FormData,
|
||||
): Promise<CalendarActionResult> {
|
||||
const principal = await requireActiveEditorial(new Headers(await headers()));
|
||||
const eventId = eventIdFrom(formData);
|
||||
if (!eventId) return { ok: false, message: "Ungültiger Termin." };
|
||||
|
||||
try {
|
||||
await calendarService.unreserve({ eventId, editorialId: principal.editorialId, actorUserId: principal.userId });
|
||||
} catch (error) {
|
||||
return { ok: false, message: calendarErrorMessage(error) };
|
||||
}
|
||||
revalidate();
|
||||
return { ok: true, message: "Vormerkung entfernt." };
|
||||
}
|
||||
|
||||
function calendarErrorMessage(error: unknown): string {
|
||||
@@ -77,13 +71,13 @@ function calendarErrorMessage(error: unknown): string {
|
||||
INVALID_TITLE: "Ungültiger Termin.",
|
||||
INVALID_EVENT_DATE: "Ungültiger Termin.",
|
||||
INVALID_ALBUM: "Ungültiger Termin.",
|
||||
INVALID_STATUS: "Ungültige Rückmeldung.",
|
||||
INVALID_CATEGORY: "Ungültiger Termin.",
|
||||
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
|
||||
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verfügbar.",
|
||||
RESERVATION_NOT_FOUND: "Diese Vormerkung gibt es nicht mehr. Das Album ist vermutlich schon freigeschaltet.",
|
||||
IMMICH_UNAVAILABLE: "Das Bildarchiv ist gerade nicht erreichbar. Bitte später erneut versuchen.",
|
||||
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
|
||||
};
|
||||
return messages[error.code] ?? "Die Aktion konnte nicht ausgeführt werden.";
|
||||
return messages[error.code];
|
||||
}
|
||||
return "Die Aktion konnte nicht ausgeführt werden.";
|
||||
}
|
||||
@@ -1,84 +1,111 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { CategoryDot, CategoryLegend } from "@/components/calendar/category-legend";
|
||||
import { EventMonth } from "@/components/calendar/event-month";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Alert, Badge, Card, EmptyState } from "@/components/ui/sakani";
|
||||
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
|
||||
import { categoryService } from "@/modules/calendar/categories";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
import { EventRsvpButtons } from "./EventRsvpButtons";
|
||||
import { SelfGrantButton } from "./SelfGrantButton";
|
||||
import { respondToEventAction, selfGrantAlbumAction } from "./actions";
|
||||
import { EventAccessAction } from "./EventAccessAction";
|
||||
import { reserveEventAction, unreserveEventAction } from "./actions";
|
||||
|
||||
export default async function EditorialCalendarPage() {
|
||||
const principal = await requireEditorial();
|
||||
const { events, immichUnavailable } = await calendarService.listEditorialEvents(
|
||||
principal.editorialId,
|
||||
new Date(),
|
||||
);
|
||||
const [{ events, immichUnavailable }, categories] = await Promise.all([
|
||||
calendarService.listEditorialEvents(principal.editorialId, new Date()),
|
||||
categoryService.listCategories(),
|
||||
]);
|
||||
const today = isoDateInBerlin(new Date());
|
||||
const upcoming = events.filter((event) => event.eventDate >= today);
|
||||
const past = events.filter((event) => event.eventDate < today).reverse();
|
||||
const ordered = [...upcoming, ...past];
|
||||
const usedCategoryIds = new Set(events.map((event) => event.category?.id).filter(Boolean));
|
||||
|
||||
return (
|
||||
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="calendar-title">
|
||||
<section aria-labelledby="calendar-title" className="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
kicker="Bildarchiv · Kalender"
|
||||
title="Kalender"
|
||||
titleId="calendar-title"
|
||||
description="Kommende Spiele und Termine. Melden Sie zurück, ob Sie da sind, und schalten Sie das Album zum Termin selbst frei, sobald es angelegt ist."
|
||||
description="Kommende Spiele und Termine. Fügen Sie einen Termin zu Ihren Alben hinzu: Ist das Album schon da, ist es sofort freigeschaltet, sonst automatisch, sobald es angelegt ist."
|
||||
/>
|
||||
|
||||
{immichUnavailable ? (
|
||||
<p className="bg-muted p-4 rounded-md text-sm" role="status">
|
||||
Das Bildarchiv ist gerade nicht erreichbar. Termine und Rückmeldungen funktionieren weiterhin, Alben erscheinen wieder, sobald die Verbindung steht.
|
||||
</p>
|
||||
<Alert
|
||||
color="warning"
|
||||
description="Das Bildarchiv ist gerade nicht erreichbar. Termine und Vormerkungen funktionieren weiterhin, Alben erscheinen wieder, sobald die Verbindung steht."
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{ordered.length === 0 ? (
|
||||
<p className="text-muted-foreground text-center py-12">
|
||||
Zurzeit sind keine Termine eingetragen. Sobald ein Spiel oder Event geplant ist, erscheint es hier.
|
||||
</p>
|
||||
{events.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Zurzeit keine Termine"
|
||||
description="Sobald ein Spiel oder Event geplant ist, erscheint es hier."
|
||||
/>
|
||||
) : (
|
||||
<ul className="space-y-3">
|
||||
{ordered.map((event) => (
|
||||
<li
|
||||
key={event.id}
|
||||
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col lg:flex-row lg:items-center gap-4 justify-between"
|
||||
>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? (
|
||||
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">{formatIsoDateGerman(event.eventDate)}</p>
|
||||
{event.album ? null : (
|
||||
<p className="text-xs text-muted-foreground">Album noch nicht angelegt.</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
|
||||
<EventRsvpButtons
|
||||
action={respondToEventAction}
|
||||
eventId={event.id}
|
||||
initialResponse={event.response}
|
||||
/>
|
||||
{event.album && event.isGranted ? (
|
||||
<Link
|
||||
className="inline-flex min-h-11 items-center justify-center rounded-md border border-border bg-background px-4 text-sm font-medium transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
|
||||
href={`/redaktion/alben/${encodeURIComponent(event.album.id)}`}
|
||||
>
|
||||
Album öffnen
|
||||
</Link>
|
||||
) : event.album ? (
|
||||
<SelfGrantButton action={selfGrantAlbumAction} eventId={event.id} />
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<>
|
||||
<Card title="Monatsübersicht">
|
||||
<EventMonth
|
||||
events={events.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.title,
|
||||
eventDate: event.eventDate,
|
||||
color: event.category?.color ?? null,
|
||||
}))}
|
||||
/>
|
||||
<CategoryLegend
|
||||
categories={categories.filter((category) => usedCategoryIds.has(category.id))}
|
||||
showUncategorized={events.some((event) => !event.category)}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{[
|
||||
{ id: "upcoming", title: "Kommende Termine", list: upcoming },
|
||||
{ id: "past", title: "Vergangene Termine", list: past },
|
||||
]
|
||||
.filter((group) => group.list.length > 0)
|
||||
.map((group) => (
|
||||
<section aria-labelledby={`calendar-${group.id}`} className="flex flex-col gap-3" key={group.id}>
|
||||
<h2 className="text-xl font-semibold" id={`calendar-${group.id}`}>
|
||||
{group.title}
|
||||
</h2>
|
||||
<ul className="flex flex-col gap-3">
|
||||
{group.list.map((event) => (
|
||||
<li
|
||||
className="flex flex-col justify-between gap-4 rounded-xl border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-4 outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-focus)] lg:flex-row lg:items-center"
|
||||
id={`termin-${event.id}`}
|
||||
key={event.id}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<p className="flex flex-wrap items-center gap-2 font-semibold">
|
||||
{event.title}
|
||||
{event.eventDate < today ? <Badge>vorbei</Badge> : null}
|
||||
</p>
|
||||
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-fg-muted)]">
|
||||
<span>{formatIsoDateGerman(event.eventDate)}</span>
|
||||
{event.category ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
· <CategoryDot color={event.category.color} /> {event.category.name}
|
||||
</span>
|
||||
) : null}
|
||||
{event.album ? null : <span>· Album noch nicht angelegt</span>}
|
||||
</p>
|
||||
</div>
|
||||
<EventAccessAction
|
||||
access={event.access}
|
||||
albumId={event.album?.id ?? null}
|
||||
eventId={event.id}
|
||||
reserveAction={reserveEventAction}
|
||||
unreserveAction={unreserveEventAction}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CATEGORY_COLOR_VARS, type CategoryColor } from "@/modules/calendar/colors";
|
||||
|
||||
export function CategoryDot({ color }: Readonly<{ color: CategoryColor }>) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="inline-block size-2.5 shrink-0 rounded-full"
|
||||
style={{ background: CATEGORY_COLOR_VARS[color] }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoryLegend({
|
||||
categories,
|
||||
showUncategorized = false,
|
||||
}: Readonly<{ categories: Array<{ id: string; name: string; color: CategoryColor }>; showUncategorized?: boolean }>) {
|
||||
if (categories.length === 0 && !showUncategorized) return null;
|
||||
return (
|
||||
<ul aria-label="Legende" className="flex flex-wrap gap-x-5 gap-y-2 text-sm text-[var(--color-fg-muted)]">
|
||||
{categories.map((category) => (
|
||||
<li className="flex items-center gap-2" key={category.id}>
|
||||
<CategoryDot color={category.color} />
|
||||
{category.name}
|
||||
</li>
|
||||
))}
|
||||
{showUncategorized ? (
|
||||
<li className="flex items-center gap-2">
|
||||
<CategoryDot color="neutral" />
|
||||
Ohne Kategorie
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button, IconButton, MonthCalendar, type CalendarEventData } from "@sakaniui/react";
|
||||
import { IconChevronLeft, IconChevronRight } from "@sakaniui/react/icons";
|
||||
|
||||
import type { CategoryColor } from "@/modules/calendar/colors";
|
||||
|
||||
export type MonthEvent = { id: string; title: string; eventDate: string; color: CategoryColor | null };
|
||||
|
||||
/** ISO day -> local midnight, so the chip lands on its day in every time zone. */
|
||||
function localDay(isoDate: string): Date {
|
||||
const [year, month, day] = isoDate.split("-").map(Number);
|
||||
return new Date(year, month - 1, day);
|
||||
}
|
||||
|
||||
const monthTitle = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" });
|
||||
|
||||
// The month grid is the overview; details and actions live in the event list
|
||||
// below it. A click scrolls to that event's entry (id "termin-{id}") and
|
||||
// focuses it, so keyboard and screen-reader users land on the actions too.
|
||||
// Sakani's header is English-only, so we draw a German one (hideHeader);
|
||||
// weekday labels are swapped in globals.css (.event-month).
|
||||
export function EventMonth({ events }: Readonly<{ events: MonthEvent[] }>) {
|
||||
const [month, setMonth] = useState(() => new Date());
|
||||
const shift = (delta: number) => setMonth((current) => new Date(current.getFullYear(), current.getMonth() + delta, 1));
|
||||
const data: CalendarEventData[] = events.map((event) => {
|
||||
const day = localDay(event.eventDate);
|
||||
return { id: event.id, title: event.title, start: day, end: day, allDay: true, color: event.color ?? "neutral" };
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="event-month flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 aria-live="polite" className="text-lg font-semibold capitalize">
|
||||
{monthTitle.format(month)}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button onClick={() => setMonth(new Date())} size="sm" type="button" variant="outline">
|
||||
Heute
|
||||
</Button>
|
||||
<IconButton aria-label="Vorheriger Monat" icon={IconChevronLeft} onClick={() => shift(-1)} size="sm" variant="ghost" />
|
||||
<IconButton aria-label="Nächster Monat" icon={IconChevronRight} onClick={() => shift(1)} size="sm" variant="ghost" />
|
||||
</div>
|
||||
</div>
|
||||
<MonthCalendar
|
||||
date={month}
|
||||
events={data}
|
||||
hideHeader
|
||||
onDateChange={setMonth}
|
||||
onEventClick={(event) => {
|
||||
const target = document.getElementById(`termin-${event.id}`);
|
||||
target?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
target?.focus({ preventScroll: true });
|
||||
}}
|
||||
weekStartsOn={1}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,24 +9,22 @@ 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.2.2",
|
||||
title: "Kalender, Statistiken, Collab und Rechnungen",
|
||||
version: "2.3",
|
||||
title: "Kalender mit Kategorien und Vormerken",
|
||||
notes: {
|
||||
redaktion: [
|
||||
"Neuer Kalender: kommende Termine sehen, zurückmelden ob Sie da sind, und das verknüpfte Album selbst freischalten.",
|
||||
"Die Suche findet jetzt auch Dateinamen; Merkzettel-Links führen direkt zum richtigen Bild.",
|
||||
"Fotos lassen sich nach ältesten und neuesten sortieren; die Bildbeschreibung erscheint in der Großansicht.",
|
||||
"Wenn Ihre Redaktion für Collab freigeschaltet ist, können Sie Downloads als kostenlose Collab-Nutzung markieren (auch für mehrere Bilder vom Merkzettel).",
|
||||
"Rechnung und Nutzungsnachweis kommen gebündelt per E-Mail, sobald die Rechnung vorliegt.",
|
||||
"Unter Neuigkeiten steht jetzt die komplette Versionshistorie: alle Änderungen seit Version 2.0, neueste zuerst.",
|
||||
"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.",
|
||||
],
|
||||
admin: [
|
||||
"Neue Statistik-Seite: Downloads, Datenmenge, Aufrufe, Suchen, Umsatz und Collab-Quote mit Zeitraum-Vergleich.",
|
||||
"Kalender unter /admin/kalender: Termine anlegen, Alben verknüpfen, Zusagen der Redaktionen einsehen.",
|
||||
"Collab-Nutzung je Redaktion freischalten; Collab-Positionen erscheinen mit 0,00 € in der Abrechnung und lassen sich dort korrigieren.",
|
||||
"Rechnungs-PDF je Abrechnung hochladen: danach geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per E-Mail raus. Der Nutzungsnachweis wird beim Finalisieren nicht mehr automatisch verschickt.",
|
||||
"Abrechnungen laufen immer quartalsweise: Die Abrechnungsseite öffnet direkt das aktuelle Quartal.",
|
||||
"Versionshinweise werden unter /admin/versionen gepflegt; dort steht jetzt auch die komplette Versionshistorie, gruppiert nach Version.",
|
||||
"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.",
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -9,21 +9,44 @@ import { editorialAccounts } from "./editorials";
|
||||
// the album appears: "{title}" or "{title} | {TT.MM.JJJJ}". Only linked albums
|
||||
// are eligible for editorial self-service access; auto-rule grants stay
|
||||
// independent of the calendar.
|
||||
// Admin-managed categories (e.g. "Fußball - 1. Bundesliga") with one of the
|
||||
// colors Sakani's calendar supports (src/modules/calendar/colors.ts), so chips
|
||||
// stay readable in both themes.
|
||||
export const eventCategories = pgTable(
|
||||
"event_categories",
|
||||
{
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
color: text("color").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
createdByUserId: uuid("created_by_user_id").references(() => users.id, { onDelete: "restrict" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("event_categories_name_lower_unique").on(sql`lower(${table.name})`),
|
||||
check(
|
||||
"event_categories_color_check",
|
||||
sql`${table.color} in ('blue', 'green', 'orange', 'purple', 'teal', 'gold', 'red', 'neutral')`,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const calendarEvents = pgTable("calendar_events", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
eventDate: date("event_date").notNull(),
|
||||
immichAlbumId: text("immich_album_id"),
|
||||
categoryId: uuid("category_id").references(() => eventCategories.id, { onDelete: "restrict" }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
|
||||
onDelete: "restrict",
|
||||
}),
|
||||
});
|
||||
|
||||
// Editorial RSVP per event: "attending" or "not_attending". One row per
|
||||
// (event, editorial); responding again updates the existing row.
|
||||
export const eventResponses = pgTable(
|
||||
"event_responses",
|
||||
// "Zu meinen Alben hinzufügen": an editorial reserves an event. If the linked
|
||||
// album exists, access is granted at once (self_service); otherwise the
|
||||
// auto-rule scheduler grants it once the album appears and sets grantedAt.
|
||||
export const eventReservations = pgTable(
|
||||
"event_reservations",
|
||||
{
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
eventId: uuid("event_id")
|
||||
@@ -32,11 +55,10 @@ export const eventResponses = pgTable(
|
||||
editorialAccountId: uuid("editorial_account_id")
|
||||
.notNull()
|
||||
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
||||
status: text("status").notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
grantedAt: timestamp("granted_at", { withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("event_responses_event_editorial_unique").on(table.eventId, table.editorialAccountId),
|
||||
check("event_responses_status_check", sql`${table.status} in ('attending', 'not_attending')`),
|
||||
uniqueIndex("event_reservations_event_editorial_unique").on(table.eventId, table.editorialAccountId),
|
||||
],
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import "server-only";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { autoRuleService } from "./auto-rules";
|
||||
import { calendarService } from "@/modules/calendar/service";
|
||||
|
||||
const DEFAULT_INTERVAL_SECONDS = 120;
|
||||
const INITIAL_DELAY_MS = 15_000;
|
||||
@@ -37,6 +38,16 @@ export function startAutoRuleScheduler(): void {
|
||||
} catch (error) {
|
||||
console.error("[auto-rule-sync] failed:", error);
|
||||
}
|
||||
// Calendar reservations ("Zu meinen Alben hinzufügen") resolve on the
|
||||
// same tick: same Immich album list, same cadence.
|
||||
try {
|
||||
const reserved = await calendarService.resolvePendingReservations();
|
||||
if (reserved.granted > 0) {
|
||||
console.log(`[calendar-reservations] granted ${reserved.granted} reserved album(s)`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[calendar-reservations] failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const initialTimeout = setTimeout(tick, INITIAL_DELAY_MS);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
|
||||
import { useEffect, useState, type CSSProperties } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { EmptyState, IconButton } from "@sakaniui/react";
|
||||
import { IconChevronLeft, IconChevronRight, IconX } from "@sakaniui/react/icons";
|
||||
|
||||
@@ -96,7 +96,6 @@ export function PhotoGallery({
|
||||
className="photo-tile-image"
|
||||
loading="lazy"
|
||||
src={thumbnailUrl(asset.id)}
|
||||
style={aspectStyle(asset)}
|
||||
/>
|
||||
</button>
|
||||
<div className="photo-tile-overlay">
|
||||
@@ -195,9 +194,3 @@ function PhotoLightbox({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function aspectStyle(asset: GalleryPhoto): CSSProperties {
|
||||
const width = asset.width ?? 0;
|
||||
const height = asset.height ?? 0;
|
||||
return width > 0 && height > 0 ? { aspectRatio: `${width} / ${height}` } : {};
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { CategoryServiceError, createCategoryService, type CategoryRepository } from "./categories";
|
||||
|
||||
function setup(overrides: Partial<CategoryRepository> = {}) {
|
||||
const repository: CategoryRepository = {
|
||||
list: vi.fn(async () => []),
|
||||
insert: vi.fn(async (input) => ({ id: "c1", name: input.name, color: input.color })),
|
||||
get: vi.fn(async () => ({ id: "c1", name: "Fußball", color: "green" as const, eventCount: 0 })),
|
||||
delete: vi.fn(async () => undefined),
|
||||
...overrides,
|
||||
};
|
||||
const writeAudit = vi.fn(async () => undefined);
|
||||
return { repository, writeAudit, service: createCategoryService({ repository, audit: { writeAudit } }) };
|
||||
}
|
||||
|
||||
const code = (promise: Promise<unknown>) =>
|
||||
promise.then(
|
||||
() => "ok",
|
||||
(error: unknown) => (error instanceof CategoryServiceError ? error.code : error),
|
||||
);
|
||||
|
||||
test("createCategory validates name and color", async () => {
|
||||
const { service } = setup();
|
||||
expect(await code(service.createCategory({ name: " ", color: "blue", adminUserId: "u" }))).toBe("INVALID_NAME");
|
||||
expect(await code(service.createCategory({ name: "x".repeat(81), color: "blue", adminUserId: "u" }))).toBe("INVALID_NAME");
|
||||
expect(await code(service.createCategory({ name: "Volleyball", color: "pink", adminUserId: "u" }))).toBe("INVALID_COLOR");
|
||||
});
|
||||
|
||||
test("createCategory trims, stores and audits", async () => {
|
||||
const { service, repository, writeAudit } = setup();
|
||||
const created = await service.createCategory({ name: " Fußball - 1. Bundesliga ", color: "green", adminUserId: "u" });
|
||||
expect(created.name).toBe("Fußball - 1. Bundesliga");
|
||||
expect(repository.insert).toHaveBeenCalledWith({ name: "Fußball - 1. Bundesliga", color: "green", adminUserId: "u" });
|
||||
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ type: "event_category_created" }));
|
||||
});
|
||||
|
||||
test("createCategory maps a unique violation (also wrapped) to DUPLICATE_NAME", async () => {
|
||||
const wrapped = Object.assign(new Error("query failed"), { cause: { code: "23505" } });
|
||||
const { service } = setup({ insert: vi.fn(async () => Promise.reject(wrapped)) });
|
||||
expect(await code(service.createCategory({ name: "fußball", color: "green", adminUserId: "u" }))).toBe("DUPLICATE_NAME");
|
||||
});
|
||||
|
||||
test("deleteCategory refuses categories in use and unknown ones", async () => {
|
||||
const inUse = setup({ get: vi.fn(async () => ({ id: "c1", name: "F", color: "green" as const, eventCount: 2 })) });
|
||||
expect(await code(inUse.service.deleteCategory({ id: "c1", adminUserId: "u" }))).toBe("CATEGORY_IN_USE");
|
||||
expect(inUse.repository.delete).not.toHaveBeenCalled();
|
||||
|
||||
const missing = setup({ get: vi.fn(async () => null) });
|
||||
expect(await code(missing.service.deleteCategory({ id: "c1", adminUserId: "u" }))).toBe("CATEGORY_NOT_FOUND");
|
||||
});
|
||||
|
||||
test("deleteCategory deletes unused categories and audits", async () => {
|
||||
const { service, repository, writeAudit } = setup();
|
||||
await service.deleteCategory({ id: "c1", adminUserId: "u" });
|
||||
expect(repository.delete).toHaveBeenCalledWith("c1");
|
||||
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ type: "event_category_deleted" }));
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import "server-only";
|
||||
|
||||
import { asc, count, eq } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { calendarEvents, eventCategories } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { writeAudit } from "@/modules/audit/write";
|
||||
|
||||
import { isCategoryColor, type CategoryColor } from "./colors";
|
||||
|
||||
export { CATEGORY_COLORS, CATEGORY_COLOR_LABELS, type CategoryColor } from "./colors";
|
||||
export const CATEGORY_NAME_MAX_LENGTH = 80;
|
||||
|
||||
export type EventCategory = { id: string; name: string; color: CategoryColor };
|
||||
export type EventCategoryWithUsage = EventCategory & { eventCount: number };
|
||||
|
||||
export type CategoryError =
|
||||
| "INVALID_NAME"
|
||||
| "INVALID_COLOR"
|
||||
| "DUPLICATE_NAME"
|
||||
| "CATEGORY_IN_USE"
|
||||
| "CATEGORY_NOT_FOUND";
|
||||
|
||||
export class CategoryServiceError extends Error {
|
||||
readonly name = "CategoryServiceError";
|
||||
|
||||
constructor(readonly code: CategoryError) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export type CategoryRepository = {
|
||||
list(): Promise<EventCategoryWithUsage[]>;
|
||||
insert(input: { name: string; color: CategoryColor; adminUserId: string }): Promise<EventCategory>;
|
||||
get(id: string): Promise<EventCategoryWithUsage | null>;
|
||||
delete(id: string): Promise<void>;
|
||||
};
|
||||
|
||||
// Drizzle wraps driver errors; the Postgres code may sit on the cause.
|
||||
function postgresCode(error: unknown): unknown {
|
||||
if (typeof error !== "object" || error === null) return undefined;
|
||||
const direct = (error as { code?: unknown }).code;
|
||||
if (direct) return direct;
|
||||
return postgresCode((error as { cause?: unknown }).cause);
|
||||
}
|
||||
|
||||
export function createCategoryService({
|
||||
repository,
|
||||
audit,
|
||||
}: {
|
||||
repository: CategoryRepository;
|
||||
audit: { writeAudit: typeof writeAudit };
|
||||
}) {
|
||||
return {
|
||||
listCategories(): Promise<EventCategoryWithUsage[]> {
|
||||
return repository.list();
|
||||
},
|
||||
|
||||
async createCategory(input: { name: string; color: string; adminUserId: string }): Promise<EventCategory> {
|
||||
const name = input.name.trim();
|
||||
if (name.length === 0 || name.length > CATEGORY_NAME_MAX_LENGTH) {
|
||||
throw new CategoryServiceError("INVALID_NAME");
|
||||
}
|
||||
if (!isCategoryColor(input.color)) {
|
||||
throw new CategoryServiceError("INVALID_COLOR");
|
||||
}
|
||||
let created: EventCategory;
|
||||
try {
|
||||
created = await repository.insert({ name, color: input.color, adminUserId: input.adminUserId });
|
||||
} catch (error) {
|
||||
if (postgresCode(error) === "23505") throw new CategoryServiceError("DUPLICATE_NAME");
|
||||
throw error;
|
||||
}
|
||||
await audit.writeAudit({
|
||||
type: "event_category_created",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "event_category",
|
||||
entityId: created.id,
|
||||
metadata: { name: created.name, color: created.color },
|
||||
});
|
||||
return created;
|
||||
},
|
||||
|
||||
async deleteCategory(input: { id: string; adminUserId: string }): Promise<void> {
|
||||
const category = await repository.get(input.id);
|
||||
if (!category) throw new CategoryServiceError("CATEGORY_NOT_FOUND");
|
||||
if (category.eventCount > 0) throw new CategoryServiceError("CATEGORY_IN_USE");
|
||||
try {
|
||||
await repository.delete(input.id);
|
||||
} catch (error) {
|
||||
// A concurrent event creation can still hit the FK.
|
||||
if (postgresCode(error) === "23503") throw new CategoryServiceError("CATEGORY_IN_USE");
|
||||
throw error;
|
||||
}
|
||||
await audit.writeAudit({
|
||||
type: "event_category_deleted",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "event_category",
|
||||
entityId: category.id,
|
||||
metadata: { name: category.name },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createCategoryRepository(database: NodePgDatabase<typeof schema>): CategoryRepository {
|
||||
const columns = {
|
||||
id: eventCategories.id,
|
||||
name: eventCategories.name,
|
||||
color: eventCategories.color,
|
||||
eventCount: count(calendarEvents.id),
|
||||
};
|
||||
const withUsage = () =>
|
||||
database
|
||||
.select(columns)
|
||||
.from(eventCategories)
|
||||
.leftJoin(calendarEvents, eq(calendarEvents.categoryId, eventCategories.id))
|
||||
.groupBy(eventCategories.id);
|
||||
const cast = (row: { id: string; name: string; color: string; eventCount: number }) => ({
|
||||
...row,
|
||||
color: row.color as CategoryColor,
|
||||
});
|
||||
|
||||
return {
|
||||
async list() {
|
||||
const rows = await withUsage().orderBy(asc(eventCategories.name));
|
||||
return rows.map(cast);
|
||||
},
|
||||
async insert(input) {
|
||||
const [row] = await database
|
||||
.insert(eventCategories)
|
||||
.values({ name: input.name, color: input.color, createdByUserId: input.adminUserId })
|
||||
.returning({ id: eventCategories.id, name: eventCategories.name, color: eventCategories.color });
|
||||
return { ...row, color: row.color as CategoryColor };
|
||||
},
|
||||
async get(id) {
|
||||
const [row] = await withUsage().where(eq(eventCategories.id, id)).limit(1);
|
||||
return row ? cast(row) : null;
|
||||
},
|
||||
async delete(id) {
|
||||
await database.delete(eventCategories).where(eq(eventCategories.id, id));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const categoryService = createCategoryService({
|
||||
repository: createCategoryRepository(db),
|
||||
audit: { writeAudit },
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
// Client-safe: the colors Sakani's MonthCalendar supports, with the same CSS
|
||||
// variables Sakani paints its chips with, so legend dots match in both themes.
|
||||
export const CATEGORY_COLORS = ["blue", "green", "orange", "purple", "teal", "gold", "red", "neutral"] as const;
|
||||
export type CategoryColor = (typeof CATEGORY_COLORS)[number];
|
||||
|
||||
export const CATEGORY_COLOR_LABELS: Record<CategoryColor, string> = {
|
||||
blue: "Blau",
|
||||
green: "Grün",
|
||||
orange: "Orange",
|
||||
purple: "Lila",
|
||||
teal: "Türkis",
|
||||
gold: "Gold",
|
||||
red: "Rot",
|
||||
neutral: "Grau",
|
||||
};
|
||||
|
||||
export const CATEGORY_COLOR_VARS: Record<CategoryColor, string> = {
|
||||
blue: "var(--color-chart-2)",
|
||||
green: "var(--color-chart-6)",
|
||||
orange: "var(--color-chart-1)",
|
||||
purple: "var(--color-chart-4)",
|
||||
teal: "var(--color-chart-3)",
|
||||
gold: "var(--color-chart-5)",
|
||||
red: "var(--color-danger-solid)",
|
||||
neutral: "var(--color-fg-muted)",
|
||||
};
|
||||
|
||||
export function isCategoryColor(value: unknown): value is CategoryColor {
|
||||
return typeof value === "string" && (CATEGORY_COLORS as readonly string[]).includes(value);
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
createCalendarService,
|
||||
type CalendarRepository,
|
||||
type CalendarEvent,
|
||||
type EventResponseStatus,
|
||||
eventAccessState,
|
||||
matchesAutoRule,
|
||||
} from "./service";
|
||||
|
||||
const editorialUuid = "1111111a-1111-4111-8111-11111111111a";
|
||||
@@ -30,20 +31,27 @@ function event(overrides: Partial<CalendarEvent> = {}): CalendarEvent {
|
||||
title: "Hamburger SV - VfL Wolfsburg",
|
||||
eventDate: "2026-09-12",
|
||||
immichAlbumId: null,
|
||||
category: null,
|
||||
createdAt: new Date("2026-09-01T08:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type Reservation = { eventId: string; editorialId: string; grantedAt: Date | null };
|
||||
|
||||
function setup(options: {
|
||||
events?: CalendarEvent[];
|
||||
albums?: ImmichAlbumSummary[] | null;
|
||||
grantedAlbumIds?: string[];
|
||||
responses?: Array<{ eventId: string; status: EventResponseStatus }>;
|
||||
grantSources?: Array<{ immichAlbumId: string; source: string }>;
|
||||
reservations?: Reservation[];
|
||||
keywords?: string[];
|
||||
rateLimitAllowed?: boolean;
|
||||
grantError?: Error;
|
||||
} = {}) {
|
||||
const events = [...(options.events ?? [event()])];
|
||||
const responses = [...(options.responses ?? [])];
|
||||
const reservations = [...(options.reservations ?? [])];
|
||||
const find = (input: { eventId: string; editorialId: string }) =>
|
||||
reservations.find((row) => row.eventId === input.eventId && row.editorialId === input.editorialId);
|
||||
const repository: CalendarRepository = {
|
||||
async insertEvent(input) {
|
||||
const created = event({
|
||||
@@ -65,25 +73,35 @@ function setup(options: {
|
||||
const index = events.findIndex((candidate) => candidate.id === id);
|
||||
if (index === -1) return null;
|
||||
const [deleted] = events.splice(index, 1);
|
||||
for (let i = reservations.length - 1; i >= 0; i--) if (reservations[i].eventId === id) reservations.splice(i, 1);
|
||||
return deleted;
|
||||
},
|
||||
async upsertResponse(input) {
|
||||
const existing = responses.find((response) => response.eventId === input.eventId);
|
||||
if (existing) {
|
||||
existing.status = input.status;
|
||||
} else {
|
||||
responses.push({ eventId: input.eventId, status: input.status });
|
||||
}
|
||||
async insertReservation(input) {
|
||||
if (!find(input)) reservations.push({ ...input, grantedAt: null });
|
||||
},
|
||||
async listResponsesForEditorial() {
|
||||
return responses;
|
||||
async markReservationGranted(input) {
|
||||
find(input)!.grantedAt = new Date();
|
||||
},
|
||||
async listAllResponses() {
|
||||
return responses.map((response) => ({
|
||||
...response,
|
||||
editorialId: editorialUuid,
|
||||
editorialName: "Kicker Daily",
|
||||
}));
|
||||
async deletePendingReservation(input) {
|
||||
const row = find(input);
|
||||
if (!row || row.grantedAt) return false;
|
||||
reservations.splice(reservations.indexOf(row), 1);
|
||||
return true;
|
||||
},
|
||||
async listReservationsForEditorial(editorialId) {
|
||||
return reservations.filter((row) => row.editorialId === editorialId);
|
||||
},
|
||||
async listAllReservations() {
|
||||
return reservations.map((row) => ({ ...row, editorialName: "Kicker Daily" }));
|
||||
},
|
||||
async listPendingReservations() {
|
||||
return reservations.filter((row) => row.grantedAt === null).map(({ eventId, editorialId }) => ({ eventId, editorialId }));
|
||||
},
|
||||
async listGrantSources() {
|
||||
return options.grantSources ?? [];
|
||||
},
|
||||
async listAutoRuleKeywords() {
|
||||
return options.keywords ?? [];
|
||||
},
|
||||
};
|
||||
|
||||
@@ -94,8 +112,7 @@ function setup(options: {
|
||||
}),
|
||||
};
|
||||
const grants = {
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue(options.grantedAlbumIds ?? []),
|
||||
grantAlbum: vi.fn().mockResolvedValue(undefined),
|
||||
grantAlbum: options.grantError ? vi.fn().mockRejectedValue(options.grantError) : vi.fn().mockResolvedValue(undefined),
|
||||
revokeSelfServiceGrantsForAlbum: vi.fn().mockResolvedValue(1),
|
||||
};
|
||||
const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) };
|
||||
@@ -112,7 +129,7 @@ function setup(options: {
|
||||
audit,
|
||||
consumeRateLimit,
|
||||
events,
|
||||
responses,
|
||||
reservations,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,83 +155,6 @@ test("createEvent rejects an explicit album that does not exist in Immich", asyn
|
||||
).rejects.toMatchObject({ code: "INVALID_ALBUM" });
|
||||
});
|
||||
|
||||
test("selfGrantAlbum grants only the album linked to the event, as self_service", async () => {
|
||||
const { service, grants, audit } = setup();
|
||||
const album = await service.selfGrantAlbum({
|
||||
eventId: eventUuid,
|
||||
editorialId: editorialUuid,
|
||||
actorUserId: userUuid,
|
||||
});
|
||||
expect(album).toEqual({ id: albumUuid, albumName: matchAlbum.albumName });
|
||||
expect(grants.grantAlbum).toHaveBeenCalledWith({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: null,
|
||||
source: "self_service",
|
||||
});
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: "album_self_granted", actorType: "editorial" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("selfGrantAlbum refuses events without a linked album", async () => {
|
||||
const { service, grants } = setup({ albums: [] });
|
||||
await expect(
|
||||
service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "EVENT_ALBUM_UNAVAILABLE" });
|
||||
expect(grants.grantAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("selfGrantAlbum refuses unknown events", async () => {
|
||||
const { service } = setup();
|
||||
await expect(
|
||||
service.selfGrantAlbum({
|
||||
eventId: "99999999-9999-4999-8999-999999999999",
|
||||
editorialId: editorialUuid,
|
||||
actorUserId: userUuid,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "EVENT_NOT_FOUND" });
|
||||
});
|
||||
|
||||
test("selfGrantAlbum surfaces rate limits and Immich outages", async () => {
|
||||
const limited = setup({ rateLimitAllowed: false });
|
||||
await expect(
|
||||
limited.service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "RATE_LIMITED", retryAfterSeconds: 42 });
|
||||
|
||||
const down = setup({ albums: null });
|
||||
await expect(
|
||||
down.service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
|
||||
});
|
||||
|
||||
test("selfGrantAlbum maps a vanished album to EVENT_ALBUM_UNAVAILABLE", async () => {
|
||||
const { service, grants } = setup();
|
||||
grants.grantAlbum.mockRejectedValue(new AlbumGrantError("ALBUM_NOT_ASSIGNABLE"));
|
||||
await expect(
|
||||
service.selfGrantAlbum({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid }),
|
||||
).rejects.toMatchObject({ code: "EVENT_ALBUM_UNAVAILABLE" });
|
||||
});
|
||||
|
||||
test("respond validates the status and upserts one response per event", async () => {
|
||||
const { service, responses, audit } = setup();
|
||||
await expect(
|
||||
service.respond({
|
||||
eventId: eventUuid,
|
||||
editorialId: editorialUuid,
|
||||
actorUserId: userUuid,
|
||||
status: "maybe" as EventResponseStatus,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "INVALID_STATUS" });
|
||||
|
||||
await service.respond({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid, status: "attending" });
|
||||
await service.respond({ eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid, status: "not_attending" });
|
||||
expect(responses).toEqual([{ eventId: eventUuid, status: "not_attending" }]);
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: "event_response_recorded", actorType: "editorial" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("deleteEvent revokes self-service grants on the linked album and removes the event", async () => {
|
||||
const { service, grants, events, audit } = setup();
|
||||
await service.deleteEvent({ id: eventUuid, adminUserId: userUuid });
|
||||
@@ -232,12 +172,112 @@ test("deleteEvent reports unknown events", async () => {
|
||||
).rejects.toMatchObject({ code: "EVENT_NOT_FOUND" });
|
||||
});
|
||||
|
||||
test("listEditorialEvents marks granted albums, own responses and the past window", async () => {
|
||||
const reserveInput = { eventId: eventUuid, editorialId: editorialUuid, actorUserId: userUuid };
|
||||
|
||||
test("reserve grants the linked album at once as self_service", async () => {
|
||||
const { service, grants, reservations, audit } = setup();
|
||||
const result = await service.reserve(reserveInput);
|
||||
expect(result).toEqual({ status: "granted", album: { id: albumUuid, albumName: matchAlbum.albumName } });
|
||||
expect(grants.grantAlbum).toHaveBeenCalledWith({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: null,
|
||||
source: "self_service",
|
||||
});
|
||||
expect(reservations[0].grantedAt).toBeInstanceOf(Date);
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith(expect.objectContaining({ type: "album_self_granted" }));
|
||||
});
|
||||
|
||||
test("reserve without an album (or with Immich down) keeps a pending reservation", async () => {
|
||||
for (const albums of [[], null]) {
|
||||
const { service, grants, reservations, audit } = setup({ albums });
|
||||
expect(await service.reserve(reserveInput)).toEqual({ status: "reserved", album: null });
|
||||
expect(grants.grantAlbum).not.toHaveBeenCalled();
|
||||
expect(reservations).toEqual([{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: null }]);
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith(expect.objectContaining({ type: "event_reserved" }));
|
||||
}
|
||||
});
|
||||
|
||||
test("reserve keeps the reservation pending when the album is not assignable", async () => {
|
||||
const { service, reservations } = setup({ grantError: new AlbumGrantError("ALBUM_NOT_ASSIGNABLE") });
|
||||
expect((await service.reserve(reserveInput)).status).toBe("reserved");
|
||||
expect(reservations[0].grantedAt).toBeNull();
|
||||
});
|
||||
|
||||
test("reserve refuses unknown events and surfaces rate limits", async () => {
|
||||
const { service } = setup();
|
||||
await expect(service.reserve({ ...reserveInput, eventId: "99999999-9999-4999-8999-999999999999" })).rejects.toMatchObject({
|
||||
code: "EVENT_NOT_FOUND",
|
||||
});
|
||||
const limited = setup({ rateLimitAllowed: false });
|
||||
await expect(limited.service.reserve(reserveInput)).rejects.toMatchObject({ code: "RATE_LIMITED", retryAfterSeconds: 42 });
|
||||
});
|
||||
|
||||
test("unreserve removes only pending reservations", async () => {
|
||||
const pending = setup({ reservations: [{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: null }] });
|
||||
await pending.service.unreserve(reserveInput);
|
||||
expect(pending.reservations).toHaveLength(0);
|
||||
|
||||
const granted = setup({ reservations: [{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: new Date() }] });
|
||||
await expect(granted.service.unreserve(reserveInput)).rejects.toMatchObject({ code: "RESERVATION_NOT_FOUND" });
|
||||
expect(granted.reservations).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("resolvePendingReservations grants reservations whose album appeared and skips the rest", async () => {
|
||||
const otherEvent = event({ id: "7777777a-7777-4777-8777-77777777777a", title: "Volleyball Finale" });
|
||||
const { service, grants, reservations } = setup({
|
||||
events: [event(), otherEvent],
|
||||
reservations: [
|
||||
{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: null },
|
||||
{ eventId: otherEvent.id, editorialId: editorialUuid, grantedAt: null },
|
||||
],
|
||||
});
|
||||
expect(await service.resolvePendingReservations()).toEqual({ granted: 1 });
|
||||
expect(grants.grantAlbum).toHaveBeenCalledTimes(1);
|
||||
expect(reservations.find((row) => row.eventId === eventUuid)!.grantedAt).toBeInstanceOf(Date);
|
||||
expect(reservations.find((row) => row.eventId === otherEvent.id)!.grantedAt).toBeNull();
|
||||
});
|
||||
|
||||
test("resolvePendingReservations does nothing while Immich is down", async () => {
|
||||
const { service, grants } = setup({
|
||||
albums: null,
|
||||
reservations: [{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: null }],
|
||||
});
|
||||
expect(await service.resolvePendingReservations()).toEqual({ granted: 0 });
|
||||
expect(grants.grantAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("deleteEvent also removes reservations", async () => {
|
||||
const { service, reservations } = setup({
|
||||
reservations: [{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: new Date() }],
|
||||
});
|
||||
await service.deleteEvent({ id: eventUuid, adminUserId: userUuid });
|
||||
expect(reservations).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("eventAccessState checks granted, auto rule, reserved, available in that order", () => {
|
||||
expect(eventAccessState({ grantSource: "auto_rule", autoRuleMatch: true, reserved: true })).toBe("auto_granted");
|
||||
expect(eventAccessState({ grantSource: "self_service", autoRuleMatch: true, reserved: true })).toBe("granted");
|
||||
expect(eventAccessState({ grantSource: "admin", autoRuleMatch: false, reserved: false })).toBe("granted");
|
||||
expect(eventAccessState({ grantSource: null, autoRuleMatch: true, reserved: true })).toBe("auto_rule");
|
||||
expect(eventAccessState({ grantSource: null, autoRuleMatch: false, reserved: true })).toBe("reserved");
|
||||
expect(eventAccessState({ grantSource: null, autoRuleMatch: false, reserved: false })).toBe("available");
|
||||
});
|
||||
|
||||
test("matchesAutoRule matches keywords inside title or album name, ignoring case and blanks", () => {
|
||||
expect(matchesAutoRule(["hsv"], ["Hamburger SV - VfL Wolfsburg", null])).toBe(false);
|
||||
expect(matchesAutoRule(["Hamburger SV"], ["hamburger sv - VfL Wolfsburg"])).toBe(true);
|
||||
expect(matchesAutoRule(["Wolfsburg"], [null, "Hamburger SV - VfL Wolfsburg | 12.09.2026"])).toBe(true);
|
||||
expect(matchesAutoRule([" "], ["anything"])).toBe(false);
|
||||
});
|
||||
|
||||
test("listEditorialEvents derives access per event and keeps the past window", async () => {
|
||||
const oldEvent = event({ id: "7777777a-7777-4777-8777-77777777777a", eventDate: "2026-01-01" });
|
||||
const futureEvent = event({ id: "8888888b-8888-4888-8888-88888888888b", title: "Volleyball Finale", eventDate: "2026-09-20" });
|
||||
const { service } = setup({
|
||||
events: [event(), oldEvent],
|
||||
grantedAlbumIds: [albumUuid],
|
||||
responses: [{ eventId: eventUuid, status: "attending" }],
|
||||
events: [event(), oldEvent, futureEvent],
|
||||
grantSources: [{ immichAlbumId: albumUuid, source: "auto_rule" }],
|
||||
reservations: [{ eventId: futureEvent.id, editorialId: editorialUuid, grantedAt: null }],
|
||||
});
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(
|
||||
editorialUuid,
|
||||
@@ -245,22 +285,27 @@ test("listEditorialEvents marks granted albums, own responses and the past windo
|
||||
);
|
||||
expect(immichUnavailable).toBe(false);
|
||||
// The January event is outside the 30-day past window.
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
id: eventUuid,
|
||||
isGranted: true,
|
||||
response: "attending",
|
||||
album: { id: albumUuid, albumName: matchAlbum.albumName },
|
||||
});
|
||||
expect(events.map((row) => [row.id, row.access])).toEqual([
|
||||
[eventUuid, "auto_granted"],
|
||||
[futureEvent.id, "reserved"],
|
||||
]);
|
||||
expect(events[0].album).toEqual({ id: albumUuid, albumName: matchAlbum.albumName });
|
||||
});
|
||||
|
||||
test("listEditorialEvents degrades gracefully when Immich is down", async () => {
|
||||
const { service } = setup({ albums: null });
|
||||
const { service } = setup({ albums: null, keywords: ["Wolfsburg"] });
|
||||
const { events, immichUnavailable } = await service.listEditorialEvents(
|
||||
editorialUuid,
|
||||
new Date("2026-09-10T08:00:00.000Z"),
|
||||
);
|
||||
expect(immichUnavailable).toBe(true);
|
||||
expect(events[0].album).toBeNull();
|
||||
expect(events[0].isGranted).toBe(false);
|
||||
// The keyword still matches the title, so the auto rule will deliver the album.
|
||||
expect(events[0].access).toBe("auto_rule");
|
||||
});
|
||||
|
||||
test("listAdminEvents attaches reservations per event", async () => {
|
||||
const { service } = setup({ reservations: [{ eventId: eventUuid, editorialId: editorialUuid, grantedAt: null }] });
|
||||
const { events } = await service.listAdminEvents();
|
||||
expect(events[0].reservations).toEqual([{ editorialId: editorialUuid, editorialName: "Kicker Daily", grantedAt: null }]);
|
||||
});
|
||||
+296
-160
@@ -1,10 +1,17 @@
|
||||
import "server-only";
|
||||
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { and, asc, eq, isNull } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { calendarEvents, editorialAccounts, eventResponses } from "@/db/schema";
|
||||
import {
|
||||
albumAutoRules,
|
||||
albumGrants,
|
||||
calendarEvents,
|
||||
editorialAccounts,
|
||||
eventCategories,
|
||||
eventReservations,
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { albumGrantService, AlbumGrantError } from "@/modules/albums/grants";
|
||||
import {
|
||||
@@ -22,46 +29,49 @@ import {
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
|
||||
import type { EventCategory } from "./categories";
|
||||
import type { CategoryColor } from "./colors";
|
||||
import { matchEventAlbum } from "./event-albums";
|
||||
|
||||
export const CALENDAR_EVENT_MAX_TITLE_LENGTH = 200;
|
||||
/** Past events stay visible (and self-serviceable) for this many days. */
|
||||
/** Past events stay visible (and reservable) for this many days. */
|
||||
export const CALENDAR_PAST_DAYS = 30;
|
||||
|
||||
export type EventResponseStatus = "attending" | "not_attending";
|
||||
|
||||
export type CalendarEvent = {
|
||||
id: string;
|
||||
title: string;
|
||||
eventDate: string;
|
||||
immichAlbumId: string | null;
|
||||
category: EventCategory | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type LinkedAlbum = { id: string; albumName: string };
|
||||
|
||||
/**
|
||||
* What an editorial sees for one event, checked in this order:
|
||||
* granted (admin/self-service), auto_granted (via auto rule), auto_rule (a
|
||||
* keyword matches, the album will arrive by itself), reserved, available.
|
||||
*/
|
||||
export type EventAccessState = "granted" | "auto_granted" | "auto_rule" | "reserved" | "available";
|
||||
|
||||
export type EditorialCalendarEvent = CalendarEvent & {
|
||||
album: LinkedAlbum | null;
|
||||
isGranted: boolean;
|
||||
response: EventResponseStatus | null;
|
||||
access: EventAccessState;
|
||||
};
|
||||
|
||||
export type AdminCalendarEvent = CalendarEvent & {
|
||||
album: LinkedAlbum | null;
|
||||
responses: Array<{
|
||||
editorialId: string;
|
||||
editorialName: string;
|
||||
status: EventResponseStatus;
|
||||
}>;
|
||||
reservations: Array<{ editorialId: string; editorialName: string; grantedAt: Date | null }>;
|
||||
};
|
||||
|
||||
export type CalendarError =
|
||||
| "INVALID_TITLE"
|
||||
| "INVALID_EVENT_DATE"
|
||||
| "INVALID_ALBUM"
|
||||
| "INVALID_STATUS"
|
||||
| "INVALID_CATEGORY"
|
||||
| "EVENT_NOT_FOUND"
|
||||
| "EVENT_ALBUM_UNAVAILABLE"
|
||||
| "RESERVATION_NOT_FOUND"
|
||||
| "IMMICH_UNAVAILABLE"
|
||||
| "RATE_LIMITED";
|
||||
|
||||
@@ -76,40 +86,69 @@ export class CalendarServiceError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function eventAccessState(input: {
|
||||
grantSource: string | null;
|
||||
autoRuleMatch: boolean;
|
||||
reserved: boolean;
|
||||
}): EventAccessState {
|
||||
if (input.grantSource === "auto_rule") return "auto_granted";
|
||||
if (input.grantSource) return "granted";
|
||||
if (input.autoRuleMatch) return "auto_rule";
|
||||
if (input.reserved) return "reserved";
|
||||
return "available";
|
||||
}
|
||||
|
||||
/** Same rule as the auto-rule job: a keyword contained in the name, ignoring case. */
|
||||
export function matchesAutoRule(keywords: string[], names: Array<string | null | undefined>): boolean {
|
||||
const lowered = names.filter((name): name is string => Boolean(name)).map((name) => name.toLowerCase());
|
||||
return keywords.some((keyword) => {
|
||||
const needle = keyword.trim().toLowerCase();
|
||||
return needle.length > 0 && lowered.some((name) => name.includes(needle));
|
||||
});
|
||||
}
|
||||
|
||||
export type CalendarRepository = {
|
||||
insertEvent(input: {
|
||||
title: string;
|
||||
eventDate: string;
|
||||
immichAlbumId: string | null;
|
||||
categoryId: string | null;
|
||||
adminUserId: string;
|
||||
}): Promise<CalendarEvent>;
|
||||
getEvent(id: string): Promise<CalendarEvent | null>;
|
||||
listEvents(): Promise<CalendarEvent[]>;
|
||||
deleteEvent(id: string): Promise<CalendarEvent | null>;
|
||||
upsertResponse(input: {
|
||||
eventId: string;
|
||||
editorialId: string;
|
||||
status: EventResponseStatus;
|
||||
}): Promise<void>;
|
||||
listResponsesForEditorial(editorialId: string): Promise<Array<{ eventId: string; status: EventResponseStatus }>>;
|
||||
listAllResponses(): Promise<
|
||||
Array<{ eventId: string; editorialId: string; editorialName: string; status: EventResponseStatus }>
|
||||
insertReservation(input: { eventId: string; editorialId: string }): Promise<void>;
|
||||
markReservationGranted(input: { eventId: string; editorialId: string }): Promise<void>;
|
||||
/** Deletes a reservation that has not been granted yet; false if none. */
|
||||
deletePendingReservation(input: { eventId: string; editorialId: string }): Promise<boolean>;
|
||||
listReservationsForEditorial(editorialId: string): Promise<Array<{ eventId: string; grantedAt: Date | null }>>;
|
||||
listAllReservations(): Promise<
|
||||
Array<{ eventId: string; editorialId: string; editorialName: string; grantedAt: Date | null }>
|
||||
>;
|
||||
listPendingReservations(): Promise<Array<{ eventId: string; editorialId: string }>>;
|
||||
listGrantSources(editorialId: string): Promise<Array<{ immichAlbumId: string; source: string }>>;
|
||||
listAutoRuleKeywords(editorialId: string): Promise<string[]>;
|
||||
};
|
||||
|
||||
export type CalendarDependencies = {
|
||||
repository: CalendarRepository;
|
||||
immich: Pick<ImmichClient, "listAlbums">;
|
||||
grants: Pick<
|
||||
typeof albumGrantService,
|
||||
"getGrantedAlbumIds" | "grantAlbum" | "revokeSelfServiceGrantsForAlbum"
|
||||
>;
|
||||
grants: Pick<typeof albumGrantService, "grantAlbum" | "revokeSelfServiceGrantsForAlbum">;
|
||||
audit: { writeAudit: typeof writeAudit };
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
// Drizzle wraps driver errors; the Postgres code may sit on the cause.
|
||||
function postgresCode(error: unknown): unknown {
|
||||
if (typeof error !== "object" || error === null) return undefined;
|
||||
const direct = (error as { code?: unknown }).code;
|
||||
if (direct) return direct;
|
||||
return postgresCode((error as { cause?: unknown }).cause);
|
||||
}
|
||||
|
||||
export function createCalendarService({
|
||||
repository,
|
||||
immich,
|
||||
@@ -125,11 +164,28 @@ export function createCalendarService({
|
||||
}
|
||||
}
|
||||
|
||||
/** Grants the event album as self_service; false when it cannot be granted right now. */
|
||||
async function grantEventAlbum(editorialId: string, album: LinkedAlbum): Promise<boolean> {
|
||||
try {
|
||||
await grants.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId: null, source: "self_service" });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof AlbumGrantError &&
|
||||
(error.code === "ALBUM_NOT_ASSIGNABLE" || error.code === "IMMICH_UNAVAILABLE")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async createEvent(input: {
|
||||
title: string;
|
||||
eventDate: string;
|
||||
immichAlbumId?: string | null;
|
||||
categoryId?: string | null;
|
||||
adminUserId: string;
|
||||
}): Promise<CalendarEvent> {
|
||||
const title = input.title.trim();
|
||||
@@ -139,6 +195,10 @@ export function createCalendarService({
|
||||
if (!isValidIsoDate(input.eventDate)) {
|
||||
throw new CalendarServiceError("INVALID_EVENT_DATE");
|
||||
}
|
||||
const categoryId = input.categoryId ? input.categoryId : null;
|
||||
if (categoryId && !UUID_PATTERN.test(categoryId)) {
|
||||
throw new CalendarServiceError("INVALID_CATEGORY");
|
||||
}
|
||||
|
||||
let immichAlbumId: string | null = null;
|
||||
if (input.immichAlbumId) {
|
||||
@@ -158,12 +218,19 @@ export function createCalendarService({
|
||||
immichAlbumId = album.id;
|
||||
}
|
||||
|
||||
const created = await repository.insertEvent({
|
||||
title,
|
||||
eventDate: input.eventDate,
|
||||
immichAlbumId,
|
||||
adminUserId: input.adminUserId,
|
||||
});
|
||||
let created: CalendarEvent;
|
||||
try {
|
||||
created = await repository.insertEvent({
|
||||
title,
|
||||
eventDate: input.eventDate,
|
||||
immichAlbumId,
|
||||
categoryId,
|
||||
adminUserId: input.adminUserId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (postgresCode(error) === "23503") throw new CalendarServiceError("INVALID_CATEGORY");
|
||||
throw error;
|
||||
}
|
||||
|
||||
await audit.writeAudit({
|
||||
type: "calendar_event_created",
|
||||
@@ -171,7 +238,7 @@ export function createCalendarService({
|
||||
actorType: "admin",
|
||||
entityType: "calendar_event",
|
||||
entityId: created.id,
|
||||
metadata: { title: created.title, eventDate: created.eventDate, immichAlbumId },
|
||||
metadata: { title: created.title, eventDate: created.eventDate, immichAlbumId, categoryId },
|
||||
});
|
||||
|
||||
return created;
|
||||
@@ -218,14 +285,15 @@ export function createCalendarService({
|
||||
): Promise<{ events: EditorialCalendarEvent[]; immichUnavailable: boolean }> {
|
||||
const today = isoDateInBerlin(now);
|
||||
const minDate = shiftIsoDate(today, -CALENDAR_PAST_DAYS);
|
||||
const [allEvents, albums, grantedAlbumIds, responses] = await Promise.all([
|
||||
const [allEvents, albums, grantSources, reservations, keywords] = await Promise.all([
|
||||
repository.listEvents(),
|
||||
loadAlbumsOrNull(),
|
||||
grants.getGrantedAlbumIds(editorialId),
|
||||
repository.listResponsesForEditorial(editorialId),
|
||||
repository.listGrantSources(editorialId),
|
||||
repository.listReservationsForEditorial(editorialId),
|
||||
repository.listAutoRuleKeywords(editorialId),
|
||||
]);
|
||||
const granted = new Set(grantedAlbumIds.map((id) => id.toLowerCase()));
|
||||
const responseByEvent = new Map(responses.map((response) => [response.eventId, response.status]));
|
||||
const sourceByAlbum = new Map(grantSources.map((grant) => [grant.immichAlbumId.toLowerCase(), grant.source]));
|
||||
const pending = new Set(reservations.filter((row) => row.grantedAt === null).map((row) => row.eventId));
|
||||
|
||||
const events = allEvents
|
||||
.filter((event) => event.eventDate >= minDate)
|
||||
@@ -234,80 +302,51 @@ export function createCalendarService({
|
||||
return {
|
||||
...event,
|
||||
album: album ? { id: album.id, albumName: album.albumName } : null,
|
||||
isGranted: album ? granted.has(album.id.toLowerCase()) : false,
|
||||
response: responseByEvent.get(event.id) ?? null,
|
||||
access: eventAccessState({
|
||||
grantSource: album ? (sourceByAlbum.get(album.id.toLowerCase()) ?? null) : null,
|
||||
autoRuleMatch: matchesAutoRule(keywords, [event.title, album?.albumName]),
|
||||
reserved: pending.has(event.id),
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { events, immichUnavailable: albums === null };
|
||||
},
|
||||
|
||||
/** Admin overview: every event with its linked album and all RSVPs. */
|
||||
/** Admin overview: every event with its linked album and all reservations. */
|
||||
async listAdminEvents(): Promise<{ events: AdminCalendarEvent[]; immichUnavailable: boolean }> {
|
||||
const [allEvents, albums, responses] = await Promise.all([
|
||||
const [allEvents, albums, reservations] = await Promise.all([
|
||||
repository.listEvents(),
|
||||
loadAlbumsOrNull(),
|
||||
repository.listAllResponses(),
|
||||
repository.listAllReservations(),
|
||||
]);
|
||||
const responsesByEvent = new Map<string, AdminCalendarEvent["responses"]>();
|
||||
for (const response of responses) {
|
||||
const list = responsesByEvent.get(response.eventId) ?? [];
|
||||
list.push({
|
||||
editorialId: response.editorialId,
|
||||
editorialName: response.editorialName,
|
||||
status: response.status,
|
||||
});
|
||||
responsesByEvent.set(response.eventId, list);
|
||||
const byEvent = new Map<string, AdminCalendarEvent["reservations"]>();
|
||||
for (const row of reservations) {
|
||||
const list = byEvent.get(row.eventId) ?? [];
|
||||
list.push({ editorialId: row.editorialId, editorialName: row.editorialName, grantedAt: row.grantedAt });
|
||||
byEvent.set(row.eventId, list);
|
||||
}
|
||||
const events = allEvents.map((event) => {
|
||||
const album = albums ? matchEventAlbum(event, albums) : null;
|
||||
return {
|
||||
...event,
|
||||
album: album ? { id: album.id, albumName: album.albumName } : null,
|
||||
responses: responsesByEvent.get(event.id) ?? [],
|
||||
reservations: byEvent.get(event.id) ?? [],
|
||||
};
|
||||
});
|
||||
return { events, immichUnavailable: albums === null };
|
||||
},
|
||||
|
||||
async respond(input: {
|
||||
eventId: string;
|
||||
editorialId: string;
|
||||
actorUserId: string;
|
||||
status: EventResponseStatus;
|
||||
}): Promise<void> {
|
||||
if (input.status !== "attending" && input.status !== "not_attending") {
|
||||
throw new CalendarServiceError("INVALID_STATUS");
|
||||
}
|
||||
const event = await repository.getEvent(input.eventId);
|
||||
if (!event) {
|
||||
throw new CalendarServiceError("EVENT_NOT_FOUND");
|
||||
}
|
||||
await repository.upsertResponse({
|
||||
eventId: input.eventId,
|
||||
editorialId: input.editorialId,
|
||||
status: input.status,
|
||||
});
|
||||
await audit.writeAudit({
|
||||
type: "event_response_recorded",
|
||||
actorUserId: input.actorUserId,
|
||||
actorType: "editorial",
|
||||
entityType: "calendar_event",
|
||||
entityId: input.eventId,
|
||||
metadata: { status: input.status, title: event.title, eventDate: event.eventDate },
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Editorial self-service: grant access to the album linked to a calendar
|
||||
* event. The event (admin-created) is the trust boundary; only its linked
|
||||
* album is grantable, never arbitrary Immich albums. Idempotent: an
|
||||
* existing active grant is left as-is.
|
||||
* "Zu meinen Alben hinzufügen". The event (admin-created) is the trust
|
||||
* boundary: only its linked album is ever granted. With the album present
|
||||
* access is granted at once; otherwise the reservation waits for
|
||||
* resolvePendingReservations (auto-rule scheduler).
|
||||
*/
|
||||
async selfGrantAlbum(input: {
|
||||
async reserve(input: {
|
||||
eventId: string;
|
||||
editorialId: string;
|
||||
actorUserId: string;
|
||||
}): Promise<LinkedAlbum> {
|
||||
}): Promise<{ status: "granted" | "reserved"; album: LinkedAlbum | null }> {
|
||||
try {
|
||||
await enforceRateLimit(consume, `calendar-self-grant:${input.editorialId}`, calendarSelfGrantPolicy);
|
||||
} catch (error) {
|
||||
@@ -321,46 +360,85 @@ export function createCalendarService({
|
||||
if (!event) {
|
||||
throw new CalendarServiceError("EVENT_NOT_FOUND");
|
||||
}
|
||||
const albums = await loadAlbumsOrNull();
|
||||
if (!albums) {
|
||||
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
const album = matchEventAlbum(event, albums);
|
||||
if (!album) {
|
||||
throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE");
|
||||
}
|
||||
await repository.insertReservation({ eventId: event.id, editorialId: input.editorialId });
|
||||
|
||||
try {
|
||||
await grants.grantAlbum({
|
||||
editorialId: input.editorialId,
|
||||
immichAlbumId: album.id,
|
||||
adminUserId: null,
|
||||
source: "self_service",
|
||||
const albums = await loadAlbumsOrNull();
|
||||
const match = albums ? matchEventAlbum(event, albums) : null;
|
||||
const album = match ? { id: match.id, albumName: match.albumName } : null;
|
||||
if (album && (await grantEventAlbum(input.editorialId, album))) {
|
||||
await repository.markReservationGranted({ eventId: event.id, editorialId: input.editorialId });
|
||||
await audit.writeAudit({
|
||||
type: "album_self_granted",
|
||||
actorUserId: input.actorUserId,
|
||||
actorType: "editorial",
|
||||
entityType: "album_grant",
|
||||
entityId: album.id,
|
||||
metadata: { editorialId: input.editorialId, eventId: event.id, albumName: album.albumName },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumGrantError && error.code === "ALBUM_NOT_ASSIGNABLE") {
|
||||
throw new CalendarServiceError("EVENT_ALBUM_UNAVAILABLE");
|
||||
}
|
||||
if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") {
|
||||
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
throw error;
|
||||
return { status: "granted", album };
|
||||
}
|
||||
|
||||
await audit.writeAudit({
|
||||
type: "album_self_granted",
|
||||
type: "event_reserved",
|
||||
actorUserId: input.actorUserId,
|
||||
actorType: "editorial",
|
||||
entityType: "album_grant",
|
||||
entityId: album.id,
|
||||
metadata: {
|
||||
editorialId: input.editorialId,
|
||||
eventId: input.eventId,
|
||||
albumName: album.albumName,
|
||||
},
|
||||
entityType: "calendar_event",
|
||||
entityId: event.id,
|
||||
metadata: { editorialId: input.editorialId, title: event.title, eventDate: event.eventDate },
|
||||
});
|
||||
return { status: "reserved", album: null };
|
||||
},
|
||||
|
||||
return { id: album.id, albumName: album.albumName };
|
||||
async unreserve(input: { eventId: string; editorialId: string; actorUserId: string }): Promise<void> {
|
||||
const removed = await repository.deletePendingReservation({
|
||||
eventId: input.eventId,
|
||||
editorialId: input.editorialId,
|
||||
});
|
||||
if (!removed) {
|
||||
throw new CalendarServiceError("RESERVATION_NOT_FOUND");
|
||||
}
|
||||
await audit.writeAudit({
|
||||
type: "event_reservation_removed",
|
||||
actorUserId: input.actorUserId,
|
||||
actorType: "editorial",
|
||||
entityType: "calendar_event",
|
||||
entityId: input.eventId,
|
||||
metadata: { editorialId: input.editorialId },
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Runs on every auto-rule scheduler tick: grants pending reservations
|
||||
* whose event album has appeared. Never throws for a single reservation.
|
||||
*/
|
||||
async resolvePendingReservations(): Promise<{ granted: number }> {
|
||||
const pending = await repository.listPendingReservations();
|
||||
if (pending.length === 0) return { granted: 0 };
|
||||
const albums = await loadAlbumsOrNull();
|
||||
if (!albums) return { granted: 0 };
|
||||
const events = new Map((await repository.listEvents()).map((event) => [event.id, event]));
|
||||
|
||||
let granted = 0;
|
||||
for (const reservation of pending) {
|
||||
const event = events.get(reservation.eventId);
|
||||
const match = event ? matchEventAlbum(event, albums) : null;
|
||||
if (!event || !match) continue;
|
||||
try {
|
||||
if (!(await grantEventAlbum(reservation.editorialId, { id: match.id, albumName: match.albumName }))) continue;
|
||||
await repository.markReservationGranted(reservation);
|
||||
await audit.writeAudit({
|
||||
type: "album_self_granted",
|
||||
actorType: "system",
|
||||
entityType: "album_grant",
|
||||
entityId: match.id,
|
||||
metadata: { editorialId: reservation.editorialId, eventId: event.id, albumName: match.albumName, viaReservation: true },
|
||||
});
|
||||
granted += 1;
|
||||
} catch (error) {
|
||||
console.error("[calendar-reservations] grant failed:", error);
|
||||
}
|
||||
}
|
||||
return { granted };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -372,7 +450,33 @@ export function createCalendarRepository(database: NodePgDatabase<typeof schema>
|
||||
eventDate: calendarEvents.eventDate,
|
||||
immichAlbumId: calendarEvents.immichAlbumId,
|
||||
createdAt: calendarEvents.createdAt,
|
||||
categoryId: eventCategories.id,
|
||||
categoryName: eventCategories.name,
|
||||
categoryColor: eventCategories.color,
|
||||
};
|
||||
type Row = {
|
||||
id: string;
|
||||
title: string;
|
||||
eventDate: string;
|
||||
immichAlbumId: string | null;
|
||||
createdAt: Date;
|
||||
categoryId: string | null;
|
||||
categoryName: string | null;
|
||||
categoryColor: string | null;
|
||||
};
|
||||
const toEvent = ({ categoryId, categoryName, categoryColor, ...event }: Row): CalendarEvent => ({
|
||||
...event,
|
||||
category:
|
||||
categoryId && categoryName && categoryColor
|
||||
? { id: categoryId, name: categoryName, color: categoryColor as CategoryColor }
|
||||
: null,
|
||||
});
|
||||
const selectEvents = (executor: Pick<NodePgDatabase<typeof schema>, "select"> = database) =>
|
||||
executor
|
||||
.select(eventColumns)
|
||||
.from(calendarEvents)
|
||||
.leftJoin(eventCategories, eq(calendarEvents.categoryId, eventCategories.id));
|
||||
|
||||
return {
|
||||
async insertEvent(input) {
|
||||
const [row] = await database
|
||||
@@ -381,80 +485,112 @@ export function createCalendarRepository(database: NodePgDatabase<typeof schema>
|
||||
title: input.title,
|
||||
eventDate: input.eventDate,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
categoryId: input.categoryId,
|
||||
createdByUserId: input.adminUserId,
|
||||
})
|
||||
.returning(eventColumns);
|
||||
return row;
|
||||
.returning({ id: calendarEvents.id });
|
||||
const [created] = await selectEvents().where(eq(calendarEvents.id, row.id)).limit(1);
|
||||
return toEvent(created);
|
||||
},
|
||||
|
||||
async getEvent(id) {
|
||||
const [row] = await database
|
||||
.select(eventColumns)
|
||||
.from(calendarEvents)
|
||||
.where(eq(calendarEvents.id, id))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
const [row] = await selectEvents().where(eq(calendarEvents.id, id)).limit(1);
|
||||
return row ? toEvent(row) : null;
|
||||
},
|
||||
|
||||
async listEvents() {
|
||||
return database
|
||||
.select(eventColumns)
|
||||
.from(calendarEvents)
|
||||
.orderBy(asc(calendarEvents.eventDate), asc(calendarEvents.createdAt));
|
||||
const rows = await selectEvents().orderBy(asc(calendarEvents.eventDate), asc(calendarEvents.createdAt));
|
||||
return rows.map(toEvent);
|
||||
},
|
||||
|
||||
async deleteEvent(id) {
|
||||
return database.transaction(async (transaction) => {
|
||||
const [event] = await transaction
|
||||
.select(eventColumns)
|
||||
const [locked] = await transaction
|
||||
.select({ id: calendarEvents.id })
|
||||
.from(calendarEvents)
|
||||
.where(eq(calendarEvents.id, id))
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!event) {
|
||||
if (!locked) {
|
||||
return null;
|
||||
}
|
||||
await transaction.delete(eventResponses).where(eq(eventResponses.eventId, id));
|
||||
const [event] = await selectEvents(transaction).where(eq(calendarEvents.id, id)).limit(1);
|
||||
await transaction.delete(eventReservations).where(eq(eventReservations.eventId, id));
|
||||
await transaction.delete(calendarEvents).where(eq(calendarEvents.id, id));
|
||||
return event;
|
||||
return toEvent(event);
|
||||
});
|
||||
},
|
||||
|
||||
async upsertResponse(input) {
|
||||
async insertReservation(input) {
|
||||
await database
|
||||
.insert(eventResponses)
|
||||
.values({
|
||||
eventId: input.eventId,
|
||||
editorialAccountId: input.editorialId,
|
||||
status: input.status,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [eventResponses.eventId, eventResponses.editorialAccountId],
|
||||
set: { status: input.status, updatedAt: new Date() },
|
||||
});
|
||||
.insert(eventReservations)
|
||||
.values({ eventId: input.eventId, editorialAccountId: input.editorialId })
|
||||
.onConflictDoNothing({ target: [eventReservations.eventId, eventReservations.editorialAccountId] });
|
||||
},
|
||||
|
||||
async listResponsesForEditorial(editorialId) {
|
||||
const rows = await database
|
||||
.select({ eventId: eventResponses.eventId, status: eventResponses.status })
|
||||
.from(eventResponses)
|
||||
.where(eq(eventResponses.editorialAccountId, editorialId));
|
||||
return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus }));
|
||||
async markReservationGranted(input) {
|
||||
await database
|
||||
.update(eventReservations)
|
||||
.set({ grantedAt: new Date() })
|
||||
.where(
|
||||
and(eq(eventReservations.eventId, input.eventId), eq(eventReservations.editorialAccountId, input.editorialId)),
|
||||
);
|
||||
},
|
||||
|
||||
async listAllResponses() {
|
||||
const rows = await database
|
||||
async deletePendingReservation(input) {
|
||||
const deleted = await database
|
||||
.delete(eventReservations)
|
||||
.where(
|
||||
and(
|
||||
eq(eventReservations.eventId, input.eventId),
|
||||
eq(eventReservations.editorialAccountId, input.editorialId),
|
||||
isNull(eventReservations.grantedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: eventReservations.id });
|
||||
return deleted.length > 0;
|
||||
},
|
||||
|
||||
async listReservationsForEditorial(editorialId) {
|
||||
return database
|
||||
.select({ eventId: eventReservations.eventId, grantedAt: eventReservations.grantedAt })
|
||||
.from(eventReservations)
|
||||
.where(eq(eventReservations.editorialAccountId, editorialId));
|
||||
},
|
||||
|
||||
async listAllReservations() {
|
||||
return database
|
||||
.select({
|
||||
eventId: eventResponses.eventId,
|
||||
eventId: eventReservations.eventId,
|
||||
editorialId: editorialAccounts.id,
|
||||
editorialName: editorialAccounts.name,
|
||||
status: eventResponses.status,
|
||||
grantedAt: eventReservations.grantedAt,
|
||||
})
|
||||
.from(eventResponses)
|
||||
.innerJoin(editorialAccounts, eq(eventResponses.editorialAccountId, editorialAccounts.id))
|
||||
.from(eventReservations)
|
||||
.innerJoin(editorialAccounts, eq(eventReservations.editorialAccountId, editorialAccounts.id))
|
||||
.orderBy(asc(editorialAccounts.name));
|
||||
return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus }));
|
||||
},
|
||||
|
||||
async listPendingReservations() {
|
||||
return database
|
||||
.select({ eventId: eventReservations.eventId, editorialId: eventReservations.editorialAccountId })
|
||||
.from(eventReservations)
|
||||
.where(isNull(eventReservations.grantedAt));
|
||||
},
|
||||
|
||||
async listGrantSources(editorialId) {
|
||||
return database
|
||||
.select({ immichAlbumId: albumGrants.immichAlbumId, source: albumGrants.source })
|
||||
.from(albumGrants)
|
||||
.where(and(eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt)));
|
||||
},
|
||||
|
||||
async listAutoRuleKeywords(editorialId) {
|
||||
const rows = await database
|
||||
.select({ keyword: albumAutoRules.keyword })
|
||||
.from(albumAutoRules)
|
||||
.where(eq(albumAutoRules.editorialAccountId, editorialId));
|
||||
return rows.map((row) => row.keyword);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, eq, gte, isNull, lt, sql } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { billingReports, editorialAccounts, usages } from "@/db/schema";
|
||||
import { quarterPeriod } from "@/modules/billing/period";
|
||||
|
||||
import { berlinQuarter, type DashboardCounts } from "./tasks";
|
||||
|
||||
export async function loadDashboardCounts(now: Date = new Date()): Promise<DashboardCounts> {
|
||||
const { year, quarter } = berlinQuarter(now);
|
||||
const period = quarterPeriod(year, quarter);
|
||||
const [[approvals], [withoutInvoice], [failedMails], [openRevenue]] = await Promise.all([
|
||||
db
|
||||
.select({ count: sql<number>`COUNT(*)::int` })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.status, "pending_approval")),
|
||||
db
|
||||
.select({ count: sql<number>`COUNT(*)::int` })
|
||||
.from(billingReports)
|
||||
.where(and(eq(billingReports.status, "final"), isNull(billingReports.invoicePdfSha256))),
|
||||
db
|
||||
.select({ count: sql<number>`COUNT(*)::int` })
|
||||
.from(billingReports)
|
||||
.where(and(eq(billingReports.status, "final"), eq(billingReports.invoiceEmailStatus, "failed"))),
|
||||
db
|
||||
.select({ total: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int` })
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
sql`${usages.billingStatus} in ('open', 'reopened')`,
|
||||
gte(usages.createdAt, period.fromUtc),
|
||||
lt(usages.createdAt, period.toUtcExclusive),
|
||||
),
|
||||
),
|
||||
]);
|
||||
return {
|
||||
pendingApprovals: approvals?.count ?? 0,
|
||||
reportsWithoutInvoice: withoutInvoice?.count ?? 0,
|
||||
failedInvoiceMails: failedMails?.count ?? 0,
|
||||
openQuarterRevenueCents: openRevenue?.total ?? 0,
|
||||
quarterLabel: `Q${quarter} ${year}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { berlinQuarter, dashboardTasks } from "./tasks";
|
||||
|
||||
const none = { pendingApprovals: 0, reportsWithoutInvoice: 0, failedInvoiceMails: 0, openQuarterRevenueCents: 0, quarterLabel: "Q4 2026" };
|
||||
|
||||
test("dashboardTasks is empty when nothing is pending", () => {
|
||||
expect(dashboardTasks(none)).toEqual([]);
|
||||
});
|
||||
|
||||
test("dashboardTasks lists pending items, failed mails first, with singular labels", () => {
|
||||
const tasks = dashboardTasks({ ...none, pendingApprovals: 1, reportsWithoutInvoice: 2, failedInvoiceMails: 1, openQuarterRevenueCents: 12_550 });
|
||||
expect(tasks.map((task) => task.id)).toEqual(["failed-mails", "approvals", "invoices", "open-revenue"]);
|
||||
expect(tasks[1].label).toBe("Registrierung wartet auf Freigabe");
|
||||
expect(tasks[2].label).toBe("Abrechnungen ohne Rechnungs-PDF");
|
||||
expect(tasks[3]).toMatchObject({ label: "Offener Umsatz Q4 2026", value: expect.stringContaining("125,50") });
|
||||
});
|
||||
|
||||
test("berlinQuarter uses Berlin local time at the year boundary", () => {
|
||||
// 31.12. 23:30 UTC is already 1 January in Berlin.
|
||||
expect(berlinQuarter(new Date("2026-12-31T23:30:00.000Z"))).toEqual({ year: 2027, quarter: 1 });
|
||||
expect(berlinQuarter(new Date("2026-11-30T12:00:00.000Z"))).toEqual({ year: 2026, quarter: 4 });
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
export type DashboardCounts = {
|
||||
pendingApprovals: number;
|
||||
reportsWithoutInvoice: number;
|
||||
failedInvoiceMails: number;
|
||||
openQuarterRevenueCents: number;
|
||||
quarterLabel: string;
|
||||
};
|
||||
|
||||
export type DashboardTask = { id: string; label: string; value: string; href: string; tone: "warning" | "danger" | "info" };
|
||||
|
||||
const euro = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
/** Open to-dos for the admin, most urgent first; empty when nothing is pending. */
|
||||
export function dashboardTasks(counts: DashboardCounts): DashboardTask[] {
|
||||
const tasks: DashboardTask[] = [];
|
||||
if (counts.failedInvoiceMails > 0) {
|
||||
tasks.push({
|
||||
id: "failed-mails",
|
||||
label: counts.failedInvoiceMails === 1 ? "Rechnungsmail fehlgeschlagen" : "Rechnungsmails fehlgeschlagen",
|
||||
value: String(counts.failedInvoiceMails),
|
||||
href: "/admin/abrechnungen",
|
||||
tone: "danger",
|
||||
});
|
||||
}
|
||||
if (counts.pendingApprovals > 0) {
|
||||
tasks.push({
|
||||
id: "approvals",
|
||||
label: counts.pendingApprovals === 1 ? "Registrierung wartet auf Freigabe" : "Registrierungen warten auf Freigabe",
|
||||
value: String(counts.pendingApprovals),
|
||||
href: "/admin/redaktionen",
|
||||
tone: "warning",
|
||||
});
|
||||
}
|
||||
if (counts.reportsWithoutInvoice > 0) {
|
||||
tasks.push({
|
||||
id: "invoices",
|
||||
label: counts.reportsWithoutInvoice === 1 ? "Abrechnung ohne Rechnungs-PDF" : "Abrechnungen ohne Rechnungs-PDF",
|
||||
value: String(counts.reportsWithoutInvoice),
|
||||
href: "/admin/abrechnungen",
|
||||
tone: "warning",
|
||||
});
|
||||
}
|
||||
if (counts.openQuarterRevenueCents > 0) {
|
||||
tasks.push({
|
||||
id: "open-revenue",
|
||||
label: `Offener Umsatz ${counts.quarterLabel}`,
|
||||
value: euro.format(counts.openQuarterRevenueCents / 100),
|
||||
href: "/admin/abrechnungen",
|
||||
tone: "info",
|
||||
});
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
/** Current quarter in Europe/Berlin, e.g. { year: 2026, quarter: 4 }. */
|
||||
export function berlinQuarter(now: Date): { year: number; quarter: number } {
|
||||
const parts = new Intl.DateTimeFormat("en-US", { timeZone: "Europe/Berlin", year: "numeric", month: "numeric" }).formatToParts(now);
|
||||
const year = Number(parts.find((part) => part.type === "year")?.value);
|
||||
const month = Number(parts.find((part) => part.type === "month")?.value);
|
||||
return { year, quarter: Math.floor((month - 1) / 3) + 1 };
|
||||
}
|
||||
Reference in new issue
Block a user