feat(cms): improve catalog, editorial recovery and operations
This commit is contained in:
1 parent
2fead134e6
commit
c389c3893d
122 files changed
+8137
-703
No files matched your search
@@ -1,14 +1,16 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
guard: vi.fn(),
|
||||
resolve: vi.fn(),
|
||||
assign: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/admin/guard", () => ({ requirePermission: mocks.guard }));
|
||||
vi.mock("@/lib/error-monitor", () => ({
|
||||
ErrorStore: class {
|
||||
resolve = mocks.resolve;
|
||||
assign = mocks.assign;
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/permissions", () => ({
|
||||
@@ -17,7 +19,7 @@ vi.mock("@/lib/permissions", () => ({
|
||||
vi.mock("@/lib/services/audit", () => ({ logAudit: mocks.audit }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
|
||||
|
||||
import { resolveCmsError } from "./actions";
|
||||
import { assignCmsError, resolveCmsError } from "./actions";
|
||||
|
||||
it("requires edit permission before resolving or auditing", async () => {
|
||||
mocks.guard.mockRejectedValue(new Error("denied"));
|
||||
@@ -37,3 +39,33 @@ it("records who resolved the problem", async () => {
|
||||
expect.objectContaining({ userId: 42, action: "cms.error.resolve" }),
|
||||
);
|
||||
});
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
it("requires edit permission before assigning", async () => {
|
||||
mocks.guard.mockRejectedValue(new Error("denied"));
|
||||
await expect(assignCmsError(new FormData())).rejects.toThrow("denied");
|
||||
expect(mocks.assign).not.toHaveBeenCalled();
|
||||
});
|
||||
it("assigns only the authenticated staff member, ignoring submitted user IDs", async () => {
|
||||
mocks.guard.mockResolvedValue({ id: 42 });
|
||||
const data = new FormData();
|
||||
data.set("fingerprint", "aabbccddeeff0011");
|
||||
data.set("assignment", "self");
|
||||
data.set("userId", "999");
|
||||
await assignCmsError(data);
|
||||
expect(mocks.guard).toHaveBeenCalledWith("admin.devops.edit");
|
||||
expect(mocks.assign).toHaveBeenCalledWith("aabbccddeeff0011", 42);
|
||||
expect(mocks.audit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: 42, action: "cms.error.assign" }),
|
||||
);
|
||||
data.set("assignment", "clear");
|
||||
await assignCmsError(data);
|
||||
expect(mocks.assign).toHaveBeenLastCalledWith("aabbccddeeff0011", null);
|
||||
});
|
||||
it("rejects unsupported assignment commands", async () => {
|
||||
mocks.guard.mockResolvedValue({ id: 42 });
|
||||
const data = new FormData();
|
||||
data.set("assignment", "other");
|
||||
await expect(assignCmsError(data)).rejects.toThrow("Invalid assignment");
|
||||
expect(mocks.assign).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -15,3 +15,20 @@ export async function resolveCmsError(data: FormData) {
|
||||
});
|
||||
revalidatePath("/admin/devops/cms-errors");
|
||||
}
|
||||
|
||||
export async function assignCmsError(data: FormData) {
|
||||
const staff = await requirePermission(PERMS.DEVOPS_EDIT);
|
||||
const mode = data.get("assignment");
|
||||
if (mode !== "self" && mode !== "clear")
|
||||
throw new Error("Invalid assignment operation");
|
||||
const fingerprint = String(data.get("fingerprint") ?? "");
|
||||
const userId = mode === "self" ? staff.id : null;
|
||||
await new ErrorStore().assign(fingerprint, userId);
|
||||
await logAudit({
|
||||
userId: staff.id,
|
||||
action: "cms.error.assign",
|
||||
target: "cms-error",
|
||||
after: { fingerprint, assignedUserId: userId },
|
||||
});
|
||||
revalidatePath("/admin/devops/cms-errors");
|
||||
}
|
||||
@@ -1,21 +1,35 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getTranslations } from "next-intl/server";
|
||||
|
||||
import Link from "@/components/link";
|
||||
|
||||
import { summarizeErrorGroup } from "@/lib/error-groups";
|
||||
|
||||
import { ErrorStore } from "@/lib/error-monitor";
|
||||
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { resolveCmsError } from "./actions";
|
||||
|
||||
import { assignCmsError, resolveCmsError } from "./actions";
|
||||
|
||||
export default async function CmsErrorsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string>>;
|
||||
}) {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
|
||||
if (!canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank))
|
||||
redirect("/admin");
|
||||
|
||||
const t = await getTranslations("pages.admin.cmsErrors");
|
||||
|
||||
const params = await searchParams;
|
||||
|
||||
const query = (params.q ?? "").trim().slice(0, 200).toLowerCase();
|
||||
|
||||
let result: Awaited<ReturnType<ErrorStore["read"]>>;
|
||||
|
||||
try {
|
||||
result = await new ErrorStore().read();
|
||||
} catch {
|
||||
@@ -25,28 +39,48 @@ export default async function CmsErrorsPage({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const filtered = result.records.filter(
|
||||
(r) =>
|
||||
(!params.source || r.source === params.source) &&
|
||||
(params.status !== "open" || !r.resolved) &&
|
||||
(params.status !== "resolved" || r.resolved) &&
|
||||
(!query || JSON.stringify(r).toLowerCase().includes(query)),
|
||||
);
|
||||
const groups = new Map<string, typeof filtered>();
|
||||
for (const r of filtered) {
|
||||
const list = groups.get(r.fingerprint) ?? [];
|
||||
list.push(r);
|
||||
groups.set(r.fingerprint, list);
|
||||
|
||||
const allGroups = new Map<string, typeof result.records>();
|
||||
|
||||
for (const record of result.records) {
|
||||
const events = allGroups.get(record.fingerprint) ?? [];
|
||||
|
||||
events.push(record);
|
||||
allGroups.set(record.fingerprint, events);
|
||||
}
|
||||
|
||||
const groups = new Map(
|
||||
[...allGroups.entries()].filter(([, events]) => {
|
||||
const latest = summarizeErrorGroup(events).latest;
|
||||
|
||||
return (
|
||||
latest &&
|
||||
(!params.source || latest.source === params.source) &&
|
||||
(params.status !== "open" || !latest.resolved) &&
|
||||
(params.status !== "resolved" || latest.resolved) &&
|
||||
(!query ||
|
||||
events.some((record) =>
|
||||
JSON.stringify(record).toLowerCase().includes(query),
|
||||
))
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const filtered = [...groups.values()].flat();
|
||||
|
||||
const page = Math.max(
|
||||
1,
|
||||
|
||||
Math.min(
|
||||
Number(params.page) || 1,
|
||||
|
||||
Math.max(1, Math.ceil(groups.size / 25)),
|
||||
),
|
||||
);
|
||||
|
||||
const pageHref = (next: number) =>
|
||||
`?${new URLSearchParams({ q: params.q ?? "", source: params.source ?? "", status: params.status ?? "", page: String(next) })}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
@@ -104,9 +138,16 @@ export default async function CmsErrorsPage({
|
||||
<div className="admin-card">{t("empty")}</div>
|
||||
) : null}
|
||||
{[...groups.entries()]
|
||||
|
||||
.slice((page - 1) * 25, page * 25)
|
||||
|
||||
.map(([fingerprint, events]) => {
|
||||
const r = events[0];
|
||||
const metrics = summarizeErrorGroup(events);
|
||||
|
||||
const r = metrics.latest;
|
||||
|
||||
if (!r) return null;
|
||||
|
||||
return (
|
||||
<details key={fingerprint} className="admin-card overflow-hidden">
|
||||
<summary className="cursor-pointer">
|
||||
@@ -118,6 +159,105 @@ export default async function CmsErrorsPage({
|
||||
<p className="text-sm break-words">{r.message}</p>
|
||||
</summary>
|
||||
<div className="mt-4 space-y-3 text-sm">
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("firstSeen")}</dt>
|
||||
<dd>
|
||||
<time dateTime={metrics.firstAt ?? ""}>
|
||||
{metrics.firstAt}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("lastSeen")}</dt>
|
||||
<dd>
|
||||
<time dateTime={metrics.lastAt ?? ""}>
|
||||
{metrics.lastAt}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
{t("affectedUsers")}
|
||||
</dt>
|
||||
<dd>{metrics.affectedUsers}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">
|
||||
{t("unidentifiedEvents")}
|
||||
</dt>
|
||||
<dd>{metrics.unidentified}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("metricsScope")}
|
||||
</p>
|
||||
<p>
|
||||
{r.assignment
|
||||
? t("assignedStaff", { id: r.assignment.userId })
|
||||
: t("unassigned")}
|
||||
</p>
|
||||
{canAccess(
|
||||
permissions,
|
||||
PERMS.DEVOPS_EDIT,
|
||||
session.user.rank,
|
||||
) && (
|
||||
<form
|
||||
action={assignCmsError}
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
<input
|
||||
type="hidden"
|
||||
name="fingerprint"
|
||||
value={fingerprint}
|
||||
/>
|
||||
{r.assignment?.userId !== session.user.id && (
|
||||
<button
|
||||
type="submit"
|
||||
name="assignment"
|
||||
value="self"
|
||||
className="btn btn-outline"
|
||||
>
|
||||
{t("assignSelf")}
|
||||
</button>
|
||||
)}
|
||||
{r.assignment && (
|
||||
<button
|
||||
type="submit"
|
||||
name="assignment"
|
||||
value="clear"
|
||||
className="btn btn-outline"
|
||||
>
|
||||
{t("clearAssignment")}
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
{metrics.operationLink && (
|
||||
<Link
|
||||
href={metrics.operationLink}
|
||||
className="btn btn-outline"
|
||||
>
|
||||
{t("openOperation")}
|
||||
</Link>
|
||||
)}
|
||||
<details>
|
||||
<summary className="cursor-pointer">
|
||||
{t("releaseOccurrences")}
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-2">
|
||||
{metrics.releases.map((release) => (
|
||||
<li key={release.release} className="break-all">
|
||||
<code>{release.release}</code> ·{" "}
|
||||
{t("occurrences", { count: release.count })} ·{" "}
|
||||
{release.firstAt} — {release.lastAt}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("releaseScope")}
|
||||
</p>
|
||||
</details>
|
||||
<p>
|
||||
{t("reference")}: <code className="break-all">{r.id}</code>
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ inspect: vi.fn(), access: vi.fn() }));
|
||||
vi.mock("@/lib/permissions", () => ({
|
||||
getAdminContext: async () => ({
|
||||
session: { user: { rank: 1 } },
|
||||
permissions: {},
|
||||
}),
|
||||
canAccess: mocks.access,
|
||||
PERMS: { DEVOPS_VIEW: "devops.view" },
|
||||
}));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: () => {
|
||||
throw Error("redirect");
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/admin/installation", () => ({
|
||||
inspectInstallation: mocks.inspect,
|
||||
}));
|
||||
vi.mock("../../commandocentrum/refresh-status", () => ({
|
||||
RefreshStatus: () => null,
|
||||
}));
|
||||
|
||||
import Page from "./page";
|
||||
|
||||
it("rejects unauthorized access before checking database, filesystem or worker", async () => {
|
||||
mocks.access.mockReturnValue(false);
|
||||
await expect(Page()).rejects.toThrow("redirect");
|
||||
expect(mocks.inspect).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { inspectInstallation } from "@/lib/admin/installation";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||
import { RefreshStatus } from "../../commandocentrum/refresh-status";
|
||||
export default async function InstallationPage() {
|
||||
const { session, permissions } = await getAdminContext();
|
||||
if (!canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank))
|
||||
redirect("/admin");
|
||||
const t = await getTranslations("pages.admin.installation");
|
||||
const result = await inspectInstallation();
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h1 className="text-2xl font-semibold">{t("title")}</h1>
|
||||
<p>{t("hint")}</p>
|
||||
<p className="text-sm text-[var(--admin-text-muted)]">
|
||||
{t("checked", {
|
||||
time: formatDate(new Date(result.checkedAt), "datetime-seconds"),
|
||||
ms: result.durationMs,
|
||||
})}
|
||||
</p>
|
||||
<RefreshStatus label={t("recheck")} />
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{result.rows.map((row) => (
|
||||
<section key={row.key} className="admin-card space-y-2 min-w-0">
|
||||
<h2 className="font-semibold">{t(row.key)}</h2>
|
||||
<p
|
||||
className={
|
||||
row.state === "failed"
|
||||
? "text-destructive"
|
||||
: row.state === "ok"
|
||||
? "text-[var(--admin-success)]"
|
||||
: "text-[var(--admin-text-muted)]"
|
||||
}
|
||||
>
|
||||
{t(row.state)}
|
||||
</p>
|
||||
{row.detail ? (
|
||||
<code className="block break-all text-xs">{row.detail}</code>
|
||||
) : null}
|
||||
<p className="text-sm text-[var(--admin-text-muted)]">
|
||||
{t(`${row.key}Hint`)}
|
||||
</p>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -53,12 +53,16 @@ export default async function DevOpsPage() {
|
||||
|
||||
const t = await getTranslations("pages.admin.devops");
|
||||
const data = await getDevOpsData();
|
||||
const installation = await getTranslations("pages.admin.installation");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<a href="/admin/devops/cms-errors" className="btn btn-outline">
|
||||
{t("cmsErrors")}
|
||||
</a>
|
||||
<Link href="/admin/devops/installation" className="btn btn-outline">
|
||||
{installation("title")}
|
||||
</Link>
|
||||
{/* Status cards */}
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
|
||||
<Card>
|
||||
|
||||
Reference in new issue
Block a user