feat(cms): recover drafts and failed imports with verified UI workflows
CI / check (push) Successful in 2m3s
CI / deploy (push) Successful in 1m31s
CI / publish-container (push) Successful in 1m41s

This commit is contained in:
Simo committed 2026-09-11 08:58:10 +02:00
1 parent 410a1e466c
commit 88790d1a0d
84 files changed
+3952 -288

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ export default async function EditArticle({
</p>
) : null}
<ArticleForm
userId={String(session.user.id)}
articleKey={String(article.id)}
baseToken={articleEditToken(article)}
action={async (fd) => {
+1 -1
View File
@@ -39,7 +39,7 @@ export default async function NewArticle({
Error: {error}
</p>
) : null}
<ArticleForm action={createArticle} />
<ArticleForm userId={String(session.user.id)} action={createArticle} />
</main>
);
}
+1 -1
View File
@@ -29,7 +29,7 @@ export default async function CreateEventPage() {
</p>
</div>
<EventForm eventTypes={eventTypes} />
<EventForm userId={String(session.user.id)} eventTypes={eventTypes} />
</div>
);
}
+217 -173
View File
@@ -1,5 +1,6 @@
"use client";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
@@ -19,7 +20,9 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useFormRecovery } from "@/hooks/use-form-recovery";
import { useServerAction } from "@/hooks/use-server-action";
import { useUnsavedChanges } from "@/hooks/use-unsaved-changes";
import { publicationIssues } from "@/lib/publication-preflight";
import type {
CreateEventInput,
@@ -34,6 +37,7 @@ interface EventType {
}
interface EventFormProps {
userId?: string;
eventTypes: EventType[];
defaultValues?: Partial<CreateEventInput> & { id?: number };
}
@@ -51,9 +55,14 @@ interface EventFormValues {
endsAt?: Date | null;
}
export function EventForm({ eventTypes, defaultValues }: EventFormProps) {
export function EventForm({
eventTypes,
defaultValues,
userId,
}: EventFormProps) {
const t = useTranslations("pages.admin.events");
const tAction = useTranslations("pages.admin.actions");
const router = useRouter();
const [preview, setPreview] = useState(false);
const { run, isPending } = useServerAction();
const isEditing = !!defaultValues?.id;
@@ -69,9 +78,28 @@ export function EventForm({ eventTypes, defaultValues }: EventFormProps) {
},
});
const dirty = form.formState.isDirty;
useUnsavedChanges(dirty, tAction("leaveUnsaved"));
const recovery = useFormRecovery({
userId,
kind: "event",
record: String(defaultValues?.id ?? "new"),
dirty,
snapshot: () => JSON.parse(JSON.stringify(form.getValues())),
restore: (payload) => {
const restored = {
...payload,
startsAt: payload.startsAt ? new Date(String(payload.startsAt)) : null,
endsAt: payload.endsAt ? new Date(String(payload.endsAt)) : null,
} as EventFormValues;
form.reset(restored, { keepDefaultValues: true });
},
});
const values = form.watch();
const issues = publicationIssues({ kind: "event", ...values });
function onSubmit(data: EventFormValues) {
if (isPending) return;
recovery.flush();
if (
data.status === "published" &&
publicationIssues({ kind: "event", ...data }).some(
@@ -87,15 +115,21 @@ export function EventForm({ eventTypes, defaultValues }: EventFormProps) {
}),
{
successMessage: t("toastUpdated"),
onSuccess: () => {
recovery.clear();
form.reset(data);
router.refresh();
},
},
);
} else {
run(() => createEvent(data as CreateEventInput), {
successMessage: t("toastCreated"),
onSuccess: (result) => {
const data = result.data as Record<string, unknown> | undefined;
if (data?.id) {
window.location.href = `/admin/events/${data.id}`;
recovery.clear();
form.reset(data);
if (result.id) {
router.push(`/admin/events/${result.id}`);
}
},
});
@@ -103,178 +137,188 @@ export function EventForm({ eventTypes, defaultValues }: EventFormProps) {
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>
{isEditing ? t("formEditTitle") : t("formDetailsTitle")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="title">{t("formTitle")}</Label>
<Input id="title" {...form.register("title")} />
{form.formState.errors.title && (
<p className="text-sm text-destructive">
{form.formState.errors.title.message}
</p>
)}
</div>
<form
onChangeCapture={recovery.changed}
onSubmit={form.handleSubmit(onSubmit)}
>
<fieldset disabled={isPending} className="contents">
<Card>
<CardHeader>
<CardTitle>
{isEditing ? t("formEditTitle") : t("formDetailsTitle")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{recovery.panel}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="title">{t("formTitle")}</Label>
<Input id="title" {...form.register("title")} />
{form.formState.errors.title && (
<p className="text-sm text-destructive">
{form.formState.errors.title.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="typeId">{t("formEventType")}</Label>
<Select
value={String(form.watch("typeId"))}
onValueChange={(v) => form.setValue("typeId", Number(v))}
>
<SelectTrigger>
<SelectValue placeholder={t("formSelectType")} />
</SelectTrigger>
<SelectContent>
{eventTypes.map((et) => (
<SelectItem key={et.id} value={String(et.id)}>
{et.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="description">{t("formDescription")}</Label>
<Textarea
id="description"
rows={4}
{...form.register("description")}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>{t("formStartsAt")}</Label>
<DateTimePicker
value={form.watch("startsAt")}
onChange={(d) =>
form.setValue("startsAt", d, { shouldDirty: true })
}
placeholder={t("formSelectStart")}
/>
</div>
<div className="space-y-2">
<Label>{t("formEndsAt")}</Label>
<DateTimePicker
value={form.watch("endsAt")}
onChange={(d) =>
form.setValue("endsAt", d ?? null, { shouldDirty: true })
}
placeholder={t("formSelectEnd")}
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxPlayers">{t("formMaxPlayers")}</Label>
<Input
id="maxPlayers"
type="number"
{...form.register("maxPlayers")}
placeholder={t("formUnlimited")}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="roomId">{t("formRoomId")}</Label>
<Input
id="roomId"
type="number"
{...form.register("roomId")}
placeholder={t("formOptional")}
/>
</div>
<div className="space-y-2">
<Label htmlFor="status">{t("colStatus")}</Label>
<Select
value={form.watch("status")}
onValueChange={(v) =>
form.setValue("status", v as CreateEventInput["status"])
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">{t("statusDraft")}</SelectItem>
<SelectItem value="published">
{t("statusPublished")}
</SelectItem>
<SelectItem value="cancelled">
{t("statusCancelled")}
</SelectItem>
<SelectItem value="completed">
{t("statusCompleted")}
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="image">{t("formImageUrl")}</Label>
<Input
id="image"
{...form.register("image")}
placeholder="https://..."
/>
</div>
<PublicationPreflight
issues={issues}
paths={[
"/events",
...(defaultValues?.id ? [`/events/${defaultValues.id}`] : []),
]}
/>
<ArticlePreview
title={tAction("preview")}
data={
preview
? {
title: values.title,
image: values.image ?? "",
summary: values.description,
body: "",
<div className="space-y-2">
<Label htmlFor="typeId">{t("formEventType")}</Label>
<Select
value={String(form.watch("typeId"))}
onValueChange={(v) =>
form.setValue("typeId", Number(v), { shouldDirty: true })
}
: null
}
onClose={() => setPreview(false)}
/>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => setPreview(true)}
>
{tAction("preview")}
</Button>
<Button
type="submit"
disabled={
isPending ||
(values.status === "published" &&
issues.some((issue) => issue.severity === "error"))
>
<SelectTrigger>
<SelectValue placeholder={t("formSelectType")} />
</SelectTrigger>
<SelectContent>
{eventTypes.map((et) => (
<SelectItem key={et.id} value={String(et.id)}>
{et.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="description">{t("formDescription")}</Label>
<Textarea
id="description"
rows={4}
{...form.register("description")}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>{t("formStartsAt")}</Label>
<DateTimePicker
value={form.watch("startsAt")}
onChange={(d) =>
form.setValue("startsAt", d, { shouldDirty: true })
}
placeholder={t("formSelectStart")}
/>
</div>
<div className="space-y-2">
<Label>{t("formEndsAt")}</Label>
<DateTimePicker
value={form.watch("endsAt")}
onChange={(d) =>
form.setValue("endsAt", d ?? null, { shouldDirty: true })
}
placeholder={t("formSelectEnd")}
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxPlayers">{t("formMaxPlayers")}</Label>
<Input
id="maxPlayers"
type="number"
{...form.register("maxPlayers")}
placeholder={t("formUnlimited")}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="roomId">{t("formRoomId")}</Label>
<Input
id="roomId"
type="number"
{...form.register("roomId")}
placeholder={t("formOptional")}
/>
</div>
<div className="space-y-2">
<Label htmlFor="status">{t("colStatus")}</Label>
<Select
value={form.watch("status")}
onValueChange={(v) =>
form.setValue("status", v as CreateEventInput["status"], {
shouldDirty: true,
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">{t("statusDraft")}</SelectItem>
<SelectItem value="published">
{t("statusPublished")}
</SelectItem>
<SelectItem value="cancelled">
{t("statusCancelled")}
</SelectItem>
<SelectItem value="completed">
{t("statusCompleted")}
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="image">{t("formImageUrl")}</Label>
<Input
id="image"
{...form.register("image")}
placeholder="https://..."
/>
</div>
<PublicationPreflight
issues={issues}
paths={[
"/events",
...(defaultValues?.id ? [`/events/${defaultValues.id}`] : []),
]}
/>
<ArticlePreview
title={tAction("preview")}
data={
preview
? {
title: values.title,
image: values.image ?? "",
summary: values.description,
body: "",
}
: null
}
>
{isPending
? t("formSaving")
: isEditing
? t("formUpdate")
: t("formCreate")}
</Button>
</div>
</CardContent>
</Card>
onClose={() => setPreview(false)}
/>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => setPreview(true)}
>
{tAction("preview")}
</Button>
<Button
type="submit"
disabled={
isPending ||
(values.status === "published" &&
issues.some((issue) => issue.severity === "error"))
}
>
{isPending
? t("formSaving")
: isEditing
? t("formUpdate")
: t("formCreate")}
</Button>
</div>
</CardContent>
</Card>
</fieldset>
</form>
);
}
@@ -1,4 +1,4 @@
import { apiError, apiOk } from "@/lib/api";
import { apiError, apiJson, apiOk } from "@/lib/api";
import { withAdmin } from "@/lib/api-handler";
import { validateClassnames } from "@/lib/furni/studio-inspection";
import { PERMS } from "@/lib/permission-slugs";
@@ -28,9 +28,16 @@ export const POST = withAdmin(
);
return apiOk({ attachmentId });
} catch (error) {
return apiError(
error instanceof Error ? error.message : "Invalid .nitro file",
400,
return apiJson(
{
error: "Invalid original .nitro file",
code:
error instanceof Error &&
error.message.startsWith("This bundle does not belong")
? "mismatchedFile"
: "invalidFile",
},
{ status: 400 },
);
}
},
@@ -4,6 +4,7 @@ import { beforeEach, expect, it, vi } from "vitest";
import { PERMS } from "@/lib/permission-slugs";
const mocks = vi.hoisted(() => ({
attachment: vi.fn(),
guard: vi.fn(),
create: vi.fn(),
list: vi.fn(),
@@ -40,6 +41,10 @@ vi.mock("@/lib/services/furni-job-store", async (original) => ({
}));
vi.mock("@/lib/services/clone-sources", () => ({ getSource: mocks.source }));
vi.mock("@/lib/services/furni-attachment", () => ({
readFurnitureAttachment: mocks.attachment,
}));
import { GET, PATCH, POST } from "./route";
const item = {
@@ -179,3 +184,53 @@ it("rejects malformed history cursors", async () => {
).status,
).toBe(400);
});
it("validates recovery attachment ownership and classname before queueing", async () => {
const id = randomUUID(),
attachmentId = randomUUID();
mocks.attachment.mockResolvedValue(Buffer.from("valid"));
mocks.retry.mockResolvedValue({ id });
expect(
(
await PATCH(
request({ id, action: "retry", attachments: { chair: attachmentId } }),
ctx,
)
).status,
).toBe(200);
expect(mocks.attachment).toHaveBeenCalledWith(attachmentId, "chair", 7);
expect(mocks.retry).toHaveBeenCalledWith(id, 7, { chair: attachmentId });
});
it("rejects foreign or mismatched recovery files without retrying", async () => {
mocks.retry.mockClear();
mocks.attachment.mockRejectedValue(Error("owner mismatch"));
expect(
(
await PATCH(
request({
id: randomUUID(),
action: "retry",
attachments: { chair: randomUUID() },
}),
ctx,
)
).status,
).toBe(400);
expect(mocks.retry).not.toHaveBeenCalled();
});
it("rejects invalid recovery attachment paths", async () => {
mocks.retry.mockClear();
expect(
(
await PATCH(
request({
id: randomUUID(),
action: "retry",
attachments: { "../chair": randomUUID() },
}),
ctx,
)
).status,
).toBe(400);
expect(mocks.retry).not.toHaveBeenCalled();
});
+37 -5
View File
@@ -1,12 +1,13 @@
import { after } from "next/server";
import { z } from "zod";
import { apiError, apiOk } from "@/lib/api";
import { apiError, apiJson, apiOk } from "@/lib/api";
import { withAdmin } from "@/lib/api-handler";
import { getRequestId } from "@/lib/foundation/request-context";
import { validateClassnames } from "@/lib/furni/studio-inspection";
import { PERMS } from "@/lib/permission-slugs";
import { redis } from "@/lib/redis";
import { getSource } from "@/lib/services/clone-sources";
import { readFurnitureAttachment } from "@/lib/services/furni-attachment";
import { ImportJobStore, validJobId } from "@/lib/services/furni-job-store";
import { drainFurnitureImports } from "@/lib/services/furni-job-worker";
@@ -115,10 +116,41 @@ export const PATCH = withAdmin(
"Background import queue is temporarily unavailable",
503,
);
const job = await new ImportJobStore().retry(
body.id,
ctx.session.user.id,
);
const parsed = z
.record(z.string(), z.uuid())
.refine(
(value) =>
Object.keys(value).length <= 500 &&
(!Object.keys(value).length ||
validateClassnames(Object.keys(value))),
)
.safeParse(body.attachments ?? {});
if (!parsed.success) return apiError("Invalid recovery attachments", 400);
const attachments = parsed.data;
let job: Awaited<ReturnType<ImportJobStore["retry"]>>;
try {
for (const [classname, attachmentId] of Object.entries(attachments))
await readFurnitureAttachment(
attachmentId,
classname,
ctx.session.user.id,
);
const store = new ImportJobStore();
job = Object.keys(attachments).length
? await store.retry(body.id, ctx.session.user.id, attachments)
: await store.retry(body.id, ctx.session.user.id);
} catch (error) {
const message = error instanceof Error ? error.message : "";
const code = message.startsWith("Recovery already started")
? "alreadyStarted"
: message.includes("not eligible")
? "notEligible"
: "invalidFile";
return apiJson(
{ error: "Cannot resume with these attachments", code },
{ status: 400 },
);
}
if (!job)
return apiError(
"No safe remaining items to retry, or import job not found",