diff --git a/AI_MEMORY.md b/AI_MEMORY.md index 2b7f57b..e91a835 100644 --- a/AI_MEMORY.md +++ b/AI_MEMORY.md @@ -41,6 +41,7 @@ Redaktionen können Bilder durchsuchen, einen Leuchtkasten verwenden, Bilder her ## 6. Admin-Bereich & Freigaben - **Redaktions-Freigabe:** Wenn eine Redaktion den Status `pending_approval` hat, wird sie im Admin-Detail-Dashboard über die `ApproveForm` freigegeben. In diesem Schritt *muss* der Admin zwingend einen individuellen Nettopreis für die Redaktion festlegen. Ohne das Setzen des Preises bleibt die Redaktion gesperrt. +- **Admin-Alben-Tab (Stand 2026-09):** Unter `/admin/alben` gibt es eine zentrale Albumzugriffs-Übersicht: alle Immich-Alben mit den Redaktionen, die Zugriff haben (Chips mit Link + Ein-Klick-Entziehen pro Paar), plus **Bulk-Zuweisung** (mehrere Alben × mehrere Redaktionen per Checkbox, „Alle auswählen", ein Submit). Logik: `albumGrantService.listAlbumAccessOverview()` + `bulkGrantAlbums()` in `src/modules/albums/grants.ts` (Album-Existenz wird EINMAL per `listAlbums` geprüft statt `getAlbum` pro Paar; bereits aktive Paare werden übersprungen; jedes Paar committet in eigener Transaktion und schreibt ein `album_granted`-Audit-Event; ein fehlgeschlagenes Paar bricht den Rest nicht ab). Actions: `src/app/admin/alben/actions.ts` (bulkGrant/revoke, revalidiert `/admin/alben` + jede betroffene `/admin/redaktionen/[id]/alben`). Bulk-Auswahl: nur nicht-archivierte Redaktionen; archivierte erscheinen weiterhin als Chip in der Übersicht. ## 7. Auth-Härtung (Stand 2026) - **PROD-MIGRATION-BASELINE (erledigt 2026-08-25):** Die frühere Abweichung zwischen Prod-Journal (Stand 0006) und Schema wurde per History-Squash behoben: `drizzle/` enthält nur noch `0000_baseline.sql` (aus dem aktuellen Schema generiert, Snapshot = altes 0012-Snapshot semantisch identisch, via pg_dump-Diff gegen die alte Migrationskette verifiziert). Der Journal-Eintrag der Baseline trägt bewusst das **Original-Timestamp der alten Migration 0000** (`1786299825190`) – der Drizzle-Migrator vergleicht `created_at` der Tabelle `drizzle.__drizzle_migrations` mit dem Journal-`when`, daher wird die Baseline auf jeder bestehenden DB (Prod, Dev) übersprungen und nur auf frischen DBs angewendet. Zukünftige Migrationen (`drizzle-kit generate`) greifen damit auf allen Umgebungen automatisch. Alte Migrationsdateien + Snapshots liegen in `drizzle-history/pre-squash-2026-08/` und werden NUR von den Historie-Tests genutzt (`tests/db/postgres.ts` akzeptiert dafür `migrationsDir`). Erste Ausführung von `docker compose --profile ops run --rm migrate` auf PROD ist ein No-op (Baseline skippt), danach laufen neue Migrationen normal. diff --git a/src/app/admin/alben/AlbumAccessManager.test.tsx b/src/app/admin/alben/AlbumAccessManager.test.tsx new file mode 100644 index 0000000..4b2aac9 --- /dev/null +++ b/src/app/admin/alben/AlbumAccessManager.test.tsx @@ -0,0 +1,163 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { afterEach, expect, test, vi } from "vitest"; + +import { + AlbumAccessManager, + type AlbumAccessManagerAlbum, + type AlbumAccessManagerEditorial, +} from "./AlbumAccessManager"; +import type { AlbumAccessActionResult } from "./actions"; + +afterEach(cleanup); + +const albumOne = "11111111-1111-4111-8111-111111111111"; +const albumTwo = "22222222-2222-4222-8222-222222222222"; +const editorialOne = "33333333-3333-4333-8333-333333333333"; +const editorialTwo = "44444444-4444-4444-8444-444444444444"; + +const albums: AlbumAccessManagerAlbum[] = [ + { + id: albumOne, + albumName: "Pressefotos", + albumThumbnailAssetId: null, + assetCount: 4, + grants: [ + { editorialId: editorialOne, editorialName: "Kicker Daily", archived: false }, + ], + }, + { + id: albumTwo, + albumName: "Spieltagfotos", + albumThumbnailAssetId: null, + assetCount: 12, + grants: [], + }, +]; + +const editorials: AlbumAccessManagerEditorial[] = [ + { id: editorialOne, name: "Kicker Daily" }, + { id: editorialTwo, name: "Sport Woche" }, +]; + +const okResult: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 }; + +function setup() { + const bulkGrantAction = vi.fn().mockResolvedValue(okResult); + const revokeAction = vi.fn().mockResolvedValue(okResult); + render( + , + ); + return { bulkGrantAction, revokeAction }; +} + +function bulkFieldset() { + return within( + screen + .getByLabelText("Alben für die Bulk-Zuweisung durchsuchen") + .closest("fieldset") as HTMLFieldSetElement, + ); +} + +function overviewTable() { + return within(screen.getByRole("table")); +} + +test("lists every album with its granted editorials and a link to the editorial", () => { + setup(); + + const overview = overviewTable(); + const pressefotosRow = overview.getByText("Pressefotos").closest("tr"); + expect(pressefotosRow?.textContent).toContain("Kicker Daily"); + expect( + overview + .getByRole("link", { name: "Kicker Daily" }) + .getAttribute("href") + ?.startsWith("/admin/redaktionen/33333333"), + ).toBe(true); + const spieltagRow = overview.getByText("Spieltagfotos").closest("tr"); + expect(spieltagRow?.textContent).toContain("Noch keine Redaktion"); +}); + +test("the grant button stays disabled until an album and an editorial are selected", () => { + setup(); + + const grantButton = screen.getByRole("button", { + name: "Zugriff gewähren", + }) as HTMLButtonElement; + expect(grantButton.disabled).toBe(true); + + fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Pressefotos/ })); + expect(grantButton.disabled).toBe(true); + + fireEvent.click(screen.getByRole("checkbox", { name: "Sport Woche" })); + expect( + screen.getByRole("button", { name: "Zugriff gewähren (1 Album, 1 Redaktion)" }), + ).toBeTruthy(); +}); + +test("selects all albums via Alle auswählen and clears them again", () => { + setup(); + + fireEvent.click(bulkFieldset().getByRole("button", { name: /Alle auswählen/i })); + expect( + screen.getByRole("button", { name: "Zugriff gewähren (2 Alben, 0 Redaktionen)" }), + ).toBeTruthy(); + + fireEvent.click(bulkFieldset().getByRole("button", { name: /Auswahl aufheben/i })); + expect(screen.getByRole("button", { name: "Zugriff gewähren" })).toBeTruthy(); +}); + +test("the album search narrows the bulk selection and select-all respects the filter", () => { + setup(); + + fireEvent.change(screen.getByLabelText("Alben für die Bulk-Zuweisung durchsuchen"), { + target: { value: "Spieltag" }, + }); + + expect(bulkFieldset().queryByRole("checkbox", { name: /Pressefotos/ })).toBeNull(); + fireEvent.click(bulkFieldset().getByRole("button", { name: /Alle auswählen/i })); + expect( + screen.getByRole("button", { name: "Zugriff gewähren (1 Album, 0 Redaktionen)" }), + ).toBeTruthy(); +}); + +test("the selected checkboxes carry album and editorial ids for the server action", () => { + const { bulkGrantAction } = setup(); + const form = screen + .getByRole("button", { name: "Zugriff gewähren" }) + .closest("form") as HTMLFormElement; + + fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Pressefotos/ })); + fireEvent.click(bulkFieldset().getByRole("checkbox", { name: /Spieltagfotos/ })); + fireEvent.click(screen.getByRole("checkbox", { name: "Sport Woche" })); + + const albumValues = [...form.querySelectorAll('input[name="immichAlbumIds"]')] + .filter((input) => input.checked) + .map((input) => input.value); + const editorialValues = [...form.querySelectorAll('input[name="editorialIds"]')] + .filter((input) => input.checked) + .map((input) => input.value); + + expect(albumValues).toEqual([albumOne, albumTwo]); + expect(editorialValues).toEqual([editorialTwo]); + expect(bulkGrantAction).not.toHaveBeenCalled(); +}); + +test("the overview search matches album names and granted editorial names", () => { + setup(); + + fireEvent.change(screen.getByLabelText("Albumzugriffe durchsuchen"), { + target: { value: "Kicker" }, + }); + + const overview = overviewTable(); + expect(overview.queryByText("Spieltagfotos")).toBeNull(); + expect(overview.getByText("Pressefotos")).toBeTruthy(); +}); diff --git a/src/app/admin/alben/AlbumAccessManager.tsx b/src/app/admin/alben/AlbumAccessManager.tsx new file mode 100644 index 0000000..d2876cb --- /dev/null +++ b/src/app/admin/alben/AlbumAccessManager.tsx @@ -0,0 +1,410 @@ +"use client"; + +/* eslint-disable @next/next/no-img-element */ + +import { useActionState, useMemo, useState, useTransition } from "react"; +import Link from "next/link"; + +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import type { AlbumAccessActionResult } from "./actions"; + +type AccessAction = ( + state: AlbumAccessActionResult, + formData: FormData, +) => Promise; + +export type AlbumAccessManagerAlbum = { + id: string; + albumName: string; + albumThumbnailAssetId: string | null; + assetCount: number; + grants: Array<{ editorialId: string; editorialName: string; archived: boolean }>; +}; + +export type AlbumAccessManagerEditorial = { id: string; name: string }; + +const INITIAL_RESULT: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 }; + +export function AlbumAccessManager({ + albums, + editorials, + bulkGrantAction, + revokeAction, +}: Readonly<{ + albums: AlbumAccessManagerAlbum[]; + editorials: AlbumAccessManagerEditorial[]; + bulkGrantAction: AccessAction; + revokeAction: AccessAction; +}>) { + const [bulkState, setBulkState] = useState(INITIAL_RESULT); + const [bulkPending, startBulkTransition] = useTransition(); + const [revokeState, revokeFormAction, revokePending] = useActionState( + revokeAction, + INITIAL_RESULT, + ); + const [selectedAlbumIds, setSelectedAlbumIds] = useState>(new Set()); + const [selectedEditorialIds, setSelectedEditorialIds] = useState>(new Set()); + const [bulkSearch, setBulkSearch] = useState(""); + const [overviewSearch, setOverviewSearch] = useState(""); + + // Same selection flow as the single-editorial AlbumGrid: call the action in a + // transition so the result can clear the checkboxes without an effect. + const handleBulkSubmit = (formData: FormData) => { + startBulkTransition(async () => { + const result = await bulkGrantAction(INITIAL_RESULT, formData); + setBulkState(result); + if (result.ok && result.grantedCount > 0) { + setSelectedAlbumIds(new Set()); + setSelectedEditorialIds(new Set()); + } + }); + }; + + const bulkQuery = bulkSearch.trim().toLowerCase(); + const bulkAlbums = useMemo( + () => + bulkQuery + ? albums.filter((album) => album.albumName.toLowerCase().includes(bulkQuery)) + : albums, + [albums, bulkQuery], + ); + + const overviewQuery = overviewSearch.trim().toLowerCase(); + const overviewAlbums = useMemo( + () => + overviewQuery + ? albums.filter( + (album) => + album.albumName.toLowerCase().includes(overviewQuery) || + album.grants.some((holder) => + holder.editorialName.toLowerCase().includes(overviewQuery), + ), + ) + : albums, + [albums, overviewQuery], + ); + + const allBulkAlbumsSelected = + bulkAlbums.length > 0 && bulkAlbums.every((album) => selectedAlbumIds.has(album.id)); + const allEditorialsSelected = + editorials.length > 0 && editorials.every((editorial) => selectedEditorialIds.has(editorial.id)); + + const toggleAlbumSelection = (albumId: string, selected: boolean) => { + setSelectedAlbumIds((previous) => { + const next = new Set(previous); + if (selected) { + next.add(albumId); + } else { + next.delete(albumId); + } + return next; + }); + }; + + const toggleEditorialSelection = (editorialId: string, selected: boolean) => { + setSelectedEditorialIds((previous) => { + const next = new Set(previous); + if (selected) { + next.add(editorialId); + } else { + next.delete(editorialId); + } + return next; + }); + }; + + const toggleAllBulkAlbums = () => { + setSelectedAlbumIds((previous) => { + const next = new Set(previous); + for (const album of bulkAlbums) { + if (allBulkAlbumsSelected) { + next.delete(album.id); + } else { + next.add(album.id); + } + } + return next; + }); + }; + + const toggleAllEditorials = () => { + setSelectedEditorialIds((previous) => { + const next = new Set(previous); + for (const editorial of editorials) { + if (allEditorialsSelected) { + next.delete(editorial.id); + } else { + next.add(editorial.id); + } + } + return next; + }); + }; + + const canSubmit = selectedAlbumIds.size > 0 && selectedEditorialIds.size > 0; + const submitLabel = + selectedAlbumIds.size === 0 && selectedEditorialIds.size === 0 + ? "Zugriff gewähren" + : `Zugriff gewähren (${selectedAlbumIds.size} ${ + selectedAlbumIds.size === 1 ? "Album" : "Alben" + }, ${selectedEditorialIds.size} ${ + selectedEditorialIds.size === 1 ? "Redaktion" : "Redaktionen" + })`; + + return ( +
+ + + Bulk-Zuweisung + + Alben und Redaktionen auswählen und allen ausgewählten Redaktionen mit einem Klick + Zugriff auf alle ausgewählten Alben geben. Bereits bestehende Zuweisungen werden + übersprungen. + + + +
+
+
+ + Alben ({selectedAlbumIds.size} ausgewählt) + +
+ setBulkSearch(event.target.value)} + placeholder="Alben suchen…" + aria-label="Alben für die Bulk-Zuweisung durchsuchen" + /> + +
+
+ {bulkAlbums.length === 0 ? ( +

Keine Alben gefunden.

+ ) : ( + bulkAlbums.map((album) => ( + + )) + )} +
+
+ +
+ + Redaktionen ({selectedEditorialIds.size} ausgewählt) + +
+ +
+
+ {editorials.length === 0 ? ( +

+ Keine aktiven Redaktionen vorhanden. +

+ ) : ( + editorials.map((editorial) => ( + + )) + )} +
+
+
+ +
+ {bulkState.message ? ( +

+ {bulkState.message} +

+ ) : ( +

+ Wähle mindestens ein Album und eine Redaktion aus. +

+ )} + +
+
+
+
+ + + +
+ Albumzugriffe + + Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den + Zugriff für die einzelne Redaktion. + +
+
+ setOverviewSearch(event.target.value)} + placeholder="Album oder Redaktion suchen…" + aria-label="Albumzugriffe durchsuchen" + /> +
+
+ + {revokeState.message ? ( +

+ {revokeState.message} +

+ ) : null} + + {albums.length === 0 ? ( +

Derzeit sind keine Alben vorhanden.

+ ) : overviewAlbums.length === 0 ? ( +

Keine Alben gefunden.

+ ) : ( +
+ + + + + + + + + + {overviewAlbums.map((album, index) => ( + + + + + + ))} + +
AlbumRedaktionen mit ZugriffAnzahl
+
+ {album.albumThumbnailAssetId ? ( + + ) : ( + + )} +
+

+ {album.albumName} +

+

{album.assetCount} Fotos

+
+
+
+ {album.grants.length === 0 ? ( + Noch keine Redaktion + ) : ( +
+ {album.grants.map((holder) => ( +
+ + + + {holder.editorialName} + {holder.archived ? " (archiviert)" : ""} + + +
+ ))} +
+ )} +
{album.grants.length}
+
+ )} +
+
+
+ ); +} diff --git a/src/app/admin/alben/actions.test.ts b/src/app/admin/alben/actions.test.ts new file mode 100644 index 0000000..8ab44d1 --- /dev/null +++ b/src/app/admin/alben/actions.test.ts @@ -0,0 +1,146 @@ +import { beforeEach, expect, test, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + bulkGrantAlbums: vi.fn(), + headers: vi.fn(), + requireAdmin: vi.fn(), + revalidatePath: vi.fn(), + revokeAlbum: vi.fn(), +})); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +vi.mock("next/headers", () => ({ headers: mocks.headers })); +vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath })); +vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin })); +vi.mock("@/modules/albums/grants", () => ({ + AlbumGrantError: class AlbumGrantError extends Error { + constructor(readonly code: string) { + super(code); + } + }, + albumGrantService: { bulkGrantAlbums: mocks.bulkGrantAlbums, revokeAlbum: mocks.revokeAlbum }, +})); + +import { bulkGrantAlbumAccessAction, revokeAlbumAccessAction } from "./actions"; + +const initial = { ok: true, message: "", grantedCount: 0 }; +const albumOne = "11111111-1111-4111-8111-111111111111"; +const albumTwo = "22222222-2222-4222-8222-222222222222"; +const editorialOne = "33333333-3333-4333-8333-333333333333"; +const editorialTwo = "44444444-4444-4444-8444-444444444444"; + +function bulkFormData(): FormData { + const formData = new FormData(); + for (const albumId of [albumOne, albumTwo]) { + formData.append("immichAlbumIds", albumId); + } + for (const editorialId of [editorialOne, editorialTwo]) { + formData.append("editorialIds", editorialId); + } + return formData; +} + +test("the bulk action rejects unauthenticated callers before touching the service", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED")); + + await expect(bulkGrantAlbumAccessAction(initial, bulkFormData())).rejects.toThrow( + "ADMIN_REQUIRED", + ); + expect(mocks.bulkGrantAlbums).not.toHaveBeenCalled(); +}); + +test("the bulk action demands at least one album and one editorial", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + + const result = await bulkGrantAlbumAccessAction(initial, new FormData()); + + expect(result).toMatchObject({ ok: false, grantedCount: 0 }); + expect(result.message).toContain("mindestens ein Album und eine Redaktion"); + expect(mocks.bulkGrantAlbums).not.toHaveBeenCalled(); +}); + +test("the bulk action grants every selected combination and revalidates affected pages", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + mocks.bulkGrantAlbums.mockResolvedValue({ granted: 4, skipped: 0, failed: 0 }); + + const result = await bulkGrantAlbumAccessAction(initial, bulkFormData()); + + expect(mocks.bulkGrantAlbums).toHaveBeenCalledWith({ + albumIds: [albumOne, albumTwo], + editorialIds: [editorialOne, editorialTwo], + adminUserId: "admin-1", + }); + expect(result).toMatchObject({ ok: true, grantedCount: 4 }); + expect(result.message).toContain("4 Zuweisung(en) erstellt"); + expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/alben"); + expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialOne}/alben`); + expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialTwo}/alben`); +}); + +test("the bulk action reports skipped and failed pairs in German", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + mocks.bulkGrantAlbums.mockResolvedValue({ granted: 1, skipped: 2, failed: 1 }); + + const result = await bulkGrantAlbumAccessAction(initial, bulkFormData()); + + expect(result.ok).toBe(false); + expect(result.message).toContain("1 Zuweisung(en) erstellt"); + expect(result.message).toContain("2 bestand(en) bereits"); + expect(result.message).toContain("1 fehlgeschlagen"); +}); + +test("the bulk action returns a German message when Immich is down", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + const { AlbumGrantError } = await import("@/modules/albums/grants"); + mocks.bulkGrantAlbums.mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE")); + + const result = await bulkGrantAlbumAccessAction(initial, bulkFormData()); + + expect(result).toMatchObject({ + ok: false, + grantedCount: 0, + message: "Immich ist momentan nicht erreichbar. Bitte später erneut versuchen.", + }); + expect(mocks.revalidatePath).not.toHaveBeenCalled(); +}); + +test("the revoke action entzieht a single album-editorial pair", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + mocks.revokeAlbum.mockResolvedValue(undefined); + const formData = new FormData(); + formData.set("immichAlbumId", albumOne); + formData.set("editorialId", editorialOne); + + const result = await revokeAlbumAccessAction(initial, formData); + + expect(mocks.revokeAlbum).toHaveBeenCalledWith({ + editorialId: editorialOne, + immichAlbumId: albumOne, + adminUserId: "admin-1", + }); + expect(result).toEqual({ ok: true, message: "", grantedCount: 0 }); + expect(mocks.revalidatePath).toHaveBeenCalledWith("/admin/alben"); + expect(mocks.revalidatePath).toHaveBeenCalledWith(`/admin/redaktionen/${editorialOne}/alben`); +}); + +test("the revoke action rejects malformed identifiers", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + const formData = new FormData(); + formData.set("immichAlbumId", "not-a-uuid"); + formData.set("editorialId", editorialOne); + + const result = await revokeAlbumAccessAction(initial, formData); + + expect(result).toMatchObject({ ok: false, grantedCount: 0 }); + expect(mocks.revokeAlbum).not.toHaveBeenCalled(); +}); diff --git a/src/app/admin/alben/actions.ts b/src/app/admin/alben/actions.ts new file mode 100644 index 0000000..56d887a --- /dev/null +++ b/src/app/admin/alben/actions.ts @@ -0,0 +1,112 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { headers } from "next/headers"; + +import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants"; +import { requireAdmin } from "@/modules/auth/principal"; + +// Returned to the client form so failures surface as inline German text +// instead of an opaque Next.js error-digest page (a thrown server action +// becomes a 500 with a digest the user can't read). +export type AlbumAccessActionResult = { + ok: boolean; + message: string; + grantedCount: number; +}; + +const INITIAL_RESULT: AlbumAccessActionResult = { ok: true, message: "", grantedCount: 0 }; + +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 async function bulkGrantAlbumAccessAction( + _prevState: AlbumAccessActionResult, + formData: FormData, +): Promise { + const principal = await requireAdmin(new Headers(await headers())); + const albumIds = formData.getAll("immichAlbumIds").filter(isValidUuid); + const editorialIds = formData.getAll("editorialIds").filter(isValidUuid); + + if (albumIds.length === 0 || editorialIds.length === 0) { + return { + ok: false, + message: "Bitte mindestens ein Album und eine Redaktion auswählen.", + grantedCount: 0, + }; + } + + let result: Awaited>; + try { + result = await albumGrantService.bulkGrantAlbums({ + albumIds, + editorialIds, + adminUserId: principal.userId, + }); + } catch (error) { + return { ok: false, message: albumGrantErrorMessage(error), grantedCount: 0 }; + } + + revalidatePath("/admin/alben"); + for (const editorialId of editorialIds) { + revalidatePath(`/admin/redaktionen/${editorialId}/alben`); + } + + const parts: string[] = []; + if (result.granted > 0) parts.push(`${result.granted} Zuweisung(en) erstellt`); + if (result.skipped > 0) parts.push(`${result.skipped} bestand(en) bereits`); + if (result.failed > 0) parts.push(`${result.failed} fehlgeschlagen`); + return { + ok: result.failed === 0, + message: + parts.length > 0 + ? `${parts.join(", ")}.` + : "Es gab nichts zu zuweisen — alle ausgewählten Kombinationen bestanden bereits.", + grantedCount: result.granted, + }; +} + +export async function revokeAlbumAccessAction( + _prevState: AlbumAccessActionResult, + formData: FormData, +): Promise { + const principal = await requireAdmin(new Headers(await headers())); + const immichAlbumId = formData.get("immichAlbumId"); + const editorialId = formData.get("editorialId"); + if (!isValidUuid(immichAlbumId) || !isValidUuid(editorialId)) { + return { ok: false, message: "Ungültige Kennung.", grantedCount: 0 }; + } + + try { + await albumGrantService.revokeAlbum({ + editorialId, + immichAlbumId, + adminUserId: principal.userId, + }); + } catch (error) { + return { ok: false, message: albumGrantErrorMessage(error), grantedCount: 0 }; + } + + revalidatePath("/admin/alben"); + revalidatePath(`/admin/redaktionen/${editorialId}/alben`); + return INITIAL_RESULT; +} + +function isValidUuid(value: FormDataEntryValue | null): value is string { + return typeof value === "string" && UUID_PATTERN.test(value); +} + +function albumGrantErrorMessage(error: unknown): string { + if (error instanceof AlbumGrantError) { + const messages: Record = { + ALBUM_NOT_ASSIGNABLE: + "Mindestens ein Album konnte nicht gefunden werden oder lässt sich nicht zuweisen.", + IMMICH_UNAVAILABLE: + "Immich ist momentan nicht erreichbar. Bitte später erneut versuchen.", + EDITORIAL_NOT_FOUND: "Redaktion nicht gefunden.", + INVALID_ALBUM_GRANT_INPUT: "Ungültige Auswahl.", + }; + return messages[error.code] ?? "Die Zuweisung ist fehlgeschlagen."; + } + return "Die Zuweisung ist fehlgeschlagen."; +} diff --git a/src/app/admin/alben/page-content.test.ts b/src/app/admin/alben/page-content.test.ts new file mode 100644 index 0000000..61c1305 --- /dev/null +++ b/src/app/admin/alben/page-content.test.ts @@ -0,0 +1,25 @@ +import { expect, test, vi } from "vitest"; + +import { AlbumGrantError } from "@/modules/albums/grants"; + +import { loadAlbumAccess } from "./page-content"; + +test("only an explicit Immich-unavailable error renders the unavailable album state", async () => { + const unavailableService = { + listAlbumAccessOverview: vi.fn().mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE")), + }; + + await expect(loadAlbumAccess(unavailableService)).resolves.toEqual({ + albums: [], + unavailable: true, + }); +}); + +test("database and programming errors propagate instead of being displayed as Immich unavailable", async () => { + const databaseFailure = new Error("database connection lost"); + const failingService = { + listAlbumAccessOverview: vi.fn().mockRejectedValue(databaseFailure), + }; + + await expect(loadAlbumAccess(failingService)).rejects.toBe(databaseFailure); +}); diff --git a/src/app/admin/alben/page-content.ts b/src/app/admin/alben/page-content.ts new file mode 100644 index 0000000..e9fcf75 --- /dev/null +++ b/src/app/admin/alben/page-content.ts @@ -0,0 +1,38 @@ +import { asc, isNull } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { + AlbumGrantError, + albumGrantService, + type AlbumAccessOverviewAlbum, +} from "@/modules/albums/grants"; + +export type EditorialOption = { id: string; name: string }; + +export async function loadAlbumAccess( + service: Pick = albumGrantService, +): Promise<{ albums: AlbumAccessOverviewAlbum[]; unavailable: boolean }> { + try { + const albums = await service.listAlbumAccessOverview(); + return { albums, unavailable: false }; + } catch (error) { + if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") { + return { albums: [], unavailable: true }; + } + throw error; + } +} + +/** + * Bulk-grant targets: every non-archived editorial. Archived accounts cannot + * log in anymore, so they stay out of the selection; grants they still hold + * remain visible in the overview. + */ +export async function loadAssignableEditorials(): Promise { + return db + .select({ id: editorialAccounts.id, name: editorialAccounts.name }) + .from(editorialAccounts) + .where(isNull(editorialAccounts.archivedAt)) + .orderBy(asc(editorialAccounts.name)); +} diff --git a/src/app/admin/alben/page.tsx b/src/app/admin/alben/page.tsx new file mode 100644 index 0000000..592db92 --- /dev/null +++ b/src/app/admin/alben/page.tsx @@ -0,0 +1,57 @@ +import Link from "next/link"; + +import { PageHeader } from "@/components/ui/page-header"; + +import { loadAlbumAccess, loadAssignableEditorials } from "./page-content"; +import { AlbumAccessManager } from "./AlbumAccessManager"; +import { bulkGrantAlbumAccessAction, revokeAlbumAccessAction } from "./actions"; + +export default async function AdminAlbumsPage() { + const [albumResult, editorials] = await Promise.all([ + loadAlbumAccess(), + loadAssignableEditorials(), + ]); + + return ( +
+ + + {albumResult.unavailable ? ( +
+ Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben + unverändert. +
+ ) : ( + ({ + id: album.id, + albumName: album.albumName, + albumThumbnailAssetId: album.albumThumbnailAssetId, + assetCount: album.assetCount, + grants: album.grants.map((holder) => ({ + editorialId: holder.editorialId, + editorialName: holder.editorialName, + archived: holder.archivedAt !== null, + })), + }))} + editorials={editorials} + bulkGrantAction={bulkGrantAlbumAccessAction} + revokeAction={revokeAlbumAccessAction} + /> + )} + +

