feat: 完成模板目录导入与生命周期管理
This commit is contained in:
1 parent
553a07c4ec
commit
413413efda
25 files changed
+1313
-24
No files matched your search
@@ -9,6 +9,7 @@ API_PREFIX=
|
||||
ADMIN_PORT=3000
|
||||
SESSION_SECRET=replace-with-a-long-random-value
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||
OBJECT_STORAGE_ENDPOINT=http://localhost:9000
|
||||
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
FeatureMembersPage,
|
||||
FeatureOverviewPage,
|
||||
FeaturePublicationPage,
|
||||
FeatureTemplateManagementPage,
|
||||
FeatureServicesPage,
|
||||
FeatureTrustContentPage,
|
||||
FeatureWorkspacePage,
|
||||
@@ -35,7 +36,15 @@ import { Route, Routes } from "react-router-dom";
|
||||
import { AdminOverviewRedirect } from "./AdminRouter.js";
|
||||
import { Suspense } from "react";
|
||||
|
||||
export function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) {
|
||||
export function Dashboard({
|
||||
onLogout,
|
||||
role,
|
||||
platformTemplateRole,
|
||||
}: {
|
||||
onLogout: () => void;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const brand = useQuery({
|
||||
@@ -79,6 +88,9 @@ export function Dashboard({ onLogout, role }: { onLogout: () => void; role: stri
|
||||
children: [
|
||||
{ key: "capabilities", label: "能力插件", icon: <ThunderboltOutlined /> },
|
||||
{ key: "members", label: "团队成员", icon: <TeamOutlined /> },
|
||||
...(platformTemplateRole === "template_admin"
|
||||
? [{ key: "templates", label: "模板管理", icon: <AppstoreOutlined /> }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
]),
|
||||
@@ -143,6 +155,9 @@ export function Dashboard({ onLogout, role }: { onLogout: () => void; role: stri
|
||||
<>
|
||||
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
|
||||
<Route path="members" element={<FeatureMembersPage />} />
|
||||
{platformTemplateRole === "template_admin" ? (
|
||||
<Route path="templates" element={<FeatureTemplateManagementPage />} />
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<Route path="*" element={<AdminOverviewRedirect />} />
|
||||
|
||||
@@ -7,6 +7,9 @@ import { adminMessage as message } from "../components/AdminMessage.js";
|
||||
export function Root() {
|
||||
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
|
||||
const [role, setRole] = useState(localStorage.getItem("adminRole") || "owner");
|
||||
const [platformTemplateRole, setPlatformTemplateRole] = useState(
|
||||
localStorage.getItem("adminPlatformTemplateRole") || "none",
|
||||
);
|
||||
const [mustChangePassword, setMustChangePassword] = useState(
|
||||
localStorage.getItem("adminMustChangePassword") === "true",
|
||||
);
|
||||
@@ -21,6 +24,7 @@ export function Root() {
|
||||
const logout = () => {
|
||||
localStorage.removeItem("adminToken");
|
||||
localStorage.removeItem("adminRole");
|
||||
localStorage.removeItem("adminPlatformTemplateRole");
|
||||
localStorage.removeItem("adminMustChangePassword");
|
||||
setLoggedIn(false);
|
||||
};
|
||||
@@ -29,6 +33,7 @@ export function Root() {
|
||||
<Login
|
||||
onLogin={(session) => {
|
||||
setRole(session.role);
|
||||
setPlatformTemplateRole(session.platformTemplateRole);
|
||||
setMustChangePassword(session.mustChangePassword);
|
||||
setLoggedIn(true);
|
||||
}}
|
||||
@@ -37,7 +42,7 @@ export function Root() {
|
||||
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
|
||||
return (
|
||||
<AdminRouter>
|
||||
<Dashboard onLogout={logout} role={role} />
|
||||
<Dashboard onLogout={logout} role={role} platformTemplateRole={platformTemplateRole} />
|
||||
</AdminRouter>
|
||||
);
|
||||
}
|
||||
@@ -43,3 +43,8 @@ export const FeaturePublicationPage = React.lazy(() =>
|
||||
default: module.PublicationPage,
|
||||
})),
|
||||
);
|
||||
export const FeatureTemplateManagementPage = React.lazy(() =>
|
||||
import("../features/template-management/TemplateManagementPage.js").then((module) => ({
|
||||
default: module.TemplateManagementPage,
|
||||
})),
|
||||
);
|
||||
@@ -9,7 +9,11 @@ import { AdminForm, AdminInput } from "../../components/AdminForm.js";
|
||||
export function Login({
|
||||
onLogin,
|
||||
}: {
|
||||
onLogin: (session: { role: string; mustChangePassword: boolean }) => void;
|
||||
onLogin: (session: {
|
||||
role: string;
|
||||
mustChangePassword: boolean;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
}) => void;
|
||||
}) {
|
||||
const [form] = AdminForm.useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -19,6 +23,7 @@ export function Login({
|
||||
const result = await createApiClient().loginAdmin(values.username, values.password);
|
||||
localStorage.setItem("adminToken", result.token);
|
||||
localStorage.setItem("adminRole", result.role);
|
||||
localStorage.setItem("adminPlatformTemplateRole", result.platformTemplateRole);
|
||||
localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword));
|
||||
onLogin(result);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Alert, Button, List, Modal, Table, Tag, Typography, message } from "antd";
|
||||
import { ReloadOutlined, UploadOutlined } from "@ant-design/icons";
|
||||
import type { TemplatePackageVersion } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { AdminSection } from "../../components/AdminSection.js";
|
||||
import { EmptyState } from "../../components/EmptyState.js";
|
||||
import { ErrorNote, QueryState } from "../../components/QueryState.js";
|
||||
|
||||
const client = createApiClient();
|
||||
|
||||
function formatBytes(value: unknown): string {
|
||||
const bytes = typeof value === "number" ? value : 0;
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function TemplateManagementPage() {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [auditId, setAuditId] = useState<string | null>(null);
|
||||
const queryClient = useQueryClient();
|
||||
const packages = useQuery({
|
||||
queryKey: ["admin-template-packages", page, pageSize],
|
||||
queryFn: () => client.listAdminTemplatePackages({ page, pageSize }),
|
||||
});
|
||||
const audit = useQuery({
|
||||
queryKey: ["admin-template-package-audit", auditId],
|
||||
queryFn: () => client.listAdminTemplatePackageAudit(auditId as string),
|
||||
enabled: Boolean(auditId),
|
||||
});
|
||||
const lifecycle = useMutation({
|
||||
mutationFn: async ({ id, action }: { id: string; action: "publish" | "retire" }) =>
|
||||
action === "publish"
|
||||
? client.publishAdminTemplatePackage(id)
|
||||
: client.retireAdminTemplatePackage(id),
|
||||
onSuccess: (result) => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-packages"] });
|
||||
message.success(result.changed ? "模板目录状态已更新" : "模板目录状态未变化");
|
||||
},
|
||||
});
|
||||
const importing = useMutation({
|
||||
mutationFn: (file: File) => {
|
||||
const form = new FormData();
|
||||
form.append("archive", file, file.name);
|
||||
return client.importAdminTemplatePackage(form);
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-packages"] });
|
||||
},
|
||||
});
|
||||
const chooseFile = () => inputRef.current?.click();
|
||||
const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
if (!file.name.endsWith(".tar.gz")) {
|
||||
importing.reset();
|
||||
return;
|
||||
}
|
||||
importing.mutate(file);
|
||||
};
|
||||
const rows = packages.data?.items ?? [];
|
||||
return (
|
||||
<div className="admin-stack admin-stack-lg">
|
||||
<AdminPageHeader
|
||||
title="模板管理"
|
||||
description="导入通过本地模板检查的确定性 archive,登记版本、校验摘要并供后续预览与安装使用。"
|
||||
extra={
|
||||
<>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".tar.gz,application/gzip"
|
||||
onChange={onFileChange}
|
||||
hidden
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<UploadOutlined />}
|
||||
loading={importing.isPending}
|
||||
onClick={chooseFile}
|
||||
>
|
||||
导入模板包
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="导入规则"
|
||||
description="系统会校验文件路径、链接、文件数量、解压体积、template.json、package.json 和 checksums.json;包内脚本不会被执行。"
|
||||
/>
|
||||
{importing.isError ? <ErrorNote error={importing.error} /> : null}
|
||||
{importing.isSuccess ? (
|
||||
<Alert
|
||||
type="success"
|
||||
showIcon
|
||||
message={importing.data.idempotent ? "模板版本已存在,未重复写入" : "模板版本导入成功"}
|
||||
description={`${importing.data.version.packageKey}@${importing.data.version.version}`}
|
||||
/>
|
||||
) : null}
|
||||
{lifecycle.isError ? <ErrorNote error={lifecycle.error} /> : null}
|
||||
<AdminSection
|
||||
title="已导入版本"
|
||||
description="同一 package key 的不同版本并列保留,发布品牌时再选择安装版本。"
|
||||
>
|
||||
<QueryState
|
||||
loading={packages.isLoading}
|
||||
error={packages.error}
|
||||
onRetry={() => void packages.refetch()}
|
||||
>
|
||||
{rows.length ? (
|
||||
<Table<TemplatePackageVersion>
|
||||
rowKey="id"
|
||||
dataSource={rows}
|
||||
pagination={{
|
||||
current: packages.data?.page ?? page,
|
||||
pageSize: packages.data?.pageSize ?? pageSize,
|
||||
total: packages.data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (nextPage, nextPageSize) => {
|
||||
setPage(nextPageSize === pageSize ? nextPage : 1);
|
||||
setPageSize(nextPageSize);
|
||||
},
|
||||
}}
|
||||
scroll={{ x: 980 }}
|
||||
columns={[
|
||||
{
|
||||
title: "模板",
|
||||
key: "template",
|
||||
render: (_, item) => (
|
||||
<div>
|
||||
<Typography.Text strong>{item.displayName}</Typography.Text>
|
||||
<div className="admin-muted-text">{item.packageKey}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ title: "版本", dataIndex: "version", key: "version" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "status",
|
||||
key: "status",
|
||||
render: (value: TemplatePackageVersion["status"]) => (
|
||||
<Tag
|
||||
color={
|
||||
value === "published" ? "green" : value === "imported" ? "blue" : "default"
|
||||
}
|
||||
>
|
||||
{value === "published"
|
||||
? "已发布"
|
||||
: value === "imported"
|
||||
? "待发布"
|
||||
: value === "retired"
|
||||
? "已撤回"
|
||||
: "已停用"}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "文件",
|
||||
key: "report",
|
||||
render: (_, item) => {
|
||||
const report = item.validationReport;
|
||||
return `${String(report.fileCount ?? "-")} 个,${formatBytes(report.extractedBytes)}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "内容 checksum",
|
||||
dataIndex: "contentChecksum",
|
||||
key: "contentChecksum",
|
||||
render: (value: string) => (
|
||||
<Typography.Text copyable>{value.slice(0, 16)}…</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "导入人",
|
||||
key: "importedBy",
|
||||
render: (_, item) => item.importedBy.displayName,
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
key: "actions",
|
||||
render: (_, item) => (
|
||||
<span>
|
||||
<Button
|
||||
type="link"
|
||||
loading={lifecycle.isPending && lifecycle.variables?.id === item.id}
|
||||
onClick={() =>
|
||||
lifecycle.mutate({
|
||||
id: item.id,
|
||||
action: item.status === "published" ? "retire" : "publish",
|
||||
})
|
||||
}
|
||||
disabled={item.status === "disabled"}
|
||||
>
|
||||
{item.status === "published" ? "撤回" : "发布"}
|
||||
</Button>
|
||||
<Button type="link" onClick={() => setAuditId(item.id)}>
|
||||
审计
|
||||
</Button>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="还没有导入模板"
|
||||
description="从本地执行 template:pack 后导入 tar.gz。"
|
||||
/>
|
||||
)}
|
||||
</QueryState>
|
||||
</AdminSection>
|
||||
{packages.isError ? (
|
||||
<Button icon={<ReloadOutlined />} onClick={() => void packages.refetch()}>
|
||||
重试加载
|
||||
</Button>
|
||||
) : null}
|
||||
<Modal
|
||||
title="模板版本审计"
|
||||
open={Boolean(auditId)}
|
||||
footer={null}
|
||||
onCancel={() => setAuditId(null)}
|
||||
>
|
||||
<QueryState
|
||||
loading={audit.isLoading}
|
||||
error={audit.error}
|
||||
onRetry={() => void audit.refetch()}
|
||||
>
|
||||
<List
|
||||
dataSource={audit.data ?? []}
|
||||
locale={{ emptyText: "暂无审计记录" }}
|
||||
renderItem={(item) => (
|
||||
<List.Item>
|
||||
<List.Item.Meta
|
||||
title={`${item.action} · ${item.actor.displayName}`}
|
||||
description={`${item.fromStatus ?? "-"} -> ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}`}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</QueryState>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
CREATE TYPE "PlatformTemplateRole" AS ENUM ('none', 'template_admin');
|
||||
CREATE TYPE "TemplatePackageVersionStatus" AS ENUM ('imported', 'disabled');
|
||||
|
||||
ALTER TABLE "AdminUser"
|
||||
ADD COLUMN "platformTemplateRole" "PlatformTemplateRole" NOT NULL DEFAULT 'none';
|
||||
|
||||
CREATE TABLE "TemplatePackage" (
|
||||
"id" TEXT NOT NULL,
|
||||
"packageKey" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
CONSTRAINT "TemplatePackage_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE "TemplatePackageVersion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"templatePackageId" TEXT NOT NULL,
|
||||
"packageKey" TEXT NOT NULL,
|
||||
"version" TEXT NOT NULL,
|
||||
"displayName" TEXT NOT NULL,
|
||||
"visualTemplateKey" TEXT,
|
||||
"status" "TemplatePackageVersionStatus" NOT NULL DEFAULT 'imported',
|
||||
"manifestSnapshot" JSONB NOT NULL,
|
||||
"validationReport" JSONB NOT NULL,
|
||||
"contentChecksum" TEXT NOT NULL,
|
||||
"archiveChecksum" TEXT NOT NULL,
|
||||
"artifactPath" TEXT NOT NULL,
|
||||
"importedById" TEXT NOT NULL,
|
||||
"importedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
CONSTRAINT "TemplatePackageVersion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "TemplatePackage_packageKey_key" ON "TemplatePackage"("packageKey");
|
||||
CREATE UNIQUE INDEX "TemplatePackageVersion_templatePackageId_version_key" ON "TemplatePackageVersion"("templatePackageId", "version");
|
||||
CREATE INDEX "TemplatePackageVersion_packageKey_status_idx" ON "TemplatePackageVersion"("packageKey", "status");
|
||||
CREATE INDEX "TemplatePackageVersion_importedById_importedAt_idx" ON "TemplatePackageVersion"("importedById", "importedAt");
|
||||
|
||||
ALTER TABLE "TemplatePackageVersion"
|
||||
ADD CONSTRAINT "TemplatePackageVersion_templatePackageId_fkey"
|
||||
FOREIGN KEY ("templatePackageId") REFERENCES "TemplatePackage"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "TemplatePackageVersion"
|
||||
ADD CONSTRAINT "TemplatePackageVersion_importedById_fkey"
|
||||
FOREIGN KEY ("importedById") REFERENCES "AdminUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
ALTER TYPE "TemplatePackageVersionStatus" ADD VALUE 'published';
|
||||
ALTER TYPE "TemplatePackageVersionStatus" ADD VALUE 'retired';
|
||||
|
||||
CREATE TABLE "TemplatePackageAuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"templatePackageVersionId" TEXT NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"fromStatus" "TemplatePackageVersionStatus",
|
||||
"toStatus" "TemplatePackageVersionStatus",
|
||||
"requestId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "TemplatePackageAuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "TemplatePackageAuditLog_templatePackageVersionId_createdAt_idx"
|
||||
ON "TemplatePackageAuditLog"("templatePackageVersionId", "createdAt" DESC);
|
||||
CREATE INDEX "TemplatePackageAuditLog_actorId_createdAt_idx"
|
||||
ON "TemplatePackageAuditLog"("actorId", "createdAt" DESC);
|
||||
|
||||
ALTER TABLE "TemplatePackageAuditLog"
|
||||
ADD CONSTRAINT "TemplatePackageAuditLog_templatePackageVersionId_fkey"
|
||||
FOREIGN KEY ("templatePackageVersionId") REFERENCES "TemplatePackageVersion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "TemplatePackageAuditLog"
|
||||
ADD CONSTRAINT "TemplatePackageAuditLog_actorId_fkey"
|
||||
FOREIGN KEY ("actorId") REFERENCES "AdminUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -139,6 +139,18 @@ enum MiniAppBuildStatus {
|
||||
failed
|
||||
}
|
||||
|
||||
enum PlatformTemplateRole {
|
||||
none
|
||||
template_admin
|
||||
}
|
||||
|
||||
enum TemplatePackageVersionStatus {
|
||||
imported
|
||||
published
|
||||
retired
|
||||
disabled
|
||||
}
|
||||
|
||||
model CapabilityAuditLog {
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
@@ -385,12 +397,66 @@ model AdminUser {
|
||||
passwordHash String
|
||||
displayName String
|
||||
role String @default("admin")
|
||||
platformTemplateRole PlatformTemplateRole @default(none)
|
||||
isEnabled Boolean @default(true)
|
||||
mustChangePassword Boolean @default(false)
|
||||
lastLoginAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
memberships BrandMembership[]
|
||||
importedTemplateVersions TemplatePackageVersion[] @relation("TemplatePackageImportedBy")
|
||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
||||
}
|
||||
|
||||
model TemplatePackage {
|
||||
id String @id @default(uuid())
|
||||
packageKey String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
versions TemplatePackageVersion[]
|
||||
}
|
||||
|
||||
model TemplatePackageVersion {
|
||||
id String @id @default(uuid())
|
||||
templatePackageId String
|
||||
templatePackage TemplatePackage @relation(fields: [templatePackageId], references: [id], onDelete: Cascade)
|
||||
packageKey String
|
||||
version String
|
||||
displayName String
|
||||
visualTemplateKey String?
|
||||
status TemplatePackageVersionStatus @default(imported)
|
||||
manifestSnapshot Json
|
||||
validationReport Json
|
||||
contentChecksum String
|
||||
archiveChecksum String
|
||||
artifactPath String
|
||||
importedById String
|
||||
importedBy AdminUser @relation("TemplatePackageImportedBy", fields: [importedById], references: [id], onDelete: Restrict)
|
||||
auditLogs TemplatePackageAuditLog[]
|
||||
importedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([templatePackageId, version])
|
||||
@@index([packageKey, status])
|
||||
@@index([importedById, importedAt])
|
||||
}
|
||||
|
||||
model TemplatePackageAuditLog {
|
||||
id String @id @default(uuid())
|
||||
templatePackageVersionId String
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Cascade)
|
||||
actorId String
|
||||
actor AdminUser @relation("TemplatePackageAuditActor", fields: [actorId], references: [id], onDelete: Restrict)
|
||||
action String
|
||||
fromStatus TemplatePackageVersionStatus?
|
||||
toStatus TemplatePackageVersionStatus?
|
||||
requestId String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([templatePackageVersionId, createdAt])
|
||||
@@index([actorId, createdAt])
|
||||
}
|
||||
|
||||
model BrandMembership {
|
||||
|
||||
@@ -852,11 +852,12 @@ async function main(): Promise<void> {
|
||||
}
|
||||
const admin = await prisma.adminUser.upsert({
|
||||
where: { username: "admin" },
|
||||
update: {},
|
||||
update: { platformTemplateRole: "template_admin" },
|
||||
create: {
|
||||
username: "admin",
|
||||
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
|
||||
displayName: "品牌管理员",
|
||||
platformTemplateRole: "template_admin",
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -21,9 +21,9 @@ export class AdminAccessService {
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { mustChangePassword: true },
|
||||
select: { mustChangePassword: true, isEnabled: true },
|
||||
});
|
||||
if (!user || user.mustChangePassword)
|
||||
if (!user?.isEnabled || user.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const membership = await this.prisma.brandMembership.findUnique({
|
||||
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
|
||||
@@ -39,4 +39,25 @@ export class AdminAccessService {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async requireTemplateAdmin(request: FastifyRequest): Promise<{ subject: string }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { isEnabled: true, mustChangePassword: true, platformTemplateRole: true },
|
||||
});
|
||||
if (!user?.isEnabled || user.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
if (user.platformTemplateRole !== "template_admin")
|
||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||
return { subject: identity.subject };
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,13 @@ export class AdminAuthService {
|
||||
async login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
|
||||
): Promise<{
|
||||
token: string;
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
}> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
|
||||
throw new UnauthorizedException("账号或密码错误");
|
||||
@@ -41,6 +47,7 @@ export class AdminAuthService {
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: activeMembership.role,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,9 @@ export class AdminMembershipGuard implements CanActivate {
|
||||
if (routePath === "admin/session/login") return Promise.resolve(true);
|
||||
if (routePath === "admin/session/change-password") return Promise.resolve(true);
|
||||
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
|
||||
if (routePath === "admin/templates" || routePath.startsWith("admin/templates/")) {
|
||||
return this.access.requireTemplateAdmin(request).then(() => true);
|
||||
}
|
||||
if (
|
||||
/^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
|
||||
routePath,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { ListTemplatePackagesQueryDto } from "./admin-template-package.dto.js";
|
||||
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
|
||||
|
||||
@Controller("admin/templates")
|
||||
export class AdminTemplatePackageController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly templates: AdminTemplatePackageService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@Query() query: ListTemplatePackagesQueryDto,
|
||||
): ReturnType<AdminTemplatePackageService["list"]> {
|
||||
return this.templates.list(query.page, query.pageSize);
|
||||
}
|
||||
|
||||
@Post("import")
|
||||
async import(@Req() request: FastifyRequest) {
|
||||
const { subject } = await this.access.requireTemplateAdmin(request);
|
||||
return this.templates.importArchive(request, subject);
|
||||
}
|
||||
|
||||
@Post(":id/publish")
|
||||
async publish(@Req() request: FastifyRequest, @Param("id") id: string) {
|
||||
const { subject } = await this.access.requireTemplateAdmin(request);
|
||||
return this.templates.publish(id, subject, request.headers["x-request-id"]?.toString());
|
||||
}
|
||||
|
||||
@Post(":id/retire")
|
||||
async retire(@Req() request: FastifyRequest, @Param("id") id: string) {
|
||||
const { subject } = await this.access.requireTemplateAdmin(request);
|
||||
return this.templates.retire(id, subject, request.headers["x-request-id"]?.toString());
|
||||
}
|
||||
|
||||
@Get(":id/audit")
|
||||
audit(@Param("id") id: string): ReturnType<AdminTemplatePackageService["audit"]> {
|
||||
return this.templates.audit(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Type } from "class-transformer";
|
||||
import { IsInt, IsOptional, Max, Min } from "class-validator";
|
||||
|
||||
export class ListTemplatePackagesQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page = 1;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
pageSize = 20;
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
PayloadTooLargeException,
|
||||
} from "@nestjs/common";
|
||||
import { validateTemplatePackageManifest } from "@personal-brand/config";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const MAX_ARCHIVE_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_EXTRACTED_BYTES = 200 * 1024 * 1024;
|
||||
const MAX_FILES = 5_000;
|
||||
const PACKAGE_KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
|
||||
type Manifest = {
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
visualTemplateKey?: string;
|
||||
};
|
||||
|
||||
type ChecksumFile = {
|
||||
formatVersion: string;
|
||||
packageKey: string;
|
||||
version: string;
|
||||
contentChecksum: string;
|
||||
files: Array<{ path: string; bytes: number; sha256: string }>;
|
||||
};
|
||||
|
||||
function sha256(value: Buffer | string): string {
|
||||
return createHash("sha256").update(value).digest("hex");
|
||||
}
|
||||
|
||||
function canonical(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(canonical);
|
||||
if (!value || typeof value !== "object") return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, item]) => [key, canonical(item)]),
|
||||
);
|
||||
}
|
||||
|
||||
function jsonObject(value: unknown, label: string): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new BadRequestException(`${label} 必须是 JSON 对象`);
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function safeEntryName(input: string): string {
|
||||
if (!input || input.includes("\\") || input.startsWith("/") || /^[A-Za-z]:/.test(input))
|
||||
throw new BadRequestException("模板包包含不安全的文件路径");
|
||||
const withoutTrailingSlash = input.endsWith("/") ? input.slice(0, -1) : input;
|
||||
const normalized = path.posix.normalize(withoutTrailingSlash);
|
||||
if (!withoutTrailingSlash || normalized !== withoutTrailingSlash || normalized === ".")
|
||||
throw new BadRequestException("模板包包含不安全的文件路径");
|
||||
if (normalized.split("/").some((segment) => segment === ".." || segment === "."))
|
||||
throw new BadRequestException("模板包包含不安全的文件路径");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
async function listArchiveEntries(archivePath: string): Promise<string[]> {
|
||||
let list: string;
|
||||
let verbose: string;
|
||||
try {
|
||||
({ stdout: list } = await execFileAsync("tar", ["-tzf", archivePath], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
}));
|
||||
({ stdout: verbose } = await execFileAsync("tar", ["-tvzf", archivePath], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
}));
|
||||
} catch {
|
||||
throw new BadRequestException("模板包不是有效的 gzip tar archive");
|
||||
}
|
||||
const entries = list
|
||||
.split("\n")
|
||||
.map((item) => item.trimEnd())
|
||||
.filter(Boolean)
|
||||
.map(safeEntryName);
|
||||
if (!entries.length || entries.length > MAX_FILES)
|
||||
throw new BadRequestException("模板包文件数量超出限制");
|
||||
const typeLines = verbose
|
||||
.split("\n")
|
||||
.map((item) => item.trimEnd())
|
||||
.filter(Boolean);
|
||||
if (
|
||||
typeLines.length !== entries.length ||
|
||||
typeLines.some((line) => !["-", "d"].includes(line[0] ?? ""))
|
||||
)
|
||||
throw new BadRequestException("模板包只允许包含普通文件和目录,不允许链接或特殊文件");
|
||||
if (new Set(entries).size !== entries.length) throw new BadRequestException("模板包包含重复路径");
|
||||
return entries;
|
||||
}
|
||||
|
||||
async function walkFiles(
|
||||
directory: string,
|
||||
relative = "",
|
||||
): Promise<Array<{ path: string; bytes: number }>> {
|
||||
const result: Array<{ path: string; bytes: number }> = [];
|
||||
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
||||
const current = relative ? `${relative}/${entry.name}` : entry.name;
|
||||
const absolute = path.join(directory, entry.name);
|
||||
if (entry.isSymbolicLink()) throw new BadRequestException("模板包解压后包含符号链接");
|
||||
if (entry.isDirectory()) result.push(...(await walkFiles(absolute, current)));
|
||||
else if (entry.isFile()) result.push({ path: current, bytes: (await fs.stat(absolute)).size });
|
||||
else throw new BadRequestException("模板包包含不支持的文件类型");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminTemplatePackageService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(page = 1, pageSize = 20) {
|
||||
const [total, versions] = await this.prisma.$transaction([
|
||||
this.prisma.templatePackageVersion.count(),
|
||||
this.prisma.templatePackageVersion.findMany({
|
||||
orderBy: { importedAt: "desc" },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
select: {
|
||||
id: true,
|
||||
packageKey: true,
|
||||
version: true,
|
||||
displayName: true,
|
||||
visualTemplateKey: true,
|
||||
status: true,
|
||||
contentChecksum: true,
|
||||
archiveChecksum: true,
|
||||
validationReport: true,
|
||||
importedAt: true,
|
||||
updatedAt: true,
|
||||
templatePackage: { select: { id: true } },
|
||||
importedBy: { select: { id: true, username: true, displayName: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items: versions.map(({ templatePackage, ...version }) => ({
|
||||
...version,
|
||||
templatePackageId: templatePackage.id,
|
||||
})),
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
async importArchive(request: FastifyRequest, actorId: string) {
|
||||
const part = await request.file({ limits: { files: 1, fileSize: MAX_ARCHIVE_BYTES } });
|
||||
if (!part) throw new BadRequestException("请上传模板 archive 文件");
|
||||
if (part.fieldname !== "archive") throw new BadRequestException("上传字段必须是 archive");
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let storedArtifactPath: string | null = null;
|
||||
try {
|
||||
for await (const chunk of part.file) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
bytes += buffer.length;
|
||||
if (bytes > MAX_ARCHIVE_BYTES) throw new PayloadTooLargeException("模板包超过 50 MB 限制");
|
||||
chunks.push(buffer);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PayloadTooLargeException) throw error;
|
||||
throw new BadRequestException("读取模板 archive 失败");
|
||||
}
|
||||
if (part.file.truncated) throw new PayloadTooLargeException("模板包超过 50 MB 限制");
|
||||
const archive = Buffer.concat(chunks);
|
||||
const archiveChecksum = sha256(archive);
|
||||
const temporaryRoot = await fs.mkdtemp(path.join(process.cwd(), ".template-import-"));
|
||||
const archivePath = path.join(temporaryRoot, "package.tar.gz");
|
||||
const extractedRoot = path.join(temporaryRoot, "extracted");
|
||||
try {
|
||||
await fs.writeFile(archivePath, archive, { mode: 0o600 });
|
||||
const entries = await listArchiveEntries(archivePath);
|
||||
const roots = new Set(entries.map((entry) => entry.split("/")[0]));
|
||||
if (roots.size !== 1) throw new BadRequestException("模板包必须只有一个根目录");
|
||||
const rootName = [...roots][0];
|
||||
if (
|
||||
!rootName ||
|
||||
entries.some((entry) => entry !== rootName && !entry.startsWith(`${rootName}/`))
|
||||
)
|
||||
throw new BadRequestException("模板包根目录结构无效");
|
||||
await fs.mkdir(extractedRoot, { recursive: true });
|
||||
try {
|
||||
await execFileAsync(
|
||||
"tar",
|
||||
[
|
||||
"-xzf",
|
||||
archivePath,
|
||||
"--directory",
|
||||
extractedRoot,
|
||||
"--no-same-owner",
|
||||
"--no-same-permissions",
|
||||
],
|
||||
{ maxBuffer: 4 * 1024 * 1024 },
|
||||
);
|
||||
} catch {
|
||||
throw new BadRequestException("模板包解压失败");
|
||||
}
|
||||
const packageRoot = path.join(extractedRoot, rootName);
|
||||
const files = await walkFiles(packageRoot);
|
||||
if (files.length > MAX_FILES) throw new BadRequestException("模板包文件数量超出限制");
|
||||
if (files.reduce((total, file) => total + file.bytes, 0) > MAX_EXTRACTED_BYTES)
|
||||
throw new PayloadTooLargeException("模板包解压后超过 200 MB 限制");
|
||||
const manifest = (await this.readJson(
|
||||
path.join(packageRoot, "template.json"),
|
||||
"template.json",
|
||||
)) as Manifest;
|
||||
const packageJson = jsonObject(
|
||||
await this.readJson(path.join(packageRoot, "package.json"), "package.json"),
|
||||
"package.json",
|
||||
) as { name?: unknown; version?: unknown };
|
||||
const checksums = jsonObject(
|
||||
await this.readJson(path.join(packageRoot, "checksums.json"), "checksums.json"),
|
||||
"checksums.json",
|
||||
) as unknown as ChecksumFile;
|
||||
this.validateManifest(manifest, packageJson, checksums);
|
||||
await this.validateChecksums(packageRoot, files, checksums);
|
||||
const packageKey = manifest.packageKey;
|
||||
const existingPackage = await this.prisma.templatePackage.findUnique({
|
||||
where: { packageKey },
|
||||
});
|
||||
const existingVersion = existingPackage
|
||||
? await this.prisma.templatePackageVersion.findUnique({
|
||||
where: {
|
||||
templatePackageId_version: {
|
||||
templatePackageId: existingPackage.id,
|
||||
version: manifest.version,
|
||||
},
|
||||
},
|
||||
})
|
||||
: null;
|
||||
if (existingVersion) {
|
||||
if (existingVersion.contentChecksum === checksums.contentChecksum)
|
||||
return {
|
||||
imported: false,
|
||||
idempotent: true,
|
||||
version: this.publicVersion(existingVersion),
|
||||
};
|
||||
throw new ConflictException(`${packageKey}@${manifest.version} 已存在不同内容的版本`);
|
||||
}
|
||||
const artifactRoot = path.resolve(
|
||||
process.env.TEMPLATE_ARTIFACT_ROOT ??
|
||||
path.join(process.cwd(), "storage", "template-artifacts"),
|
||||
);
|
||||
const artifactPath = path.join(
|
||||
artifactRoot,
|
||||
packageKey,
|
||||
manifest.version,
|
||||
`${archiveChecksum}.tar.gz`,
|
||||
);
|
||||
await fs.mkdir(path.dirname(artifactPath), { recursive: true });
|
||||
await fs.copyFile(archivePath, artifactPath);
|
||||
storedArtifactPath = artifactPath;
|
||||
const version = await this.prisma.$transaction(async (tx) => {
|
||||
const packageRecord =
|
||||
existingPackage ?? (await tx.templatePackage.create({ data: { packageKey } }));
|
||||
const created = await tx.templatePackageVersion.create({
|
||||
data: {
|
||||
templatePackageId: packageRecord.id,
|
||||
packageKey,
|
||||
version: manifest.version,
|
||||
displayName: manifest.displayName,
|
||||
visualTemplateKey: manifest.visualTemplateKey ?? null,
|
||||
manifestSnapshot: manifest as unknown as Prisma.InputJsonValue,
|
||||
validationReport: {
|
||||
formatVersion: "1",
|
||||
errors: [],
|
||||
fileCount: files.length,
|
||||
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
|
||||
} as Prisma.InputJsonValue,
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
archiveChecksum,
|
||||
artifactPath,
|
||||
importedById: actorId,
|
||||
},
|
||||
});
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: created.id,
|
||||
actorId,
|
||||
action: "imported",
|
||||
toStatus: "imported",
|
||||
metadata: {
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
archiveChecksum,
|
||||
},
|
||||
},
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return { imported: true, idempotent: false, version: this.publicVersion(version) };
|
||||
} catch (error) {
|
||||
if (storedArtifactPath) await fs.rm(storedArtifactPath, { force: true });
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.rm(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async publish(id: string, actorId: string, requestId?: string) {
|
||||
return this.transition(id, actorId, "published", requestId);
|
||||
}
|
||||
|
||||
async retire(id: string, actorId: string, requestId?: string) {
|
||||
return this.transition(id, actorId, "retired", requestId);
|
||||
}
|
||||
|
||||
async audit(id: string) {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (!version) throw new BadRequestException("模板版本不存在");
|
||||
return this.prisma.templatePackageAuditLog.findMany({
|
||||
where: { templatePackageVersionId: id },
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: { actor: { select: { id: true, username: true, displayName: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
private async transition(
|
||||
id: string,
|
||||
actorId: string,
|
||||
target: "published" | "retired",
|
||||
requestId?: string,
|
||||
) {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (!version) throw new BadRequestException("模板版本不存在");
|
||||
if (version.status === target) return { changed: false, version: this.publicVersion(version) };
|
||||
const valid =
|
||||
target === "published" ? version.status === "imported" : version.status === "published";
|
||||
if (!valid) throw new ConflictException(`模板版本当前状态为 ${version.status},不能执行此操作`);
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.templatePackageVersion.updateMany({
|
||||
where: { id, status: version.status },
|
||||
data: { status: target },
|
||||
});
|
||||
if (changed.count !== 1) {
|
||||
const current = await tx.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (current?.status === target) return { next: current, changed: false };
|
||||
throw new ConflictException("模板版本状态已被其他操作修改,请刷新后重试");
|
||||
}
|
||||
const next = await tx.templatePackageVersion.findUniqueOrThrow({ where: { id } });
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: id,
|
||||
actorId,
|
||||
action: target,
|
||||
fromStatus: version.status,
|
||||
toStatus: target,
|
||||
...(requestId ? { requestId } : {}),
|
||||
},
|
||||
});
|
||||
return { next, changed: true };
|
||||
});
|
||||
return { changed: updated.changed, version: this.publicVersion(updated.next) };
|
||||
}
|
||||
|
||||
private async readJson(filePath: string, label: string): Promise<unknown> {
|
||||
try {
|
||||
return JSON.parse(await fs.readFile(filePath, "utf8")) as unknown;
|
||||
} catch {
|
||||
throw new BadRequestException(`${label} 不是有效的 JSON 文件`);
|
||||
}
|
||||
}
|
||||
|
||||
private validateManifest(
|
||||
manifest: Manifest,
|
||||
packageJson: { name?: unknown; version?: unknown },
|
||||
checksums: ChecksumFile,
|
||||
) {
|
||||
if (!manifest || typeof manifest !== "object")
|
||||
throw new BadRequestException("template.json 无效");
|
||||
if (!PACKAGE_KEY_PATTERN.test(manifest.packageKey))
|
||||
throw new BadRequestException("模板 packageKey 无效");
|
||||
if (typeof manifest.version !== "string" || !manifest.version.trim())
|
||||
throw new BadRequestException("模板 version 无效");
|
||||
if (typeof manifest.displayName !== "string" || !manifest.displayName.trim())
|
||||
throw new BadRequestException("模板 displayName 无效");
|
||||
if (packageJson.name !== `@personal-brand/template-${manifest.packageKey}`)
|
||||
throw new BadRequestException("package.json name 与 template.json packageKey 不一致");
|
||||
if (packageJson.version !== manifest.version)
|
||||
throw new BadRequestException("package.json version 与 template.json version 不一致");
|
||||
let errors: string[];
|
||||
try {
|
||||
errors = validateTemplatePackageManifest(manifest as never);
|
||||
} catch {
|
||||
throw new BadRequestException("template.json 不符合模板契约");
|
||||
}
|
||||
if (errors.length)
|
||||
throw new BadRequestException(`template.json 不符合模板契约:${errors.join(";")}`);
|
||||
if (
|
||||
checksums.formatVersion !== "1" ||
|
||||
checksums.packageKey !== manifest.packageKey ||
|
||||
checksums.version !== manifest.version
|
||||
)
|
||||
throw new BadRequestException("checksums.json 元数据不一致");
|
||||
}
|
||||
|
||||
private async validateChecksums(
|
||||
packageRoot: string,
|
||||
files: Array<{ path: string; bytes: number }>,
|
||||
checksums: ChecksumFile,
|
||||
) {
|
||||
if (!Array.isArray(checksums.files) || checksums.files.length !== files.length - 1)
|
||||
throw new BadRequestException("checksums.json 文件清单不完整");
|
||||
const comparePath = (left: { path: string }, right: { path: string }) =>
|
||||
left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
|
||||
const actualFiles = files.filter((file) => file.path !== "checksums.json").sort(comparePath);
|
||||
const checksumFiles = [...checksums.files].sort(comparePath);
|
||||
if (checksumFiles.some((item, index) => item.path !== actualFiles[index]?.path))
|
||||
throw new BadRequestException("checksums.json 文件清单与 archive 不一致");
|
||||
for (const item of checksumFiles) {
|
||||
safeEntryName(item.path);
|
||||
if (
|
||||
!Number.isSafeInteger(item.bytes) ||
|
||||
item.bytes < 0 ||
|
||||
!/^[a-f0-9]{64}$/.test(item.sha256)
|
||||
)
|
||||
throw new BadRequestException("checksums.json 文件摘要格式无效");
|
||||
const content = fs.readFile(path.join(packageRoot, item.path));
|
||||
if (item.bytes !== actualFiles.find((file) => file.path === item.path)?.bytes)
|
||||
throw new BadRequestException("模板文件大小校验失败");
|
||||
if (sha256(await content) !== item.sha256)
|
||||
throw new BadRequestException("模板文件摘要校验失败");
|
||||
}
|
||||
const expected = sha256(JSON.stringify(canonical(checksumFiles)));
|
||||
if (checksums.contentChecksum !== expected || !/^[a-f0-9]{64}$/.test(checksums.contentChecksum))
|
||||
throw new BadRequestException("模板内容摘要校验失败");
|
||||
}
|
||||
|
||||
private publicVersion(version: {
|
||||
id: string;
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
visualTemplateKey: string | null;
|
||||
status: string;
|
||||
contentChecksum: string;
|
||||
archiveChecksum: string;
|
||||
importedAt: Date;
|
||||
}) {
|
||||
return {
|
||||
id: version.id,
|
||||
packageKey: version.packageKey,
|
||||
version: version.version,
|
||||
displayName: version.displayName,
|
||||
visualTemplateKey: version.visualTemplateKey,
|
||||
status: version.status,
|
||||
contentChecksum: version.contentChecksum,
|
||||
archiveChecksum: version.archiveChecksum,
|
||||
importedAt: version.importedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import { AdminMiniAppUploadService } from "./admin-miniapp-upload.service.js";
|
||||
import { AdminReleaseController } from "./admin-release.controller.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
import { AdminTemplatePackageController } from "./admin-template-package.controller.js";
|
||||
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
|
||||
|
||||
@Module({
|
||||
imports: [InfrastructureModule, BookingModule],
|
||||
@@ -23,6 +25,7 @@ import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
AdminUploadController,
|
||||
AdminLocalUploadController,
|
||||
AdminBookingController,
|
||||
AdminTemplatePackageController,
|
||||
],
|
||||
providers: [
|
||||
AdminBrandConfigService,
|
||||
@@ -31,6 +34,7 @@ import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
AdminMiniAppSettingsService,
|
||||
AdminMiniAppUploadService,
|
||||
AdminUploadService,
|
||||
AdminTemplatePackageService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -29,9 +29,13 @@ export class AdminSessionController {
|
||||
constructor(private readonly auth: AdminAuthService) {}
|
||||
|
||||
@Post("login")
|
||||
login(
|
||||
@Body() body: AdminLoginDto,
|
||||
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
|
||||
login(@Body() body: AdminLoginDto): Promise<{
|
||||
token: string;
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
}> {
|
||||
return this.auth.login(body.username, body.password);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, readdirSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { after, before, test } from "node:test";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { getVisualTemplateManifest } from "@personal-brand/config";
|
||||
@@ -16,12 +20,140 @@ let customerToken;
|
||||
const createdBookingIds = [];
|
||||
|
||||
before(async () => {
|
||||
process.env.TEMPLATE_ARTIFACT_ROOT = mkdtempSync(
|
||||
path.join(os.tmpdir(), "personal-brand-template-artifacts-"),
|
||||
);
|
||||
await prisma.customerUser.create({ data: { brandId, openid } });
|
||||
customerToken = signIdentity({ subject: openid, brandId, role: "customer" });
|
||||
app = await createApp();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
function multipartArchive(archive) {
|
||||
const boundary = "----personal-brand-template-test";
|
||||
const prefix = Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="archive"; filename="template.tar.gz"\r\nContent-Type: application/gzip\r\n\r\n`,
|
||||
);
|
||||
const suffix = Buffer.from(`\r\n--${boundary}--\r\n`);
|
||||
return {
|
||||
payload: Buffer.concat([prefix, archive, suffix]),
|
||||
headers: { "content-type": `multipart/form-data; boundary=${boundary}` },
|
||||
};
|
||||
}
|
||||
|
||||
function createTemplateArchive() {
|
||||
const output = mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-pack-"));
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
"acheng-campus-food",
|
||||
"--out",
|
||||
output,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
|
||||
);
|
||||
const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz"));
|
||||
assert.ok(filename);
|
||||
return readFileSync(path.join(output, filename));
|
||||
}
|
||||
|
||||
test("模板目录只允许平台模板管理员访问,并支持安全、幂等导入", async () => {
|
||||
const missing = await request("/admin/templates");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
const customer = await request("/admin/templates", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customer.statusCode, 403);
|
||||
const ordinaryUser = await prisma.adminUser.create({
|
||||
data: {
|
||||
username: `template-viewer-${Date.now()}`,
|
||||
passwordHash: "not-used-by-this-test",
|
||||
displayName: "普通管理员",
|
||||
platformTemplateRole: "none",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
try {
|
||||
const ordinary = await request("/admin/templates", {
|
||||
headers: {
|
||||
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
||||
},
|
||||
});
|
||||
assert.equal(ordinary.statusCode, 403);
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
||||
}
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const empty = await request("/admin/templates", { headers });
|
||||
assert.equal(empty.statusCode, 200);
|
||||
assert.deepEqual(JSON.parse(empty.body).items, []);
|
||||
assert.equal(JSON.parse(empty.body).total, 0);
|
||||
|
||||
const archive = createTemplateArchive();
|
||||
const imported = await request("/admin/templates/import", {
|
||||
method: "POST",
|
||||
headers: { ...headers, ...multipartArchive(archive).headers },
|
||||
rawPayload: multipartArchive(archive).payload,
|
||||
});
|
||||
assert.equal(imported.statusCode, 201);
|
||||
assert.equal(JSON.parse(imported.body).imported, true);
|
||||
const repeated = await request("/admin/templates/import", {
|
||||
method: "POST",
|
||||
headers: { ...headers, ...multipartArchive(archive).headers },
|
||||
rawPayload: multipartArchive(archive).payload,
|
||||
});
|
||||
assert.equal(repeated.statusCode, 201);
|
||||
assert.equal(JSON.parse(repeated.body).idempotent, true);
|
||||
const listed = await request("/admin/templates", { headers });
|
||||
const listedBody = JSON.parse(listed.body);
|
||||
assert.equal(listedBody.items.length, 1);
|
||||
assert.equal(listedBody.items[0].status, "imported");
|
||||
const versionId = listedBody.items[0].id;
|
||||
const publishMissing = await request(`/admin/templates/${versionId}/publish`, { method: "POST" });
|
||||
assert.equal(publishMissing.statusCode, 401);
|
||||
const publishCustomer = await request(`/admin/templates/${versionId}/publish`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(publishCustomer.statusCode, 403);
|
||||
const published = await request(`/admin/templates/${versionId}/publish`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
});
|
||||
assert.equal(published.statusCode, 201);
|
||||
assert.equal(JSON.parse(published.body).version.status, "published");
|
||||
const repeatedPublish = await request(`/admin/templates/${versionId}/publish`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
});
|
||||
assert.equal(JSON.parse(repeatedPublish.body).changed, false);
|
||||
const audit = await request(`/admin/templates/${versionId}/audit`, { headers });
|
||||
assert.equal(audit.statusCode, 200);
|
||||
assert.deepEqual(
|
||||
JSON.parse(audit.body).map((item) => item.action),
|
||||
["imported", "published"],
|
||||
);
|
||||
const retired = await request(`/admin/templates/${versionId}/retire`, {
|
||||
method: "POST",
|
||||
headers: { ...headers, "x-request-id": "template-retire-test" },
|
||||
});
|
||||
assert.equal(retired.statusCode, 201);
|
||||
assert.equal(JSON.parse(retired.body).version.status, "retired");
|
||||
const invalidRetire = await request(`/admin/templates/${versionId}/retire`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
});
|
||||
assert.equal(invalidRetire.statusCode, 201);
|
||||
assert.equal(JSON.parse(invalidRetire.body).changed, false);
|
||||
});
|
||||
|
||||
test("admin routes remain guarded when an API prefix is configured", async () => {
|
||||
process.env.API_PREFIX = "api";
|
||||
try {
|
||||
@@ -1126,10 +1258,16 @@ function errorMessage(body) {
|
||||
}
|
||||
|
||||
async function request(url, options = {}) {
|
||||
const { rawPayload, ...injectOptions } = options;
|
||||
return app
|
||||
.getHttpAdapter()
|
||||
.getInstance()
|
||||
.inject({ method: "GET", url, ...options });
|
||||
.inject({
|
||||
method: "GET",
|
||||
url,
|
||||
...injectOptions,
|
||||
...(rawPayload ? { payload: rawPayload } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async function publishReleaseForTests(note = "集成测试发布") {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 任务 ID:TMP-PLATFORM-001
|
||||
>
|
||||
> 状态:规划已固化,分阶段实施尚未完成
|
||||
> 状态:实施中,Phase 0/1 已完成,Phase 2 导入基础链路已完成,目录发布与独立预览待继续推进
|
||||
>
|
||||
> 唯一任务入口:本文档
|
||||
>
|
||||
@@ -370,15 +370,27 @@ Phase 0 执行记录(2026-10-16):
|
||||
|
||||
### Phase 2:线上导入、校验和模板目录
|
||||
|
||||
- [ ] 增加 TemplatePackage、TemplatePackageVersion、validation run 和 artifact 引用;
|
||||
- [ ] 实现临时存储、安全检查、checksum 幂等和冲突拒绝;
|
||||
- [x] 增加 TemplatePackage、TemplatePackageVersion、生命周期审计和 artifact 引用;
|
||||
- [x] 实现临时存储、安全检查、checksum 幂等和冲突拒绝;
|
||||
- [ ] 完成 manifest、runtime、renderer、industry、capability、资源和 fixture 诊断;
|
||||
- [ ] 实现目录发布、撤回、分页、审计和旧资源保留;
|
||||
- [ ] 增加独立平台模板权限;
|
||||
- [ ] API、DTO、shared client 和 integration test 一起交付。
|
||||
- [x] 实现目录发布、撤回、分页、审计和旧资源保留;
|
||||
- [x] 增加独立平台模板权限;
|
||||
- [x] API、DTO、shared client 和 integration test 一起交付。
|
||||
|
||||
退出门禁:非法包不会进入可用目录;重复导入不重复建版本;同版本不同 checksum 明确失败;未发布版本不能被品牌管理员安装。
|
||||
|
||||
Phase 2 当前进度(2026-10-16):
|
||||
|
||||
- 已增加 `TemplatePackage`、`TemplatePackageVersion`、版本状态和 `AdminUser.platformTemplateRole`,artifact 路径独立于 release 目录;
|
||||
- 已实现平台模板管理员 guard、`GET /admin/templates` 和 `POST /admin/templates/import`;普通品牌管理员和 customer 均不能访问;
|
||||
- 已实现临时文件导入、archive 路径/链接/重复项检查、文件数和解压体积限制、manifest/package metadata/checksum 校验、幂等和版本冲突拒绝;不执行包内脚本;
|
||||
- 已同步 shared client 和 Admin `/admin/templates` 的导入、版本列表、loading/empty/error/retry/success 状态;
|
||||
- 已通过 `51/51` API HTTP integration tests 和 `2/2` upload tests;
|
||||
- 已补充 `imported -> published -> retired` 生命周期、重复操作幂等、状态竞争保护、分页、审计查询和 Admin 页面发布/撤回/审计操作;
|
||||
- 已将模板包和版本及审计写入同一数据库事务,数据库失败时清理已落盘 artifact,避免留下半版本;
|
||||
- 已通过 `51/51` API HTTP integration tests、`2/2` upload tests 和 `6/6` API client tests;
|
||||
- 尚未完成:独立 validation run / renderer / capability / fixture 诊断、独立 preview session、品牌精确版本安装;因此 Phase 2 目录基础闭环已完成,完整任务继续进入 Phase 3/4。
|
||||
|
||||
### Phase 3:独立预览和模板管理页面
|
||||
|
||||
- [ ] 增加 preview session 或同等短期隔离上下文;
|
||||
|
||||
@@ -19,22 +19,33 @@ export interface ApiClientOptions {
|
||||
|
||||
export type RequestFn = <T>(
|
||||
path: string,
|
||||
options?: { method?: string; body?: unknown },
|
||||
options?: { method?: string; body?: unknown; rawBody?: unknown },
|
||||
) => Promise<T>;
|
||||
|
||||
export async function request<T>(
|
||||
state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined },
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown } = {},
|
||||
options: { method?: string; body?: unknown; rawBody?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: "application/json" };
|
||||
if (options.body !== undefined) headers["content-type"] = "application/json";
|
||||
if (options.rawBody === undefined && options.body !== undefined)
|
||||
headers["content-type"] = "application/json";
|
||||
if (state.token) headers.authorization = `Bearer ${state.token}`;
|
||||
const response = await state.fetcher(`${state.baseUrl}${path}`, {
|
||||
const init = {
|
||||
method: options.method ?? "GET",
|
||||
headers,
|
||||
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
||||
});
|
||||
...(options.rawBody !== undefined
|
||||
? { body: options.rawBody }
|
||||
: options.body === undefined
|
||||
? {}
|
||||
: { body: JSON.stringify(options.body) }),
|
||||
};
|
||||
const response = await (
|
||||
state.fetcher as unknown as (
|
||||
input: string,
|
||||
init?: { method?: string; headers?: Record<string, string>; body?: unknown },
|
||||
) => Promise<FetchResponse>
|
||||
)(`${state.baseUrl}${path}`, init);
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody);
|
||||
return body as T;
|
||||
|
||||
@@ -36,6 +36,14 @@ export type {
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "./types/template.js";
|
||||
export type {
|
||||
TemplateMethods,
|
||||
TemplatePackageActionResult,
|
||||
TemplatePackageAuditEntry,
|
||||
TemplatePackageImportResult,
|
||||
TemplatePackageList,
|
||||
TemplatePackageVersion,
|
||||
} from "./resources/template.js";
|
||||
export type { TrustContent, TrustContentInput } from "./types/trust.js";
|
||||
export type { PublicWorkspace } from "./types/workspace.js";
|
||||
export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types";
|
||||
@@ -90,7 +98,7 @@ export class ApiClient
|
||||
private readonly state: ClientState;
|
||||
private readonly requestFn: <T>(
|
||||
path: string,
|
||||
options?: { method?: string; body?: unknown },
|
||||
options?: { method?: string; body?: unknown; rawBody?: unknown },
|
||||
) => Promise<T>;
|
||||
private resources!: {
|
||||
booking: BookingMethods;
|
||||
@@ -229,6 +237,21 @@ export class ApiClient
|
||||
updateAdminMiniAppSettings = (
|
||||
...arguments_: Parameters<BrandMethods["updateAdminMiniAppSettings"]>
|
||||
) => this.resources.brand.updateAdminMiniAppSettings(...arguments_);
|
||||
listAdminTemplatePackages = (
|
||||
...arguments_: Parameters<TemplateMethods["listAdminTemplatePackages"]>
|
||||
) => this.resources.template.listAdminTemplatePackages(...arguments_);
|
||||
importAdminTemplatePackage = (
|
||||
...arguments_: Parameters<TemplateMethods["importAdminTemplatePackage"]>
|
||||
) => this.resources.template.importAdminTemplatePackage(...arguments_);
|
||||
publishAdminTemplatePackage = (
|
||||
...arguments_: Parameters<TemplateMethods["publishAdminTemplatePackage"]>
|
||||
) => this.resources.template.publishAdminTemplatePackage(...arguments_);
|
||||
retireAdminTemplatePackage = (
|
||||
...arguments_: Parameters<TemplateMethods["retireAdminTemplatePackage"]>
|
||||
) => this.resources.template.retireAdminTemplatePackage(...arguments_);
|
||||
listAdminTemplatePackageAudit = (
|
||||
...arguments_: Parameters<TemplateMethods["listAdminTemplatePackageAudit"]>
|
||||
) => this.resources.template.listAdminTemplatePackageAudit(...arguments_);
|
||||
getPublicTemplate = (...arguments_: Parameters<TemplateMethods["getPublicTemplate"]>) =>
|
||||
this.resources.template.getPublicTemplate(...arguments_);
|
||||
listPublicTemplates = (...arguments_: Parameters<TemplateMethods["listPublicTemplates"]>) =>
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface SessionMethods {
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
}>;
|
||||
changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }>;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,14 @@ import type { AdminTemplateContent } from "../types/template.js";
|
||||
import type { BrandTemplateDefinition } from "../types/template-definition.js";
|
||||
|
||||
export interface TemplateMethods {
|
||||
listAdminTemplatePackages(params?: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}): Promise<TemplatePackageList>;
|
||||
importAdminTemplatePackage(body: unknown): Promise<TemplatePackageImportResult>;
|
||||
publishAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
|
||||
retireAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
|
||||
listAdminTemplatePackageAudit(id: string): Promise<TemplatePackageAuditEntry[]>;
|
||||
getPublicTemplate(key: BrandTemplateKey): Promise<BrandTemplateDefinition>;
|
||||
listPublicTemplates(): Promise<{
|
||||
industries: BrandTemplateDefinition[];
|
||||
@@ -86,8 +94,92 @@ export interface TemplateMethods {
|
||||
rollbackAdminTemplate(): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface TemplatePackageVersion {
|
||||
id: string;
|
||||
templatePackageId: string;
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
visualTemplateKey: string | null;
|
||||
status: "imported" | "published" | "retired" | "disabled";
|
||||
contentChecksum: string;
|
||||
archiveChecksum: string;
|
||||
validationReport: Record<string, unknown>;
|
||||
importedAt: string;
|
||||
updatedAt: string;
|
||||
importedBy: { id: string; username: string; displayName: string };
|
||||
}
|
||||
|
||||
export interface TemplatePackageList {
|
||||
items: TemplatePackageVersion[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface TemplatePackageActionResult {
|
||||
changed: boolean;
|
||||
version: Pick<
|
||||
TemplatePackageVersion,
|
||||
| "id"
|
||||
| "packageKey"
|
||||
| "version"
|
||||
| "displayName"
|
||||
| "visualTemplateKey"
|
||||
| "status"
|
||||
| "contentChecksum"
|
||||
| "archiveChecksum"
|
||||
| "importedAt"
|
||||
>;
|
||||
}
|
||||
|
||||
export interface TemplatePackageAuditEntry {
|
||||
id: string;
|
||||
action: string;
|
||||
fromStatus: TemplatePackageVersion["status"] | null;
|
||||
toStatus: TemplatePackageVersion["status"] | null;
|
||||
requestId: string | null;
|
||||
metadata: Record<string, unknown> | null;
|
||||
createdAt: string;
|
||||
actor: { id: string; username: string; displayName: string };
|
||||
}
|
||||
|
||||
export interface TemplatePackageImportResult {
|
||||
imported: boolean;
|
||||
idempotent: boolean;
|
||||
version: Pick<
|
||||
TemplatePackageVersion,
|
||||
| "id"
|
||||
| "packageKey"
|
||||
| "version"
|
||||
| "displayName"
|
||||
| "visualTemplateKey"
|
||||
| "status"
|
||||
| "contentChecksum"
|
||||
| "archiveChecksum"
|
||||
| "importedAt"
|
||||
>;
|
||||
}
|
||||
|
||||
export function templateMethods({ request }: { request: RequestFn }): TemplateMethods {
|
||||
return {
|
||||
listAdminTemplatePackages: (params = {}) => {
|
||||
const query = [
|
||||
params.page === undefined ? null : `page=${encodeURIComponent(String(params.page))}`,
|
||||
params.pageSize === undefined
|
||||
? null
|
||||
: `pageSize=${encodeURIComponent(String(params.pageSize))}`,
|
||||
].filter((item): item is string => item !== null);
|
||||
return request(`/admin/templates${query.length ? `?${query.join("&")}` : ""}`);
|
||||
},
|
||||
importAdminTemplatePackage: (body) =>
|
||||
request("/admin/templates/import", { method: "POST", rawBody: body }),
|
||||
publishAdminTemplatePackage: (id) =>
|
||||
request(`/admin/templates/${encodeURIComponent(id)}/publish`, { method: "POST" }),
|
||||
retireAdminTemplatePackage: (id) =>
|
||||
request(`/admin/templates/${encodeURIComponent(id)}/retire`, { method: "POST" }),
|
||||
listAdminTemplatePackageAudit: (id) =>
|
||||
request(`/admin/templates/${encodeURIComponent(id)}/audit`),
|
||||
getPublicTemplate: (key) => request(`/public/templates/${key}`),
|
||||
listPublicTemplates: () =>
|
||||
request<{
|
||||
|
||||
@@ -95,3 +95,29 @@ test("小程序上传配置会提交请求地址", async () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("模板目录客户端发送分页并支持版本发布和审计", async () => {
|
||||
const calls: Array<{ url: string; method?: string }> = [];
|
||||
const client = new ApiClient({
|
||||
baseUrl: "http://api.test",
|
||||
token: "template-admin-token",
|
||||
fetcher: async (url, init) => {
|
||||
calls.push({ url, method: init?.method });
|
||||
return response(
|
||||
url.includes("/audit")
|
||||
? []
|
||||
: url.endsWith("/publish")
|
||||
? { changed: true, version: { id: "version-1", status: "published" } }
|
||||
: { items: [], page: 2, pageSize: 10, total: 0 },
|
||||
);
|
||||
},
|
||||
});
|
||||
await client.listAdminTemplatePackages({ page: 2, pageSize: 10 });
|
||||
await client.publishAdminTemplatePackage("version/1");
|
||||
await client.listAdminTemplatePackageAudit("version/1");
|
||||
assert.deepEqual(calls, [
|
||||
{ url: "http://api.test/admin/templates?page=2&pageSize=10", method: "GET" },
|
||||
{ url: "http://api.test/admin/templates/version%2F1/publish", method: "POST" },
|
||||
{ url: "http://api.test/admin/templates/version%2F1/audit", method: "GET" },
|
||||
]);
|
||||
});
|
||||
Reference in new issue
Block a user