feat: add admin albums tab with access overview and bulk grants
New /admin/alben page: all Immich albums with per-album editorial grant chips (link + one-click revoke) and a bulk-grant form (multiple albums x multiple editorials, select-all, search). bulkGrantAlbums validates album existence once via listAlbums, skips already-active pairs, and commits each pair in its own transaction with full audit attribution.
This commit is contained in:
1 parent
0b65fbba16
commit
0931ffc777
12 files changed
+1245
-12
No files matched your search
@@ -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(
|
||||
<AlbumAccessManager
|
||||
albums={albums}
|
||||
editorials={editorials}
|
||||
bulkGrantAction={bulkGrantAction}
|
||||
revokeAction={revokeAction}
|
||||
/>,
|
||||
);
|
||||
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<HTMLInputElement>('input[name="immichAlbumIds"]')]
|
||||
.filter((input) => input.checked)
|
||||
.map((input) => input.value);
|
||||
const editorialValues = [...form.querySelectorAll<HTMLInputElement>('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();
|
||||
});
|
||||
@@ -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<AlbumAccessActionResult>;
|
||||
|
||||
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<AlbumAccessActionResult>(INITIAL_RESULT);
|
||||
const [bulkPending, startBulkTransition] = useTransition();
|
||||
const [revokeState, revokeFormAction, revokePending] = useActionState(
|
||||
revokeAction,
|
||||
INITIAL_RESULT,
|
||||
);
|
||||
const [selectedAlbumIds, setSelectedAlbumIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [selectedEditorialIds, setSelectedEditorialIds] = useState<ReadonlySet<string>>(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 (
|
||||
<div className="space-y-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Bulk-Zuweisung</CardTitle>
|
||||
<CardDescription>
|
||||
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.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={handleBulkSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<fieldset className="space-y-3 min-w-0">
|
||||
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Alben ({selectedAlbumIds.size} ausgewählt)
|
||||
</legend>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Input
|
||||
type="search"
|
||||
value={bulkSearch}
|
||||
onChange={(event) => setBulkSearch(event.target.value)}
|
||||
placeholder="Alben suchen…"
|
||||
aria-label="Alben für die Bulk-Zuweisung durchsuchen"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="whitespace-nowrap"
|
||||
onClick={toggleAllBulkAlbums}
|
||||
disabled={bulkAlbums.length === 0}
|
||||
>
|
||||
{allBulkAlbumsSelected ? "Auswahl aufheben" : "Alle auswählen"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-80 overflow-y-auto rounded-md border border-border divide-y divide-border">
|
||||
{bulkAlbums.length === 0 ? (
|
||||
<p className="p-4 text-sm text-muted-foreground">Keine Alben gefunden.</p>
|
||||
) : (
|
||||
bulkAlbums.map((album) => (
|
||||
<label
|
||||
key={album.id}
|
||||
className="flex items-center gap-3 px-4 py-2.5 text-sm cursor-pointer hover:bg-accent/50"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="immichAlbumIds"
|
||||
value={album.id}
|
||||
checked={selectedAlbumIds.has(album.id)}
|
||||
onChange={(event) =>
|
||||
toggleAlbumSelection(album.id, event.target.checked)
|
||||
}
|
||||
className="h-4 w-4 accent-primary-600"
|
||||
/>
|
||||
<span className="truncate font-medium">{album.albumName}</span>
|
||||
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
|
||||
{album.assetCount} Fotos
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="space-y-3 min-w-0">
|
||||
<legend className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Redaktionen ({selectedEditorialIds.size} ausgewählt)
|
||||
</legend>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={toggleAllEditorials}
|
||||
disabled={editorials.length === 0}
|
||||
>
|
||||
{allEditorialsSelected ? "Auswahl aufheben" : "Alle auswählen"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-80 overflow-y-auto rounded-md border border-border divide-y divide-border">
|
||||
{editorials.length === 0 ? (
|
||||
<p className="p-4 text-sm text-muted-foreground">
|
||||
Keine aktiven Redaktionen vorhanden.
|
||||
</p>
|
||||
) : (
|
||||
editorials.map((editorial) => (
|
||||
<label
|
||||
key={editorial.id}
|
||||
className="flex items-center gap-3 px-4 py-2.5 text-sm cursor-pointer hover:bg-accent/50"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="editorialIds"
|
||||
value={editorial.id}
|
||||
checked={selectedEditorialIds.has(editorial.id)}
|
||||
onChange={(event) =>
|
||||
toggleEditorialSelection(editorial.id, event.target.checked)
|
||||
}
|
||||
className="h-4 w-4 accent-primary-600"
|
||||
/>
|
||||
<span className="truncate font-medium">{editorial.name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
|
||||
{bulkState.message ? (
|
||||
<p
|
||||
role={bulkState.ok ? "status" : "alert"}
|
||||
className={`text-sm ${
|
||||
bulkState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
|
||||
}`}
|
||||
>
|
||||
{bulkState.message}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Wähle mindestens ein Album und eine Redaktion aus.
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={!canSubmit || bulkPending} className="shrink-0">
|
||||
{bulkPending ? "Wird verarbeitet…" : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="gap-4">
|
||||
<div>
|
||||
<CardTitle className="text-lg">Albumzugriffe</CardTitle>
|
||||
<CardDescription>
|
||||
Welche Redaktionen Zugriff auf welches Album hat. Ein Klick auf das × entzieht den
|
||||
Zugriff für die einzelne Redaktion.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="sm:max-w-sm">
|
||||
<Input
|
||||
type="search"
|
||||
value={overviewSearch}
|
||||
onChange={(event) => setOverviewSearch(event.target.value)}
|
||||
placeholder="Album oder Redaktion suchen…"
|
||||
aria-label="Albumzugriffe durchsuchen"
|
||||
/>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{revokeState.message ? (
|
||||
<p
|
||||
role={revokeState.ok ? "status" : "alert"}
|
||||
className={`text-sm ${
|
||||
revokeState.ok ? "text-green-700 dark:text-green-400" : "text-destructive"
|
||||
}`}
|
||||
>
|
||||
{revokeState.message}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{albums.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">Derzeit sind keine Alben vorhanden.</p>
|
||||
) : overviewAlbums.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">Keine Alben gefunden.</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">Redaktionen mit Zugriff</th>
|
||||
<th className="py-3 px-4 font-semibold text-right">Anzahl</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{overviewAlbums.map((album, index) => (
|
||||
<tr
|
||||
key={album.id}
|
||||
className={index !== overviewAlbums.length - 1 ? "border-b border-border" : ""}
|
||||
>
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-3">
|
||||
{album.albumThumbnailAssetId ? (
|
||||
<img
|
||||
className="h-10 w-14 rounded object-cover bg-muted shrink-0"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="h-10 w-14 rounded bg-muted shrink-0 flex items-center justify-center text-[10px] uppercase tracking-widest text-muted-foreground"
|
||||
>
|
||||
Kein Cover
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium truncate" title={album.albumName}>
|
||||
{album.albumName}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">{album.assetCount} Fotos</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
{album.grants.length === 0 ? (
|
||||
<span className="text-muted-foreground">Noch keine Redaktion</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{album.grants.map((holder) => (
|
||||
<form
|
||||
key={holder.editorialId}
|
||||
action={revokeFormAction}
|
||||
className="inline-flex items-center overflow-hidden rounded-full border border-primary-200 bg-primary-50 text-primary-700 dark:border-primary-800 dark:bg-primary-900/30 dark:text-primary-300"
|
||||
>
|
||||
<input type="hidden" name="immichAlbumId" value={album.id} />
|
||||
<input type="hidden" name="editorialId" value={holder.editorialId} />
|
||||
<Link
|
||||
href={`/admin/redaktionen/${holder.editorialId}`}
|
||||
className="py-0.5 pl-2.5 text-xs font-medium hover:underline"
|
||||
>
|
||||
{holder.editorialName}
|
||||
{holder.archived ? " (archiviert)" : ""}
|
||||
</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={revokePending}
|
||||
aria-label={`Zugriff auf ${album.albumName} für ${holder.editorialName} entziehen`}
|
||||
title={`Zugriff für ${holder.editorialName} entziehen`}
|
||||
className="px-2 py-0.5 text-xs font-bold hover:bg-primary-100 dark:hover:bg-primary-800/50 disabled:opacity-50"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</form>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3 px-4 text-right tabular-nums">{album.grants.length}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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<AlbumAccessActionResult> {
|
||||
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<ReturnType<typeof albumGrantService.bulkGrantAlbums>>;
|
||||
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<AlbumAccessActionResult> {
|
||||
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<AlbumGrantError["code"], string> = {
|
||||
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.";
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<typeof albumGrantService, "listAlbumAccessOverview"> = 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<EditorialOption[]> {
|
||||
return db
|
||||
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
|
||||
.from(editorialAccounts)
|
||||
.where(isNull(editorialAccounts.archivedAt))
|
||||
.orderBy(asc(editorialAccounts.name));
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="space-y-8 max-w-7xl animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<PageHeader
|
||||
kicker="Albumverwaltung"
|
||||
title="Alben"
|
||||
description="Alle Immich-Alben mit ihren Redaktionsfreigaben — inklusive Bulk-Zuweisung für mehrere Alben und Redaktionen auf einmal."
|
||||
/>
|
||||
|
||||
{albumResult.unavailable ? (
|
||||
<div
|
||||
className="bg-destructive/15 text-destructive p-4 rounded-md border border-destructive/30"
|
||||
role="status"
|
||||
>
|
||||
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben
|
||||
unverändert.
|
||||
</div>
|
||||
) : (
|
||||
<AlbumAccessManager
|
||||
albums={albumResult.albums.map((album) => ({
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
|
||||
<p className="text-sm">
|
||||
<Link href="/admin/redaktionen" className="text-primary-600 hover:underline">
|
||||
Zu den Redaktionen
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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" },
|
||||
]}
|
||||
|
||||
Reference in new issue
Block a user