fix: album assignment + approval error handling

Album assignment 500'd with IMMICH_UNAVAILABLE because grantAlbum verified the
album via getAlbum, which pulled the full album incl. all assets — large albums
blew the 15s timeout. Request ?withoutAssets=true so Immich returns metadata
only (no consumer reads .assets); make assets optional in the schema.

Album thumbnails 500'd because next/image rejected the ?albumId= query string
(images.localPatterns). Switch the album page to a plain <img>, matching the
editorial catalog (next/image was used in exactly one place).

Overhaul action error handling: grantAlbumAction/revokeAlbumAction/approveEditorialAction
returned a thrown Error, which Next.js turns into an opaque error-digest page —
the German message never reached the admin. They now return {ok,message}; new
client AlbumGrantForm + ApproveForm use useActionState to show the message
inline. Auth (requireAdmin) still throws (guarded by the layout). Update both
action test files to the result contract.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Leon TonhäuserandClaude committed 2026-08-11 02:09:16 +02:00
1 parent 7aeceee078
commit 089f5f7035
9 files changed
+231 -58

No files matched your search

+27 -9
View File
@@ -25,6 +25,8 @@ vi.mock("@/modules/editorials/service", () => ({
import { approveEditorialAction } from "./actions"; import { approveEditorialAction } from "./actions";
const initial = { ok: true, message: "" };
test("the approve action rejects unauthenticated callers before touching the service", async () => { test("the approve action rejects unauthenticated callers before touching the service", async () => {
mocks.headers.mockResolvedValue(new Headers()); mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED")); mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
@@ -32,7 +34,7 @@ test("the approve action rejects unauthenticated callers before touching the ser
formData.set("priceEuros", "10.00"); formData.set("priceEuros", "10.00");
await expect( await expect(
approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), approveEditorialAction("00000000-0000-4000-8000-000000000001", initial, formData),
).rejects.toThrow("ADMIN_REQUIRED"); ).rejects.toThrow("ADMIN_REQUIRED");
expect(mocks.approveEditorial).not.toHaveBeenCalled(); expect(mocks.approveEditorial).not.toHaveBeenCalled();
}); });
@@ -44,8 +46,13 @@ test("the approve action forwards the authenticated principal and cents price to
const formData = new FormData(); const formData = new FormData();
formData.set("priceEuros", "12,50"); formData.set("priceEuros", "12,50");
await approveEditorialAction("00000000-0000-4000-8000-000000000001", formData); const result = await approveEditorialAction(
"00000000-0000-4000-8000-000000000001",
initial,
formData,
);
expect(result).toEqual({ ok: true, message: "" });
expect(mocks.approveEditorial).toHaveBeenCalledWith({ expect(mocks.approveEditorial).toHaveBeenCalledWith({
editorialId: "00000000-0000-4000-8000-000000000001", editorialId: "00000000-0000-4000-8000-000000000001",
priceCents: 1250, priceCents: 1250,
@@ -56,15 +63,19 @@ test("the approve action forwards the authenticated principal and cents price to
); );
}); });
test("the approve action rejects a non-positive price before calling the service", async () => { test("the approve action returns a German message for a non-positive price before calling the service", async () => {
mocks.headers.mockResolvedValue(new Headers()); mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
const formData = new FormData(); const formData = new FormData();
formData.set("priceEuros", "0"); formData.set("priceEuros", "0");
await expect( const result = await approveEditorialAction(
approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), "00000000-0000-4000-8000-000000000001",
).rejects.toThrow("Bitte geben Sie einen gültigen Nettopreis an."); initial,
formData,
);
expect(result).toEqual({ ok: false, message: "Bitte geben Sie einen gültigen Nettopreis an." });
expect(mocks.approveEditorial).not.toHaveBeenCalled(); expect(mocks.approveEditorial).not.toHaveBeenCalled();
}); });
@@ -76,7 +87,14 @@ test("the approve action translates a service error into a German message", asyn
const formData = new FormData(); const formData = new FormData();
formData.set("priceEuros", "10.00"); formData.set("priceEuros", "10.00");
await expect( const result = await approveEditorialAction(
approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), "00000000-0000-4000-8000-000000000001",
).rejects.toThrow("Bitte weisen Sie zuerst mindestens ein Album zu."); initial,
formData,
);
expect(result).toEqual({
ok: false,
message: "Bitte weisen Sie zuerst mindestens ein Album zu.",
});
}); });
+24 -7
View File
@@ -6,32 +6,49 @@ import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal"; import { requireAdmin } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service"; import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
export async function approveEditorialAction(editorialId: string, formData: FormData): Promise<void> { // 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 ApproveActionResult = { ok: boolean; message: string };
const INITIAL_RESULT: ApproveActionResult = { ok: true, message: "" };
export async function approveEditorialAction(
editorialId: string,
_prevState: ApproveActionResult,
formData: FormData,
): Promise<ApproveActionResult> {
const principal = await requireAdmin(new Headers(await headers())); const principal = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId); const safeEditorialId = requiredId(editorialId);
const priceCents = parsePriceCents(formData.get("priceEuros")); const price = parsePriceCents(formData.get("priceEuros"));
if (!price.ok) {
return { ok: false, message: price.message };
}
try { try {
await editorialService.approveEditorial({ await editorialService.approveEditorial({
editorialId: safeEditorialId, editorialId: safeEditorialId,
priceCents, priceCents: price.cents,
adminUserId: principal.userId, adminUserId: principal.userId,
}); });
} catch (error) { } catch (error) {
throw new Error(approveErrorMessage(error)); return { ok: false, message: approveErrorMessage(error) };
} }
revalidatePath(`/admin/redaktionen/${safeEditorialId}`); revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
revalidatePath(`/admin/redaktionen`); revalidatePath(`/admin/redaktionen`);
return INITIAL_RESULT;
} }
function parsePriceCents(value: unknown): number { function parsePriceCents(
value: unknown,
): { ok: true; cents: number } | { ok: false; message: string } {
const euros = const euros =
typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN; typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN;
if (!Number.isFinite(euros) || euros <= 0) { if (!Number.isFinite(euros) || euros <= 0) {
throw new Error("Bitte geben Sie einen gültigen Nettopreis an."); return { ok: false, message: "Bitte geben Sie einen gültigen Nettopreis an." };
} }
return Math.round(euros * 100); return { ok: true, cents: Math.round(euros * 100) };
} }
function approveErrorMessage(error: unknown): string { function approveErrorMessage(error: unknown): string {
@@ -1,4 +1,4 @@
import { expect, test, vi } from "vitest"; import { beforeEach, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
grantAlbum: vi.fn(), grantAlbum: vi.fn(),
@@ -8,15 +8,26 @@ const mocks = vi.hoisted(() => ({
revokeAlbum: vi.fn(), revokeAlbum: vi.fn(),
})); }));
beforeEach(() => {
vi.clearAllMocks();
});
vi.mock("next/headers", () => ({ headers: mocks.headers })); vi.mock("next/headers", () => ({ headers: mocks.headers }));
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath })); vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin })); vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
vi.mock("@/modules/albums/grants", () => ({ vi.mock("@/modules/albums/grants", () => ({
AlbumGrantError: class AlbumGrantError extends Error {
constructor(readonly code: string) {
super(code);
}
},
albumGrantService: { grantAlbum: mocks.grantAlbum, revokeAlbum: mocks.revokeAlbum }, albumGrantService: { grantAlbum: mocks.grantAlbum, revokeAlbum: mocks.revokeAlbum },
})); }));
import { grantAlbumAction } from "./actions"; import { grantAlbumAction } from "./actions";
const initial = { ok: true, message: "" };
test("the grant action rejects unauthenticated callers before accepting submitted identifiers", async () => { test("the grant action rejects unauthenticated callers before accepting submitted identifiers", async () => {
mocks.headers.mockResolvedValue(new Headers()); mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED")); mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
@@ -25,7 +36,7 @@ test("the grant action rejects unauthenticated callers before accepting submitte
formData.set("adminUserId", "forged-user"); formData.set("adminUserId", "forged-user");
await expect( await expect(
grantAlbumAction("00000000-0000-4000-8000-000000000001", formData), grantAlbumAction("00000000-0000-4000-8000-000000000001", initial, formData),
).rejects.toThrow("ADMIN_REQUIRED"); ).rejects.toThrow("ADMIN_REQUIRED");
expect(mocks.grantAlbum).not.toHaveBeenCalled(); expect(mocks.grantAlbum).not.toHaveBeenCalled();
}); });
@@ -38,8 +49,13 @@ test("the grant action uses the authenticated principal instead of a submitted a
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111"); formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
formData.set("adminUserId", "forged-user"); formData.set("adminUserId", "forged-user");
await grantAlbumAction("00000000-0000-4000-8000-000000000001", formData); const result = await grantAlbumAction(
"00000000-0000-4000-8000-000000000001",
initial,
formData,
);
expect(result).toEqual({ ok: true, message: "" });
expect(mocks.grantAlbum).toHaveBeenCalledWith({ expect(mocks.grantAlbum).toHaveBeenCalledWith({
editorialId: "00000000-0000-4000-8000-000000000001", editorialId: "00000000-0000-4000-8000-000000000001",
immichAlbumId: "11111111-1111-4111-8111-111111111111", immichAlbumId: "11111111-1111-4111-8111-111111111111",
@@ -49,3 +65,24 @@ test("the grant action uses the authenticated principal instead of a submitted a
"/admin/redaktionen/00000000-0000-4000-8000-000000000001/alben", "/admin/redaktionen/00000000-0000-4000-8000-000000000001/alben",
); );
}); });
test("the grant action returns a German message when the service reports Immich is down", async () => {
mocks.headers.mockResolvedValue(new Headers());
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
const { AlbumGrantError } = await import("@/modules/albums/grants");
mocks.grantAlbum.mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE"));
const formData = new FormData();
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
const result = await grantAlbumAction(
"00000000-0000-4000-8000-000000000001",
initial,
formData,
);
expect(result).toEqual({
ok: false,
message: "Immich ist momentan nicht erreichbar. Bitte später erneut versuchen.",
});
expect(mocks.revalidatePath).not.toHaveBeenCalled();
});
+53 -13
View File
@@ -3,37 +3,77 @@
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { albumGrantService } from "@/modules/albums/grants"; import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
import { requireAdmin } from "@/modules/auth/principal"; import { requireAdmin } from "@/modules/auth/principal";
export async function grantAlbumAction(editorialId: string, formData: FormData): Promise<void> { // 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 AlbumActionResult = { ok: boolean; message: string };
const INITIAL_RESULT: AlbumActionResult = { ok: true, message: "" };
export async function grantAlbumAction(
editorialId: string,
_prevState: AlbumActionResult,
formData: FormData,
): Promise<AlbumActionResult> {
const principal = await getAdminPrincipal(); const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId); const safeEditorialId = requiredId(editorialId);
const immichAlbumId = requiredId(formData.get("immichAlbumId")); const immichAlbumId = requiredId(formData.get("immichAlbumId"));
await albumGrantService.grantAlbum({ try {
editorialId: safeEditorialId, await albumGrantService.grantAlbum({
immichAlbumId, editorialId: safeEditorialId,
adminUserId: principal.userId, immichAlbumId,
}); adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: albumGrantErrorMessage(error) };
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`); revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
return INITIAL_RESULT;
} }
export async function revokeAlbumAction(editorialId: string, formData: FormData): Promise<void> { export async function revokeAlbumAction(
editorialId: string,
_prevState: AlbumActionResult,
formData: FormData,
): Promise<AlbumActionResult> {
const principal = await getAdminPrincipal(); const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId); const safeEditorialId = requiredId(editorialId);
const immichAlbumId = requiredId(formData.get("immichAlbumId")); const immichAlbumId = requiredId(formData.get("immichAlbumId"));
await albumGrantService.revokeAlbum({ try {
editorialId: safeEditorialId, await albumGrantService.revokeAlbum({
immichAlbumId, editorialId: safeEditorialId,
adminUserId: principal.userId, immichAlbumId,
}); adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: albumGrantErrorMessage(error) };
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`); revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
return INITIAL_RESULT;
} }
async function getAdminPrincipal() { async function getAdminPrincipal() {
return requireAdmin(new Headers(await headers())); return requireAdmin(new Headers(await headers()));
} }
function albumGrantErrorMessage(error: unknown): string {
if (error instanceof AlbumGrantError) {
const messages: Record<AlbumGrantError["code"], string> = {
ALBUM_NOT_ASSIGNABLE:
"Das 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 Albumkennung.",
};
return messages[error.code] ?? "Die Zuweisung ist fehlgeschlagen.";
}
return "Die Zuweisung ist fehlgeschlagen.";
}
function requiredId(value: unknown): string { function requiredId(value: unknown): string {
if ( if (
typeof value !== "string" || typeof value !== "string" ||
@@ -1,8 +1,10 @@
import Image from "next/image"; /* eslint-disable @next/next/no-img-element */
import Link from "next/link"; import Link from "next/link";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { AlbumGrantForm } from "@/components/admin/album-grant-form";
import { db } from "@/db/client"; import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema"; import { editorialAccounts } from "@/db/schema";
import { albumGrantService } from "@/modules/albums/grants"; import { albumGrantService } from "@/modules/albums/grants";
@@ -62,7 +64,7 @@ export default async function EditorialAlbumsPage({
<li key={album.id}> <li key={album.id}>
<article aria-labelledby={`album-${album.id}`}> <article aria-labelledby={`album-${album.id}`}>
{album.albumThumbnailAssetId ? ( {album.albumThumbnailAssetId ? (
<Image <img
alt={`Titelbild von ${album.albumName}`} alt={`Titelbild von ${album.albumName}`}
height={120} height={120}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`} src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
@@ -78,12 +80,11 @@ export default async function EditorialAlbumsPage({
<p> <p>
Status: <strong>{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}</strong> Status: <strong>{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}</strong>
</p> </p>
<form action={action.bind(null, editorial.id)}> <AlbumGrantForm
<input name="immichAlbumId" type="hidden" value={album.id} /> action={action.bind(null, editorial.id)}
<button type="submit"> albumId={album.id}
{album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"} isGranted={album.isGranted}
</button> />
</form>
</article> </article>
</li> </li>
); );
+30
View File
@@ -0,0 +1,30 @@
"use client";
import { useActionState } from "react";
import type { AlbumActionResult } from "@/app/admin/redaktionen/[id]/alben/actions";
// Client wrapper so the grant/revoke result (a returned object, not a thrown
// error) surfaces as inline German text via useActionState. The page picks the
// bound server action (grant or revoke) based on `isGranted`.
export function AlbumGrantForm({
action,
isGranted,
albumId,
}: Readonly<{
action: (state: AlbumActionResult, formData: FormData) => Promise<AlbumActionResult>;
isGranted: boolean;
albumId: string;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction}>
<input name="immichAlbumId" type="hidden" value={albumId} />
<button type="submit" disabled={pending}>
{pending ? "…" : isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
</button>
{state.ok ? null : <p role="alert">{state.message}</p>}
</form>
);
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useActionState } from "react";
import type { ApproveActionResult } from "@/app/admin/redaktionen/[id]/actions";
// Client wrapper so the approve result (a returned object, not a thrown
// error) surfaces as inline German text via useActionState. `canApprove`
// mirrors the server-side gate (email verified + active album grant).
export function ApproveForm({
action,
canApprove,
}: Readonly<{
action: (state: ApproveActionResult, formData: FormData) => Promise<ApproveActionResult>;
canApprove: boolean;
}>) {
const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
return (
<form action={formAction} className="account-form">
<label>
Individueller Nettopreis (EUR)
<input
inputMode="decimal"
min="0.01"
name="priceEuros"
required
step="0.01"
type="number"
/>
</label>
<button type="submit" disabled={!canApprove || pending}>
{pending ? "…" : "Redaktion freigeben"}
</button>
{state.ok ? null : <p role="alert">{state.message}</p>}
</form>
);
}
+5 -16
View File
@@ -1,5 +1,6 @@
import Link from "next/link"; import Link from "next/link";
import { ApproveForm } from "@/components/admin/approve-form";
import { approveEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; import { approveEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
export type EditorialDetail = { export type EditorialDetail = {
@@ -51,22 +52,10 @@ export function EditorialDetailContent({
<p>Die Redaktion ist freigegeben (Netto {formatCents(editorial.currentPriceCents ?? 0)}).</p> <p>Die Redaktion ist freigegeben (Netto {formatCents(editorial.currentPriceCents ?? 0)}).</p>
) : ( ) : (
<> <>
<form action={approveEditorialAction.bind(null, editorial.id)} className="account-form"> <ApproveForm
<label> action={approveEditorialAction.bind(null, editorial.id)}
Individueller Nettopreis (EUR) canApprove={canApprove}
<input />
inputMode="decimal"
min="0.01"
name="priceEuros"
required
step="0.01"
type="number"
/>
</label>
<button type="submit" disabled={!canApprove}>
Redaktion freigeben
</button>
</form>
<p>{approvalHint}</p> <p>{approvalHint}</p>
<Link href={`/admin/redaktionen/${editorial.id}/alben`}>Albumrechte verwalten</Link> <Link href={`/admin/redaktionen/${editorial.id}/alben`}>Albumrechte verwalten</Link>
</> </>
+5 -2
View File
@@ -43,7 +43,10 @@ const albumSummarySchema = z
.passthrough(); .passthrough();
const albumSchema = albumSummarySchema.extend({ const albumSchema = albumSummarySchema.extend({
assets: z.array(assetSchema), // `getAlbum` requests `?withoutAssets=true` so Immich returns album metadata
// without the full asset list — otherwise large albums blow past the request
// timeout and surface as IMMICH_UNAVAILABLE. No consumer reads `.assets`.
assets: z.array(assetSchema).optional().default([]),
}); });
const metadataSearchSchema = z const metadataSearchSchema = z
@@ -324,7 +327,7 @@ export function createImmichClient({
}, },
getAlbum(albumId, signal) { getAlbum(albumId, signal) {
return requestJson<ImmichAlbum>( return requestJson<ImmichAlbum>(
`/albums/${encodeURIComponent(albumId)}`, `/albums/${encodeURIComponent(albumId)}?withoutAssets=true`,
{ method: "GET" }, { method: "GET" },
albumSchema, albumSchema,
signal, signal,