Compare commits
3 Commits
7fd3feb77c
...
57261dad71
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57261dad71 | ||
|
|
f31db01b8e | ||
|
|
e160d7f217 |
@ -32,6 +32,8 @@ import {
|
||||
MonitorPlay,
|
||||
Package,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Save,
|
||||
Search,
|
||||
Settings2,
|
||||
@ -187,6 +189,8 @@ const WORKFLOW_SETTINGS_STALE_DRAFT_STORAGE_KEY = "agent-workflow-settings-stale
|
||||
const WORKFLOW_SETTINGS_DRAFT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const AGENT_WORKFLOW_SETTINGS_ENDPOINT =
|
||||
"/api/site-settings?scope=agent-workflow-admin";
|
||||
const AGENT_WORKFLOW_SNAPSHOTS_ENDPOINT =
|
||||
"/api/admin/system-settings/snapshots?scope=agent-workflow&limit=12";
|
||||
const AGENT_WORKFLOW_SAVE_TIMEOUT_MS = 30_000;
|
||||
const DELETE_WORKFLOW_STEP_PASSWORD = "123456";
|
||||
const BUSINESS_MODE_DEFAULT_MODEL_EMPTY_VALUE = "__agent_workflow_mode_default_model_empty__";
|
||||
@ -1811,6 +1815,76 @@ interface AgentWorkflowSettingsPayload {
|
||||
agentPsdTemplateSecondaryCategoryConfig?: AgentPsdTemplateSecondaryCategoryConfig;
|
||||
}
|
||||
|
||||
interface AgentWorkflowDestructiveChangePayload {
|
||||
totalBeforeOptionCount: number;
|
||||
totalAfterOptionCount: number;
|
||||
removedOptionCount: number;
|
||||
removedEnabledOptionCount: number;
|
||||
promptClearedCount: number;
|
||||
previewClearedCount: number;
|
||||
removedOptionSamples: string[];
|
||||
promptClearedSamples: string[];
|
||||
previewClearedSamples: string[];
|
||||
approvalToken: string;
|
||||
}
|
||||
|
||||
interface AgentWorkflowSnapshotItem {
|
||||
id: string;
|
||||
scope: string;
|
||||
label: string | null;
|
||||
summary?: {
|
||||
keyCount?: number;
|
||||
nonNullKeyCount?: number;
|
||||
byteLength?: number;
|
||||
siteFieldCount?: number;
|
||||
} | null;
|
||||
createdAt: string;
|
||||
createdByName?: string | null;
|
||||
createdByEmail?: string | null;
|
||||
}
|
||||
|
||||
function formatSnapshotByteLength(value?: number | null) {
|
||||
const byteLength = Number(value || 0);
|
||||
if (!Number.isFinite(byteLength) || byteLength <= 0) {
|
||||
return "0 KB";
|
||||
}
|
||||
|
||||
return `${(byteLength / 1024).toFixed(byteLength >= 1024 * 1024 ? 1 : 0)} KB`;
|
||||
}
|
||||
|
||||
function formatAgentWorkflowDestructiveChangeConfirmText(
|
||||
payload: AgentWorkflowDestructiveChangePayload
|
||||
) {
|
||||
const lines = [
|
||||
"这次保存会对风格化工作流做大规模删改,系统已拦截。",
|
||||
"",
|
||||
`删除节点:${payload.removedOptionCount}(其中启用中 ${payload.removedEnabledOptionCount})`,
|
||||
`清空提示词:${payload.promptClearedCount}`,
|
||||
`清空预览图:${payload.previewClearedCount}`,
|
||||
"",
|
||||
];
|
||||
|
||||
const sampleGroups: Array<[string, string[]]> = [
|
||||
["将删除的分支示例", payload.removedOptionSamples],
|
||||
["将清空提示词的示例", payload.promptClearedSamples],
|
||||
["将清空预览图的示例", payload.previewClearedSamples],
|
||||
];
|
||||
|
||||
for (const [label, samples] of sampleGroups) {
|
||||
if (samples.length === 0) {
|
||||
continue;
|
||||
}
|
||||
lines.push(`${label}:`);
|
||||
for (const sample of samples.slice(0, 5)) {
|
||||
lines.push(`- ${sample}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
lines.push("如果这是你确认要执行的结构性删除,请点击“确定”再次保存。");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
interface AdminAiModelOption {
|
||||
id: string;
|
||||
modelId?: string | null;
|
||||
@ -1915,6 +1989,15 @@ export function AgentWorkflowSettingsClient({
|
||||
fetcher,
|
||||
{ revalidateOnFocus: false }
|
||||
);
|
||||
const {
|
||||
data: snapshotsData,
|
||||
isLoading: isLoadingSnapshots,
|
||||
mutate: mutateSnapshots,
|
||||
} = useSWR<{ snapshots: AgentWorkflowSnapshotItem[] }>(
|
||||
AGENT_WORKFLOW_SNAPSHOTS_ENDPOINT,
|
||||
fetcher,
|
||||
{ revalidateOnFocus: false }
|
||||
);
|
||||
const [agentWorkflowDefaultModelId, setAgentWorkflowDefaultModelId] = useState<string | null>(null);
|
||||
const [presetLibraryConfig, setPresetLibraryConfig] = useState<AgentPresetLibraryConfig>(
|
||||
defaultAgentPresetLibraryConfig
|
||||
@ -1970,6 +2053,9 @@ export function AgentWorkflowSettingsClient({
|
||||
const [autoDraftUpdatedAt, setAutoDraftUpdatedAt] = useState<number | null>(null);
|
||||
const [autoDraftStatus, setAutoDraftStatus] = useState<"idle" | "restored" | "saved">("idle");
|
||||
const [recoverableDraftUpdatedAt, setRecoverableDraftUpdatedAt] = useState<number | null>(null);
|
||||
const [snapshotDialogOpen, setSnapshotDialogOpen] = useState(false);
|
||||
const [isCreatingSnapshot, setIsCreatingSnapshot] = useState(false);
|
||||
const [restoringSnapshotId, setRestoringSnapshotId] = useState<string | null>(null);
|
||||
const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});
|
||||
const brandImportInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const hasAppliedInitialSettingsRef = useRef(false);
|
||||
@ -3899,39 +3985,77 @@ export function AgentWorkflowSettingsClient({
|
||||
changedPayload.agentWorkflowSettingsBaseSignatures[field] = baseSignatures[field];
|
||||
}
|
||||
|
||||
const response = await fetchAgentWorkflowSettingsWithTimeout(
|
||||
"/api/site-settings",
|
||||
{
|
||||
const submitChangedPayload = async (payload: Record<string, unknown>) =>
|
||||
fetchAgentWorkflowSettingsWithTimeout("/api/site-settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(changedPayload),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
let response = await submitChangedPayload(changedPayload as Record<string, unknown>);
|
||||
let responsePayload = (await response.json().catch(() => null)) as
|
||||
| {
|
||||
error?: string;
|
||||
details?: Array<{ message?: string; path?: Array<string | number> }>;
|
||||
requiresDestructiveChangeApproval?: boolean;
|
||||
destructiveChange?: AgentWorkflowDestructiveChangePayload;
|
||||
}
|
||||
| null;
|
||||
|
||||
if (
|
||||
!response.ok &&
|
||||
responsePayload?.requiresDestructiveChangeApproval &&
|
||||
responsePayload?.destructiveChange?.approvalToken
|
||||
) {
|
||||
const shouldContinue = window.confirm(
|
||||
formatAgentWorkflowDestructiveChangeConfirmText(
|
||||
responsePayload.destructiveChange
|
||||
)
|
||||
);
|
||||
|
||||
if (!shouldContinue) {
|
||||
toast.info("已取消本次高风险保存");
|
||||
return;
|
||||
}
|
||||
);
|
||||
|
||||
response = await submitChangedPayload({
|
||||
...changedPayload,
|
||||
agentWorkflowDestructiveChangeApproval: {
|
||||
token: responsePayload.destructiveChange.approvalToken,
|
||||
},
|
||||
});
|
||||
responsePayload = (await response.json().catch(() => null)) as
|
||||
| {
|
||||
error?: string;
|
||||
details?: Array<{ message?: string; path?: Array<string | number> }>;
|
||||
}
|
||||
| null;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
let message = "保存失败";
|
||||
|
||||
try {
|
||||
const payload = await response.json();
|
||||
if (Array.isArray(payload?.details) && payload.details.length > 0) {
|
||||
const firstIssue = payload.details[0] as {
|
||||
message?: string;
|
||||
path?: Array<string | number>;
|
||||
};
|
||||
const pathText =
|
||||
Array.isArray(firstIssue.path) && firstIssue.path.length > 0
|
||||
? firstIssue.path
|
||||
.filter((segment) => segment !== undefined && segment !== null && segment !== "")
|
||||
.join(" / ")
|
||||
: "";
|
||||
const reasonText = String(firstIssue.message || "").trim();
|
||||
if (Array.isArray(responsePayload?.details) && responsePayload.details.length > 0) {
|
||||
const firstIssue = responsePayload.details[0] as {
|
||||
message?: string;
|
||||
path?: Array<string | number>;
|
||||
};
|
||||
const pathText =
|
||||
Array.isArray(firstIssue.path) && firstIssue.path.length > 0
|
||||
? firstIssue.path
|
||||
.filter((segment) => segment !== undefined && segment !== null && segment !== "")
|
||||
.join(" / ")
|
||||
: "";
|
||||
const reasonText = String(firstIssue.message || "").trim();
|
||||
|
||||
message = [payload?.error, pathText, reasonText].filter(Boolean).join(":");
|
||||
} else if (typeof payload?.error === "string" && payload.error.trim()) {
|
||||
message = payload.error.trim();
|
||||
}
|
||||
} catch {
|
||||
// Ignore JSON parsing issues and keep the generic message.
|
||||
message = [responsePayload?.error, pathText, reasonText]
|
||||
.filter(Boolean)
|
||||
.join(":");
|
||||
} else if (
|
||||
typeof responsePayload?.error === "string" &&
|
||||
responsePayload.error.trim()
|
||||
) {
|
||||
message = responsePayload.error.trim();
|
||||
}
|
||||
|
||||
throw new Error(message);
|
||||
@ -3990,6 +4114,81 @@ export function AgentWorkflowSettingsClient({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
try {
|
||||
setIsCreatingSnapshot(true);
|
||||
const response = await fetch("/api/admin/system-settings/snapshots", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "create",
|
||||
scope: "agent-workflow",
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json().catch(() => null)) as
|
||||
| { error?: string; snapshot?: AgentWorkflowSnapshotItem | null }
|
||||
| null;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(payload?.error || "创建快照失败");
|
||||
}
|
||||
|
||||
await mutateSnapshots();
|
||||
toast.success("已创建当前工作流快照");
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "创建快照失败");
|
||||
} finally {
|
||||
setIsCreatingSnapshot(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestoreSnapshot = async (snapshot: AgentWorkflowSnapshotItem) => {
|
||||
const shouldContinue = window.confirm(
|
||||
[
|
||||
"将把风格化工作流恢复到这个快照版本。",
|
||||
"恢复前系统会自动再做一份当前快照,便于继续回退。",
|
||||
"",
|
||||
`快照标签:${snapshot.label || "未命名快照"}`,
|
||||
`创建时间:${new Date(snapshot.createdAt).toLocaleString("zh-CN")}`,
|
||||
].join("\n")
|
||||
);
|
||||
|
||||
if (!shouldContinue) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setRestoringSnapshotId(snapshot.id);
|
||||
const response = await fetch("/api/admin/system-settings/snapshots", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "restore",
|
||||
snapshotId: snapshot.id,
|
||||
reason: `restore-snapshot:${snapshot.id}`,
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json().catch(() => null)) as
|
||||
| { error?: string; backupSnapshotId?: string | null }
|
||||
| null;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(payload?.error || "恢复快照失败");
|
||||
}
|
||||
|
||||
await Promise.all([mutate(), mutateSnapshots()]);
|
||||
toast.success(
|
||||
payload?.backupSnapshotId
|
||||
? `已恢复快照,并自动创建恢复前备份 ${payload.backupSnapshotId.slice(0, 8)}`
|
||||
: "已恢复到所选快照"
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "恢复快照失败");
|
||||
} finally {
|
||||
setRestoringSnapshotId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadBrandTemplate = async () => {
|
||||
try {
|
||||
await downloadAgentWorkflowBrandImportTemplate(categoryLabels);
|
||||
@ -5782,6 +5981,15 @@ export function AgentWorkflowSettingsClient({
|
||||
>
|
||||
{recoverableDraftUpdatedAt ? "恢复旧草稿" : "查找旧草稿"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSnapshotDialogOpen(true)}
|
||||
>
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
快照中心
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href="/settings/agent-workflow/psd-templates">
|
||||
<Layers className="mr-2 h-4 w-4" />
|
||||
@ -5812,6 +6020,126 @@ export function AgentWorkflowSettingsClient({
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Dialog open={snapshotDialogOpen} onOpenChange={setSnapshotDialogOpen}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>风格化工作流快照中心</DialogTitle>
|
||||
<DialogDescription>
|
||||
查看最近快照、手动创建安全点,并一键恢复到指定版本。恢复前系统会自动再备份一次当前状态。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3 rounded-2xl border bg-muted/20 p-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm font-medium">当前共有 {snapshotsData?.snapshots?.length || 0} 条最近快照</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
自动快照会在高风险保存前生成,手动快照适合在批量编辑前先留一个恢复点。
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => mutateSnapshots()}
|
||||
disabled={isLoadingSnapshots}
|
||||
>
|
||||
<RefreshCw
|
||||
className={cn("mr-2 h-4 w-4", isLoadingSnapshots && "animate-spin")}
|
||||
/>
|
||||
刷新
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleCreateSnapshot}
|
||||
disabled={isCreatingSnapshot}
|
||||
>
|
||||
{isCreatingSnapshot ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
创建快照
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[60vh] space-y-3 overflow-y-auto pr-1">
|
||||
{isLoadingSnapshots ? (
|
||||
<div className="flex h-40 items-center justify-center text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
正在加载快照列表...
|
||||
</div>
|
||||
) : (snapshotsData?.snapshots?.length || 0) === 0 ? (
|
||||
<div className="flex h-40 items-center justify-center rounded-2xl border border-dashed text-sm text-muted-foreground">
|
||||
还没有可用快照,先创建一个安全点吧。
|
||||
</div>
|
||||
) : (
|
||||
(snapshotsData?.snapshots || []).map((snapshot, index) => (
|
||||
<div
|
||||
key={snapshot.id}
|
||||
className="rounded-2xl border bg-background p-4 shadow-sm"
|
||||
>
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant={index === 0 ? "default" : "secondary"}>
|
||||
{index === 0 ? "最新" : `#${index + 1}`}
|
||||
</Badge>
|
||||
<span className="font-medium">
|
||||
{snapshot.label || "未命名快照"}
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{snapshot.id.slice(0, 8)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{new Date(snapshot.createdAt).toLocaleString("zh-CN")}
|
||||
{" · "}
|
||||
{snapshot.createdByName ||
|
||||
snapshot.createdByEmail ||
|
||||
"系统自动创建"}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
|
||||
<span className="rounded-full border px-2 py-1">
|
||||
配置键 {snapshot.summary?.keyCount ?? "-"}
|
||||
</span>
|
||||
<span className="rounded-full border px-2 py-1">
|
||||
站点字段 {snapshot.summary?.siteFieldCount ?? 0}
|
||||
</span>
|
||||
<span className="rounded-full border px-2 py-1">
|
||||
非空项 {snapshot.summary?.nonNullKeyCount ?? "-"}
|
||||
</span>
|
||||
<span className="rounded-full border px-2 py-1">
|
||||
大小 {formatSnapshotByteLength(snapshot.summary?.byteLength)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleRestoreSnapshot(snapshot)}
|
||||
disabled={restoringSnapshotId === snapshot.id}
|
||||
>
|
||||
{restoringSnapshotId === snapshot.id ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
恢复到此版本
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Stats Bar */}
|
||||
<div className="border-b bg-muted/30">
|
||||
<div className="container mx-auto px-6 py-3">
|
||||
|
||||
257
app/api/admin/system-settings/snapshots/route.ts
Normal file
257
app/api/admin/system-settings/snapshots/route.ts
Normal file
@ -0,0 +1,257 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import {
|
||||
siteSettings,
|
||||
systemSettingHistory,
|
||||
systemSettingSnapshot,
|
||||
systemSettings,
|
||||
user,
|
||||
} from "@/lib/db/schema";
|
||||
import { ChatSDKError } from "@/lib/errors";
|
||||
import { requireAgentWorkflowAdmin } from "@/lib/middleware/admin";
|
||||
import { clearScopedSiteSettingsCache } from "@/lib/site-settings/public-cache";
|
||||
import {
|
||||
AGENT_WORKFLOW_SNAPSHOT_SCOPE,
|
||||
createSystemSettingSnapshotData,
|
||||
getSystemSettingSnapshotScopeKeys,
|
||||
readSystemSettingSnapshotData,
|
||||
summarizeSystemSettingSnapshotData,
|
||||
type SystemSettingSnapshotScope,
|
||||
} from "@/lib/system-settings/snapshot";
|
||||
|
||||
const snapshotScopeSchema = z.enum([AGENT_WORKFLOW_SNAPSHOT_SCOPE]);
|
||||
|
||||
const listQuerySchema = z.object({
|
||||
scope: snapshotScopeSchema,
|
||||
limit: z.coerce.number().int().min(1).max(50).optional(),
|
||||
});
|
||||
|
||||
const mutationSchema = z.discriminatedUnion("action", [
|
||||
z.object({
|
||||
action: z.literal("create"),
|
||||
scope: snapshotScopeSchema,
|
||||
label: z.string().trim().min(1).max(128).optional(),
|
||||
}),
|
||||
z.object({
|
||||
action: z.literal("restore"),
|
||||
snapshotId: z.string().uuid(),
|
||||
reason: z.string().trim().min(1).max(128).optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
async function loadSnapshotSource(scope: SystemSettingSnapshotScope) {
|
||||
const keys = getSystemSettingSnapshotScopeKeys(scope);
|
||||
const rows = await db
|
||||
.select({
|
||||
key: systemSettings.key,
|
||||
value: systemSettings.value,
|
||||
})
|
||||
.from(systemSettings)
|
||||
.where(inArray(systemSettings.key, [...keys]));
|
||||
const valueByKey = new Map(rows.map((row) => [row.key, row.value]));
|
||||
const [currentSiteSettings] = await db
|
||||
.select({
|
||||
agentWorkflowDefaultModelId: siteSettings.agentWorkflowDefaultModelId,
|
||||
})
|
||||
.from(siteSettings)
|
||||
.limit(1);
|
||||
|
||||
return {
|
||||
snapshotData: createSystemSettingSnapshotData(scope, valueByKey, {
|
||||
agentWorkflowDefaultModelId:
|
||||
String(currentSiteSettings?.agentWorkflowDefaultModelId || "").trim() || null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function createSnapshot(params: {
|
||||
scope: SystemSettingSnapshotScope;
|
||||
label?: string;
|
||||
createdBy: string;
|
||||
}) {
|
||||
const { snapshotData } = await loadSnapshotSource(params.scope);
|
||||
const [snapshot] = await db
|
||||
.insert(systemSettingSnapshot)
|
||||
.values({
|
||||
scope: params.scope,
|
||||
label: params.label || `manual-${params.scope}-snapshot`,
|
||||
summary: summarizeSystemSettingSnapshotData(snapshotData),
|
||||
data: snapshotData,
|
||||
createdAt: new Date(),
|
||||
createdBy: params.createdBy,
|
||||
})
|
||||
.returning({
|
||||
id: systemSettingSnapshot.id,
|
||||
scope: systemSettingSnapshot.scope,
|
||||
label: systemSettingSnapshot.label,
|
||||
createdAt: systemSettingSnapshot.createdAt,
|
||||
});
|
||||
|
||||
return snapshot ?? null;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
await requireAgentWorkflowAdmin();
|
||||
|
||||
const parsed = listQuerySchema.parse(
|
||||
Object.fromEntries(new URL(request.url).searchParams.entries())
|
||||
);
|
||||
|
||||
const snapshots = await db
|
||||
.select({
|
||||
id: systemSettingSnapshot.id,
|
||||
scope: systemSettingSnapshot.scope,
|
||||
label: systemSettingSnapshot.label,
|
||||
summary: systemSettingSnapshot.summary,
|
||||
createdAt: systemSettingSnapshot.createdAt,
|
||||
createdByName: user.name,
|
||||
createdByEmail: user.email,
|
||||
})
|
||||
.from(systemSettingSnapshot)
|
||||
.leftJoin(user, eq(user.id, systemSettingSnapshot.createdBy))
|
||||
.where(eq(systemSettingSnapshot.scope, parsed.scope))
|
||||
.orderBy(desc(systemSettingSnapshot.createdAt))
|
||||
.limit(parsed.limit ?? 12);
|
||||
|
||||
return NextResponse.json({ snapshots });
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) {
|
||||
return error.toResponse();
|
||||
}
|
||||
return new ChatSDKError("offline:admin").toResponse();
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireAgentWorkflowAdmin();
|
||||
const body = mutationSchema.parse(await request.json());
|
||||
|
||||
if (body.action === "create") {
|
||||
const snapshot = await createSnapshot({
|
||||
scope: body.scope,
|
||||
label: body.label,
|
||||
createdBy: session.user.id,
|
||||
});
|
||||
return NextResponse.json({ snapshot });
|
||||
}
|
||||
|
||||
const [targetSnapshot] = await db
|
||||
.select({
|
||||
id: systemSettingSnapshot.id,
|
||||
scope: systemSettingSnapshot.scope,
|
||||
data: systemSettingSnapshot.data,
|
||||
})
|
||||
.from(systemSettingSnapshot)
|
||||
.where(eq(systemSettingSnapshot.id, body.snapshotId))
|
||||
.limit(1);
|
||||
|
||||
if (!targetSnapshot) {
|
||||
return NextResponse.json({ error: "快照不存在" }, { status: 404 });
|
||||
}
|
||||
|
||||
const scope = snapshotScopeSchema.parse(targetSnapshot.scope);
|
||||
const parsedSnapshot = readSystemSettingSnapshotData(scope, targetSnapshot.data);
|
||||
const currentSource = await loadSnapshotSource(scope);
|
||||
|
||||
const [backupSnapshot] = await db.transaction(async (tx) => {
|
||||
const [preRestoreSnapshot] = await tx
|
||||
.insert(systemSettingSnapshot)
|
||||
.values({
|
||||
scope,
|
||||
label: `before-restore-${body.snapshotId.slice(0, 8)}`,
|
||||
summary: summarizeSystemSettingSnapshotData(currentSource.snapshotData),
|
||||
data: currentSource.snapshotData,
|
||||
createdAt: new Date(),
|
||||
createdBy: session.user.id,
|
||||
})
|
||||
.returning({
|
||||
id: systemSettingSnapshot.id,
|
||||
});
|
||||
|
||||
for (const [key, nextValue] of Object.entries(parsedSnapshot.systemSettings)) {
|
||||
const [existingSetting] = await tx
|
||||
.select({ value: systemSettings.value })
|
||||
.from(systemSettings)
|
||||
.where(eq(systemSettings.key, key))
|
||||
.limit(1);
|
||||
|
||||
await tx.insert(systemSettingHistory).values({
|
||||
key,
|
||||
previousValue: existingSetting?.value ?? null,
|
||||
nextValue,
|
||||
reason: body.reason || `restore-snapshot:${body.snapshotId}`,
|
||||
changedAt: new Date(),
|
||||
changedBy: session.user.id,
|
||||
});
|
||||
|
||||
await tx
|
||||
.insert(systemSettings)
|
||||
.values({
|
||||
key,
|
||||
value: nextValue,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: session.user.id,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: systemSettings.key,
|
||||
set: {
|
||||
value: nextValue,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: session.user.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if ("agentWorkflowDefaultModelId" in parsedSnapshot.siteSettings) {
|
||||
const [existingSiteSettings] = await tx.select().from(siteSettings).limit(1);
|
||||
const nextAgentWorkflowDefaultModelId =
|
||||
String(parsedSnapshot.siteSettings.agentWorkflowDefaultModelId || "").trim() || null;
|
||||
|
||||
if (existingSiteSettings) {
|
||||
await tx
|
||||
.update(siteSettings)
|
||||
.set({
|
||||
agentWorkflowDefaultModelId: nextAgentWorkflowDefaultModelId,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: session.user.id,
|
||||
})
|
||||
.where(eq(siteSettings.id, existingSiteSettings.id));
|
||||
} else {
|
||||
await tx.insert(siteSettings).values({
|
||||
siteName: "AI Chatbot",
|
||||
agentWorkflowDefaultModelId: nextAgentWorkflowDefaultModelId,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: session.user.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [preRestoreSnapshot];
|
||||
});
|
||||
|
||||
clearScopedSiteSettingsCache();
|
||||
|
||||
return NextResponse.json({
|
||||
restoredSnapshotId: body.snapshotId,
|
||||
backupSnapshotId: backupSnapshot?.id ?? null,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) {
|
||||
return error.toResponse();
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "请求参数不合法",
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
return new ChatSDKError("offline:admin").toResponse();
|
||||
}
|
||||
}
|
||||
@ -5,13 +5,11 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
||||
import { getEnabledAiModelsWithProvider, getSystemSetting, upsertMediaAsset } from "@/lib/db/queries";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
import { getEnabledAiModelsWithProvider, getSystemSetting } from "@/lib/db/queries";
|
||||
import {
|
||||
AGENT_WORKFLOW_MATERIAL_API_CONFIG_KEY,
|
||||
normalizeAgentWorkflowMaterialApiConfig,
|
||||
} from "@/lib/agents/workflow-material-config";
|
||||
import { analyzeWorkflowMaterialAppearanceFromImage } from "@/lib/agents/workflow-material-appearance";
|
||||
import {
|
||||
AGENT_WORKFLOW_GOODS_INFO_API_CONFIG_KEY,
|
||||
normalizeAgentWorkflowGoodsInfoApiConfig,
|
||||
@ -29,6 +27,7 @@ const querySchema = z.object({
|
||||
|
||||
const QWEN_VL_MODEL_MATCHER = /(qwen|千问|通义).*(vl|vision)|qwen3-vl|qwen-vl/i;
|
||||
const FUNCTIONAL_IMAGE_HINT_REGEX = /开门|开柜|柜门|抽屉|打开|开合|功能|展示|收纳|储物|细节/i;
|
||||
const GOODS_INFO_FETCH_TIMEOUT_MS = 1500;
|
||||
|
||||
type ExternalImageRecord = {
|
||||
key?: string;
|
||||
@ -76,6 +75,18 @@ type ExternalGoodsInfoResponse = {
|
||||
data?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
type MaterialSearchImage = {
|
||||
id: string;
|
||||
key: string;
|
||||
label: string;
|
||||
fileName: string;
|
||||
imageUrl: string;
|
||||
assetId: string | null;
|
||||
mimeType: string;
|
||||
group: "fixed" | "other";
|
||||
sortOrder: number;
|
||||
};
|
||||
|
||||
function normalizeBaseUrl(value: string) {
|
||||
return String(value || "").trim().replace(/\/+$/, "");
|
||||
}
|
||||
@ -191,6 +202,7 @@ async function fetchGoodsInfoByKeyword(params: {
|
||||
method: "GET",
|
||||
headers: commonHeaders,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(GOODS_INFO_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
const result = (await response.json().catch(() => ({}))) as ExternalGoodsInfoResponse;
|
||||
if (response.ok && result.success === true && result.data && typeof result.data === "object") {
|
||||
@ -467,18 +479,9 @@ async function analyzeFunctionalShowcaseImage(params: {
|
||||
}
|
||||
|
||||
async function recommendMaterialImageIds(params: {
|
||||
images: Array<{
|
||||
id: string;
|
||||
key: string;
|
||||
label: string;
|
||||
fileName: string;
|
||||
imageUrl: string;
|
||||
assetId: string | null;
|
||||
mimeType: string;
|
||||
group: "fixed" | "other";
|
||||
sortOrder: number;
|
||||
}>;
|
||||
images: MaterialSearchImage[];
|
||||
requiredCount: number;
|
||||
visionAnalysisEnabled?: boolean;
|
||||
}) {
|
||||
const requiredCount = Math.max(1, Math.min(4, Math.round(params.requiredCount)));
|
||||
const selectedIds: string[] = [];
|
||||
@ -517,7 +520,11 @@ async function recommendMaterialImageIds(params: {
|
||||
}
|
||||
|
||||
const functionalRemainingNeedCount = requiredCount - selectedIds.length;
|
||||
if (functionalRemainingNeedCount > 0 && otherImages.length > 0) {
|
||||
if (
|
||||
params.visionAnalysisEnabled === true &&
|
||||
functionalRemainingNeedCount > 0 &&
|
||||
otherImages.length > 0
|
||||
) {
|
||||
const analyzableImages = otherImages
|
||||
.filter((image) => !selectedIds.includes(image.id))
|
||||
.slice(0, 6);
|
||||
@ -572,100 +579,40 @@ async function recommendMaterialImageIds(params: {
|
||||
return selectedIds.slice(0, requiredCount);
|
||||
}
|
||||
|
||||
function sanitizeFilenamePart(value: string) {
|
||||
return String(value || "")
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]+/g, "-")
|
||||
.replace(/\s+/g, "-")
|
||||
.slice(0, 80);
|
||||
function inferMimeTypeFromFilename(filename: string) {
|
||||
const normalized = String(filename || "").toLowerCase();
|
||||
if (normalized.endsWith(".jpg") || normalized.endsWith(".jpeg")) return "image/jpeg";
|
||||
if (normalized.endsWith(".webp")) return "image/webp";
|
||||
if (normalized.endsWith(".gif")) return "image/gif";
|
||||
return "image/png";
|
||||
}
|
||||
|
||||
function getExtensionFromMimeType(mimeType: string) {
|
||||
const normalized = String(mimeType || "").toLowerCase();
|
||||
if (normalized.includes("png")) return "png";
|
||||
if (normalized.includes("webp")) return "webp";
|
||||
if (normalized.includes("jpeg") || normalized.includes("jpg")) return "jpg";
|
||||
if (normalized.includes("gif")) return "gif";
|
||||
return "png";
|
||||
}
|
||||
|
||||
function ensureFilenameWithExtension(filename: string, mimeType: string) {
|
||||
const trimmed = sanitizeFilenamePart(filename) || `workflow-material-${Date.now()}`;
|
||||
if (/\.[a-z0-9]+$/i.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
return `${trimmed}.${getExtensionFromMimeType(mimeType)}`;
|
||||
}
|
||||
|
||||
async function importExternalImage(params: {
|
||||
userId: string;
|
||||
function mapExternalImage(params: {
|
||||
keyword: string;
|
||||
source: "primary" | "secondary";
|
||||
matchedSku: string;
|
||||
productModel?: string | null;
|
||||
group: "fixed" | "other";
|
||||
sortOrder: number;
|
||||
image: ExternalImageRecord;
|
||||
}) {
|
||||
}): MaterialSearchImage | null {
|
||||
const downloadUrl = String(params.image.downloadUrl || "").trim();
|
||||
if (!downloadUrl) return null;
|
||||
|
||||
const imageResponse = await fetch(downloadUrl, {
|
||||
cache: "no-store",
|
||||
redirect: "follow",
|
||||
});
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error(`下载图片失败(${imageResponse.status})`);
|
||||
}
|
||||
|
||||
const imageBuffer = await imageResponse.arrayBuffer();
|
||||
const mimeType =
|
||||
String(imageResponse.headers.get("content-type") || "").split(";")[0].trim() || "image/png";
|
||||
const filename = ensureFilenameWithExtension(
|
||||
params.image.fileName ||
|
||||
params.image.label ||
|
||||
`${params.matchedSku || params.keyword}-${params.group}-${params.sortOrder + 1}`,
|
||||
mimeType
|
||||
);
|
||||
const uploaded = await uploadFile(filename, imageBuffer);
|
||||
|
||||
let assetId: string | null = null;
|
||||
try {
|
||||
const asset = await upsertMediaAsset({
|
||||
userId: params.userId,
|
||||
mediaType: "image",
|
||||
sourceType: "agent_workflow_material_search",
|
||||
status: "ready",
|
||||
originalUrl: uploaded.url,
|
||||
previewUrl: uploaded.url,
|
||||
thumbnailUrl: uploaded.url,
|
||||
mimeType: uploaded.contentType || mimeType,
|
||||
displayName: filename,
|
||||
sourceTable: "agent_workflow_material_search",
|
||||
metadata: {
|
||||
keyword: params.keyword,
|
||||
source: params.source,
|
||||
matchedSku: params.matchedSku,
|
||||
productModel: params.productModel || null,
|
||||
group: params.group,
|
||||
externalKey: String(params.image.key || "").trim() || null,
|
||||
fileSize: Number(params.image.fileSize || 0) || null,
|
||||
pathname: uploaded.pathname,
|
||||
},
|
||||
});
|
||||
assetId = asset?.id ?? null;
|
||||
} catch (error) {
|
||||
console.warn("[Agent Workflow Material Search] Failed to register media asset:", error);
|
||||
}
|
||||
const filename =
|
||||
String(params.image.fileName || "").trim() ||
|
||||
String(params.image.label || "").trim() ||
|
||||
`${params.matchedSku || params.keyword}-${params.group}-${params.sortOrder + 1}.png`;
|
||||
const identityHash = createHash("sha1")
|
||||
.update(`${params.group}:${params.sortOrder}:${downloadUrl}`, "utf8")
|
||||
.digest("hex")
|
||||
.slice(0, 12);
|
||||
|
||||
return {
|
||||
id: assetId || `${params.group}-${params.sortOrder + 1}`,
|
||||
id: `external-${params.group}-${params.sortOrder + 1}-${identityHash}`,
|
||||
key: String(params.image.key || "").trim() || `${params.group}-${params.sortOrder + 1}`,
|
||||
label: String(params.image.label || "").trim() || `图片${params.sortOrder + 1}`,
|
||||
fileName: filename,
|
||||
imageUrl: uploaded.url,
|
||||
assetId,
|
||||
mimeType: uploaded.contentType || mimeType,
|
||||
imageUrl: downloadUrl,
|
||||
assetId: null,
|
||||
mimeType: inferMimeTypeFromFilename(filename),
|
||||
group: params.group,
|
||||
sortOrder: params.sortOrder,
|
||||
};
|
||||
@ -704,9 +651,6 @@ export async function GET(request: NextRequest) {
|
||||
appearanceRecognitionEnabled:
|
||||
request.nextUrl.searchParams.get("appearanceRecognitionEnabled") || undefined,
|
||||
});
|
||||
const appearanceRecognitionEnabled =
|
||||
parsed.appearanceRecognitionEnabled !== "false" &&
|
||||
parsed.appearanceRecognitionEnabled !== "0";
|
||||
|
||||
const setting = await getSystemSetting({ key: AGENT_WORKFLOW_MATERIAL_API_CONFIG_KEY });
|
||||
const config = normalizeAgentWorkflowMaterialApiConfig(setting?.value);
|
||||
@ -731,6 +675,16 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const normalizedKeyword = parsed.keyword.trim().toUpperCase();
|
||||
const queryType = parsed.queryType === "spu" ? "spu" : "sku";
|
||||
const goodsInfoPromise =
|
||||
queryType === "sku"
|
||||
? fetchGoodsInfoByKeyword({
|
||||
keyword: normalizedKeyword,
|
||||
config: goodsInfoConfig,
|
||||
}).catch((error) => {
|
||||
console.warn("[Agent Workflow Material Search] Goods info fetch failed:", error);
|
||||
return null;
|
||||
})
|
||||
: Promise.resolve(null);
|
||||
const upstreamUrl = `${normalizeBaseUrl(
|
||||
config.baseUrl
|
||||
)}/standard-model-white-background?resourceType=white-background&${queryType}=${encodeURIComponent(normalizedKeyword)}`;
|
||||
@ -802,16 +756,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const matchedSku = String(upstreamResult.data.sku || normalizedKeyword).trim() || normalizedKeyword;
|
||||
const productModel = String(upstreamResult.data.productModel || "").trim() || null;
|
||||
const goodsInfo =
|
||||
queryType === "sku"
|
||||
? await fetchGoodsInfoByKeyword({
|
||||
keyword: normalizedKeyword,
|
||||
config: goodsInfoConfig,
|
||||
}).catch((error) => {
|
||||
console.warn("[Agent Workflow Material Search] Goods info fetch failed:", error);
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const goodsInfo = await goodsInfoPromise;
|
||||
const requiredCount = Number.isFinite(Number(parsed.requiredCount))
|
||||
? Math.max(1, Math.min(4, Math.round(Number(parsed.requiredCount))))
|
||||
: null;
|
||||
@ -822,62 +767,34 @@ export async function GET(request: NextRequest) {
|
||||
? upstreamResult.data.whiteBackground?.other || []
|
||||
: [];
|
||||
|
||||
const importedImages = (
|
||||
await Promise.all([
|
||||
...fixedImages.map((image, index) =>
|
||||
importExternalImage({
|
||||
userId: session.user.id,
|
||||
keyword: normalizedKeyword,
|
||||
source: parsed.source || "primary",
|
||||
matchedSku,
|
||||
productModel,
|
||||
group: "fixed",
|
||||
sortOrder: index,
|
||||
image,
|
||||
}).catch((error) => {
|
||||
console.warn("[Agent Workflow Material Search] Fixed image import failed:", error);
|
||||
return null;
|
||||
})
|
||||
),
|
||||
...otherImages.map((image, index) =>
|
||||
importExternalImage({
|
||||
userId: session.user.id,
|
||||
keyword: normalizedKeyword,
|
||||
source: parsed.source || "primary",
|
||||
matchedSku,
|
||||
productModel,
|
||||
group: "other",
|
||||
sortOrder: fixedImages.length + index,
|
||||
image,
|
||||
}).catch((error) => {
|
||||
console.warn("[Agent Workflow Material Search] Other image import failed:", error);
|
||||
return null;
|
||||
})
|
||||
),
|
||||
])
|
||||
).filter(
|
||||
(
|
||||
item
|
||||
): item is {
|
||||
id: string;
|
||||
key: string;
|
||||
label: string;
|
||||
fileName: string;
|
||||
imageUrl: string;
|
||||
assetId: string | null;
|
||||
mimeType: string;
|
||||
group: "fixed" | "other";
|
||||
sortOrder: number;
|
||||
} => Boolean(item)
|
||||
);
|
||||
const externalImages = [
|
||||
...fixedImages.map((image, index) =>
|
||||
mapExternalImage({
|
||||
keyword: normalizedKeyword,
|
||||
matchedSku,
|
||||
group: "fixed",
|
||||
sortOrder: index,
|
||||
image,
|
||||
})
|
||||
),
|
||||
...otherImages.map((image, index) =>
|
||||
mapExternalImage({
|
||||
keyword: normalizedKeyword,
|
||||
matchedSku,
|
||||
group: "other",
|
||||
sortOrder: fixedImages.length + index,
|
||||
image,
|
||||
})
|
||||
),
|
||||
].filter((item): item is MaterialSearchImage => Boolean(item));
|
||||
|
||||
if (importedImages.length === 0) {
|
||||
if (externalImages.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code: "IMAGE_IMPORT_FAILED",
|
||||
message: "已获取到素材记录,但图片导入失败,请稍后重试",
|
||||
code: "IMAGE_URL_NOT_FOUND",
|
||||
message: "已获取到素材记录,但未返回可用图片地址,请稍后重试",
|
||||
},
|
||||
},
|
||||
{ status: 502 }
|
||||
@ -886,26 +803,10 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const recommendedImageIds = requiredCount
|
||||
? await recommendMaterialImageIds({
|
||||
images: importedImages,
|
||||
images: externalImages,
|
||||
requiredCount,
|
||||
})
|
||||
: [];
|
||||
const firstImageAppearanceSummary = appearanceRecognitionEnabled
|
||||
? await analyzeWorkflowMaterialAppearanceFromImage(
|
||||
importedImages[0]?.imageUrl || ""
|
||||
).catch((error) => {
|
||||
console.warn("[Agent Workflow Material Search] Appearance analysis failed:", error);
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const annotatedImages = importedImages.map((image, index) =>
|
||||
index === 0 && firstImageAppearanceSummary
|
||||
? {
|
||||
...image,
|
||||
appearanceSummary: firstImageAppearanceSummary,
|
||||
}
|
||||
: image
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
@ -917,10 +818,10 @@ export async function GET(request: NextRequest) {
|
||||
materialId: String(upstreamResult.data.materialId || "").trim() || null,
|
||||
productModel,
|
||||
zipUrl: String(upstreamResult.data.downloadUrls?.zip || "").trim() || null,
|
||||
fixedCount: annotatedImages.filter((item) => item.group === "fixed").length,
|
||||
otherCount: annotatedImages.filter((item) => item.group === "other").length,
|
||||
totalCount: annotatedImages.length,
|
||||
images: annotatedImages,
|
||||
fixedCount: externalImages.filter((item) => item.group === "fixed").length,
|
||||
otherCount: externalImages.filter((item) => item.group === "other").length,
|
||||
totalCount: externalImages.length,
|
||||
images: externalImages,
|
||||
recommendedImageIds,
|
||||
skuOptions: [],
|
||||
goodsInfo: goodsInfo
|
||||
@ -931,13 +832,8 @@ export async function GET(request: NextRequest) {
|
||||
designer: goodsInfo.designer,
|
||||
buyer: goodsInfo.buyer,
|
||||
boardType: goodsInfo.boardType,
|
||||
appearanceSummary: firstImageAppearanceSummary,
|
||||
}
|
||||
: firstImageAppearanceSummary
|
||||
? {
|
||||
appearanceSummary: firstImageAppearanceSummary,
|
||||
}
|
||||
: null,
|
||||
: null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@ -1,7 +1,14 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { aiProvider, siteSettings, systemSettingHistory, systemSettings } from "@/lib/db/schema";
|
||||
import {
|
||||
aiProvider,
|
||||
siteSettings,
|
||||
systemSettingHistory,
|
||||
systemSettingSnapshot,
|
||||
systemSettings,
|
||||
} from "@/lib/db/schema";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { isAgentWorkflowAdminType, isSiteAdminType } from "@/lib/middleware/admin";
|
||||
@ -35,8 +42,10 @@ import {
|
||||
AGENT_WORKFLOW_UI_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_PROMPT_FRAGMENT_MAX_LENGTH,
|
||||
defaultAgentWorkflowUiConfig,
|
||||
isAgentWorkflowDestructiveChangeSignificant,
|
||||
normalizeAgentWorkflowStepOrdering,
|
||||
normalizeAgentWorkflowUiConfig,
|
||||
summarizeAgentWorkflowDestructiveChange,
|
||||
} from "@/lib/agents/workflow-ui-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_BRAND_MODEL_CONFIG_KEY,
|
||||
@ -105,6 +114,11 @@ import {
|
||||
PUBLIC_SITE_SETTINGS_CACHE_TTL_MS,
|
||||
setScopedSiteSettingsCache,
|
||||
} from "@/lib/site-settings/public-cache";
|
||||
import {
|
||||
AGENT_WORKFLOW_SNAPSHOT_SCOPE,
|
||||
createSystemSettingSnapshotData,
|
||||
summarizeSystemSettingSnapshotData,
|
||||
} from "@/lib/system-settings/snapshot";
|
||||
import {
|
||||
getHomeChatAnimationHtmlBytes,
|
||||
HOME_CHAT_ANIMATION_CONFIG_KEY,
|
||||
@ -1612,6 +1626,11 @@ const updateSchema = z.object({
|
||||
agentWorkflowSettingsBaseSignatures: z
|
||||
.record(z.string().trim().min(1).max(128))
|
||||
.optional(),
|
||||
agentWorkflowDestructiveChangeApproval: z
|
||||
.object({
|
||||
token: z.string().trim().min(16).max(128),
|
||||
})
|
||||
.optional(),
|
||||
agentWorkflowUiConfig: z
|
||||
.object({
|
||||
inputOptions: z
|
||||
@ -1965,6 +1984,7 @@ export async function PUT(request: NextRequest) {
|
||||
"agentPresetLibraryConfig",
|
||||
"agentWorkflowSettingsBaseSignature",
|
||||
"agentWorkflowSettingsBaseSignatures",
|
||||
"agentWorkflowDestructiveChangeApproval",
|
||||
"agentWorkflowUiConfig",
|
||||
"agentWorkflowMaterialApiConfig",
|
||||
"agentWorkflowGoodsInfoApiConfig",
|
||||
@ -1992,6 +2012,7 @@ export async function PUT(request: NextRequest) {
|
||||
agentSecondaryTypeConfig,
|
||||
agentWorkflowSettingsBaseSignature,
|
||||
agentWorkflowSettingsBaseSignatures,
|
||||
agentWorkflowDestructiveChangeApproval,
|
||||
agentWorkflowUiConfig,
|
||||
agentWorkflowMaterialApiConfig,
|
||||
agentWorkflowGoodsInfoApiConfig,
|
||||
@ -2033,6 +2054,29 @@ export async function PUT(request: NextRequest) {
|
||||
.map(([field]) => field);
|
||||
|
||||
const isUpdatingAgentWorkflowSettings = updatedAgentWorkflowFields.length > 0;
|
||||
let currentWorkflowValues = new Map<string, unknown>();
|
||||
let currentWorkflowSectionSignatures:
|
||||
| ReturnType<typeof createAgentWorkflowSettingsSectionSignatures>
|
||||
| null = null;
|
||||
let workflowDestructiveChangeSummary:
|
||||
| ReturnType<typeof summarizeAgentWorkflowDestructiveChange>
|
||||
| null = null;
|
||||
let agentWorkflowSnapshotCreated = false;
|
||||
|
||||
const createAgentWorkflowDestructiveChangeApprovalToken = (params: {
|
||||
currentSignature: string;
|
||||
nextConfig: unknown;
|
||||
summary: ReturnType<typeof summarizeAgentWorkflowDestructiveChange>;
|
||||
}) =>
|
||||
createHash("sha256")
|
||||
.update(
|
||||
JSON.stringify({
|
||||
currentSignature: params.currentSignature,
|
||||
nextConfig: params.nextConfig,
|
||||
summary: params.summary,
|
||||
})
|
||||
)
|
||||
.digest("hex");
|
||||
|
||||
if (isUpdatingAgentWorkflowSettings) {
|
||||
if (!agentWorkflowSettingsBaseSignatures && !agentWorkflowSettingsBaseSignature) {
|
||||
@ -2052,10 +2096,10 @@ export async function PUT(request: NextRequest) {
|
||||
})
|
||||
.from(systemSettings)
|
||||
.where(inArray(systemSettings.key, [...AGENT_WORKFLOW_SETTINGS_CONFLICT_KEYS]));
|
||||
const currentWorkflowValues = new Map<string, unknown>(
|
||||
currentWorkflowValues = new Map<string, unknown>(
|
||||
currentWorkflowRows.map((row) => [row.key, row.value])
|
||||
);
|
||||
const currentSectionSignatures =
|
||||
currentWorkflowSectionSignatures =
|
||||
createAgentWorkflowSettingsSectionSignatures(currentWorkflowValues);
|
||||
const currentWorkflowSignature =
|
||||
agentWorkflowSettingsBaseSignature && !agentWorkflowSettingsBaseSignatures
|
||||
@ -2064,7 +2108,8 @@ export async function PUT(request: NextRequest) {
|
||||
const hasWorkflowConflict = agentWorkflowSettingsBaseSignatures
|
||||
? updatedAgentWorkflowFields.some(
|
||||
(field) =>
|
||||
currentSectionSignatures[field] !== agentWorkflowSettingsBaseSignatures[field]
|
||||
currentWorkflowSectionSignatures![field] !==
|
||||
agentWorkflowSettingsBaseSignatures[field]
|
||||
)
|
||||
: currentWorkflowSignature !== agentWorkflowSettingsBaseSignature;
|
||||
|
||||
@ -2077,6 +2122,44 @@ export async function PUT(request: NextRequest) {
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
if (agentWorkflowUiConfig !== undefined) {
|
||||
const currentWorkflowUiConfig = normalizeAgentWorkflowUiConfig(
|
||||
currentWorkflowValues.get(AGENT_WORKFLOW_UI_CONFIG_KEY)
|
||||
);
|
||||
const nextWorkflowUiConfig = normalizeAgentWorkflowUiConfig(agentWorkflowUiConfig);
|
||||
workflowDestructiveChangeSummary = summarizeAgentWorkflowDestructiveChange(
|
||||
currentWorkflowUiConfig,
|
||||
nextWorkflowUiConfig
|
||||
);
|
||||
|
||||
if (isAgentWorkflowDestructiveChangeSignificant(workflowDestructiveChangeSummary)) {
|
||||
const approvalToken = createAgentWorkflowDestructiveChangeApprovalToken({
|
||||
currentSignature:
|
||||
currentWorkflowSectionSignatures.agentWorkflowUiConfig ||
|
||||
createAgentWorkflowSettingsSignature(
|
||||
new Map([[AGENT_WORKFLOW_UI_CONFIG_KEY, currentWorkflowUiConfig]])
|
||||
),
|
||||
nextConfig: nextWorkflowUiConfig,
|
||||
summary: workflowDestructiveChangeSummary,
|
||||
});
|
||||
|
||||
if (agentWorkflowDestructiveChangeApproval?.token !== approvalToken) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"本次保存会删除大量风格化工作流节点或清空关键内容,已被系统拦截。请确认后再次提交。",
|
||||
requiresDestructiveChangeApproval: true,
|
||||
destructiveChange: {
|
||||
...workflowDestructiveChangeSummary,
|
||||
approvalToken,
|
||||
},
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const persistSystemSettingWithHistory = async (
|
||||
@ -2136,6 +2219,47 @@ export async function PUT(request: NextRequest) {
|
||||
});
|
||||
};
|
||||
|
||||
const createAgentWorkflowScopeSnapshot = async () => {
|
||||
if (!isUpdatingAgentWorkflowSettings || agentWorkflowSnapshotCreated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [currentSiteSettings] = await db
|
||||
.select({
|
||||
agentWorkflowDefaultModelId: siteSettings.agentWorkflowDefaultModelId,
|
||||
})
|
||||
.from(siteSettings)
|
||||
.limit(1);
|
||||
const snapshotData = createSystemSettingSnapshotData(
|
||||
AGENT_WORKFLOW_SNAPSHOT_SCOPE,
|
||||
currentWorkflowValues,
|
||||
{
|
||||
agentWorkflowDefaultModelId:
|
||||
String(currentSiteSettings?.agentWorkflowDefaultModelId || "").trim() || null,
|
||||
}
|
||||
);
|
||||
const [snapshot] = await db
|
||||
.insert(systemSettingSnapshot)
|
||||
.values({
|
||||
scope: AGENT_WORKFLOW_SNAPSHOT_SCOPE,
|
||||
label: workflowDestructiveChangeSummary
|
||||
? "before-destructive-agent-workflow-save"
|
||||
: "before-agent-workflow-save",
|
||||
summary: {
|
||||
...summarizeSystemSettingSnapshotData(snapshotData),
|
||||
updatedFields: updatedAgentWorkflowFields,
|
||||
destructiveChange: workflowDestructiveChangeSummary,
|
||||
},
|
||||
data: snapshotData,
|
||||
createdAt: new Date(),
|
||||
createdBy: session.user.id,
|
||||
})
|
||||
.returning({ id: systemSettingSnapshot.id });
|
||||
|
||||
agentWorkflowSnapshotCreated = true;
|
||||
return snapshot?.id ?? null;
|
||||
};
|
||||
|
||||
const persistHomeAnimationConfig = async () => {
|
||||
if (homeAnimationConfig === undefined) {
|
||||
return;
|
||||
@ -2175,6 +2299,8 @@ export async function PUT(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
await createAgentWorkflowScopeSnapshot();
|
||||
|
||||
// 查找现有设置
|
||||
const [existing] = await db.select().from(siteSettings).limit(1);
|
||||
|
||||
@ -798,6 +798,139 @@ export function countAgentWorkflowOptionTree(
|
||||
return flattenAgentWorkflowOptionTree(options).length;
|
||||
}
|
||||
|
||||
export interface AgentWorkflowDestructiveChangeSummary {
|
||||
totalBeforeOptionCount: number;
|
||||
totalAfterOptionCount: number;
|
||||
removedOptionCount: number;
|
||||
removedEnabledOptionCount: number;
|
||||
promptClearedCount: number;
|
||||
previewClearedCount: number;
|
||||
removedOptionSamples: string[];
|
||||
promptClearedSamples: string[];
|
||||
previewClearedSamples: string[];
|
||||
}
|
||||
|
||||
const AGENT_WORKFLOW_DESTRUCTIVE_CHANGE_SAMPLE_LIMIT = 12;
|
||||
|
||||
function collectAgentWorkflowAuditEntries(
|
||||
steps: AgentWorkflowStepUiConfig[],
|
||||
stepKeyPath: string[] = [],
|
||||
stepLabelPath: string[] = [],
|
||||
output: Array<{
|
||||
identityPath: string;
|
||||
displayPath: string;
|
||||
enabled: boolean;
|
||||
hasPrompt: boolean;
|
||||
hasPreview: boolean;
|
||||
}> = []
|
||||
) {
|
||||
for (const step of [...(steps || [])].sort((left, right) => left.sortOrder - right.sortOrder)) {
|
||||
const nextStepKeyPath = [...stepKeyPath, `s:${String(step.key || "").trim()}`];
|
||||
const nextStepLabelPath = [
|
||||
...stepLabelPath,
|
||||
String(step.title || step.key || "未命名模块").trim() || "未命名模块",
|
||||
];
|
||||
|
||||
const visitOptions = (
|
||||
options: AgentWorkflowOptionUiConfig[],
|
||||
parentKeyPath: string[],
|
||||
parentLabelPath: string[]
|
||||
) => {
|
||||
for (const option of [...(options || [])].sort((left, right) => left.sortOrder - right.sortOrder)) {
|
||||
const optionKey = String(option.key || "").trim() || "option";
|
||||
const optionLabel =
|
||||
String(option.buttonName || option.key || "未命名卡片").trim() || "未命名卡片";
|
||||
const nextKeyPath = [...parentKeyPath, `o:${optionKey}`];
|
||||
const nextLabelPath = [...parentLabelPath, optionLabel];
|
||||
output.push({
|
||||
identityPath: nextKeyPath.join(">"),
|
||||
displayPath: nextLabelPath.join(" > "),
|
||||
enabled: option.enabled !== false,
|
||||
hasPrompt: Boolean(String(option.promptFragment || "").trim()),
|
||||
hasPreview: hasAgentWorkflowOptionOwnPreview(option),
|
||||
});
|
||||
visitOptions(option.children || [], nextKeyPath, nextLabelPath);
|
||||
}
|
||||
};
|
||||
|
||||
visitOptions(step.options || [], nextStepKeyPath, nextStepLabelPath);
|
||||
collectAgentWorkflowAuditEntries(
|
||||
step.children || [],
|
||||
nextStepKeyPath,
|
||||
nextStepLabelPath,
|
||||
output
|
||||
);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export function summarizeAgentWorkflowDestructiveChange(
|
||||
beforeConfig: AgentWorkflowUiConfig,
|
||||
afterConfig: AgentWorkflowUiConfig
|
||||
): AgentWorkflowDestructiveChangeSummary {
|
||||
const beforeEntries = collectAgentWorkflowAuditEntries(beforeConfig.steps || []);
|
||||
const afterEntries = collectAgentWorkflowAuditEntries(afterConfig.steps || []);
|
||||
const afterByIdentityPath = new Map(
|
||||
afterEntries.map((entry) => [entry.identityPath, entry])
|
||||
);
|
||||
|
||||
const removedEntries = beforeEntries.filter(
|
||||
(entry) => !afterByIdentityPath.has(entry.identityPath)
|
||||
);
|
||||
const promptClearedEntries = beforeEntries.filter((entry) => {
|
||||
const nextEntry = afterByIdentityPath.get(entry.identityPath);
|
||||
return Boolean(nextEntry && entry.hasPrompt && !nextEntry.hasPrompt);
|
||||
});
|
||||
const previewClearedEntries = beforeEntries.filter((entry) => {
|
||||
const nextEntry = afterByIdentityPath.get(entry.identityPath);
|
||||
return Boolean(nextEntry && entry.hasPreview && !nextEntry.hasPreview);
|
||||
});
|
||||
|
||||
return {
|
||||
totalBeforeOptionCount: beforeEntries.length,
|
||||
totalAfterOptionCount: afterEntries.length,
|
||||
removedOptionCount: removedEntries.length,
|
||||
removedEnabledOptionCount: removedEntries.filter((entry) => entry.enabled).length,
|
||||
promptClearedCount: promptClearedEntries.length,
|
||||
previewClearedCount: previewClearedEntries.length,
|
||||
removedOptionSamples: removedEntries
|
||||
.slice(0, AGENT_WORKFLOW_DESTRUCTIVE_CHANGE_SAMPLE_LIMIT)
|
||||
.map((entry) => entry.displayPath),
|
||||
promptClearedSamples: promptClearedEntries
|
||||
.slice(0, AGENT_WORKFLOW_DESTRUCTIVE_CHANGE_SAMPLE_LIMIT)
|
||||
.map((entry) => entry.displayPath),
|
||||
previewClearedSamples: previewClearedEntries
|
||||
.slice(0, AGENT_WORKFLOW_DESTRUCTIVE_CHANGE_SAMPLE_LIMIT)
|
||||
.map((entry) => entry.displayPath),
|
||||
};
|
||||
}
|
||||
|
||||
export function isAgentWorkflowDestructiveChangeSignificant(
|
||||
summary: AgentWorkflowDestructiveChangeSummary
|
||||
) {
|
||||
if (summary.removedEnabledOptionCount >= 10) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (summary.removedOptionCount >= 20) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
summary.totalBeforeOptionCount > 0 &&
|
||||
summary.removedOptionCount / summary.totalBeforeOptionCount >= 0.03
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (summary.promptClearedCount >= 10) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return summary.previewClearedCount >= 5;
|
||||
}
|
||||
|
||||
export function hasAgentWorkflowOptionOwnPreview(
|
||||
option: AgentWorkflowOptionUiConfig
|
||||
): boolean {
|
||||
|
||||
23
lib/db/migrations/0085_add_system_setting_snapshots.sql
Normal file
23
lib/db/migrations/0085_add_system_setting_snapshots.sql
Normal file
@ -0,0 +1,23 @@
|
||||
CREATE TABLE IF NOT EXISTS "SystemSettingSnapshot" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"scope" varchar(64) NOT NULL,
|
||||
"label" varchar(128),
|
||||
"summary" jsonb,
|
||||
"data" jsonb NOT NULL,
|
||||
"createdAt" timestamp DEFAULT now() NOT NULL,
|
||||
"createdBy" uuid
|
||||
);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
ALTER TABLE "SystemSettingSnapshot"
|
||||
ADD CONSTRAINT "SystemSettingSnapshot_createdBy_User_id_fk"
|
||||
FOREIGN KEY ("createdBy") REFERENCES "public"."User"("id")
|
||||
ON DELETE NO ACTION
|
||||
ON UPDATE NO ACTION;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "SystemSettingSnapshot_scope_createdAt_idx"
|
||||
ON "SystemSettingSnapshot" ("scope", "createdAt" DESC);
|
||||
@ -498,6 +498,13 @@
|
||||
"when": 1779797137842,
|
||||
"tag": "0084_optimize_featured_home_query",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 71,
|
||||
"version": "7",
|
||||
"when": 1780075200000,
|
||||
"tag": "0085_add_system_setting_snapshots",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -260,6 +260,18 @@ export const systemSettingHistory = pgTable("SystemSettingHistory", {
|
||||
|
||||
export type SystemSettingHistory = InferSelectModel<typeof systemSettingHistory>;
|
||||
|
||||
export const systemSettingSnapshot = pgTable("SystemSettingSnapshot", {
|
||||
id: uuid("id").primaryKey().notNull().defaultRandom(),
|
||||
scope: varchar("scope", { length: 64 }).notNull(),
|
||||
label: varchar("label", { length: 128 }),
|
||||
summary: jsonb("summary"),
|
||||
data: jsonb("data").notNull(),
|
||||
createdAt: timestamp("createdAt").notNull().defaultNow(),
|
||||
createdBy: uuid("createdBy").references(() => user.id),
|
||||
});
|
||||
|
||||
export type SystemSettingSnapshot = InferSelectModel<typeof systemSettingSnapshot>;
|
||||
|
||||
export const dingTalkNotificationTask = pgTable("DingTalkNotificationTask", {
|
||||
id: uuid("id").primaryKey().notNull().defaultRandom(),
|
||||
title: varchar("title", { length: 100 }).notNull(),
|
||||
|
||||
132
lib/system-settings/snapshot.ts
Normal file
132
lib/system-settings/snapshot.ts
Normal file
@ -0,0 +1,132 @@
|
||||
import {
|
||||
AGENT_PRESET_LIBRARY_CONFIG_KEY,
|
||||
} from "@/lib/agents/preset-library-config";
|
||||
import {
|
||||
AGENT_PSD_TEMPLATE_SECONDARY_CATEGORY_CONFIG_KEY,
|
||||
} from "@/lib/agents/psd-template-secondary-category-config";
|
||||
import {
|
||||
AGENT_PSD_TEXT_COLOR_CONFIG_KEY,
|
||||
} from "@/lib/agents/psd-text-color-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_BRAND_MODEL_CONFIG_KEY,
|
||||
} from "@/lib/agents/workflow-brand-model-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_GOODS_INFO_API_CONFIG_KEY,
|
||||
} from "@/lib/agents/workflow-goods-info-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_MATERIAL_API_CONFIG_KEY,
|
||||
} from "@/lib/agents/workflow-material-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY,
|
||||
} from "@/lib/agents/workflow-showcase-config";
|
||||
import {
|
||||
AGENT_WORKFLOW_UI_CONFIG_KEY,
|
||||
} from "@/lib/agents/workflow-ui-config";
|
||||
|
||||
export const AGENT_WORKFLOW_SNAPSHOT_SCOPE = "agent-workflow";
|
||||
|
||||
export const SYSTEM_SETTING_SNAPSHOT_SCOPES = {
|
||||
[AGENT_WORKFLOW_SNAPSHOT_SCOPE]: [
|
||||
AGENT_PRESET_LIBRARY_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_UI_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_MATERIAL_API_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_GOODS_INFO_API_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_BRAND_MODEL_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY,
|
||||
AGENT_PSD_TEXT_COLOR_CONFIG_KEY,
|
||||
AGENT_PSD_TEMPLATE_SECONDARY_CATEGORY_CONFIG_KEY,
|
||||
],
|
||||
} as const;
|
||||
|
||||
export const SYSTEM_SETTING_SNAPSHOT_SITE_FIELDS = {
|
||||
[AGENT_WORKFLOW_SNAPSHOT_SCOPE]: ["agentWorkflowDefaultModelId"],
|
||||
} as const;
|
||||
|
||||
export type SystemSettingSnapshotScope = keyof typeof SYSTEM_SETTING_SNAPSHOT_SCOPES;
|
||||
|
||||
export function getSystemSettingSnapshotScopeKeys(
|
||||
scope: SystemSettingSnapshotScope
|
||||
) {
|
||||
return SYSTEM_SETTING_SNAPSHOT_SCOPES[scope];
|
||||
}
|
||||
|
||||
export function getSystemSettingSnapshotScopeSiteFields(
|
||||
scope: SystemSettingSnapshotScope
|
||||
) {
|
||||
return SYSTEM_SETTING_SNAPSHOT_SITE_FIELDS[scope];
|
||||
}
|
||||
|
||||
export function createSystemSettingSnapshotData(
|
||||
scope: SystemSettingSnapshotScope,
|
||||
valueByKey: ReadonlyMap<string, unknown>,
|
||||
siteSettingsValues: Record<string, unknown> = {}
|
||||
) {
|
||||
const keys = getSystemSettingSnapshotScopeKeys(scope);
|
||||
const siteFields = getSystemSettingSnapshotScopeSiteFields(scope);
|
||||
return {
|
||||
version: 2,
|
||||
scope,
|
||||
systemSettings: Object.fromEntries(keys.map((key) => [key, valueByKey.get(key) ?? null])),
|
||||
siteSettings: Object.fromEntries(
|
||||
siteFields.map((field) => [field, siteSettingsValues[field] ?? null])
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function readSystemSettingSnapshotData(
|
||||
scope: SystemSettingSnapshotScope,
|
||||
rawData: unknown
|
||||
) {
|
||||
const normalized =
|
||||
rawData && typeof rawData === "object" && !Array.isArray(rawData)
|
||||
? (rawData as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
if (
|
||||
normalized.systemSettings &&
|
||||
typeof normalized.systemSettings === "object" &&
|
||||
!Array.isArray(normalized.systemSettings)
|
||||
) {
|
||||
return {
|
||||
systemSettings: normalized.systemSettings as Record<string, unknown>,
|
||||
siteSettings:
|
||||
normalized.siteSettings &&
|
||||
typeof normalized.siteSettings === "object" &&
|
||||
!Array.isArray(normalized.siteSettings)
|
||||
? (normalized.siteSettings as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
const keys = new Set<string>(getSystemSettingSnapshotScopeKeys(scope));
|
||||
return {
|
||||
systemSettings: Object.fromEntries(
|
||||
Object.entries(normalized).filter(([key]) => keys.has(key))
|
||||
),
|
||||
siteSettings: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeSystemSettingSnapshotData(
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
const systemEntries =
|
||||
data.systemSettings &&
|
||||
typeof data.systemSettings === "object" &&
|
||||
!Array.isArray(data.systemSettings)
|
||||
? Object.entries(data.systemSettings as Record<string, unknown>)
|
||||
: Object.entries(data);
|
||||
const siteEntries =
|
||||
data.siteSettings &&
|
||||
typeof data.siteSettings === "object" &&
|
||||
!Array.isArray(data.siteSettings)
|
||||
? Object.entries(data.siteSettings as Record<string, unknown>)
|
||||
: [];
|
||||
const entries = [...systemEntries, ...siteEntries];
|
||||
return {
|
||||
keyCount: entries.length,
|
||||
nonNullKeyCount: entries.filter(([, value]) => value !== null && value !== undefined).length,
|
||||
byteLength: Buffer.byteLength(JSON.stringify(data), "utf8"),
|
||||
siteFieldCount: siteEntries.length,
|
||||
};
|
||||
}
|
||||
@ -43,6 +43,8 @@
|
||||
"db:pull": "drizzle-kit pull",
|
||||
"db:check": "drizzle-kit check",
|
||||
"db:up": "drizzle-kit up",
|
||||
"db:snapshot:system-settings": "pnpm exec tsx scripts/system-settings/create-snapshot.ts",
|
||||
"db:restore:system-settings-snapshot": "pnpm exec tsx scripts/system-settings/restore-snapshot.ts",
|
||||
"poc:nanobanana": "pnpm exec tsx scripts/nanobanana-browser-poc.ts",
|
||||
"test": "export PLAYWRIGHT=True && pnpm exec playwright test",
|
||||
"storage:configure-upload-cors": "pnpm exec tsx scripts/storage/configure-direct-upload-cors.ts",
|
||||
|
||||
93
scripts/system-settings/create-snapshot.ts
Normal file
93
scripts/system-settings/create-snapshot.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import { config as loadEnv } from "dotenv";
|
||||
import { inArray } from "drizzle-orm";
|
||||
|
||||
loadEnv({ path: ".env.local" });
|
||||
|
||||
function readArg(name: string) {
|
||||
const prefix = `${name}=`;
|
||||
const match = process.argv.find((arg) => arg.startsWith(prefix));
|
||||
return match ? match.slice(prefix.length) : null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const scopeArg = readArg("--scope");
|
||||
const label = readArg("--label");
|
||||
|
||||
if (!scopeArg) {
|
||||
throw new Error("Usage: pnpm tsx scripts/system-settings/create-snapshot.ts --scope=<scope> [--label=<label>]");
|
||||
}
|
||||
|
||||
const dbModule = await import("../../lib/db");
|
||||
const schemaModule = await import("../../lib/db/schema");
|
||||
const snapshotModule = await import("../../lib/system-settings/snapshot");
|
||||
|
||||
const { db } = dbModule;
|
||||
const { siteSettings, systemSettingSnapshot, systemSettings } = schemaModule;
|
||||
const {
|
||||
createSystemSettingSnapshotData,
|
||||
getSystemSettingSnapshotScopeKeys,
|
||||
summarizeSystemSettingSnapshotData,
|
||||
} = snapshotModule;
|
||||
|
||||
const keys = getSystemSettingSnapshotScopeKeys(
|
||||
scopeArg as keyof typeof snapshotModule.SYSTEM_SETTING_SNAPSHOT_SCOPES
|
||||
);
|
||||
const rows = await db
|
||||
.select({
|
||||
key: systemSettings.key,
|
||||
value: systemSettings.value,
|
||||
})
|
||||
.from(systemSettings)
|
||||
.where(inArray(systemSettings.key, [...keys]));
|
||||
const valueByKey = new Map(rows.map((row) => [row.key, row.value]));
|
||||
const [currentSiteSettings] = await db
|
||||
.select({
|
||||
agentWorkflowDefaultModelId: siteSettings.agentWorkflowDefaultModelId,
|
||||
})
|
||||
.from(siteSettings)
|
||||
.limit(1);
|
||||
const snapshotData = createSystemSettingSnapshotData(
|
||||
scopeArg as keyof typeof snapshotModule.SYSTEM_SETTING_SNAPSHOT_SCOPES,
|
||||
valueByKey,
|
||||
{
|
||||
agentWorkflowDefaultModelId:
|
||||
String(currentSiteSettings?.agentWorkflowDefaultModelId || "").trim() || null,
|
||||
}
|
||||
);
|
||||
|
||||
const [snapshot] = await db
|
||||
.insert(systemSettingSnapshot)
|
||||
.values({
|
||||
scope: scopeArg,
|
||||
label: label || `manual-${scopeArg}-snapshot`,
|
||||
summary: summarizeSystemSettingSnapshotData(snapshotData),
|
||||
data: snapshotData,
|
||||
createdAt: new Date(),
|
||||
createdBy: null,
|
||||
})
|
||||
.returning({
|
||||
id: systemSettingSnapshot.id,
|
||||
scope: systemSettingSnapshot.scope,
|
||||
label: systemSettingSnapshot.label,
|
||||
createdAt: systemSettingSnapshot.createdAt,
|
||||
});
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
snapshotId: snapshot?.id ?? null,
|
||||
scope: snapshot?.scope ?? scopeArg,
|
||||
label: snapshot?.label ?? label ?? null,
|
||||
createdAt: snapshot?.createdAt ?? null,
|
||||
keyCount: keys.length,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
130
scripts/system-settings/restore-snapshot.ts
Normal file
130
scripts/system-settings/restore-snapshot.ts
Normal file
@ -0,0 +1,130 @@
|
||||
import { config as loadEnv } from "dotenv";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
loadEnv({ path: ".env.local" });
|
||||
|
||||
function readArg(name: string) {
|
||||
const prefix = `${name}=`;
|
||||
const match = process.argv.find((arg) => arg.startsWith(prefix));
|
||||
return match ? match.slice(prefix.length) : null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const snapshotId = readArg("--snapshot-id");
|
||||
const reason = readArg("--reason") || "manual-snapshot-restore";
|
||||
|
||||
if (!snapshotId) {
|
||||
throw new Error(
|
||||
"Usage: pnpm tsx scripts/system-settings/restore-snapshot.ts --snapshot-id=<id> [--reason=<reason>]"
|
||||
);
|
||||
}
|
||||
|
||||
const dbModule = await import("../../lib/db");
|
||||
const schemaModule = await import("../../lib/db/schema");
|
||||
const snapshotModule = await import("../../lib/system-settings/snapshot");
|
||||
|
||||
const { db } = dbModule;
|
||||
const { siteSettings, systemSettingHistory, systemSettingSnapshot, systemSettings } =
|
||||
schemaModule;
|
||||
const { readSystemSettingSnapshotData } = snapshotModule;
|
||||
|
||||
const [snapshot] = await db
|
||||
.select({
|
||||
id: systemSettingSnapshot.id,
|
||||
scope: systemSettingSnapshot.scope,
|
||||
data: systemSettingSnapshot.data,
|
||||
})
|
||||
.from(systemSettingSnapshot)
|
||||
.where(eq(systemSettingSnapshot.id, snapshotId))
|
||||
.limit(1);
|
||||
|
||||
if (!snapshot) {
|
||||
throw new Error(`Snapshot not found: ${snapshotId}`);
|
||||
}
|
||||
|
||||
const parsedSnapshot = readSystemSettingSnapshotData(
|
||||
snapshot.scope as keyof typeof snapshotModule.SYSTEM_SETTING_SNAPSHOT_SCOPES,
|
||||
snapshot.data
|
||||
);
|
||||
const keys = Object.keys(parsedSnapshot.systemSettings);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const key of keys) {
|
||||
const [existing] = await tx
|
||||
.select({ value: systemSettings.value })
|
||||
.from(systemSettings)
|
||||
.where(eq(systemSettings.key, key))
|
||||
.limit(1);
|
||||
|
||||
const nextValue = parsedSnapshot.systemSettings[key] ?? null;
|
||||
|
||||
await tx.insert(systemSettingHistory).values({
|
||||
key,
|
||||
previousValue: existing?.value ?? null,
|
||||
nextValue,
|
||||
reason,
|
||||
changedAt: new Date(),
|
||||
changedBy: null,
|
||||
});
|
||||
|
||||
await tx
|
||||
.insert(systemSettings)
|
||||
.values({
|
||||
key,
|
||||
value: nextValue,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: null,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: systemSettings.key,
|
||||
set: {
|
||||
value: nextValue,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if ("agentWorkflowDefaultModelId" in parsedSnapshot.siteSettings) {
|
||||
const [existingSiteSettings] = await tx.select().from(siteSettings).limit(1);
|
||||
const nextAgentWorkflowDefaultModelId =
|
||||
String(parsedSnapshot.siteSettings.agentWorkflowDefaultModelId || "").trim() || null;
|
||||
|
||||
if (existingSiteSettings) {
|
||||
await tx
|
||||
.update(siteSettings)
|
||||
.set({
|
||||
agentWorkflowDefaultModelId: nextAgentWorkflowDefaultModelId,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: null,
|
||||
})
|
||||
.where(eq(siteSettings.id, existingSiteSettings.id));
|
||||
} else {
|
||||
await tx.insert(siteSettings).values({
|
||||
siteName: "AI Chatbot",
|
||||
agentWorkflowDefaultModelId: nextAgentWorkflowDefaultModelId,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
snapshotId,
|
||||
scope: snapshot.scope,
|
||||
restoredKeyCount: keys.length,
|
||||
reason,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user