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
@@ -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.
|
||||
|
||||
@@ -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" },
|
||||
]}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
newValues: Record<string, unknown>;
|
||||
};
|
||||
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<string, EditorialDirectoryEntry> = {},
|
||||
) {
|
||||
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);
|
||||
});
|
||||
@@ -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<string[]>;
|
||||
listActiveGrantsWithEditorials(): Promise<
|
||||
Array<{ immichAlbumId: string } & AlbumGrantHolder>
|
||||
>;
|
||||
grant(input: AlbumGrantInput): Promise<boolean>;
|
||||
revoke(input: AlbumGrantInput): Promise<boolean>;
|
||||
};
|
||||
@@ -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<AlbumAccessOverviewAlbum[]> {
|
||||
const [albums, activeGrants] = await Promise.all([
|
||||
loadAlbums(immich),
|
||||
repository.listActiveGrantsWithEditorials(),
|
||||
]);
|
||||
const holdersByCanonicalAlbumId = new Map<string, AlbumGrantHolder[]>();
|
||||
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<BulkAlbumGrantResult> {
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user