+ + Zu den Redaktionen + +

+
+ ); +} diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index 421f306..051115f 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -14,6 +14,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea nav={[ { href: "/admin", label: "Dashboard" }, { href: "/admin/redaktionen", label: "Redaktionen" }, + { href: "/admin/alben", label: "Alben" }, { href: "/admin/abrechnungen", label: "Abrechnungen" }, { href: "/admin/audit", label: "Audit" }, ]} diff --git a/src/modules/albums/auto-rules.test.ts b/src/modules/albums/auto-rules.test.ts index 277618e..841b96c 100644 --- a/src/modules/albums/auto-rules.test.ts +++ b/src/modules/albums/auto-rules.test.ts @@ -42,6 +42,14 @@ function createFakeGrantService(initial: FakeGrant[] = []) { .filter((grant) => grant.editorialId === editorialId) .map((grant) => grant.albumId); }, + async listActiveGrantsWithEditorials() { + return grants.map((grant) => ({ + immichAlbumId: grant.albumId, + editorialId: grant.editorialId, + editorialName: "Fake Redaktion", + archivedAt: null, + })); + }, async grant(input) { grantInputs.push({ editorialId: input.editorialId, diff --git a/src/modules/albums/grants.test.ts b/src/modules/albums/grants.test.ts index 3fa5e8f..4701c2b 100644 --- a/src/modules/albums/grants.test.ts +++ b/src/modules/albums/grants.test.ts @@ -9,6 +9,7 @@ import { type AlbumGrantRepository, } from "./grants"; 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 Audit = { @@ -19,11 +20,32 @@ type Audit = { previousValues: Record; newValues: Record; }; +type EditorialDirectoryEntry = { name: string; archivedAt: Date | null }; const editorialUuid = "1111111a-1111-4111-8111-11111111111a"; const albumUuid = "2222222b-2222-4222-8222-22222222222b"; const adminUuid = "3333333c-3333-4333-8333-33333333333c"; const unavailableAlbumUuid = "4444444d-4444-4444-8444-44444444444d"; +const secondEditorialUuid = "6666666f-6666-4666-8666-66666666666f"; +const secondAlbumUuid = "5555555e-5555-4555-8555-55555555555e"; + +const defaultAlbums: ImmichAlbumSummary[] = [ + { + id: albumUuid, + albumName: "Pressefotos", + description: null, + albumThumbnailAssetId: "cover-1", + assetCount: 4, + }, +]; + +const secondAlbum: ImmichAlbumSummary = { + id: secondAlbumUuid, + albumName: "Spieltagfotos", + description: null, + albumThumbnailAssetId: "cover-2", + assetCount: 12, +}; const earlierGrant = new Date("2026-08-07T08:00:00.000Z"); const laterGrant = new Date("2026-08-08T08:00:00.000Z"); @@ -115,7 +137,10 @@ test("revoke targets every active case-equivalent row", () => { ]); }); -function createRepository(initial: Grant[] = []) { +function createRepository( + initial: Grant[] = [], + editorialDirectory: Record = {}, +) { const grants = [...initial]; const audit: Audit[] = []; const repository: AlbumGrantRepository = { @@ -124,6 +149,17 @@ function createRepository(initial: Grant[] = []) { .filter((grant) => grant.editorialId === editorialId && grant.revokedAt === null) .map((grant) => grant.albumId); }, + async listActiveGrantsWithEditorials() { + return grants + .filter((grant) => grant.revokedAt === null) + .map((grant) => ({ + immichAlbumId: grant.albumId, + editorialId: grant.editorialId, + editorialName: editorialDirectory[grant.editorialId]?.name ?? "Unbekannte Redaktion", + archivedAt: editorialDirectory[grant.editorialId]?.archivedAt ?? null, + })) + .sort((left, right) => left.editorialName.localeCompare(right.editorialName, "de")); + }, async grant(input) { const matching = grants.filter( (grant) => @@ -185,8 +221,11 @@ function createRepository(initial: Grant[] = []) { return { repository, grants, audit }; } -function createService(initial: Grant[] = []) { - const { repository, grants, audit } = createRepository(initial); +function createService(initial: Grant[] = [], albums: ImmichAlbumSummary[] = defaultAlbums) { + const { repository, grants, audit } = createRepository(initial, { + [editorialUuid]: { name: "Kicker Daily", archivedAt: null }, + [secondEditorialUuid]: { name: "Sport Woche", archivedAt: null }, + }); const immich = { getAlbum: vi.fn().mockResolvedValue({ id: albumUuid, @@ -196,15 +235,7 @@ function createService(initial: Grant[] = []) { assetCount: 4, assets: [], }), - listAlbums: vi.fn().mockResolvedValue([ - { - id: albumUuid, - albumName: "Pressefotos", - description: null, - albumThumbnailAssetId: "cover-1", - assetCount: 4, - }, - ]), + listAlbums: vi.fn().mockResolvedValue(albums), }; return { service: createAlbumGrantService({ repository, immich }), @@ -407,3 +438,129 @@ test("reports a stable unavailable error when the Immich album list cannot be lo new AlbumGrantError("IMMICH_UNAVAILABLE"), ); }); + +test("the access overview lists every album with its canonical grant holders", async () => { + const { service } = createService( + [ + { editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null }, + { editorialId: secondEditorialUuid, albumId: albumUuid, revokedAt: null }, + { editorialId: secondEditorialUuid, albumId: secondAlbumUuid, revokedAt: null }, + ], + [defaultAlbums[0], secondAlbum], + ); + + const overview = await service.listAlbumAccessOverview(); + + expect(overview).toHaveLength(2); + const pressefotos = overview.find((album) => album.id === albumUuid)!; + expect(pressefotos.grants.map((holder) => holder.editorialName)).toEqual([ + "Kicker Daily", + "Sport Woche", + ]); + expect(pressefotos.grants[0]).toMatchObject({ + editorialId: editorialUuid, + archivedAt: null, + }); + const spieltagfotos = overview.find((album) => album.id === secondAlbumUuid)!; + expect(spieltagfotos.grants.map((holder) => holder.editorialId)).toEqual([ + secondEditorialUuid, + ]); +}); + +test("bulk grant skips existing pairs, canonicalizes duplicates, and grants the rest", async () => { + const { service, grants, audit } = createService( + [{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null }], + [defaultAlbums[0], secondAlbum], + ); + + await expect( + service.bulkGrantAlbums({ + albumIds: [albumUuid.toUpperCase(), secondAlbumUuid], + editorialIds: [editorialUuid, secondEditorialUuid, editorialUuid.toUpperCase()], + adminUserId: adminUuid, + }), + ).resolves.toEqual({ granted: 3, skipped: 1, failed: 0 }); + + const active = grants.filter((grant) => grant.revokedAt === null); + expect(active).toHaveLength(4); + expect(audit.filter((event) => event.eventType === "album_granted")).toHaveLength(3); + expect(audit.every((event) => event.actorUserId === adminUuid)).toBe(true); +}); + +test("bulk grant refuses the whole batch when one album is unknown to Immich", async () => { + const { service, grants } = createService(); + + await expect( + service.bulkGrantAlbums({ + albumIds: [albumUuid, unavailableAlbumUuid], + editorialIds: [editorialUuid], + adminUserId: adminUuid, + }), + ).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" }); + expect(grants).toHaveLength(0); +}); + +test("bulk grant rejects empty album or editorial selections", async () => { + const { service } = createService(); + + await expect( + service.bulkGrantAlbums({ + albumIds: [], + editorialIds: [editorialUuid], + adminUserId: adminUuid, + }), + ).rejects.toMatchObject({ code: "INVALID_ALBUM_GRANT_INPUT" }); + await expect( + service.bulkGrantAlbums({ + albumIds: [albumUuid], + editorialIds: [], + adminUserId: adminUuid, + }), + ).rejects.toMatchObject({ code: "INVALID_ALBUM_GRANT_INPUT" }); +}); + +test("bulk grant continues with the remaining pairs when a single pair fails", async () => { + const { repository, grants } = createRepository([], { + [editorialUuid]: { name: "Kicker Daily", archivedAt: null }, + [secondEditorialUuid]: { name: "Sport Woche", archivedAt: null }, + }); + const failingRepository: AlbumGrantRepository = { + ...repository, + async grant(input) { + if (input.editorialId === secondEditorialUuid && input.immichAlbumId === albumUuid) { + throw new Error("unique constraint violation"); + } + return repository.grant(input); + }, + }; + const service = createAlbumGrantService({ + repository: failingRepository, + immich: { + getAlbum: vi.fn(), + listAlbums: vi.fn().mockResolvedValue([defaultAlbums[0], secondAlbum]), + }, + }); + + await expect( + service.bulkGrantAlbums({ + albumIds: [albumUuid, secondAlbumUuid], + editorialIds: [editorialUuid, secondEditorialUuid], + adminUserId: adminUuid, + }), + ).resolves.toEqual({ granted: 3, skipped: 0, failed: 1 }); + expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(3); +}); + +test("bulk grant reports a stable unavailable error when Immich is down", async () => { + const { service, immich, grants } = createService(); + immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" }); + + await expect( + service.bulkGrantAlbums({ + albumIds: [albumUuid], + editorialIds: [editorialUuid], + adminUserId: adminUuid, + }), + ).rejects.toEqual(new AlbumGrantError("IMMICH_UNAVAILABLE")); + expect(grants).toHaveLength(0); +}); diff --git a/src/modules/albums/grants.ts b/src/modules/albums/grants.ts index 637cf1f..433abe0 100644 --- a/src/modules/albums/grants.ts +++ b/src/modules/albums/grants.ts @@ -19,8 +19,33 @@ export type AlbumGrantInput = { adminUserId: string | null; }; +export type AlbumGrantHolder = { + editorialId: string; + editorialName: string; + archivedAt: Date | null; +}; + +export type AlbumAccessOverviewAlbum = ImmichAlbumSummary & { + grants: AlbumGrantHolder[]; +}; + +export type BulkAlbumGrantInput = { + albumIds: string[]; + editorialIds: string[]; + adminUserId: string | null; +}; + +export type BulkAlbumGrantResult = { + granted: number; + skipped: number; + failed: number; +}; + export type AlbumGrantRepository = { listActiveAlbumIds(editorialId: string): Promise; + listActiveGrantsWithEditorials(): Promise< + Array<{ immichAlbumId: string } & AlbumGrantHolder> + >; grant(input: AlbumGrantInput): Promise; revoke(input: AlbumGrantInput): Promise; }; @@ -96,6 +121,82 @@ export function createAlbumGrantService({ const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId)); return uniqueCanonicalIdentifiers(albumIds); }, + + /** + * All Immich albums enriched with the editorials that currently hold an + * active grant — the admin album-access overview page. + */ + async listAlbumAccessOverview(): Promise { + const [albums, activeGrants] = await Promise.all([ + loadAlbums(immich), + repository.listActiveGrantsWithEditorials(), + ]); + const holdersByCanonicalAlbumId = new Map(); + for (const grant of activeGrants) { + const key = canonicalizeStoredIdentifier(grant.immichAlbumId); + const holders = holdersByCanonicalAlbumId.get(key) ?? []; + holders.push({ + editorialId: grant.editorialId, + editorialName: grant.editorialName, + archivedAt: grant.archivedAt, + }); + holdersByCanonicalAlbumId.set(key, holders); + } + for (const holders of holdersByCanonicalAlbumId.values()) { + holders.sort((left, right) => left.editorialName.localeCompare(right.editorialName, "de")); + } + return albums.map((album) => ({ + ...album, + grants: holdersByCanonicalAlbumId.get(canonicalizeStoredIdentifier(album.id)) ?? [], + })); + }, + + /** + * Grants every selected album to every selected editorial in one admin + * click. Album existence is validated once against the Immich album list + * (instead of one `getAlbum` per pair); pairs that already hold an active + * grant are skipped. A failing pair neither aborts nor undoes the others — + * each pair commits in its own transaction, mirroring the auto-rule sync. + */ + async bulkGrantAlbums(input: BulkAlbumGrantInput): Promise { + const albumIds = uniqueCanonicalIdentifiers(input.albumIds); + const editorialIds = [...new Set(input.editorialIds.map(normalizeIdentifier))]; + const adminUserId = + input.adminUserId === null ? null : normalizeIdentifier(input.adminUserId); + if (albumIds.length === 0 || editorialIds.length === 0) { + throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT"); + } + + const albums = await loadAlbums(immich); + const knownAlbumIds = new Set(albums.map((album) => canonicalizeStoredIdentifier(album.id))); + for (const albumId of albumIds) { + if (!knownAlbumIds.has(albumId)) { + throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE"); + } + } + + let granted = 0; + let skipped = 0; + let failed = 0; + for (const editorialId of editorialIds) { + const activeAlbumIds = new Set( + uniqueCanonicalIdentifiers(await repository.listActiveAlbumIds(editorialId)), + ); + for (const albumId of albumIds) { + if (activeAlbumIds.has(albumId)) { + skipped += 1; + continue; + } + try { + await repository.grant({ editorialId, immichAlbumId: albumId, adminUserId }); + granted += 1; + } catch { + failed += 1; + } + } + } + return { granted, skipped, failed }; + }, }; } @@ -111,6 +212,20 @@ export function createAlbumGrantRepository( return uniqueCanonicalIdentifiers(grants.map((grant) => grant.immichAlbumId)); }, + async listActiveGrantsWithEditorials() { + return database + .select({ + immichAlbumId: albumGrants.immichAlbumId, + editorialId: editorialAccounts.id, + editorialName: editorialAccounts.name, + archivedAt: editorialAccounts.archivedAt, + }) + .from(albumGrants) + .innerJoin(editorialAccounts, eq(albumGrants.editorialAccountId, editorialAccounts.id)) + .where(isNull(albumGrants.revokedAt)) + .orderBy(asc(editorialAccounts.name)); + }, + async grant(input) { return database.transaction(async (transaction) => { await lockEditorialAlbumMutation(transaction, input.editorialId);