fix(housekeeping): preserve form state and accurate access details

This commit is contained in:
Simo committed 2026-09-03 20:39:10 +02:00
1 parent 93367a239f
commit 11ddf6cf0b
8 files changed
+293 -68

No files matched your search

@@ -1,5 +1,6 @@
"use client";
import { useRouter } from "next/navigation";
import { useActionState, useId } from "react";
import { requiresHousekeepingReason } from "../../../foundation/commands/reason-policy";
import type { HousekeepingResult } from "../../../foundation/contracts";
@@ -161,7 +162,22 @@ export async function submitContentCommandForm(
input,
...(reasonRequired ? { reason } : {}),
});
return { result, values: result.ok ? {} : submittedValues };
return { result, values: submittedValues };
}
export async function submitContentCommandFormAndRefresh(
configuration: ContentCommandSubmission,
refresh: () => void,
previous: ContentCommandFormState | null,
formData: FormData,
): Promise<ContentCommandFormState> {
const state = await submitContentCommandForm(
configuration,
previous,
formData,
);
if (state.result?.ok) refresh();
return state;
}
export function ContentCommandFieldError({
@@ -191,18 +207,23 @@ export function ContentCommandForm({
requiresReason = false,
}: ContentCommandFormProps) {
const formId = useId();
const router = useRouter();
const reasonRequired = requiresHousekeepingReason(requiresReason, input);
const [state, submit, pending] = useActionState(
submitContentCommandForm.bind(null, {
commandId,
input,
fields,
requiresReason: reasonRequired,
}),
submitContentCommandFormAndRefresh.bind(
null,
{
commandId,
input,
fields,
requiresReason: reasonRequired,
},
() => router.refresh(),
),
initialState,
);
const result = state.result;
const retainedValues = result && !result.ok ? state.values : {};
const retainedValues = result ? state.values : {};
const remountKey = `${formId}-${result?.correlationId ?? "initial"}`;
const reasonErrorId = `${formId}-reason-error`;
const hasReasonError =
@@ -23,8 +23,9 @@ import { ContentHelpPage } from "./help";
import { ContentLocalizationPage } from "./localization";
import { ContentMediaPage } from "./media";
const { actionState } = vi.hoisted(() => ({
const { actionState, routerRefresh } = vi.hoisted(() => ({
actionState: { current: null as unknown },
routerRefresh: vi.fn(),
}));
vi.mock("react", async (importOriginal) => {
@@ -43,6 +44,10 @@ vi.mock("@/actions/housekeeping-command", () => ({
executeHousekeepingCommand: vi.fn(),
}));
vi.mock("next/navigation", () => ({
useRouter: () => ({ refresh: routerRefresh }),
}));
function context(granted: readonly string[]): HousekeepingCapabilityContext {
const permissions = new Set(granted);
return {
@@ -313,7 +318,7 @@ describe("Content actionable form wiring", () => {
});
});
it("clears retained values after a successful command", async () => {
it("retains submitted values after a successful command", async () => {
vi.mocked(executeHousekeepingCommand).mockResolvedValue(
ok({ before: null, after: { id: "41" } }, "poll-success"),
);
@@ -330,7 +335,96 @@ describe("Content actionable form wiring", () => {
formData,
);
expect(state).toMatchObject({ result: { ok: true }, values: {} });
expect(state).toMatchObject({
result: { ok: true },
values: { title: "Published poll" },
});
});
it("keeps the first successful edit across stale SSR defaults and refreshes each success once", async () => {
const module = (await import("./content-command-form")) as Record<
string,
unknown
>;
const submitAndRefresh = module.submitContentCommandFormAndRefresh;
expect(submitAndRefresh).toBeTypeOf("function");
if (typeof submitAndRefresh !== "function") return;
vi.mocked(executeHousekeepingCommand)
.mockResolvedValueOnce(
ok(
{ before: { title: "Title A" }, after: { title: "Title B" } },
"first-success",
),
)
.mockResolvedValueOnce(
ok(
{
before: { title: "Title B", description: "Old summary" },
after: { title: "Title B", description: "New summary" },
},
"second-success",
),
);
const configuration = {
commandId: "content.editorial.article.change",
input: { action: "update", id: "41" },
fields: [
{ name: "title", label: "Title", type: "text" as const },
{
name: "description",
label: "Summary",
type: "text" as const,
},
],
};
const firstData = new FormData();
firstData.set("title", "Title B");
firstData.set("description", "Old summary");
const firstState = await Reflect.apply(submitAndRefresh, undefined, [
configuration,
routerRefresh,
null,
firstData,
]);
expect(firstState).toMatchObject({
result: { ok: true },
values: { title: "Title B", description: "Old summary" },
});
actionState.current = firstState;
const remounted = renderToStaticMarkup(
<ContentCommandForm
{...configuration}
buttonLabel="Save article"
fields={[
{ ...configuration.fields[0], defaultValue: "Title A" },
{ ...configuration.fields[1], defaultValue: "Old summary" },
]}
/>,
);
expect(remounted).toMatch(/name="title"[^>]*value="Title B"/u);
const secondData = new FormData();
secondData.set("title", "Title B");
secondData.set("description", "New summary");
await Reflect.apply(submitAndRefresh, undefined, [
configuration,
routerRefresh,
firstState,
secondData,
]);
expect(executeHousekeepingCommand).toHaveBeenNthCalledWith(2, {
commandId: "content.editorial.article.change",
input: {
action: "update",
id: "41",
title: "Title B",
description: "New summary",
},
});
expect(routerRefresh).toHaveBeenCalledTimes(2);
});
it("renders an accessible stable field error", () => {
@@ -1,6 +1,6 @@
"use client";
import { useActionState } from "react";
import { useActionState, useId } from "react";
import type { HousekeepingResult } from "../../../foundation/contracts";
export interface PeopleCommandField {
@@ -204,6 +204,7 @@ export function PeopleCommandForm({
includeReasonInInput = false,
nestFields = false,
}: PeopleCommandFormProps) {
const formId = useId();
const [result, submit, pending] = useActionState(
submitPeopleCommandForm.bind(null, {
commandId,
@@ -222,61 +223,56 @@ export function PeopleCommandForm({
data-housekeeping-command={commandId}
className="space-y-3 rounded border border-[var(--admin-border)] p-3"
>
{fields.map((field) => (
<label
key={field.name}
htmlFor={`${commandId}-${field.name}`}
className="block text-sm"
>
{field.type === "checkbox" ? (
<>
<input
id={`${commandId}-${field.name}`}
name={field.name}
type="checkbox"
/>{" "}
{field.label}
</>
) : field.type === "select" ? (
<>
{field.label}
<select
id={`${commandId}-${field.name}`}
name={field.name}
defaultValue={field.defaultValue}
required={field.required}
className="mt-1 block w-full"
>
{field.options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</>
) : (
<>
{field.label}
<input
id={`${commandId}-${field.name}`}
name={field.name}
type={field.type === "number" ? "number" : "text"}
defaultValue={field.defaultValue}
required={field.required}
min={field.min}
max={field.max}
maxLength={field.maxLength}
className="mt-1 block w-full"
/>
</>
)}
</label>
))}
{fields.map((field) => {
const fieldId = `${formId}-${field.name}`;
return (
<label key={field.name} htmlFor={fieldId} className="block text-sm">
{field.type === "checkbox" ? (
<>
<input id={fieldId} name={field.name} type="checkbox" />{" "}
{field.label}
</>
) : field.type === "select" ? (
<>
{field.label}
<select
id={fieldId}
name={field.name}
defaultValue={field.defaultValue}
required={field.required}
className="mt-1 block w-full"
>
{field.options?.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</>
) : (
<>
{field.label}
<input
id={fieldId}
name={field.name}
type={field.type === "number" ? "number" : "text"}
defaultValue={field.defaultValue}
required={field.required}
min={field.min}
max={field.max}
maxLength={field.maxLength}
className="mt-1 block w-full"
/>
</>
)}
</label>
);
})}
{requiresReason ? (
<label htmlFor={`${commandId}-reason`} className="block text-sm">
<label htmlFor={`${formId}-reason`} className="block text-sm">
Reason
<textarea
id={`${commandId}-reason`}
id={`${formId}-reason`}
name="reason"
required
maxLength={1000}
@@ -244,6 +244,14 @@ describe("People support/moderation pages", () => {
expect(html).toContain('value="Hello"');
expect(html).toContain('value="general"');
expect(html).toContain('value="4"');
const titleIds = [
...html.matchAll(
/<input(?=[^>]*\bname="title")(?=[^>]*\bid="([^"]+)")[^>]*>/gu,
),
].map((match) => match[1]);
expect(titleIds).toHaveLength(2);
expect(new Set(titleIds).size).toBe(titleIds.length);
for (const id of titleIds) expect(html).toContain(`for="${id}"`);
executeHousekeepingCommand.mockResolvedValue({
ok: true,
@@ -8,6 +8,7 @@ import { HousekeepingPageShell } from "../../../foundation/page/housekeeping-pag
import { HousekeepingPageState } from "../../../foundation/page/housekeeping-page-state";
import type { HousekeepingPageInput } from "../../../route-handlers";
import {
SYSTEM_ACCESS_USER_SAMPLE_LIMIT,
type SystemAccessQueryData,
type SystemAccessQueryInput,
systemAccessQuery,
@@ -61,8 +62,13 @@ function accessContent(data: SystemAccessQueryData) {
<dd>{data.rank.id}</dd>
<dt>Level</dt>
<dd>{data.rank.level}</dd>
<dt>Users</dt>
<dt>Total users</dt>
<dd>{data.rank.userCount}</dd>
<dt>User sample</dt>
<dd>
Showing {data.rank.users.length} of {data.rank.userCount} (maximum{" "}
{SYSTEM_ACCESS_USER_SAMPLE_LIMIT})
</dd>
</dl>
</section>
<section className="rounded-lg border border-[var(--admin-border)] bg-[var(--admin-surface)] p-4">
@@ -204,3 +204,34 @@ it.each([
expect(html).not.toContain('data-housekeeping-state="empty"');
},
);
it("labels the rank total separately from its bounded user sample", () => {
const html = renderToStaticMarkup(
<SystemAccessPage
result={ok(
{
kind: "permission-detail",
rank: {
id: 7,
name: "Administrator",
level: 7,
userCount: 237,
badge: "ADM",
permissions: {},
cmsRole: null,
users: [
{ id: 1, username: "Ada" },
{ id: 2, username: "Linus" },
],
},
partialDependencies: [],
},
correlationId,
)}
/>,
);
expect(html).toContain("Total users");
expect(html).toContain("User sample");
expect(html).toContain("Showing 2 of 237 (maximum 200)");
});
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { execute, fetchEmulatorRankForEdit } = vi.hoisted(() => ({
execute: vi.fn(),
fetchEmulatorRankForEdit: vi.fn(),
}));
vi.mock("@/lib/db", () => ({ db: { execute } }));
vi.mock("@/lib/services/permission-ranks", () => ({
fetchEmulatorRankForEdit,
}));
import { systemAccessAdapters } from "./access";
describe("System rank-detail production adapter", () => {
beforeEach(() => {
execute.mockReset();
fetchEmulatorRankForEdit.mockReset();
});
it("separates the exact user total from the bounded 200-row sample", async () => {
fetchEmulatorRankForEdit.mockResolvedValue({
id: 7,
rank_name: "Administrator",
level: 7,
badge: "ADM",
permissions: {},
});
execute
.mockResolvedValueOnce([
[
{ id: 1n, username: "Ada" },
{ id: 2n, username: "Linus" },
],
])
.mockResolvedValueOnce([[{ total: 237n }]])
.mockResolvedValueOnce([
[
{
id: 3n,
slug: "rank_7",
title: "Administrator",
permission_slug: "admin.settings.view",
},
],
]);
const detail = await systemAccessAdapters.loadRankDetail(7);
expect(execute).toHaveBeenCalledTimes(3);
expect(detail).toMatchObject({
userCount: 237,
users: [
{ id: 1, username: "Ada" },
{ id: 2, username: "Linus" },
],
});
});
});
@@ -28,6 +28,8 @@ export interface SystemAccessRankDetail extends SystemAccessRank {
readonly users: readonly { id: number; username: string }[];
}
export const SYSTEM_ACCESS_USER_SAMPLE_LIMIT = 200;
export interface SystemAclOverview {
readonly roles: number;
readonly permissions: number;
@@ -178,13 +180,18 @@ export const systemAccessAdapters: SystemAccessAdapters = {
const rank = await fetchEmulatorRankForEdit(db, rankId);
if (!rank) return null;
const [userResult, roleResult] = await Promise.all([
const [userResult, userCountResult, roleResult] = await Promise.all([
db.execute(sql`
SELECT id, username
FROM users
WHERE \`rank\` = ${rankId}
ORDER BY username ASC
LIMIT 200
LIMIT ${SYSTEM_ACCESS_USER_SAMPLE_LIMIT}
`),
db.execute(sql`
SELECT COUNT(*) AS total
FROM users
WHERE \`rank\` = ${rankId}
`),
db.execute(sql`
SELECT ar.id, ar.slug, ar.title, ap.slug AS permission_slug
@@ -200,6 +207,9 @@ export const systemAccessAdapters: SystemAccessAdapters = {
id: number | bigint;
username: string;
}[];
const [userCountRow] = userCountResult[0] as unknown as {
total: number | bigint;
}[];
const roles = roleResult[0] as unknown as {
id: number | bigint;
slug: string;
@@ -212,7 +222,7 @@ export const systemAccessAdapters: SystemAccessAdapters = {
id: rank.id,
name: rank.rank_name,
level: rank.level,
userCount: users.length,
userCount: Number(userCountRow?.total ?? 0),
badge: rank.badge,
permissions: rank.permissions,
cmsRole: role