feat: v2.2 batch (calendar, self-service, sort, description, filename search, stats, collab, invoice) on pre-redesign base

This commit is contained in:
Leon Tonhäuser committed 2026-11-30 21:20:13 +01:00
1 parent 453bece72c
commit 7204dd6b60
108 files changed
+10400 -105

No files matched your search

@@ -17,6 +17,7 @@ const openPosition: BillingPosition = {
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
status: "open",
selectable: true,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
@@ -32,6 +33,7 @@ const billedPosition: BillingPosition = {
purpose: "Sportbericht",
reference: null,
priceCents: 1_500,
collab: false,
status: "billed",
selectable: false,
createdAt: new Date("2026-08-06T10:00:00.000Z"),
@@ -47,6 +49,7 @@ const reopenedPosition: BillingPosition = {
purpose: "Reopened",
reference: null,
priceCents: 1_500,
collab: false,
status: "reopened",
selectable: true,
createdAt: new Date("2026-08-07T10:00:00.000Z"),
@@ -162,6 +162,28 @@ export function BillingSelection({
}
}
async function handleToggleCollab(position: BillingPosition) {
setActionState({ loading: true, message: null, isError: false });
try {
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ collab: !position.collab }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
}
window.location.reload();
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Collab-Kennzeichnung fehlgeschlagen",
isError: true,
});
}
}
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
const quarterHref = quarter
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
@@ -228,7 +250,20 @@ export function BillingSelection({
<td>{position.albumName}</td>
<td>{position.purpose}</td>
<td>{position.reference ?? "—"}</td>
<td className="billing-price">{formatCents(position.priceCents)}</td>
<td className="billing-price">
{formatCents(position.priceCents)}
{position.collab && <span className="billing-collab-badge">Collab</span>}
{position.selectable && (
<button
type="button"
className="billing-collab-toggle"
onClick={() => handleToggleCollab(position)}
disabled={actionState.loading}
>
{position.collab ? "Collab entfernen" : "Als Collab markieren"}
</button>
)}
</td>
<td>
<span className="billing-status">
{STATUS_LABELS[position.status]}
@@ -334,13 +369,48 @@ export function BillingSelection({
</div>
{report.status === "final" && (
<>
<div className="billing-invoice-block">
<p className="billing-invoice-status">
Rechnung:{" "}
{report.invoiceEmailStatus === "sent" ? (
<>
versendet am{" "}
<time
dateTime={report.invoiceEmailSentAt?.toISOString()}
suppressHydrationWarning
>
{report.invoiceEmailSentAt?.toLocaleDateString("de-DE")}
</time>
</>
) : report.hasInvoicePdf ? (
"PDF hinterlegt, Versand fehlgeschlagen"
) : (
"noch keine PDF hinterlegt"
)}
</p>
<InvoiceUploadForm
reportId={report.id}
reportNumber={report.reportNumber}
hasInvoice={report.hasInvoicePdf}
emailFailed={report.hasInvoicePdf && report.invoiceEmailStatus === "failed"}
/>
{report.hasInvoicePdf && (
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}/invoice`}
className="billing-report-download"
download
>
Rechnungs-PDF herunterladen
</a>
)}
</div>
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
<a
<a
href={`/api/billing-reports/${encodeURIComponent(report.id)}`}
className="billing-report-download"
download
>
PDF herunterladen
Nutzungsnachweis herunterladen
</a>
</>
)}
@@ -403,6 +473,114 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
);
}
type InvoiceUploadFormProps = {
reportId: string;
reportNumber: number;
hasInvoice: boolean;
emailFailed: boolean;
};
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleUpload(event: React.FormEvent) {
event.preventDefault();
if (!file || loading) return;
setLoading(true);
setError(null);
try {
const formData = new FormData();
formData.set("invoice", file);
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/invoice`, {
method: "POST",
body: formData,
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
setLoading(false);
}
}
async function handleResend() {
if (loading) return;
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
{ method: "POST" },
);
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
setLoading(false);
}
}
return (
<form className="billing-invoice-form" onSubmit={handleUpload}>
<label>
<span>
{hasInvoice ? "Rechnungs-PDF ersetzen" : "Rechnungs-PDF hochladen"} (Bericht Nr. {reportNumber})
</span>
<input
type="file"
accept="application/pdf,.pdf"
required
disabled={loading}
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
aria-label={`Rechnungs-PDF für Bericht Nr. ${reportNumber}`}
/>
</label>
<div className="billing-invoice-controls">
<button type="submit" disabled={!file || loading}>
{loading ? "Wird gesendet…" : "Hochladen & senden"}
</button>
{hasInvoice && (
<button type="button" onClick={handleResend} disabled={loading}>
{emailFailed ? "Erneut senden" : "Nochmal senden"}
</button>
)}
</div>
<p className="form-note">
Nach dem Upload geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per
E-Mail an die Redaktion.
</p>
{error && (
<p className="billing-status-message" role="alert">
{error}
</p>
)}
</form>
);
}
function invoiceErrorMessage(code: unknown): string {
switch (code) {
case "INVALID_PDF":
return "Die Datei ist keine gültige PDF (max. 20 MB).";
case "REPORT_NOT_FINAL":
return "Der Bericht ist nicht finalisiert.";
case "INVOICE_NOT_UPLOADED":
return "Es ist noch keine Rechnungs-PDF hinterlegt.";
case "RATE_LIMITED":
return "Zu viele Versuche. Bitte kurz warten.";
default:
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
}
}
type CancelReportFormProps = {
reportId: string;
reportNumber: number;
@@ -15,6 +15,10 @@ export type FinalizedReportSummary = {
netTotalCents: number;
status: string;
createdAt: Date;
hasInvoicePdf: boolean;
invoiceUploadedAt: Date | null;
invoiceEmailStatus: string;
invoiceEmailSentAt: Date | null;
};
export type BillingSelectionData = {
@@ -54,6 +58,10 @@ export async function loadBillingSelection(
netTotalCents: billingReports.netTotalCents,
status: billingReports.status,
createdAt: billingReports.createdAt,
invoicePdfSha256: billingReports.invoicePdfSha256,
invoiceUploadedAt: billingReports.invoiceUploadedAt,
invoiceEmailStatus: billingReports.invoiceEmailStatus,
invoiceEmailSentAt: billingReports.invoiceEmailSentAt,
})
.from(billingReports)
.where(eq(billingReports.editorialAccountId, editorialId))
@@ -77,6 +85,10 @@ export async function loadBillingSelection(
netTotalCents: row.netTotalCents,
status: row.status,
createdAt: row.createdAt,
hasInvoicePdf: row.invoicePdfSha256 !== null,
invoiceUploadedAt: row.invoiceUploadedAt,
invoiceEmailStatus: row.invoiceEmailStatus,
invoiceEmailSentAt: row.invoiceEmailSentAt,
})),
};
}
@@ -0,0 +1,99 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { CalendarActionResult } from "./actions";
export function CalendarEventForm({
action,
defaultEventDate,
albums,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
defaultEventDate: string;
albums: Array<{ id: string; albumName: string }>;
}>) {
const titleId = useId();
const dateId = useId();
const albumId = useId();
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [title, setTitle] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setTitle("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="space-y-2">
<label htmlFor={titleId} className="text-sm font-medium">
Titel (Spielpaarung oder Event)
</label>
<Input
id={titleId}
name="title"
value={title}
onChange={(event) => setTitle(event.target.value)}
maxLength={200}
required
placeholder="z. B. Hamburger SV - VfL Wolfsburg"
/>
<p className="text-xs text-muted-foreground">
Ohne direkte Album-Auswahl wird automatisch verknüpft, sobald ein Album exakt
{" „{Titel}“ "}oder{" „{Titel} | TT.MM.JJJJ“ "}heißt (Datum dieses Termins).
</p>
</div>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={dateId} className="text-sm font-medium">
Datum
</label>
<Input id={dateId} type="date" name="eventDate" defaultValue={defaultEventDate} required className="sm:w-48" />
</div>
<div className="space-y-2 flex-1">
<label htmlFor={albumId} className="text-sm font-medium">
Album direkt verknüpfen (optional)
</label>
<select
id={albumId}
name="immichAlbumId"
defaultValue=""
className="flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Automatisch über den Namen</option>
{albums.map((album) => (
<option key={album.id} value={album.id}>
{album.albumName}
</option>
))}
</select>
</div>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird angelegt…" : "Termin anlegen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
@@ -0,0 +1,44 @@
"use client";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import type { CalendarActionResult } from "./actions";
// Deleting an event also revokes self-service grants on its linked album, so
// the admin confirms once before the action runs.
export function DeleteCalendarEventButton({
action,
eventId,
}: Readonly<{
action: (state: CalendarActionResult, formData: FormData) => Promise<CalendarActionResult>;
eventId: string;
}>) {
const [state, setState] = useState<CalendarActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const handleClick = () => {
if (!window.confirm("Termin löschen? Selbst freigeschaltete Zugriffe auf das verknüpfte Album werden entzogen.")) {
return;
}
const formData = new FormData();
formData.set("eventId", eventId);
startTransition(async () => {
setState(await action({ ok: true, message: "" }, formData));
});
};
return (
<div className="flex flex-col items-end gap-1">
<Button type="button" variant="outline" size="sm" disabled={pending} onClick={handleClick}>
{pending ? "…" : "Löschen"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</div>
);
}
+84
View File
@@ -0,0 +1,84 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { CalendarServiceError, calendarService } from "@/modules/calendar/service";
export type CalendarActionResult = {
ok: boolean;
message: string;
};
export async function createCalendarEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const title = formData.get("title");
const eventDate = formData.get("eventDate");
const immichAlbumId = formData.get("immichAlbumId");
if (typeof title !== "string" || typeof eventDate !== "string") {
return { ok: false, message: "Bitte Titel und Datum ausfüllen." };
}
try {
await calendarService.createEvent({
title,
eventDate,
immichAlbumId: typeof immichAlbumId === "string" && immichAlbumId ? immichAlbumId : null,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/admin/kalender");
revalidatePath("/redaktion/kalender");
return {
ok: true,
message:
"Termin angelegt. Sobald ein passendes Album in Immich erscheint, können Redaktionen es selbst freischalten.",
};
}
export async function deleteCalendarEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const eventId = formData.get("eventId");
if (typeof eventId !== "string" || eventId.length === 0) {
return { ok: false, message: "Ungültige Kennung." };
}
try {
await calendarService.deleteEvent({ id: eventId, adminUserId: principal.userId });
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/admin/kalender");
revalidatePath("/redaktion/kalender");
revalidatePath("/redaktion/alben");
return { ok: true, message: "" };
}
function calendarErrorMessage(error: unknown): string {
if (error instanceof CalendarServiceError) {
const messages: Record<CalendarServiceError["code"], string> = {
INVALID_TITLE: "Bitte geben Sie einen Titel mit 1 bis 200 Zeichen ein.",
INVALID_EVENT_DATE: "Bitte wählen Sie ein gültiges Datum.",
INVALID_ALBUM: "Das gewählte Album existiert nicht mehr in Immich.",
INVALID_STATUS: "Ungültige Rückmeldung.",
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verknüpft.",
IMMICH_UNAVAILABLE: "Immich ist gerade nicht erreichbar. Bitte später erneut versuchen.",
RATE_LIMITED: "Zu viele Anfragen. Bitte kurz warten.",
};
return messages[error.code] ?? "Der Termin konnte nicht gespeichert werden.";
}
return "Der Termin konnte nicht gespeichert werden.";
}
+107
View File
@@ -0,0 +1,107 @@
import { PageHeader } from "@/components/ui/page-header";
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
import { calendarService } from "@/modules/calendar/service";
import { immichClient } from "@/modules/immich/client";
import { CalendarEventForm } from "./CalendarEventForm";
import { DeleteCalendarEventButton } from "./DeleteCalendarEventButton";
import { createCalendarEventAction, deleteCalendarEventAction } from "./actions";
export default async function AdminCalendarPage() {
const [{ events, immichUnavailable }, albums] = await Promise.all([
calendarService.listAdminEvents(),
immichClient.listAlbums().catch(() => []),
]);
const today = isoDateInBerlin(new Date());
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Planung"
title="Kalender"
description="Termine für Redaktionen, z. B. kommende Spiele. Redaktionen melden zurück, ob sie da sind, und können das verknüpfte Album selbst freischalten. Alben ohne Kalender-Termin bleiben unsichtbar; automatische Zuweisungsregeln gelten unabhängig davon."
/>
<CalendarEventForm
action={createCalendarEventAction}
defaultEventDate={today}
albums={albums.map((album) => ({ id: album.id, albumName: album.albumName }))}
/>
{immichUnavailable ? (
<p className="bg-muted p-4 rounded-md text-sm" role="status">
Immich ist gerade nicht erreichbar. Verknüpfte Alben werden angezeigt, sobald die Verbindung wieder steht.
</p>
) : null}
<section className="space-y-4" aria-labelledby="calendar-list-title">
<div className="flex items-baseline justify-between">
<h2 id="calendar-list-title" className="text-xl font-semibold">
Alle Termine
</h2>
<p className="text-sm text-muted-foreground">{events.length} insgesamt</p>
</div>
{events.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Termine vorhanden. Legen Sie oben den ersten Termin an.
</p>
) : (
<ul className="space-y-3">
{events.map((event) => {
const attending = event.responses.filter((response) => response.status === "attending");
const notAttending = event.responses.filter((response) => response.status === "not_attending");
return (
<li
key={event.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-2 min-w-0">
<p className="font-semibold">
{event.title}
{event.eventDate < today ? (
<span className="ml-2 text-xs font-normal text-muted-foreground">vorbei</span>
) : null}
</p>
<p className="text-xs text-muted-foreground">
{formatIsoDateGerman(event.eventDate)} ·{" "}
{event.album ? (
<span>Album: {event.album.albumName}</span>
) : (
<span>Noch kein Album verknüpft</span>
)}
</p>
{event.responses.length > 0 ? (
<div className="flex flex-wrap gap-1.5 text-xs">
{attending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-green-600/10 px-2.5 py-1 font-medium text-green-700 dark:text-green-400"
>
{response.editorialName}: da
</span>
))}
{notAttending.map((response) => (
<span
key={response.editorialId}
className="rounded-full bg-muted px-2.5 py-1 text-muted-foreground"
>
{response.editorialName}: nicht da
</span>
))}
</div>
) : (
<p className="text-xs text-muted-foreground">Noch keine Rückmeldungen.</p>
)}
</div>
<DeleteCalendarEventButton action={deleteCalendarEventAction} eventId={event.id} />
</li>
);
})}
</ul>
)}
</section>
</div>
);
}
+3
View File
@@ -13,9 +13,12 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
sectionLabel="Administration"
nav={[
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/statistiken", label: "Statistiken" },
{ href: "/admin/redaktionen", label: "Redaktionen" },
{ href: "/admin/alben", label: "Alben" },
{ href: "/admin/kalender", label: "Kalender" },
{ href: "/admin/hinweise", label: "Hinweise" },
{ href: "/admin/versionen", label: "Versionen" },
{ href: "/admin/abrechnungen", label: "Abrechnungen" },
{ href: "/admin/audit", label: "Audit" },
]}
+34
View File
@@ -9,6 +9,7 @@ import { editorialAccounts } from "@/db/schema";
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
import { writeAudit } from "@/modules/audit/write";
// Returned to the client form so failures surface as inline German text
// instead of an opaque Next.js error-digest page (a thrown server action
@@ -203,6 +204,39 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
export async function updateCollabAction(editorialId: string, formData: FormData): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const collabEnabled = formData.get("collabEnabled") === "on";
const [previous] = await db
.select({ collabEnabled: editorialAccounts.collabEnabled })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, safeEditorialId))
.limit(1);
if (!previous) throw new Error("EDITORIAL_NOT_FOUND");
await db
.update(editorialAccounts)
.set({ collabEnabled })
.where(eq(editorialAccounts.id, safeEditorialId));
try {
await writeAudit({
type: "editorial_collab_updated",
actorUserId: admin.userId,
actorType: "admin",
entityType: "editorial_account",
entityId: safeEditorialId,
metadata: { from: previous.collabEnabled, to: collabEnabled },
});
} catch {
// Audit is observability, not a transaction participant.
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
function parsePriceCents(
value: unknown,
): { ok: true; cents: number } | { ok: false; message: string } {
@@ -18,6 +18,7 @@ const editorial = {
flatrateActive: false,
flatratePriceCents: null,
flatrateAssetLimit: null,
collabEnabled: false,
archivedAt: null,
};
+1
View File
@@ -21,6 +21,7 @@ export default async function EditorialDetailPage({
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
collabEnabled: editorialAccounts.collabEnabled,
archivedAt: editorialAccounts.archivedAt,
})
.from(editorialAccounts)
+358
View File
@@ -0,0 +1,358 @@
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
formatBytes,
normalizeStatsDays,
percentChange,
STATS_PERIOD_OPTIONS,
statsQueries,
} from "@/modules/stats/queries";
import { requireAdminPage } from "../access";
import { ActivityChart, RevenueChart } from "./stats-charts-lazy";
const euroFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const ACTIVITY_LABELS: Record<string, string> = {
album_view: "Album geöffnet",
search: "Suche",
lightbox_view: "Großansicht",
};
export default async function AdminStatsPage({
searchParams,
}: Readonly<{ searchParams: Promise<Record<string, string | string[] | undefined>> }>) {
await requireAdminPage();
const sp = await searchParams;
const rawDays = Array.isArray(sp.zeitraum) ? sp.zeitraum[0] : sp.zeitraum;
const days = normalizeStatsDays(rawDays);
const stats = await statsQueries.loadOverview(days);
const { kpis, previousKpis } = stats;
return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
title="Statistiken"
description="Downloads, Aufrufe, Suchen und Umsatz im Detail. Aufrufe und Suchen werden seit Version 2.2 erfasst."
/>
<div className="flex flex-wrap items-center justify-between gap-4">
<nav
aria-label="Zeitraum"
className="inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 p-1"
>
{STATS_PERIOD_OPTIONS.map((option) => (
<Link
key={option}
href={`/admin/statistiken?zeitraum=${option}`}
aria-current={option === days ? "page" : undefined}
className={`rounded-full px-4 py-1.5 text-sm transition-colors ${
option === days
? "bg-card font-semibold shadow-sm"
: "text-muted-foreground hover:text-foreground"
}`}
>
{option} Tage
</Link>
))}
</nav>
<p className="text-sm text-muted-foreground">
Zeitraum: {stats.window.fromUtc.toLocaleDateString("de-DE")} bis{" "}
{stats.window.toUtcExclusive.toLocaleDateString("de-DE")}
</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<KpiCard
label="Downloads"
value={String(kpis.downloadsCompleted)}
hint={`${kpis.downloadsInterrupted} unterbrochen, ${kpis.downloadsFailed} fehlgeschlagen`}
change={percentChange(kpis.downloadsCompleted, previousKpis.downloadsCompleted)}
/>
<KpiCard
label="Datenmenge"
value={formatBytes(kpis.transferredBytes)}
hint="Ausgelieferte Originaldateien"
/>
<KpiCard
label="Neue Nutzungen"
value={String(kpis.newUsages)}
hint={`${kpis.collabUsages} davon Collab (kostenfrei)`}
change={percentChange(kpis.newUsages, previousKpis.newUsages)}
/>
<KpiCard
label="Umsatz im Zeitraum"
value={euroFormatter.format(kpis.revenueCents / 100)}
hint="Netto, aus neuen Nutzungen"
change={percentChange(kpis.revenueCents, previousKpis.revenueCents)}
/>
<KpiCard
label="Album-Aufrufe"
value={String(kpis.albumViews)}
hint="Seitenaufrufe der Albumansicht"
change={percentChange(kpis.albumViews, previousKpis.albumViews)}
/>
<KpiCard
label="Suchen"
value={String(kpis.searches)}
hint="In Alben und über alle Alben"
change={percentChange(kpis.searches, previousKpis.searches)}
/>
<KpiCard
label="Großansichten"
value={String(kpis.lightboxViews)}
hint="Lightbox-Öffnungen"
change={percentChange(kpis.lightboxViews, previousKpis.lightboxViews)}
/>
<KpiCard
label="Aktive Redaktionen"
value={String(kpis.activeEditorials)}
hint="Mit mindestens einem Download"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Offener Umsatz gesamt
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">
{euroFormatter.format(stats.openRevenueCents / 100)}
</p>
<p className="mt-1 text-sm text-muted-foreground">
Noch nicht abgerechnete Nutzungen
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Abrechnungen im Zeitraum
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">{stats.finalizedReports}</p>
<p className="mt-1 text-sm text-muted-foreground">Finalisierte Nutzungsnachweise</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Collab-Quote
</p>
<p className="mt-1 text-2xl font-bold tabular-nums">
{kpis.newUsages > 0
? `${Math.round((kpis.collabUsages / kpis.newUsages) * 100)} %`
: "0 %"}
</p>
<p className="mt-1 text-sm text-muted-foreground">
Anteil kostenfreier Collab-Nutzungen
</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Aktivität der letzten {days} Tage</CardTitle>
<CardDescription>
Downloads, Album-Aufrufe und Suchen pro Tag über alle Redaktionen.
</CardDescription>
</CardHeader>
<CardContent>
<ActivityChart data={stats.daily} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Umsatz pro Tag</CardTitle>
<CardDescription>Netto-Umsatz aus neuen Nutzungen im Zeitraum.</CardDescription>
</CardHeader>
<CardContent>
<RevenueChart data={stats.daily} />
</CardContent>
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<Card>
<CardHeader>
<CardTitle>Redaktionen im Zeitraum</CardTitle>
<CardDescription>Nach Downloads sortiert.</CardDescription>
</CardHeader>
<CardContent>
{stats.topEditorials.length === 0 ? (
<p className="text-sm text-muted-foreground">Noch keine Daten vorhanden.</p>
) : (
<div className="overflow-x-auto rounded-md border border-border">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Redaktion</th>
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-right">Collab</th>
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
<th className="py-3 px-4 font-semibold text-right">Aufrufe</th>
<th className="py-3 px-4 font-semibold text-right">Suchen</th>
</tr>
</thead>
<tbody>
{stats.topEditorials.map((row, index) => (
<tr
key={row.editorialId}
className={index !== stats.topEditorials.length - 1 ? "border-b border-border" : ""}
>
<td className="py-3 px-4">
<Link
href={`/admin/redaktionen/${row.editorialId}`}
className="font-medium text-primary-600 hover:underline dark:text-primary-400"
>
{row.name}
</Link>
</td>
<td className="py-3 px-4 text-right tabular-nums">{row.downloads}</td>
<td className="py-3 px-4 text-right tabular-nums">
{row.collabUsages > 0 ? (
<span className="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground">
{row.collabUsages}
</span>
) : (
"0"
)}
</td>
<td className="py-3 px-4 text-right tabular-nums">
{euroFormatter.format(row.revenueCents / 100)}
</td>
<td className="py-3 px-4 text-right tabular-nums">{row.views}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.searches}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Alben im Zeitraum</CardTitle>
<CardDescription>Nach Downloads und Aufrufen sortiert.</CardDescription>
</CardHeader>
<CardContent>
{stats.topAlbums.length === 0 ? (
<p className="text-sm text-muted-foreground">Noch keine Daten vorhanden.</p>
) : (
<div className="overflow-x-auto rounded-md border border-border">
<table className="w-full text-left text-sm">
<thead className="bg-muted/50 border-b border-border">
<tr>
<th className="py-3 px-4 font-semibold">Album</th>
<th className="py-3 px-4 font-semibold text-right">Downloads</th>
<th className="py-3 px-4 font-semibold text-right">Aufrufe</th>
<th className="py-3 px-4 font-semibold text-right">Umsatz</th>
</tr>
</thead>
<tbody>
{stats.topAlbums.map((row, index) => (
<tr
key={row.albumKey}
className={index !== stats.topAlbums.length - 1 ? "border-b border-border" : ""}
>
<td className="py-3 px-4 font-medium">{row.albumName}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.downloads}</td>
<td className="py-3 px-4 text-right tabular-nums">{row.views}</td>
<td className="py-3 px-4 text-right tabular-nums">
{euroFormatter.format(row.revenueCents / 100)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Letzte Aktivitäten</CardTitle>
<CardDescription>Die neuesten erfassten Aktionen der Redaktionen.</CardDescription>
</CardHeader>
<CardContent>
{stats.recentActivity.length === 0 ? (
<p className="text-sm text-muted-foreground">
Noch keine Aktivitäten erfasst. Aufrufe und Suchen werden ab Version 2.2 gezählt.
</p>
) : (
<ul className="divide-y divide-border">
{stats.recentActivity.map((event) => (
<li key={event.id} className="flex flex-wrap items-center gap-3 py-2.5 text-sm">
<span className="inline-flex items-center rounded-full border border-border px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
{ACTIVITY_LABELS[event.eventType] ?? event.eventType}
</span>
<span className="font-medium">{event.editorialName}</span>
{event.query ? (
<span className="text-muted-foreground">„{event.query}“</span>
) : null}
<time
className="ml-auto text-xs text-muted-foreground tabular-nums"
dateTime={event.occurredAt.toISOString()}
suppressHydrationWarning
>
{event.occurredAt.toLocaleString("de-DE", {
day: "2-digit",
month: "2-digit",
hour: "2-digit",
minute: "2-digit",
})}
</time>
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
);
}
type KpiCardProps = {
label: string;
value: string;
hint: string;
change?: number | null;
};
function KpiCard({ label, value, hint, change }: KpiCardProps) {
return (
<Card className="transition-shadow hover:shadow-md">
<CardContent className="pt-6">
<div className="flex items-start justify-between gap-2">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</p>
{change !== undefined && change !== null ? (
<span
className={`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[11px] font-semibold tabular-nums ${
change > 0
? "border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-400"
: change < 0
? "border-red-300 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-950/40 dark:text-red-400"
: "border-border bg-muted/40 text-muted-foreground"
}`}
title="Veränderung gegenüber dem vorherigen Zeitraum"
>
{change > 0 ? "+" : ""}
{change} %
</span>
) : null}
</div>
<p className="mt-2 text-3xl font-bold tabular-nums">{value}</p>
<p className="mt-1 text-sm text-muted-foreground">{hint}</p>
</CardContent>
</Card>
);
}
@@ -0,0 +1,15 @@
"use client";
import dynamic from "next/dynamic";
const ActivityChart = dynamic(
() => import("./stats-charts").then((mod) => mod.ActivityChart),
{ ssr: false },
);
const RevenueChart = dynamic(
() => import("./stats-charts").then((mod) => mod.RevenueChart),
{ ssr: false },
);
export { ActivityChart, RevenueChart };
+177
View File
@@ -0,0 +1,177 @@
"use client";
import { useTheme } from "next-themes";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { DailyPoint } from "@/modules/stats/queries";
type StatsChartsProps = {
data: DailyPoint[];
};
const euroFormatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
function useChartColors() {
const { theme } = useTheme();
const dark = theme === "dark";
return {
grid: dark ? "#333333" : "#e5e5e5",
axis: "#888888",
tooltip: {
backgroundColor: dark ? "#1f2937" : "#ffffff",
borderColor: dark ? "#374151" : "#e5e7eb",
color: dark ? "#f3f4f6" : "#111827",
},
cursor: dark ? "#ffffff10" : "#00000005",
downloads: dark ? "#6366f1" : "#4f46e5",
views: dark ? "#34d399" : "#059669",
searches: dark ? "#fbbf24" : "#d97706",
};
}
function formatDay(value: string): string {
return new Date(value).toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
}
function formatDayLong(value: string): string {
return new Date(value).toLocaleDateString("de-DE", {
weekday: "long",
day: "2-digit",
month: "long",
year: "numeric",
});
}
export function ActivityChart({ data }: StatsChartsProps) {
const colors = useChartColors();
return (
<div className="h-[300px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="statsDownloads" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={colors.downloads} stopOpacity={0.25} />
<stop offset="100%" stopColor={colors.downloads} stopOpacity={0.02} />
</linearGradient>
<linearGradient id="statsViews" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={colors.views} stopOpacity={0.25} />
<stop offset="100%" stopColor={colors.views} stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={colors.grid} />
<XAxis
dataKey="date"
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={formatDay}
minTickGap={24}
/>
<YAxis
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
allowDecimals={false}
/>
<Tooltip
cursor={{ stroke: colors.grid }}
contentStyle={{
...colors.tooltip,
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
}}
labelFormatter={(label) => formatDayLong(String(label))}
/>
<Legend wrapperStyle={{ fontSize: 12 }} />
<Area
type="monotone"
dataKey="downloads"
name="Downloads"
stroke={colors.downloads}
fill="url(#statsDownloads)"
strokeWidth={2}
/>
<Area
type="monotone"
dataKey="views"
name="Album-Aufrufe"
stroke={colors.views}
fill="url(#statsViews)"
strokeWidth={2}
/>
<Area
type="monotone"
dataKey="searches"
name="Suchen"
stroke={colors.searches}
fill="transparent"
strokeWidth={2}
strokeDasharray="4 3"
/>
</AreaChart>
</ResponsiveContainer>
</div>
);
}
export function RevenueChart({ data }: StatsChartsProps) {
const colors = useChartColors();
return (
<div className="h-[260px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={colors.grid} />
<XAxis
dataKey="date"
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={formatDay}
minTickGap={24}
/>
<YAxis
stroke={colors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value: number) => `${value} €`}
/>
<Tooltip
cursor={{ fill: colors.cursor }}
contentStyle={{
...colors.tooltip,
borderRadius: "8px",
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
}}
labelFormatter={(label) => formatDayLong(String(label))}
formatter={(value) => [euroFormatter.format(Number(value) / 100), "Umsatz"]}
/>
<Bar
dataKey="revenueCents"
name="Umsatz"
fill={colors.downloads}
radius={[4, 4, 0, 0]}
maxBarSize={40}
/>
</BarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,31 @@
"use client";
import { useActionState } from "react";
import { Button } from "@/components/ui/button";
import type { ReleaseNoteActionResult } from "./actions";
export function DeleteReleaseNoteButton({
action,
noteId,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
noteId: string;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction} className="flex flex-col items-end gap-1">
<input type="hidden" name="noteId" value={noteId} />
<Button type="submit" variant="outline" size="sm" disabled={pending}>
{pending ? "…" : "Löschen"}
</Button>
{state.ok ? null : (
<p role="alert" className="text-xs text-destructive">
{state.message}
</p>
)}
</form>
);
}
@@ -0,0 +1,91 @@
"use client";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ReleaseNoteActionResult } from "./actions";
export function ReleaseNoteForm({
action,
}: Readonly<{
action: (state: ReleaseNoteActionResult, formData: FormData) => Promise<ReleaseNoteActionResult>;
}>) {
const versionId = useId();
const audienceId = useId();
const bodyId = useId();
const [state, setState] = useState<ReleaseNoteActionResult>({ ok: true, message: "" });
const [pending, startTransition] = useTransition();
const [body, setBody] = useState("");
const handleSubmit = (formData: FormData) => {
startTransition(async () => {
const result = await action({ ok: true, message: "" }, formData);
setState(result);
if (result.ok) {
setBody("");
}
});
};
return (
<form
action={handleSubmit}
className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-4"
>
<div className="flex flex-col sm:flex-row gap-4">
<div className="space-y-2">
<label htmlFor={versionId} className="text-sm font-medium">
Version
</label>
<Input id={versionId} name="version" placeholder="z. B. 2.1.1" required className="sm:w-36" />
</div>
<div className="space-y-2">
<label htmlFor={audienceId} className="text-sm font-medium">
Zielgruppe
</label>
<select
id={audienceId}
name="audience"
defaultValue="editorial"
className="flex h-10 w-full sm:w-48 rounded-md border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="editorial">Redaktionen</option>
<option value="admin">Admins</option>
<option value="both">Beide</option>
</select>
</div>
</div>
<div className="space-y-2">
<label htmlFor={bodyId} className="text-sm font-medium">
Hinweis
</label>
<textarea
id={bodyId}
name="body"
rows={4}
maxLength={2000}
required
value={body}
onChange={(event) => setBody(event.target.value)}
placeholder="Was ist neu in dieser Version?"
className="flex w-full rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
<p className="text-xs text-muted-foreground">{body.length}/2000 Zeichen</p>
</div>
<Button type="submit" disabled={pending}>
{pending ? "Wird veröffentlicht…" : "Hinweis veröffentlichen"}
</Button>
{state.message ? (
<p
role="status"
aria-live="polite"
className={state.ok ? "text-sm text-green-600 dark:text-green-400" : "text-sm text-destructive"}
>
{state.message}
</p>
) : null}
</form>
);
}
+83
View File
@@ -0,0 +1,83 @@
"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import {
ReleaseNoteServiceError,
releaseNoteService,
type ReleaseNoteAudience,
} from "@/modules/releases/service";
export type ReleaseNoteActionResult = {
ok: boolean;
message: string;
};
export async function createReleaseNoteAction(
_prevState: ReleaseNoteActionResult,
formData: FormData,
): Promise<ReleaseNoteActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const version = formData.get("version");
const audience = formData.get("audience");
const body = formData.get("body");
if (typeof version !== "string" || typeof body !== "string") {
return { ok: false, message: "Bitte Version und Text ausfüllen." };
}
if (audience !== "admin" && audience !== "editorial" && audience !== "both") {
return { ok: false, message: "Bitte Zielgruppe wählen." };
}
try {
await releaseNoteService.createReleaseNote({
version,
audience: audience as ReleaseNoteAudience,
body,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: releaseNoteErrorMessage(error) };
}
revalidatePath("/admin/versionen");
revalidatePath("/redaktion/neuigkeiten");
return { ok: true, message: "Versionshinweis veröffentlicht." };
}
export async function deleteReleaseNoteAction(
_prevState: ReleaseNoteActionResult,
formData: FormData,
): Promise<ReleaseNoteActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const noteId = formData.get("noteId");
if (typeof noteId !== "string" || noteId.length === 0) {
return { ok: false, message: "Ungültige Kennung." };
}
try {
await releaseNoteService.deleteReleaseNote({ id: noteId, adminUserId: principal.userId });
} catch (error) {
return { ok: false, message: releaseNoteErrorMessage(error) };
}
revalidatePath("/admin/versionen");
revalidatePath("/redaktion/neuigkeiten");
return { ok: true, message: "" };
}
function releaseNoteErrorMessage(error: unknown): string {
if (error instanceof ReleaseNoteServiceError) {
const messages: Record<ReleaseNoteServiceError["code"], string> = {
INVALID_VERSION: "Bitte eine Version wie 2.1 oder 2.1.1 angeben.",
INVALID_BODY: "Bitte einen Text mit 1 bis 2000 Zeichen eingeben.",
INVALID_AUDIENCE: "Bitte Zielgruppe wählen.",
DUPLICATE_RELEASE_NOTE: "Für diese Version und Zielgruppe gibt es bereits einen Hinweis.",
RELEASE_NOTE_NOT_FOUND: "Dieser Hinweis existiert nicht mehr.",
};
return messages[error.code] ?? "Der Hinweis konnte nicht gespeichert werden.";
}
return "Der Hinweis konnte nicht gespeichert werden.";
}
+66
View File
@@ -0,0 +1,66 @@
import { PageHeader } from "@/components/ui/page-header";
import { releaseNoteService, type ReleaseNoteAudience } from "@/modules/releases/service";
import { DeleteReleaseNoteButton } from "./DeleteReleaseNoteButton";
import { ReleaseNoteForm } from "./ReleaseNoteForm";
import { createReleaseNoteAction, deleteReleaseNoteAction } from "./actions";
const audienceLabels: Record<ReleaseNoteAudience, string> = {
admin: "Admins",
editorial: "Redaktionen",
both: "Beide",
};
export default async function AdminVersionsPage() {
const notes = await releaseNoteService.listReleaseNotes();
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
<PageHeader
kicker="Portal"
title="Versionshinweise"
description="Was sich im Portal geändert hat, getrennt nach Zielgruppe. Redaktionen sehen ihre Hinweise unter Neuigkeiten. Jede Veröffentlichung im Portal bekommt hier einen Eintrag und eine fortlaufende Versionsnummer."
/>
<ReleaseNoteForm action={createReleaseNoteAction} />
<section className="space-y-4" aria-labelledby="release-notes-list-title">
<div className="flex items-baseline justify-between">
<h2 id="release-notes-list-title" className="text-xl font-semibold">
Alle Hinweise
</h2>
<p className="text-sm text-muted-foreground">{notes.length} insgesamt</p>
</div>
{notes.length === 0 ? (
<p className="text-muted-foreground py-8 text-center">
Noch keine Versionshinweise vorhanden.
</p>
) : (
<ul className="space-y-3">
{notes.map((note) => (
<li
key={note.id}
className="bg-card p-4 rounded-xl border border-border shadow-sm flex flex-col sm:flex-row sm:items-start gap-4 justify-between"
>
<div className="space-y-1 min-w-0">
<p className="text-sm font-semibold">
Version {note.version}
<span className="ml-2 rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
{audienceLabels[note.audience]}
</span>
</p>
<p className="text-sm whitespace-pre-line break-words">{note.body}</p>
<p className="text-xs text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(note.createdAt)}
</p>
</div>
<DeleteReleaseNoteButton action={deleteReleaseNoteAction} noteId={note.id} />
</li>
))}
</ul>
)}
</section>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { recordActivity } from "@/modules/activity/service";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
// Client beacon for lightbox views. Album views and searches are recorded
// server-side in the pages themselves; this endpoint only accepts lightbox_view.
export async function POST(request: Request): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await requireActiveEditorial(request.headers);
const body = (await request.json().catch(() => null)) as {
type?: unknown;
albumId?: unknown;
assetId?: unknown;
} | null;
if (!body || body.type !== "lightbox_view") {
return Response.json({ code: "INVALID_REQUEST" }, { status: 400 });
}
await recordActivity({
editorialId: principal.editorialId,
type: "lightbox_view",
...(typeof body.albumId === "string" ? { albumId: body.albumId } : {}),
...(typeof body.assetId === "string" ? { assetId: body.assetId } : {}),
});
return new Response(null, {
status: 204,
headers: { "cache-control": "private, no-store" },
});
} catch (error) {
if (error instanceof CrossOriginRequestError) {
return Response.json({ code: "CROSS_ORIGIN_REQUEST" }, { status: 403 });
}
if (error instanceof PrincipalAuthorizationError) {
return Response.json(
{ code: "FORBIDDEN" },
{ status: error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403 },
);
}
return Response.json({ code: "REQUEST_FAILED" }, { status: 500 });
}
}
@@ -0,0 +1,156 @@
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
import {
uploadInvoice,
resendInvoice,
getInvoicePdf,
InvoiceError,
INVOICE_PDF_MAX_BYTES,
} from "@/modules/billing/invoice";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { invoiceUploadPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
type InvoiceRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
type InvoiceHandlerDependencies = {
requireAdmin: typeof requireAdmin;
uploadInvoice: typeof uploadInvoice;
resendInvoice: typeof resendInvoice;
getInvoicePdf: typeof getInvoicePdf;
consumeRateLimit: ConsumeRateLimit;
};
export function createInvoiceUploadHandler(dependencies: InvoiceHandlerDependencies) {
return async function POST(request: Request, context: InvoiceRouteContext): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireAdmin(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`invoice-upload:${principal.userId}`,
invoiceUploadPolicy,
);
const { reportId } = await context.params;
const formData = await request.formData().catch(() => null);
const file = formData?.get("invoice");
if (!(file instanceof File)) return jsonError(400, "INVALID_REQUEST");
if (file.size === 0 || file.size > INVOICE_PDF_MAX_BYTES) {
return jsonError(400, "INVALID_PDF");
}
const bytes = Buffer.from(await file.arrayBuffer());
const result = await dependencies.uploadInvoice({
reportId,
bytes,
filename: file.name || "rechnung.pdf",
adminUserId: principal.userId,
});
return Response.json(
{ ok: true, emailStatus: result.emailStatus },
{ status: 200, headers: { "cache-control": "private, no-store" } },
);
} catch (error) {
return mappedError(error);
}
};
}
export function createInvoiceResendHandler(dependencies: InvoiceHandlerDependencies) {
return async function POST(request: Request, context: InvoiceRouteContext): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireAdmin(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`invoice-upload:${principal.userId}`,
invoiceUploadPolicy,
);
const { reportId } = await context.params;
const result = await dependencies.resendInvoice({
reportId,
adminUserId: principal.userId,
});
return Response.json(
{ ok: true, emailStatus: result.emailStatus },
{ status: 200, headers: { "cache-control": "private, no-store" } },
);
} catch (error) {
return mappedError(error);
}
};
}
export function createInvoiceGetHandler(dependencies: InvoiceHandlerDependencies) {
return async function GET(request: Request, context: InvoiceRouteContext): Promise<Response> {
try {
await dependencies.requireAdmin(request.headers);
const { reportId } = await context.params;
const invoice = await dependencies.getInvoicePdf(reportId);
if (!invoice) {
return new Response(null, {
status: 404,
headers: { "cache-control": "private, no-store" },
});
}
const filename = invoice.filename.replace(/[^\w.\-]/g, "_");
return new Response(new Uint8Array(invoice.bytes), {
status: 200,
headers: {
"content-type": "application/pdf",
"cache-control": "private, no-store",
"content-disposition": `attachment; filename="${filename}"`,
},
});
} catch (error) {
return mappedError(error);
}
};
}
function mappedError(error: unknown): Response {
if (error instanceof RateLimitExceededError) {
return jsonError(429, "RATE_LIMITED", { "retry-after": String(error.retryAfterSeconds) });
}
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
if (error instanceof InvoiceError) {
switch (error.code) {
case "REPORT_NOT_FOUND":
return jsonError(404, "REPORT_NOT_FOUND");
case "REPORT_NOT_FINAL":
return jsonError(409, "REPORT_NOT_FINAL");
case "INVALID_PDF":
return jsonError(400, "INVALID_PDF");
case "INVOICE_NOT_UPLOADED":
return jsonError(409, "INVOICE_NOT_UPLOADED");
case "EDITORIAL_NOT_FOUND":
return jsonError(404, "EDITORIAL_NOT_FOUND");
}
}
return jsonError(500, "REQUEST_FAILED");
}
function jsonError(status: number, code: string, extraHeaders?: HeadersInit): Response {
const headers = new Headers(extraHeaders);
headers.set("cache-control", "private, no-store");
return Response.json({ code }, { status, headers });
}
const dependencies: InvoiceHandlerDependencies = {
requireAdmin,
uploadInvoice,
resendInvoice,
getInvoicePdf,
consumeRateLimit,
};
export const invoiceUploadHandler = createInvoiceUploadHandler(dependencies);
export const invoiceResendHandler = createInvoiceResendHandler(dependencies);
export const invoiceGetHandler = createInvoiceGetHandler(dependencies);
@@ -0,0 +1,3 @@
import { invoiceResendHandler } from "../invoice-handler";
export const POST = invoiceResendHandler;
@@ -0,0 +1,4 @@
import { invoiceGetHandler, invoiceUploadHandler } from "./invoice-handler";
export const POST = invoiceUploadHandler;
export const GET = invoiceGetHandler;
@@ -8,11 +8,6 @@ import {
} from "@/modules/billing/reports";
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { emailService } from "@/modules/email/service";
import { getReportPdf } from "@/modules/billing/reports";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { eq } from "drizzle-orm";
const finalizePayload = z
.object({
@@ -51,34 +46,9 @@ export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies)
flatrateCentsSnapshot: null,
});
// Email dispatch
try {
const [editorial] = await db
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
if (editorial?.email) {
const reportPdf = await getReportPdf(result.reportId);
if (reportPdf) {
const periodString = month
? `${month.toString().padStart(2, "0")}/${year}`
: `Q${quarter}/${year}`;
// Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background)
await emailService.sendBillingReport(
editorial.email,
periodString,
reportPdf.bytes,
result.reportNumber
);
}
}
} catch (emailError) {
console.error("Failed to send billing email:", emailError);
// Do not fail the request if email fails
}
// No email here: the admin reviews the Nutzungsnachweis (and can fix
// collab/wrong positions via cancel + re-finalize), then uploads the
// invoice PDF. That upload sends invoice + Nutzungsnachweis bundled.
return Response.json(
{
@@ -20,6 +20,7 @@ const newUsagePayload = z
purpose: z.string(),
reference: z.string().optional(),
idempotencyKey: z.string(),
collab: z.boolean().optional(),
})
.strict();
@@ -65,6 +66,7 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
? {}
: { reference: payload.data.reference }),
idempotencyKey: payload.data.idempotencyKey,
...(payload.data.collab === true ? { collab: true } : {}),
})
: await dependencies.createRepeatDownload({
editorialId: principal.editorialId,
@@ -125,6 +127,8 @@ function mappedError(error: unknown): Response {
return errorResponse(422, "INVALID_ASSET");
case "EDITORIAL_NOT_ACTIVE":
return errorResponse(403, "FORBIDDEN");
case "COLLAB_NOT_ENABLED":
return errorResponse(403, "COLLAB_NOT_ENABLED");
case "INVALID_PRICE":
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
}
@@ -1,6 +1,7 @@
import { expect, test, vi } from "vitest";
import { createDownloadIntentHandler } from "./intent-handler";
import { UsageAccountingError } from "@/modules/usages/types";
const editorialId = "11111111-1111-4111-8111-111111111111";
const assetId = "22222222-2222-4222-8222-222222222222";
@@ -159,3 +160,46 @@ test("returns retry-after without creating an intent when the editorial limit is
);
expect(deps.createNewUsage).not.toHaveBeenCalled();
});
test("passes the collab flag through to the usage service", async () => {
const deps = dependencies();
deps.createNewUsage.mockResolvedValue({
id: downloadId,
usageId,
assetId,
priceCents: 0,
billable: true,
status: "authorized",
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
});
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Collab Strecke",
idempotencyKey,
collab: true,
});
expect(response.status).toBe(201);
expect(deps.createNewUsage).toHaveBeenCalledWith(
expect.objectContaining({ editorialId, collab: true }),
);
await expect(response.json()).resolves.toMatchObject({ priceCents: 0 });
});
test("maps COLLAB_NOT_ENABLED to 403 with a stable code", async () => {
const deps = dependencies();
deps.createNewUsage.mockRejectedValue(new UsageAccountingError("COLLAB_NOT_ENABLED"));
const response = await post(createDownloadIntentHandler(deps), {
kind: "new_usage",
assetId,
albumId,
purpose: "Collab Strecke",
idempotencyKey,
collab: true,
});
expect(response.status).toBe(403);
await expect(response.json()).resolves.toEqual({ code: "COLLAB_NOT_ENABLED" });
});
@@ -47,6 +47,7 @@ type BulkDownloadHandlerDependencies = {
purpose: string;
reference?: string;
idempotencyKey: string;
collab?: boolean;
}): Promise<{ id: string }>;
createRepeatDownload(input: {
editorialId: string;
@@ -224,7 +225,7 @@ async function grantedAssetMap(
async function prepareDownloads(
dependencies: BulkDownloadHandlerDependencies,
editorialId: string,
payload: { assetIds: string[]; purpose: string },
payload: { assetIds: string[]; purpose: string; collab?: boolean },
assetToGrantedAlbum: Map<string, string>,
onPrepared: (item: PreparedDownload) => Promise<void>,
) {
@@ -256,6 +257,7 @@ async function prepareDownloads(
purpose: payload.purpose,
reference: undefined,
idempotencyKey: randomUUID(),
...(payload.collab === true ? { collab: true } : {}),
});
const prepared = {
assetId: asset.id,
@@ -269,7 +271,10 @@ async function prepareDownloads(
}
async function parsePayload(request: Request) {
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown };
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown; collab?: unknown };
if (body.collab !== undefined && typeof body.collab !== "boolean") {
throw new BulkInputError();
}
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) {
throw new BulkInputError();
}
@@ -280,7 +285,11 @@ async function parsePayload(request: Request) {
if (typeof body.purpose !== "string" || body.purpose.trim().length === 0 || body.purpose.trim().length > 500) {
throw new BulkInputError();
}
return { assetIds: body.assetIds as string[], purpose: body.purpose.trim() };
return {
assetIds: body.assetIds as string[],
purpose: body.purpose.trim(),
...(body.collab === true ? { collab: true } : {}),
};
}
class BulkInputError extends Error {}
@@ -322,6 +331,7 @@ function mappedBulkError(error: unknown): Response {
USAGE_NOT_FOUND: 404,
IMMICH_UNAVAILABLE: 503,
EDITORIAL_NOT_ACTIVE: 403,
COLLAB_NOT_ENABLED: 403,
INVALID_PRICE: 409,
};
return jsonError(statusByCode[error.code] ?? 500, error.code);
@@ -0,0 +1,79 @@
import { z } from "zod";
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { setUsageCollab, CollabAdminError } from "@/modules/usages/collab-admin";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { downloadIntentsPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
const payloadSchema = z.object({ collab: z.boolean() }).strict();
type CollabRouteContext = Readonly<{ params: Promise<{ usageId: string }> }>;
type CollabHandlerDependencies = {
requireAdmin: typeof requireAdmin;
setUsageCollab: typeof setUsageCollab;
consumeRateLimit: ConsumeRateLimit;
};
export function createUsageCollabHandler(dependencies: CollabHandlerDependencies) {
return async function POST(request: Request, context: CollabRouteContext): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireAdmin(request.headers);
await enforceRateLimit(
dependencies.consumeRateLimit,
`usage-collab:${principal.userId}`,
downloadIntentsPolicy,
);
const { usageId } = await context.params;
const parsed = payloadSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return jsonError(400, "INVALID_REQUEST");
const result = await dependencies.setUsageCollab({
usageId,
collab: parsed.data.collab,
adminUserId: principal.userId,
});
return Response.json(
{ ok: true, priceCents: result.priceCents },
{ status: 200, headers: { "cache-control": "private, no-store" } },
);
} catch (error) {
if (error instanceof RateLimitExceededError) {
return jsonError(429, "RATE_LIMITED", { "retry-after": String(error.retryAfterSeconds) });
}
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
if (error instanceof CollabAdminError) {
switch (error.code) {
case "USAGE_NOT_FOUND":
return jsonError(404, "USAGE_NOT_FOUND");
case "USAGE_NOT_EDITABLE":
return jsonError(409, "USAGE_NOT_EDITABLE");
case "INVALID_PRICE":
return jsonError(409, "INVALID_PRICE");
}
}
return jsonError(500, "REQUEST_FAILED");
}
};
}
function jsonError(status: number, code: string, extraHeaders?: HeadersInit): Response {
const headers = new Headers(extraHeaders);
headers.set("cache-control", "private, no-store");
return Response.json({ code }, { status, headers });
}
export const usageCollabHandler = createUsageCollabHandler({
requireAdmin,
setUsageCollab,
consumeRateLimit,
});
@@ -0,0 +1,3 @@
import { usageCollabHandler } from "./collab-handler";
export const POST = usageCollabHandler;
+153 -4
View File
@@ -471,16 +471,21 @@ a {
min-width: 0;
}
/* Header logos use the trimmed variants (logo-*-header.png): the originals
carry large transparent/white margins that shrank the mark to a few pixels
under the old width+max-height letterboxing. Height-led sizing with a fixed
aspect ratio reserves layout space without intrinsic width/height attrs. */
.brand-logo {
display: block;
width: min(10rem, 35vw);
height: auto;
max-height: 2.5rem;
height: 2.25rem;
width: auto;
max-width: min(12rem, 40vw);
object-fit: contain;
transition: opacity 0.2s ease;
}
.brand-logo-dark { display: none; }
.brand-logo-light { aspect-ratio: 800 / 441; }
.brand-logo-dark { display: none; aspect-ratio: 194 / 104; }
.dark .brand-logo-light { display: none; }
.dark .brand-logo-dark { display: block; }
@@ -1074,6 +1079,26 @@ a {
font-size: 0.9rem;
}
/* Photographer's description in the lightbox. Full caption width, scrollable
when long, so the image keeps the focus and the text stays readable. */
.lightbox-description {
flex-basis: 100%;
max-width: 62ch;
max-height: 24vh;
margin: 0;
overflow-y: auto;
color: rgb(255 255 255 / 88%);
font-size: 0.85rem;
line-height: 1.5;
text-align: left;
white-space: pre-line;
overflow-wrap: break-word;
}
.lightbox-figure-described .lightbox-image {
max-height: 60vh;
}
.lightbox-actions {
display: flex;
align-items: center;
@@ -1310,6 +1335,37 @@ a {
white-space: nowrap;
}
.usage-collab-option {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: 0.9rem;
padding: 0.9rem 0;
border-bottom: 1px solid var(--line);
cursor: pointer;
}
.usage-collab-option input {
width: 1.05rem;
height: 1.05rem;
accent-color: var(--ink);
}
.usage-collab-option span {
display: grid;
gap: 0.2rem;
min-width: 0;
}
.usage-collab-option strong {
font-size: 0.875rem;
}
.usage-collab-option small {
color: var(--metadata);
font-size: 0.7rem;
}
.usage-purpose {
display: grid;
gap: 0.5rem;
@@ -2215,6 +2271,99 @@ a {
background: var(--soft);
}
.billing-collab-badge {
display: inline-block;
margin-left: 0.5rem;
padding: 0.1rem 0.5rem;
border: 1px solid var(--line);
border-radius: 999px;
font-size: 0.65rem;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--metadata);
}
.billing-collab-toggle {
display: block;
margin-top: 0.35rem;
padding: 0;
border: 0;
background: transparent;
color: var(--metadata);
font-size: 0.7rem;
font-weight: 600;
text-decoration: underline;
cursor: pointer;
}
.billing-collab-toggle:hover:not(:disabled) {
color: var(--ink);
}
.billing-collab-toggle:disabled {
opacity: 0.5;
cursor: default;
}
.billing-invoice-block {
margin-top: 1rem;
padding: 0.9rem 1rem;
border: 1px solid var(--line);
background: var(--soft);
}
.billing-invoice-status {
margin: 0 0 0.6rem;
font-size: 0.8rem;
font-weight: 650;
}
.billing-invoice-form label {
display: grid;
gap: 0.35rem;
font-size: 0.75rem;
font-weight: 650;
}
.billing-invoice-form input[type="file"] {
font-size: 0.8rem;
font-weight: 400;
}
.billing-invoice-controls {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 0.6rem;
}
.billing-invoice-controls button {
padding: 0.45rem 0.9rem;
border: 1px solid var(--ink);
background: var(--ink);
color: var(--paper);
font-size: 0.75rem;
font-weight: 650;
cursor: pointer;
}
.billing-invoice-controls button[type="button"] {
background: transparent;
color: var(--ink);
}
.billing-invoice-controls button:disabled {
opacity: 0.5;
cursor: default;
}
.billing-invoice-form .form-note {
margin: 0.6rem 0 0;
font-size: 0.7rem;
color: var(--metadata);
}
/* ------------------------------------------------------------------ */
/* Danger Zone & Status Actions */
/* ------------------------------------------------------------------ */
+25 -5
View File
@@ -1,9 +1,10 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { recordActivity } from "@/modules/activity/service";
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
import { formatCount, PhotoPagination } from "@/modules/albums/catalog-content";
import { filterPhotos, paginatePhotos } from "@/modules/albums/filter";
import { filterPhotos, normalizeSort, paginatePhotos, sortPhotos } from "@/modules/albums/filter";
import { PhotoGallery } from "@/modules/albums/photo-gallery";
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
import { lightboxService } from "@/modules/lightbox/service";
@@ -19,7 +20,7 @@ const ALBUM_FETCH_SIZE = 1000;
type AlbumPageProps = Readonly<{
params: Promise<{ albumId: string }>;
searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[] }>;
searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[]; sortierung?: string | string[] }>;
}>;
export default async function AlbumPage({ params, searchParams }: AlbumPageProps) {
@@ -31,6 +32,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
const query = normalizedQuery(singleValue(rawSearchParams.suche));
const format = singleValue(rawSearchParams.format);
const jahr = singleValue(rawSearchParams.jahr);
const sortierung = normalizeSort(singleValue(rawSearchParams.sortierung));
const result = await loadAlbumPage({
editorialId: principal.editorialId,
albumId,
@@ -38,6 +40,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
page: singleValue(rawSearchParams.page),
format,
jahr,
sortierung,
});
if (result.unavailable) {
@@ -47,6 +50,13 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
notFound();
}
await recordActivity({
editorialId: principal.editorialId,
type: query ? "search" : "album_view",
albumId: result.album.id,
...(query ? { query } : {}),
});
return (
<section className="editorial-section" aria-labelledby="album-title">
<PageHeader
@@ -58,7 +68,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
Alle Alben
</Link>
</PageHeader>
<AlbumSearchForm albumId={result.album.id} query={query} format={format} />
<AlbumSearchForm albumId={result.album.id} query={query} format={format} sortierung={sortierung} />
<p aria-live="polite" className="result-summary" role="status">
{formatCount(result.page.total, "Foto")} gefunden
</p>
@@ -76,12 +86,13 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
query={query}
format={format}
jahr={jahr}
sortierung={sortierung}
/>
</section>
);
}
function AlbumSearchForm({ albumId, query, format }: { albumId: string; query: string; format?: string; }) {
function AlbumSearchForm({ albumId, query, format, sortierung }: { albumId: string; query: string; format?: string; sortierung: string; }) {
return (
<form
action={`/redaktion/alben/${albumId}`}
@@ -109,6 +120,13 @@ function AlbumSearchForm({ albumId, query, format }: { albumId: string; query: s
<option value="hoch">Hochformat</option>
</select>
</label>
<label className="album-search-select">
<span>Sortierung</span>
<select name="sortierung" defaultValue={sortierung}>
<option value="neueste">Neueste zuerst</option>
<option value="aelteste">Älteste zuerst</option>
</select>
</label>
<button type="submit">Suchen</button>
</div>
</form>
@@ -122,6 +140,7 @@ async function loadAlbumPage({
page,
format,
jahr,
sortierung,
}: {
editorialId: string;
albumId: string;
@@ -129,6 +148,7 @@ async function loadAlbumPage({
page: string | undefined;
format?: string;
jahr?: string;
sortierung: ReturnType<typeof normalizeSort>;
}) {
try {
const albums = await albumCatalog.getVisibleAlbums(editorialId);
@@ -147,7 +167,7 @@ async function loadAlbumPage({
// total, the page slice, and the has-more-pages signal all reflect the
// active filters. The old code filtered a single 60-item page client-side,
// which silently dropped matching photos and reported the unfiltered total.
const filtered = filterPhotos(results.items, { format, jahr });
const filtered = sortPhotos(filterPhotos(results.items, { format, jahr }), sortierung);
const { result: resultPage, currentPage } = paginatePhotos(filtered, page, PHOTO_PAGE_SIZE);
const downloadOptions = await loadEditorialDownloadOptions(
+23 -14
View File
@@ -1,6 +1,7 @@
import { recordActivity } from "@/modules/activity/service";
import { AlbumCatalogError, albumCatalog, PHOTO_PAGE_SIZE } from "@/modules/albums/catalog";
import { AlbumContactSheet, formatCount } from "@/modules/albums/catalog-content";
import { filterPhotos, paginatePhotos, type InAppPage } from "@/modules/albums/filter";
import { filterPhotos, normalizeSort, paginatePhotos, sortPhotos, type InAppPage, type PhotoSort } from "@/modules/albums/filter";
import { PhotoGallery } from "@/modules/albums/photo-gallery";
import { AnnouncementBanner } from "@/modules/announcements/announcement-banner";
import { announcementService } from "@/modules/announcements/service";
@@ -17,12 +18,13 @@ import { requireEditorial } from "../access";
// up to 1000 matching photos, then filters/paginates in-app.
const SEARCH_FETCH_SIZE = 1000;
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[] }> }) {
export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[]; sortierung?: string | string[] }> }) {
const principal = await requireEditorial();
const rawSearchParams = await searchParams;
const query = normalizedQuery(singleValue(rawSearchParams.suche));
const format = singleValue(rawSearchParams.format);
const jahr = singleValue(rawSearchParams.jahr);
const sortierung = normalizeSort(singleValue(rawSearchParams.sortierung));
const hints = await announcementService.listActiveAnnouncements(new Date());
if (query) {
@@ -35,12 +37,14 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
});
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "RATE_LIMITED") {
return <SearchRateLimited query={query} format={format} jahr={jahr} />;
return <SearchRateLimited query={query} format={format} jahr={jahr} sortierung={sortierung} />;
}
throw error;
}
const filtered = filterPhotos(results.items, { format, jahr });
await recordActivity({ editorialId: principal.editorialId, type: "search", query });
const filtered = sortPhotos(filterPhotos(results.items, { format, jahr }), sortierung);
const { result: page, currentPage } = paginatePhotos(filtered, singleValue(rawSearchParams.page), PHOTO_PAGE_SIZE);
const downloadOptions = await loadEditorialDownloadOptions(
@@ -58,7 +62,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
titleId="albums-title"
/>
<AnnouncementBanner items={hints} />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<GlobalSearchForm query={query} format={format} jahr={jahr} sortierung={sortierung} />
<p aria-live="polite" className="result-summary" role="status">
{formatCount(page.total, "Foto")} gefunden
</p>
@@ -69,7 +73,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
lightboxAssetIds={[...lightboxAssetIds]}
showAlbumName
/>
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} />
<GlobalSearchPagination currentPage={currentPage} page={page} query={query} format={format} jahr={jahr} sortierung={sortierung} />
</div>
);
}
@@ -89,7 +93,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
description="Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen."
/>
<AnnouncementBanner items={hints} />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<GlobalSearchForm query={query} format={format} jahr={jahr} sortierung={sortierung} />
{result.albums.length === 0 ? (
<p className="text-muted-foreground text-center py-12">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
) : (
@@ -99,11 +103,11 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
);
}
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
function SearchRateLimited({ query, format, jahr, sortierung }: { query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
return (
<div className="space-y-6 max-w-7xl" aria-labelledby="albums-title">
<PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" />
<GlobalSearchForm query={query} format={format} jahr={jahr} />
<GlobalSearchForm query={query} format={format} jahr={jahr} sortierung={sortierung} />
<p className="bg-muted p-4 rounded-md" role="status">
Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut.
</p>
@@ -111,7 +115,7 @@ function SearchRateLimited({ query, format, jahr }: { query: string; format?: st
);
}
function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) {
function GlobalSearchForm({ query, format, jahr, sortierung }: { query: string; format?: string; jahr?: string; sortierung: PhotoSort; }) {
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
@@ -138,13 +142,17 @@ function GlobalSearchForm({ query, format, jahr }: { query: string; format?: str
<option key={y} value={y.toString()}>{y}</option>
))}
</select>
<select name="sortierung" defaultValue={sortierung} aria-label="Sortierung" className="flex h-10 w-full items-center justify-between rounded-md border border-border bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50">
<option value="neueste">Neueste zuerst</option>
<option value="aelteste">Älteste zuerst</option>
</select>
<Button type="submit" variant="default">Suchen</Button>
</div>
</form>
);
}
function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string }) {
function GlobalSearchPagination({ currentPage, page, query, format, jahr, sortierung }: { currentPage: number; page: InAppPage; query: string; format?: string; jahr?: string; sortierung: PhotoSort }) {
const hasPrev = currentPage > 1;
const hasNext = page.nextPage !== null;
if (!hasPrev && !hasNext) {
@@ -154,19 +162,20 @@ function GlobalSearchPagination({ currentPage, page, query, format, jahr }: { cu
return (
<nav aria-label="Suchergebnisseiten" className="flex justify-between items-center mt-8 pt-4 border-t border-border text-sm font-medium">
{hasPrev ? (
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage - 1, query, format, jahr)}>Vorherige Seite</Link>
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage - 1, query, format, jahr, sortierung)}>Vorherige Seite</Link>
) : <div />}
{hasNext ? (
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage + 1, query, format, jahr)}>Nächste Seite</Link>
<Link className="text-primary-600 hover:underline" href={globalPageHref(currentPage + 1, query, format, jahr, sortierung)}>Nächste Seite</Link>
) : <div />}
</nav>
);
}
function globalPageHref(page: number, query: string, format?: string, jahr?: string): string {
function globalPageHref(page: number, query: string, format?: string, jahr?: string, sortierung?: PhotoSort): string {
const parameters = new URLSearchParams({ suche: query, page: String(page) });
if (format) parameters.set("format", format);
if (jahr) parameters.set("jahr", jahr);
if (sortierung === "aelteste") parameters.set("sortierung", sortierung);
return `/redaktion/alben?${parameters.toString()}`;
}
@@ -0,0 +1,71 @@
"use client";
import { useState, useTransition } from "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);
}
});
};
const base =
"min-h-11 rounded-md border px-4 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50";
const active = "border-primary-600 bg-primary-600 text-white";
const inactive = "border-border bg-background hover:bg-accent";
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"
className={`${base} ${response === "attending" ? active : inactive}`}
aria-pressed={response === "attending"}
disabled={pending}
onClick={() => respond("attending")}
>
Bin da
</button>
<button
type="button"
className={`${base} ${response === "not_attending" ? active : inactive}`}
aria-pressed={response === "not_attending"}
disabled={pending}
onClick={() => respond("not_attending")}
>
Bin nicht da
</button>
</div>
{error ? (
<p role="alert" className="text-xs text-destructive">
{error}
</p>
) : null}
</div>
);
}
@@ -0,0 +1,47 @@
"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>
);
}
+89
View File
@@ -0,0 +1,89 @@
"use server";
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";
export type CalendarActionResult = {
ok: boolean;
message: string;
albumId?: string;
};
export async function respondToEventAction(
_prevState: CalendarActionResult,
formData: FormData,
): Promise<CalendarActionResult> {
const principal = await requireActiveEditorial(new Headers(await headers()));
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: "" };
}
export async function selfGrantAlbumAction(
_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." };
}
let albumId: string;
try {
const album = await calendarService.selfGrantAlbum({
eventId,
editorialId: principal.editorialId,
actorUserId: principal.userId,
});
albumId = album.id;
} catch (error) {
return { ok: false, message: calendarErrorMessage(error) };
}
revalidatePath("/redaktion/kalender");
revalidatePath("/redaktion/alben");
revalidatePath(`/redaktion/alben/${albumId}`);
return { ok: true, message: "", albumId };
}
function calendarErrorMessage(error: unknown): string {
if (error instanceof CalendarServiceError) {
const messages: Record<CalendarServiceError["code"], string> = {
INVALID_TITLE: "Ungültiger Termin.",
INVALID_EVENT_DATE: "Ungültiger Termin.",
INVALID_ALBUM: "Ungültiger Termin.",
INVALID_STATUS: "Ungültige Rückmeldung.",
EVENT_NOT_FOUND: "Dieser Termin existiert nicht mehr.",
EVENT_ALBUM_UNAVAILABLE: "Zu diesem Termin ist noch kein Album verfügbar.",
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 "Die Aktion konnte nicht ausgeführt werden.";
}
+84
View File
@@ -0,0 +1,84 @@
import Link from "next/link";
import { PageHeader } from "@/components/ui/page-header";
import { formatIsoDateGerman, isoDateInBerlin } from "@/modules/announcements/service";
import { calendarService } from "@/modules/calendar/service";
import { requireEditorial } from "../access";
import { EventRsvpButtons } from "./EventRsvpButtons";
import { SelfGrantButton } from "./SelfGrantButton";
import { respondToEventAction, selfGrantAlbumAction } from "./actions";
export default async function EditorialCalendarPage() {
const principal = await requireEditorial();
const { events, immichUnavailable } = await calendarService.listEditorialEvents(
principal.editorialId,
new Date(),
);
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];
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="calendar-title">
<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."
/>
{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>
) : 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>
) : (
<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>
)}
</div>
);
}
+2
View File
@@ -13,8 +13,10 @@ export default async function EditorialLayout({ children }: Readonly<{ children:
sectionLabel="Redaktionsarchiv"
nav={[
{ href: "/redaktion/alben", label: "Alben" },
{ href: "/redaktion/kalender", label: "Kalender" },
{ href: "/redaktion/leuchtkasten", label: "Merkzettel" },
{ href: "/redaktion/nutzungen", label: "Nutzungen" },
{ href: "/redaktion/neuigkeiten", label: "Neuigkeiten" },
{ href: "/redaktion/profil", label: "Profil" },
]}
>
@@ -3,10 +3,17 @@
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
export function DownloadLightboxForm({
assetIds,
collabEnabled = false,
}: {
assetIds: string[];
collabEnabled?: boolean;
}) {
const [loading, setLoading] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null);
const [purpose, setPurpose] = useState("");
const [collab, setCollab] = useState(false);
const router = useRouter();
async function handleBulkDownload(e: React.FormEvent) {
@@ -19,7 +26,7 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
const response = await fetch("/api/lightbox/bulk-download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ assetIds, purpose }),
body: JSON.stringify({ assetIds, purpose, ...(collab ? { collab: true } : {}) }),
});
if (!response.ok) {
@@ -50,6 +57,7 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
dialogRef.current?.close();
setPurpose("");
setCollab(false);
router.refresh(); // Refresh to update usage history
} catch (err) {
const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
@@ -95,8 +103,25 @@ export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
disabled={loading}
/>
</div>
{collabEnabled ? (
<label className="flex items-start gap-3 rounded-md border border-border bg-muted/40 p-3 cursor-pointer">
<input
type="checkbox"
checked={collab}
onChange={(e) => setCollab(e.target.checked)}
disabled={loading}
className="mt-0.5 h-4 w-4 rounded border-border text-primary-600 focus:ring-primary-500"
/>
<span className="text-sm">
<span className="font-medium">Collab-Nutzung (kostenfrei)</span>
<span className="block text-xs text-muted-foreground">
Alle {assetIds.length} Bilder werden mit 0,00 € in der Abrechnung geführt.
</span>
</span>
</label>
) : null}
</div>
<div className="mt-8 flex justify-end gap-3">
<button
type="button"
+17 -2
View File
@@ -1,16 +1,28 @@
/* eslint-disable @next/next/no-img-element */
import { eq } from "drizzle-orm";
import { PageHeader } from "@/components/ui/page-header";
import { lightboxService } from "@/modules/lightbox/service";
import { immichClient } from "@/modules/immich/client";
import Link from "next/link";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton";
import { DownloadLightboxForm } from "./DownloadLightboxForm";
import { requireEditorial } from "../access";
export default async function LightboxPage() {
const principal = await requireEditorial();
const items = await lightboxService.getLightboxItems(principal.editorialId);
const [items, editorial] = await Promise.all([
lightboxService.getLightboxItems(principal.editorialId),
db
.select({ collabEnabled: editorialAccounts.collabEnabled })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, principal.editorialId))
.limit(1)
.then((rows) => rows[0]),
]);
// Fetch asset details for all items in the lightbox
const assets = items.length > 0
@@ -35,7 +47,10 @@ export default async function LightboxPage() {
<p className="text-sm font-medium text-muted-foreground">
{items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt
</p>
<DownloadLightboxForm assetIds={items.map(i => i.assetId)} />
<DownloadLightboxForm
assetIds={items.map(i => i.assetId)}
collabEnabled={editorial?.collabEnabled === true}
/>
</div>
<ul className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
+40
View File
@@ -0,0 +1,40 @@
import { PageHeader } from "@/components/ui/page-header";
import { releaseNoteService } from "@/modules/releases/service";
import { requireEditorial } from "../access";
export default async function EditorialNewsPage() {
await requireEditorial();
const notes = await releaseNoteService.listEditorialReleaseNotes();
return (
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500" aria-labelledby="news-title">
<PageHeader
kicker="Portal · Versionshinweise"
title="Neuigkeiten"
titleId="news-title"
description="Was sich im Redaktionsportal geändert hat, neueste Version zuerst."
/>
{notes.length === 0 ? (
<p className="text-muted-foreground text-center py-12">
Noch keine Versionshinweise vorhanden.
</p>
) : (
<ul className="space-y-3">
{notes.map((note) => (
<li key={note.id} className="bg-card p-4 rounded-xl border border-border shadow-sm space-y-1">
<p className="text-sm font-semibold">
Version {note.version}
<span className="ml-2 text-xs font-normal text-muted-foreground">
{new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(note.createdAt)}
</span>
</p>
<p className="text-sm whitespace-pre-line break-words">{note.body}</p>
</li>
))}
</ul>
)}
</div>
);
}
+2 -2
View File
@@ -6,12 +6,12 @@ export function BrandLogo() {
<img
alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-light"
src="/brand/logo-black.png"
src="/brand/logo-black-header.png"
/>
<img
alt="Leon Tonhäuser Sportfotografie"
className="brand-logo brand-logo-dark"
src="/brand/logo-white.png"
src="/brand/logo-white-header.png"
/>
</>
);
@@ -107,6 +107,58 @@ test("reuses one idempotency key when the same failed submission is retried", as
}
});
test("collab checkbox only appears for enabled editorials and sends collab with price 0", async () => {
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
const fetch = vi.fn().mockResolvedValue(
Response.json({
downloadId: "66666666-6666-4666-8666-666666666666",
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
priceCents: 0,
billable: true,
}),
);
vi.stubGlobal("fetch", fetch);
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
const { unmount } = render(
<UsageDialog
albumId="33333333-3333-4333-8333-333333333333"
assetId="22222222-2222-4222-8222-222222222222"
filename="tor-des-monats.jpg"
newUsagePriceCents={1_500}
priorUsages={[]}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
expect(screen.queryByRole("checkbox", { name: /collab/i })).toBeNull();
unmount();
render(
<UsageDialog
albumId="33333333-3333-4333-8333-333333333333"
assetId="22222222-2222-4222-8222-222222222222"
filename="tor-des-monats.jpg"
newUsagePriceCents={1_500}
priorUsages={[]}
collabEnabled
/>,
);
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
const checkbox = screen.getByRole("checkbox", { name: /collab-nutzung \(kostenfrei\)/i });
fireEvent.click(checkbox);
expect(screen.getByText("0,00 €")).not.toBeNull();
fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), {
target: { value: "Collab Strecke" },
});
fireEvent.click(screen.getByRole("button", { name: /download anfordern/i }));
await waitFor(() => expect(fetch).toHaveBeenCalledOnce());
expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toMatchObject({
kind: "new_usage",
collab: true,
});
});
test("suppresses double-click submission while one request is pending", async () => {
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
let resolveRequest: ((response: Response) => void) | undefined;
+26 -1
View File
@@ -11,6 +11,7 @@ type UsageDialogProps = Readonly<{
filename: string;
newUsagePriceCents: number;
priorUsages: DownloadDialogUsage[];
collabEnabled?: boolean;
}>;
type IntentResponse = {
@@ -31,18 +32,21 @@ export function UsageDialog({
filename,
newUsagePriceCents,
priorUsages,
collabEnabled = false,
}: UsageDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
const firstChoiceRef = useRef<HTMLInputElement>(null);
const idempotencyKeyRef = useRef<string | null>(null);
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
const [choice, setChoice] = useState(initialChoice);
const [collab, setCollab] = useState(false);
const [purpose, setPurpose] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
function openDialog() {
setChoice(initialChoice);
setCollab(false);
setPurpose("");
setPending(false);
setError(null);
@@ -79,6 +83,7 @@ export function UsageDialog({
albumId,
purpose,
idempotencyKey: idempotencyKeyRef.current,
...(collab ? { collab: true } : {}),
};
try {
@@ -175,10 +180,28 @@ export function UsageDialog({
<strong>Neue Nutzung</strong>
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
</span>
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
<b>{priceFormatter.format((collab ? 0 : newUsagePriceCents) / 100)}</b>
</label>
</fieldset>
{collabEnabled && isNewUsage ? (
<label className="usage-collab-option">
<input
checked={collab}
disabled={pending}
onChange={(event) => {
setCollab(event.target.checked);
resetSubmission();
}}
type="checkbox"
/>
<span>
<strong>Collab-Nutzung (kostenfrei)</strong>
<small>Diese Nutzung wird mit 0,00 € in der Abrechnung geführt.</small>
</span>
</label>
) : null}
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
Verwendungszweck
<textarea
@@ -242,6 +265,8 @@ function downloadErrorMessage(code: string | null, status: number): string {
switch (code) {
case "FORBIDDEN":
return "Ihr Konto ist nicht freigegeben oder gesperrt.";
case "COLLAB_NOT_ENABLED":
return "Collab-Nutzung ist für Ihr Konto nicht freigeschaltet. Bitte den Admin, die Option zu aktivieren.";
case "INVALID_REQUEST":
return "Die Anfrage war unvollständig. Bitte laden Sie die Seite neu und versuchen Sie es erneut.";
case "IDEMPOTENCY_CONFLICT":
+2 -2
View File
@@ -36,8 +36,8 @@ export function PortalShell({
<div className="flex items-center"><BrandLogo /></div>
</Link>
<div className="flex items-center gap-6 text-sm font-medium">
<span className="hidden md:inline-block text-muted-foreground uppercase tracking-widest text-xs font-bold">{sectionLabel}</span>
<nav aria-label={sectionLabel} className="hidden sm:flex items-center gap-6">
<span className="hidden lg:inline-block text-muted-foreground uppercase tracking-widest text-xs font-bold">{sectionLabel}</span>
<nav aria-label={sectionLabel} className="hidden sm:flex items-center gap-4 lg:gap-6">
{nav.map((item) => (
<Link
key={item.href}
+34
View File
@@ -0,0 +1,34 @@
import { sql } from "drizzle-orm";
import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { editorialAccounts } from "./editorials";
// Lightweight editorial activity trail for the admin statistics page.
// Downloads/usages are NOT duplicated here; they already live in their own
// accounting tables. This table only captures browsing behaviour.
export const activityEvents = pgTable(
"activity_events",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
eventType: text("event_type").notNull(),
immichAlbumId: text("immich_album_id"),
immichAssetId: text("immich_asset_id"),
query: text("query"),
occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index("activity_events_occurred_at_idx").on(table.occurredAt.desc()),
index("activity_events_editorial_occurred_idx").on(
table.editorialAccountId,
table.occurredAt.desc(),
),
index("activity_events_type_occurred_idx").on(table.eventType, table.occurredAt.desc()),
check(
"activity_events_event_type_check",
sql`${table.eventType} in ('album_view', 'search', 'lightbox_view')`,
),
],
);
+6
View File
@@ -17,6 +17,11 @@ export const albumGrants = pgTable(
grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
// How the grant came to be: manual admin assignment, an auto-rule sync,
// or editorial self-service via the event calendar. Self-service grants
// are revocable in bulk when their calendar event is deleted; auto-rule
// and admin grants are never touched by the calendar.
source: text("source").notNull().default("admin"),
},
(table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
@@ -28,5 +33,6 @@ export const albumGrants = pgTable(
"album_grants_immich_album_id_uuid_check",
sql`${table.immichAlbumId} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
),
check("album_grants_source_check", sql`${table.source} in ('admin', 'auto_rule', 'self_service')`),
],
);
+19
View File
@@ -1,5 +1,6 @@
import { sql } from "drizzle-orm";
import {
boolean,
check,
customType,
integer,
@@ -43,6 +44,15 @@ export const billingReports = pgTable(
status: reportStatus("status").notNull().default("draft"),
pdf: bytea("pdf"),
pdfSha256: varchar("pdf_sha256", { length: 64 }),
// The actual VAT invoice is uploaded by the admin AFTER finalization.
// Uploading it triggers the bundled email (invoice + Nutzungsnachweis).
invoicePdf: bytea("invoice_pdf"),
invoicePdfSha256: varchar("invoice_pdf_sha256", { length: 64 }),
invoicePdfFilename: text("invoice_pdf_filename"),
invoiceUploadedAt: timestamp("invoice_uploaded_at", { withTimezone: true }),
invoiceEmailStatus: text("invoice_email_status").notNull().default("not_sent"),
invoiceEmailSentAt: timestamp("invoice_email_sent_at", { withTimezone: true }),
invoiceEmailError: text("invoice_email_error"),
createdByUserId: uuid("created_by_user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
@@ -58,6 +68,14 @@ export const billingReports = pgTable(
uniqueIndex("billing_reports_report_number_unique").on(table.reportNumber),
uniqueIndex("billing_reports_invoice_number_unique").on(table.invoiceNumber),
check("billing_reports_pdf_sha256_hex_check", sql`${table.pdfSha256} ~ '^[0-9a-f]{64}$'`),
check(
"billing_reports_invoice_pdf_sha256_hex_check",
sql`${table.invoicePdfSha256} IS NULL OR ${table.invoicePdfSha256} ~ '^[0-9a-f]{64}$'`,
),
check(
"billing_reports_invoice_email_status_check",
sql`${table.invoiceEmailStatus} in ('not_sent', 'sent', 'failed')`,
),
check(
"billing_reports_final_pdf_check",
sql`${table.status} <> 'final' OR (${table.pdf} IS NOT NULL AND ${table.pdfSha256} IS NOT NULL)`,
@@ -81,6 +99,7 @@ export const billingReportItems = pgTable(
purposeSnapshot: text("purpose_snapshot").notNull(),
internalReferenceSnapshot: text("internal_reference_snapshot"),
priceCents: integer("price_cents").notNull(),
collab: boolean("collab").notNull().default(false),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
+42
View File
@@ -0,0 +1,42 @@
import { sql } from "drizzle-orm";
import { check, date, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
import { editorialAccounts } from "./editorials";
// Admin-managed event calendar (e.g. upcoming matches). An event links to an
// Immich album either explicitly (immichAlbumId) or by exact name match once
// 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.
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"),
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",
{
id: uuid("id").defaultRandom().primaryKey(),
eventId: uuid("event_id")
.notNull()
.references(() => calendarEvents.id, { onDelete: "restrict" }),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
status: text("status").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("event_responses_event_editorial_unique").on(table.eventId, table.editorialAccountId),
check("event_responses_status_check", sql`${table.status} in ('attending', 'not_attending')`),
],
);
+1
View File
@@ -26,6 +26,7 @@ export const editorialAccounts = pgTable("editorial_accounts", {
flatrateActive: boolean("flatrate_active").notNull().default(false),
flatratePriceCents: integer("flatrate_price_cents"),
flatrateAssetLimit: integer("flatrate_asset_limit"),
collabEnabled: boolean("collab_enabled").notNull().default(false),
approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"),
currentBillingAddressVersionId: uuid("current_billing_address_version_id").references(
(): AnyPgColumn => billingAddressVersions.id,
+3
View File
@@ -1,10 +1,13 @@
export * from "./activity";
export * from "./albums";
export * from "./announcements";
export * from "./audit";
export * from "./auth";
export * from "./auto-rules";
export * from "./billing";
export * from "./calendar";
export * from "./editorials";
export * from "./lightbox";
export * from "./rate-limits";
export * from "./releases";
export * from "./usages";
+27
View File
@@ -0,0 +1,27 @@
import { sql } from "drizzle-orm";
import { check, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
// Version notes ("Versionshinweise") maintained by the admin. One row per
// version and audience, so a release can carry separate notes for admins and
// editorial users. The editorial portal shows rows with audience 'editorial'
// or 'both'; the admin overview shows everything.
export const releaseNotes = pgTable(
"release_notes",
{
id: uuid("id").defaultRandom().primaryKey(),
version: text("version").notNull(),
audience: text("audience").notNull().default("both"),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
},
(table) => [
uniqueIndex("release_notes_version_audience_unique").on(table.version, table.audience),
check("release_notes_audience_check", sql`${table.audience} in ('admin', 'editorial', 'both')`),
check("release_notes_version_check", sql`${table.version} ~ '^[0-9]+\\.[0-9]+(\\.[0-9]+)?$'`),
],
);
+1
View File
@@ -43,6 +43,7 @@ export const usages = pgTable(
purpose: text("purpose").notNull(),
internalReference: text("internal_reference"),
priceCents: integer("price_cents").notNull(),
collab: boolean("collab").notNull().default(false),
billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
onDelete: "restrict",
+84
View File
@@ -0,0 +1,84 @@
import { expect, test, vi } from "vitest";
import { createActivityService, normalizeActivityInput } from "./service";
import type { RateLimitPolicy, RateLimitResult } from "@/modules/security/rate-limit";
type Consume = (key: string, policy: RateLimitPolicy) => Promise<RateLimitResult>;
const editorialId = "1111111a-1111-4111-8111-11111111111a";
const albumId = "2222222b-2222-4222-8222-22222222222b";
test("normalizeActivityInput validates ids, types and query length", () => {
expect(
normalizeActivityInput({ editorialId, type: "album_view", albumId }),
).toEqual({ editorialId, type: "album_view", albumId });
expect(normalizeActivityInput({ editorialId: "nope", type: "album_view" })).toBeNull();
expect(
normalizeActivityInput({ editorialId, type: "download" as never }),
).toBeNull();
expect(
normalizeActivityInput({ editorialId, type: "search", albumId: "bad id" }),
).toBeNull();
const normalized = normalizeActivityInput({
editorialId: editorialId.toUpperCase(),
type: "search",
query: ` wob ${"x".repeat(300)} `,
});
expect(normalized?.editorialId).toBe(editorialId);
expect(normalized?.query?.length).toBeLessThanOrEqual(200);
expect(normalized?.query?.startsWith("wob")).toBe(true);
});
function createService(overrides: {
consume?: ReturnType<typeof vi.fn>;
insert?: ReturnType<typeof vi.fn>;
editorialExists?: boolean;
} = {}) {
const insert = overrides.insert ?? vi.fn().mockResolvedValue(undefined);
const consume = (overrides.consume ??
vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 })) as Consume;
const database = {
select: vi.fn().mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue(
overrides.editorialExists === false ? [] : [{ id: editorialId }],
),
}),
}),
}),
insert: vi.fn().mockReturnValue({ values: insert }),
};
return {
service: createActivityService({ database: database as never, consume }),
insert,
consume,
};
}
test("record inserts a normalized activity row", async () => {
const { service, insert } = createService();
await service.record({ editorialId, type: "search", albumId, query: " wob " });
expect(insert).toHaveBeenCalledWith({
editorialAccountId: editorialId,
eventType: "search",
immichAlbumId: albumId,
immichAssetId: null,
query: "wob",
});
});
test("record stays silent when rate-limited, unknown editorial or DB fails", async () => {
const limited = createService({
consume: vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 10 }),
});
await limited.service.record({ editorialId, type: "album_view" });
expect(limited.insert).not.toHaveBeenCalled();
const unknown = createService({ editorialExists: false });
await unknown.service.record({ editorialId, type: "album_view" });
expect(unknown.insert).not.toHaveBeenCalled();
const broken = createService({ insert: vi.fn().mockRejectedValue(new Error("db down")) });
await expect(broken.service.record({ editorialId, type: "album_view" })).resolves.toBeUndefined();
});
+83
View File
@@ -0,0 +1,83 @@
import "server-only";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { activityEvents, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { activityPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
export const ACTIVITY_EVENT_TYPES = ["album_view", "search", "lightbox_view"] as const;
export type ActivityEventType = (typeof ACTIVITY_EVENT_TYPES)[number];
export type RecordActivityInput = {
editorialId: string;
type: ActivityEventType;
albumId?: string;
assetId?: string;
query?: string;
};
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;
export function normalizeActivityInput(input: RecordActivityInput): RecordActivityInput | null {
if (!UUID_PATTERN.test(input.editorialId)) return null;
if (!ACTIVITY_EVENT_TYPES.includes(input.type)) return null;
if (input.albumId !== undefined && !UUID_PATTERN.test(input.albumId)) return null;
if (input.assetId !== undefined && !UUID_PATTERN.test(input.assetId)) return null;
const query = input.query?.replace(/\s+/g, " ").trim().slice(0, 200);
return {
editorialId: input.editorialId.toLowerCase(),
type: input.type,
...(input.albumId === undefined ? {} : { albumId: input.albumId.toLowerCase() }),
...(input.assetId === undefined ? {} : { assetId: input.assetId.toLowerCase() }),
...(query ? { query } : {}),
};
}
export function createActivityService({
database,
consume,
}: {
database: NodePgDatabase<typeof schema>;
consume: typeof consumeRateLimit;
}) {
return {
/**
* Fire-and-forget browsing trail for the statistics page. Never throws and
* never blocks the page: invalid input, rate limits and DB errors are all
* swallowed. Downloads are NOT recorded here (see download_events).
*/
async record(rawInput: RecordActivityInput): Promise<void> {
try {
const input = normalizeActivityInput(rawInput);
if (!input) return;
const limit = await consume(`activity:${input.editorialId}`, activityPolicy);
if (!limit.allowed) return;
const [editorial] = await database
.select({ id: editorialAccounts.id })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
.limit(1);
if (!editorial) return;
await database.insert(activityEvents).values({
editorialAccountId: input.editorialId,
eventType: input.type,
immichAlbumId: input.albumId ?? null,
immichAssetId: input.assetId ?? null,
query: input.query ?? null,
});
} catch {
// Observability must never break the editorial experience.
}
},
};
}
export const activityService = createActivityService({
database: db,
consume: consumeRateLimit,
});
export const recordActivity = activityService.record;
+4 -1
View File
@@ -71,6 +71,9 @@ function createFakeGrantService(initial: FakeGrant[] = []) {
async revoke() {
return false;
},
async revokeSelfServiceForAlbum() {
return 0;
},
};
return { repository, grants, grantInputs };
}
@@ -258,6 +261,6 @@ test("applyRules keeps admin attribution for the manual per-editorial run", asyn
await expect(service.applyRules(editorialA, adminUuid)).resolves.toEqual({ granted: 1 });
expect(grantInputs).toEqual([
{ editorialId: editorialA, immichAlbumId: albumFcBayern, adminUserId: adminUuid },
{ editorialId: editorialA, immichAlbumId: albumFcBayern, adminUserId: adminUuid, source: "auto_rule" },
]);
});
+1
View File
@@ -78,6 +78,7 @@ export function createAutoRuleService({
editorialId: input.editorialId,
immichAlbumId: album.id,
adminUserId: input.adminUserId,
source: "auto_rule",
});
grantedAlbumIds.add(album.id);
newlyGrantedAlbumNames.push(album.albumName);
+2 -1
View File
@@ -56,6 +56,7 @@ test("renders the server-scoped download choices for a catalog photo", () => {
albumName="Heimspiel gegen Nord"
downloadOptions={{
priceCents: 1_500,
collabEnabled: false,
priorUsagesByAsset: {
"22222222-2222-4222-8222-222222222222": [
{
@@ -87,7 +88,7 @@ test("offers the existing download workflow on a global search result and its li
render(
<PhotoGallery
albumName="Alle Alben"
downloadOptions={{ priceCents: 100, priorUsagesByAsset: {} }}
downloadOptions={{ priceCents: 100, collabEnabled: false, priorUsagesByAsset: {} }}
items={[{
...photo,
id: "22222222-2222-4222-8222-222222222222",
+9 -2
View File
@@ -49,6 +49,7 @@ export function PhotoPagination({
query,
format,
jahr,
sortierung,
}: Readonly<{
albumId: string;
currentPage: number;
@@ -56,6 +57,7 @@ export function PhotoPagination({
query: string;
format?: string;
jahr?: string;
sortierung?: string;
}>) {
const hasPrev = currentPage > 1;
const hasNext = page.nextPage !== null;
@@ -65,8 +67,8 @@ export function PhotoPagination({
return (
<nav aria-label="Suchergebnisseiten" className="photo-pagination">
{hasPrev ? <Link href={pageHref(albumId, currentPage - 1, query, format, jahr)}>Vorherige Seite</Link> : null}
{hasNext ? <Link href={pageHref(albumId, currentPage + 1, query, format, jahr)}>Nächste Seite</Link> : null}
{hasPrev ? <Link href={pageHref(albumId, currentPage - 1, query, format, jahr, sortierung)}>Vorherige Seite</Link> : null}
{hasNext ? <Link href={pageHref(albumId, currentPage + 1, query, format, jahr, sortierung)}>Nächste Seite</Link> : null}
</nav>
);
}
@@ -81,6 +83,7 @@ export function pageHref(
query: string,
format?: string,
jahr?: string,
sortierung?: string,
): string {
const parameters = new URLSearchParams({ page: String(page) });
if (query) {
@@ -92,6 +95,10 @@ export function pageHref(
if (jahr) {
parameters.set("jahr", jahr);
}
// Newest-first is the default; only the flipped order needs to travel.
if (sortierung === "aelteste") {
parameters.set("sortierung", sortierung);
}
return `/redaktion/alben/${encodeURIComponent(albumId)}?${parameters.toString()}`;
}
+33
View File
@@ -62,6 +62,39 @@ test("uses a requested album only when it is in the current editorial grants", a
);
});
test("a query searches description and filename and merges deduplicated", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
const asset = (id: string, fileName: string) => ({
id,
type: "IMAGE" as const,
originalFileName: fileName,
originalMimeType: "image/jpeg",
localDateTime: null,
fileCreatedAt: null,
albums: [{ id: "allowed" }],
});
immich.searchPhotos.mockImplementation(async (input: { description?: string; originalFileName?: string }) => {
if (input.description) {
return { items: [asset("a1", "tor.jpg"), asset("a2", "jubel.jpg")], total: 2, nextPage: null, previousPage: null };
}
return { items: [asset("a2", "jubel.jpg"), asset("a3", "torjubel.jpg")], total: 2, nextPage: null, previousPage: null };
});
const result = await catalog.searchVisiblePhotos("editorial-1", {
requestedAlbumId: "allowed",
description: "tor",
page: 1,
});
expect(result.items.map((item) => item.id)).toEqual(["a1", "a2", "a3"]);
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["allowed"], description: "tor" }),
);
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["allowed"], originalFileName: "tor" }),
);
});
test("restores the queried granted album when Immich omits an asset album association", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
immich.searchPhotos.mockResolvedValue({
+34 -4
View File
@@ -79,7 +79,7 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
if (albumIds.length === 0) {
return emptySearchPage();
}
return searchAlbum(immich, albumIds, description, page, size);
return searchAlbumMerged(immich, albumIds, description, page, size);
}
// Cross-album search. Immich's `albumIds` filter is AND across albums —
@@ -94,24 +94,54 @@ export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }
const visibleIds = new Set((await loadAlbums(immich)).map(({ id }) => id));
const pages = await Promise.all(
grantedAlbumIds.filter((id) => visibleIds.has(id))
.map((albumId) => searchAlbum(immich, [albumId], description, page, size)),
.map((albumId) => searchAlbumMerged(immich, [albumId], description, page, size)),
);
return mergeSearchPages(pages);
},
};
}
async function searchAlbum(
/**
* A query matches the photographer description OR the original filename (the
* Merkzettel deep-links into the album search with filenames). Immich combines
* metadata filters with AND, so the two predicates run as separate searches
* and merge deduplicated. ponytail: two upstream calls per album when a query
* is present; bounded by the grant count and the per-album size cap.
*/
async function searchAlbumMerged(
immich: Pick<ImmichClient, "searchPhotos">,
albumIds: string[],
description: string | undefined,
page: number,
size: number,
): Promise<ImmichSearchPage> {
if (description === undefined) {
return searchAlbum(immich, albumIds, {}, page, size);
}
const [byDescription, byFileName] = await Promise.all([
searchAlbum(immich, albumIds, { description }, page, size),
searchAlbum(immich, albumIds, { originalFileName: description }, page, size),
]);
const seen = new Set<string>();
const items = [...byDescription.items, ...byFileName.items].filter((asset) => {
if (seen.has(asset.id)) return false;
seen.add(asset.id);
return true;
});
return { items, total: items.length, nextPage: null, previousPage: null };
}
async function searchAlbum(
immich: Pick<ImmichClient, "searchPhotos">,
albumIds: string[],
filter: { description?: string; originalFileName?: string },
page: number,
size: number,
): Promise<ImmichSearchPage> {
try {
const searchPage = await immich.searchPhotos({
albumIds,
...(description === undefined ? {} : { description }),
...filter,
type: "IMAGE",
page,
size,
+32 -1
View File
@@ -1,6 +1,6 @@
import { expect, test } from "vitest";
import { filterPhotos, matchesOrientation, matchesYear, paginatePhotos } from "./filter";
import { filterPhotos, matchesOrientation, matchesYear, normalizeSort, paginatePhotos, sortPhotos } from "./filter";
import type { ImmichAsset } from "@/modules/immich/types";
function photo(overrides: Partial<ImmichAsset> & { id: string }): ImmichAsset {
@@ -85,4 +85,35 @@ test("paginatePhotos handles an empty set without dividing by zero", () => {
expect(result.items).toEqual([]);
expect(result.nextPage).toBeNull();
expect(result.previousPage).toBeNull();
});
test("normalizeSort only accepts aelteste, everything else stays newest-first", () => {
expect(normalizeSort("aelteste")).toBe("aelteste");
expect(normalizeSort("neueste")).toBe("neueste");
expect(normalizeSort(undefined)).toBe("neueste");
expect(normalizeSort("DESC")).toBe("neueste");
expect(normalizeSort(["aelteste"])).toBe("neueste");
});
test("sortPhotos orders the whole set by capture date in both directions", () => {
const items = [
photo({ id: "mid", localDateTime: "2026-05-01T10:00:00.000Z" }),
photo({ id: "old", localDateTime: "2025-01-01T10:00:00.000Z" }),
photo({ id: "new", localDateTime: "2026-09-01T10:00:00.000Z" }),
];
expect(sortPhotos(items, "neueste").map((p) => p.id)).toEqual(["new", "mid", "old"]);
expect(sortPhotos(items, "aelteste").map((p) => p.id)).toEqual(["old", "mid", "new"]);
// Does not mutate the input order.
expect(items.map((p) => p.id)).toEqual(["mid", "old", "new"]);
});
test("sortPhotos falls back to fileCreatedAt and keeps undated assets last", () => {
const items = [
photo({ id: "undated", localDateTime: null, fileCreatedAt: null }),
photo({ id: "fallback", localDateTime: null, fileCreatedAt: "2026-02-01T00:00:00.000Z" }),
photo({ id: "dated", localDateTime: "2026-03-01T00:00:00.000Z" }),
photo({ id: "broken", localDateTime: "not-a-date", fileCreatedAt: null }),
];
expect(sortPhotos(items, "neueste").map((p) => p.id)).toEqual(["dated", "fallback", "undated", "broken"]);
expect(sortPhotos(items, "aelteste").map((p) => p.id)).toEqual(["fallback", "dated", "undated", "broken"]);
});
+31
View File
@@ -42,6 +42,37 @@ export function filterPhotos(
return filtered;
}
export type PhotoSort = "neueste" | "aelteste";
/** Only "aelteste" flips the order; anything else keeps the newest-first default. */
export function normalizeSort(value: unknown): PhotoSort {
return value === "aelteste" ? "aelteste" : "neueste";
}
/**
* Sort the fetched set by capture date before paginating, so the order holds
* across the whole result (and across merged per-album pages in the global
* search), not just within one upstream page. Assets without a usable date
* keep a stable order at the end in both directions.
*/
export function sortPhotos(items: ImmichAsset[], sort: PhotoSort): ImmichAsset[] {
const direction = sort === "aelteste" ? 1 : -1;
const timestamp = (asset: ImmichAsset): number | null => {
const value = asset.localDateTime ?? asset.fileCreatedAt;
if (!value) return null;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? null : parsed;
};
return [...items].sort((left, right) => {
const leftTime = timestamp(left);
const rightTime = timestamp(right);
if (leftTime === null && rightTime === null) return 0;
if (leftTime === null) return 1;
if (rightTime === null) return -1;
return (leftTime - rightTime) * direction;
});
}
export type InAppPage = {
items: ImmichAsset[];
total: number;
+57 -5
View File
@@ -11,7 +11,7 @@ import {
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null };
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null; source?: string };
type Audit = {
eventType: string;
actorUserId: string | null;
@@ -183,8 +183,14 @@ function createRepository(
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
survivor.source = input.source ?? "admin";
} else {
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
grants.push({
editorialId: input.editorialId,
albumId: input.immichAlbumId,
revokedAt: null,
source: input.source ?? "admin",
});
}
audit.push({
eventType: "album_granted",
@@ -192,7 +198,7 @@ function createRepository(
editorialId: input.editorialId,
albumId: input.immichAlbumId,
previousValues: { granted: false },
newValues: { granted: true },
newValues: { granted: true, source: input.source ?? "admin" },
});
return true;
},
@@ -217,6 +223,18 @@ function createRepository(
});
return true;
},
async revokeSelfServiceForAlbum(immichAlbumId) {
const active = grants.filter(
(grant) =>
grant.albumId.toLowerCase() === immichAlbumId &&
grant.source === "self_service" &&
grant.revokedAt === null,
);
for (const grant of active) {
grant.revokedAt = new Date();
}
return active.length;
},
};
return { repository, grants, audit };
}
@@ -269,7 +287,7 @@ test("canonicalizes UUID grant input before Immich and repository side effects",
expect(immich.getAlbum).toHaveBeenCalledWith(albumUuid);
expect(grants).toEqual([
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null, source: "admin" },
]);
});
@@ -378,7 +396,7 @@ test("granting an album is idempotent and records one state-change audit event",
editorialId: editorialUuid,
albumId: albumUuid,
previousValues: { granted: false },
newValues: { granted: true },
newValues: { granted: true, source: "admin" },
}),
]);
});
@@ -564,3 +582,37 @@ test("bulk grant reports a stable unavailable error when Immich is down", async
).rejects.toEqual(new AlbumGrantError("IMMICH_UNAVAILABLE"));
expect(grants).toHaveLength(0);
});
test("self-service revoke only retires self-service grants, never admin or auto-rule grants", async () => {
const { service, grants } = createService();
await service.grantAlbum({ editorialId: editorialUuid, immichAlbumId: albumUuid, adminUserId: adminUuid });
await service.grantAlbum({
editorialId: secondEditorialUuid,
immichAlbumId: albumUuid,
adminUserId: null,
source: "auto_rule",
});
await service.grantAlbum({
editorialId: secondEditorialUuid,
immichAlbumId: secondAlbumUuid,
adminUserId: null,
source: "self_service",
});
await expect(service.revokeSelfServiceGrantsForAlbum(secondAlbumUuid)).resolves.toBe(1);
const active = grants.filter((grant) => grant.revokedAt === null);
expect(active).toHaveLength(2);
expect(active.every((grant) => grant.albumId === albumUuid)).toBe(true);
});
test("grant records its source for the audit trail", async () => {
const { service, audit } = createService();
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: null,
source: "self_service",
});
expect(audit[0].newValues.source).toBe("self_service");
});
+66
View File
@@ -12,11 +12,15 @@ import type { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
export type AssignableAlbum = ImmichAlbumSummary & { isGranted: boolean };
export type AlbumGrantSource = "admin" | "auto_rule" | "self_service";
export type AlbumGrantInput = {
editorialId: string;
immichAlbumId: string;
/** Admin user for audit attribution; null marks an automated (system) grant. */
adminUserId: string | null;
/** How the grant came to be; defaults to a manual admin assignment. */
source?: AlbumGrantSource;
};
export type AlbumGrantHolder = {
@@ -48,6 +52,7 @@ export type AlbumGrantRepository = {
>;
grant(input: AlbumGrantInput): Promise<boolean>;
revoke(input: AlbumGrantInput): Promise<boolean>;
revokeSelfServiceForAlbum(immichAlbumId: string): Promise<number>;
};
export type AlbumGrantMutationCandidate = {
@@ -117,6 +122,15 @@ export function createAlbumGrantService({
await repository.revoke(normalizeInput(input));
},
/**
* Revokes only self-service grants for one album (used when its calendar
* event is deleted). Admin and auto-rule grants are never touched, so
* automatic keyword assignments keep outranking the calendar.
*/
async revokeSelfServiceGrantsForAlbum(immichAlbumId: string): Promise<number> {
return repository.revokeSelfServiceForAlbum(normalizeIdentifier(immichAlbumId));
},
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId));
return uniqueCanonicalIdentifiers(albumIds);
@@ -258,6 +272,7 @@ export function createAlbumGrantRepository(
immichAlbumId: input.immichAlbumId,
grantedAt: changedAt,
grantedByUserId: input.adminUserId,
source: input.source ?? "admin",
revokedAt: null,
})
.where(eq(albumGrants.id, plan.survivorId));
@@ -267,6 +282,7 @@ export function createAlbumGrantRepository(
immichAlbumId: input.immichAlbumId,
grantedAt: changedAt,
grantedByUserId: input.adminUserId,
source: input.source ?? "admin",
});
}
@@ -285,6 +301,7 @@ export function createAlbumGrantRepository(
editorialId: editorial.id,
immichAlbumId: input.immichAlbumId,
granted: true,
source: input.source ?? "admin",
},
occurredAt: changedAt,
});
@@ -292,6 +309,54 @@ export function createAlbumGrantRepository(
});
},
async revokeSelfServiceForAlbum(immichAlbumId) {
return database.transaction(async (transaction) => {
const grants = await transaction
.select({ id: albumGrants.id, editorialAccountId: albumGrants.editorialAccountId })
.from(albumGrants)
.where(
and(
sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`,
eq(albumGrants.source, "self_service"),
isNull(albumGrants.revokedAt),
),
)
.for("update");
if (grants.length === 0) {
return 0;
}
const changedAt = new Date();
await transaction
.update(albumGrants)
.set({ revokedAt: changedAt })
.where(inArray(albumGrants.id, grants.map((grant) => grant.id)));
for (const grant of grants) {
await transaction.insert(auditEvents).values({
eventType: "album_revoked",
actorUserId: null,
actorType: "system",
entityType: "album_grant",
entityId: immichAlbumId,
previousValues: {
editorialId: grant.editorialAccountId,
immichAlbumId,
granted: true,
source: "self_service",
},
newValues: {
editorialId: grant.editorialAccountId,
immichAlbumId,
granted: false,
reason: "calendar_event_deleted",
},
occurredAt: changedAt,
});
}
return grants.length;
});
},
async revoke(input) {
return database.transaction(async (transaction) => {
await lockEditorialAlbumMutation(transaction, input.editorialId);
@@ -350,6 +415,7 @@ function normalizeInput(input: AlbumGrantInput): AlbumGrantInput {
immichAlbumId: normalizeIdentifier(input.immichAlbumId),
adminUserId:
input.adminUserId === null ? null : normalizeIdentifier(input.adminUserId),
source: input.source ?? "admin",
};
}
+34 -1
View File
@@ -34,6 +34,25 @@ export function PhotoGallery({
// Keyboard nav + scroll lock while the lightbox is open. ponytail: a single
// window listener is enough; the lightbox is the only overlay in this view.
// Lightbox-view beacon for the admin statistics page. Fire-and-forget; the
// server rate-limits and never lets tracking break the gallery.
useEffect(() => {
if (openIndex === null) return;
const asset = items[openIndex];
if (!asset) return;
const payload = JSON.stringify({
type: "lightbox_view",
assetId: asset.id,
...(albumId ? { albumId } : {}),
});
fetch("/api/activity", {
method: "POST",
headers: { "content-type": "application/json" },
body: payload,
keepalive: true,
}).catch(() => undefined);
}, [openIndex, items, albumId]);
useEffect(() => {
if (openIndex === null) return;
function onKey(event: KeyboardEvent) {
@@ -99,6 +118,7 @@ export function PhotoGallery({
filename={asset.originalFileName}
newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
collabEnabled={downloadOptions.collabEnabled}
/>
) : null}
</div>
@@ -150,6 +170,7 @@ function PhotoLightbox({
onNext,
}: PhotoLightboxProps) {
const activeAlbumId = albumId ?? (asset.albums?.[0]?.id as string | undefined);
const description = assetDescription(asset);
return (
<div className="photo-lightbox" role="dialog" aria-modal="true" aria-label={asset.originalFileName}>
<button className="lightbox-close" type="button" onClick={onClose} aria-label="Schließen">
@@ -165,11 +186,12 @@ function PhotoLightbox({
›
</button>
) : null}
<figure className="lightbox-figure">
<figure className={description ? "lightbox-figure lightbox-figure-described" : "lightbox-figure"}>
<img alt={asset.originalFileName} className="lightbox-image" src={thumbnailUrl(asset.id)} />
<figcaption className="lightbox-caption">
<span className="photo-tile-name">{asset.originalFileName}</span>
<span className="photo-tile-date">{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
{description ? <p className="lightbox-description">{description}</p> : null}
</figcaption>
</figure>
<div className="lightbox-actions">
@@ -181,6 +203,7 @@ function PhotoLightbox({
filename={asset.originalFileName}
newUsagePriceCents={downloadOptions.priceCents}
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
collabEnabled={downloadOptions.collabEnabled}
/>
) : null}
</div>
@@ -188,6 +211,16 @@ function PhotoLightbox({
);
}
// Immich stores the photographer's description in the EXIF payload
// (`withExif: true` is already requested for the orientation filter). Rendered
// as plain React text, never as HTML.
function assetDescription(asset: ImmichAsset): string | null {
const value = asset.exifInfo?.description;
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function aspectStyle(asset: ImmichAsset): CSSProperties {
const width = asset.exifInfo?.exifImageWidth ?? 0;
const height = asset.exifInfo?.exifImageHeight ?? 0;
+141
View File
@@ -0,0 +1,141 @@
import { expect, test, vi } from "vitest";
import {
assertPdfBytes,
createInvoiceService,
formatPeriodLabel,
InvoiceError,
type InvoiceReport,
type InvoiceRepository,
} from "./invoice";
const reportId = "1111111a-1111-4111-8111-11111111111a";
const editorialId = "2222222b-2222-4222-8222-22222222222b";
const adminUserId = "3333333c-3333-4333-8333-33333333333c";
const pdfBytes = Buffer.from("%PDF-1.4 test invoice");
function baseReport(overrides: Partial<InvoiceReport> = {}): InvoiceReport {
return {
id: reportId,
status: "final",
editorialAccountId: editorialId,
reportNumber: 7,
invoiceNumber: "NN-2026-0007",
periodStartsAt: new Date("2026-07-01T00:00:00.000Z"),
periodEndsAt: new Date("2026-10-01T00:00:00.000Z"),
pdf: Buffer.from("%PDF-1.4 nutzungsnachweis"),
invoicePdf: null,
invoicePdfFilename: null,
...overrides,
};
}
function createRepo(report: InvoiceReport | null) {
let stored = report;
const repo: InvoiceRepository = {
getReport: vi.fn(async () => stored),
getEditorialEmail: vi.fn(async () => "redaktion@example.com"),
storeInvoice: vi.fn(async (_id, input) => {
if (stored) {
stored = {
...stored,
invoicePdf: input.bytes,
invoicePdfFilename: input.filename,
};
}
}),
markEmailOutcome: vi.fn(async () => undefined),
};
return { repo, getStored: () => stored };
}
test("assertPdfBytes accepts PDF magic and rejects everything else", () => {
expect(() => assertPdfBytes(pdfBytes)).not.toThrow();
expect(() => assertPdfBytes(Buffer.alloc(0))).toThrow(InvoiceError);
const zipMagic = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from("zip")]);
expect(() => assertPdfBytes(zipMagic)).toThrow(InvoiceError);
expect(() => assertPdfBytes(Buffer.alloc(21 * 1024 * 1024))).toThrow(InvoiceError);
});
test("formatPeriodLabel renders Berlin months and quarters", () => {
expect(
formatPeriodLabel(new Date("2026-08-01T00:00:00.000Z"), new Date("2026-09-01T00:00:00.000Z")),
).toBe("August 2026");
expect(
formatPeriodLabel(new Date("2026-07-01T00:00:00.000Z"), new Date("2026-10-01T00:00:00.000Z")),
).toBe("Q3 2026");
// Berlin rollover: Dec 31 23:00 UTC is already January in Berlin.
expect(
formatPeriodLabel(new Date("2026-12-31T23:00:00.000Z"), new Date("2027-02-01T00:00:00.000Z")),
).toBe("Januar 2027");
});
test("upload stores the PDF and sends the bundled email", async () => {
const { repo } = createRepo(baseReport());
const sendEmail = vi.fn().mockResolvedValue(undefined);
const service = createInvoiceService({ repo, sendEmail });
const result = await service.uploadInvoice({
reportId,
bytes: pdfBytes,
filename: "rechnung.pdf",
adminUserId,
});
expect(result.emailStatus).toBe("sent");
expect(repo.storeInvoice).toHaveBeenCalledOnce();
expect(sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
toEmail: "redaktion@example.com",
periodLabel: "Q3 2026",
invoiceNumber: "NN-2026-0007",
}),
);
expect(repo.markEmailOutcome).toHaveBeenCalledWith(reportId, "sent", null);
});
test("a failed send keeps the upload and marks the outcome failed", async () => {
const { repo, getStored } = createRepo(baseReport());
const sendEmail = vi.fn().mockRejectedValue(new Error("smtp down"));
const service = createInvoiceService({ repo, sendEmail });
const result = await service.uploadInvoice({
reportId,
bytes: pdfBytes,
filename: "rechnung.pdf",
adminUserId,
});
expect(result.emailStatus).toBe("failed");
expect(getStored()?.invoicePdf).toEqual(pdfBytes);
expect(repo.markEmailOutcome).toHaveBeenCalledWith(reportId, "failed", "smtp down");
});
test("upload rejects non-final reports and non-PDF bytes", async () => {
const { repo } = createRepo(baseReport({ status: "cancelled" }));
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(
service.uploadInvoice({ reportId, bytes: pdfBytes, filename: "r.pdf", adminUserId }),
).rejects.toMatchObject({ code: "REPORT_NOT_FINAL" });
const final = createRepo(baseReport());
const service2 = createInvoiceService({ repo: final.repo, sendEmail: vi.fn() });
await expect(
service2.uploadInvoice({ reportId, bytes: Buffer.from("nope"), filename: "r.pdf", adminUserId }),
).rejects.toMatchObject({ code: "INVALID_PDF" });
});
test("resend requires an uploaded invoice", async () => {
const { repo } = createRepo(baseReport());
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(
service.resendInvoice({ reportId, adminUserId }),
).rejects.toMatchObject({ code: "INVOICE_NOT_UPLOADED" });
});
test("getInvoicePdf returns null without an uploaded invoice", async () => {
const { repo } = createRepo(baseReport());
const service = createInvoiceService({ repo, sendEmail: vi.fn() });
await expect(service.getInvoicePdf(reportId)).resolves.toBeNull();
});
+302
View File
@@ -0,0 +1,302 @@
import "server-only";
import { createHash } from "node:crypto";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { billingReports, editorialAccounts } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
import { emailService } from "@/modules/email/service";
export const INVOICE_PDF_MAX_BYTES = 20 * 1024 * 1024;
export class InvoiceError extends Error {
readonly name = "InvoiceError";
constructor(
readonly code:
| "REPORT_NOT_FOUND"
| "REPORT_NOT_FINAL"
| "INVALID_PDF"
| "INVOICE_NOT_UPLOADED"
| "EDITORIAL_NOT_FOUND",
) {
super(code);
}
}
export type InvoiceReport = {
id: string;
status: "draft" | "final" | "cancelled";
editorialAccountId: string;
reportNumber: number;
invoiceNumber: string | null;
periodStartsAt: Date;
periodEndsAt: Date;
pdf: Buffer | null;
invoicePdf: Buffer | null;
invoicePdfFilename: string | null;
};
export type InvoiceEmailOutcome = "sent" | "failed";
export type InvoiceRepository = {
getReport(reportId: string): Promise<InvoiceReport | null>;
getEditorialEmail(editorialId: string): Promise<string | null>;
storeInvoice(
reportId: string,
input: { bytes: Buffer; sha256: string; filename: string; uploadedAt: Date },
): Promise<void>;
markEmailOutcome(
reportId: string,
outcome: InvoiceEmailOutcome,
error: string | null,
): Promise<void>;
};
export type SendInvoiceBundle = (input: {
toEmail: string;
periodLabel: string;
invoicePdf: Buffer;
reportPdf: Buffer;
invoiceNumber: string;
}) => Promise<void>;
export function createInvoiceService({
repo,
sendEmail,
}: {
repo: InvoiceRepository;
sendEmail: SendInvoiceBundle;
}) {
async function dispatch(report: InvoiceReport, adminUserId: string): Promise<InvoiceEmailOutcome> {
const invoicePdf = report.invoicePdf;
if (!invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED");
const toEmail = await repo.getEditorialEmail(report.editorialAccountId);
if (!toEmail) throw new InvoiceError("EDITORIAL_NOT_FOUND");
const periodLabel = formatPeriodLabel(report.periodStartsAt, report.periodEndsAt);
const invoiceNumber = report.invoiceNumber ?? String(report.reportNumber);
try {
await sendEmail({
toEmail,
periodLabel,
invoicePdf,
reportPdf: report.pdf ?? Buffer.alloc(0),
invoiceNumber,
});
await repo.markEmailOutcome(report.id, "sent", null);
await audit("invoice_email_sent", adminUserId, report.id, { toEmail, periodLabel });
return "sent";
} catch (error) {
const message = error instanceof Error ? error.message.slice(0, 500) : "unknown";
await repo.markEmailOutcome(report.id, "failed", message);
await audit("invoice_email_failed", adminUserId, report.id, { toEmail, error: message });
return "failed";
}
}
return {
/**
* Stores the admin-uploaded invoice PDF on a finalized report and sends
* the bundled email (invoice + Nutzungsnachweis). A failed send does not
* undo the upload; the admin can resend from the report list.
*/
async uploadInvoice(input: {
reportId: string;
bytes: Buffer;
filename: string;
adminUserId: string;
}): Promise<{ emailStatus: InvoiceEmailOutcome }> {
assertPdfBytes(input.bytes);
const report = await repo.getReport(input.reportId);
if (!report) throw new InvoiceError("REPORT_NOT_FOUND");
if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL");
const sha256 = createHash("sha256").update(input.bytes).digest("hex");
const filename = sanitizeFilename(input.filename);
await repo.storeInvoice(input.reportId, {
bytes: input.bytes,
sha256,
filename,
uploadedAt: new Date(),
});
await audit("invoice_uploaded", input.adminUserId, input.reportId, {
filename,
sizeBytes: input.bytes.length,
sha256,
});
const updated = await repo.getReport(input.reportId);
if (!updated) throw new InvoiceError("REPORT_NOT_FOUND");
const emailStatus = await dispatch(updated, input.adminUserId);
return { emailStatus };
},
async resendInvoice(input: {
reportId: string;
adminUserId: string;
}): Promise<{ emailStatus: InvoiceEmailOutcome }> {
const report = await repo.getReport(input.reportId);
if (!report) throw new InvoiceError("REPORT_NOT_FOUND");
if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL");
if (!report.invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED");
const emailStatus = await dispatch(report, input.adminUserId);
return { emailStatus };
},
async getInvoicePdf(
reportId: string,
): Promise<{ bytes: Buffer; filename: string } | null> {
const report = await repo.getReport(reportId);
if (!report || report.status !== "final" || !report.invoicePdf) return null;
return {
bytes: report.invoicePdf,
filename: report.invoicePdfFilename ?? `rechnung-${report.reportNumber}.pdf`,
};
},
};
}
export function assertPdfBytes(bytes: Buffer): void {
if (
bytes.length === 0 ||
bytes.length > INVOICE_PDF_MAX_BYTES ||
bytes.subarray(0, 5).toString("latin1") !== "%PDF-"
) {
throw new InvoiceError("INVALID_PDF");
}
}
function sanitizeFilename(value: string): string {
const cleaned = value.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_").trim().slice(0, 180);
return cleaned.toLowerCase().endsWith(".pdf") ? cleaned : `${cleaned || "rechnung"}.pdf`;
}
/**
* Human period label for the invoice email, derived from the stored report
* period (Europe/Berlin). Spans longer than 40 days are treated as quarters.
*/
export function formatPeriodLabel(startsAt: Date, endsAt: Date): string {
const spanDays = (endsAt.getTime() - startsAt.getTime()) / 86_400_000;
const parts = new Intl.DateTimeFormat("de-DE", {
month: "long",
year: "numeric",
timeZone: "Europe/Berlin",
}).formatToParts(startsAt);
const month = parts.find((part) => part.type === "month")?.value ?? "";
const year = parts.find((part) => part.type === "year")?.value ?? "";
if (spanDays > 40) {
const monthIndex = new Intl.DateTimeFormat("en-US", {
month: "numeric",
timeZone: "Europe/Berlin",
}).format(startsAt);
const quarter = Math.floor((Number(monthIndex) - 1) / 3) + 1;
return `Q${quarter} ${year}`;
}
return `${month} ${year}`;
}
async function audit(
type: string,
adminUserId: string,
reportId: string,
metadata: Record<string, unknown>,
): Promise<void> {
try {
await writeAudit({
type,
actorUserId: adminUserId,
actorType: "admin",
entityType: "billing_report",
entityId: reportId,
metadata,
});
} catch {
// Audit is observability, not a transaction participant.
}
}
// ---------------------------------------------------------------------------
// Drizzle repository
// ---------------------------------------------------------------------------
export function createInvoiceRepository(
database: NodePgDatabase<typeof schema>,
): InvoiceRepository {
return {
async getReport(reportId) {
const [row] = await database
.select({
id: billingReports.id,
status: billingReports.status,
editorialAccountId: billingReports.editorialAccountId,
reportNumber: billingReports.reportNumber,
invoiceNumber: billingReports.invoiceNumber,
periodStartsAt: billingReports.periodStartsAt,
periodEndsAt: billingReports.periodEndsAt,
pdf: billingReports.pdf,
invoicePdf: billingReports.invoicePdf,
invoicePdfFilename: billingReports.invoicePdfFilename,
})
.from(billingReports)
.where(eq(billingReports.id, reportId))
.limit(1);
return (row as InvoiceReport | undefined) ?? null;
},
async getEditorialEmail(editorialId) {
const [row] = await database
.select({ email: editorialAccounts.loginEmail })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
return row?.email ?? null;
},
async storeInvoice(reportId, input) {
await database
.update(billingReports)
.set({
invoicePdf: input.bytes,
invoicePdfSha256: input.sha256,
invoicePdfFilename: input.filename,
invoiceUploadedAt: input.uploadedAt,
invoiceEmailStatus: "not_sent",
invoiceEmailSentAt: null,
invoiceEmailError: null,
})
.where(eq(billingReports.id, reportId));
},
async markEmailOutcome(reportId, outcome, error) {
await database
.update(billingReports)
.set({
invoiceEmailStatus: outcome,
invoiceEmailSentAt: outcome === "sent" ? new Date() : null,
invoiceEmailError: error,
})
.where(eq(billingReports.id, reportId));
},
};
}
export const invoiceService = createInvoiceService({
repo: createInvoiceRepository(db),
sendEmail: async (input) => {
await emailService.sendInvoiceBundle(
input.toEmail,
input.periodLabel,
input.invoicePdf,
input.reportPdf,
input.invoiceNumber,
);
},
});
export const uploadInvoice = invoiceService.uploadInvoice;
export const resendInvoice = invoiceService.resendInvoice;
export const getInvoicePdf = invoiceService.getInvoicePdf;
+8
View File
@@ -50,6 +50,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Titelgeschichte",
internalReference: "Ausgabe 8/26",
priceCents: 1_500,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-05T10:00:00.000Z"),
billingReportId: null,
@@ -64,6 +65,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Sportbericht",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "billed",
createdAt: new Date("2026-08-06T10:00:00.000Z"),
billingReportId: "r1",
@@ -78,6 +80,7 @@ test("returns billed rows disabled and open rows selectable", async () => {
purpose: "Reopened story",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "reopened",
createdAt: new Date("2026-08-07T10:00:00.000Z"),
billingReportId: null,
@@ -103,6 +106,7 @@ test("maps raw billable usages to billing positions with snapshot fields", async
purpose: "Titelgeschichte",
internalReference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-05T10:00:00.000Z"),
billingReportId: null,
@@ -120,6 +124,7 @@ test("maps raw billable usages to billing positions with snapshot fields", async
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 6_000,
collab: false,
status: "open",
selectable: true,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
@@ -138,6 +143,7 @@ test("surfaces report and invoice references on billed positions", async () => {
purpose: "Sportbericht",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "billed",
createdAt: new Date("2026-08-06T10:00:00.000Z"),
billingReportId: "r1",
@@ -164,6 +170,7 @@ test("excludes voided usages from billable positions", async () => {
purpose: "Voided",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "voided",
createdAt: new Date("2026-08-03T10:00:00.000Z"),
billingReportId: null,
@@ -178,6 +185,7 @@ test("excludes voided usages from billable positions", async () => {
purpose: "Open",
internalReference: null,
priceCents: 1_500,
collab: false,
billingStatus: "open",
createdAt: new Date("2026-08-04T10:00:00.000Z"),
billingReportId: null,
+4
View File
@@ -21,6 +21,7 @@ export type BillingPosition = {
purpose: string;
reference: string | null;
priceCents: number;
collab: boolean;
status: "open" | "billed" | "reopened";
selectable: boolean;
createdAt: Date;
@@ -49,6 +50,7 @@ export type RawBillableUsage = {
purpose: string;
internalReference: string | null;
priceCents: number;
collab: boolean;
billingStatus: "open" | "billed" | "reopened" | "voided";
createdAt: Date;
billingReportId: string | null;
@@ -129,6 +131,7 @@ function toBillingPosition(row: RawBillableUsage): BillingPosition {
purpose: row.purpose,
reference: row.internalReference,
priceCents: row.priceCents,
collab: row.collab,
status,
selectable: status === "open" || status === "reopened",
createdAt: row.createdAt,
@@ -155,6 +158,7 @@ export function createBillingRepository(
purpose: usages.purpose,
internalReference: usages.internalReference,
priceCents: usages.priceCents,
collab: usages.collab,
billingStatus: usages.billingStatus,
createdAt: usages.createdAt,
billingReportId: usages.billingReportId,
+1
View File
@@ -46,6 +46,7 @@ function selectedUsage(id: string, status: "open" | "reopened" = "open"): Select
purpose: "Titelgeschichte",
internalReference: null,
priceCents: 3_000,
collab: false,
billingStatus: status,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
editorialAccountId: "e1",
+4
View File
@@ -87,6 +87,7 @@ export type SelectedUsage = {
purpose: string;
internalReference: string | null;
priceCents: number;
collab: boolean;
billingStatus: "open" | "billed" | "reopened" | "voided";
createdAt: Date;
editorialAccountId: string;
@@ -468,6 +469,7 @@ function toReportPosition(usage: SelectedUsage): BillingReportPosition {
purpose: usage.purpose,
reference: usage.internalReference,
priceCents: usage.priceCents,
collab: usage.collab,
createdAt: usage.createdAt,
};
}
@@ -533,6 +535,7 @@ export function createReportRepository(
purpose: usages.purpose,
internalReference: usages.internalReference,
priceCents: usages.priceCents,
collab: usages.collab,
billingStatus: usages.billingStatus,
createdAt: usages.createdAt,
editorialAccountId: usages.editorialAccountId,
@@ -639,6 +642,7 @@ export function createReportRepository(
purposeSnapshot: u.purpose,
internalReferenceSnapshot: u.internalReference,
priceCents: u.priceCents,
collab: u.collab,
})),
);
+2
View File
@@ -29,6 +29,8 @@ export type BillingReportPosition = {
purpose: string;
reference: string | null;
priceCents: number;
/** Free collaborative usage: rendered with 0,00 € and a Collab marker. */
collab: boolean;
createdAt: Date;
};
+57
View File
@@ -0,0 +1,57 @@
import { expect, test } from "vitest";
import { expectedAlbumNames, germanEventDate, matchEventAlbum } from "./event-albums";
const matchAlbum = { id: "2222222b-2222-4222-8222-22222222222b", albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026" };
const eventAlbum = { id: "3333333c-3333-4333-8333-33333333333c", albumName: "DFB-Pokal Finale" };
const privateAlbum = { id: "4444444d-4444-4444-8444-44444444444d", albumName: "Privaturlaub Sylt" };
test("germanEventDate formats ISO dates as TT.MM.JJJJ", () => {
expect(germanEventDate("2026-09-12")).toBe("12.09.2026");
});
test("expectedAlbumNames covers the bare event and the match naming convention", () => {
expect(expectedAlbumNames("Hamburger SV - VfL Wolfsburg", "2026-09-12")).toEqual([
"Hamburger SV - VfL Wolfsburg",
"Hamburger SV - VfL Wolfsburg | 12.09.2026",
]);
});
test("matchEventAlbum links the dated match album by exact name", () => {
const event = { title: "Hamburger SV - VfL Wolfsburg", eventDate: "2026-09-12", immichAlbumId: null };
expect(matchEventAlbum(event, [privateAlbum, matchAlbum])).toEqual(matchAlbum);
});
test("matchEventAlbum links a bare event album by exact name", () => {
const event = { title: "DFB-Pokal Finale", eventDate: "2026-05-23", immichAlbumId: null };
expect(matchEventAlbum(event, [eventAlbum])).toEqual(eventAlbum);
});
test("matchEventAlbum never links private or differently named albums", () => {
const event = { title: "Hamburger SV - VfL Wolfsburg", eventDate: "2026-09-12", immichAlbumId: null };
expect(matchEventAlbum(event, [privateAlbum])).toBeNull();
// Wrong date in the album name must not match.
const otherDate = { id: matchAlbum.id, albumName: "Hamburger SV - VfL Wolfsburg | 13.09.2026" };
expect(matchEventAlbum(event, [otherDate])).toBeNull();
//Substring or partial titles must not match.
const partial = { id: matchAlbum.id, albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026 Highlights" };
expect(matchEventAlbum(event, [partial])).toBeNull();
});
test("matchEventAlbum prefers the explicit album id over name matching", () => {
const event = {
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: eventAlbum.id.toUpperCase(),
};
expect(matchEventAlbum(event, [matchAlbum, eventAlbum])).toEqual(eventAlbum);
});
test("matchEventAlbum falls back to name matching when the explicit album is gone", () => {
const event = {
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: "99999999-9999-4999-8999-999999999999",
};
expect(matchEventAlbum(event, [matchAlbum])).toEqual(matchAlbum);
});
+46
View File
@@ -0,0 +1,46 @@
import type { ImmichAlbumSummary } from "@/modules/immich/types";
/**
* Pure linking rules between calendar events and Immich albums.
*
* Album names follow the photographer's convention "{Event}" or
* "{Verein A} - {Verein B} | {TT.MM.JJJJ}". An event links to an album either
* explicitly (admin picked its id) or by exact name match once the album
* appears: the bare title, or the title plus " | {TT.MM.JJJJ}" of the event
* date. Exact matching keeps private albums out: only albums whose names the
* admin deliberately mirrored into an event title ever become linkable.
*/
export type EventAlbumLink = {
title: string;
/** ISO date YYYY-MM-DD. */
eventDate: string;
immichAlbumId: string | null;
};
export type LinkableAlbum = Pick<ImmichAlbumSummary, "id" | "albumName">;
/** Formats an ISO date as TT.MM.JJJJ without timezone round-trips. */
export function germanEventDate(isoDate: string): string {
const [year, month, day] = isoDate.split("-");
return `${day}.${month}.${year}`;
}
export function expectedAlbumNames(title: string, eventDate: string): string[] {
const trimmed = title.trim();
return [trimmed, `${trimmed} | ${germanEventDate(eventDate)}`];
}
export function matchEventAlbum<T extends LinkableAlbum>(
event: EventAlbumLink,
albums: T[],
): T | null {
if (event.immichAlbumId) {
const explicit = albums.find(
(album) => album.id.toLowerCase() === event.immichAlbumId!.toLowerCase(),
);
if (explicit) return explicit;
}
const names = new Set(expectedAlbumNames(event.title, event.eventDate));
return albums.find((album) => names.has(album.albumName.trim())) ?? null;
}
+266
View File
@@ -0,0 +1,266 @@
import { expect, test, vi } from "vitest";
import { AlbumGrantError } from "@/modules/albums/grants";
import type { ImmichAlbumSummary } from "@/modules/immich/types";
import {
CalendarServiceError,
createCalendarService,
type CalendarRepository,
type CalendarEvent,
type EventResponseStatus,
} from "./service";
const editorialUuid = "1111111a-1111-4111-8111-11111111111a";
const userUuid = "3333333c-3333-4333-8333-33333333333c";
const eventUuid = "5555555e-5555-4555-8555-55555555555e";
const albumUuid = "2222222b-2222-4222-8222-22222222222b";
const matchAlbum: ImmichAlbumSummary = {
id: albumUuid,
albumName: "Hamburger SV - VfL Wolfsburg | 12.09.2026",
description: null,
albumThumbnailAssetId: null,
assetCount: 42,
};
function event(overrides: Partial<CalendarEvent> = {}): CalendarEvent {
return {
id: eventUuid,
title: "Hamburger SV - VfL Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: null,
createdAt: new Date("2026-09-01T08:00:00.000Z"),
...overrides,
};
}
function setup(options: {
events?: CalendarEvent[];
albums?: ImmichAlbumSummary[] | null;
grantedAlbumIds?: string[];
responses?: Array<{ eventId: string; status: EventResponseStatus }>;
rateLimitAllowed?: boolean;
} = {}) {
const events = [...(options.events ?? [event()])];
const responses = [...(options.responses ?? [])];
const repository: CalendarRepository = {
async insertEvent(input) {
const created = event({
id: "6666666f-6666-4666-8666-66666666666f",
title: input.title,
eventDate: input.eventDate,
immichAlbumId: input.immichAlbumId,
});
events.push(created);
return created;
},
async getEvent(id) {
return events.find((candidate) => candidate.id === id) ?? null;
},
async listEvents() {
return [...events].sort((left, right) => left.eventDate.localeCompare(right.eventDate));
},
async deleteEvent(id) {
const index = events.findIndex((candidate) => candidate.id === id);
if (index === -1) return null;
const [deleted] = events.splice(index, 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 listResponsesForEditorial() {
return responses;
},
async listAllResponses() {
return responses.map((response) => ({
...response,
editorialId: editorialUuid,
editorialName: "Kicker Daily",
}));
},
};
const immich = {
listAlbums: vi.fn(async () => {
if (options.albums === null) throw new Error("immich down");
return options.albums ?? [matchAlbum];
}),
};
const grants = {
getGrantedAlbumIds: vi.fn().mockResolvedValue(options.grantedAlbumIds ?? []),
grantAlbum: vi.fn().mockResolvedValue(undefined),
revokeSelfServiceGrantsForAlbum: vi.fn().mockResolvedValue(1),
};
const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) };
const consumeRateLimit = vi.fn().mockResolvedValue({
allowed: options.rateLimitAllowed ?? true,
retryAfterSeconds: 42,
});
return {
service: createCalendarService({ repository, immich, grants, audit, consumeRateLimit }),
repository,
immich,
grants,
audit,
consumeRateLimit,
events,
responses,
};
}
test("createEvent rejects an empty title and an invalid date", async () => {
const { service } = setup();
await expect(
service.createEvent({ title: " ", eventDate: "2026-09-12", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_TITLE" });
await expect(
service.createEvent({ title: "HSV - Wolfsburg", eventDate: "12.09.2026", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_EVENT_DATE" });
});
test("createEvent rejects an explicit album that does not exist in Immich", async () => {
const { service } = setup({ albums: [matchAlbum] });
await expect(
service.createEvent({
title: "HSV - Wolfsburg",
eventDate: "2026-09-12",
immichAlbumId: "99999999-9999-4999-8999-999999999999",
adminUserId: userUuid,
}),
).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 });
expect(grants.revokeSelfServiceGrantsForAlbum).toHaveBeenCalledWith(albumUuid);
expect(events).toHaveLength(0);
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "calendar_event_deleted" }),
);
});
test("deleteEvent reports unknown events", async () => {
const { service } = setup();
await expect(
service.deleteEvent({ id: "99999999-9999-4999-8999-999999999999", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "EVENT_NOT_FOUND" });
});
test("listEditorialEvents marks granted albums, own responses and the past window", async () => {
const oldEvent = event({ id: "7777777a-7777-4777-8777-77777777777a", eventDate: "2026-01-01" });
const { service } = setup({
events: [event(), oldEvent],
grantedAlbumIds: [albumUuid],
responses: [{ eventId: eventUuid, status: "attending" }],
});
const { events, immichUnavailable } = await service.listEditorialEvents(
editorialUuid,
new Date("2026-09-10T08:00:00.000Z"),
);
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 },
});
});
test("listEditorialEvents degrades gracefully when Immich is down", async () => {
const { service } = setup({ albums: null });
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);
});
+468
View File
@@ -0,0 +1,468 @@
import "server-only";
import { asc, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { calendarEvents, editorialAccounts, eventResponses } from "@/db/schema";
import type * as schema from "@/db/schema";
import { albumGrantService, AlbumGrantError } from "@/modules/albums/grants";
import {
isoDateInBerlin,
isValidIsoDate,
shiftIsoDate,
} from "@/modules/announcements/service";
import { writeAudit } from "@/modules/audit/write";
import { immichClient } from "@/modules/immich/client";
import type { ImmichClient } from "@/modules/immich/types";
import { consumeRateLimit, calendarSelfGrantPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
import { matchEventAlbum } from "./event-albums";
export const CALENDAR_EVENT_MAX_TITLE_LENGTH = 200;
/** Past events stay visible (and self-serviceable) 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;
createdAt: Date;
};
export type LinkedAlbum = { id: string; albumName: string };
export type EditorialCalendarEvent = CalendarEvent & {
album: LinkedAlbum | null;
isGranted: boolean;
response: EventResponseStatus | null;
};
export type AdminCalendarEvent = CalendarEvent & {
album: LinkedAlbum | null;
responses: Array<{
editorialId: string;
editorialName: string;
status: EventResponseStatus;
}>;
};
export type CalendarError =
| "INVALID_TITLE"
| "INVALID_EVENT_DATE"
| "INVALID_ALBUM"
| "INVALID_STATUS"
| "EVENT_NOT_FOUND"
| "EVENT_ALBUM_UNAVAILABLE"
| "IMMICH_UNAVAILABLE"
| "RATE_LIMITED";
export class CalendarServiceError extends Error {
readonly name = "CalendarServiceError";
constructor(
readonly code: CalendarError,
readonly retryAfterSeconds?: number,
) {
super(code);
}
}
export type CalendarRepository = {
insertEvent(input: {
title: string;
eventDate: string;
immichAlbumId: 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 }>
>;
};
export type CalendarDependencies = {
repository: CalendarRepository;
immich: Pick<ImmichClient, "listAlbums">;
grants: Pick<
typeof albumGrantService,
"getGrantedAlbumIds" | "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;
export function createCalendarService({
repository,
immich,
grants,
audit,
consumeRateLimit: consume,
}: CalendarDependencies) {
async function loadAlbumsOrNull() {
try {
return await immich.listAlbums();
} catch {
return null;
}
}
return {
async createEvent(input: {
title: string;
eventDate: string;
immichAlbumId?: string | null;
adminUserId: string;
}): Promise<CalendarEvent> {
const title = input.title.trim();
if (title.length === 0 || title.length > CALENDAR_EVENT_MAX_TITLE_LENGTH) {
throw new CalendarServiceError("INVALID_TITLE");
}
if (!isValidIsoDate(input.eventDate)) {
throw new CalendarServiceError("INVALID_EVENT_DATE");
}
let immichAlbumId: string | null = null;
if (input.immichAlbumId) {
if (!UUID_PATTERN.test(input.immichAlbumId)) {
throw new CalendarServiceError("INVALID_ALBUM");
}
const albums = await loadAlbumsOrNull();
if (!albums) {
throw new CalendarServiceError("IMMICH_UNAVAILABLE");
}
const album = albums.find(
(candidate) => candidate.id.toLowerCase() === input.immichAlbumId!.toLowerCase(),
);
if (!album) {
throw new CalendarServiceError("INVALID_ALBUM");
}
immichAlbumId = album.id;
}
const created = await repository.insertEvent({
title,
eventDate: input.eventDate,
immichAlbumId,
adminUserId: input.adminUserId,
});
await audit.writeAudit({
type: "calendar_event_created",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "calendar_event",
entityId: created.id,
metadata: { title: created.title, eventDate: created.eventDate, immichAlbumId },
});
return created;
},
async deleteEvent(input: { id: string; adminUserId: string }): Promise<void> {
const event = await repository.getEvent(input.id);
if (!event) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
// Revoking self-service grants keeps the calendar authoritative: an
// album that leaves the calendar loses self-service access. Admin and
// auto-rule grants are untouched (auto assignment outranks the calendar).
const albums = (await loadAlbumsOrNull()) ?? [];
const album = matchEventAlbum(event, albums);
const revoked = album
? await grants.revokeSelfServiceGrantsForAlbum(album.id)
: 0;
const deleted = await repository.deleteEvent(input.id);
if (!deleted) {
throw new CalendarServiceError("EVENT_NOT_FOUND");
}
await audit.writeAudit({
type: "calendar_event_deleted",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "calendar_event",
entityId: deleted.id,
metadata: {
title: deleted.title,
eventDate: deleted.eventDate,
revokedSelfServiceGrants: revoked,
},
});
},
/** Editorial calendar: upcoming events plus the recent past window. */
async listEditorialEvents(
editorialId: string,
now: Date,
): Promise<{ events: EditorialCalendarEvent[]; immichUnavailable: boolean }> {
const today = isoDateInBerlin(now);
const minDate = shiftIsoDate(today, -CALENDAR_PAST_DAYS);
const [allEvents, albums, grantedAlbumIds, responses] = await Promise.all([
repository.listEvents(),
loadAlbumsOrNull(),
grants.getGrantedAlbumIds(editorialId),
repository.listResponsesForEditorial(editorialId),
]);
const granted = new Set(grantedAlbumIds.map((id) => id.toLowerCase()));
const responseByEvent = new Map(responses.map((response) => [response.eventId, response.status]));
const events = allEvents
.filter((event) => event.eventDate >= minDate)
.map((event) => {
const album = albums ? matchEventAlbum(event, albums) : null;
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,
};
});
return { events, immichUnavailable: albums === null };
},
/** Admin overview: every event with its linked album and all RSVPs. */
async listAdminEvents(): Promise<{ events: AdminCalendarEvent[]; immichUnavailable: boolean }> {
const [allEvents, albums, responses] = await Promise.all([
repository.listEvents(),
loadAlbumsOrNull(),
repository.listAllResponses(),
]);
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 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) ?? [],
};
});
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.
*/
async selfGrantAlbum(input: {
eventId: string;
editorialId: string;
actorUserId: string;
}): Promise<LinkedAlbum> {
try {
await enforceRateLimit(consume, `calendar-self-grant:${input.editorialId}`, calendarSelfGrantPolicy);
} catch (error) {
if (error instanceof RateLimitExceededError) {
throw new CalendarServiceError("RATE_LIMITED", error.retryAfterSeconds);
}
throw error;
}
const event = await repository.getEvent(input.eventId);
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");
}
try {
await grants.grantAlbum({
editorialId: input.editorialId,
immichAlbumId: album.id,
adminUserId: null,
source: "self_service",
});
} 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;
}
await audit.writeAudit({
type: "album_self_granted",
actorUserId: input.actorUserId,
actorType: "editorial",
entityType: "album_grant",
entityId: album.id,
metadata: {
editorialId: input.editorialId,
eventId: input.eventId,
albumName: album.albumName,
},
});
return { id: album.id, albumName: album.albumName };
},
};
}
export function createCalendarRepository(database: NodePgDatabase<typeof schema>): CalendarRepository {
const eventColumns = {
id: calendarEvents.id,
title: calendarEvents.title,
eventDate: calendarEvents.eventDate,
immichAlbumId: calendarEvents.immichAlbumId,
createdAt: calendarEvents.createdAt,
};
return {
async insertEvent(input) {
const [row] = await database
.insert(calendarEvents)
.values({
title: input.title,
eventDate: input.eventDate,
immichAlbumId: input.immichAlbumId,
createdByUserId: input.adminUserId,
})
.returning(eventColumns);
return row;
},
async getEvent(id) {
const [row] = await database
.select(eventColumns)
.from(calendarEvents)
.where(eq(calendarEvents.id, id))
.limit(1);
return row ?? null;
},
async listEvents() {
return database
.select(eventColumns)
.from(calendarEvents)
.orderBy(asc(calendarEvents.eventDate), asc(calendarEvents.createdAt));
},
async deleteEvent(id) {
return database.transaction(async (transaction) => {
const [event] = await transaction
.select(eventColumns)
.from(calendarEvents)
.where(eq(calendarEvents.id, id))
.for("update")
.limit(1);
if (!event) {
return null;
}
await transaction.delete(eventResponses).where(eq(eventResponses.eventId, id));
await transaction.delete(calendarEvents).where(eq(calendarEvents.id, id));
return event;
});
},
async upsertResponse(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() },
});
},
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 listAllResponses() {
const rows = await database
.select({
eventId: eventResponses.eventId,
editorialId: editorialAccounts.id,
editorialName: editorialAccounts.name,
status: eventResponses.status,
})
.from(eventResponses)
.innerJoin(editorialAccounts, eq(eventResponses.editorialAccountId, editorialAccounts.id))
.orderBy(asc(editorialAccounts.name));
return rows.map((row) => ({ ...row, status: row.status as EventResponseStatus }));
},
};
}
export const calendarService = createCalendarService({
repository: createCalendarRepository(db),
immich: immichClient,
grants: albumGrantService,
audit: { writeAudit },
consumeRateLimit,
});
+8 -3
View File
@@ -594,6 +594,7 @@ export type DownloadDialogUsage = {
export type EditorialDownloadOptions = {
priceCents: number;
collabEnabled: boolean;
priorUsagesByAsset: Record<string, DownloadDialogUsage[]>;
};
@@ -610,7 +611,10 @@ export function createEditorialDownloadOptionsLoader(
throw new UsageAccountingError("INVALID_INPUT");
}
const [editorial] = await database
.select({ currentPriceCents: editorialAccounts.currentPriceCents })
.select({
currentPriceCents: editorialAccounts.currentPriceCents,
collabEnabled: editorialAccounts.collabEnabled,
})
.from(editorialAccounts)
.where(
and(
@@ -623,8 +627,9 @@ export function createEditorialDownloadOptionsLoader(
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
throw new UsageAccountingError("INVALID_PRICE");
}
const collabEnabled = editorial?.collabEnabled === true;
if (normalizedAssets.length === 0) {
return { priceCents: priceCents!, priorUsagesByAsset: {} };
return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset: {} };
}
const deliveredOriginal = database
@@ -657,7 +662,7 @@ export function createEditorialDownloadOptionsLoader(
createdAt: row.createdAt.toISOString(),
});
}
return { priceCents: priceCents!, priorUsagesByAsset };
return { priceCents: priceCents!, collabEnabled, priorUsagesByAsset };
};
}
+33 -1
View File
@@ -2,7 +2,7 @@ import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { archiveEditorialAction, unarchiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions";
import { archiveEditorialAction, unarchiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction, updateCollabAction } from "@/app/admin/redaktionen/[id]/actions";
import { DangerZone } from "./DangerZone";
import { ResetUsageCard } from "./ResetUsageCard";
import { ApproveForm } from "./ApproveForm";
@@ -18,6 +18,7 @@ export type EditorialDetail = {
flatrateActive: boolean;
flatratePriceCents: number | null;
flatrateAssetLimit: number | null;
collabEnabled: boolean;
archivedAt: Date | null;
};
@@ -175,6 +176,37 @@ export function EditorialDetailContent({
</Card>
)}
{!editorial.archivedAt && (
<Card>
<CardHeader>
<CardTitle>Collab-Nutzung</CardTitle>
<CardDescription>
Erlaubt der Redaktion, Downloads als kostenlose Collab-Nutzung zu markieren
(0,00 € in der Abrechnung, mit Collab-Kennzeichnung).
</CardDescription>
</CardHeader>
<CardContent>
<form action={updateCollabAction.bind(null, editorial.id)} className="space-y-4">
<div className="flex items-center space-x-2">
<input
type="checkbox"
name="collabEnabled"
id="collabEnabled"
defaultChecked={editorial.collabEnabled}
className="w-4 h-4 rounded border-border text-primary-600 focus:ring-primary-500"
/>
<label htmlFor="collabEnabled" className="text-sm font-medium leading-none">
Collab-Option freischalten
</label>
</div>
<Button type="submit" variant="secondary">
Speichern
</Button>
</form>
</CardContent>
</Card>
)}
{!editorial.archivedAt && (
<Card className="border-border">
<CardHeader>
+11
View File
@@ -0,0 +1,11 @@
import { expect, test } from "vitest";
import { invoiceMessage } from "./invoice-message";
test("invoice message names the period and both attachments", () => {
const message = invoiceMessage("Q3 2026");
expect(message.subject).toBe("Ihre Rechnung für Q3 2026");
expect(message.text).toContain("Rechnung für Q3 2026");
expect(message.text).toContain("Nutzungsnachweis");
expect(message.htmlContent).toContain("Q3 2026");
});
+21
View File
@@ -0,0 +1,21 @@
export function invoiceMessage(periodLabel: string) {
return {
subject: `Ihre Rechnung für ${periodLabel}`,
text: `Hallo,
anbei erhalten Sie Ihre Rechnung für ${periodLabel} sowie den zugehörigen Nutzungsnachweis als PDF-Dokumente.
Bei Fragen zu den Positionen melden Sie sich gerne bei uns.
Viele Grüße,
Ihr Redaktions-Team`,
htmlContent: `Hallo,
anbei erhalten Sie Ihre **Rechnung für ${periodLabel}** sowie den zugehörigen Nutzungsnachweis als PDF-Dokumente.
Bei Fragen zu den Positionen melden Sie sich gerne bei uns.
Viele Grüße,
Ihr Redaktions-Team`,
};
}
+35
View File
@@ -2,6 +2,7 @@ import "server-only";
import nodemailer from "nodemailer";
import { env } from "@/config/env";
import { billingReportMessage } from "./billing-report-message";
import { invoiceMessage } from "./invoice-message";
const transporter = nodemailer.createTransport({
host: env.SMTP_HOST,
@@ -94,6 +95,40 @@ export const emailService = {
});
},
async sendInvoiceBundle(
toEmail: string,
periodLabel: string,
invoicePdf: Buffer,
reportPdf: Buffer,
invoiceNumber: string,
) {
const safeNumber = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") || "rechnung";
const message = invoiceMessage(periodLabel);
await transporter.sendMail({
from: env.SMTP_FROM,
to: toEmail,
subject: message.subject,
text: message.text,
html: buildHtml("Ihre Rechnung", message.htmlContent, {
text: "Zum Portal",
url: `${env.BETTER_AUTH_URL}/anmelden`,
}),
attachments: [
{
filename: `Rechnung-${safeNumber}.pdf`,
content: invoicePdf,
contentType: "application/pdf",
},
{
filename: `Nutzungsnachweis-${safeNumber}.pdf`,
content: reportPdf,
contentType: "application/pdf",
},
],
});
},
async sendNewAlbumNotification(toEmail: string, albumNames: string | string[]) {
const albums = Array.isArray(albumNames) ? albumNames : [albumNames];
+2
View File
@@ -28,6 +28,7 @@ const assetSchema = z
exifInfo: z.object({
exifImageWidth: z.number().optional().nullable(),
exifImageHeight: z.number().optional().nullable(),
description: nullableString,
}).passthrough().optional().nullable(),
})
.passthrough();
@@ -369,6 +370,7 @@ export function createImmichClient({
albumIds: input.albumIds,
...(input.id === undefined ? {} : { id: input.id }),
...(input.description === undefined ? {} : { description: input.description }),
...(input.originalFileName === undefined ? {} : { originalFileName: input.originalFileName }),
type: "IMAGE",
page: input.page,
size: input.size,
+2 -1
View File
@@ -16,6 +16,7 @@ export type ImmichAsset = {
exifInfo?: {
exifImageWidth?: number | null;
exifImageHeight?: number | null;
description?: string | null;
} | null;
albums: Array<{ id: string }>;
};
@@ -46,7 +47,7 @@ export interface ImmichClient {
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
getAsset(assetId: string, signal?: AbortSignal): Promise<ImmichAsset>;
searchPhotos(
input: { albumIds: string[]; id?: string; description?: string; page: number; size: number; type?: "IMAGE"; withExif?: boolean },
input: { albumIds: string[]; id?: string; description?: string; originalFileName?: string; page: number; size: number; type?: "IMAGE"; withExif?: boolean },
signal?: AbortSignal,
): Promise<ImmichSearchPage>;
getThumbnail(assetId: string, signal?: AbortSignal): Promise<ImmichBinary>;
+1 -1
View File
@@ -80,7 +80,7 @@ function paidPositionsTable(snapshot: BillingReportSnapshot) {
body.push([
{ text: pos.filename, style: "tableCell" },
{ text: pos.albumName, style: "tableCell" },
{ text: pos.purpose, style: "tableCell" },
{ text: pos.collab ? `${pos.purpose} (Collab)` : pos.purpose, style: "tableCell" },
{ text: pos.reference ?? "", style: "tableCell" },
{ text: formatGermanDate(pos.createdAt), style: "tableCell", alignment: "right" as const },
{ text: formatCents(pos.priceCents), style: "tableCell", alignment: "right" as const },
+98
View File
@@ -0,0 +1,98 @@
import { expect, test, vi } from "vitest";
import {
createReleaseNoteService,
isValidVersion,
ReleaseNoteServiceError,
type ReleaseNote,
type ReleaseNoteRepository,
} from "./service";
const userUuid = "3333333c-3333-4333-8333-33333333333c";
function note(overrides: Partial<ReleaseNote> = {}): ReleaseNote {
return {
id: "5555555e-5555-4555-8555-55555555555e",
version: "2.1.0",
audience: "editorial",
body: "Neu in 2.1: Sortierung und Kalender.",
createdAt: new Date("2026-11-30T08:00:00.000Z"),
...overrides,
};
}
function setup(options: { insertError?: unknown } = {}) {
const repository: ReleaseNoteRepository = {
insert: vi.fn(async (input) => {
if (options.insertError) throw options.insertError;
return note({ version: input.version, audience: input.audience, body: input.body });
}),
listForEditorial: vi.fn().mockResolvedValue([note()]),
listAll: vi.fn().mockResolvedValue([note(), note({ audience: "admin" })]),
deleteById: vi.fn().mockResolvedValue(note()),
};
const audit = { writeAudit: vi.fn().mockResolvedValue(undefined) };
return { service: createReleaseNoteService({ repository, audit }), repository, audit };
}
test("isValidVersion accepts major.minor and major.minor.patch only", () => {
expect(isValidVersion("2.1")).toBe(true);
expect(isValidVersion("2.1.0")).toBe(true);
expect(isValidVersion("2.10.12")).toBe(true);
expect(isValidVersion("2")).toBe(false);
expect(isValidVersion("2.1.0.4")).toBe(false);
expect(isValidVersion("v2.1")).toBe(false);
expect(isValidVersion("2.x")).toBe(false);
});
test("createReleaseNote validates version, audience and body", async () => {
const { service, repository } = setup();
await expect(
service.createReleaseNote({ version: "abc", audience: "editorial", body: "Text", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_VERSION" });
await expect(
service.createReleaseNote({
version: "2.1",
audience: "everyone" as never,
body: "Text",
adminUserId: userUuid,
}),
).rejects.toMatchObject({ code: "INVALID_AUDIENCE" });
await expect(
service.createReleaseNote({ version: "2.1", audience: "editorial", body: " ", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "INVALID_BODY" });
expect(repository.insert).not.toHaveBeenCalled();
});
test("createReleaseNote trims input, writes audit and maps duplicate versions", async () => {
const { service, audit } = setup();
const created = await service.createReleaseNote({
version: " 2.1 ",
audience: "both",
body: " Text ",
adminUserId: userUuid,
});
expect(created.version).toBe("2.1");
expect(created.body).toBe("Text");
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "release_note_created", actorType: "admin" }),
);
const duplicate = setup({ insertError: { code: "23505" } });
await expect(
duplicate.service.createReleaseNote({ version: "2.1", audience: "both", body: "Text", adminUserId: userUuid }),
).rejects.toMatchObject({ code: "DUPLICATE_RELEASE_NOTE" });
});
test("deleteReleaseNote reports missing notes and audits deletions", async () => {
const { service, repository, audit } = setup();
await service.deleteReleaseNote({ id: note().id, adminUserId: userUuid });
expect(audit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ type: "release_note_deleted" }),
);
repository.deleteById = vi.fn().mockResolvedValue(null);
await expect(
service.deleteReleaseNote({ id: note().id, adminUserId: userUuid }),
).rejects.toBeInstanceOf(ReleaseNoteServiceError);
});
+203
View File
@@ -0,0 +1,203 @@
import "server-only";
import { desc, eq, inArray } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { releaseNotes } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
export const RELEASE_NOTE_MAX_BODY_LENGTH = 2000;
export type ReleaseNoteAudience = "admin" | "editorial" | "both";
export type ReleaseNote = {
id: string;
version: string;
audience: ReleaseNoteAudience;
body: string;
createdAt: Date;
};
export type ReleaseNoteError =
| "INVALID_VERSION"
| "INVALID_BODY"
| "INVALID_AUDIENCE"
| "DUPLICATE_RELEASE_NOTE"
| "RELEASE_NOTE_NOT_FOUND";
export class ReleaseNoteServiceError extends Error {
readonly name = "ReleaseNoteServiceError";
constructor(readonly code: ReleaseNoteError) {
super(code);
}
}
export type CreateReleaseNoteInput = {
version: string;
audience: ReleaseNoteAudience;
body: string;
adminUserId: string;
};
export type ReleaseNoteRepository = {
insert(input: {
version: string;
audience: ReleaseNoteAudience;
body: string;
adminUserId: string;
}): Promise<ReleaseNote>;
listForEditorial(): Promise<ReleaseNote[]>;
listAll(): Promise<ReleaseNote[]>;
deleteById(id: string): Promise<ReleaseNote | null>;
};
const VERSION_PATTERN = /^\d+\.\d+(\.\d+)?$/;
const AUDIENCES: ReleaseNoteAudience[] = ["admin", "editorial", "both"];
export function isValidVersion(value: string): boolean {
return VERSION_PATTERN.test(value);
}
export function createReleaseNoteService({
repository,
audit,
}: {
repository: ReleaseNoteRepository;
audit: { writeAudit: typeof writeAudit };
}) {
return {
async createReleaseNote(input: CreateReleaseNoteInput): Promise<ReleaseNote> {
const version = input.version.trim();
if (!isValidVersion(version)) {
throw new ReleaseNoteServiceError("INVALID_VERSION");
}
if (!AUDIENCES.includes(input.audience)) {
throw new ReleaseNoteServiceError("INVALID_AUDIENCE");
}
const body = input.body.trim();
if (body.length === 0 || body.length > RELEASE_NOTE_MAX_BODY_LENGTH) {
throw new ReleaseNoteServiceError("INVALID_BODY");
}
let created: ReleaseNote;
try {
created = await repository.insert({
version,
audience: input.audience,
body,
adminUserId: input.adminUserId,
});
} catch (error) {
if (isUniqueViolation(error)) {
throw new ReleaseNoteServiceError("DUPLICATE_RELEASE_NOTE");
}
throw error;
}
await audit.writeAudit({
type: "release_note_created",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "release_note",
entityId: created.id,
metadata: { version: created.version, audience: created.audience },
});
return created;
},
/** Notes visible to editorial users (their own plus shared ones). */
async listEditorialReleaseNotes(): Promise<ReleaseNote[]> {
return repository.listForEditorial();
},
/** Every note for the admin overview. */
async listReleaseNotes(): Promise<ReleaseNote[]> {
return repository.listAll();
},
async deleteReleaseNote(input: { id: string; adminUserId: string }): Promise<void> {
const deleted = await repository.deleteById(input.id);
if (!deleted) {
throw new ReleaseNoteServiceError("RELEASE_NOTE_NOT_FOUND");
}
await audit.writeAudit({
type: "release_note_deleted",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "release_note",
entityId: deleted.id,
metadata: { version: deleted.version, audience: deleted.audience },
});
},
};
}
function isUniqueViolation(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error as { code?: unknown }).code === "23505"
);
}
export function createReleaseNoteRepository(
database: NodePgDatabase<typeof schema>,
): ReleaseNoteRepository {
const columns = {
id: releaseNotes.id,
version: releaseNotes.version,
audience: releaseNotes.audience,
body: releaseNotes.body,
createdAt: releaseNotes.createdAt,
};
return {
async insert(input) {
const [row] = await database
.insert(releaseNotes)
.values({
version: input.version,
audience: input.audience,
body: input.body,
createdByUserId: input.adminUserId,
})
.returning(columns);
return { ...row, audience: row.audience as ReleaseNoteAudience };
},
async listForEditorial() {
const rows = await database
.select(columns)
.from(releaseNotes)
.where(inArray(releaseNotes.audience, ["editorial", "both"]))
.orderBy(desc(releaseNotes.createdAt));
return rows.map((row) => ({ ...row, audience: row.audience as ReleaseNoteAudience }));
},
async listAll() {
const rows = await database
.select(columns)
.from(releaseNotes)
.orderBy(desc(releaseNotes.createdAt));
return rows.map((row) => ({ ...row, audience: row.audience as ReleaseNoteAudience }));
},
async deleteById(id) {
const [row] = await database
.delete(releaseNotes)
.where(eq(releaseNotes.id, id))
.returning(columns);
return row ? { ...row, audience: row.audience as ReleaseNoteAudience } : null;
},
};
}
export const releaseNoteService = createReleaseNoteService({
repository: createReleaseNoteRepository(db),
audit: { writeAudit },
});
+3
View File
@@ -34,6 +34,9 @@ export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSecon
export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 };
export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
export const calendarSelfGrantPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
export const invoiceUploadPolicy: RateLimitPolicy = { maxAttempts: 10, windowSeconds: 60 };
export const activityPolicy: RateLimitPolicy = { maxAttempts: 240, windowSeconds: 60 };
// ---------------------------------------------------------------------------
// Limiter factory
+56
View File
@@ -0,0 +1,56 @@
import { expect, test } from "vitest";
import {
fillDailySeries,
formatBytes,
normalizeStatsDays,
percentChange,
previousWindow,
statsWindow,
} from "./queries";
test("normalizeStatsDays only accepts the offered periods", () => {
expect(normalizeStatsDays("7")).toBe(7);
expect(normalizeStatsDays("90")).toBe(90);
expect(normalizeStatsDays("30")).toBe(30);
expect(normalizeStatsDays("365")).toBe(30);
expect(normalizeStatsDays(undefined)).toBe(30);
expect(normalizeStatsDays("abc")).toBe(30);
});
test("percentChange returns null without a baseline and rounds otherwise", () => {
expect(percentChange(5, 0)).toBeNull();
expect(percentChange(0, 0)).toBeNull();
expect(percentChange(150, 100)).toBe(50);
expect(percentChange(50, 100)).toBe(-50);
expect(percentChange(100, 100)).toBe(0);
});
test("statsWindow and previousWindow tile the timeline without gaps", () => {
const now = new Date("2026-11-30T12:00:00.000Z");
const window = statsWindow(30, now);
const previous = previousWindow(window);
expect(window.toUtcExclusive).toEqual(now);
expect(previous.toUtcExclusive).toEqual(window.fromUtc);
expect(previous.fromUtc.getTime()).toBe(window.fromUtc.getTime() - 30 * 86_400_000);
});
test("fillDailySeries fills missing days with zeroes", () => {
const now = new Date("2026-11-30T12:00:00.000Z");
const window = statsWindow(7, now);
const points = fillDailySeries(
[{ date: "2026-11-29", downloads: 4, revenueCents: 1500 }],
window,
);
expect(points).toHaveLength(7);
expect(points[0].date).toBe("2026-11-23");
expect(points[6].date).toBe("2026-11-29");
expect(points[6]).toMatchObject({ downloads: 4, revenueCents: 1500, views: 0, searches: 0 });
expect(points[5]).toMatchObject({ downloads: 0, views: 0, searches: 0, revenueCents: 0 });
});
test("formatBytes switches from MB to GB", () => {
expect(formatBytes(0)).toBe("0 MB");
expect(formatBytes(5 * 1024 * 1024)).toContain("5");
expect(formatBytes(2 * 1024 * 1024 * 1024)).toContain("GB");
});
+364
View File
@@ -0,0 +1,364 @@
import "server-only";
import { and, desc, eq, gte, lt, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import {
activityEvents,
billingReports,
downloadEvents,
editorialAccounts,
usages,
} from "@/db/schema";
import type * as schema from "@/db/schema";
// ---------------------------------------------------------------------------
// Pure helpers (unit-tested without a database)
// ---------------------------------------------------------------------------
export const STATS_PERIOD_OPTIONS = [7, 30, 90] as const;
export type StatsPeriodDays = (typeof STATS_PERIOD_OPTIONS)[number];
export function normalizeStatsDays(value: unknown): StatsPeriodDays {
const parsed = typeof value === "string" ? Number.parseInt(value, 10) : NaN;
return (STATS_PERIOD_OPTIONS as readonly number[]).includes(parsed)
? (parsed as StatsPeriodDays)
: 30;
}
export type StatsWindow = { fromUtc: Date; toUtcExclusive: Date; days: number };
export function statsWindow(days: number, now: Date = new Date()): StatsWindow {
const toUtcExclusive = new Date(now);
const fromUtc = new Date(now.getTime() - days * 86_400_000);
return { fromUtc, toUtcExclusive, days };
}
export function previousWindow(window: StatsWindow): StatsWindow {
const span = window.toUtcExclusive.getTime() - window.fromUtc.getTime();
return {
fromUtc: new Date(window.fromUtc.getTime() - span),
toUtcExclusive: window.fromUtc,
days: window.days,
};
}
/** Relative change in percent; null when the previous value is 0 (no baseline). */
export function percentChange(current: number, previous: number): number | null {
if (previous === 0) return null;
return Math.round(((current - previous) / previous) * 100);
}
export type DailyPoint = {
date: string;
downloads: number;
views: number;
searches: number;
revenueCents: number;
};
/** Fill missing days with zeroes so charts always show the full window. */
export function fillDailySeries(
rows: Array<Partial<DailyPoint> & { date: string }>,
window: StatsWindow,
): DailyPoint[] {
const byDate = new Map(rows.map((row) => [row.date, row]));
const points: DailyPoint[] = [];
const start = new Date(window.toUtcExclusive.getTime() - window.days * 86_400_000);
for (let i = 0; i < window.days; i++) {
const day = new Date(start.getTime() + i * 86_400_000);
const date = day.toISOString().slice(0, 10);
const row = byDate.get(date);
points.push({
date,
downloads: row?.downloads ?? 0,
views: row?.views ?? 0,
searches: row?.searches ?? 0,
revenueCents: row?.revenueCents ?? 0,
});
}
return points;
}
export function formatBytes(bytes: number): string {
if (bytes <= 0) return "0 MB";
const mb = bytes / (1024 * 1024);
if (mb < 1024) return `${mb.toLocaleString("de-DE", { maximumFractionDigits: 1 })} MB`;
return `${(mb / 1024).toLocaleString("de-DE", { maximumFractionDigits: 2 })} GB`;
}
// ---------------------------------------------------------------------------
// Aggregates
// ---------------------------------------------------------------------------
export type StatsKpis = {
downloadsCompleted: number;
downloadsInterrupted: number;
downloadsFailed: number;
transferredBytes: number;
newUsages: number;
collabUsages: number;
revenueCents: number;
albumViews: number;
searches: number;
lightboxViews: number;
activeEditorials: number;
};
export type EditorialStatsRow = {
editorialId: string;
name: string;
downloads: number;
usages: number;
collabUsages: number;
revenueCents: number;
views: number;
searches: number;
};
export type AlbumStatsRow = {
albumKey: string;
albumName: string;
downloads: number;
revenueCents: number;
views: number;
};
export type RecentActivityRow = {
id: string;
editorialName: string;
eventType: string;
query: string | null;
occurredAt: Date;
};
export type StatsOverview = {
window: StatsWindow;
kpis: StatsKpis;
previousKpis: StatsKpis;
daily: DailyPoint[];
topEditorials: EditorialStatsRow[];
topAlbums: AlbumStatsRow[];
openRevenueCents: number;
finalizedReports: number;
recentActivity: RecentActivityRow[];
};
export function createStatsQueries({ database }: { database: NodePgDatabase<typeof schema> }) {
async function kpisFor(window: StatsWindow): Promise<StatsKpis> {
const from = window.fromUtc;
const to = window.toUtcExclusive;
const [downloads] = await database
.select({
completed: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'completed')::int`,
interrupted: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'interrupted')::int`,
failed: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'failed_before_delivery')::int`,
bytes: sql<string>`COALESCE(SUM(${downloadEvents.transferredBytes}) FILTER (WHERE ${downloadEvents.status} = 'completed'), 0)::text`,
activeEditorials: sql<number>`COUNT(DISTINCT ${downloadEvents.editorialAccountId})::int`,
})
.from(downloadEvents)
.where(and(gte(downloadEvents.authorizedAt, from), lt(downloadEvents.authorizedAt, to)));
const [usageStats] = await database
.select({
count: sql<number>`COUNT(*)::int`,
collab: sql<number>`COUNT(*) FILTER (WHERE ${usages.collab})::int`,
revenue: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)));
const [activity] = await database
.select({
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
lightbox: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'lightbox_view')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)));
return {
downloadsCompleted: downloads?.completed ?? 0,
downloadsInterrupted: downloads?.interrupted ?? 0,
downloadsFailed: downloads?.failed ?? 0,
transferredBytes: Number(downloads?.bytes ?? 0),
newUsages: usageStats?.count ?? 0,
collabUsages: usageStats?.collab ?? 0,
revenueCents: usageStats?.revenue ?? 0,
albumViews: activity?.views ?? 0,
searches: activity?.searches ?? 0,
lightboxViews: activity?.lightbox ?? 0,
activeEditorials: downloads?.activeEditorials ?? 0,
};
}
return {
async loadOverview(days: StatsPeriodDays, now: Date = new Date()): Promise<StatsOverview> {
const window = statsWindow(days, now);
const previous = previousWindow(window);
const from = window.fromUtc;
const to = window.toUtcExclusive;
const [kpis, previousKpis, dailyDownloads, dailyActivity, dailyRevenue, editorialUsageRows, editorialActivityRows, albumUsageRows, albumViewRows, openRevenue, finalizedReports, recentActivity] = await Promise.all([
kpisFor(window),
kpisFor(previous),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${downloadEvents.authorizedAt}), 'YYYY-MM-DD')`,
downloads: sql<number>`COUNT(*) FILTER (WHERE ${downloadEvents.status} = 'completed')::int`,
})
.from(downloadEvents)
.where(and(gte(downloadEvents.authorizedAt, from), lt(downloadEvents.authorizedAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${downloadEvents.authorizedAt})`),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${activityEvents.occurredAt}), 'YYYY-MM-DD')`,
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${activityEvents.occurredAt})`),
database
.select({
date: sql<string>`TO_CHAR(DATE_TRUNC('day', ${usages.createdAt}), 'YYYY-MM-DD')`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(sql`DATE_TRUNC('day', ${usages.createdAt})`),
database
.select({
editorialId: usages.editorialAccountId,
name: editorialAccounts.name,
usages: sql<number>`COUNT(*)::int`,
collabUsages: sql<number>`COUNT(*) FILTER (WHERE ${usages.collab})::int`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(usages.editorialAccountId, editorialAccounts.name),
database
.select({
editorialId: activityEvents.editorialAccountId,
views: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'album_view')::int`,
searches: sql<number>`COUNT(*) FILTER (WHERE ${activityEvents.eventType} = 'search')::int`,
})
.from(activityEvents)
.where(and(gte(activityEvents.occurredAt, from), lt(activityEvents.occurredAt, to)))
.groupBy(activityEvents.editorialAccountId),
database
.select({
albumKey: usages.immichAlbumIdSnapshot,
albumName: sql<string>`MAX(${usages.albumNameSnapshot})`,
downloads: sql<number>`COUNT(*)::int`,
revenueCents: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int`,
})
.from(usages)
.where(and(gte(usages.createdAt, from), lt(usages.createdAt, to)))
.groupBy(usages.immichAlbumIdSnapshot),
database
.select({
albumKey: activityEvents.immichAlbumId,
views: sql<number>`COUNT(*)::int`,
})
.from(activityEvents)
.where(
and(
gte(activityEvents.occurredAt, from),
lt(activityEvents.occurredAt, to),
eq(activityEvents.eventType, "album_view"),
),
)
.groupBy(activityEvents.immichAlbumId),
database
.select({ total: sql<number>`COALESCE(SUM(${usages.priceCents}), 0)::int` })
.from(usages)
.where(sql`${usages.billingStatus} in ('open', 'reopened')`),
database
.select({ count: sql<number>`COUNT(*)::int` })
.from(billingReports)
.where(
and(
eq(billingReports.status, "final"),
gte(billingReports.finalizedAt, from),
lt(billingReports.finalizedAt, to),
),
),
database
.select({
id: activityEvents.id,
editorialName: editorialAccounts.name,
eventType: activityEvents.eventType,
query: activityEvents.query,
occurredAt: activityEvents.occurredAt,
})
.from(activityEvents)
.innerJoin(editorialAccounts, eq(activityEvents.editorialAccountId, editorialAccounts.id))
.orderBy(desc(activityEvents.occurredAt))
.limit(15),
]);
const dailyMap = new Map<string, Partial<DailyPoint> & { date: string }>();
for (const row of dailyDownloads) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, downloads: row.downloads });
}
for (const row of dailyActivity) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, views: row.views, searches: row.searches });
}
for (const row of dailyRevenue) {
dailyMap.set(row.date, { ...dailyMap.get(row.date), date: row.date, revenueCents: row.revenueCents });
}
const activityByEditorial = new Map(editorialActivityRows.map((row) => [row.editorialId, row]));
const topEditorials: EditorialStatsRow[] = editorialUsageRows
.map((row) => ({
editorialId: row.editorialId,
name: row.name,
downloads: row.usages,
usages: row.usages,
collabUsages: row.collabUsages,
revenueCents: row.revenueCents,
views: activityByEditorial.get(row.editorialId)?.views ?? 0,
searches: activityByEditorial.get(row.editorialId)?.searches ?? 0,
}))
.sort((a, b) => b.downloads - a.downloads)
.slice(0, 8);
const viewsByAlbum = new Map(
albumViewRows.filter((row) => row.albumKey !== null).map((row) => [row.albumKey as string, row.views]),
);
const albumKeys = new Set([...albumUsageRows.map((row) => row.albumKey), ...viewsByAlbum.keys()]);
const usageByAlbum = new Map(albumUsageRows.map((row) => [row.albumKey, row]));
const topAlbums: AlbumStatsRow[] = [...albumKeys]
.map((key) => {
const usage = usageByAlbum.get(key);
return {
albumKey: key,
albumName: usage?.albumName ?? key,
downloads: usage?.downloads ?? 0,
revenueCents: usage?.revenueCents ?? 0,
views: viewsByAlbum.get(key) ?? 0,
};
})
.sort((a, b) => b.downloads + b.views - (a.downloads + a.views))
.slice(0, 8);
return {
window,
kpis,
previousKpis,
daily: fillDailySeries([...dailyMap.values()], window),
topEditorials,
topAlbums,
openRevenueCents: openRevenue[0]?.total ?? 0,
finalizedReports: finalizedReports[0]?.count ?? 0,
recentActivity,
};
},
};
}
export const statsQueries = createStatsQueries({ database: db });
+70
View File
@@ -0,0 +1,70 @@
import { expect, test, vi } from "vitest";
import {
CollabAdminError,
createCollabAdminService,
type CollabAdminRepository,
} from "./collab-admin";
const usageId = "1111111a-1111-4111-8111-11111111111a";
const adminUserId = "2222222b-2222-4222-8222-22222222222b";
function createRepo(overrides: Partial<Awaited<ReturnType<CollabAdminRepository["getUsageForCorrection"]>>> = {}) {
const repo: CollabAdminRepository = {
getUsageForCorrection: vi.fn().mockResolvedValue({
id: usageId,
editorialAccountId: "3333333c-3333-4333-8333-33333333333c",
billingStatus: "open",
collab: false,
priceCents: 1_500,
currentPriceCents: 1_500,
...overrides,
}),
updateUsageCollab: vi.fn().mockResolvedValue(undefined),
};
return repo;
}
test("marking collab zeroes the price", async () => {
const repo = createRepo();
const service = createCollabAdminService({ repo });
const result = await service.setUsageCollab({ usageId, collab: true, adminUserId });
expect(result.priceCents).toBe(0);
expect(repo.updateUsageCollab).toHaveBeenCalledWith(usageId, true, 0);
});
test("unmarking collab restores the editorial price", async () => {
const repo = createRepo({ collab: true, priceCents: 0 });
const service = createCollabAdminService({ repo });
const result = await service.setUsageCollab({ usageId, collab: false, adminUserId });
expect(result.priceCents).toBe(1_500);
expect(repo.updateUsageCollab).toHaveBeenCalledWith(usageId, false, 1_500);
});
test("billed usages cannot be corrected", async () => {
const repo = createRepo({ billingStatus: "billed" });
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: true, adminUserId }),
).rejects.toMatchObject({ code: "USAGE_NOT_EDITABLE" });
expect(repo.updateUsageCollab).not.toHaveBeenCalled();
});
test("unmarking without a valid editorial price fails", async () => {
const repo = createRepo({ collab: true, priceCents: 0, currentPriceCents: null });
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: false, adminUserId }),
).rejects.toBeInstanceOf(CollabAdminError);
});
test("missing usage is reported", async () => {
const repo: CollabAdminRepository = {
getUsageForCorrection: vi.fn().mockResolvedValue(null),
updateUsageCollab: vi.fn(),
};
const service = createCollabAdminService({ repo });
await expect(
service.setUsageCollab({ usageId, collab: true, adminUserId }),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
+118
View File
@@ -0,0 +1,118 @@
import "server-only";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
import { editorialAccounts, usages } from "@/db/schema";
import type * as schema from "@/db/schema";
import { writeAudit } from "@/modules/audit/write";
export class CollabAdminError extends Error {
readonly name = "CollabAdminError";
constructor(
readonly code: "USAGE_NOT_FOUND" | "USAGE_NOT_EDITABLE" | "INVALID_PRICE",
) {
super(code);
}
}
export type CollabAdminRepository = {
getUsageForCorrection(usageId: string): Promise<{
id: string;
editorialAccountId: string;
billingStatus: "open" | "billed" | "reopened" | "voided";
collab: boolean;
priceCents: number;
currentPriceCents: number | null;
} | null>;
updateUsageCollab(usageId: string, collab: boolean, priceCents: number): Promise<void>;
};
/**
* Admin correction of the collab flag on open usages, so wrong entries can be
* fixed before the Nutzungsnachweis is finalized and sent. Marking collab sets
* the price to 0; unmarking restores the editorial's current price.
*/
export function createCollabAdminService({ repo }: { repo: CollabAdminRepository }) {
return {
async setUsageCollab(input: {
usageId: string;
collab: boolean;
adminUserId: string;
}): Promise<{ priceCents: number }> {
const usage = await repo.getUsageForCorrection(input.usageId);
if (!usage) throw new CollabAdminError("USAGE_NOT_FOUND");
if (usage.billingStatus !== "open" && usage.billingStatus !== "reopened") {
throw new CollabAdminError("USAGE_NOT_EDITABLE");
}
let priceCents: number;
if (input.collab) {
priceCents = 0;
} else {
if (
!Number.isSafeInteger(usage.currentPriceCents) ||
(usage.currentPriceCents ?? 0) <= 0
) {
throw new CollabAdminError("INVALID_PRICE");
}
priceCents = usage.currentPriceCents!;
}
await repo.updateUsageCollab(input.usageId, input.collab, priceCents);
try {
await writeAudit({
type: "usage_collab_updated",
actorUserId: input.adminUserId,
actorType: "admin",
entityType: "usage",
entityId: input.usageId,
metadata: {
from: { collab: usage.collab, priceCents: usage.priceCents },
to: { collab: input.collab, priceCents },
},
});
} catch {
// Audit is observability, not a transaction participant.
}
return { priceCents };
},
};
}
export function createCollabAdminRepository(
database: NodePgDatabase<typeof schema>,
): CollabAdminRepository {
return {
async getUsageForCorrection(usageId) {
const [row] = await database
.select({
id: usages.id,
editorialAccountId: usages.editorialAccountId,
billingStatus: usages.billingStatus,
collab: usages.collab,
priceCents: usages.priceCents,
currentPriceCents: editorialAccounts.currentPriceCents,
})
.from(usages)
.innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id))
.where(eq(usages.id, usageId))
.limit(1);
return row ?? null;
},
async updateUsageCollab(usageId, collab, priceCents) {
await database
.update(usages)
.set({ collab, priceCents })
.where(eq(usages.id, usageId));
},
};
}
export const collabAdminService = createCollabAdminService({
repo: createCollabAdminRepository(db),
});
export const setUsageCollab = collabAdminService.setUsageCollab;
+20 -9
View File
@@ -46,6 +46,7 @@ export type BillableIntentInput = {
reference?: string;
idempotencyKey: string;
requestFingerprint: string;
collab?: boolean;
};
export type UsageRepository = {
@@ -144,6 +145,7 @@ export function createUsageServiceRepository(
flatrateActive: editorialAccounts.flatrateActive,
flatratePriceCents: editorialAccounts.flatratePriceCents,
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
collabEnabled: editorialAccounts.collabEnabled,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, input.editorialId))
@@ -152,9 +154,15 @@ export function createUsageServiceRepository(
if (!editorial || editorial.status !== "active") {
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
}
// Collab usages are free, but only for editorials the admin enabled.
const collab = input.collab === true;
if (collab && !editorial.collabEnabled) {
throw new UsageAccountingError("COLLAB_NOT_ENABLED");
}
if (
!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0
!collab &&
(!Number.isSafeInteger(editorial.currentPriceCents) ||
(editorial.currentPriceCents ?? 0) <= 0)
) {
throw new UsageAccountingError("INVALID_PRICE");
}
@@ -173,9 +181,9 @@ export function createUsageServiceRepository(
.limit(1);
if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED");
let priceCents = editorial.currentPriceCents!;
if (editorial.flatrateActive) {
let priceCents = collab ? 0 : editorial.currentPriceCents!;
if (!collab && editorial.flatrateActive) {
if (
!Number.isSafeInteger(editorial.flatratePriceCents) ||
(editorial.flatratePriceCents ?? 0) <= 0
@@ -197,10 +205,10 @@ export function createUsageServiceRepository(
sql`${usages.createdAt} >= ${period.fromUtc}`,
sql`${usages.createdAt} < ${period.toUtcExclusive}`,
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
// For flatrate, we only count usages that were originally free via the flatrate
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?
// Yes, any billable usage this month counts towards the limit.
eq(usages.priceCents, 0)
// Flatrate usages are the free ones (priceCents = 0). Collab
// usages are also free but must NOT consume the flatrate limit.
eq(usages.priceCents, 0),
eq(usages.collab, false)
)
);
@@ -227,6 +235,7 @@ export function createUsageServiceRepository(
purpose: input.purpose,
internalReference: input.reference,
priceCents: priceCents,
collab,
billingStatus: "open",
createdAt,
})
@@ -261,6 +270,7 @@ export function createUsageServiceRepository(
assetId: input.assetId,
albumId: input.albumId,
priceCents: priceCents,
collab,
downloadId: event.id,
},
occurredAt: createdAt,
@@ -334,6 +344,7 @@ function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput
purpose,
...(reference === undefined ? {} : { reference }),
idempotencyKey: normalizeUuid(input.idempotencyKey),
...(input.collab === true ? { collab: true } : {}),
};
}
+7 -1
View File
@@ -7,6 +7,8 @@ export type CreateNewUsageInput = {
purpose: string;
reference?: string;
idempotencyKey: string;
/** Free collaborative usage; only honoured when the editorial is collab-enabled. */
collab?: boolean;
};
export type CreateRepeatDownloadInput = {
@@ -49,7 +51,8 @@ export type UsageAccountingErrorCode =
| "ASSET_NOT_FOUND"
| "ASSET_NOT_IMAGE"
| "IMMICH_UNAVAILABLE"
| "USAGE_NOT_FOUND";
| "USAGE_NOT_FOUND"
| "COLLAB_NOT_ENABLED";
export class UsageAccountingError extends Error {
readonly name = "UsageAccountingError";
@@ -59,6 +62,9 @@ export class UsageAccountingError extends Error {
}
}
// The new_usage payload must stay byte-compatible with the fingerprint
// reconstruction in the historical accounting migrations (0001/0002), so
// later request fields like `collab` are deliberately NOT part of it.
type FingerprintPayload =
| {
kind: "new_usage";