From 089f5f7035a2733861986d50c721e8e02ea9acdf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Leon=20Tonh=C3=A4user?=
Date: Tue, 11 Aug 2026 02:09:16 +0200
Subject: [PATCH] fix: album assignment + approval error handling
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
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 , 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
---
.../admin/redaktionen/[id]/actions.test.ts | 36 +++++++---
src/app/admin/redaktionen/[id]/actions.ts | 31 +++++++--
.../redaktionen/[id]/alben/actions.test.ts | 43 +++++++++++-
.../admin/redaktionen/[id]/alben/actions.ts | 68 +++++++++++++++----
src/app/admin/redaktionen/[id]/alben/page.tsx | 19 +++---
src/components/admin/album-grant-form.tsx | 30 ++++++++
src/components/admin/approve-form.tsx | 38 +++++++++++
src/modules/editorials/admin-detail.tsx | 21 ++----
src/modules/immich/client.ts | 7 +-
9 files changed, 233 insertions(+), 60 deletions(-)
create mode 100644 src/components/admin/album-grant-form.tsx
create mode 100644 src/components/admin/approve-form.tsx
diff --git a/src/app/admin/redaktionen/[id]/actions.test.ts b/src/app/admin/redaktionen/[id]/actions.test.ts
index 54d2b4c..02bb67f 100644
--- a/src/app/admin/redaktionen/[id]/actions.test.ts
+++ b/src/app/admin/redaktionen/[id]/actions.test.ts
@@ -25,6 +25,8 @@ vi.mock("@/modules/editorials/service", () => ({
import { approveEditorialAction } from "./actions";
+const initial = { ok: true, message: "" };
+
test("the approve action rejects unauthenticated callers before touching the service", async () => {
mocks.headers.mockResolvedValue(new Headers());
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");
await expect(
- approveEditorialAction("00000000-0000-4000-8000-000000000001", formData),
+ approveEditorialAction("00000000-0000-4000-8000-000000000001", initial, formData),
).rejects.toThrow("ADMIN_REQUIRED");
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();
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({
editorialId: "00000000-0000-4000-8000-000000000001",
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.requireAdmin.mockResolvedValue({ userId: "admin-1" });
const formData = new FormData();
formData.set("priceEuros", "0");
- await expect(
- approveEditorialAction("00000000-0000-4000-8000-000000000001", formData),
- ).rejects.toThrow("Bitte geben Sie einen gültigen Nettopreis an.");
+ const result = await approveEditorialAction(
+ "00000000-0000-4000-8000-000000000001",
+ initial,
+ formData,
+ );
+
+ expect(result).toEqual({ ok: false, message: "Bitte geben Sie einen gültigen Nettopreis an." });
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();
formData.set("priceEuros", "10.00");
- await expect(
- approveEditorialAction("00000000-0000-4000-8000-000000000001", formData),
- ).rejects.toThrow("Bitte weisen Sie zuerst mindestens ein Album zu.");
+ const result = await approveEditorialAction(
+ "00000000-0000-4000-8000-000000000001",
+ initial,
+ formData,
+ );
+
+ expect(result).toEqual({
+ ok: false,
+ message: "Bitte weisen Sie zuerst mindestens ein Album zu.",
+ });
});
\ No newline at end of file
diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts
index daf57f2..761570b 100644
--- a/src/app/admin/redaktionen/[id]/actions.ts
+++ b/src/app/admin/redaktionen/[id]/actions.ts
@@ -6,32 +6,49 @@ import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
-export async function approveEditorialAction(editorialId: string, formData: FormData): Promise {
+// 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 {
const principal = await requireAdmin(new Headers(await headers()));
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 {
await editorialService.approveEditorial({
editorialId: safeEditorialId,
- priceCents,
+ priceCents: price.cents,
adminUserId: principal.userId,
});
} catch (error) {
- throw new Error(approveErrorMessage(error));
+ return { ok: false, message: approveErrorMessage(error) };
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
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 =
typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN;
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 {
diff --git a/src/app/admin/redaktionen/[id]/alben/actions.test.ts b/src/app/admin/redaktionen/[id]/alben/actions.test.ts
index 4c6e717..5b3cc08 100644
--- a/src/app/admin/redaktionen/[id]/alben/actions.test.ts
+++ b/src/app/admin/redaktionen/[id]/alben/actions.test.ts
@@ -1,4 +1,4 @@
-import { expect, test, vi } from "vitest";
+import { beforeEach, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
grantAlbum: vi.fn(),
@@ -8,15 +8,26 @@ const mocks = vi.hoisted(() => ({
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: { grantAlbum: mocks.grantAlbum, revokeAlbum: mocks.revokeAlbum },
}));
import { grantAlbumAction } from "./actions";
+const initial = { ok: true, message: "" };
+
test("the grant action rejects unauthenticated callers before accepting submitted identifiers", async () => {
mocks.headers.mockResolvedValue(new Headers());
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");
await expect(
- grantAlbumAction("00000000-0000-4000-8000-000000000001", formData),
+ grantAlbumAction("00000000-0000-4000-8000-000000000001", initial, formData),
).rejects.toThrow("ADMIN_REQUIRED");
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("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({
editorialId: "00000000-0000-4000-8000-000000000001",
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",
);
});
+
+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();
+});
\ No newline at end of file
diff --git a/src/app/admin/redaktionen/[id]/alben/actions.ts b/src/app/admin/redaktionen/[id]/alben/actions.ts
index 719093d..af58f2c 100644
--- a/src/app/admin/redaktionen/[id]/alben/actions.ts
+++ b/src/app/admin/redaktionen/[id]/alben/actions.ts
@@ -3,37 +3,77 @@
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
-import { albumGrantService } from "@/modules/albums/grants";
+import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
import { requireAdmin } from "@/modules/auth/principal";
-export async function grantAlbumAction(editorialId: string, formData: FormData): Promise {
+// 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 {
const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId);
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
- await albumGrantService.grantAlbum({
- editorialId: safeEditorialId,
- immichAlbumId,
- adminUserId: principal.userId,
- });
+ try {
+ await albumGrantService.grantAlbum({
+ editorialId: safeEditorialId,
+ immichAlbumId,
+ adminUserId: principal.userId,
+ });
+ } catch (error) {
+ return { ok: false, message: albumGrantErrorMessage(error) };
+ }
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
+ return INITIAL_RESULT;
}
-export async function revokeAlbumAction(editorialId: string, formData: FormData): Promise {
+export async function revokeAlbumAction(
+ editorialId: string,
+ _prevState: AlbumActionResult,
+ formData: FormData,
+): Promise {
const principal = await getAdminPrincipal();
const safeEditorialId = requiredId(editorialId);
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
- await albumGrantService.revokeAlbum({
- editorialId: safeEditorialId,
- immichAlbumId,
- adminUserId: principal.userId,
- });
+ try {
+ await albumGrantService.revokeAlbum({
+ editorialId: safeEditorialId,
+ immichAlbumId,
+ adminUserId: principal.userId,
+ });
+ } catch (error) {
+ return { ok: false, message: albumGrantErrorMessage(error) };
+ }
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
+ return INITIAL_RESULT;
}
async function getAdminPrincipal() {
return requireAdmin(new Headers(await headers()));
}
+function albumGrantErrorMessage(error: unknown): string {
+ if (error instanceof AlbumGrantError) {
+ const messages: Record = {
+ 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 {
if (
typeof value !== "string" ||
@@ -42,4 +82,4 @@ function requiredId(value: unknown): string {
throw new Error("INVALID_ID");
}
return value;
-}
+}
\ No newline at end of file
diff --git a/src/app/admin/redaktionen/[id]/alben/page.tsx b/src/app/admin/redaktionen/[id]/alben/page.tsx
index 728f642..40e7fbc 100644
--- a/src/app/admin/redaktionen/[id]/alben/page.tsx
+++ b/src/app/admin/redaktionen/[id]/alben/page.tsx
@@ -1,8 +1,10 @@
-import Image from "next/image";
+/* eslint-disable @next/next/no-img-element */
+
import Link from "next/link";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
+import { AlbumGrantForm } from "@/components/admin/album-grant-form";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { albumGrantService } from "@/modules/albums/grants";
@@ -62,7 +64,7 @@ export default async function EditorialAlbumsPage({
{album.albumThumbnailAssetId ? (
-
Status: {album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}
-
+
);
@@ -92,4 +93,4 @@ export default async function EditorialAlbumsPage({
)}
);
-}
+}
\ No newline at end of file
diff --git a/src/components/admin/album-grant-form.tsx b/src/components/admin/album-grant-form.tsx
new file mode 100644
index 0000000..a94f090
--- /dev/null
+++ b/src/components/admin/album-grant-form.tsx
@@ -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;
+ isGranted: boolean;
+ albumId: string;
+}>) {
+ const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
+
+ return (
+
+ );
+}
\ No newline at end of file
diff --git a/src/components/admin/approve-form.tsx b/src/components/admin/approve-form.tsx
new file mode 100644
index 0000000..ea34ea7
--- /dev/null
+++ b/src/components/admin/approve-form.tsx
@@ -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;
+ canApprove: boolean;
+}>) {
+ const [state, formAction, pending] = useActionState(action, { ok: true, message: "" });
+
+ return (
+
+ );
+}
\ No newline at end of file
diff --git a/src/modules/editorials/admin-detail.tsx b/src/modules/editorials/admin-detail.tsx
index 613ad28..c93a848 100644
--- a/src/modules/editorials/admin-detail.tsx
+++ b/src/modules/editorials/admin-detail.tsx
@@ -1,5 +1,6 @@
import Link from "next/link";
+import { ApproveForm } from "@/components/admin/approve-form";
import { approveEditorialAction } from "@/app/admin/redaktionen/[id]/actions";
export type EditorialDetail = {
@@ -51,22 +52,10 @@ export function EditorialDetailContent({
Die Redaktion ist freigegeben (Netto {formatCents(editorial.currentPriceCents ?? 0)}).
) : (
<>
-
+
{approvalHint}
Albumrechte verwalten
>
diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts
index 1ea6d5a..bd0d731 100644
--- a/src/modules/immich/client.ts
+++ b/src/modules/immich/client.ts
@@ -43,7 +43,10 @@ const albumSummarySchema = z
.passthrough();
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
@@ -324,7 +327,7 @@ export function createImmichClient({
},
getAlbum(albumId, signal) {
return requestJson(
- `/albums/${encodeURIComponent(albumId)}`,
+ `/albums/${encodeURIComponent(albumId)}?withoutAssets=true`,
{ method: "GET" },
albumSchema,
signal,