Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 136 additions & 1 deletion src/routes/-management.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { getFunctionName } from "convex/server";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Management } from "./management";
import { Management, Route } from "./management";

const useQueryMock = vi.fn();
const usePaginatedQueryMock = vi.fn();
const useMutationMock = vi.fn();
const useActionMock = vi.fn();
const convexClientMock = { query: vi.fn() };
const navigateMock = vi.fn();
let searchState: Record<string, string | undefined> = {};
let authUser: { _id: string; handle: string; role: "admin" | "moderator" | "user" } = {
Expand Down Expand Up @@ -227,7 +228,16 @@ function linkHref(to: string, search: unknown) {
return query ? `${to}?${query}` : to;
}

function validateManagementSearch(search: Record<string, unknown>) {
return (
Route as unknown as {
validateSearch: (search: Record<string, unknown>) => Record<string, string | undefined>;
}
).validateSearch(search);
}

vi.mock("convex/react", () => ({
useConvex: () => convexClientMock,
useAction: (...args: unknown[]) => useActionMock(...args),
usePaginatedQuery: (...args: unknown[]) => usePaginatedQueryMock(...args),
useQuery: (...args: unknown[]) => useQueryMock(...args),
Expand Down Expand Up @@ -1362,6 +1372,131 @@ describe("Management", () => {
);
});

it.each([
["downloads", "Template downloads"],
["search-insights", "Search intelligence"],
["overview", "Overview"],
["abuse", "Publisher abuse"],
["reports", "Content reports"],
["users", "Users"],
["publishers", "Publishers"],
["skills", "Skills"],
["plugins", "Plugins"],
["promotions", "Promotions"],
["duplicates", "Duplicate candidates"],
["recent", "Recent pushes"],
["audit", "Audit log"],
["system", "System"],
["settings", "Settings"],
])("preserves the %s URL and breadcrumb label", async (view, label) => {
if (view === "downloads") convexClientMock.query.mockResolvedValue(null);
if (view === "search-insights") {
useMutationMock.mockReturnValue(
vi.fn().mockResolvedValue({ reportId: "report:1", status: "pending" }),
);
}
const url = new URL(`/management?view=${view}`, "https://example.invalid");
searchState = validateManagementSearch(Object.fromEntries(url.searchParams));
expect(searchState).toEqual({ view });

const { container } = render(<Management />);

await waitFor(() =>
expect(container.querySelector(".management-breadcrumb strong")?.textContent).toBe(label),
);
const link = container.querySelector(`a[href="/management?view=${view}"]`);
if (link) expect(link.querySelector("span")?.textContent).toBe(label);
});

it.each(["constructor", "__proto__", "toString", "Skills", " skills", "skills ", "missing", ""])(
"rejects the unsupported view %j without changing the default",
(view) => {
const url = new URL("/management", "https://example.invalid");
url.searchParams.set("view", view);
searchState = validateManagementSearch(Object.fromEntries(url.searchParams));
expect(searchState).toEqual({});

const { container } = render(<Management />);

expect(container.querySelector(".management-breadcrumb strong")?.textContent).toBe(
"Publisher abuse",
);
},
);

it.each([undefined, null, 1, {}, ["skills"]])("rejects a non-string view %j", (view) => {
expect(validateManagementSearch({ view })).toEqual({});
});

it.each([
[{ view: "reports", skill: "owned-skill", plugin: "example-plugin" }, "Skills"],
[{ skill: " owned-skill " }, "Skills"],
[{ view: "reports", plugin: "example-plugin" }, "Plugins"],
[{ view: "reports", skill: " ", plugin: "example-plugin" }, "Plugins"],
[{ view: "reports", skill: " ", plugin: " " }, "Content reports"],
])("preserves selected item precedence for %j", (search, label) => {
searchState = validateManagementSearch(search);

const { container } = render(<Management />);

expect(container.querySelector(".management-breadcrumb strong")?.textContent).toBe(label);
});

it.each(["admin", "moderator"] as const)("keeps %s navigation order and groups", (role) => {
authUser = { ...authUser, role };
render(<Management />);
const nav = screen.getByRole("navigation", { name: "Management sections" });
const expectedViews = ["abuse", "reports", "duplicates", "recent"];
if (role === "admin") expectedViews.push("downloads");
expectedViews.push("search-insights");
if (role === "admin") expectedViews.push("users");
expectedViews.push("skills", "plugins");
if (role === "admin") expectedViews.push("promotions");
expect(Array.from(nav.querySelectorAll("a"), (link) => link.getAttribute("href"))).toEqual(
expectedViews.map((view) => `/management?view=${view}`),
);
expect(
Array.from(
nav.querySelectorAll(".management-sidebar-section-title"),
(group) => group.textContent,
),
).toEqual(["Review", "Queues", "Staff tools"]);
});

it.each([undefined, 0, 2])("keeps queue badge visibility for count %j", (count) => {
const originalQuery = useQueryMock.getMockImplementation();
useQueryMock.mockImplementation((query, args) => {
if (args === "skip") return undefined;
const name = getFunctionName(query);
if (name === "publisherAbuse:listReviewDashboard") {
return count === undefined
? undefined
: makeEmptyPublisherAbuseDashboard({
pendingPotentialBanCandidateItems: Array.from({ length: count }, (_, index) =>
makePublisherAbuseItem({ id: String(index + 1) }),
),
});
}
if (
[
"skills:listReportedSkills",
"skills:listDuplicateCandidates",
"skills:listRecentVersions",
].includes(name)
) {
return count === undefined ? undefined : Array.from({ length: count }, () => ({}));
}
return originalQuery?.(query, args);
});
render(<Management />);
const nav = screen.getByRole("navigation", { name: "Management sections" });
for (const view of ["abuse", "reports", "duplicates", "recent"]) {
expect(nav.querySelector(`a[href="/management?view=${view}"] small`)?.textContent).toBe(
count ? String(count) : undefined,
);
}
});

it("links admins to Template download analytics", () => {
render(<Management />);
expect(screen.getByRole("link", { name: "Template downloads" }).getAttribute("href")).toBe(
Expand Down
35 changes: 19 additions & 16 deletions src/routes/-management/managementShared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,25 @@ export type PublisherAbuseTab =
| "all_pending"
| "resolved"
| "signals";
export type ManagementView =
| "downloads"
| "search-insights"
| "overview"
| "abuse"
| "reports"
| "users"
| "publishers"
| "skills"
| "plugins"
| "promotions"
| "duplicates"
| "recent"
| "audit"
| "system"
| "settings";
export const MANAGEMENT_VIEW_LABELS = {
downloads: "Template downloads",
"search-insights": "Search intelligence",
overview: "Overview",
abuse: "Publisher abuse",
reports: "Content reports",
users: "Users",
publishers: "Publishers",
skills: "Skills",
plugins: "Plugins",
promotions: "Promotions",
duplicates: "Duplicate candidates",
recent: "Recent pushes",
audit: "Audit log",
system: "System",
settings: "Settings",
} as const;

export type ManagementView = keyof typeof MANAGEMENT_VIEW_LABELS;

export type PromotionEntry = FunctionReturnType<typeof api.promotions.listForStaff>["page"][number];
export type PromotionStatus = PromotionEntry["status"];
Expand Down
57 changes: 4 additions & 53 deletions src/routes/management.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
formatManagementUserLabel,
formatMutationError,
formatWholeNumber,
MANAGEMENT_VIEW_LABELS,
SKILL_AUDIT_LOG_LIMIT,
type DuplicateCandidateEntry,
type ManagementOwnerOption,
Expand All @@ -70,23 +71,7 @@ import { SearchInsightsPage } from "./-management/SearchInsightsPage";
import { SkillsPage } from "./-management/SkillsPage";
import { UsersPage } from "./-management/UsersPage";

const MANAGEMENT_VIEWS = new Set<string>([
"downloads",
"search-insights",
"overview",
"abuse",
"reports",
"users",
"publishers",
"skills",
"plugins",
"promotions",
"duplicates",
"recent",
"audit",
"system",
"settings",
]);
const MANAGEMENT_VIEWS = new Set<string>(Object.keys(MANAGEMENT_VIEW_LABELS));

function isManagementView(value: unknown): value is ManagementView {
return typeof value === "string" && MANAGEMENT_VIEWS.has(value);
Expand Down Expand Up @@ -766,7 +751,7 @@ export function Management() {
<div className="management-breadcrumb">
<span>Management</span>
<ChevronRight size={13} aria-hidden="true" />
<strong>{formatManagementViewLabel(activeView)}</strong>
<strong>{MANAGEMENT_VIEW_LABELS[activeView]}</strong>
</div>

{activeView === "downloads" ? (
Expand Down Expand Up @@ -1055,14 +1040,12 @@ function ManagementSidebar({
active={activeView === "abuse"}
badge={queueBadge(abuseCount)}
icon={<AlertTriangle size={15} />}
label="Publisher abuse"
view="abuse"
/>
<ManagementSidebarLink
active={activeView === "reports"}
badge={queueBadge(reportCount)}
icon={<ClipboardList size={15} />}
label="Content reports"
view="reports"
/>
</div>
Expand All @@ -1073,14 +1056,12 @@ function ManagementSidebar({
active={activeView === "duplicates"}
badge={queueBadge(duplicateCount)}
icon={<PackageSearch size={15} />}
label="Duplicate candidates"
view="duplicates"
/>
<ManagementSidebarLink
active={activeView === "recent"}
badge={queueBadge(recentCount)}
icon={<GitBranch size={15} />}
label="Recent pushes"
view="recent"
/>
</div>
Expand All @@ -1090,14 +1071,12 @@ function ManagementSidebar({
<ManagementSidebarLink
active={activeView === "downloads"}
icon={<Download size={15} />}
label="Template downloads"
view="downloads"
/>
) : null}
<ManagementSidebarLink
active={activeView === "search-insights"}
icon={<PackageSearch size={15} />}
label="Search intelligence"
view="search-insights"
/>
<div className="management-sidebar-group">
Expand All @@ -1106,27 +1085,23 @@ function ManagementSidebar({
active={activeView === "users"}
badge={userCount === undefined ? undefined : formatWholeNumber(userCount)}
icon={<UserRound size={15} />}
label="Users"
view="users"
/>
) : null}
<ManagementSidebarLink
active={activeView === "skills"}
icon={<Wrench size={15} />}
label="Skills"
view="skills"
/>
<ManagementSidebarLink
active={activeView === "plugins"}
icon={<Plug size={15} />}
label="Plugins"
view="plugins"
/>
{admin ? (
<ManagementSidebarLink
active={activeView === "promotions"}
icon={<Megaphone size={15} />}
label="Promotions"
view="promotions"
/>
) : null}
Expand All @@ -1140,13 +1115,11 @@ function ManagementSidebarLink({
active,
badge,
icon,
label,
view,
}: {
active: boolean;
badge?: string;
icon: ReactNode;
label: string;
view: ManagementView;
}) {
return (
Expand All @@ -1156,7 +1129,7 @@ function ManagementSidebarLink({
search={{ view, skill: undefined, plugin: undefined }}
>
{icon}
<span>{label}</span>
<span>{MANAGEMENT_VIEW_LABELS[view]}</span>
{badge ? <small>{badge}</small> : null}
</Link>
);
Expand All @@ -1172,28 +1145,6 @@ function resolveManagementView(
return view ?? "abuse";
}

const MANAGEMENT_VIEW_LABELS: Record<ManagementView, string> = {
downloads: "Template downloads",
"search-insights": "Search intelligence",
overview: "Overview",
abuse: "Publisher abuse",
reports: "Content reports",
users: "Users",
publishers: "Publishers",
skills: "Skills",
plugins: "Plugins",
promotions: "Promotions",
duplicates: "Duplicate candidates",
recent: "Recent pushes",
audit: "Audit log",
system: "System",
settings: "Settings",
};

function formatManagementViewLabel(view: ManagementView) {
return MANAGEMENT_VIEW_LABELS[view];
}

/** Queue badges only carry signal when there is a backlog; hide 0 and loading. */
function queueBadge(count: number | undefined) {
return count ? formatWholeNumber(count) : undefined;
Expand Down
Loading