feat: 常用问题 is edited and published in the admin; content_editor role for the astrologer
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
import ConsultPresetsManagement from "@/components/admin/consult-presets-management";
|
||||
export default function Page() { return <ConsultPresetsManagement />; }
|
||||
@@ -26,7 +26,7 @@ type AdministratorRow = {
|
||||
const mutationSchema = z.object({
|
||||
email: z.string().trim().email().optional(),
|
||||
userId: z.string().uuid().optional(),
|
||||
roleCode: z.enum(["owner", "model_admin", "billing_admin", "operations", "support", "auditor"]),
|
||||
roleCode: z.enum(["owner", "model_admin", "billing_admin", "operations", "support", "auditor", "content_editor"]),
|
||||
}).refine((value) => Boolean(value.email || value.userId), {
|
||||
message: "email_or_user_id_required",
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { refuseContentOnlyAdmin } from "@/lib/admin/auth-boundary";
|
||||
import { z } from "zod";
|
||||
|
||||
import { runCodeRpc } from "@/lib/admin/codes";
|
||||
@@ -30,6 +31,7 @@ export async function PATCH(
|
||||
request,
|
||||
"admin.access",
|
||||
);
|
||||
refuseContentOnlyAdmin(session);
|
||||
const parsedParams = paramsSchema.safeParse(await context.params);
|
||||
const parsedBody = updateCodeSchema.safeParse(
|
||||
await request.json().catch(() => null),
|
||||
@@ -66,6 +68,7 @@ export async function DELETE(
|
||||
request,
|
||||
"admin.access",
|
||||
);
|
||||
refuseContentOnlyAdmin(session);
|
||||
const parsed = paramsSchema.safeParse(await context.params);
|
||||
if (!parsed.success) return invalidQueryResponse();
|
||||
const rows = await runCodeRpc(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { requirePermission } from "@/lib/admin/auth";
|
||||
import { refuseContentOnlyAdmin } from "@/lib/admin/auth-boundary";
|
||||
import {
|
||||
mapCode,
|
||||
runCodeRpc,
|
||||
@@ -64,7 +65,7 @@ function serializedCodeRow(row: CodeRow) {
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requirePermission("admin.access");
|
||||
refuseContentOnlyAdmin(await requirePermission("admin.access"));
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q, status } = parsed.data;
|
||||
@@ -126,6 +127,7 @@ export async function POST(request: Request) {
|
||||
request,
|
||||
"admin.access",
|
||||
);
|
||||
refuseContentOnlyAdmin(session);
|
||||
const parsed = createCodesSchema.safeParse(
|
||||
await request.json().catch(() => null),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { requirePermission } from "@/lib/admin/auth";
|
||||
import { queryAdminRows } from "@/lib/admin/database";
|
||||
import { adminErrorResponse, invalidQueryResponse, requestId, requireAdminMutation } from "@/lib/admin/http";
|
||||
import { builtInPresetLibrary, consultPresetLibrarySchema } from "@/lib/consult-preset-library";
|
||||
import { loadPublishedPresets } from "@/lib/consult-preset-server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const publishSchema = z.object({
|
||||
action: z.literal("publish"),
|
||||
groups: consultPresetLibrarySchema,
|
||||
expectedVersion: z.number().int().min(0),
|
||||
}).strict();
|
||||
|
||||
type Row = { version: number; content: unknown; published_at: Date };
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await requirePermission("admin.access");
|
||||
const rows = await queryAdminRows<Row>(
|
||||
"select version, content, published_at from public.consult_preset_libraries where status='published' limit 1",
|
||||
);
|
||||
const row = rows[0];
|
||||
const stored = row ? consultPresetLibrarySchema.safeParse(row.content) : null;
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
version: row?.version ?? 0,
|
||||
publishedAt: row?.published_at.toISOString() ?? null,
|
||||
// An unpublished or unreadable library is edited from the built-in one.
|
||||
source: stored?.success ? "published" : "built_in",
|
||||
groups: stored?.success ? stored.data : builtInPresetLibrary(),
|
||||
builtIn: builtInPresetLibrary(),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = publishSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!body.success) return invalidQueryResponse(body.error.flatten());
|
||||
const session = await requireAdminMutation(request, "content.presets.write");
|
||||
const rid = requestId(request);
|
||||
const rows = await queryAdminRows<{ version: number }>(
|
||||
"select public.admin_publish_consult_presets($1,$2::jsonb,$3,$4,$5) as version",
|
||||
[session.user.id, JSON.stringify(body.data.groups), body.data.expectedVersion, "admin_console_publish_consult_presets", rid],
|
||||
);
|
||||
await loadPublishedPresets({ fresh: true });
|
||||
return NextResponse.json({ data: { version: rows[0]!.version, requestId: rid } });
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { loadPublishedPresets } from "@/lib/consult-preset-server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/** The 「常用问题」 menu content. Public menu copy, no user data. */
|
||||
export async function GET() {
|
||||
const presets = await loadPublishedPresets();
|
||||
return NextResponse.json(
|
||||
{ source: presets.source, version: presets.version, domains: presets.domains },
|
||||
{ headers: { "Cache-Control": "private, max-age=30" } },
|
||||
);
|
||||
}
|
||||
@@ -126,6 +126,7 @@ export function AdminApp({ children }: { children: ReactNode }) {
|
||||
{ name: "model-releases", list: "/admin/model-releases", meta: { label: "模型发布", icon: <ControlOutlined /> } },
|
||||
{ name: "payments", list: "/admin/payments", meta: { label: "支付配置", icon: <CreditCardOutlined /> } },
|
||||
{ name: "feature-flags", list: "/admin/feature-flags", meta: { label: "功能开关", icon: <ControlOutlined /> } },
|
||||
{ name: "consult-presets", list: "/admin/consult-presets", meta: { label: "常用问题", icon: <MessageOutlined /> } },
|
||||
{ name: "security", list: "/admin/security", meta: { label: "安全验证", icon: <SafetyCertificateOutlined /> } },
|
||||
{ name: "audit-logs", list: "/admin/audit-logs", meta: { label: "审计日志", icon: <AuditOutlined /> } },
|
||||
{ name: "moderation-events", list: "/admin/moderation-events", meta: { label: "内容审核", icon: <AuditOutlined /> } },
|
||||
|
||||
@@ -16,6 +16,7 @@ const roleOptions = [
|
||||
{ value: "operations", label: "Operations" },
|
||||
{ value: "support", label: "Support" },
|
||||
{ value: "auditor", label: "Auditor" },
|
||||
{ value: "content_editor", label: "内容编辑(只能改常用问题)" },
|
||||
] as const;
|
||||
|
||||
type RoleCode = (typeof roleOptions)[number]["value"];
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons";
|
||||
import { useGetIdentity } from "@refinedev/core";
|
||||
import { List } from "@refinedev/antd";
|
||||
import { Alert, App, Button, Card, Form, Input, Space, Tabs, Typography } from "antd";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { adminRequestJson, type AdminIdentity } from "@/lib/admin/providers";
|
||||
import { consultPresetLibrarySchema, PRESET_LIMITS, type ConsultPresetLibraryInput } from "@/lib/consult-preset-library";
|
||||
import { formatAdminDate } from "./resource-table";
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
|
||||
type Group = ConsultPresetLibraryInput[number];
|
||||
type Payload = { data: { version: number; publishedAt: string | null; source: "published" | "built_in"; groups: Group[]; builtIn: Group[] } };
|
||||
|
||||
function firstProblem(groups: Group[]): string | null {
|
||||
const parsed = consultPresetLibrarySchema.safeParse(groups);
|
||||
if (parsed.success) return null;
|
||||
const issue = parsed.error.issues[0];
|
||||
if (!issue) return "内容不完整";
|
||||
const [groupAt, , promptAt, field] = issue.path;
|
||||
const group = typeof groupAt === "number" ? groups[groupAt] : null;
|
||||
const where = group
|
||||
? typeof promptAt === "number" ? `「${group.label || "未命名分组"}」第 ${promptAt + 1} 条` : `「${group.label || "未命名分组"}」`
|
||||
: "";
|
||||
const what = field === "title" ? "菜单上的问题" : field === "hint" ? "小字说明" : field === "prompt" ? "发给模型的话" : issue.path[1] === "label" ? "分组名" : issue.path[1] === "note" ? "分组顶部的说明" : "";
|
||||
const reason = issue.code === "too_small" ? "不能为空" : issue.code === "too_big" ? "太长了" : issue.message;
|
||||
return `${where}${what ? `的${what}` : ""}${reason}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「常用问题」 editor (owner 2026-11-17): the astrologer edits the composer's
|
||||
* preset menu here. The twelve groups are fixed (each is a consultation
|
||||
* domain); a group holds up to five questions and an empty group is hidden.
|
||||
* 保存并发布 replaces the whole published library with what is on screen.
|
||||
*/
|
||||
export default function ConsultPresetsManagement() {
|
||||
const { message } = App.useApp();
|
||||
const { data: identity } = useGetIdentity<AdminIdentity>();
|
||||
const canWrite = Boolean(identity?.permissions.includes("content.presets.write"));
|
||||
const [groups, setGroups] = useState<Group[]>([]);
|
||||
const [saved, setSaved] = useState<Group[]>([]);
|
||||
const [builtIn, setBuiltIn] = useState<Group[]>([]);
|
||||
const [version, setVersion] = useState(0);
|
||||
const [publishedAt, setPublishedAt] = useState<string | null>(null);
|
||||
const [source, setSource] = useState<"published" | "built_in">("built_in");
|
||||
const [active, setActive] = useState<string>("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const payload = await adminRequestJson<Payload>("/api/admin/consult-presets");
|
||||
setGroups(payload.data.groups);
|
||||
setSaved(payload.data.groups);
|
||||
setBuiltIn(payload.data.builtIn);
|
||||
setVersion(payload.data.version);
|
||||
setPublishedAt(payload.data.publishedAt);
|
||||
setSource(payload.data.source);
|
||||
setActive((current) => current || payload.data.groups[0]?.id || "");
|
||||
setLoadError(null);
|
||||
} catch (error) {
|
||||
setLoadError(error instanceof Error ? error.message : "读取失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => void load(), 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [load]);
|
||||
|
||||
const dirty = useMemo(() => JSON.stringify(groups) !== JSON.stringify(saved), [groups, saved]);
|
||||
const problem = useMemo(() => (groups.length > 0 ? firstProblem(groups) : null), [groups]);
|
||||
|
||||
function changeGroup(id: string, change: (group: Group) => Group) {
|
||||
setGroups((current) => current.map((group) => (group.id === id ? change(group) : group)));
|
||||
}
|
||||
|
||||
function changePrompt(id: string, at: number, field: "title" | "hint" | "prompt", value: string) {
|
||||
changeGroup(id, (group) => ({ ...group, prompts: group.prompts.map((item, index) => (index === at ? { ...item, [field]: value } : item)) }));
|
||||
}
|
||||
|
||||
function movePrompt(id: string, at: number, by: -1 | 1) {
|
||||
changeGroup(id, (group) => {
|
||||
const to = at + by;
|
||||
if (to < 0 || to >= group.prompts.length) return group;
|
||||
const prompts = [...group.prompts];
|
||||
[prompts[at], prompts[to]] = [prompts[to]!, prompts[at]!];
|
||||
return { ...group, prompts };
|
||||
});
|
||||
}
|
||||
|
||||
async function publish() {
|
||||
if (problem) {
|
||||
message.error(problem);
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await adminRequestJson("/api/admin/consult-presets", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ action: "publish", groups, expectedVersion: version }),
|
||||
});
|
||||
await load();
|
||||
message.success("已发布,用户刷新页面后看到新内容");
|
||||
} catch (error) {
|
||||
message.error(`没有发布成功:${error instanceof Error ? error.message : "请求失败"}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const editable = canWrite && !saving;
|
||||
|
||||
return <List title="常用问题" headerButtons={null}>
|
||||
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
|
||||
<Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
这里是用户输入框旁「常用问题」菜单的全部内容。每个分组最多 {PRESET_LIMITS.promptsPerGroup} 条,一条也没有的分组不在菜单里显示。
|
||||
「发给模型的话」里用全角括号(……)留出让用户自己填的地方,用户点菜单后光标停在第一个括号上。改完点「保存并发布」才生效。
|
||||
</Paragraph>
|
||||
<Text type="secondary">
|
||||
{source === "published" ? `现在在线的是第 ${version} 版,${formatAdminDate(publishedAt)} 发布。` : "还没有在后台发布过,现在在线的是代码里自带的那一版;下面就是它的内容。"}
|
||||
</Text>
|
||||
{loadError && <Alert type="error" showIcon message={`内容没有读出来:${loadError}`} />}
|
||||
{!canWrite && !loading && <Alert type="info" showIcon message="你的账号只能查看,不能修改。" />}
|
||||
<Tabs
|
||||
activeKey={active}
|
||||
onChange={setActive}
|
||||
items={groups.map((group) => ({
|
||||
key: group.id,
|
||||
label: `${group.label || "未命名"}(${group.prompts.length})`,
|
||||
children: (
|
||||
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
|
||||
<Form layout="vertical" disabled={!editable}>
|
||||
<Form.Item label="分组名(菜单左边那一列)" style={{ maxWidth: 320 }}>
|
||||
<Input value={group.label} maxLength={PRESET_LIMITS.label} showCount onChange={(event) => changeGroup(group.id, (item) => ({ ...item, label: event.target.value }))} />
|
||||
</Form.Item>
|
||||
<Form.Item label="分组顶部固定显示的一行(可不填)">
|
||||
<Input value={group.note ?? ""} maxLength={PRESET_LIMITS.note} showCount onChange={(event) => changeGroup(group.id, (item) => ({ ...item, note: event.target.value ? event.target.value : null }))} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
{group.prompts.map((item, at) => (
|
||||
<Card
|
||||
key={at}
|
||||
size="small"
|
||||
title={`第 ${at + 1} 条`}
|
||||
extra={editable ? (
|
||||
<Space>
|
||||
<Button size="small" icon={<ArrowUpOutlined />} disabled={at === 0} onClick={() => movePrompt(group.id, at, -1)} aria-label="上移" />
|
||||
<Button size="small" icon={<ArrowDownOutlined />} disabled={at === group.prompts.length - 1} onClick={() => movePrompt(group.id, at, 1)} aria-label="下移" />
|
||||
<Button size="small" danger icon={<DeleteOutlined />} onClick={() => changeGroup(group.id, (current) => ({ ...current, prompts: current.prompts.filter((_, index) => index !== at) }))}>删除</Button>
|
||||
</Space>
|
||||
) : null}
|
||||
>
|
||||
<Form layout="vertical" disabled={!editable}>
|
||||
<Form.Item label="菜单上的问题">
|
||||
<Input value={item.title} maxLength={PRESET_LIMITS.title} showCount onChange={(event) => changePrompt(group.id, at, "title", event.target.value)} />
|
||||
</Form.Item>
|
||||
<Form.Item label="小字说明(问题下面的灰字,可不填)">
|
||||
<Input value={item.hint} maxLength={PRESET_LIMITS.hint} showCount onChange={(event) => changePrompt(group.id, at, "hint", event.target.value)} />
|
||||
</Form.Item>
|
||||
<Form.Item label="发给模型的话(用户点了以后填进输入框,还可以再改)" style={{ marginBottom: 0 }}>
|
||||
<Input.TextArea value={item.prompt} maxLength={PRESET_LIMITS.prompt} showCount autoSize={{ minRows: 3, maxRows: 12 }} onChange={(event) => changePrompt(group.id, at, "prompt", event.target.value)} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
))}
|
||||
{editable && (
|
||||
<Space wrap>
|
||||
<Button
|
||||
icon={<PlusOutlined />}
|
||||
disabled={group.prompts.length >= PRESET_LIMITS.promptsPerGroup}
|
||||
onClick={() => changeGroup(group.id, (current) => ({ ...current, prompts: [...current.prompts, { title: "", hint: "", prompt: "" }] }))}
|
||||
>
|
||||
加一条
|
||||
</Button>
|
||||
{group.prompts.length >= PRESET_LIMITS.promptsPerGroup && <Text type="secondary">这个分组已经有 {PRESET_LIMITS.promptsPerGroup} 条,菜单放不下更多。</Text>}
|
||||
<Button
|
||||
onClick={() => {
|
||||
const original = builtIn.find((entry) => entry.id === group.id);
|
||||
if (original) changeGroup(group.id, () => original);
|
||||
}}
|
||||
>
|
||||
这个分组恢复成代码自带的内容
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
{canWrite && (
|
||||
<Space wrap>
|
||||
<Button type="primary" loading={saving} disabled={!dirty || loading} onClick={() => void publish()}>保存并发布</Button>
|
||||
<Button disabled={!dirty || saving} onClick={() => setGroups(saved)}>放弃修改</Button>
|
||||
{dirty ? <Text type={problem ? "danger" : "secondary"}>{problem ?? "有修改还没发布。"}</Text> : <Text type="secondary">没有未发布的修改。</Text>}
|
||||
</Space>
|
||||
)}
|
||||
</Space>
|
||||
</List>;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { Drawer, DrawerContent, DrawerTitle, DrawerTrigger } from "@/components/
|
||||
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import type { ConsultationDomain } from "@/lib/consultation-domain-registry";
|
||||
import { CONSULT_PRESET_DOMAINS } from "@/lib/consult-preset-prompts";
|
||||
import { readConsultPresetDomains, requestPublishedConsultPresets, subscribeConsultPresetDomains } from "@/lib/consult-preset-store";
|
||||
|
||||
/** Same switch as the chat 选择星盘 picker: a phone gets a bottom sheet. */
|
||||
const PRESET_SHEET_QUERY = "(max-width: 640px)";
|
||||
@@ -73,7 +73,9 @@ function PresetBody({ sheet, currentDomainRef, onPick }: PresetBodyProps) {
|
||||
const domainRefs = useRef<(HTMLButtonElement | null)[]>([]);
|
||||
const questionRefs = useRef<(HTMLButtonElement | null)[]>([]);
|
||||
const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const domain = CONSULT_PRESET_DOMAINS[index]!;
|
||||
// The published library can have fewer groups than the built-in one.
|
||||
const domains = useSyncExternalStore(subscribeConsultPresetDomains, readConsultPresetDomains, readConsultPresetDomains);
|
||||
const domain = domains[Math.min(index, domains.length - 1)]!;
|
||||
|
||||
useEffect(() => () => {
|
||||
if (hoverTimer.current) clearTimeout(hoverTimer.current);
|
||||
@@ -91,7 +93,7 @@ function PresetBody({ sheet, currentDomainRef, onPick }: PresetBodyProps) {
|
||||
|
||||
function choose(next: number) {
|
||||
cancelHover();
|
||||
if (next < 0 || next >= CONSULT_PRESET_DOMAINS.length) return;
|
||||
if (next < 0 || next >= domains.length) return;
|
||||
setIndex(next);
|
||||
setActive(null);
|
||||
}
|
||||
@@ -126,7 +128,7 @@ function PresetBody({ sheet, currentDomainRef, onPick }: PresetBodyProps) {
|
||||
<Tabs
|
||||
className={sheet ? "consult-preset-sheet-body" : "consult-preset-panel"}
|
||||
value={domain.id}
|
||||
onValueChange={(value) => choose(CONSULT_PRESET_DOMAINS.findIndex((item) => item.id === value))}
|
||||
onValueChange={(value) => choose(domains.findIndex((item) => item.id === value))}
|
||||
orientation={sheet ? "horizontal" : "vertical"}
|
||||
>
|
||||
<TabsList
|
||||
@@ -135,7 +137,7 @@ function PresetBody({ sheet, currentDomainRef, onPick }: PresetBodyProps) {
|
||||
activateOnFocus
|
||||
onPointerLeave={cancelHover}
|
||||
>
|
||||
{CONSULT_PRESET_DOMAINS.map((item, at) => (
|
||||
{domains.map((item, at) => (
|
||||
<TabsTrigger
|
||||
key={item.id}
|
||||
ref={(node: HTMLButtonElement | null) => {
|
||||
@@ -192,6 +194,11 @@ export function ConsultPresetMenu({ disabled = false, onPick }: ConsultPresetMen
|
||||
const currentDomainRef = useRef<HTMLButtonElement | null>(null);
|
||||
const listId = useId();
|
||||
|
||||
// 「常用问题」 is edited in the admin: fetch the published library once.
|
||||
useEffect(() => {
|
||||
void requestPublishedConsultPresets();
|
||||
}, []);
|
||||
|
||||
function pick(prompt: string, id: ConsultationDomain, index: number) {
|
||||
lastDomainIndex = index;
|
||||
setOpen(false);
|
||||
|
||||
@@ -96,3 +96,14 @@ export async function authorizeAdminRequest<IdentityConfig>(
|
||||
throw new AdminAuthorizationError("后台服务暂时不可用", 503);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The content_editor role (the astrologer's account) may only edit content.
|
||||
* Redemption codes are open to every other admin role through admin.access;
|
||||
* a session that holds nothing but content_editor is refused there.
|
||||
*/
|
||||
export function refuseContentOnlyAdmin(session: Pick<AdminSession, "roles">): void {
|
||||
if (session.roles.length > 0 && session.roles.every((role) => role === "content_editor")) {
|
||||
throw new AdminAuthorizationError("无此操作权限", 403);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@ export type AdminRole =
|
||||
| "billing_admin"
|
||||
| "operations"
|
||||
| "support"
|
||||
| "auditor";
|
||||
| "auditor"
|
||||
| "content_editor";
|
||||
|
||||
export const adminPermissions = [
|
||||
"admin.access",
|
||||
@@ -33,6 +34,7 @@ export const adminPermissions = [
|
||||
"support.feedback.write",
|
||||
"support.quality.read",
|
||||
"support.quality.write",
|
||||
"content.presets.write",
|
||||
] as const;
|
||||
|
||||
export type AdminPermission = (typeof adminPermissions)[number];
|
||||
|
||||
@@ -210,6 +210,7 @@ const resourcePermissions: Record<string, { read: string; write?: string }> = {
|
||||
models: { read: "models.read", write: "models.write" },
|
||||
"model-releases": { read: "models.read", write: "models.publish" },
|
||||
"feature-flags": { read: "admin.access", write: "ops.flags.write" },
|
||||
"consult-presets": { read: "admin.access", write: "content.presets.write" },
|
||||
security: { read: "admin.access", write: "admin.access" },
|
||||
};
|
||||
|
||||
@@ -218,6 +219,10 @@ export const adminAccessControlProvider: AccessControlProvider = {
|
||||
const identity = await loadIdentity();
|
||||
const required = resourcePermissions[resource ?? ""];
|
||||
if (!required) return { can: false, reason: "未知管理资源" };
|
||||
// The content-only role (the astrologer's account) does not get redemption codes.
|
||||
if (resource === "codes" && identity.roles.length > 0 && identity.roles.every((role) => role === "content_editor")) {
|
||||
return { can: false, reason: "无此操作权限" };
|
||||
}
|
||||
const permission =
|
||||
action === "list" || action === "show" ? required.read : required.write;
|
||||
return permission && identity.permissions.includes(permission)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { consultationDomainIds, type ConsultationDomain } from "./consultation-domain-registry.ts";
|
||||
import { CONSULT_PRESET_DOMAINS, type ConsultPresetDomain } from "./consult-preset-prompts.ts";
|
||||
|
||||
/**
|
||||
* 「常用问题」 as editable content (owner 2026-11-17): the astrologer edits the
|
||||
* library in the admin and publishes it; the menu reads the published version
|
||||
* and falls back to the built-in library when none is published or it cannot
|
||||
* be read. The menu has a fixed height that fits five questions, so a group
|
||||
* holds at most five.
|
||||
*/
|
||||
export const PRESET_LIMITS = {
|
||||
groups: 12,
|
||||
promptsPerGroup: 5,
|
||||
label: 8,
|
||||
note: 80,
|
||||
title: 30,
|
||||
hint: 20,
|
||||
prompt: 1200,
|
||||
} as const;
|
||||
|
||||
// Product rule 2026-11-13: no middle dot in user-facing copy.
|
||||
const MIDDLE_DOT = String.fromCharCode(183);
|
||||
|
||||
const text = (max: number) => z.string().trim().min(1).max(max).refine((value) => !value.includes(MIDDLE_DOT), "不能用间隔号");
|
||||
|
||||
const promptSchema = z.object({
|
||||
title: text(PRESET_LIMITS.title),
|
||||
hint: z.string().trim().max(PRESET_LIMITS.hint).refine((value) => !value.includes(MIDDLE_DOT), "不能用间隔号"),
|
||||
prompt: text(PRESET_LIMITS.prompt),
|
||||
}).strict();
|
||||
|
||||
const groupSchema = z.object({
|
||||
id: z.enum(consultationDomainIds),
|
||||
label: text(PRESET_LIMITS.label),
|
||||
note: z.string().trim().max(PRESET_LIMITS.note).nullable(),
|
||||
prompts: z.array(promptSchema).max(PRESET_LIMITS.promptsPerGroup),
|
||||
}).strict();
|
||||
|
||||
/** What the admin saves: every group it wants to keep, in menu order. A group may be empty (it is then hidden). */
|
||||
export const consultPresetLibrarySchema = z.array(groupSchema).min(1).max(PRESET_LIMITS.groups)
|
||||
.refine((groups) => new Set(groups.map((group) => group.id)).size === groups.length, "同一个分组不能出现两次")
|
||||
.refine((groups) => groups.some((group) => group.prompts.length > 0), "至少要有一条问题");
|
||||
|
||||
export type ConsultPresetLibraryInput = z.infer<typeof consultPresetLibrarySchema>;
|
||||
|
||||
/** The built-in library in the editable shape: what the editor starts from before anything is published. */
|
||||
export function builtInPresetLibrary(): ConsultPresetLibraryInput {
|
||||
return CONSULT_PRESET_DOMAINS.map((domain) => ({
|
||||
id: domain.id,
|
||||
label: domain.label,
|
||||
note: domain.note,
|
||||
prompts: domain.prompts.map((item) => ({ title: item.title, hint: item.hint, prompt: item.prompt })),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored content → what the menu renders. Empty groups are dropped and keys
|
||||
* are assigned by position. Returns null when the content is not a valid
|
||||
* library, so the caller keeps the built-in one.
|
||||
*/
|
||||
export function menuDomainsFromLibrary(content: unknown): ConsultPresetDomain[] | null {
|
||||
const parsed = consultPresetLibrarySchema.safeParse(content);
|
||||
if (!parsed.success) return null;
|
||||
const domains = parsed.data
|
||||
.filter((group) => group.prompts.length > 0)
|
||||
.map((group, groupAt) => ({
|
||||
id: group.id as ConsultationDomain,
|
||||
label: group.label,
|
||||
note: group.note && group.note.length > 0 ? group.note : null,
|
||||
prompts: group.prompts.map((item, at) => ({
|
||||
key: `${groupAt + 1}.${at + 1}`,
|
||||
title: item.title,
|
||||
hint: item.hint,
|
||||
prompt: item.prompt,
|
||||
added: false,
|
||||
})),
|
||||
}));
|
||||
return domains.length > 0 ? domains : null;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// Generated from docs/research/consult_preset_prompts_reviewed_2026_11_02.md (issue #151).
|
||||
// The prompt text is the astrologer-reviewed wording, copied verbatim. Edit the doc, then regenerate.
|
||||
// Since 2026-11-17 this is only the built-in fallback: the library the menu shows is edited and published
|
||||
// in the admin (常用问题, public.consult_preset_libraries); see src/lib/consult-preset-library.ts.
|
||||
import type { ConsultationDomain } from "./consultation-domain-registry.ts";
|
||||
|
||||
export type ConsultPresetPrompt = Readonly<{
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import "server-only";
|
||||
|
||||
import { queryAdminRows } from "@/lib/admin/database";
|
||||
import { menuDomainsFromLibrary } from "@/lib/consult-preset-library";
|
||||
import { CONSULT_PRESET_DOMAINS, type ConsultPresetDomain } from "@/lib/consult-preset-prompts";
|
||||
|
||||
export type PublishedPresets = Readonly<{
|
||||
source: "published" | "built_in";
|
||||
version: number;
|
||||
publishedAt: string | null;
|
||||
domains: readonly ConsultPresetDomain[];
|
||||
}>;
|
||||
|
||||
type Row = { version: number; content: unknown; published_at: Date };
|
||||
|
||||
const BUILT_IN: PublishedPresets = { source: "built_in", version: 0, publishedAt: null, domains: CONSULT_PRESET_DOMAINS };
|
||||
const CACHE_MS = 30_000;
|
||||
const state = globalThis as typeof globalThis & { jyotishaPresetCache?: { expiresAt: number; value: PublishedPresets } };
|
||||
|
||||
/** The published library, or the built-in one when nothing is published, the content is invalid, or the read fails. */
|
||||
export async function loadPublishedPresets(options: Readonly<{ fresh?: boolean }> = {}): Promise<PublishedPresets> {
|
||||
const cached = state.jyotishaPresetCache;
|
||||
if (!options.fresh && cached && cached.expiresAt > Date.now()) return cached.value;
|
||||
let value = BUILT_IN;
|
||||
try {
|
||||
const rows = await queryAdminRows<Row>(
|
||||
"select version, content, published_at from public.consult_preset_libraries where status='published' limit 1",
|
||||
);
|
||||
const row = rows[0];
|
||||
const domains = row ? menuDomainsFromLibrary(row.content) : null;
|
||||
if (row && domains) value = { source: "published", version: row.version, publishedAt: row.published_at.toISOString(), domains };
|
||||
} catch {
|
||||
// Not self-hosted, table missing, or the database is down: the built-in library stays.
|
||||
if (cached) return cached.value;
|
||||
}
|
||||
state.jyotishaPresetCache = { expiresAt: Date.now() + CACHE_MS, value };
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resetPublishedPresetsCacheForTests(): void {
|
||||
delete state.jyotishaPresetCache;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { CONSULT_PRESET_DOMAINS, type ConsultPresetDomain } from "./consult-preset-prompts.ts";
|
||||
|
||||
/**
|
||||
* The 「常用问题」 the menu shows. It starts as the built-in library and is
|
||||
* replaced once by the published one (admin-edited) when that arrives. A
|
||||
* failed or malformed read leaves the built-in library in place.
|
||||
*/
|
||||
let domains: readonly ConsultPresetDomain[] = CONSULT_PRESET_DOMAINS;
|
||||
let requested = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function usable(value: unknown): value is ConsultPresetDomain[] {
|
||||
return Array.isArray(value) && value.length > 0 && value.every((domain) => {
|
||||
const group = domain as Partial<ConsultPresetDomain> | null;
|
||||
return Boolean(group) && typeof group!.id === "string" && typeof group!.label === "string"
|
||||
&& Array.isArray(group!.prompts) && group!.prompts.length > 0
|
||||
&& group!.prompts.every((item) => typeof item?.key === "string" && typeof item.title === "string"
|
||||
&& typeof item.hint === "string" && typeof item.prompt === "string");
|
||||
});
|
||||
}
|
||||
|
||||
export function readConsultPresetDomains(): readonly ConsultPresetDomain[] {
|
||||
return domains;
|
||||
}
|
||||
|
||||
export function subscribeConsultPresetDomains(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => { listeners.delete(listener); };
|
||||
}
|
||||
|
||||
export function setConsultPresetDomains(next: readonly ConsultPresetDomain[]): void {
|
||||
domains = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** Ask for the published library once per page load. */
|
||||
export function requestPublishedConsultPresets(fetcher: typeof fetch = fetch): Promise<void> {
|
||||
if (requested) return Promise.resolve();
|
||||
requested = true;
|
||||
return fetcher("/api/consult-presets", { credentials: "same-origin" })
|
||||
.then((response) => (response.ok ? response.json() : null))
|
||||
.then((payload: { source?: string; domains?: unknown } | null) => {
|
||||
if (payload?.source === "published" && usable(payload.domains)) setConsultPresetDomains(payload.domains);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
export function resetConsultPresetStoreForTests(): void {
|
||||
domains = CONSULT_PRESET_DOMAINS;
|
||||
requested = false;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
-- 「常用问题」 (the composer's preset menu) becomes admin-editable content.
|
||||
-- Each publish stores the whole library as a new version; the previous one is
|
||||
-- kept as retired, so a bad edit can be traced and re-published.
|
||||
begin;
|
||||
|
||||
create table if not exists public.consult_preset_libraries (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
version integer not null unique check (version > 0),
|
||||
content jsonb not null check (jsonb_typeof(content) = 'array'),
|
||||
status text not null default 'published' check (status in ('published', 'retired')),
|
||||
created_by uuid references auth.users(id) on delete set null,
|
||||
created_at timestamptz not null default now(),
|
||||
published_at timestamptz not null default clock_timestamp()
|
||||
);
|
||||
create unique index if not exists consult_preset_libraries_one_published_idx
|
||||
on public.consult_preset_libraries ((status)) where status = 'published';
|
||||
|
||||
alter table public.consult_preset_libraries enable row level security;
|
||||
revoke all on table public.consult_preset_libraries from public, anon, authenticated;
|
||||
grant select on table public.consult_preset_libraries to service_role;
|
||||
|
||||
insert into public.admin_permissions (permission_key, description) values
|
||||
('content.presets.write', '修改并发布「常用问题」')
|
||||
on conflict (permission_key) do update set description = excluded.description;
|
||||
|
||||
insert into public.admin_roles (code, name, description, requires_mfa) values
|
||||
('content_editor', 'Content Editor', '只能修改「常用问题」等内容,不能查看用户、订单和模型配置', false)
|
||||
on conflict (code) do update set
|
||||
name = excluded.name,
|
||||
description = excluded.description,
|
||||
requires_mfa = excluded.requires_mfa;
|
||||
|
||||
with role_grants(role_code, permission_key) as (values
|
||||
('owner', 'content.presets.write'),
|
||||
('content_editor', 'admin.access'),
|
||||
('content_editor', 'content.presets.write')
|
||||
)
|
||||
insert into public.admin_role_permissions (role_id, permission_id)
|
||||
select r.id, p.id
|
||||
from role_grants g
|
||||
join public.admin_roles r on r.code = g.role_code
|
||||
join public.admin_permissions p on p.permission_key = g.permission_key
|
||||
on conflict do nothing;
|
||||
|
||||
create or replace function public.admin_publish_consult_presets(
|
||||
p_actor_user_id uuid, p_content jsonb, p_expected_version integer, p_reason text, p_request_id text
|
||||
)
|
||||
returns integer language plpgsql security definer set search_path = ''
|
||||
as $$ declare v_current integer; v_next integer; v_id uuid;
|
||||
begin
|
||||
if not public.admin_has_permission(p_actor_user_id, 'content.presets.write') then
|
||||
raise exception 'admin_permission_denied' using errcode = '42501';
|
||||
end if;
|
||||
if char_length(btrim(coalesce(p_reason, ''))) not between 1 and 500 then
|
||||
raise exception 'admin_reason_required' using errcode = '22023';
|
||||
end if;
|
||||
if jsonb_typeof(p_content) is distinct from 'array' or jsonb_array_length(p_content) not between 1 and 12 then
|
||||
raise exception 'consult_presets_invalid' using errcode = '22023';
|
||||
end if;
|
||||
perform pg_advisory_xact_lock(hashtextextended('consult_preset_libraries', 0));
|
||||
select version into v_current from public.consult_preset_libraries where status = 'published';
|
||||
-- 0 means "nothing published yet": the editor started from the built-in library.
|
||||
if coalesce(v_current, 0) is distinct from coalesce(p_expected_version, 0) then
|
||||
raise exception 'consult_presets_version_conflict' using errcode = '40001';
|
||||
end if;
|
||||
select coalesce(max(version), 0) + 1 into v_next from public.consult_preset_libraries;
|
||||
update public.consult_preset_libraries set status = 'retired' where status = 'published';
|
||||
insert into public.consult_preset_libraries (version, content, created_by)
|
||||
values (v_next, p_content, p_actor_user_id) returning id into v_id;
|
||||
insert into audit.admin_audit_logs (actor_user_id, actor_email, actor_role, action, target_type, target_id, after_value,
|
||||
request_id, permission_used, reason)
|
||||
select p_actor_user_id, lower(btrim(u.email)), 'admin', 'content.presets.publish', 'consult_preset_library', v_id,
|
||||
jsonb_build_object('version', v_next, 'groups', jsonb_array_length(p_content)),
|
||||
p_request_id, 'content.presets.write', btrim(p_reason)
|
||||
from identity.users u where u.id = p_actor_user_id on conflict do nothing;
|
||||
return v_next;
|
||||
end $$;
|
||||
|
||||
revoke all on function public.admin_publish_consult_presets(uuid, jsonb, integer, text, text) from public, anon, authenticated;
|
||||
grant execute on function public.admin_publish_consult_presets(uuid, jsonb, integer, text, text) to service_role;
|
||||
|
||||
do $$ begin
|
||||
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
|
||||
grant select on table public.consult_preset_libraries to admin_runtime;
|
||||
grant execute on function public.admin_publish_consult_presets(uuid, jsonb, integer, text, text) to admin_runtime;
|
||||
drop policy if exists consult_preset_libraries_admin_read on public.consult_preset_libraries;
|
||||
create policy consult_preset_libraries_admin_read on public.consult_preset_libraries
|
||||
for select to admin_runtime using (true);
|
||||
end if;
|
||||
end $$;
|
||||
|
||||
commit;
|
||||
@@ -0,0 +1,109 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { builtInPresetLibrary, consultPresetLibrarySchema, menuDomainsFromLibrary, PRESET_LIMITS } from "../src/lib/consult-preset-library.ts";
|
||||
import { CONSULT_PRESET_DOMAINS } from "../src/lib/consult-preset-prompts.ts";
|
||||
import {
|
||||
readConsultPresetDomains,
|
||||
requestPublishedConsultPresets,
|
||||
resetConsultPresetStoreForTests,
|
||||
} from "../src/lib/consult-preset-store.ts";
|
||||
import { refuseContentOnlyAdmin } from "../src/lib/admin/auth-boundary.ts";
|
||||
|
||||
const source = (path: string) => readFileSync(fileURLToPath(new URL(`../${path}`, import.meta.url)), "utf8");
|
||||
|
||||
test("the built-in library is a valid editable library and round-trips to the same menu", () => {
|
||||
const library = builtInPresetLibrary();
|
||||
assert.equal(consultPresetLibrarySchema.safeParse(library).success, true);
|
||||
const menu = menuDomainsFromLibrary(library)!;
|
||||
assert.deepEqual(menu.map((domain) => [domain.id, domain.label, domain.note]), CONSULT_PRESET_DOMAINS.map((domain) => [domain.id, domain.label, domain.note]));
|
||||
assert.deepEqual(
|
||||
menu.map((domain) => domain.prompts.map((item) => [item.title, item.hint, item.prompt])),
|
||||
CONSULT_PRESET_DOMAINS.map((domain) => domain.prompts.map((item) => [item.title, item.hint, item.prompt])),
|
||||
);
|
||||
// The menu's fixed height fits five questions: the built-in library already obeys the limit.
|
||||
assert.ok(CONSULT_PRESET_DOMAINS.every((domain) => domain.prompts.length <= PRESET_LIMITS.promptsPerGroup));
|
||||
});
|
||||
|
||||
test("an edited library: empty groups are hidden, limits and the fixed group ids are enforced", () => {
|
||||
const library = builtInPresetLibrary().map((group) => ({ ...group, prompts: [...group.prompts] }));
|
||||
library[1] = { ...library[1]!, prompts: [] };
|
||||
library[0] = { ...library[0]!, label: "了解自己", prompts: [{ title: "新问题", hint: "", prompt: "请看(哪件事)。" }] };
|
||||
const menu = menuDomainsFromLibrary(library)!;
|
||||
assert.equal(menu.length, CONSULT_PRESET_DOMAINS.length - 1);
|
||||
assert.equal(menu[0]!.label, "了解自己");
|
||||
assert.deepEqual(menu[0]!.prompts, [{ key: "1.1", title: "新问题", hint: "", prompt: "请看(哪件事)。", added: false }]);
|
||||
assert.equal(menu.some((domain) => domain.id === library[1]!.id), false);
|
||||
|
||||
const six = { ...library[0]!, prompts: Array.from({ length: 6 }, () => ({ title: "t", hint: "", prompt: "p" })) };
|
||||
assert.equal(menuDomainsFromLibrary([six]), null);
|
||||
assert.equal(menuDomainsFromLibrary([{ ...library[0]!, id: "not_a_domain" }]), null);
|
||||
assert.equal(menuDomainsFromLibrary([library[0]!, library[0]!]), null);
|
||||
assert.equal(menuDomainsFromLibrary([{ ...library[0]!, prompts: [] }]), null);
|
||||
assert.equal(menuDomainsFromLibrary([{ ...library[0]!, prompts: [{ title: "", hint: "", prompt: "p" }] }]), null);
|
||||
assert.equal(menuDomainsFromLibrary([{ ...library[0]!, prompts: [{ title: "甲\u00b7乙", hint: "", prompt: "p" }] }]), null);
|
||||
assert.equal(menuDomainsFromLibrary("nonsense"), null);
|
||||
});
|
||||
|
||||
test("the menu store takes the published library and keeps the built-in one on any failure", async () => {
|
||||
const published = menuDomainsFromLibrary([{ ...builtInPresetLibrary()[0]!, label: "新分组名" }])!;
|
||||
const respond = (body: unknown, ok = true) => (async () => ({ ok, json: async () => body })) as unknown as typeof fetch;
|
||||
|
||||
resetConsultPresetStoreForTests();
|
||||
await requestPublishedConsultPresets(respond({ source: "built_in", version: 0, domains: published }));
|
||||
assert.equal(readConsultPresetDomains(), CONSULT_PRESET_DOMAINS);
|
||||
|
||||
resetConsultPresetStoreForTests();
|
||||
await requestPublishedConsultPresets(respond({ source: "published", domains: [{ id: "general", label: "x", prompts: [] }] }));
|
||||
assert.equal(readConsultPresetDomains(), CONSULT_PRESET_DOMAINS);
|
||||
|
||||
resetConsultPresetStoreForTests();
|
||||
await requestPublishedConsultPresets(respond(null, false));
|
||||
assert.equal(readConsultPresetDomains(), CONSULT_PRESET_DOMAINS);
|
||||
|
||||
resetConsultPresetStoreForTests();
|
||||
await requestPublishedConsultPresets((async () => { throw new Error("offline"); }) as unknown as typeof fetch);
|
||||
assert.equal(readConsultPresetDomains(), CONSULT_PRESET_DOMAINS);
|
||||
|
||||
resetConsultPresetStoreForTests();
|
||||
let calls = 0;
|
||||
const counting = (async () => { calls += 1; return { ok: true, json: async () => ({ source: "published", domains: published }) }; }) as unknown as typeof fetch;
|
||||
await requestPublishedConsultPresets(counting);
|
||||
await requestPublishedConsultPresets(counting);
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(readConsultPresetDomains()[0]!.label, "新分组名");
|
||||
resetConsultPresetStoreForTests();
|
||||
});
|
||||
|
||||
test("only content.presets.write may publish, and the content-only role cannot touch redemption codes", () => {
|
||||
const route = source("src/app/api/admin/consult-presets/route.ts");
|
||||
assert.match(route, /requireAdminMutation\(request, "content\.presets\.write"\)/);
|
||||
assert.match(route, /await requirePermission\("admin\.access"\)/);
|
||||
const migration = source("supabase/migrations/20261117010000_consult_preset_libraries.sql");
|
||||
assert.match(migration, /admin_has_permission\(p_actor_user_id, 'content\.presets\.write'\)/);
|
||||
assert.match(migration, /\('content_editor', 'admin\.access'\),\s*\('content_editor', 'content\.presets\.write'\)/);
|
||||
assert.doesNotMatch(migration, /'content_editor', '(?!admin\.access|content\.presets\.write)[a-z_.]+'/);
|
||||
assert.match(migration, /for select to admin_runtime using \(true\)/);
|
||||
|
||||
assert.throws(() => refuseContentOnlyAdmin({ roles: ["content_editor"] }), /无此操作权限/);
|
||||
assert.doesNotThrow(() => refuseContentOnlyAdmin({ roles: ["content_editor", "support"] }));
|
||||
assert.doesNotThrow(() => refuseContentOnlyAdmin({ roles: ["owner"] }));
|
||||
for (const [file, mutations] of [["src/app/api/admin/codes/route.ts", 1], ["src/app/api/admin/codes/[id]/route.ts", 2]] as const) {
|
||||
const guards = source(file).match(/requireAdminMutation\(\s*request,\s*"admin\.access",?\s*\);\s*refuseContentOnlyAdmin\(session\);/g) ?? [];
|
||||
assert.equal(guards.length, mutations, file);
|
||||
}
|
||||
assert.match(source("src/app/api/admin/codes/route.ts"), /refuseContentOnlyAdmin\(await requirePermission\("admin\.access"\)\)/);
|
||||
});
|
||||
|
||||
test("the menu reads the store, and the admin lists the page for the new permission", () => {
|
||||
const menu = source("src/components/consult-preset-menu.tsx");
|
||||
assert.doesNotMatch(menu, /CONSULT_PRESET_DOMAINS/);
|
||||
assert.match(menu, /useSyncExternalStore\(subscribeConsultPresetDomains, readConsultPresetDomains, readConsultPresetDomains\)/);
|
||||
assert.match(menu, /void requestPublishedConsultPresets\(\);/);
|
||||
assert.match(source("src/lib/admin/providers.ts"), /"consult-presets": \{ read: "admin\.access", write: "content\.presets\.write" \}/);
|
||||
assert.match(source("src/components/admin/admin-app.tsx"), /name: "consult-presets", list: "\/admin\/consult-presets"/);
|
||||
assert.match(source("src/components/admin/administrators-resource.tsx"), /value: "content_editor"/);
|
||||
assert.match(source("src/app/api/admin/administrators/route.ts"), /"auditor", "content_editor"\]/);
|
||||
});
|
||||
@@ -339,6 +339,9 @@ test("local PostgreSQL applies the reviewed business schema and serves authentic
|
||||
"chart_choice_records",
|
||||
"chart_profiles",
|
||||
"chat_sessions",
|
||||
// 新值: 加入 consult_preset_libraries
|
||||
// 原因: 「常用问题」改为后台可编辑(20261117010000_consult_preset_libraries.sql)
|
||||
"consult_preset_libraries",
|
||||
"consultation_requests",
|
||||
"credit_request_cancellations",
|
||||
"credit_transactions",
|
||||
|
||||
@@ -1587,6 +1587,10 @@ def test_capability_audit_scans_registry_and_local_sources() -> None:
|
||||
'admin/administrators',
|
||||
'admin/audit-logs',
|
||||
'admin/codes',
|
||||
# 原值: admin/codes 之后直接是 admin/consultations
|
||||
# 新值: 中间加入 admin/consult-presets
|
||||
# 原因: 「常用问题」后台编辑页(2026-11-17)
|
||||
'admin/consult-presets',
|
||||
'admin/consultations',
|
||||
'admin/credit-transactions',
|
||||
'admin/customers',
|
||||
|
||||
Reference in New Issue
Block a user