feat(admin): reorganize housekeeping and strengthen shared workflows

This commit is contained in:
Simo committed 2026-09-06 17:17:30 +02:00
1 parent 35f66d879f
commit a070004e7b
35 files changed
+1667 -462

No files matched your search

+40 -41
View File
@@ -1,4 +1,5 @@
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import Link from "@/components/link";
import { ErrorStore } from "@/lib/error-monitor";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
@@ -11,6 +12,7 @@ export default async function CmsErrorsPage({
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"]>>;
@@ -19,14 +21,15 @@ export default async function CmsErrorsPage({
} catch {
return (
<div className="admin-card" role="alert">
Error storage could not be read. Check the CMS storage volume and
permissions.
{t("storageError")}
</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>();
@@ -43,62 +46,62 @@ export default async function CmsErrorsPage({
),
);
const pageHref = (next: number) =>
`?${new URLSearchParams({ q: params.q ?? "", source: params.source ?? "", page: String(next) })}`;
`?${new URLSearchParams({ q: params.q ?? "", source: params.source ?? "", status: params.status ?? "", page: String(next) })}`;
return (
<div className="space-y-5">
<div>
<h1 className="text-2xl font-semibold">CMS error center</h1>
<p className="text-muted-foreground">
Server and browser errors from the last 7 days. Browser reports are
unverified client observations.
</p>
<h1 className="text-2xl font-semibold">{t("title")}</h1>
<p className="text-muted-foreground">{t("subtitle")}</p>
</div>
<div className="flex flex-wrap gap-3">
<Link href="/admin/devops" className="btn btn-outline">
DevOps
</Link>
<Link href="/admin/devops/errors" className="btn btn-outline">
Emulator errors
{t("emulator")}
</Link>
<Link href="/admin/devops/cms-errors" className="btn btn-outline">
Refresh / clear filters
{t("refresh")}
</Link>
</div>
<form className="admin-card flex flex-wrap gap-3">
<input
aria-label="Search errors"
aria-label={t("search")}
name="q"
defaultValue={params.q}
placeholder="Reference, digest, message, route or release"
placeholder={t("searchHint")}
className="input min-w-0 flex-1"
/>
<select
name="source"
aria-label="Error source"
aria-label={t("source")}
defaultValue={params.source ?? ""}
className="input"
>
<option value="">All sources</option>
<option value="">{t("allSources")}</option>
<option value="server">Server</option>
<option value="browser">Browser</option>
</select>
<select
name="status"
aria-label={t("status")}
defaultValue={params.status ?? ""}
className="input"
>
<option value="">{t("allStatuses")}</option>
<option value="open">{t("open")}</option>
<option value="resolved">{t("resolved")}</option>
</select>
<button type="submit" className="btn btn-primary">
Search
{t("search")}
</button>
</form>
<p className="text-sm text-muted-foreground">
{filtered.length} occurrences · {groups.size} groups.{" "}
{result.truncated
? "Showing the latest 1,000 events. Narrowing filters searches this retained window."
: ""}{" "}
Storage is limited to 10 MB per day; excess events remain in server logs
where available.
{t("counts", { count: filtered.length, groups: groups.size })}{" "}
{result.truncated ? t("truncated") : ""} {t("retention")}
</p>
{groups.size === 0 ? (
<div className="admin-card">
No captured errors match these filters. Monitoring starts with this
deployment; older console logs are not imported.
</div>
<div className="admin-card">{t("empty")}</div>
) : null}
{[...groups.entries()]
.slice((page - 1) * 25, page * 25)
@@ -108,25 +111,24 @@ export default async function CmsErrorsPage({
<details key={fingerprint} className="admin-card overflow-hidden">
<summary className="cursor-pointer">
<span className="text-xs text-muted-foreground">
{r.resolved ? "Resolved" : "Open"} · {r.source} ·{" "}
{events.length} occurrences · {r.at}
{t(r.resolved ? "resolved" : "open")} · {r.source} ·{" "}
{t("occurrences", { count: events.length })} · {r.at}
</span>
<p className="font-semibold break-words">{r.event}</p>
<p className="text-sm break-words">{r.message}</p>
</summary>
<div className="mt-4 space-y-3 text-sm">
<p>
Reference: <code className="break-all">{r.id}</code>
{t("reference")}: <code className="break-all">{r.id}</code>
</p>
<p>
Release: <code className="break-all">{r.release}</code>
{t("release")}: <code className="break-all">{r.release}</code>
</p>
<pre className="whitespace-pre-wrap break-all rounded bg-muted p-3">
{JSON.stringify(r.context, null, 2)}
</pre>
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-3">
{r.stack ||
"No stack supplied. Use the reference or digest to correlate server logs."}
{r.stack || t("noStack")}
</pre>
{!r.resolved &&
canAccess(permissions, PERMS.DEVOPS_EDIT, session.user.rank) ? (
@@ -137,16 +139,16 @@ export default async function CmsErrorsPage({
value={r.fingerprint}
/>
<button type="submit" className="btn btn-outline">
Mark resolved
{t("resolve")}
</button>
<p className="text-muted-foreground text-xs">
A new occurrence reopens the group automatically.
{t("reopenHint")}
</p>
</form>
) : null}
<details>
<summary className="cursor-pointer">
Occurrence references
{t("references")}
</summary>
<ul>
{events.map((e) => (
@@ -156,23 +158,20 @@ export default async function CmsErrorsPage({
))}
</ul>
</details>
<p className="text-muted-foreground">
Browser stack traces may reference compiled chunks. This view
does not infer a root cause or include request bodies.
</p>
<p className="text-muted-foreground">{t("stackHint")}</p>
</div>
</details>
);
})}
<nav aria-label="Error pages" className="flex gap-3">
<nav aria-label={t("pages")} className="flex gap-3">
{page > 1 ? (
<Link href={pageHref(page - 1)} className="btn btn-outline">
Previous
{t("previous")}
</Link>
) : null}
{page * 25 < groups.size ? (
<Link href={pageHref(page + 1)} className="btn btn-outline">
Next
{t("next")}
</Link>
) : null}
</nav>
+1 -1
View File
@@ -57,7 +57,7 @@ export default async function DevOpsPage() {
return (
<div className="space-y-6">
<a href="/admin/devops/cms-errors" className="btn btn-outline">
CMS error center
{t("cmsErrors")}
</a>
{/* Status cards */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
+6 -28
View File
@@ -11,14 +11,9 @@ import { LanguageSwitcher } from "@/components/language-switcher";
import Link from "@/components/link";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { requireStaff } from "@/lib/admin/guard";
import { collectNavPermissionSlugs } from "@/lib/admin-nav";
import {
ADMIN_NAV_CONFIG_KEY,
parseAdminNavConfig,
} from "@/lib/admin-nav-config";
import { loadAdminNavigation } from "@/lib/admin/navigation";
import { db, User } from "@/lib/db";
import { readCsrfCookieToken } from "@/lib/foundation/security";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { siteSettings } from "@/lib/services/site-settings";
// Request-time auth, existing CSRF cookie, and optional 2FA gate cannot be
@@ -31,6 +26,7 @@ export default async function AdminLayout({
children: ReactNode;
}) {
const staff = await requireStaff();
const navigation = await loadAdminNavigation();
const csrfToken = await readCsrfCookieToken();
if (await siteSettings.getBool("force_staff_2fa", false)) {
const u = await db
@@ -52,7 +48,7 @@ export default async function AdminLayout({
className="flex flex-col min-w-0 p-5 lg:p-6 min-h-full"
style={{ backgroundColor: "var(--admin-canvas)" }}
>
<AdminTopbar staff={staff} />
<AdminTopbar staff={staff} navigation={navigation} />
<section className="admin-page flex-1">
<AdminHubChrome>{children}</AdminHubChrome>
</section>
@@ -69,27 +65,8 @@ async function Sidebar({
}) {
const t = await getTranslations("pages.admin.nav");
const initial = staff.username.charAt(0).toUpperCase();
const { permissions } = await getAdminContext();
const isSuperAdmin = permissions.isSuperAdmin;
const hasDashboard = canAccess(
permissions,
PERMS.ADMIN_DASHBOARD,
staff.rank,
);
// Super-admins see everything. Everyone else sees items their ACL grants.
// If they can open the admin panel but ACL is incomplete (common after HK→ACL
// migration gaps), still show *.view nav entries so categories do not vanish.
const allowedPermissions = isSuperAdmin
? []
: collectNavPermissionSlugs().filter((slug) => {
if (canAccess(permissions, slug, staff.rank)) return true;
if (!hasDashboard) return false;
return slug.endsWith(".view") || slug === PERMS.ADMIN_DASHBOARD;
});
const navConfig = parseAdminNavConfig(
await siteSettings.get(ADMIN_NAV_CONFIG_KEY, ""),
);
const { allowedPermissions, isSuperAdmin, navConfig } =
await loadAdminNavigation();
return (
<aside
@@ -118,6 +95,7 @@ async function Sidebar({
</div>
<AdminSidebarNav
userId={staff.id}
allowedPermissions={allowedPermissions}
isSuperAdmin={isSuperAdmin}
navConfig={navConfig}
+2
View File
@@ -8,6 +8,7 @@ import {
Users,
} from "lucide-react";
import { getTranslations } from "next-intl/server";
import { AdminWorkQueue } from "@/components/admin/admin-work-queue";
import { StatusCard } from "@/components/admin/dashboard";
import Link from "@/components/link";
import { unixNow } from "@/lib/bans";
@@ -126,6 +127,7 @@ export default async function AdminDashboard() {
/>
</div>
<AdminWorkQueue />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<section className="admin-card p-5">
<h2 className="text-sm font-bold text-[var(--admin-text)] mb-4 admin-section-title">
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useRef, useState } from "react";
import { useVisiblePolling } from "@/hooks/use-visible-polling";
import { adminFetch } from "@/lib/admin-fetch";
import { CatalogGitConfiguration } from "./catalog-git-configuration";
@@ -25,7 +26,10 @@ export function CatalogExportClient({
const [status, setStatus] = useState<ExportStatus | null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const refreshing = useRef(false);
const refresh = useCallback(async () => {
if (refreshing.current) return;
refreshing.current = true;
try {
const response = await adminFetch("/api/admin/catalog-export", {
cache: "no-store",
@@ -35,15 +39,11 @@ export function CatalogExportClient({
setError("");
} catch {
setError("Unable to load export status");
} finally {
refreshing.current = false;
}
}, []);
useEffect(() => {
void refresh();
const timer = setInterval(() => {
void refresh();
}, 15_000);
return () => clearInterval(timer);
}, [refresh]);
useVisiblePolling(refresh, 15000);
async function retry() {
setBusy(true);
try {
+6 -4
View File
@@ -27,8 +27,10 @@ export default async function UserShowPage({
const t = await getTranslations("pages.admin.users.detail");
const canEdit = canAccess(permissions, PERMS.USERS_EDIT, session.user.rank);
const data = await loadUserById(id);
const sanctions = await loadUserSanctions(data.user.id);
const watched = await getWatchedUserIds(session.user.id);
const [sanctions, watched] = await Promise.all([
loadUserSanctions(data.user.id),
getWatchedUserIds(session.user.id),
]);
return (
<div className="space-y-6">
@@ -54,7 +56,7 @@ export default async function UserShowPage({
}
>
<Tabs defaultValue="info" className="space-y-4 min-w-0">
<TabsList>
<TabsList className="h-auto flex-wrap justify-start">
<TabsTrigger value="info">{t("tabInfo")}</TabsTrigger>
<TabsTrigger value="badges">
{t("tabBadges", { count: data.user.badges.length })}
@@ -75,7 +77,7 @@ export default async function UserShowPage({
<TabsContent value="badges">
<div className="rounded-lg border bg-card p-4">
<h3 className="text-sm font-semibold mb-3">
Badges ({data.user.badges.length})
{t("tabBadges", { count: data.user.badges.length })}
</h3>
<UserBadgesReadonly badges={data.user.badges} />
</div>
+115 -86
View File
@@ -1,5 +1,6 @@
import { eq, like, or } from "drizzle-orm";
import { NextResponse } from "next/server";
import { ADMIN_NAV_GROUPS, navItemIsAllowed } from "@/lib/admin-nav";
import { apiOk } from "@/lib/api";
import { withAdmin } from "@/lib/api-handler";
import {
@@ -11,7 +12,7 @@ import {
WebsiteRareValues,
WebsiteShopArticles,
} from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import { canAccess, PERMS } from "@/lib/permissions";
import { rateLimit } from "@/lib/rate-limit";
export type AdminSearchResult = {
@@ -53,102 +54,130 @@ export const GET = withAdmin(
return apiOk({ results: [] });
}
const canSearch = (href: string) => {
const item = ADMIN_NAV_GROUPS.flatMap((group) => group.items).find(
(item) => item.href === href,
);
return (
!!item &&
navItemIsAllowed(item, {
isSuperAdmin: context.permissions.isSuperAdmin,
has: (slug) =>
canAccess(context.permissions, slug, context.session.user.rank),
})
);
};
const pattern = `%${escapeLike(q)}%`;
const idExact = Number.parseInt(q, 10);
const hasId = Number.isFinite(idExact) && String(idExact) === q;
const [users, articles, rooms, guilds, shopArticles, rareValues] =
await Promise.all([
db
.select({
id: User.id,
title: User.username,
subtitle: User.mail,
})
.from(User)
.where(
or(
like(User.username, pattern),
like(User.mail, pattern),
...(hasId ? [eq(User.id, idExact)] : []),
),
)
.limit(PER_TYPE),
canSearch("/admin/users")
? db
.select({
id: User.id,
title: User.username,
subtitle: User.mail,
})
.from(User)
.where(
or(
like(User.username, pattern),
like(User.mail, pattern),
...(hasId ? [eq(User.id, idExact)] : []),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
db
.select({
id: WebsiteArticles.id,
title: WebsiteArticles.title,
subtitle: WebsiteArticles.slug,
})
.from(WebsiteArticles)
.where(
or(
like(WebsiteArticles.title, pattern),
like(WebsiteArticles.slug, pattern),
),
)
.limit(PER_TYPE),
canSearch("/admin/articles")
? db
.select({
id: WebsiteArticles.id,
title: WebsiteArticles.title,
subtitle: WebsiteArticles.slug,
})
.from(WebsiteArticles)
.where(
or(
like(WebsiteArticles.title, pattern),
like(WebsiteArticles.slug, pattern),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
db
.select({
id: Rooms.id,
title: Rooms.name,
subtitle: Rooms.ownerName,
})
.from(Rooms)
.where(
or(
like(Rooms.name, pattern),
...(hasId ? [eq(Rooms.id, idExact)] : []),
),
)
.limit(PER_TYPE),
canSearch("/admin/rooms")
? db
.select({
id: Rooms.id,
title: Rooms.name,
subtitle: Rooms.ownerName,
})
.from(Rooms)
.where(
or(
like(Rooms.name, pattern),
...(hasId ? [eq(Rooms.id, idExact)] : []),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
db
.select({
id: Guilds.id,
title: Guilds.name,
subtitle: Guilds.description,
})
.from(Guilds)
.where(
or(
like(Guilds.name, pattern),
...(hasId ? [eq(Guilds.id, idExact)] : []),
),
)
.limit(PER_TYPE),
canSearch("/admin/guilds")
? db
.select({
id: Guilds.id,
title: Guilds.name,
subtitle: Guilds.description,
})
.from(Guilds)
.where(
or(
like(Guilds.name, pattern),
...(hasId ? [eq(Guilds.id, idExact)] : []),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
db
.select({
id: WebsiteShopArticles.id,
title: WebsiteShopArticles.name,
subtitle: WebsiteShopArticles.info,
})
.from(WebsiteShopArticles)
.where(
or(
like(WebsiteShopArticles.name, pattern),
...(hasId ? [eq(WebsiteShopArticles.id, BigInt(idExact))] : []),
),
)
.limit(PER_TYPE),
canSearch("/admin/shop")
? db
.select({
id: WebsiteShopArticles.id,
title: WebsiteShopArticles.name,
subtitle: WebsiteShopArticles.info,
})
.from(WebsiteShopArticles)
.where(
or(
like(WebsiteShopArticles.name, pattern),
...(hasId
? [eq(WebsiteShopArticles.id, BigInt(idExact))]
: []),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
db
.select({
id: WebsiteRareValues.id,
title: WebsiteRareValues.name,
subtitle: WebsiteRareValues.itemId,
})
.from(WebsiteRareValues)
.where(
or(
like(WebsiteRareValues.name, pattern),
...(hasId ? [eq(WebsiteRareValues.itemId, idExact)] : []),
),
)
.limit(PER_TYPE),
canSearch("/admin/rare-values")
? db
.select({
id: WebsiteRareValues.id,
title: WebsiteRareValues.name,
subtitle: WebsiteRareValues.itemId,
})
.from(WebsiteRareValues)
.where(
or(
like(WebsiteRareValues.name, pattern),
...(hasId ? [eq(WebsiteRareValues.itemId, idExact)] : []),
),
)
.limit(PER_TYPE)
: Promise.resolve([]),
]);
const groupMap: Record<
+106
View File
@@ -0,0 +1,106 @@
"use client";
import { Star, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import type { AdminNavItem } from "@/lib/admin-nav";
import { parseFavoritePages } from "@/lib/admin-navigation";
import { AdminNavLink } from "./admin-nav-link";
export function AdminFavorites({
userId,
items,
}: {
userId: number;
items: AdminNavItem[];
}) {
const t = useTranslations("pages.admin.nav");
const key = `admin-favorites:${userId}`;
const [saved, setSaved] = useState<{ key: string; hrefs: string[] }>({
key: "",
hrefs: [],
});
const [storageError, setStorageError] = useState(false);
useEffect(() => {
try {
setSaved({ key, hrefs: parseFavoritePages(localStorage.getItem(key)) });
} catch {
setSaved({ key, hrefs: [] });
}
}, [key]);
const favorites =
saved.key === key
? saved.hrefs.flatMap((href) => items.find((i) => i.href === href) ?? [])
: [];
function save(hrefs: string[]) {
setSaved({ key, hrefs });
try {
localStorage.setItem(key, JSON.stringify(hrefs));
setStorageError(false);
} catch {
setStorageError(true);
}
}
return (
<section
className="mb-3 border-b border-[var(--admin-border)] pb-3"
aria-label={t("favorites")}
>
<h2
style={{ fontSize: ".75rem", margin: 0 }}
className="flex items-center gap-2 px-2 py-2 text-xs font-semibold text-[var(--admin-sidebar-muted-readable)]"
>
<Star size={14} aria-hidden />
{t("favorites")}
</h2>
{favorites.map((item) => (
<div key={item.href} className="flex items-center">
<div className="min-w-0 flex-1">
<AdminNavLink {...item} icon={<item.icon size={16} />}>
{t(item.labelKey)}
</AdminNavLink>
</div>
<button
type="button"
onClick={() =>
save(
favorites
.filter((i) => i.href !== item.href)
.map((i) => i.href),
)
}
aria-label={t("removeFavorite", { name: t(item.labelKey) })}
className="grid h-9 w-9 shrink-0 place-items-center rounded focus-visible:ring-2 focus-visible:ring-[var(--admin-accent)]"
>
<X size={14} />
</button>
</div>
))}
{favorites.length < 6 && (
<select
aria-label={t("addFavorite")}
value=""
disabled={saved.key !== key}
onChange={(event) => {
if (event.target.value)
save([...favorites.map((i) => i.href), event.target.value]);
}}
className="mt-1 h-9 w-full min-w-0 rounded-lg border border-[var(--admin-border)] bg-[var(--admin-sidebar-background)] px-2 text-xs text-[var(--admin-sidebar-text-readable)]"
>
<option value="">{t("addFavorite")}</option>
{items
.filter((item) => !favorites.some((f) => f.href === item.href))
.map((item) => (
<option key={item.href} value={item.href}>
{t(item.labelKey)}
</option>
))}
</select>
)}
{storageError && (
<p role="status" className="px-2 text-xs">
{t("favoriteStorageError")}
</p>
)}
</section>
);
}
@@ -1,6 +1,7 @@
"use client";
import { Menu, X } from "lucide-react";
import { useTranslations } from "next-intl";
import {
createContext,
type ReactNode,
@@ -26,6 +27,7 @@ export function AdminMobileWrapper({
sidebar: ReactNode;
children: ReactNode;
}) {
const t = useTranslations("pages.admin.nav");
const [open, setOpen] = useState(false);
const close = useCallback(() => setOpen(false), []);
const mobile = useMemo(() => ({ close }), [close]);
@@ -57,6 +59,9 @@ export function AdminMobileWrapper({
<button
type="button"
onClick={() => setOpen(!open)}
aria-label={t(open ? "closeSidebar" : "openSidebar")}
aria-expanded={open}
aria-controls="admin-sidebar-panel"
className="flex items-center justify-center w-9 h-9 rounded-lg
focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--admin-accent)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--admin-sidebar-background)]"
style={{ color: "var(--admin-sidebar-text-readable)" }}
@@ -67,7 +72,7 @@ export function AdminMobileWrapper({
className="text-sm font-bold"
style={{ color: "var(--admin-sidebar-text-readable)" }}
>
Admin Panel
{t("housekeeping")}
</span>
</div>
@@ -75,7 +80,7 @@ export function AdminMobileWrapper({
{open && (
<button
type="button"
aria-label="Close menu"
aria-label={t("closeSidebar")}
className="fixed inset-0 z-40 lg:hidden"
onClick={() => setOpen(false)}
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
@@ -84,6 +89,7 @@ export function AdminMobileWrapper({
{/* Sidebar */}
<div
id="admin-sidebar-panel"
className={`fixed inset-y-0 left-0 z-50 flex h-full w-[260px] flex-col overflow-hidden lg:!relative lg:shrink-0 lg:!translate-x-0 ${
open ? "translate-x-0" : "-translate-x-full"
}`}
+16 -25
View File
@@ -11,16 +11,11 @@ import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AdminNavLink } from "@/components/admin/admin-nav-link";
import {
ADMIN_NAV_GROUPS,
type AdminNavItem,
navItemIsAllowed,
} from "@/lib/admin-nav";
import {
type AdminNavConfig,
applyAdminNavConfig,
} from "@/lib/admin-nav-config";
import type { AdminNavItem } from "@/lib/admin-nav";
import type { AdminNavConfig } from "@/lib/admin-nav-config";
import { visibleAdminNavigation } from "@/lib/admin-navigation";
import { cn } from "@/lib/utils";
import { AdminFavorites } from "./admin-favorites";
const STORAGE_KEY = "admin-nav-collapsed";
@@ -67,10 +62,12 @@ function persistCollapsed(next: Record<string, boolean>) {
}
export function AdminSidebarNav({
userId = 0,
allowedPermissions = [],
isSuperAdmin = false,
navConfig = {},
}: {
userId?: number;
/** ACL slugs the staff member holds (ignored when isSuperAdmin). */
allowedPermissions?: string[];
isSuperAdmin?: boolean;
@@ -83,24 +80,12 @@ export function AdminSidebarNav({
const [hydrated, setHydrated] = useState(false);
const [query, setQuery] = useState("");
const allowed = useMemo(
() => new Set(allowedPermissions),
[allowedPermissions],
const groups = useMemo(
() =>
visibleAdminNavigation({ allowedPermissions, isSuperAdmin, navConfig }),
[allowedPermissions, isSuperAdmin, navConfig],
);
const groups = useMemo(() => {
const access = {
isSuperAdmin,
has: (slug: string) => allowed.has(slug),
};
return applyAdminNavConfig(ADMIN_NAV_GROUPS, navConfig)
.map((group) => ({
...group,
items: group.items.filter((item) => navItemIsAllowed(item, access)),
}))
.filter((group) => group.items.length > 0);
}, [allowed, isSuperAdmin, navConfig]);
const search = query.trim().toLocaleLowerCase();
const visibleGroups = useMemo(
() =>
@@ -278,6 +263,12 @@ export function AdminSidebarNav({
</div>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 py-3">
{!search && (
<AdminFavorites
userId={userId}
items={groups.flatMap((group) => group.items)}
/>
)}
{visibleGroups.length === 0 && (
<p
role="status"
+5 -2
View File
@@ -6,11 +6,14 @@ import { SearchDialog } from "@/components/admin/search-dialog";
import { LanguageSwitcher } from "@/components/language-switcher";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { findAdminHub } from "@/lib/admin-nav";
import type { AdminNavigationOptions } from "@/lib/admin-navigation";
export function AdminTopbar({
staff,
navigation,
}: {
staff: { id: number; username: string; rank: number };
navigation: AdminNavigationOptions;
}) {
const tNav = useTranslations("pages.admin.nav");
const tHubs = useTranslations("pages.admin.hubs");
@@ -19,7 +22,7 @@ export function AdminTopbar({
const title = hub ? tHubs(hub.titleKey) : tNav("housekeeping");
return (
<header className="flex items-center justify-between gap-4 bg-[var(--admin-surface)] border border-[var(--admin-border)] rounded-2xl px-5 py-3 mb-5 shadow-card">
<header className="flex items-center justify-between flex-wrap gap-3 bg-[var(--admin-surface)] border border-[var(--admin-border)] rounded-2xl px-5 py-3 mb-5 shadow-card">
<div className="flex items-center gap-3">
<h2 className="m-0 text-base font-extrabold text-[var(--admin-text)]">
{title}
@@ -30,7 +33,7 @@ export function AdminTopbar({
</span>
</div>
<div className="flex items-center gap-3">
<SearchDialog />
<SearchDialog navigation={navigation} />
<div className="flex items-center gap-1.5 lg:hidden">
<LanguageSwitcher variant="admin" />
<ThemeSwitcher variant="admin" />
+104
View File
@@ -0,0 +1,104 @@
import { count, eq, ne } from "drizzle-orm";
import { ArrowRight } from "lucide-react";
import { getTranslations } from "next-intl/server";
import Link from "@/components/link";
import { db, WebsiteHelpCenterTickets, WebsiteTicket } from "@/lib/db";
import { ErrorStore } from "@/lib/error-monitor";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { logServerError } from "@/lib/server-log";
import { ImportJobStore } from "@/lib/services/furni-job-store";
export async function AdminWorkQueue() {
const [{ session, permissions }, t] = await Promise.all([
getAdminContext(),
getTranslations("pages.admin.workQueue"),
]);
const allowed = (permission: string) =>
canAccess(permissions, permission, session.user.rank);
const entries: { key: string; href: string; load: () => Promise<number> }[] =
[];
if (allowed(PERMS.TICKETS_VIEW))
entries.push({
key: "tickets",
href: "/admin/tickets",
load: async () => {
const [cms, help] = await Promise.all([
db
.select({ total: count() })
.from(WebsiteTicket)
.where(ne(WebsiteTicket.status, "closed")),
db
.select({ total: count() })
.from(WebsiteHelpCenterTickets)
.where(eq(WebsiteHelpCenterTickets.open, true)),
]);
return (cms[0]?.total ?? 0) + (help[0]?.total ?? 0);
},
});
if (allowed(PERMS.ASSETS_IMPORT))
entries.push({
key: "imports",
href: "/admin/studio/furni",
load: async () =>
(await new ImportJobStore().list()).filter(
(job) =>
job.userId === Number(session.user.id) &&
(job.state === "interrupted" ||
job.items.some((item) => item.state === "failed")),
).length,
});
if (allowed(PERMS.DEVOPS_VIEW))
entries.push({
key: "errors",
href: "/admin/devops/cms-errors?status=open",
load: async () =>
new Set(
(await new ErrorStore().read()).records
.filter((record) => !record.resolved)
.map((record) => record.fingerprint),
).size,
});
const cards = await Promise.all(
entries.map(async (entry) => {
try {
return { ...entry, count: await entry.load() };
} catch (error) {
logServerError("admin.work_queue_failed", error, { queue: entry.key });
return { ...entry, count: null };
}
}),
);
if (!cards.length) return null;
return (
<section className="mb-6" aria-labelledby="work-queue">
<h2
id="work-queue"
className="mb-3 text-sm font-bold text-[var(--admin-text)]"
>
{t("title")}
</h2>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{cards.map((card) => (
<Link
href={card.href}
key={card.key}
className="admin-card flex items-center gap-4 no-underline focus-visible:ring-2 focus-visible:ring-[var(--admin-accent)]"
>
<span className="text-2xl font-bold tabular-nums text-[var(--admin-text)]">
{card.count ?? "—"}
</span>
<span className="min-w-0 flex-1">
<strong className="block text-sm text-[var(--admin-text)]">
{t(card.key)}
</strong>
<span className="text-xs text-[var(--admin-text-muted)]">
{card.count === null ? t("unavailable") : t(`${card.key}Hint`)}
</span>
</span>
<ArrowRight size={16} aria-hidden />
</Link>
))}
</div>
</section>
);
}
+206 -158
View File
@@ -1,8 +1,8 @@
"use client";
import { useTranslations } from "next-intl";
import { useMemo, useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import { useMemo, useRef, useState, useTransition } from "react";
import { useUnsavedChanges } from "@/hooks/use-unsaved-changes";
import { slugify } from "@/lib/format";
import { ArticlePreview, type ArticlePreviewData } from "./article-preview";
import { MediaPicker } from "./media-picker";
@@ -25,6 +25,17 @@ export function ArticleForm({
};
}) {
const t = useTranslations("pages.admin.articles.form");
const tAction = useTranslations("pages.admin.actions");
const [dirty, setDirty] = useState(false);
const [pending, startTransition] = useTransition();
const [saveError, setSaveError] = useState(false);
const saving = useRef(false);
const editVersion = useRef(0);
function markDirty() {
editVersion.current++;
setDirty(true);
}
useUnsavedChanges(dirty, tAction("leaveUnsaved"));
const [title, setTitle] = useState(defaultValues?.title ?? "");
const [slug, setSlug] = useState(defaultValues?.slug ?? "");
const [slugTouched, setSlugTouched] = useState(Boolean(defaultValues?.slug));
@@ -39,175 +50,212 @@ export function ArticleForm({
return (
<form
ref={formRef}
action={action}
onChangeCapture={markDirty}
onSubmit={(event) => {
event.preventDefault();
if (saving.current) return;
const data = new FormData(event.currentTarget);
const submittedVersion = editVersion.current;
saving.current = true;
setSaveError(false);
startTransition(async () => {
try {
await action(data);
if (editVersion.current === submittedVersion) setDirty(false);
} catch (error) {
if (
error &&
typeof error === "object" &&
"digest" in error &&
String(error.digest).startsWith("NEXT_REDIRECT")
) {
setDirty(false);
throw error;
}
setSaveError(true);
} finally {
saving.current = false;
}
});
}}
className="admin-card"
style={{ display: "grid", gap: "1rem" }}
>
<div className="grid gap-4 md:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("title")}
</span>
<input
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t("titlePlaceholder")}
required
className="input input-bordered mt-1 w-full"
/>
</label>
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("slug")}
</span>
<input
name="slug"
value={slugTouched ? slug : suggestedSlug}
onChange={(e) => {
setSlug(e.target.value);
setSlugTouched(true);
}}
placeholder={t("slugPlaceholder")}
className="input input-bordered mt-1 w-full"
/>
</label>
</div>
<div className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("image")}
</span>
<div className="mt-1 flex gap-2 items-start">
<input
aria-label={t("image")}
name="image"
value={image}
onChange={(e) => {
setImage(e.target.value);
setImageError(false);
}}
placeholder={t("imagePlaceholder")}
className="input input-bordered min-w-0 flex-1"
/>
<MediaPicker
onSelect={(url) => {
setImage(url);
setImageError(false);
}}
current={image}
/>
</div>
{image && !imageError ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={image}
alt="preview"
onError={() => setImageError(true)}
className="mt-2 rounded-lg border border-[var(--admin-text-muted)]/14 object-cover"
style={{ maxHeight: 160 }}
/>
) : null}
{imageError ? (
<p className="muted mt-1" style={{ fontSize: "0.78rem" }}>
Image not found — enter a valid URL or browse.
<fieldset disabled={pending} className="contents">
{saveError && (
<p role="alert" className="text-sm">
{tAction("saveError")}
</p>
) : null}
</div>
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("body")}
</span>
<textarea
name="shortStory"
defaultValue={defaultValues?.shortStory ?? ""}
placeholder={t("bodyPlaceholder")}
rows={2}
className="input input-bordered mt-1 w-full resize-y"
/>
</label>
<div className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("body")}
</span>
<RichText
name="fullStory"
defaultValue={defaultValues?.fullStory ?? ""}
placeholder={t("bodyPlaceholder")}
rows={12}
/>
</div>
<div className="grid gap-4 md:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("status")}
</span>
<select
name="status"
value={status}
onChange={(e) => setStatus(e.target.value)}
className="input input-bordered mt-1 w-full"
>
<option value="draft">{t("statusDraft")}</option>
<option value="scheduled">{t("statusScheduled")}</option>
<option value="published">{t("statusPublished")}</option>
</select>
</label>
{status === "scheduled" ? (
)}
<div className="grid gap-4 md:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("publishAt")}
{t("title")}
</span>
<input
type="datetime-local"
name="publishAt"
defaultValue={defaultValues?.publishAt ?? ""}
name="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t("titlePlaceholder")}
required
className="input input-bordered mt-1 w-full"
/>
</label>
) : null}
</div>
<div className="sticky bottom-0 flex flex-wrap gap-2 border-t border-[var(--admin-border)] bg-[var(--admin-surface)] py-3">
<button
type="button"
className="btn btn-outline"
onClick={() => {
if (!formRef.current) return;
const values = new FormData(formRef.current);
setPreview({
title: String(values.get("title") ?? ""),
image: String(values.get("image") ?? ""),
summary: String(values.get("shortStory") ?? ""),
body: String(values.get("fullStory") ?? ""),
});
}}
>
Preview
</button>
<ArticleSaveButton label={t("save")} />
</div>
<ArticlePreview data={preview} onClose={() => setPreview(null)} />
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("slug")}
</span>
<input
name="slug"
value={slugTouched ? slug : suggestedSlug}
onChange={(e) => {
setSlug(e.target.value);
setSlugTouched(true);
}}
placeholder={t("slugPlaceholder")}
className="input input-bordered mt-1 w-full"
/>
</label>
</div>
<div className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("image")}
</span>
<div className="mt-1 flex gap-2 items-start">
<input
aria-label={t("image")}
name="image"
value={image}
onChange={(e) => {
setImage(e.target.value);
setImageError(false);
}}
placeholder={t("imagePlaceholder")}
className="input input-bordered min-w-0 flex-1"
/>
<MediaPicker
onSelect={(url) => {
setImage(url);
markDirty();
setImageError(false);
}}
current={image}
/>
</div>
{image && !imageError ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={image}
alt="preview"
onError={() => setImageError(true)}
className="mt-2 rounded-lg border border-[var(--admin-text-muted)]/14 object-cover"
style={{ maxHeight: 160 }}
/>
) : null}
{imageError ? (
<p className="muted mt-1" style={{ fontSize: "0.78rem" }}>
Image not found — enter a valid URL or browse.
</p>
) : null}
</div>
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("body")}
</span>
<textarea
name="shortStory"
defaultValue={defaultValues?.shortStory ?? ""}
placeholder={t("bodyPlaceholder")}
rows={2}
className="input input-bordered mt-1 w-full resize-y"
/>
</label>
<div className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("body")}
</span>
<RichText
onChange={markDirty}
name="fullStory"
defaultValue={defaultValues?.fullStory ?? ""}
placeholder={t("bodyPlaceholder")}
rows={12}
/>
</div>
<div className="grid gap-4 md:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("status")}
</span>
<select
name="status"
value={status}
onChange={(e) => setStatus(e.target.value)}
className="input input-bordered mt-1 w-full"
>
<option value="draft">{t("statusDraft")}</option>
<option value="scheduled">{t("statusScheduled")}</option>
<option value="published">{t("statusPublished")}</option>
</select>
</label>
{status === "scheduled" ? (
<label className="block">
<span className="text-xs font-medium text-[var(--admin-text-muted)]">
{t("publishAt")}
</span>
<input
type="datetime-local"
name="publishAt"
defaultValue={defaultValues?.publishAt ?? ""}
required
className="input input-bordered mt-1 w-full"
/>
</label>
) : null}
</div>
<div className="sticky bottom-0 flex flex-wrap gap-2 border-t border-[var(--admin-border)] bg-[var(--admin-surface)] py-3">
<button
type="button"
className="btn btn-outline"
onClick={() => {
if (!formRef.current) return;
const values = new FormData(formRef.current);
setPreview({
title: String(values.get("title") ?? ""),
image: String(values.get("image") ?? ""),
summary: String(values.get("shortStory") ?? ""),
body: String(values.get("fullStory") ?? ""),
});
}}
>
{tAction("preview")}
</button>
<button
type="submit"
className="btn btn-primary"
disabled={pending}
aria-busy={pending}
>
{pending ? tAction("saving") : t("save")}
</button>
{dirty && (
<span
role="status"
className="self-center text-xs text-[var(--admin-text-muted)]"
>
{tAction("unsaved")}
</span>
)}
</div>
<ArticlePreview data={preview} onClose={() => setPreview(null)} />
</fieldset>
</form>
);
}
function ArticleSaveButton({ label }: { label: string }) {
const { pending } = useFormStatus();
return (
<button
type="submit"
className="btn btn-primary"
disabled={pending}
aria-busy={pending}
>
{pending ? "Saving…" : label}
</button>
);
}
+104 -53
View File
@@ -12,8 +12,10 @@ import {
SlidersHorizontal,
X,
} from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useEffect, useRef, useState, useTransition } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
@@ -38,8 +40,8 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useDebounce } from "@/hooks/use-debounce";
import { PER_PAGE_OPTIONS } from "@/lib/admin-helpers";
import { tablePageNumbers } from "@/lib/admin-table-state";
import type { DataTableColumn, PaginatedResult } from "@/types/common";
/**
@@ -68,29 +70,47 @@ interface DataTableProps<T extends { id: number | string }> {
export function DataTable<T extends { id: number | string }>({
data,
columns,
searchPlaceholder = "Search...",
searchPlaceholder,
bulkActions,
onBulkAction,
exportUrl,
presets,
}: DataTableProps<T>) {
const t = useTranslations("pages.admin.table");
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const [selectedIds, setSelectedIds] = useState<Set<number | string>>(
new Set(),
);
const [searchValue, setSearchValue] = useState(
searchParams.get("search") || "",
);
const scope = `${pathname}?${searchParams.toString()}:${data.rows.map((row) => row.id).join(",")}`;
const [selection, setSelection] = useState<{
scope: string;
ids: Set<number | string>;
}>({ scope, ids: new Set() });
const selectedIds =
selection.scope === scope ? selection.ids : new Set<number | string>();
function setSelectedIds(
value:
| Set<number | string>
| ((prev: Set<number | string>) => Set<number | string>),
) {
setSelection({
scope,
ids: typeof value === "function" ? value(selectedIds) : value,
});
}
const urlSearch = searchParams.get("search") ?? "";
const [draft, setDraft] = useState({ base: urlSearch, value: urlSearch });
if (draft.base !== urlSearch) setDraft({ base: urlSearch, value: urlSearch });
const searchValue = draft.base === urlSearch ? draft.value : urlSearch;
const [bulkBusy, setBulkBusy] = useState(false);
const bulkLock = useRef(false);
const [hiddenColumns, setHiddenColumns] = useState<Set<string>>(new Set());
const currentSort = searchParams.get("sort") || "";
const currentOrder = searchParams.get("order") || "desc";
const debouncedSearch = useDebounce(searchValue, 300);
const isFirstRender = useRef(true);
// Collect active filters from URL
const filterColumns = columns.filter(
(col) => col.filterOptions && col.filterOptions.length > 0,
@@ -110,27 +130,31 @@ export function DataTable<T extends { id: number | string }>({
else params.delete(key);
}
startTransition(() => {
router.push(`?${params.toString()}`);
router.push(`?${params.toString()}`, { scroll: false });
});
}
// biome-ignore lint/correctness/useExhaustiveDependencies: explicitly chosen here, see surrounding code
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
updateParams({ search: debouncedSearch, page: "1" });
}, [debouncedSearch]); // eslint-disable-line react-hooks/exhaustive-deps
if (searchValue === urlSearch) return;
const timer = setTimeout(() => {
const params = new URLSearchParams(searchParams.toString());
if (searchValue) params.set("search", searchValue);
else params.delete("search");
params.set("page", "1");
startTransition(() =>
router.replace(`?${params.toString()}`, { scroll: false }),
);
}, 300);
return () => clearTimeout(timer);
}, [searchValue, urlSearch, searchParams, router]);
function handleSearch(value: string) {
setSearchValue(value);
setDraft({ base: urlSearch, value });
}
function handleSort(key: string) {
const newOrder =
currentSort === key && currentOrder === "asc" ? "desc" : "asc";
updateParams({ sort: key, order: newOrder });
updateParams({ sort: key, order: newOrder, page: "1" });
}
function handlePageChange(page: number) {
@@ -173,10 +197,33 @@ export function DataTable<T extends { id: number | string }>({
}
async function handleBulkAction(action: string) {
if (selectedIds.size === 0 || !onBulkAction) return;
await onBulkAction(action, Array.from(selectedIds));
setSelectedIds(new Set());
router.refresh();
if (
selectedIds.size === 0 ||
!onBulkAction ||
bulkLock.current ||
isPending
)
return;
const definition = bulkActions?.find((item) => item.value === action);
if (
definition?.variant === "destructive" &&
!window.confirm(
t("confirmBulk", { action: definition.label, count: selectedIds.size }),
)
)
return;
bulkLock.current = true;
setBulkBusy(true);
try {
await onBulkAction(action, Array.from(selectedIds));
setSelectedIds(new Set());
router.refresh();
} catch {
toast.error(t("bulkError"));
} finally {
bulkLock.current = false;
setBulkBusy(false);
}
}
function getSortIcon(key: string) {
@@ -206,7 +253,7 @@ export function DataTable<T extends { id: number | string }>({
}
return (
<div className="space-y-4">
<div className="space-y-4 min-w-0" aria-busy={isPending || bulkBusy}>
{/* Preset filter chips */}
{presets && presets.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5">
@@ -236,9 +283,11 @@ export function DataTable<T extends { id: number | string }>({
<div className="relative flex-1 min-w-[200px] max-w-sm">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder={searchPlaceholder}
placeholder={searchPlaceholder ?? t("search")}
aria-label={searchPlaceholder ?? t("search")}
value={searchValue}
onChange={(e) => handleSearch(e.target.value)}
style={{ paddingLeft: 36 }}
className="pl-9"
/>
</div>
@@ -249,7 +298,7 @@ export function DataTable<T extends { id: number | string }>({
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<Filter className="h-4 w-4" />
Filters
{t("filters")}
{activeFilterCount > 0 && (
<Badge
variant="secondary"
@@ -263,7 +312,7 @@ export function DataTable<T extends { id: number | string }>({
<PopoverContent className="w-72" align="start">
<div className="space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium">Filters</h4>
<h4 className="text-sm font-medium">{t("filters")}</h4>
{activeFilterCount > 0 && (
<Button
variant="ghost"
@@ -271,7 +320,7 @@ export function DataTable<T extends { id: number | string }>({
className="h-7 px-2 text-xs"
onClick={clearAllFilters}
>
Clear all
{t("clearAll")}
</Button>
)}
</div>
@@ -291,7 +340,7 @@ export function DataTable<T extends { id: number | string }>({
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="__all__">All</SelectItem>
<SelectItem value="__all__">{t("all")}</SelectItem>
{col.filterOptions?.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
@@ -320,6 +369,7 @@ export function DataTable<T extends { id: number | string }>({
{col.label}: {opt?.label || val}
<button
type="button"
aria-label={t("removeFilter", { name: col.label })}
onClick={() => handleFilterChange(col, "__all__")}
className="ml-0.5 rounded-full p-0.5 hover:bg-accent"
>
@@ -336,12 +386,12 @@ export function DataTable<T extends { id: number | string }>({
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<SlidersHorizontal className="h-4 w-4" />
Columns
{t("columns")}
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="start">
<div className="space-y-1">
<h4 className="text-sm font-medium mb-2">Toggle columns</h4>
<h4 className="text-sm font-medium mb-2">{t("columns")}</h4>
{columns.map((col) => (
<div
key={col.key}
@@ -349,6 +399,7 @@ export function DataTable<T extends { id: number | string }>({
>
<Checkbox
checked={!hiddenColumns.has(col.key)}
aria-label={col.label}
onCheckedChange={(checked) => {
setHiddenColumns((prev) => {
const next = new Set(prev);
@@ -375,7 +426,7 @@ export function DataTable<T extends { id: number | string }>({
<SelectContent>
{PER_PAGE_OPTIONS.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("perPage", { count: n })}
</SelectItem>
))}
</SelectContent>
@@ -393,13 +444,14 @@ export function DataTable<T extends { id: number | string }>({
{bulkActions && selectedIds.size > 0 && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
{selectedIds.size} selected
{t("selected", { count: selectedIds.size })}
</span>
{bulkActions.map((action) => (
<Button
key={action.value}
variant={action.variant || "default"}
size="sm"
disabled={bulkBusy || isPending}
onClick={() => handleBulkAction(action.value)}
>
{action.label}
@@ -409,7 +461,7 @@ export function DataTable<T extends { id: number | string }>({
)}
<div className="ml-auto text-sm text-muted-foreground">
{data.total} results
{t("results", { count: data.total })}
</div>
</div>
@@ -425,6 +477,8 @@ export function DataTable<T extends { id: number | string }>({
selectedIds.size === data.rows.length &&
data.rows.length > 0
}
aria-label={t("selectAll")}
disabled={isPending || bulkBusy}
onCheckedChange={toggleSelectAll}
/>
</TableHead>
@@ -459,7 +513,7 @@ export function DataTable<T extends { id: number | string }>({
}
className="h-24 text-center text-muted-foreground"
>
No results found.
{t("empty")}
</TableCell>
</TableRow>
) : (
@@ -473,6 +527,8 @@ export function DataTable<T extends { id: number | string }>({
<TableCell>
<Checkbox
checked={selectedIds.has(row.id)}
aria-label={t("selectRow", { id: String(row.id) })}
disabled={isPending || bulkBusy}
onCheckedChange={() => toggleSelect(row.id)}
/>
</TableCell>
@@ -504,31 +560,25 @@ export function DataTable<T extends { id: number | string }>({
{data.lastPage > 1 && (
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Page {data.page} of {data.lastPage}
{t("pageOf", { page: data.page, last: data.lastPage })}
</p>
<div className="flex items-center gap-1 flex-wrap justify-end">
<Button
variant="outline"
size="icon"
disabled={data.page <= 1}
aria-label={t("previous")}
disabled={data.page <= 1 || isPending}
onClick={() => handlePageChange(data.page - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
{Array.from({ length: Math.min(data.lastPage, 5) }, (_, i) => {
let pageNum: number;
if (data.lastPage <= 7) {
pageNum = i + 1;
} else if (data.page <= 4) {
pageNum = i + 1;
} else if (data.page >= data.lastPage - 3) {
pageNum = data.lastPage - 6 + i;
} else {
pageNum = data.page - 3 + i;
}
{tablePageNumbers(data.page, data.lastPage).map((pageNum) => {
return (
<Button
key={pageNum}
aria-label={t("page", { page: pageNum })}
aria-current={pageNum === data.page ? "page" : undefined}
disabled={isPending}
variant={pageNum === data.page ? "default" : "outline"}
size="icon"
onClick={() => handlePageChange(pageNum)}
@@ -540,7 +590,8 @@ export function DataTable<T extends { id: number | string }>({
<Button
variant="outline"
size="icon"
disabled={data.page >= data.lastPage}
aria-label={t("next")}
disabled={data.page >= data.lastPage || isPending}
onClick={() => handlePageChange(data.page + 1)}
>
<ChevronRight className="h-4 w-4" />
+13 -4
View File
@@ -57,13 +57,17 @@ export function RichText({
defaultValue = "",
placeholder,
rows = 10,
onChange,
}: {
name: string;
defaultValue?: string;
placeholder?: string;
rows?: number;
onChange?: () => void;
}) {
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const changeCallback = useRef(onChange);
changeCallback.current = onChange;
const reactId = useId();
// Stable, querySelector-safe id (useId() contains ':').
const editorId = `rt-${reactId.replace(/[^a-zA-Z0-9_-]/g, "")}`;
@@ -94,11 +98,16 @@ export function RichText({
on: (ev: string, cb: () => void) => void;
getContent: () => string;
}) => {
const sync = () => {
if (textareaRef.current)
textareaRef.current.value = editor.getContent();
const sync = (notify: boolean) => {
const field = textareaRef.current;
if (!field) return;
const html = editor.getContent();
const changed = field.value !== html;
field.value = html;
if (notify && changed) changeCallback.current?.();
};
editor.on("change keyup undo redo SetContent", sync);
editor.on("SetContent", () => sync(false));
editor.on("change keyup undo redo", () => sync(true));
},
})
.then(() => {
+72 -8
View File
@@ -13,8 +13,17 @@ import {
CommandItem,
CommandList,
} from "@/components/ui/command";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import {
Dialog,
DialogContent,
DialogDescription,
DialogTitle,
} from "@/components/ui/dialog";
import { useDebounce } from "@/hooks/use-debounce";
import {
type AdminNavigationOptions,
visibleAdminNavigation,
} from "@/lib/admin-navigation";
type SearchResult = AdminSearchResult;
@@ -23,13 +32,30 @@ type SearchResponse = {
results: SearchResult[];
};
export function SearchDialog() {
export function SearchDialog({
navigation,
}: {
navigation: AdminNavigationOptions;
}) {
const tNav = useTranslations("pages.admin.nav");
const getPages = (queryPlaceholder: string) =>
visibleAdminNavigation(navigation)
.flatMap((group) =>
group.items.map((item) => ({ ...item, group: tNav(group.labelKey) })),
)
.filter((item) =>
[tNav(item.labelKey), item.group, item.href]
.join(" ")
.toLocaleLowerCase()
.includes(queryPlaceholder),
);
const t = useTranslations("pages.admin.search");
const router = useRouter();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [results, setResults] = useState<SearchResult[]>([]);
const [loading, setLoading] = useState(false);
const [failed, setFailed] = useState(false);
const debouncedQuery = useDebounce(query, 250);
const abortRef = useRef<AbortController | null>(null);
@@ -44,6 +70,8 @@ export function SearchDialog() {
const fetchResults = useCallback(async (q: string) => {
abortRef.current?.abort();
setFailed(false);
setResults([]);
if (q.length < 2) {
setResults([]);
setLoading(false);
@@ -56,21 +84,27 @@ export function SearchDialog() {
const res = await fetch(`/api/admin/search?q=${encodeURIComponent(q)}`, {
signal: controller.signal,
});
if (!res.ok) return;
if (!res.ok) throw new Error("Search request failed");
const data: SearchResponse = await res.json();
if (abortRef.current !== controller) return;
if (abortRef.current !== controller || controller.signal.aborted) return;
if (data.ok) setResults(data.results);
else setFailed(true);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") return;
if (abortRef.current === controller) setResults([]);
if (abortRef.current === controller) {
setResults([]);
setFailed(true);
}
} finally {
if (abortRef.current === controller) setLoading(false);
}
}, []);
useEffect(() => {
if (!open) return;
fetchResults(debouncedQuery);
}, [debouncedQuery, fetchResults]);
return () => abortRef.current?.abort();
}, [debouncedQuery, fetchResults, open]);
useEffect(() => {
return () => abortRef.current?.abort();
@@ -94,13 +128,15 @@ export function SearchDialog() {
router.push(url);
}
const grouped = groupResults(results);
const grouped = groupResults(query === debouncedQuery ? results : []);
const pages = getPages(query.trim().toLocaleLowerCase()).slice(0, 8);
return (
<Dialog open={open} onOpenChange={setOpen}>
<button
type="button"
onClick={() => setOpen(true)}
aria-label={t("placeholder")}
className="flex items-center gap-2 rounded-lg border border-[var(--admin-border)] bg-[var(--admin-surface)] px-3 py-1.5 text-xs text-[var(--admin-text-muted)] hover:border-[var(--admin-accent)]/40 hover:text-[var(--admin-text)] transition-colors cursor-pointer"
>
<SearchIcon size={14} />
@@ -110,6 +146,10 @@ export function SearchDialog() {
</kbd>
</button>
<DialogContent className="sm:max-w-lg p-0 gap-0 overflow-hidden">
<DialogTitle className="sr-only">{t("placeholder")}</DialogTitle>
<DialogDescription className="sr-only">
{t("description")}
</DialogDescription>
<Command
className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground"
shouldFilter={false}
@@ -126,7 +166,31 @@ export function SearchDialog() {
…
</div>
) : null}
<CommandEmpty>{t("noResults")}</CommandEmpty>
{!loading && !failed && (
<CommandEmpty>{t("noResults")}</CommandEmpty>
)}
{failed && (
<p role="alert" className="p-4 text-sm">
{t("loadError")}
</p>
)}
{pages.length > 0 && (
<CommandGroup heading={t("pages")}>
{pages.map((item) => (
<CommandItem
key={item.href}
value={item.href}
onSelect={() => handleSelect(item.href)}
>
<item.icon size={16} />
<span>{tNav(item.labelKey)}</span>
<span className="ml-auto text-xs text-muted-foreground">
{item.group}
</span>
</CommandItem>
))}
</CommandGroup>
)}
{Object.entries(grouped).map(([group, items]) => (
<CommandGroup key={group} heading={groupLabels[group] ?? group}>
{items.map((item) => (
+8 -3
View File
@@ -1,4 +1,6 @@
"use client";
import { Search, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
type SearchInputProps = {
@@ -15,21 +17,24 @@ export function SearchInput({
placeholder,
onClear,
}: SearchInputProps) {
const t = useTranslations("pages.admin.table");
return (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder={placeholder}
aria-label={placeholder ?? t("search")}
placeholder={placeholder ?? t("search")}
value={value}
onChange={(e) => onChange(e.target.value)}
className="pl-9 h-9"
style={{ paddingLeft: 36, paddingRight: 40 }}
className="pl-9 pr-10 h-9"
/>
{value && onClear && (
<button
type="button"
onClick={onClear}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
aria-label="Clear search"
aria-label={t("clearSearch")}
>
<X className="h-4 w-4" />
</button>
+35 -15
View File
@@ -1,26 +1,29 @@
"use client";
import { useFormatter, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { retryableJobItems } from "@/lib/furni/import-job-retry";
import type { useFurnitureJobs } from "./use-furniture-jobs";
export function FurnitureJobHistory({
state,
}: {
state: ReturnType<typeof useFurnitureJobs>;
}) {
const t = useTranslations("pages.admin.importHistory");
const format = useFormatter();
return (
<details className="shrink-0 border-b border-[var(--admin-border)] bg-[var(--admin-surface)] px-4 py-2 text-sm">
<summary className="cursor-pointer">
Import history ·{" "}
{
state.jobs.filter(
(j) => j.state === "queued" || j.state === "running",
).length
}{" "}
active
{t("summary", {
count: state.jobs.filter(
(job) => job.state === "queued" || job.state === "running",
).length,
})}
</summary>
<div className="max-h-72 space-y-2 overflow-auto py-2">
{state.error && <p role="alert">{state.error}</p>}
{!state.jobs.length && <p>No background imports yet.</p>}
{!state.jobs.length && <p>{t("empty")}</p>}
{state.jobs.map((job) => {
const retryItems = retryableJobItems(job);
const done = job.items.filter((i) => i.state === "done"),
failed = job.items.filter((i) => i.state === "failed");
return (
@@ -29,14 +32,27 @@ export function FurnitureJobHistory({
className="rounded border border-[var(--admin-border)] p-2"
>
<summary className="cursor-pointer">
{new Date(job.createdAt).toLocaleString()} · {job.state} ·{" "}
{done.length}/{job.items.length} imported · {failed.length}{" "}
failed
{format.dateTime(new Date(job.createdAt), {
dateStyle: "short",
timeStyle: "short",
})}{" "}
· {t(job.state)} ·{" "}
{t("result", {
done: done.length,
total: job.items.length,
failed: failed.length,
})}
</summary>
<progress
className="mt-2 h-2 w-full"
value={done.length + failed.length}
max={Math.max(1, job.items.length)}
aria-label={t("progress")}
/>
<ul className="space-y-1 py-2">
{job.items.map((item) => (
<li key={item.classname}>
<strong>{item.classname}</strong> · {item.state}
<strong>{item.classname}</strong> · {t(item.state)}
{item.itemId ? ` · ID ${item.itemId}` : ""}
{item.error && (
<p className="text-[var(--admin-warning)]">
@@ -54,12 +70,12 @@ export function FurnitureJobHistory({
</li>
))}
</ul>
{failed.length > 0 && job.state !== "running" && (
{retryItems.length > 0 && (
<Button
variant="outline"
disabled={state.busy}
onClick={() =>
void state.submit(failed, {
void state.submit(retryItems, {
sourceId: job.sourceId,
mode: job.mode,
translate: job.translate,
@@ -67,7 +83,11 @@ export function FurnitureJobHistory({
})
}
>
Retry failed items only
{t(
job.state === "interrupted"
? "retryUnfinished"
: "retryFailed",
)}
</Button>
)}
</details>
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";
import { useVisiblePolling } from "@/hooks/use-visible-polling";
import { adminFetch } from "@/lib/admin-fetch";
import type { ImportJob, ImportJobItem } from "@/lib/furni/import-job";
export function useFurnitureJobs(onComplete: () => void) {
@@ -12,7 +13,10 @@ export function useFurnitureJobs(onComplete: () => void) {
callback.current = onComplete;
const request = useRef<{ payload: string; id: string } | null>(null);
const submitting = useRef(false);
const refreshing = useRef(false);
const refresh = useCallback(async () => {
if (refreshing.current) return;
refreshing.current = true;
try {
const response = await adminFetch("/api/admin/studio/import-jobs");
const data = await response.json();
@@ -36,13 +40,11 @@ export function useFurnitureJobs(onComplete: () => void) {
setError(
error instanceof Error ? error.message : "Cannot load import history",
);
} finally {
refreshing.current = false;
}
}, []);
useEffect(() => {
void refresh();
const timer = setInterval(() => void refresh(), 5000);
return () => clearInterval(timer);
}, [refresh]);
useVisiblePolling(refresh, 5000);
const submit = async (
items: ImportJobItem[],
options: {
+20 -5
View File
@@ -1,7 +1,8 @@
"use client";
import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { useTranslations } from "next-intl";
import { useRef, useState, useTransition } from "react";
import { toast } from "sonner";
import type { ActionResult } from "@/lib/safe-action-shared";
@@ -35,13 +36,19 @@ interface RunOptions {
* run(() => deleteNews(id), { redirectTo: '/admin/news' })
*/
export function useServerAction(options: UseServerActionOptions = {}) {
const t = useTranslations("pages.admin.actions");
const locked = useRef(false);
const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>({});
const [isPending, startTransition] = useTransition();
const router = useRouter();
function run(action: () => Promise<unknown>, opts: RunOptions = {}) {
if (locked.current) return;
locked.current = true;
setFieldErrors({});
const {
successMessage = "Saved successfully.",
errorMessage = "An error occurred.",
successMessage = t("saved"),
errorMessage = t("error"),
redirectTo,
onSuccess,
onError,
@@ -61,16 +68,24 @@ export function useServerAction(options: UseServerActionOptions = {}) {
else router.refresh();
}
} else {
toast.error(result.error || errorMessage);
setFieldErrors(result.fieldErrors ?? {});
toast.error(result.error || errorMessage, {
description:
Object.values(result.fieldErrors ?? {})
.flat()
.join(" · ") || undefined,
});
onError?.();
}
} catch (err) {
console.error("[useServerAction] Unexpected error:", err);
toast.error(errorMessage);
onError?.();
} finally {
locked.current = false;
}
});
}
return { run, isPending };
return { run, isPending, fieldErrors };
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { useEffect } from "react";
/** Protect browser close/reload and same-tab link navigation while editing. */
export function useUnsavedChanges(dirty: boolean, message: string) {
useEffect(() => {
if (!dirty) return;
function beforeUnload(event: BeforeUnloadEvent) {
event.preventDefault();
event.returnValue = "";
}
function click(event: MouseEvent) {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey
)
return;
const link =
event.target instanceof Element
? event.target.closest("a[href]")
: null;
if (
!(link instanceof HTMLAnchorElement) ||
link.hasAttribute("download") ||
(link.target && link.target !== "_self")
)
return;
const target = new URL(link.href, location.href);
if (
target.origin === location.origin &&
target.pathname === location.pathname &&
target.search === location.search
)
return;
if (!window.confirm(message)) {
event.preventDefault();
event.stopPropagation();
}
}
window.addEventListener("beforeunload", beforeUnload);
document.addEventListener("click", click, true);
return () => {
window.removeEventListener("beforeunload", beforeUnload);
document.removeEventListener("click", click, true);
};
}, [dirty, message]);
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useEffect, useRef } from "react";
/** Refresh after the prior request settles; pause while the tab is hidden. */
export function useVisiblePolling(
refresh: () => Promise<unknown>,
delay: number,
) {
const callback = useRef(refresh);
callback.current = refresh;
useEffect(() => {
let stopped = false,
running = false;
let timer: ReturnType<typeof setTimeout> | undefined;
async function tick() {
if (stopped || running) return;
clearTimeout(timer);
if (document.visibilityState === "hidden") return;
running = true;
try {
await callback.current();
} finally {
running = false;
if (!stopped) timer = setTimeout(tick, delay);
}
}
function visibility() {
if (document.visibilityState === "visible") void tick();
else clearTimeout(timer);
}
void tick();
document.addEventListener("visibilitychange", visibility);
return () => {
stopped = true;
clearTimeout(timer);
document.removeEventListener("visibilitychange", visibility);
};
}, [delay]);
}
+49
View File
@@ -0,0 +1,49 @@
import { createTranslator } from "next-intl";
import { expect, it } from "vitest";
import { ADMIN_NAV_GROUPS } from "@/lib/admin-nav";
import { visibleAdminNavigation } from "@/lib/admin-navigation";
import en from "@/messages/en.json";
import itMessages from "@/messages/it.json";
it.each([
["en", en],
["it", itMessages],
] as const)(
"renders housekeeping navigation and shared controls in %s",
(locale, messages) => {
const errors: unknown[] = [];
const t = createTranslator({
locale,
messages: messages as unknown as Record<string, string>,
onError: (error) => errors.push(error),
});
const translate = t as unknown as (
key: string,
values?: Record<string, string | number>,
) => string;
const keys = new Set([
...ADMIN_NAV_GROUPS.flatMap((g) => [
g.labelKey,
...g.items.map((i) => i.labelKey),
]),
...visibleAdminNavigation({
allowedPermissions: [],
isSuperAdmin: true,
navConfig: {},
}).map((g) => g.labelKey),
]);
for (const key of keys) translate(`pages.admin.nav.${key}`);
for (const area of ["actions", "table", "cmsErrors", "workQueue"] as const)
for (const key of Object.keys(en.pages.admin[area]))
translate(`pages.admin.${area}.${key}`, {
count: 2,
action: "Save",
page: 2,
last: 7,
id: "1",
name: "Name",
groups: 1,
});
expect(errors).toEqual([]);
},
);
+13 -1
View File
@@ -212,8 +212,13 @@ export const ADMIN_HUBS: AdminHubDefinition[] = [
icon: Server,
prefixes: ["/admin/devops"],
tabs: [
{ href: "/admin/devops", labelKey: "devops", match: ["/admin/devops"] },
{
href: "/admin/devops",
labelKey: "devops",
match: ["/admin/devops"],
},
{ href: "/admin/devops/errors", labelKey: "errors" },
{ href: "/admin/devops/cms-errors", labelKey: "cmsErrors" },
],
},
];
@@ -665,6 +670,13 @@ export const ADMIN_NAV_GROUPS: AdminNavGroup[] = [
icon: Server,
permission: PERMS.DEVOPS_VIEW,
matchPrefixes: ["/admin/devops"],
matchExcludePrefixes: ["/admin/devops/cms-errors"],
},
{
href: "/admin/devops/cms-errors",
labelKey: "cmsErrors",
icon: AlertTriangle,
permission: PERMS.DEVOPS_VIEW,
},
{
href: "/admin/alerts",
+46
View File
@@ -0,0 +1,46 @@
import { expect, it } from "vitest";
import { ADMIN_NAV_GROUPS } from "@/lib/admin-nav";
import { parseFavoritePages, visibleAdminNavigation } from "./admin-navigation";
const access = { isSuperAdmin: true, allowedPermissions: [], navConfig: {} };
it("retains each route and its permission definition once after regrouping", () => {
const original = ADMIN_NAV_GROUPS.flatMap((g) => g.items);
const actual = visibleAdminNavigation(access).flatMap((g) => g.items);
expect(actual).toHaveLength(original.length);
expect(new Set(actual.map((i) => i.href)).size).toBe(actual.length);
for (const item of original) expect(actual).toContain(item);
expect(
visibleAdminNavigation(access)
.find((g) => g.labelKey === "catalogFurniture")
?.items.some((i) => i.href === "/admin/studio"),
).toBe(true);
});
it("respects hidden groups, owner order and ACL in every consumer", () => {
const configured = visibleAdminNavigation({
...access,
navConfig: {
groupOrder: ["monitoring"],
hiddenGroups: ["economy"],
hiddenItems: ["/admin/studio"],
},
});
expect(configured[0].labelKey).toBe("monitoring");
expect(
configured
.flatMap((g) => g.items)
.some((i) => i.href === "/admin/studio" || i.href === "/admin/catalog"),
).toBe(false);
const limited = visibleAdminNavigation({
...access,
isSuperAdmin: false,
}).flatMap((g) => g.items);
expect(limited.every((i) => !i.permission)).toBe(true);
});
it("rejects malformed favorites, external links and duplicates", () => {
expect(parseFavoritePages("{")).toEqual([]);
expect(
parseFavoritePages(
'["/admin/users","https://evil.test","/admin/users",null,"/admin?token=x"]',
),
).toEqual(["/admin/users"]);
});
+180
View File
@@ -0,0 +1,180 @@
import {
Activity,
Cog,
LayoutDashboard,
Newspaper,
Package,
ShoppingCart,
Users,
UsersRound,
} from "lucide-react";
import {
ADMIN_NAV_GROUPS,
type AdminNavGroup,
navItemIsAllowed,
} from "@/lib/admin-nav";
import {
type AdminNavConfig,
applyAdminNavConfig,
} from "@/lib/admin-nav-config";
export type AdminNavigationOptions = {
allowedPermissions: string[];
isSuperAdmin: boolean;
navConfig: AdminNavConfig;
};
const sections = [
{ labelKey: "overview", icon: LayoutDashboard, roots: [""] },
{
labelKey: "peopleSupport",
icon: Users,
roots: [
"users",
"online",
"tickets",
"help-tickets",
"bans",
"ip",
"vpn",
"wordfilter",
"moderation",
"rooms",
],
},
{
labelKey: "catalogFurniture",
icon: Package,
roots: [
"studio",
"catalog",
"import",
"items",
"rare-values",
"badges",
"achievements",
"sounds",
],
},
{
labelKey: "communityContent",
icon: Newspaper,
roots: [
"articles",
"photos",
"events",
"polls",
"guilds",
"media",
"radio",
"ads",
"banners",
"navigation",
"help-questions",
"writeable-boxes",
"tags",
"prefixes",
],
},
{
labelKey: "economy",
icon: ShoppingCart,
roots: [
"shop",
"marketplace",
"transactions",
"vouchers",
"subscriptions",
"calendar",
],
},
{
labelKey: "staffPermissions",
icon: UsersRound,
roots: ["teams", "applications", "permissions"],
},
{
labelKey: "system",
icon: Cog,
roots: [
"settings",
"theme",
"theme-builder",
"maintenance",
"favicon",
"email-templates",
"translations",
"emulator",
"housekeeping",
"commandocentrum",
],
},
{
labelKey: "monitoring",
icon: Activity,
roots: ["logs", "analytics", "devops", "alerts"],
},
];
/** Owner order takes precedence; hidden entries are filtered before regrouping. */
export function visibleAdminNavigation(
options: AdminNavigationOptions,
): AdminNavGroup[] {
const allowed = new Set(options.allowedPermissions);
const groups = applyAdminNavConfig(ADMIN_NAV_GROUPS, options.navConfig)
.map((group) => ({
...group,
items: group.items.filter((item) =>
navItemIsAllowed(item, {
isSuperAdmin: options.isSuperAdmin,
has: (slug) => allowed.has(slug),
}),
),
}))
.filter((group) => group.items.length);
if (
options.navConfig.groupOrder?.length ||
Object.values(options.navConfig.itemOrder ?? {}).some(
(order) => order.length,
)
)
return groups;
const remaining = new Map(
groups.flatMap((group) => group.items).map((item) => [item.href, item]),
);
const organized = sections
.map((section) => {
const items = [...remaining.values()].filter((item) =>
section.roots.includes(item.href.split("/")[2] ?? ""),
);
for (const item of items) remaining.delete(item.href);
return { labelKey: section.labelKey, icon: section.icon, items };
})
.filter((group) => group.items.length);
// New routes remain discoverable even before being assigned to an activity.
if (remaining.size)
organized.push({
labelKey: "tools",
icon: Cog,
items: [...remaining.values()],
});
return organized;
}
export function parseFavoritePages(raw: string | null): string[] {
try {
const value: unknown = JSON.parse(raw ?? "[]");
return Array.isArray(value)
? [
...new Set(
value.filter(
(entry): entry is string =>
typeof entry === "string" &&
/^\/admin(?:\/[^?#]*)?$/.test(entry),
),
),
].slice(0, 6)
: [];
} catch {
return [];
}
}
+89
View File
@@ -0,0 +1,89 @@
import { beforeEach, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
allowed: new Set<string>(),
queried: [] as unknown[],
}));
vi.mock("@/lib/api-handler", () => ({
withAdmin: (_: unknown, handler: Function) => (request: unknown) =>
handler(request, {
session: { user: { id: 1, rank: 7 } },
permissions: { isSuperAdmin: false },
}),
}));
vi.mock("@/lib/rate-limit", () => ({ rateLimit: async () => ({ ok: true }) }));
vi.mock("@/lib/permissions", async () => ({
...(await import("@/lib/permission-slugs")),
canAccess: (_: unknown, slug: string) => state.allowed.has(slug),
}));
vi.mock("@/lib/db", () => {
const tables = Object.fromEntries(
[
"User",
"Rooms",
"Guilds",
"WebsiteArticles",
"WebsiteRareValues",
"WebsiteShopArticles",
].map((name) => [
name,
{
name,
id: `${name}Id`,
username: `${name}Name`,
mail: `${name}Mail`,
slug: `${name}Slug`,
ownerName: `${name}Owner`,
itemId: `${name}Item`,
description: `${name}Description`,
},
]),
);
return {
...tables,
db: {
select() {
let table: unknown;
const query = {
from(value: unknown) {
table = value;
return query;
},
where() {
return query;
},
async limit() {
state.queried.push(table);
return [{ id: 1, title: "Match", subtitle: "Data" }];
},
};
return query;
},
},
};
});
import { GET } from "@/app/api/admin/search/route";
import { PERMS } from "@/lib/permission-slugs";
beforeEach(() => {
state.allowed.clear();
state.queried.length = 0;
});
const request = () =>
({
nextUrl: new URL("https://test.invalid/api/admin/search?q=match"),
}) as Parameters<typeof GET>[0];
it("does not query or expose categories without their view permission", async () => {
const response = await GET(request(), {});
expect((await response.json()).results).toEqual([]);
expect(state.queried).toHaveLength(0);
});
it("searches only the permitted category", async () => {
state.allowed.add(PERMS.NEWS_VIEW);
const response = await GET(request(), {});
const body = await response.json();
expect(body.results).toHaveLength(1);
expect(body.results[0].type).toBe("articles");
expect(state.queried).toHaveLength(1);
});
+17
View File
@@ -0,0 +1,17 @@
import { expect, it } from "vitest";
import { tablePageNumbers } from "./admin-table-state";
it.each([
[1, 1],
[1, 7],
[6, 7],
[7, 7],
[50, 100],
[100, 100],
])("includes the current page %i/%i and stays in bounds", (page, last) => {
const pages = tablePageNumbers(page, last);
expect(pages).toContain(page);
expect(pages.length).toBeLessThanOrEqual(5);
expect(pages.every((p) => p >= 1 && p <= last)).toBe(true);
expect(new Set(pages).size).toBe(pages.length);
});
+6
View File
@@ -0,0 +1,6 @@
/** A centered, bounded window including the current page, also at either end. */
export function tablePageNumbers(page: number, last: number): number[] {
const count = Math.min(5, Math.max(1, last));
const start = Math.max(1, Math.min(page - 2, last - count + 1));
return Array.from({ length: count }, (_, index) => start + index);
}
+32
View File
@@ -0,0 +1,32 @@
import { cache } from "react";
import { collectNavPermissionSlugs } from "@/lib/admin-nav";
import {
ADMIN_NAV_CONFIG_KEY,
parseAdminNavConfig,
} from "@/lib/admin-nav-config";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { siteSettings } from "@/lib/services/site-settings";
export const loadAdminNavigation = cache(async () => {
const [{ session, permissions }, raw] = await Promise.all([
getAdminContext(),
siteSettings.get(ADMIN_NAV_CONFIG_KEY, ""),
]);
const hasDashboard = canAccess(
permissions,
PERMS.ADMIN_DASHBOARD,
session.user.rank,
);
return {
isSuperAdmin: permissions.isSuperAdmin,
allowedPermissions: permissions.isSuperAdmin
? []
: collectNavPermissionSlugs().filter(
(slug) =>
canAccess(permissions, slug, session.user.rank) ||
(hasDashboard &&
(slug.endsWith(".view") || slug === PERMS.ADMIN_DASHBOARD)),
),
navConfig: parseAdminNavConfig(raw),
};
});
+25
View File
@@ -0,0 +1,25 @@
import { expect, it } from "vitest";
import type { ImportJob } from "./import-job";
import { retryableJobItems } from "./import-job-retry";
const job = (state: ImportJob["state"]) =>
({
state,
items: ["done", "failed", "pending", "running"].map((state) => ({
state,
classname: state,
})),
}) as ImportJob;
it("only retries failures after a completed job", () =>
expect(retryableJobItems(job("completed")).map((i) => i.state)).toEqual([
"failed",
]));
it("recovers all unfinished items from an interrupted job", () =>
expect(retryableJobItems(job("interrupted")).map((i) => i.state)).toEqual([
"failed",
"pending",
"running",
]));
it.each(["queued", "running"] as const)("never duplicates a %s job", (state) =>
expect(retryableJobItems(job(state))).toEqual([]),
);
+10
View File
@@ -0,0 +1,10 @@
import type { ImportJob } from "./import-job";
/** Never requeue an active job or furniture already imported successfully. */
export function retryableJobItems(job: ImportJob): ImportJob["items"] {
if (job.state === "running" || job.state === "queued") return [];
return job.items.filter(
(item) =>
item.state === "failed" ||
(job.state === "interrupted" && item.state !== "done"),
);
}
+4 -4
View File
@@ -81,10 +81,10 @@ describe("staff smoke contract", () => {
expect(readFileSync("src/lib/admin-nav.ts", "utf8")).not.toContain(
"/admin/menu",
);
expect(
readFileSync("src/components/admin/admin-sidebar-nav.tsx", "utf8"),
).toContain("applyAdminNavConfig");
expect(readFileSync("src/app/admin/layout.tsx", "utf8")).toContain(
expect(readFileSync("src/lib/admin-navigation.ts", "utf8")).toContain(
"applyAdminNavConfig",
);
expect(readFileSync("src/lib/admin/navigation.ts", "utf8")).toContain(
"ADMIN_NAV_CONFIG_KEY",
);
});
+109 -4
View File
@@ -1048,7 +1048,7 @@
"system": "System",
"hubTools": "Tools",
"hubObservability": "Observability",
"commandocentrum": "Commandocentrum",
"commandocentrum": "Command center",
"emulator": "Emulator",
"alerts": "Alerts",
"logs": "Logs",
@@ -1094,7 +1094,19 @@
"guilds": "Guilds",
"shop": "Shop",
"hint": "Start typing to search across users, articles, rooms, guilds and shop items"
}
},
"peopleSupport": "Users and support",
"catalogFurniture": "Catalog and furniture",
"communityContent": "Community and content",
"staffPermissions": "Staff and access",
"favorites": "Favorites",
"addFavorite": "Add favorite",
"removeFavorite": "Remove {name} from favorites",
"favoriteStorageError": "Favorites are available for this session; browser storage is unavailable.",
"cmsErrors": "CMS errors",
"themeBuilder": "Theme builder",
"openSidebar": "Open menu",
"closeSidebar": "Close menu"
},
"dashboard": {
"title": "Dashboard",
@@ -1252,7 +1264,8 @@
},
"devops": {
"noEmulatorErrors": "No emulator errors found",
"noRecentErrors": "No recent errors"
"noRecentErrors": "No recent errors",
"cmsErrors": "CMS error center"
},
"tags": {
"title": "Tags",
@@ -2790,7 +2803,8 @@
"devops": "DevOps",
"errors": "Errors",
"alerts": "Alerts",
"toolsGroup": "Tools"
"toolsGroup": "Tools",
"cmsErrors": "CMS errors"
},
"events": "Events",
"eventsSubtitle": "Hotel events and event types",
@@ -3284,6 +3298,97 @@
"less": "Less",
"more": "More"
}
},
"search": {
"pages": "Pages and tools",
"description": "Find an admin page or search hotel records.",
"loadError": "Records could not be loaded. You can still open the pages above.",
"placeholder": "Search pages, users, rooms…"
},
"table": {
"search": "Search…",
"clearSearch": "Clear search",
"filters": "Filters",
"clearAll": "Clear all",
"all": "All",
"columns": "Columns",
"perPage": "{count} / page",
"selected": "{count} selected",
"results": "{count} results",
"empty": "No results match your search or filters.",
"selectAll": "Select all rows on this page",
"selectRow": "Select row {id}",
"removeFilter": "Remove filter: {name}",
"previous": "Previous page",
"next": "Next page",
"page": "Page {page}",
"pageOf": "Page {page} of {last}",
"bulkError": "The operation failed. Your selection has been kept; check the result before retrying.",
"confirmBulk": "{action} on {count} selected rows?"
},
"actions": {
"saved": "Saved successfully.",
"error": "The operation could not be completed.",
"saving": "Saving…",
"saveError": "Save failed. Your changes are still here; please try again.",
"unsaved": "Unsaved changes",
"leaveUnsaved": "You have unsaved changes. Leave this page?",
"preview": "Preview"
},
"workQueue": {
"title": "Work to review",
"tickets": "Open tickets",
"ticketsHint": "CMS and help-center queues",
"imports": "Imports to review",
"importsHint": "Your interrupted jobs or jobs with failed items",
"errors": "Open CMS error groups",
"errorsHint": "From the retained diagnostic history",
"unavailable": "Status unavailable — open to inspect"
},
"cmsErrors": {
"title": "CMS error center",
"storageError": "Error storage could not be read. Check the storage volume and permissions.",
"subtitle": "Server and browser errors from the last 7 days. Browser reports are unverified client observations.",
"emulator": "Emulator errors",
"refresh": "Refresh / clear filters",
"search": "Search errors",
"allSources": "All sources",
"empty": "No captured errors match these filters. Older console logs are not imported.",
"resolve": "Mark resolved",
"reopenHint": "A new occurrence reopens the group automatically.",
"references": "Occurrence references",
"stackHint": "Browser stacks may reference compiled chunks. Use the reference to investigate; request bodies are not stored.",
"previous": "Previous",
"next": "Next",
"searchHint": "Reference, digest, message, route or release",
"source": "Error source",
"pages": "Error pages",
"resolved": "Resolved",
"open": "Open",
"occurrences": "{count} occurrences",
"reference": "Reference",
"release": "Release",
"noStack": "No stack supplied. Use the reference or digest to correlate server logs.",
"truncated": "Showing the latest 1,000 events; filters search this retained window.",
"counts": "{count} occurrences · {groups} groups.",
"retention": "Storage is limited to 10 MB per day; excess events remain in server logs where available.",
"status": "Status",
"allStatuses": "All statuses"
},
"importHistory": {
"summary": "Import history · {count} active",
"empty": "No background imports yet.",
"result": "{done}/{total} imported · {failed} failed",
"progress": "Import progress",
"queued": "Queued",
"running": "Running",
"completed": "Completed",
"interrupted": "Interrupted",
"done": "Imported",
"failed": "Failed",
"pending": "Pending",
"retryFailed": "Retry failed items only",
"retryUnfinished": "Retry unfinished items"
}
},
"mod": {
+116 -4
View File
@@ -1052,7 +1052,20 @@
"tools": "Strumenti",
"guilds": "Gruppi",
"itemsBase": "Items base",
"studio": "Studio"
"studio": "Studio",
"peopleSupport": "Utenti e assistenza",
"catalogFurniture": "Catalogo e furni",
"communityContent": "Community e contenuti",
"staffPermissions": "Staff e accessi",
"favorites": "Preferiti",
"addFavorite": "Aggiungi preferito",
"removeFavorite": "Rimuovi {name} dai preferiti",
"favoriteStorageError": "Preferiti disponibili per questa sessione: memoria del browser non disponibile.",
"cmsErrors": "Errori CMS",
"themeBuilder": "Editor del tema",
"catalogMaintenance": "Manutenzione catalogo",
"openSidebar": "Apri menu",
"closeSidebar": "Chiudi menu"
},
"dashboard": {
"title": "Dashboard",
@@ -1103,7 +1116,13 @@
"saving": "Salvataggio…",
"deleteArticle": "Elimina articolo",
"deleteConfirm": "Questa azione è irreversibile. L'articolo verrà rimosso permanentemente.",
"cancel": "Annulla"
"cancel": "Annulla",
"status": "Stato",
"statusDraft": "Bozza",
"statusScheduled": "Programmato",
"statusPublished": "Pubblicato",
"publishAt": "Data di pubblicazione",
"publishedAt": "Pubblicato il"
}
},
"events": {
@@ -1204,7 +1223,8 @@
},
"devops": {
"noEmulatorErrors": "Nessun errore emulator trovato",
"noRecentErrors": "Nessun errore recente"
"noRecentErrors": "Nessun errore recente",
"cmsErrors": "Centro errori CMS"
},
"tags": {
"title": "Tag",
@@ -2965,7 +2985,8 @@
"errors": "Errori",
"alerts": "Alert",
"toolsGroup": "Strumenti",
"ticketInbox": "Inbox"
"ticketInbox": "Inbox",
"cmsErrors": "Errori CMS"
},
"events": "Eventi",
"eventsSubtitle": "Eventi hotel e tipi evento",
@@ -3221,6 +3242,97 @@
"modNavInbox": "Inbox",
"modNavDesk": "Supporto CMS",
"modNavHelp": "Help center"
},
"search": {
"pages": "Pagine e strumenti",
"description": "Trova una pagina di gestione o cerca nei dati dell’hotel.",
"loadError": "Impossibile caricare i risultati. Puoi comunque aprire le pagine elencate.",
"placeholder": "Cerca pagine, utenti, stanze…"
},
"table": {
"search": "Cerca…",
"clearSearch": "Cancella ricerca",
"filters": "Filtri",
"clearAll": "Rimuovi tutti",
"all": "Tutti",
"columns": "Colonne",
"perPage": "{count} / pagina",
"selected": "{count} selezionati",
"results": "{count} risultati",
"empty": "Nessun risultato corrisponde alla ricerca o ai filtri.",
"selectAll": "Seleziona tutte le righe di questa pagina",
"selectRow": "Seleziona riga {id}",
"removeFilter": "Rimuovi filtro: {name}",
"previous": "Pagina precedente",
"next": "Pagina successiva",
"page": "Pagina {page}",
"pageOf": "Pagina {page} di {last}",
"bulkError": "Operazione non riuscita. La selezione è stata mantenuta: verifica il risultato prima di riprovare.",
"confirmBulk": "Eseguire {action} su {count} righe selezionate?"
},
"actions": {
"saved": "Salvato correttamente.",
"error": "Impossibile completare l’operazione.",
"saving": "Salvataggio…",
"saveError": "Salvataggio non riuscito. Le modifiche sono ancora qui: riprova.",
"unsaved": "Modifiche non salvate",
"leaveUnsaved": "Hai modifiche non salvate. Vuoi lasciare la pagina?",
"preview": "Anteprima"
},
"workQueue": {
"title": "Da controllare",
"tickets": "Ticket aperti",
"ticketsHint": "Code del CMS e del centro assistenza",
"imports": "Import da verificare",
"importsHint": "I tuoi processi interrotti o con furni non importati",
"errors": "Gruppi di errori CMS aperti",
"errorsHint": "Nello storico diagnostico conservato",
"unavailable": "Stato non disponibile — apri per verificare"
},
"cmsErrors": {
"title": "Centro errori CMS",
"storageError": "Impossibile leggere gli errori. Verifica volume di archiviazione e permessi.",
"subtitle": "Errori server e browser degli ultimi 7 giorni. Le segnalazioni browser sono osservazioni del client non verificate.",
"emulator": "Errori emulatore",
"refresh": "Aggiorna / azzera filtri",
"search": "Cerca errori",
"allSources": "Tutte le origini",
"empty": "Nessun errore registrato corrisponde ai filtri. I vecchi log della console non vengono importati.",
"resolve": "Segna come risolto",
"reopenHint": "Una nuova occorrenza riapre automaticamente il gruppo.",
"references": "Riferimenti delle occorrenze",
"stackHint": "Gli stack del browser possono riferirsi a file compilati. Usa il riferimento per indagare; i contenuti delle richieste non vengono salvati.",
"previous": "Precedente",
"next": "Successiva",
"searchHint": "Riferimento, digest, messaggio, percorso o versione",
"source": "Origine errore",
"pages": "Pagine errori",
"resolved": "Risolto",
"open": "Aperto",
"occurrences": "{count} occorrenze",
"reference": "Riferimento",
"release": "Versione",
"noStack": "Stack non disponibile. Usa riferimento o digest per cercare nei log del server.",
"truncated": "Sono mostrati gli ultimi 1.000 eventi: i filtri cercano in questa finestra.",
"counts": "{count} occorrenze · {groups} gruppi.",
"retention": "Limite di archiviazione: 10 MB al giorno. Gli eventi eccedenti restano nei log server, dove disponibili.",
"status": "Stato",
"allStatuses": "Tutti gli stati"
},
"importHistory": {
"summary": "Storico importazioni · {count} attive",
"empty": "Nessuna importazione in background.",
"result": "{done}/{total} importati · {failed} falliti",
"progress": "Avanzamento importazione",
"queued": "In coda",
"running": "In corso",
"completed": "Completato",
"interrupted": "Interrotto",
"done": "Importato",
"failed": "Non riuscito",
"pending": "In attesa",
"retryFailed": "Riprova solo i furni falliti",
"retryUnfinished": "Riprendi i furni non completati"
}
},
"radioRequests": {