feat: 收口模板升级与阶段七持续回归
This commit is contained in:
1 parent
ec16fff70e
commit
71c528de34
29 files changed
+1962
-304
No files matched your search
@@ -24,6 +24,10 @@ jobs:
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm check
|
||||
- run: pnpm validate:templates
|
||||
- run: pnpm template:compatibility
|
||||
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
|
||||
- run: pnpm template:conformance
|
||||
- run: pnpm template:doctor
|
||||
|
||||
build:
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Divider,
|
||||
Input,
|
||||
Popconfirm,
|
||||
Modal,
|
||||
Form,
|
||||
Select,
|
||||
@@ -13,10 +15,8 @@ import {
|
||||
Spin,
|
||||
Tabs,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import type { BrandTemplateKey } 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";
|
||||
@@ -27,8 +27,6 @@ import { MiniAppSettingsTab, type MiniAppSettingsValues } from "./MiniAppSetting
|
||||
import { usePublicationQueries } from "./use-publication-queries.js";
|
||||
import { usePublicationMutations } from "./use-publication-mutations.js";
|
||||
|
||||
const client = createApiClient();
|
||||
|
||||
const destinations: Record<string, string> = {
|
||||
brand: "/admin/brand",
|
||||
positioning: "/admin/brand",
|
||||
@@ -45,6 +43,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
const [industryTarget, setIndustryTarget] = useState<BrandTemplateKey | null>(null);
|
||||
const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null);
|
||||
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
|
||||
const [preservedBindings, setPreservedBindings] = useState<Record<string, boolean>>({});
|
||||
const [note, setNote] = useState("");
|
||||
const [activeTab, setActiveTab] = useState("content");
|
||||
const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
|
||||
@@ -127,94 +126,6 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
}>;
|
||||
|
||||
const contentTab = null;
|
||||
const miniAppSettingsTab = (
|
||||
<div className="admin-stack admin-stack-lg">
|
||||
<AdminSection
|
||||
title="小程序上传配置"
|
||||
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
|
||||
>
|
||||
{miniAppSettings.data?.buildError ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
className="admin-offset-bottom"
|
||||
message="小程序构建参数未就绪"
|
||||
description={miniAppSettings.data.buildError}
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
className="admin-offset-bottom"
|
||||
message={`请求域名 ${miniAppSettings.data?.requestDomain ?? "未确认"}`}
|
||||
description="该域名在构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致;不一致会导致小程序打开即加载失败。"
|
||||
/>
|
||||
)}
|
||||
<Form
|
||||
form={miniAppSettingsForm}
|
||||
layout="vertical"
|
||||
onFinish={(values) => saveMiniAppSettings.mutate(values)}
|
||||
>
|
||||
<Form.Item
|
||||
name="appId"
|
||||
label="微信 AppID"
|
||||
rules={[{ required: true, message: "请输入微信 AppID" }]}
|
||||
>
|
||||
<Input maxLength={100} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="apiBaseUrl"
|
||||
label="小程序请求地址"
|
||||
rules={[
|
||||
{ required: true, message: "请输入小程序请求地址" },
|
||||
{
|
||||
validator: (_rule, value: string) =>
|
||||
!value || /^https:\/\/[^/]+/.test(value)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(
|
||||
new Error(
|
||||
"公网地址必须以 https:// 开头,例如 https://wechat.app.que01.top/api",
|
||||
),
|
||||
),
|
||||
},
|
||||
]}
|
||||
extra="构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致。修改后需重新构建并上传代码才生效。"
|
||||
>
|
||||
<Input maxLength={200} placeholder="https://wechat.app.que01.top/api" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="privateKey"
|
||||
label="上传私钥"
|
||||
help={
|
||||
miniAppSettings.data?.hasStoredCredentials
|
||||
? "已加密保存。留空保持现有私钥,输入新值可替换。"
|
||||
: "粘贴微信开发者工具导出的 private.<appid>.key 全文,必须保留换行。"
|
||||
}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={5}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder={"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"}
|
||||
className="admin-code-input"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Space>
|
||||
<Button type="primary" loading={saveMiniAppSettings.isPending} htmlType="submit">
|
||||
保存上传配置
|
||||
</Button>
|
||||
{miniAppSettings.data?.hasStoredCredentials ? (
|
||||
<StatusTag tone="success" label="已加密保存上传凭据" />
|
||||
) : (
|
||||
<StatusTag tone="warning" label="未配置上传私钥" />
|
||||
)}
|
||||
</Space>
|
||||
<MutationError error={saveMiniAppSettings.error} />
|
||||
</Form>
|
||||
</AdminSection>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryState loading={loading} error={error} onRetry={retry}>
|
||||
<AdminPageHeader
|
||||
@@ -287,33 +198,125 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
label={`最新版本 ${templatePreview.data?.latestVersion ?? "加载中"}`}
|
||||
/>
|
||||
{templatePreview.data?.canUpgrade ? (
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
disabled={!canManageTemplate}
|
||||
loading={upgradeTemplate.isPending}
|
||||
onClick={() => upgradeTemplate.mutate()}
|
||||
<Popconfirm
|
||||
title="确认升级到已发布模板包?"
|
||||
description={`新增 binding ${templatePreview.data.changes.templateBindings.added.length} 项;冲突值需逐项确认保留。升级不会删除字段或业务内容。`}
|
||||
okText="确认升级"
|
||||
cancelText="取消"
|
||||
onConfirm={() => {
|
||||
const preview = templatePreview.data;
|
||||
if (!preview?.targetPackageVersionId || !preview.targetContentChecksum)
|
||||
return;
|
||||
if (
|
||||
!preview.conflicts.every(
|
||||
(item) => preservedBindings[`${item.key}:${item.binding}`],
|
||||
)
|
||||
)
|
||||
return;
|
||||
upgradeTemplate.mutate({
|
||||
templatePackageVersionId: preview.targetPackageVersionId,
|
||||
expectedContentChecksum: preview.targetContentChecksum,
|
||||
expectedCurrentVersion: preview.currentVersion,
|
||||
expectedCurrentPackageVersionId: preview.currentPackageVersionId,
|
||||
confirm: true,
|
||||
preservedBindings: preview.conflicts.map(({ key, binding }) => ({
|
||||
key,
|
||||
binding,
|
||||
action: "preserve" as const,
|
||||
})),
|
||||
});
|
||||
}}
|
||||
>
|
||||
升级模板
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
disabled={
|
||||
!canManageTemplate ||
|
||||
!templatePreview.data?.targetPackageVersionId ||
|
||||
!templatePreview.data.conflicts.every(
|
||||
(item) => preservedBindings[`${item.key}:${item.binding}`],
|
||||
)
|
||||
}
|
||||
loading={upgradeTemplate.isPending}
|
||||
>
|
||||
升级模板
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<StatusTag tone="success" label="已是最新版本" />
|
||||
)}
|
||||
{templatePreview.data?.canRollback ? (
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
disabled={!canManageTemplate}
|
||||
loading={rollbackTemplate.isPending}
|
||||
onClick={() => rollbackTemplate.mutate()}
|
||||
<Popconfirm
|
||||
title="确认恢复上一版模板配置基线?"
|
||||
description="不会删除品牌字段、业务内容、历史发布或客户咨询记录。"
|
||||
okText="确认回滚"
|
||||
cancelText="取消"
|
||||
onConfirm={() => {
|
||||
const currentVersion = templatePreview.data?.currentVersion;
|
||||
if (!currentVersion) return;
|
||||
rollbackTemplate.mutate({
|
||||
expectedCurrentVersion: currentVersion,
|
||||
confirm: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
回滚到上一版
|
||||
</Button>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
disabled={!canManageTemplate}
|
||||
loading={rollbackTemplate.isPending}
|
||||
>
|
||||
回滚到上一版
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</Space>
|
||||
<p className="admin-section-description admin-offset-top-sm">
|
||||
行业模板随品牌身份固定,只能升级版本、不能更换行业;升级只补充字段与模块,不覆盖已有内容。视觉模板只替换排版风格。
|
||||
行业模板随品牌身份固定。升级目标为当前视觉模板最新已发布包,并按包版本与 checksum
|
||||
锁定预览;新增字段会补入,改动冲突和已移除字段不会覆盖或删除。回滚仅恢复配置基线,不删除品牌字段、内容或历史发布。
|
||||
</p>
|
||||
{templatePreview.data?.conflicts.length ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message={`请逐项确认保留 ${templatePreview.data.conflicts.length} 个现有品牌配置值`}
|
||||
description={
|
||||
<Space direction="vertical">
|
||||
{templatePreview.data.conflicts.map((item) => {
|
||||
const key = `${item.key}:${item.binding}`;
|
||||
return (
|
||||
<Checkbox
|
||||
key={key}
|
||||
checked={Boolean(preservedBindings[key])}
|
||||
onChange={(event) =>
|
||||
setPreservedBindings((current) => ({
|
||||
...current,
|
||||
[key]: event.target.checked,
|
||||
}))
|
||||
}
|
||||
>
|
||||
保留 {item.binding}({item.reason})
|
||||
</Checkbox>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{templatePreview.data ? (
|
||||
<div className="admin-section-description admin-offset-top-sm">
|
||||
页面入口变更:新增 {templatePreview.data.changes.pages.added.length}、变更{" "}
|
||||
{templatePreview.data.changes.pages.changed.length}、移除{" "}
|
||||
{templatePreview.data.changes.pages.removed.length};资源槽位变更:新增{" "}
|
||||
{templatePreview.data.changes.assets.slots.added.length}、变更{" "}
|
||||
{templatePreview.data.changes.assets.slots.changed.length}、移除{" "}
|
||||
{templatePreview.data.changes.assets.slots.removed.length};
|
||||
{templatePreview.data.changes.assets.files.available
|
||||
? `包内文件变更:新增 ${templatePreview.data.changes.assets.files.added?.length ?? 0}、变更 ${templatePreview.data.changes.assets.files.changed?.length ?? 0}、移除 ${templatePreview.data.changes.assets.files.removed?.length ?? 0}`
|
||||
: templatePreview.data.changes.assets.files.reason}
|
||||
。模块与 renderer 由已部署的平台视觉模板管理,此次包升级不会替换 renderer。
|
||||
</div>
|
||||
) : null}
|
||||
<MutationError
|
||||
error={templatePreview.error || upgradeTemplate.error || rollbackTemplate.error}
|
||||
/>
|
||||
|
||||
@@ -33,14 +33,22 @@ export function usePublicationMutations({
|
||||
},
|
||||
});
|
||||
const upgradeTemplate = useMutation({
|
||||
mutationFn: () => client.upgradeAdminTemplate(),
|
||||
mutationFn: (input: {
|
||||
templatePackageVersionId: string;
|
||||
expectedContentChecksum: string;
|
||||
expectedCurrentVersion: string;
|
||||
expectedCurrentPackageVersionId: string | null;
|
||||
confirm: true;
|
||||
preservedBindings: Array<{ key: string; binding: string; action: "preserve" }>;
|
||||
}) => client.upgradeAdminTemplate(input),
|
||||
onSuccess: () => {
|
||||
message.success("行业模板已升级,现有内容未被覆盖");
|
||||
refresh();
|
||||
},
|
||||
});
|
||||
const rollbackTemplate = useMutation({
|
||||
mutationFn: () => client.rollbackAdminTemplate(),
|
||||
mutationFn: (input: { expectedCurrentVersion: string; confirm: true }) =>
|
||||
client.rollbackAdminTemplate(input),
|
||||
onSuccess: () => {
|
||||
message.success("行业模板配置基线已回滚");
|
||||
refresh();
|
||||
|
||||
@@ -35,6 +35,10 @@ export function TemplateManagementPage() {
|
||||
queryFn: () => client.listAdminTemplatePackageAudit(auditId as string),
|
||||
enabled: Boolean(auditId),
|
||||
});
|
||||
const metrics = useQuery({
|
||||
queryKey: ["admin-template-operation-failures", 30],
|
||||
queryFn: () => client.getAdminTemplateOperationFailures({ days: 30 }),
|
||||
});
|
||||
const lifecycle = useMutation({
|
||||
mutationFn: async ({ id, action }: { id: string; action: "publish" | "retire" }) =>
|
||||
action === "publish"
|
||||
@@ -108,6 +112,29 @@ export function TemplateManagementPage() {
|
||||
/>
|
||||
) : null}
|
||||
{lifecycle.isError ? <ErrorNote error={lifecycle.error} /> : null}
|
||||
<AdminSection
|
||||
title="近 30 天失败概览"
|
||||
description="只显示按操作类别聚合的数量,不包含 requestId、错误正文或品牌内容。"
|
||||
>
|
||||
<QueryState
|
||||
loading={metrics.isLoading}
|
||||
error={metrics.error}
|
||||
onRetry={() => void metrics.refetch()}
|
||||
>
|
||||
<List
|
||||
size="small"
|
||||
grid={{ gutter: 16, column: 4 }}
|
||||
dataSource={metrics.data?.failures ?? []}
|
||||
renderItem={(item) => (
|
||||
<List.Item>
|
||||
<Typography.Text>
|
||||
{item.action}:<Typography.Text strong>{item.count}</Typography.Text>
|
||||
</Typography.Text>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</QueryState>
|
||||
</AdminSection>
|
||||
<AdminSection
|
||||
title="已导入版本"
|
||||
description="同一 package key 的不同版本并列保留,发布品牌时再选择安装版本。"
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE "TemplateOperationFailureEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"resultCode" TEXT NOT NULL,
|
||||
"requestId" TEXT,
|
||||
"actorId" TEXT,
|
||||
"brandId" TEXT,
|
||||
"packageKey" TEXT,
|
||||
"version" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TemplateOperationFailureEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "TemplateOperationFailureEvent_createdAt_action_idx" ON "TemplateOperationFailureEvent"("createdAt", "action");
|
||||
CREATE INDEX "TemplateOperationFailureEvent_packageKey_createdAt_idx" ON "TemplateOperationFailureEvent"("packageKey", "createdAt");
|
||||
@@ -112,25 +112,25 @@ enum MiniAppReleaseStatus {
|
||||
}
|
||||
|
||||
model MiniAppReleaseTask {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
releaseId String?
|
||||
release BrandRelease? @relation(fields: [releaseId], references: [id], onDelete: SetNull)
|
||||
release BrandRelease? @relation(fields: [releaseId], references: [id], onDelete: SetNull)
|
||||
version Int
|
||||
status MiniAppReleaseStatus @default(built)
|
||||
status MiniAppReleaseStatus @default(built)
|
||||
artifactPath String?
|
||||
buildLogs Json?
|
||||
buildStatus MiniAppBuildStatus @default(idle)
|
||||
uploadStatus MiniAppUploadStatus @default(idle)
|
||||
reviewStatus MiniAppReviewStatus @default(not_submitted)
|
||||
buildStatus MiniAppBuildStatus @default(idle)
|
||||
uploadStatus MiniAppUploadStatus @default(idle)
|
||||
reviewStatus MiniAppReviewStatus @default(not_submitted)
|
||||
actorId String
|
||||
error String?
|
||||
weappUploadId String?
|
||||
audit Json?
|
||||
attempts MiniAppReleaseAttempt[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([brandId, version])
|
||||
@@index([brandId, createdAt])
|
||||
@@ -171,7 +171,7 @@ enum MiniAppAttemptStatus {
|
||||
}
|
||||
|
||||
model MiniAppReleaseAttempt {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
taskId String
|
||||
task MiniAppReleaseTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||
brandId String
|
||||
@@ -179,17 +179,17 @@ model MiniAppReleaseAttempt {
|
||||
phase MiniAppAttemptPhase
|
||||
attempt Int
|
||||
status MiniAppAttemptStatus @default(running)
|
||||
leaseToken String @unique
|
||||
leaseToken String @unique
|
||||
leaseExpiresAt DateTime
|
||||
startedAt DateTime @default(now())
|
||||
heartbeatAt DateTime @default(now())
|
||||
startedAt DateTime @default(now())
|
||||
heartbeatAt DateTime @default(now())
|
||||
finishedAt DateTime?
|
||||
artifactPath String?
|
||||
externalId String?
|
||||
error String?
|
||||
logs Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([taskId, phase, attempt])
|
||||
@@index([brandId, taskId, phase, status])
|
||||
@@ -223,19 +223,19 @@ model CapabilityAuditLog {
|
||||
}
|
||||
|
||||
model BrandTemplateInstallation {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
templateKey String
|
||||
templateVersion String @default("1.0.0")
|
||||
templateVersion String @default("1.0.0")
|
||||
visualTemplateKey String?
|
||||
templatePackageVersionId String?
|
||||
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
|
||||
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
|
||||
contentChecksum String?
|
||||
configSnapshot Json
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([brandId, templateKey])
|
||||
@@index([brandId])
|
||||
@@ -453,52 +453,52 @@ model Tag {
|
||||
}
|
||||
|
||||
model AdminUser {
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
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")
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
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[]
|
||||
id String @id @default(uuid())
|
||||
packageKey String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
versions TemplatePackageVersion[]
|
||||
}
|
||||
|
||||
model TemplatePackageVersion {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
templatePackageId String
|
||||
templatePackage TemplatePackage @relation(fields: [templatePackageId], references: [id], onDelete: Cascade)
|
||||
packageKey String
|
||||
version String
|
||||
displayName 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[]
|
||||
installations BrandTemplateInstallation[] @relation("BrandTemplateInstallationPackageVersion")
|
||||
bootstrapImports TemplateBootstrapImport[]
|
||||
importedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
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[]
|
||||
installations BrandTemplateInstallation[] @relation("BrandTemplateInstallationPackageVersion")
|
||||
bootstrapImports TemplateBootstrapImport[]
|
||||
importedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([templatePackageId, version])
|
||||
@@index([packageKey, status])
|
||||
@@ -506,20 +506,20 @@ model TemplatePackageVersion {
|
||||
}
|
||||
|
||||
model TemplateBootstrapImport {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
templatePackageVersionId String
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
|
||||
packageKey String
|
||||
packageVersion String
|
||||
contentChecksum String
|
||||
actorId String
|
||||
strategy String @default("missing_only")
|
||||
strategy String @default("missing_only")
|
||||
status String
|
||||
result Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([brandId, createdAt])
|
||||
@@index([templatePackageVersionId, createdAt])
|
||||
@@ -527,22 +527,37 @@ model TemplateBootstrapImport {
|
||||
}
|
||||
|
||||
model TemplatePackageAuditLog {
|
||||
id String @id @default(uuid())
|
||||
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())
|
||||
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 TemplateOperationFailureEvent {
|
||||
id String @id @default(uuid())
|
||||
action String
|
||||
resultCode String
|
||||
requestId String?
|
||||
actorId String?
|
||||
brandId String?
|
||||
packageKey String?
|
||||
version String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt, action])
|
||||
@@index([packageKey, createdAt])
|
||||
}
|
||||
|
||||
model BrandMembership {
|
||||
id String @id @default(uuid())
|
||||
adminUserId String
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
MinLength,
|
||||
Matches,
|
||||
Max,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from "class-validator";
|
||||
import { brandTemplateKeys } from "@personal-brand/config";
|
||||
import type { BrandTemplateKey } from "@personal-brand/config";
|
||||
import { Type } from "class-transformer";
|
||||
export class UpdateBrandDto {
|
||||
@IsOptional() @IsString() name?: string;
|
||||
@IsOptional() @IsString() tagline?: string;
|
||||
@@ -107,6 +109,29 @@ export class InstallTemplateDto {
|
||||
@IsOptional() @IsUUID() templatePackageVersionId?: string;
|
||||
}
|
||||
|
||||
export class UpgradeTemplateDto {
|
||||
@IsUUID() templatePackageVersionId!: string;
|
||||
@IsString() @MinLength(1) expectedContentChecksum!: string;
|
||||
@IsString() @MinLength(1) expectedCurrentVersion!: string;
|
||||
@IsOptional() @IsUUID() expectedCurrentPackageVersionId?: string | null;
|
||||
@IsBoolean() confirm!: boolean;
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => PreserveTemplateBindingDto)
|
||||
preservedBindings!: PreserveTemplateBindingDto[];
|
||||
}
|
||||
|
||||
export class PreserveTemplateBindingDto {
|
||||
@IsString() key!: string;
|
||||
@IsString() binding!: string;
|
||||
@IsIn(["preserve"]) action!: "preserve";
|
||||
}
|
||||
|
||||
export class RollbackTemplateDto {
|
||||
@IsString() @MinLength(1) expectedCurrentVersion!: string;
|
||||
@IsBoolean() confirm!: boolean;
|
||||
}
|
||||
|
||||
export class PreviewTemplateSampleDto {
|
||||
@IsOptional() @IsUUID() templatePackageVersionId?: string;
|
||||
@IsOptional() @IsIn(["missing_only"]) strategy?: "missing_only";
|
||||
|
||||
@@ -27,7 +27,11 @@ export class AdminTemplatePackageController {
|
||||
@Post("import")
|
||||
async import(@Req() request: FastifyRequest) {
|
||||
const { subject } = await this.access.requireTemplateAdmin(request);
|
||||
return this.templates.importArchive(request, subject);
|
||||
return this.templates.importArchive(
|
||||
request,
|
||||
subject,
|
||||
request.headers["x-request-id"]?.toString() ?? request.id,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(":id/publish")
|
||||
|
||||
@@ -14,6 +14,7 @@ import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const MAX_ARCHIVE_BYTES = 50 * 1024 * 1024;
|
||||
@@ -181,13 +182,15 @@ export class AdminTemplatePackageService {
|
||||
};
|
||||
}
|
||||
|
||||
async importArchive(request: FastifyRequest, actorId: string) {
|
||||
async importArchive(request: FastifyRequest, actorId: string, requestId?: 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;
|
||||
let failurePackageKey: string | undefined;
|
||||
let failureVersion: string | undefined;
|
||||
try {
|
||||
for await (const chunk of part.file) {
|
||||
const buffer = Buffer.from(chunk as Uint8Array);
|
||||
@@ -242,6 +245,8 @@ export class AdminTemplatePackageService {
|
||||
path.join(packageRoot, "template.json"),
|
||||
"template.json",
|
||||
)) as Manifest;
|
||||
failurePackageKey = typeof manifest.packageKey === "string" ? manifest.packageKey : undefined;
|
||||
failureVersion = typeof manifest.version === "string" ? manifest.version : undefined;
|
||||
const packageJson = jsonObject(
|
||||
await this.readJson(path.join(packageRoot, "package.json"), "package.json"),
|
||||
"package.json",
|
||||
@@ -304,6 +309,7 @@ export class AdminTemplatePackageService {
|
||||
errors: [],
|
||||
fileCount: files.length,
|
||||
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
|
||||
files: checksums.files.map((file) => ({ ...file })),
|
||||
},
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
archiveChecksum,
|
||||
@@ -328,6 +334,14 @@ export class AdminTemplatePackageService {
|
||||
return { imported: true, idempotent: false, version: this.publicVersion(version) };
|
||||
} catch (error) {
|
||||
if (storedArtifactPath) await fs.rm(storedArtifactPath, { force: true });
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "import",
|
||||
error,
|
||||
...(requestId ? { requestId } : {}),
|
||||
actorId,
|
||||
...(failurePackageKey ? { packageKey: failurePackageKey } : {}),
|
||||
...(failureVersion ? { version: failureVersion } : {}),
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.rm(temporaryRoot, { recursive: true, force: true });
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
|
||||
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
|
||||
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
@@ -118,7 +119,18 @@ export class AdminTemplatePreviewService {
|
||||
};
|
||||
}
|
||||
|
||||
const projection = await this.buildPreview(id, industry);
|
||||
let projection: Awaited<ReturnType<AdminTemplatePreviewService["buildPreview"]>>;
|
||||
try {
|
||||
projection = await this.buildPreview(id, industry);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "preview",
|
||||
error,
|
||||
...(requestId ? { requestId } : {}),
|
||||
actorId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
this.cleanupPreviewSessions();
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const expiresAt = Date.now() + 15 * 60 * 1000;
|
||||
|
||||
@@ -15,6 +15,8 @@ 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";
|
||||
import { TemplateOperationMetricsController } from "./template-operation-metrics.controller.js";
|
||||
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
|
||||
@@ -29,6 +31,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
||||
AdminLocalUploadController,
|
||||
AdminBookingController,
|
||||
AdminTemplatePackageController,
|
||||
TemplateOperationMetricsController,
|
||||
],
|
||||
providers: [
|
||||
AdminBrandConfigService,
|
||||
@@ -40,6 +43,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
||||
AdminTemplatePackageService,
|
||||
AdminTemplatePreviewService,
|
||||
AdminTemplatePreviewAssetsService,
|
||||
TemplateOperationMetricsService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { HttpException } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
export async function recordTemplateOperationFailure(
|
||||
prisma: PrismaService,
|
||||
input: {
|
||||
action: string;
|
||||
error: unknown;
|
||||
requestId?: string;
|
||||
actorId?: string;
|
||||
brandId?: string;
|
||||
packageKey?: string;
|
||||
version?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const status = input.error instanceof HttpException ? input.error.getStatus() : 500;
|
||||
try {
|
||||
await prisma.templateOperationFailureEvent.create({
|
||||
data: {
|
||||
action: input.action,
|
||||
resultCode: `HTTP_${status}`,
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
...(input.actorId ? { actorId: input.actorId } : {}),
|
||||
...(input.brandId ? { brandId: input.brandId } : {}),
|
||||
...(input.packageKey ? { packageKey: input.packageKey } : {}),
|
||||
...(input.version ? { version: input.version } : {}),
|
||||
},
|
||||
});
|
||||
await prisma.templateOperationFailureEvent.deleteMany({
|
||||
where: { createdAt: { lt: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000) } },
|
||||
});
|
||||
} catch {
|
||||
// Failure telemetry must never replace the operation's original result.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Controller, Get, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsInt, IsOptional, Max, Min } from "class-validator";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
|
||||
|
||||
class TemplateOperationMetricsQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(90)
|
||||
days = 30;
|
||||
}
|
||||
|
||||
@Controller("admin/template-operations")
|
||||
export class TemplateOperationMetricsController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly metrics: TemplateOperationMetricsService,
|
||||
) {}
|
||||
|
||||
@Get("failures")
|
||||
async failures(@Req() request: FastifyRequest, @Query() query: TemplateOperationMetricsQueryDto) {
|
||||
await this.access.requireTemplateAdmin(request);
|
||||
return this.metrics.failures(query.days);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
const trackedActions = [
|
||||
"import",
|
||||
"preview",
|
||||
"install",
|
||||
"upgrade",
|
||||
"rollback",
|
||||
"install_conflict",
|
||||
] as const;
|
||||
|
||||
@Injectable()
|
||||
export class TemplateOperationMetricsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async failures(days = 30) {
|
||||
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
const [templateEvents, releaseAttempts] = await Promise.all([
|
||||
this.prisma.templateOperationFailureEvent.groupBy({
|
||||
by: ["action"],
|
||||
where: { createdAt: { gte: since } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.miniAppReleaseAttempt.groupBy({
|
||||
by: ["phase", "status"],
|
||||
where: {
|
||||
createdAt: { gte: since },
|
||||
status: { in: ["failed", "timed_out"] },
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
const eventCounts = new Map(templateEvents.map((item) => [item.action, item._count._all]));
|
||||
const buildUploadCounts = new Map<string, number>();
|
||||
for (const item of releaseAttempts) {
|
||||
const action = item.phase === "build" ? "build" : "upload";
|
||||
buildUploadCounts.set(action, (buildUploadCounts.get(action) ?? 0) + item._count._all);
|
||||
}
|
||||
return {
|
||||
since: since.toISOString(),
|
||||
until: new Date().toISOString(),
|
||||
days,
|
||||
backfilled: false,
|
||||
failures: [
|
||||
...trackedActions.map((action) => ({ action, count: eventCounts.get(action) ?? 0 })),
|
||||
{ action: "build", count: buildUploadCounts.get("build") ?? 0 },
|
||||
{ action: "upload", count: buildUploadCounts.get("upload") ?? 0 },
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
import { Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
|
||||
import { requireAdminIdentity } from "./admin-access.identity.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminTemplateController {
|
||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
||||
constructor(
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get("template/preview")
|
||||
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
@@ -13,13 +19,58 @@ class AdminTemplateController {
|
||||
}
|
||||
|
||||
@Post("template/upgrade")
|
||||
upgrade(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.upgrade(requireAdminIdentity(request).brandId);
|
||||
async upgrade(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpgradeTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.upgrade(
|
||||
identity.brandId,
|
||||
body,
|
||||
identity.subject,
|
||||
requestId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action:
|
||||
error instanceof Error && error.name.includes("Conflict")
|
||||
? "install_conflict"
|
||||
: "upgrade",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Post("template/rollback")
|
||||
rollback(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.rollback(requireAdminIdentity(request).brandId);
|
||||
async rollback(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: RollbackTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.rollback(
|
||||
identity.brandId,
|
||||
identity.subject,
|
||||
body,
|
||||
requestId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "rollback",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,15 @@ import { InstallTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "./admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspacePreviewController {
|
||||
constructor(
|
||||
private readonly workspaceService: AdminWorkspaceService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -23,12 +26,31 @@ class AdminWorkspacePreviewController {
|
||||
}
|
||||
|
||||
@Post("install")
|
||||
install(@Req() request: FastifyRequest, @Body() body: InstallTemplateDto): Promise<unknown> {
|
||||
return this.templateWorkspace.install(
|
||||
requireAdminIdentity(request).brandId,
|
||||
body.templateKey,
|
||||
body.templatePackageVersionId,
|
||||
);
|
||||
async install(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: InstallTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.install(
|
||||
identity.brandId,
|
||||
body.templateKey,
|
||||
body.templatePackageVersionId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action:
|
||||
error instanceof Error && error.name.includes("Conflict")
|
||||
? "install_conflict"
|
||||
: "install",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import type { TemplatePackageVersion } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
defaultBrandTemplateKey,
|
||||
@@ -12,8 +14,11 @@ import {
|
||||
isVisualTemplateCompatible,
|
||||
} from "@personal-brand/config";
|
||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@Injectable()
|
||||
export class TemplateWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -230,65 +235,230 @@ export class TemplateWorkspaceService {
|
||||
const templateKey = await this.getEffectiveTemplateKey(brandId);
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("当前行业模板不存在");
|
||||
const [installation, fields] = await Promise.all([
|
||||
const [installation, brand] = await Promise.all([
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
]);
|
||||
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
|
||||
const currentVersion = installation?.templateVersion ?? template.version;
|
||||
const config = record(brand?.config);
|
||||
const visualTemplateKey =
|
||||
installation?.visualTemplateKey ??
|
||||
(typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined) ??
|
||||
getDefaultVisualTemplateKey(templateKey);
|
||||
const currentPackage = installation?.templatePackageVersionId
|
||||
? await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: installation.templatePackageVersionId },
|
||||
})
|
||||
: null;
|
||||
const targetPackage = visualTemplateKey
|
||||
? await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualTemplateKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
})
|
||||
: null;
|
||||
const targetManifest = record(targetPackage?.manifestSnapshot);
|
||||
const currentManifest = record(currentPackage?.manifestSnapshot);
|
||||
const currentDeclarations = manifestRecords(currentManifest.templateFields);
|
||||
const targetDeclarations = manifestRecords(targetManifest.templateFields);
|
||||
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
|
||||
const targetByKey = new Map(targetDeclarations.map((item) => [String(item.key), item]));
|
||||
const addedBindings = targetDeclarations.filter((item) => !currentByKey.has(String(item.key)));
|
||||
const removedBindings = currentDeclarations.filter(
|
||||
(item) => !targetByKey.has(String(item.key)),
|
||||
);
|
||||
const changedBindings = targetDeclarations.flatMap((item) => {
|
||||
const current = currentByKey.get(String(item.key));
|
||||
if (!current || JSON.stringify(current) === JSON.stringify(item)) return [];
|
||||
return [{ key: String(item.key), current, proposed: item }];
|
||||
});
|
||||
const conflicts = [
|
||||
...addedBindings.flatMap((item) =>
|
||||
hasBindingValue(config, item.binding)
|
||||
? [
|
||||
{
|
||||
key: String(item.key),
|
||||
binding: String(item.binding),
|
||||
reason: "新增字段已有同路径品牌值,升级会原样保留",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
...changedBindings.flatMap(({ key, current }) =>
|
||||
hasBindingValue(config, current.binding)
|
||||
? [{ key, binding: String(current.binding), reason: "该品牌配置已填写,升级不会覆盖" }]
|
||||
: [],
|
||||
),
|
||||
...removedBindings.flatMap((item) =>
|
||||
hasBindingValue(config, item.binding)
|
||||
? [
|
||||
{
|
||||
key: String(item.key),
|
||||
binding: String(item.binding),
|
||||
reason: "新版不再声明该字段,已有品牌值仍会保留",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
];
|
||||
const currentEntrypoints = record(currentManifest.entrypoints);
|
||||
const targetEntrypoints = record(targetManifest.entrypoints);
|
||||
const currentAssets = manifestRecords(currentManifest.assetSlots);
|
||||
const targetAssets = manifestRecords(targetManifest.assetSlots);
|
||||
const [currentFiles, targetFiles] = await Promise.all([
|
||||
currentPackage ? readPackageFiles(currentPackage) : Promise.resolve([]),
|
||||
targetPackage ? readPackageFiles(targetPackage) : Promise.resolve([]),
|
||||
]);
|
||||
const currentCapabilities = stringList(currentManifest.requiredCapabilities);
|
||||
const targetCapabilities = stringList(targetManifest.requiredCapabilities);
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
return {
|
||||
templateKey,
|
||||
currentVersion,
|
||||
latestVersion: template.version,
|
||||
canUpgrade: currentVersion !== template.version,
|
||||
latestVersion: targetPackage?.version ?? template.version,
|
||||
currentPackageVersionId: currentPackage?.id ?? null,
|
||||
currentContentChecksum:
|
||||
currentPackage?.contentChecksum ?? installation?.contentChecksum ?? null,
|
||||
targetPackageVersionId: targetPackage?.id ?? null,
|
||||
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
||||
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage?.id),
|
||||
canRollback:
|
||||
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
|
||||
missingFields: template.fields.filter(
|
||||
(item) =>
|
||||
!fields.some((current) => current.scope === item.scope && current.key === item.key),
|
||||
),
|
||||
changes: {
|
||||
brandFields: { available: false, reason: "行业字段不由视觉模板包声明" },
|
||||
templateBindings: {
|
||||
added: addedBindings,
|
||||
changed: changedBindings,
|
||||
removed: removedBindings,
|
||||
},
|
||||
pages: compareRecords(currentEntrypoints, targetEntrypoints),
|
||||
modules: {
|
||||
available: Boolean(visualManifest),
|
||||
source: "platform_visual_manifest",
|
||||
packageUpgradeChangesRenderer: false,
|
||||
pages:
|
||||
visualManifest?.pages.map((page) => ({
|
||||
key: page.key,
|
||||
renderer: page.renderer ?? null,
|
||||
modules: page.modules,
|
||||
})) ?? [],
|
||||
},
|
||||
assets: {
|
||||
slots: compareKeyedRecords(currentAssets, targetAssets),
|
||||
files: compareFiles(currentFiles, targetFiles),
|
||||
},
|
||||
capabilities: {
|
||||
added: targetCapabilities.filter((item) => !currentCapabilities.includes(item)),
|
||||
removed: currentCapabilities.filter((item) => !targetCapabilities.includes(item)),
|
||||
},
|
||||
renderer: {
|
||||
available: Boolean(visualManifest),
|
||||
source: "platform_visual_manifest",
|
||||
packageUpgradeChangesRenderer: false,
|
||||
pages:
|
||||
visualManifest?.pages.map((page) => ({
|
||||
key: page.key,
|
||||
renderer: page.renderer ?? null,
|
||||
})) ?? [],
|
||||
},
|
||||
package: {
|
||||
currentContentChecksum: currentPackage?.contentChecksum ?? null,
|
||||
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
||||
runtimeContract: {
|
||||
current: currentManifest.runtimeContract ?? null,
|
||||
target: targetManifest.runtimeContract ?? null,
|
||||
},
|
||||
},
|
||||
},
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
async upgrade(brandId: string) {
|
||||
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
|
||||
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
|
||||
const installation = await this.installation(brandId);
|
||||
const template = getBrandTemplate(installation.templateKey);
|
||||
if (!template) throw new BadRequestException("已安装模板不存在");
|
||||
if (installation.templateVersion === template.version)
|
||||
throw new BadRequestException("当前模板已经是最新版本");
|
||||
const target = await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: body.templatePackageVersionId },
|
||||
});
|
||||
if (!target || target.status !== "published")
|
||||
throw new BadRequestException("目标模板包版本不存在或未发布");
|
||||
if (target.contentChecksum !== body.expectedContentChecksum)
|
||||
throw new ConflictException("目标模板包内容已变化,请重新预览升级差异");
|
||||
if (installation.templateVersion !== body.expectedCurrentVersion)
|
||||
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
||||
if (
|
||||
(body.expectedCurrentPackageVersionId ?? null) !==
|
||||
(installation.templatePackageVersionId ?? null)
|
||||
)
|
||||
throw new ConflictException("当前模板包版本已变化,请重新预览升级差异");
|
||||
const preview = await this.preview(brandId);
|
||||
const expectedConflicts = preview.conflicts
|
||||
.map(({ key, binding }) => `${key}\u0000${binding}`)
|
||||
.sort();
|
||||
const preserved = body.preservedBindings
|
||||
.map(({ key, binding, action }) => {
|
||||
if (action !== "preserve") throw new BadRequestException("当前只允许保留已有品牌配置");
|
||||
return `${key}\u0000${binding}`;
|
||||
})
|
||||
.sort();
|
||||
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
|
||||
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
|
||||
const manifest = record(target.manifestSnapshot);
|
||||
if (
|
||||
target.packageKey !== installation.visualTemplateKey ||
|
||||
manifest.packageKey !== target.packageKey ||
|
||||
manifest.version !== target.version ||
|
||||
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
||||
!manifest.supportedIndustryTemplates.includes(installation.templateKey)
|
||||
)
|
||||
throw new BadRequestException("目标模板包与当前品牌安装不兼容");
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const fields = await tx.brandFieldDefinition.findMany({ where: { brandId } });
|
||||
const addedFields = template.fields.filter(
|
||||
(item) =>
|
||||
!fields.some((current) => current.scope === item.scope && current.key === item.key),
|
||||
);
|
||||
await tx.brandFieldDefinition.createMany({
|
||||
data: addedFields.map(({ scope, key, label, type, required }, index) => ({
|
||||
brandId,
|
||||
scope,
|
||||
key,
|
||||
label,
|
||||
type,
|
||||
required,
|
||||
sortOrder: fields.length + index,
|
||||
source: "template",
|
||||
})),
|
||||
});
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
const updated = await tx.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
const claimed = await tx.brandTemplateInstallation.updateMany({
|
||||
where: {
|
||||
id: installation.id,
|
||||
templateVersion: body.expectedCurrentVersion,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
data: {
|
||||
templateVersion: template.version,
|
||||
configSnapshot: template as unknown as Prisma.InputJsonValue,
|
||||
templatePackageVersionId: target.id,
|
||||
contentChecksum: target.contentChecksum,
|
||||
templateVersion: target.version,
|
||||
configSnapshot: manifest as Prisma.InputJsonValue,
|
||||
previousSnapshots: [...history, installation.configSnapshot],
|
||||
},
|
||||
});
|
||||
return { installation: updated, addedFields };
|
||||
if (claimed.count !== 1)
|
||||
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
||||
const updated = await tx.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { id: installation.id },
|
||||
});
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: target.id,
|
||||
actorId,
|
||||
action: "brand_upgrade",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
fromVersion: installation.templateVersion,
|
||||
toVersionId: target.id,
|
||||
toVersion: target.version,
|
||||
contentChecksum: target.contentChecksum,
|
||||
preservedBindings: body.preservedBindings.map(({ key, binding }) => ({ key, binding })),
|
||||
},
|
||||
},
|
||||
});
|
||||
return { installation: updated, preservedBindings: body.preservedBindings };
|
||||
});
|
||||
}
|
||||
async rollback(brandId: string) {
|
||||
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
|
||||
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
|
||||
const installation = await this.installation(brandId);
|
||||
if (installation.templateVersion !== body.expectedCurrentVersion)
|
||||
throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
@@ -297,13 +467,55 @@ export class TemplateWorkspaceService {
|
||||
throw new BadRequestException("没有可回滚的模板版本");
|
||||
const version = (previous as { version?: unknown }).version;
|
||||
if (typeof version !== "string") throw new BadRequestException("模板快照无效");
|
||||
const updated = await this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: {
|
||||
templateVersion: version,
|
||||
configSnapshot: previous,
|
||||
previousSnapshots: history.slice(0, -1),
|
||||
},
|
||||
const previousManifest = record(previous);
|
||||
const previousPackage =
|
||||
typeof previousManifest.packageKey === "string"
|
||||
? await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: previousManifest.packageKey, version },
|
||||
})
|
||||
: null;
|
||||
if (
|
||||
previousPackage &&
|
||||
(previousPackage.packageKey !== installation.visualTemplateKey ||
|
||||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
|
||||
installation.templateKey,
|
||||
))
|
||||
)
|
||||
throw new BadRequestException("上一版模板包与当前品牌行业或视觉模板不兼容");
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.brandTemplateInstallation.updateMany({
|
||||
where: {
|
||||
id: installation.id,
|
||||
templateVersion: installation.templateVersion,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
data: {
|
||||
templateVersion: version,
|
||||
templatePackageVersionId: previousPackage?.id ?? null,
|
||||
contentChecksum: previousPackage?.contentChecksum ?? null,
|
||||
configSnapshot: previous,
|
||||
previousSnapshots: history.slice(0, -1),
|
||||
},
|
||||
});
|
||||
if (changed.count !== 1) throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
||||
if (installation.templatePackageVersionId) {
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
actorId,
|
||||
action: "brand_rollback",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
fromVersion: installation.templateVersion,
|
||||
toVersionId: previousPackage?.id ?? null,
|
||||
toVersion: version,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return tx.brandTemplateInstallation.findUniqueOrThrow({ where: { id: installation.id } });
|
||||
});
|
||||
return {
|
||||
installation: updated,
|
||||
@@ -312,8 +524,131 @@ export class TemplateWorkspaceService {
|
||||
}
|
||||
}
|
||||
|
||||
async function readPackageFiles(
|
||||
version: Pick<
|
||||
TemplatePackageVersion,
|
||||
"artifactPath" | "validationReport" | "packageKey" | "version"
|
||||
>,
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const stored = manifestRecords(record(version.validationReport).files);
|
||||
if (stored.length) return stored;
|
||||
const root = `${version.packageKey}-${version.version}`;
|
||||
const checksumEntry = `${root}/checksums.json`;
|
||||
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(version.packageKey) || root.includes("/")) return [];
|
||||
try {
|
||||
const { stdout: entries } = await execFileAsync("tar", ["-tzf", version.artifactPath], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
if (!entries.split("\n").some((entry) => entry === checksumEntry)) return [];
|
||||
const { stdout } = await execFileAsync("tar", ["-xOzf", version.artifactPath, checksumEntry], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
return manifestRecords(record(JSON.parse(stdout)).files);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function manifestRecords(value: unknown): Record<string, unknown>[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is Record<string, unknown> =>
|
||||
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string")
|
||||
: [];
|
||||
}
|
||||
|
||||
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
||||
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
||||
const value = binding
|
||||
.slice("brand.config.".length)
|
||||
.split(".")
|
||||
.reduce<unknown>((current, key) => record(current)[key], config);
|
||||
return value !== undefined && value !== null && value !== "";
|
||||
}
|
||||
|
||||
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
||||
const currentKeys = Object.keys(current);
|
||||
const targetKeys = Object.keys(target);
|
||||
return {
|
||||
added: targetKeys
|
||||
.filter((key) => !(key in current))
|
||||
.map((key) => ({ key, target: target[key] })),
|
||||
removed: currentKeys
|
||||
.filter((key) => !(key in target))
|
||||
.map((key) => ({ key, current: current[key] })),
|
||||
changed: targetKeys
|
||||
.filter(
|
||||
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
||||
)
|
||||
.map((key) => ({ key, current: current[key], target: target[key] })),
|
||||
};
|
||||
}
|
||||
|
||||
function compareKeyedRecords(
|
||||
current: Record<string, unknown>[],
|
||||
target: Record<string, unknown>[],
|
||||
) {
|
||||
const currentByKey = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.key === "string")
|
||||
.map((item) => [item.key as string, item]),
|
||||
);
|
||||
const targetByKey = new Map(
|
||||
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
||||
);
|
||||
return {
|
||||
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
||||
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
||||
changed: [...targetByKey].flatMap(([key, item]) => {
|
||||
const previous = currentByKey.get(key);
|
||||
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
||||
? [{ key, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
|
||||
const currentByPath = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const targetByPath = new Map(
|
||||
target
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
||||
return {
|
||||
available,
|
||||
...(available
|
||||
? {
|
||||
added: [...targetByPath]
|
||||
.filter(([path]) => !currentByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
removed: [...currentByPath]
|
||||
.filter(([path]) => !targetByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
changed: [...targetByPath].flatMap(([path, item]) => {
|
||||
const previous = currentByPath.get(path);
|
||||
return previous && previous.sha256 !== item.sha256
|
||||
? [{ path, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
}
|
||||
: { reason: "版本验证报告未包含完整文件清单" }),
|
||||
};
|
||||
}
|
||||
@@ -145,6 +145,13 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
assert.equal(listedBody.items.length, 1);
|
||||
assert.equal(listedBody.items[0].status, "imported");
|
||||
const versionId = listedBody.items[0].id;
|
||||
const importedVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: versionId },
|
||||
});
|
||||
assert.ok(importedVersion.validationReport.files.length > 0);
|
||||
assert.ok(
|
||||
importedVersion.validationReport.files.every((file) => /^[a-f0-9]{64}$/.test(file.sha256)),
|
||||
);
|
||||
const publishMissing = await request(`/admin/templates/${versionId}/publish`, { method: "POST" });
|
||||
assert.equal(publishMissing.statusCode, 401);
|
||||
const publishCustomer = await request(`/admin/templates/${versionId}/publish`, {
|
||||
@@ -183,6 +190,83 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
assert.equal(JSON.parse(invalidRetire.body).changed, false);
|
||||
});
|
||||
|
||||
test("模板失败指标仅平台模板管理员可查,按窗口聚合且不暴露操作内容", async () => {
|
||||
const missing = await request("/admin/template-operations/failures");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
const customer = await request("/admin/template-operations/failures", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customer.statusCode, 403);
|
||||
|
||||
const ordinaryUser = await prisma.adminUser.create({
|
||||
data: {
|
||||
username: `metrics-viewer-${randomUUID()}`,
|
||||
passwordHash: "unused",
|
||||
displayName: "普通管理员",
|
||||
platformTemplateRole: "none",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
||||
};
|
||||
try {
|
||||
const forbidden = await request("/admin/template-operations/failures", { headers });
|
||||
assert.equal(forbidden.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 adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const now = Date.now();
|
||||
const recentRequestId = `metrics-${randomUUID()}`;
|
||||
await prisma.templateOperationFailureEvent.createMany({
|
||||
data: [
|
||||
{
|
||||
action: "preview",
|
||||
resultCode: "HTTP_409",
|
||||
requestId: recentRequestId,
|
||||
actorId: "metrics-test-actor",
|
||||
brandId,
|
||||
packageKey: "metrics-test-package",
|
||||
version: "1.0.0",
|
||||
createdAt: new Date(now - 1000),
|
||||
},
|
||||
{
|
||||
action: "preview",
|
||||
resultCode: "HTTP_400",
|
||||
createdAt: new Date(now - 2 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
{
|
||||
action: "import",
|
||||
resultCode: "HTTP_400",
|
||||
createdAt: new Date(now - 200 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
],
|
||||
});
|
||||
const invalidWindow = await request("/admin/template-operations/failures?days=91", {
|
||||
headers: adminHeaders,
|
||||
});
|
||||
assert.equal(invalidWindow.statusCode, 400);
|
||||
const response = await request("/admin/template-operations/failures?days=1", {
|
||||
headers: adminHeaders,
|
||||
});
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
const report = JSON.parse(response.body);
|
||||
assert.equal(report.days, 1);
|
||||
assert.equal(report.backfilled, false);
|
||||
assert.equal(report.failures.find((item) => item.action === "preview").count, 1);
|
||||
assert.equal(report.failures.find((item) => item.action === "import").count, 0);
|
||||
assert.equal(report.failures.find((item) => item.action === "build").count, 0);
|
||||
assert.equal(JSON.stringify(report).includes(recentRequestId), false);
|
||||
assert.deepEqual(Object.keys(report.failures[0]).sort(), ["action", "count"]);
|
||||
});
|
||||
|
||||
test("平台模板管理员可以按行业预览版本,且预览不写入品牌数据", async () => {
|
||||
const missing = await request("/admin/templates/preview-version/preview?industry=personal");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
@@ -2507,12 +2591,11 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customerAccess.statusCode, 403);
|
||||
const currentTemplateKey = (
|
||||
await prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
})
|
||||
).templateKey;
|
||||
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true, config: true },
|
||||
});
|
||||
const currentTemplateKey = originalBrand.templateKey;
|
||||
const crossTemplate = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2533,6 +2616,12 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
true,
|
||||
);
|
||||
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
|
||||
const installedRecord = JSON.parse(installed.body).installation;
|
||||
const createdVersionIds = [];
|
||||
let historicalReleaseId;
|
||||
let historicalFormId;
|
||||
let historicalSubmissionId;
|
||||
let historicalReleaseSnapshot;
|
||||
try {
|
||||
const previewUnauthorized = await request("/admin/workspace/template/preview");
|
||||
assert.equal(previewUnauthorized.statusCode, 401);
|
||||
@@ -2540,27 +2629,279 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(preview.statusCode, 200);
|
||||
assert.equal(JSON.parse(preview.body).canUpgrade, false);
|
||||
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
const admin = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const latestExistingRelease = await prisma.brandRelease.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { version: "desc" },
|
||||
});
|
||||
assert.ok(
|
||||
latestExistingRelease,
|
||||
"integration fixture should have a published release snapshot",
|
||||
);
|
||||
historicalReleaseSnapshot = latestExistingRelease.snapshot;
|
||||
const historicalRelease = await prisma.brandRelease.create({
|
||||
data: {
|
||||
brandId,
|
||||
version: latestExistingRelease.version + 1,
|
||||
snapshot: historicalReleaseSnapshot,
|
||||
actorId: admin.id,
|
||||
note: "Phase 6 历史快照回归",
|
||||
},
|
||||
});
|
||||
historicalReleaseId = historicalRelease.id;
|
||||
const historicalForm = await prisma.inquiryForm.create({
|
||||
data: {
|
||||
brandId,
|
||||
name: "Phase 6 历史咨询表单",
|
||||
fieldsSnapshot: [{ key: "message", label: "留言", type: "text", required: true }],
|
||||
},
|
||||
});
|
||||
historicalFormId = historicalForm.id;
|
||||
const historicalSubmission = await prisma.inquirySubmission.create({
|
||||
data: {
|
||||
brandId,
|
||||
inquiryFormId: historicalForm.id,
|
||||
customerSubject: "phase6-history-customer",
|
||||
formVersion: 1,
|
||||
fieldsSnapshot: historicalForm.fieldsSnapshot,
|
||||
values: { message: "历史咨询内容" },
|
||||
activeFields: ["message"],
|
||||
},
|
||||
});
|
||||
historicalSubmissionId = historicalSubmission.id;
|
||||
const packageKey = installedRecord.visualTemplateKey;
|
||||
const packageVersion = `9.${Date.now()}.0`;
|
||||
const initialPackageVersion = "1.0.0-phase6-test";
|
||||
const templatePackage = await prisma.templatePackage.upsert({
|
||||
where: { packageKey },
|
||||
create: { packageKey },
|
||||
update: {},
|
||||
});
|
||||
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
|
||||
data: {
|
||||
templatePackageId: templatePackage.id,
|
||||
packageKey,
|
||||
version: initialPackageVersion,
|
||||
displayName: "集成测试基线包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: initialPackageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: ["offerings"],
|
||||
templateFields: [{ key: "founder", binding: "brand.config.founder", label: "主理人" }],
|
||||
entrypoints: { home: "pages/index/index" },
|
||||
assetSlots: [{ key: "brand.logo", binding: "brand.avatarUrl" }],
|
||||
},
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${initialPackageVersion}`,
|
||||
archiveChecksum: `archive-${initialPackageVersion}`,
|
||||
artifactPath: "/tmp/template-upgrade-initial-test",
|
||||
importedById: admin.id,
|
||||
},
|
||||
});
|
||||
createdVersionIds.push(initialPackageVersionRecord.id);
|
||||
const originalConfig =
|
||||
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
|
||||
const existingFounder = "升级前的品牌主理人";
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { config: { ...originalConfig, founder: existingFounder } },
|
||||
});
|
||||
assert.equal(rollbackUnauthorized.statusCode, 401);
|
||||
const installedRecord = JSON.parse(installed.body).installation;
|
||||
await prisma.brandTemplateInstallation.update({
|
||||
where: { id: installedRecord.id },
|
||||
data: {
|
||||
templateVersion: "2.0.0",
|
||||
previousSnapshots: [installedRecord.configSnapshot],
|
||||
templateVersion: initialPackageVersion,
|
||||
templatePackageVersionId: initialPackageVersionRecord.id,
|
||||
contentChecksum: initialPackageVersionRecord.contentChecksum,
|
||||
configSnapshot: initialPackageVersionRecord.manifestSnapshot,
|
||||
},
|
||||
});
|
||||
const packageVersionRecord = await prisma.templatePackageVersion.create({
|
||||
data: {
|
||||
templatePackageId: templatePackage.id,
|
||||
packageKey,
|
||||
version: packageVersion,
|
||||
displayName: "集成测试升级包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: packageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: [],
|
||||
templateFields: [
|
||||
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
|
||||
],
|
||||
entrypoints: { home: "pages/home/index", profile: "pages/profile/index" },
|
||||
assetSlots: [
|
||||
{ key: "brand.logo", binding: "brand.avatarUrl" },
|
||||
{ key: "home.hero", binding: "brand.config.heroImage" },
|
||||
],
|
||||
},
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${packageVersion}`,
|
||||
archiveChecksum: `archive-${packageVersion}`,
|
||||
artifactPath: "/tmp/template-upgrade-test",
|
||||
importedById: admin.id,
|
||||
},
|
||||
});
|
||||
createdVersionIds.push(packageVersionRecord.id);
|
||||
const actionablePreview = await request("/admin/workspace/template/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
const actionable = JSON.parse(actionablePreview.body);
|
||||
assert.equal(actionable.canUpgrade, true);
|
||||
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
|
||||
assert.equal(actionable.changes.brandFields.available, false);
|
||||
assert.equal(actionable.conflicts.length, 1);
|
||||
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
|
||||
assert.equal(actionable.changes.pages.added.length, 1);
|
||||
assert.equal(actionable.changes.assets.slots.added.length, 1);
|
||||
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
|
||||
assert.equal(actionable.changes.renderer.available, true);
|
||||
assert.equal(actionable.changes.renderer.packageUpgradeChangesRenderer, false);
|
||||
assert.equal(actionable.changes.assets.files.available, false);
|
||||
const missingConfirm = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: false,
|
||||
preservedBindings: [],
|
||||
},
|
||||
});
|
||||
assert.equal(missingConfirm.statusCode, 400);
|
||||
const unresolvedConflict = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: true,
|
||||
preservedBindings: [],
|
||||
},
|
||||
});
|
||||
assert.equal(unresolvedConflict.statusCode, 409);
|
||||
const upgradePayload = {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: true,
|
||||
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
|
||||
};
|
||||
const upgradeAttempts = await Promise.all(
|
||||
[0, 1].map(() =>
|
||||
request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: upgradePayload,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(upgradeAttempts.map((item) => item.statusCode).sort(), [201, 409]);
|
||||
const upgraded = upgradeAttempts.find((item) => item.statusCode === 201);
|
||||
assert.ok(upgraded);
|
||||
assert.equal(
|
||||
JSON.parse(upgraded.body).installation.templatePackageVersionId,
|
||||
packageVersionRecord.id,
|
||||
);
|
||||
assert.equal(
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
|
||||
existingFounder,
|
||||
);
|
||||
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: initialPackageVersionRecord.id },
|
||||
});
|
||||
assert.equal(retainedOldPackage.contentChecksum, initialPackageVersionRecord.contentChecksum);
|
||||
const retainedRelease = await prisma.brandRelease.findUniqueOrThrow({
|
||||
where: { id: historicalReleaseId },
|
||||
});
|
||||
assert.deepEqual(retainedRelease.snapshot, historicalReleaseSnapshot);
|
||||
assert.equal(
|
||||
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: historicalSubmissionId } }))
|
||||
.values.message,
|
||||
"历史咨询内容",
|
||||
);
|
||||
await prisma.$disconnect();
|
||||
await prisma.$connect();
|
||||
await app.close();
|
||||
app = await createApp();
|
||||
await app.init();
|
||||
const afterApiRestart = await request("/admin/workspace/template/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(afterApiRestart.statusCode, 200);
|
||||
assert.equal(JSON.parse(afterApiRestart.body).currentPackageVersionId, packageVersionRecord.id);
|
||||
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollbackUnauthorized.statusCode, 401);
|
||||
const upgradeUnauthorized = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeUnauthorized.statusCode, 401);
|
||||
const upgradeForbidden = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeForbidden.statusCode, 403);
|
||||
const upgradeInvalidDto = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeInvalidDto.statusCode, 400);
|
||||
const rollbackMissingConfirmation = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: false },
|
||||
});
|
||||
assert.equal(rollbackMissingConfirmation.statusCode, 400);
|
||||
const rollbackStaleVersion = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: actionable.currentVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollbackStaleVersion.statusCode, 409);
|
||||
const rollback = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollback.statusCode, 201);
|
||||
assert.equal(JSON.parse(rollback.body).installation.templateVersion, "1.0.0");
|
||||
assert.equal(JSON.parse(rollback.body).installation.templateVersion, initialPackageVersion);
|
||||
assert.equal(
|
||||
JSON.parse(rollback.body).installation.templatePackageVersionId,
|
||||
initialPackageVersionRecord.id,
|
||||
);
|
||||
assert.equal(JSON.parse(rollback.body).installation.previousSnapshots.length, 0);
|
||||
assert.match(JSON.parse(rollback.body).note, /配置基线/);
|
||||
const operationAudit = await prisma.templatePackageAuditLog.findMany({
|
||||
where: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
action: { in: ["brand_upgrade", "brand_rollback"] },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
assert.deepEqual(
|
||||
operationAudit.map((item) => item.action),
|
||||
["brand_upgrade", "brand_rollback"],
|
||||
);
|
||||
assert.equal(operationAudit[0].metadata.brandId, brandId);
|
||||
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
|
||||
assert.ok(operationAudit[0].requestId);
|
||||
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
|
||||
const workspace = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -2603,8 +2944,18 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
});
|
||||
assert.equal(conflict.statusCode, 400);
|
||||
} finally {
|
||||
if (historicalSubmissionId)
|
||||
await prisma.inquirySubmission.deleteMany({ where: { id: historicalSubmissionId } });
|
||||
if (historicalFormId) await prisma.inquiryForm.deleteMany({ where: { id: historicalFormId } });
|
||||
if (historicalReleaseId)
|
||||
await prisma.brandRelease.deleteMany({ where: { id: historicalReleaseId } });
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
@@ -24,17 +24,23 @@ interface Fixture {
|
||||
|
||||
function createTemplateFixture(packageKey: string): Fixture {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), `template-preview-matrix-${packageKey}-`));
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
packageKey,
|
||||
"--out",
|
||||
root,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
|
||||
);
|
||||
try {
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
packageKey,
|
||||
"--out",
|
||||
root,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "pipe", encoding: "utf8" },
|
||||
);
|
||||
} catch (error) {
|
||||
const details =
|
||||
error instanceof Error && "stderr" in error ? String(error.stderr) : String(error);
|
||||
throw new Error(`Could not package discovered template ${packageKey}: ${details}`);
|
||||
}
|
||||
const filename = readdirSync(root).find((item) => item.endsWith(".tar.gz"));
|
||||
assert.ok(filename);
|
||||
const archivePath = path.join(root, filename);
|
||||
@@ -58,8 +64,42 @@ function createTemplateFixture(packageKey: string): Fixture {
|
||||
};
|
||||
}
|
||||
|
||||
function discoverTemplatePackages(packageRoot: string): string[] {
|
||||
return readdirSync(packageRoot, { withFileTypes: true })
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.isDirectory() &&
|
||||
entry.name.startsWith("template-") &&
|
||||
readdirSync(path.join(packageRoot, entry.name)).includes("template.json"),
|
||||
)
|
||||
.map((entry) => {
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(path.join(packageRoot, entry.name, "template.json"), "utf8"),
|
||||
) as TemplatePackageManifest;
|
||||
return manifest.packageKey;
|
||||
})
|
||||
.sort();
|
||||
}
|
||||
|
||||
test("template preview matrix discovers newly added package manifests", () => {
|
||||
const packageRoot = mkdtempSync(path.join(os.tmpdir(), "template-discovery-matrix-"));
|
||||
const source = path.resolve(process.cwd(), "../../packages/template-atelier-solopreneur");
|
||||
const packageDirectory = path.join(packageRoot, "template-discovery-probe");
|
||||
cpSync(source, packageDirectory, { recursive: true });
|
||||
const manifestPath = path.join(packageDirectory, "template.json");
|
||||
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as TemplatePackageManifest;
|
||||
writeFileSync(manifestPath, JSON.stringify({ ...manifest, packageKey: "discovery-probe" }));
|
||||
try {
|
||||
assert.deepEqual(discoverTemplatePackages(packageRoot), ["discovery-probe"]);
|
||||
} finally {
|
||||
rmSync(packageRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("template preview matrix keeps every deployed package, industry, and version isolated", async () => {
|
||||
const packageKeys = ["acheng-campus-food", "atelier-solopreneur", "linjing-editorial"];
|
||||
const packageRoot = path.resolve(process.cwd(), "../../packages");
|
||||
const packageKeys = discoverTemplatePackages(packageRoot);
|
||||
assert.ok(packageKeys.length > 0, "at least one template package must be discovered");
|
||||
const fixtures = packageKeys.map(createTemplateFixture);
|
||||
let sequence = 0;
|
||||
const versionFixture = (fixture: Fixture) => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 任务 ID:TMP-PLATFORM-001
|
||||
>
|
||||
> 状态:Phase 0/1/2/3/4/5 已收口;Phase 5 的本地实现与验证完成,真实微信上传未成功,后续出现发布问题时再按需核查
|
||||
> 状态:Phase 0/1/2/3/4/5/6 已收口;Phase 7 进行中
|
||||
>
|
||||
> 唯一任务入口:本文档
|
||||
>
|
||||
@@ -312,16 +312,16 @@ admin.sections 和 renderer 必须互相校验:每个可见、可编辑的品
|
||||
|
||||
## 11. CLI、仓库工作流和构建门禁
|
||||
|
||||
当前仓库已有 template:doctor、template:check、validate:templates、generate:template-catalog、preview:templates、deploy:package、deploy:release 和 test:deploy 等命令。它们的现有行为不能在本文中被默认扩大。
|
||||
当前仓库已有 `template:doctor`、`template:check`、`validate:templates`、`template:compatibility`、`template:new`、`generate:template-catalog`、`preview:templates`、`deploy:package`、`deploy:release` 和 `test:deploy` 等命令。它们的现有行为不能在本文中被默认扩大。
|
||||
|
||||
计划新增或收敛的命令如下,实施前必须先落代码、帮助文本和测试:
|
||||
|
||||
| 命令 | 目的 | 完成门禁 |
|
||||
| -------------------- | ------------------------------------------------------------- | ---------------------------------- |
|
||||
| template:pack | 生成确定性模板导出包和 checksum | 同一输入多次输出相同 checksum |
|
||||
| template:conformance | 逐包执行 manifest、binding、资源、sample、renderer 和双端契约 | 自动发现新包,不能只测固定名称 |
|
||||
| release:conformance | 检查发布包依赖闭包、workspace、产物路径和环境参数 | 干净 install、生产 build、产物检查 |
|
||||
| template:new | 从受控 scaffold 创建新模板包和最小 fixture | 生成包自带失败示例和测试入口 |
|
||||
| 命令 | 目的 | 完成门禁 |
|
||||
| -------------------- | ------------------------------------------------------------- | ---------------------------------------- |
|
||||
| template:pack | 生成确定性模板导出包和 checksum | 同一输入多次输出相同 checksum |
|
||||
| template:conformance | 逐包执行 manifest、binding、资源、sample、renderer 和双端契约 | 自动发现新包,不能只测固定名称 |
|
||||
| release:conformance | 检查发布包依赖闭包、workspace、产物路径和环境参数 | 干净 install、生产 build、产物检查 |
|
||||
| template:new | 从受控 scaffold 创建新模板包与待完成 fixture | 生成包明确标为未验收并通过 scaffold 测试 |
|
||||
|
||||
每个模板新增、绑定修改和宣称完成前,必须运行 pnpm template:doctor,并按[模板完成度规则](template-completion-rules.md)使用真实 manifest、真实保存重载发布链路和视觉证据验收。doctor issue 使用稳定语义指纹;源代码语义改变后必须重新审查,不能通过批量行号更新伪造通过。
|
||||
|
||||
@@ -496,23 +496,42 @@ Phase 5 首轮实现记录(2026-10-17):
|
||||
|
||||
### Phase 6:升级、冲突、回滚和恢复
|
||||
|
||||
- [ ] 生成旧版本到新版本的字段、模块、资源、能力和 renderer 差异;
|
||||
- [ ] 升级支持 dry-run、显式确认、冲突逐项处理和用户内容保护;
|
||||
- [ ] 回滚明确恢复安装配置、发布快照或取消升级计划的语义;
|
||||
- [ ] 旧版本资源、品牌历史发布和咨询提交持续可读;
|
||||
- [ ] 模拟数据库、API、worker 和 Admin 重启,验证 job 恢复和幂等。
|
||||
- [x] 生成旧版本到新版本的字段 binding、页面入口、包文件、资源槽位和能力差异;视觉模块与 renderer 标记为平台视觉 manifest 所有,不随模板包升级;
|
||||
- [x] 升级支持 dry-run、显式确认、逐项保留现有 binding 冲突和用户内容保护;同一预览并发执行时 compare-and-set 保证最多一个成功;
|
||||
- [x] 回滚要求显式确认并校验当前版本,只恢复安装配置快照及不可变包关联,不恢复已删除的用户数据,也不删除当前用户数据;
|
||||
- [x] 验证旧模板版本、品牌历史发布快照和客户咨询提交在升级/回滚后持续可读;新旧包文件清单分别从验证报告或已验证归档读取;
|
||||
- [x] API / Prisma Client 重建后读取持久化安装状态;该升级操作是同步数据库事务,没有独立 worker job,Admin 页面重载后由查询重新读取 preview,陈旧操作会被版本校验拒绝。
|
||||
|
||||
退出门禁:升级失败可恢复到升级前状态;回滚不会删除用户历史数据;重试和重启不会重复导入或重复写终态。
|
||||
退出门禁:升级冲突/陈旧预览不改变安装状态;回滚不会删除用户历史数据;并发重试和 API 重建不会重复升级或覆盖终态。
|
||||
|
||||
Phase 6 收口记录(2026-10-17):
|
||||
|
||||
- 升级目标切换为当前视觉模板最新已发布的不可变 `TemplatePackageVersion`;preview 比较模板配置 binding、页面入口、语义资源槽位、能力和校验报告中的逐文件 SHA-256。视觉模块/renderer 明确标为平台视觉 manifest 管理,包升级不替换 renderer;未有历史文件清单的旧包会明确报告不可比较。
|
||||
- 升级 API 要求 DTO 显式确认并携带目标 package id/checksum、来源 package id/版本及每个冲突 binding 的 `preserve` 选择;执行时再次验证包状态、行业兼容性和冲突集合,数据库 compare-and-set 防止并发重复升级。品牌现有值不被改写,升级不删除数据。
|
||||
- 回滚要求显式确认和预期当前版本,compare-and-set 防止覆盖并发升级;回滚恢复配置快照和对应不可变包关联,不删除品牌内容、历史发布或客户提交。升级/回滚写入 package audit log,记录 actor、brand、版本、checksum、保留选择与 requestId。
|
||||
- 归档兼容:新导入包的 checksum 文件清单保存于 `validationReport`;旧记录在 preview 时从隔离存储中的已导入 archive 只读提取 `checksums.json`,缺失/损坏时返回明确不可比较,不执行包内脚本。
|
||||
- 自动化验证:无凭据/错误角色、DTO 校验、目标版本 preview、冲突未确认拒绝、同一预览并发一胜一冲突、升级与回滚审计、Prisma Client 断开重连、Nest app 重建后读取版本、历史发布与咨询内容保留;API HTTP integration `53/53`、upload integration `2/2`、API unit `64/64`、API Client `7/7`、Admin `6/6`、API/API Client/Admin typecheck、Admin production build、格式检查通过。全仓 lint 仍有本阶段之外的既有错误,本次变更文件的 lint 单独通过。
|
||||
- `pnpm template:doctor` completionStatus 仍为 `unverified`,因为真实 manifest 的品牌编辑保存/重载/发布和视觉证据未提供;这是模板完成度独立门禁,不由本阶段升级 API 测试替代。
|
||||
|
||||
### Phase 7:规模化模板生产和持续回归
|
||||
|
||||
- [ ] 新模板可通过 scaffold、package-discovered conformance 和模板管理页面进入目录;
|
||||
- [ ] 行业、视觉、能力、renderer 和 toolchain 组合有兼容矩阵;
|
||||
- [ ] 固定页面角色的视觉基线和真实数据 fixture;
|
||||
- [ ] CI 在新增模板时自动发现并执行契约、API、构建和必要的视觉检查;
|
||||
- [ ] 统计导入失败、预览失败、安装冲突、构建失败和上传失败,定期审阅高频问题;
|
||||
- [x] 新模板可通过 `pnpm template:new <package-key>` scaffold、package-discovered conformance 和模板管理页面进入目录;生成包明确保留待填写的 industry/fixture 占位,不能误当成已验收模板;
|
||||
- [x] 行业、视觉、能力、renderer 和 Taro/React toolchain 组合有自动兼容矩阵,未知 renderer、未知 capability、行业不兼容和依赖版本漂移都会阻断;
|
||||
- [x] 固定页面角色的浏览器视觉 smoke 与真实 package fixture 已由 CI browser job 执行;原型对照、真实编辑保存重载发布证据仍遵循模板完成度规则单独验收;
|
||||
- [x] CI 在新增模板时自动发现并执行契约、API 预览矩阵、compatibility、包构建 conformance 和 browser smoke;
|
||||
- [x] 统一统计导入失败、预览失败、安装失败/冲突、升级/回滚失败、构建失败和上传失败;平台模板管理员可查询窗口聚合,且不暴露错误正文;定期审阅流程仍需运营安排;
|
||||
- [ ] 删除或迁移旧注册表、默认行业映射和重复 renderer 分支。
|
||||
|
||||
Phase 7 进展记录(2026-10-17):
|
||||
|
||||
- 新增 `pnpm template:new <package-key>`,生成 package metadata、manifest、Taro renderer 和明确未完成的 README;重复 key 会拒绝,不生成可伪装完成的空样例数据。
|
||||
- 新增 `pnpm template:compatibility`,通过 TypeScript AST 读取行业、能力和视觉注册表,自动发现所有 package manifest;比较平台视觉 renderer、Admin glob、Taro renderer 导出、行业 capability 和 package/platform Taro/React 依赖主次版本,支持 JSON 报告。
|
||||
- API 模板预览矩阵自动扫描真实 manifest,逐个验证声明行业、版本隔离、品牌隔离和归档资源;CI 静态 job 显式执行 package validation、compatibility、API matrix 和 conformance。CI browser job 已执行真实包 fixture 的页面/资源/编辑回归截图。
|
||||
- 自动化验证:`pnpm template:check` 通过(contract `22/22`、scaffold/compatibility `3/3`、pack `3/3`、conformance `1/1`、compiler `10/10`、miniapp fixture `3/3`);API matrix `2/2`;compatibility 报告有 4 个支持组合;API unit `65/65`、HTTP integration `54/54`、upload integration `2/2`、API Client `8/8`、Admin `6/6`;API/API Client/Admin typecheck、Admin production build、Prettier 和 `git diff --check` 通过。
|
||||
- 剩余:指标已有统一持久化和平台管理员查询接口,但定期审阅流程仍需运营安排;旧 renderer/默认行业映射仍有兼容职责,暂不能删除。模板 doctor 的真实品牌编辑保存重载发布与原型视觉证据仍为 `unverified`,不能以 CI smoke 代替;因此 Phase 7 整体继续进行。
|
||||
|
||||
运营指标说明:新增 `TemplateOperationFailureEvent` 记录导入、预览、安装/冲突、升级和回滚失败;构建/上传从已有 release attempt 聚合。事件只保留 action、稳定 `HTTP_*` resultCode、可选实体标识和 requestId,查询只返回类别/数量;按 180 天 best-effort 清理,不回填历史失败数。定期审阅仍需运营流程和负责人。
|
||||
|
||||
退出门禁:增加一个新模板不需要修改全局 seed 才能被发现,不需要在 Controller 写行业分支,不需要手工改线上数据库才能选择、预览、安装和发布。
|
||||
|
||||
## 13. 历史问题到自动化验收的映射
|
||||
|
||||
@@ -28,12 +28,12 @@
|
||||
|
||||
## 当前缺口
|
||||
|
||||
- [ ] 版本导出、线上导入、checksum 幂等和目录发布尚未形成统一闭环;
|
||||
- [ ] 独立模板管理页面尚未覆盖导入、校验、预览、发布和审计全流程;
|
||||
- [ ] 行业安装和视觉包安装的持久化边界需要迁移设计;
|
||||
- [ ] 预览 fixture 和可导入 bootstrap 内容需要明确分离;
|
||||
- [ ] Taro renderer、Runtime contract、package schema 和 toolchain 的兼容矩阵需要落库;
|
||||
- [x] 版本导出、导入、checksum 幂等、目录发布/撤回与审计已由 template pack 和管理 API 实现;
|
||||
- [x] `/admin/templates` 覆盖导入、校验、预览、发布、撤回和审计;
|
||||
- [x] 行业安装与视觉包精确版本通过兼容读取和不可变版本台账关联;新安装保存 package version/checksum;
|
||||
- [x] 预览 fixture 与显式 bootstrap 内容分离,预览不写入品牌;
|
||||
- [x] `pnpm template:compatibility` 自动检查 package、行业、平台视觉 manifest、Taro renderer 和 Admin renderer discovery;Runtime contract 及 package schema 由 `pnpm validate:templates` 校验;toolchain 产物由 `pnpm template:conformance` 验证;
|
||||
- [x] atelier-solopreneur 的 manifest/package metadata 版本已统一,并由 validate:templates 阻断后续漂移;
|
||||
- [ ] 每个模板仍需完成真实品牌编辑、保存重载、发布、双端构建和真实微信外部验收。
|
||||
- [ ] 每个模板仍需完成真实品牌编辑、保存重载、发布和视觉证据;双端生产构建按交付变更执行,真实微信外部上传/审核尚未证明。
|
||||
|
||||
新增模板时先修改模板包和契约测试,再更新生成产物;不要直接在本文追加一条“已注册”来绕过门禁。
|
||||
+3
-1
@@ -20,10 +20,12 @@
|
||||
"validate:templates": "node scripts/validate-template-packages.cjs && pnpm --filter @personal-brand/template-contract test",
|
||||
"generate:template-catalog": "node scripts/generate-template-catalog.cjs --write",
|
||||
"template:dev": "node packages/template-compiler/src/cli.mjs --template",
|
||||
"template:check": "pnpm validate:templates && node --test scripts/template-pack.test.mjs && node --test scripts/template-conformance.test.mjs && pnpm test:template-compiler && pnpm --filter @personal-brand/miniapp test:visual-fixture",
|
||||
"template:check": "pnpm validate:templates && pnpm template:compatibility && node --test scripts/template-new.test.mjs scripts/template-compatibility.test.mjs && node --test scripts/template-pack.test.mjs && node --test scripts/template-conformance.test.mjs && pnpm test:template-compiler && pnpm --filter @personal-brand/miniapp test:visual-fixture",
|
||||
"validate:template-release": "node scripts/validate-template-release.cjs",
|
||||
"template:pack": "node scripts/template-pack.cjs",
|
||||
"template:conformance": "node scripts/template-conformance.cjs",
|
||||
"template:compatibility": "node scripts/template-compatibility.cjs",
|
||||
"template:new": "node scripts/template-new.cjs",
|
||||
"test:template-compiler": "pnpm --filter @personal-brand/template-compiler test",
|
||||
"clean": "turbo run clean && rimraf node_modules .turbo",
|
||||
"preview:food": "pnpm --filter @personal-brand/taro dev:h5",
|
||||
|
||||
@@ -287,6 +287,9 @@ export class ApiClient
|
||||
this.resources.template.upgradeAdminTemplate(...arguments_);
|
||||
rollbackAdminTemplate = (...arguments_: Parameters<TemplateMethods["rollbackAdminTemplate"]>) =>
|
||||
this.resources.template.rollbackAdminTemplate(...arguments_);
|
||||
getAdminTemplateOperationFailures = (
|
||||
...arguments_: Parameters<TemplateMethods["getAdminTemplateOperationFailures"]>
|
||||
) => this.resources.template.getAdminTemplateOperationFailures(...arguments_);
|
||||
getPublicOffering = (...arguments_: Parameters<OfferingMethods["getPublicOffering"]>) =>
|
||||
this.resources.offering.getPublicOffering(...arguments_);
|
||||
listPublicOfferings = (...arguments_: Parameters<OfferingMethods["listPublicOfferings"]>) =>
|
||||
|
||||
@@ -138,10 +138,61 @@ export interface TemplateMethods {
|
||||
latestVersion: string;
|
||||
canUpgrade: boolean;
|
||||
canRollback: boolean;
|
||||
missingFields: unknown[];
|
||||
currentPackageVersionId: string | null;
|
||||
currentContentChecksum: string | null;
|
||||
targetPackageVersionId: string | null;
|
||||
targetContentChecksum: string | null;
|
||||
changes: {
|
||||
brandFields: { available: false; reason: string };
|
||||
templateBindings: { added: unknown[]; changed: unknown[]; removed: unknown[] };
|
||||
pages: { added: unknown[]; changed: unknown[]; removed: unknown[] };
|
||||
modules: {
|
||||
available: boolean;
|
||||
source: "platform_visual_manifest";
|
||||
packageUpgradeChangesRenderer: false;
|
||||
pages: Array<{ key: string; renderer: string | null; modules?: unknown[] }>;
|
||||
};
|
||||
assets: {
|
||||
slots: { added: unknown[]; changed: unknown[]; removed: unknown[] };
|
||||
files: {
|
||||
available: boolean;
|
||||
added?: unknown[];
|
||||
changed?: unknown[];
|
||||
removed?: unknown[];
|
||||
reason?: string;
|
||||
};
|
||||
};
|
||||
capabilities: { added: string[]; removed: string[] };
|
||||
renderer: {
|
||||
available: boolean;
|
||||
source: "platform_visual_manifest";
|
||||
packageUpgradeChangesRenderer: false;
|
||||
pages: Array<{ key: string; renderer: string | null }>;
|
||||
};
|
||||
package: {
|
||||
currentContentChecksum: string | null;
|
||||
targetContentChecksum: string | null;
|
||||
runtimeContract: { current: unknown; target: unknown };
|
||||
};
|
||||
};
|
||||
conflicts: Array<{ key: string; binding: string; reason: string }>;
|
||||
}>;
|
||||
upgradeAdminTemplate(input: {
|
||||
templatePackageVersionId: string;
|
||||
expectedContentChecksum: string;
|
||||
expectedCurrentVersion: string;
|
||||
expectedCurrentPackageVersionId: string | null;
|
||||
confirm: true;
|
||||
preservedBindings: Array<{ key: string; binding: string; action: "preserve" }>;
|
||||
}): Promise<unknown>;
|
||||
rollbackAdminTemplate(input: { expectedCurrentVersion: string; confirm: true }): Promise<unknown>;
|
||||
getAdminTemplateOperationFailures(params?: { days?: number }): Promise<{
|
||||
since: string;
|
||||
until: string;
|
||||
days: number;
|
||||
backfilled: false;
|
||||
failures: Array<{ action: string; count: number }>;
|
||||
}>;
|
||||
upgradeAdminTemplate(): Promise<unknown>;
|
||||
rollbackAdminTemplate(): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface TemplatePackageVersion {
|
||||
@@ -345,7 +396,13 @@ export function templateMethods({ request }: { request: RequestFn }): TemplateMe
|
||||
importAdminSampleContent: (body) =>
|
||||
request("/admin/workspace/sample-content/import", { method: "POST", body }),
|
||||
getAdminTemplateUpgradePreview: () => request("/admin/workspace/template/preview"),
|
||||
upgradeAdminTemplate: () => request("/admin/workspace/template/upgrade", { method: "POST" }),
|
||||
rollbackAdminTemplate: () => request("/admin/workspace/template/rollback", { method: "POST" }),
|
||||
upgradeAdminTemplate: (input) =>
|
||||
request("/admin/workspace/template/upgrade", { method: "POST", body: input }),
|
||||
rollbackAdminTemplate: (input) =>
|
||||
request("/admin/workspace/template/rollback", { method: "POST", body: input }),
|
||||
getAdminTemplateOperationFailures: (params = {}) =>
|
||||
request(
|
||||
`/admin/template-operations/failures${params.days === undefined ? "" : `?days=${encodeURIComponent(String(params.days))}`}`,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -131,3 +131,67 @@ test("模板目录客户端发送分页并支持版本发布和审计", async ()
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("模板升级和回滚提交预览版本、checksum 与逐项保留确认", async () => {
|
||||
const calls: Array<{ url: string; method?: string; body?: string }> = [];
|
||||
const client = new ApiClient({
|
||||
baseUrl: "http://api.test",
|
||||
token: "brand-token",
|
||||
fetcher: async (url, init) => {
|
||||
calls.push({ url, method: init?.method, body: init?.body });
|
||||
return response({ installation: { templateVersion: "2.0.0" } });
|
||||
},
|
||||
});
|
||||
await client.upgradeAdminTemplate({
|
||||
templatePackageVersionId: "target-version",
|
||||
expectedContentChecksum: "target-checksum",
|
||||
expectedCurrentVersion: "1.0.0",
|
||||
expectedCurrentPackageVersionId: "source-version",
|
||||
confirm: true,
|
||||
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
|
||||
});
|
||||
await client.rollbackAdminTemplate({ expectedCurrentVersion: "2.0.0", confirm: true });
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
url: "http://api.test/admin/workspace/template/upgrade",
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
templatePackageVersionId: "target-version",
|
||||
expectedContentChecksum: "target-checksum",
|
||||
expectedCurrentVersion: "1.0.0",
|
||||
expectedCurrentPackageVersionId: "source-version",
|
||||
confirm: true,
|
||||
preservedBindings: [
|
||||
{ key: "founder", binding: "brand.config.founder", action: "preserve" },
|
||||
],
|
||||
}),
|
||||
},
|
||||
{
|
||||
url: "http://api.test/admin/workspace/template/rollback",
|
||||
method: "POST",
|
||||
body: JSON.stringify({ expectedCurrentVersion: "2.0.0", confirm: true }),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
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({
|
||||
since: "2026-10-01",
|
||||
until: "2026-10-17",
|
||||
days: 14,
|
||||
backfilled: false,
|
||||
failures: [],
|
||||
});
|
||||
},
|
||||
});
|
||||
await client.getAdminTemplateOperationFailures({ days: 14 });
|
||||
assert.deepEqual(calls, [
|
||||
{ url: "http://api.test/admin/template-operations/failures?days=14", method: "GET" },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const ts = require("typescript");
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const packagesRoot = path.join(root, "packages");
|
||||
const configRoot = path.join(packagesRoot, "config/src");
|
||||
const industrySource = fs.readFileSync(path.join(configRoot, "brand-templates.ts"), "utf8");
|
||||
const visualSource = fs.readFileSync(path.join(configRoot, "visual-templates.ts"), "utf8");
|
||||
const capabilitySource = fs.readFileSync(path.join(configRoot, "capability-contracts.ts"), "utf8");
|
||||
const platformPackage = JSON.parse(
|
||||
fs.readFileSync(path.join(root, "apps/taro/package.json"), "utf8"),
|
||||
);
|
||||
const rendererSource = fs.readFileSync(
|
||||
path.join(root, "apps/admin/src/features/brand/component-renderers.jsx"),
|
||||
"utf8",
|
||||
);
|
||||
function exportedObject(source, name) {
|
||||
const file = ts.createSourceFile("config.ts", source, ts.ScriptTarget.Latest, true);
|
||||
for (const statement of file.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue;
|
||||
for (const declaration of statement.declarationList.declarations) {
|
||||
if (
|
||||
ts.isIdentifier(declaration.name) &&
|
||||
declaration.name.text === name &&
|
||||
declaration.initializer
|
||||
) {
|
||||
const initializer = declaration.initializer;
|
||||
const object = ts.isSatisfiesExpression(initializer) ? initializer.expression : initializer;
|
||||
if (ts.isAsExpression(object)) return object.expression;
|
||||
return object;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(`Could not find exported object ${name}`);
|
||||
}
|
||||
function propertyName(property) {
|
||||
if (!ts.isPropertyAssignment(property)) return null;
|
||||
if (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
|
||||
return property.name.text;
|
||||
return null;
|
||||
}
|
||||
function propertyValue(object, key) {
|
||||
if (!ts.isObjectLiteralExpression(object)) return null;
|
||||
return object.properties.find((property) => propertyName(property) === key)?.initializer ?? null;
|
||||
}
|
||||
function objectKeys(object) {
|
||||
return ts.isObjectLiteralExpression(object)
|
||||
? object.properties.map(propertyName).filter(Boolean)
|
||||
: [];
|
||||
}
|
||||
function stringArray(expression) {
|
||||
return expression && ts.isArrayLiteralExpression(expression)
|
||||
? expression.elements.filter(ts.isStringLiteral).map((element) => element.text)
|
||||
: [];
|
||||
}
|
||||
const brandTemplateObject = exportedObject(industrySource, "brandTemplates");
|
||||
const visualTemplateObject = exportedObject(visualSource, "visualTemplates");
|
||||
const capabilityObject = exportedObject(capabilitySource, "capabilityRegistry");
|
||||
const industries = objectKeys(brandTemplateObject);
|
||||
const visualKeys = objectKeys(visualTemplateObject);
|
||||
const capabilityKeys = objectKeys(capabilityObject);
|
||||
const industryCapabilities = Object.fromEntries(
|
||||
(ts.isObjectLiteralExpression(brandTemplateObject) ? brandTemplateObject.properties : [])
|
||||
.map((property) => {
|
||||
const key = propertyName(property);
|
||||
const definition = ts.isPropertyAssignment(property) ? property.initializer : null;
|
||||
return [key, stringArray(propertyValue(definition, "capabilities"))];
|
||||
})
|
||||
.filter(([key]) => key),
|
||||
);
|
||||
const rendererGlob = rendererSource.match(/template-\*\/taro\/index\.tsx/);
|
||||
const packages = fs
|
||||
.readdirSync(packagesRoot, { withFileTypes: true })
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.isDirectory() &&
|
||||
entry.name.startsWith("template-") &&
|
||||
fs.existsSync(path.join(packagesRoot, entry.name, "template.json")),
|
||||
)
|
||||
.map((entry) => ({
|
||||
directory: entry.name,
|
||||
package: JSON.parse(
|
||||
fs.readFileSync(path.join(packagesRoot, entry.name, "package.json"), "utf8"),
|
||||
),
|
||||
manifest: JSON.parse(
|
||||
fs.readFileSync(path.join(packagesRoot, entry.name, "template.json"), "utf8"),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.manifest.packageKey.localeCompare(right.manifest.packageKey));
|
||||
|
||||
const results = [];
|
||||
const errors = [];
|
||||
const versionMajorMinor = (value) =>
|
||||
String(value ?? "")
|
||||
.replace(/^[^0-9]*/, "")
|
||||
.split(".")
|
||||
.slice(0, 2)
|
||||
.join(".");
|
||||
const platformRuntimeVersions = Object.fromEntries(
|
||||
Object.entries({ ...platformPackage.dependencies, ...platformPackage.devDependencies }).filter(
|
||||
([name]) => name.startsWith("@tarojs/") || name === "react" || name === "react-dom",
|
||||
),
|
||||
);
|
||||
for (const { directory, manifest, package: packageMetadata } of packages) {
|
||||
const key = manifest.packageKey;
|
||||
const packageIndustries = Array.isArray(manifest.supportedIndustryTemplates)
|
||||
? manifest.supportedIndustryTemplates
|
||||
: [];
|
||||
const visualKey = manifest.visualTemplateKey ?? key;
|
||||
const visualRegistered = visualKeys.includes(visualKey);
|
||||
const rendererPath = `${directory}/taro/index.tsx`;
|
||||
const rendererExists = fs.existsSync(path.join(packagesRoot, rendererPath));
|
||||
const rendererExport = rendererExists
|
||||
? /export\s+(?:async\s+)?function\s+TemplatePage\b|export\s+\{[^}]*\bTemplatePage\b/.test(
|
||||
fs.readFileSync(path.join(packagesRoot, rendererPath), "utf8"),
|
||||
)
|
||||
: false;
|
||||
const templateTaroVersion = packageMetadata.dependencies?.["@tarojs/taro"];
|
||||
const toolchainMismatches = Object.entries(platformRuntimeVersions).flatMap(([name, version]) => {
|
||||
const templateVersion =
|
||||
packageMetadata.dependencies?.[name] ?? packageMetadata.devDependencies?.[name];
|
||||
return templateVersion && versionMajorMinor(templateVersion) !== versionMajorMinor(version)
|
||||
? [`${name}: package ${templateVersion}, platform ${version}`]
|
||||
: [];
|
||||
});
|
||||
if (!templateTaroVersion) toolchainMismatches.push("@tarojs/taro: package dependency is missing");
|
||||
if (!packageMetadata.dependencies?.react)
|
||||
toolchainMismatches.push("react: package dependency is missing");
|
||||
const toolchainCompatible = toolchainMismatches.length === 0;
|
||||
const declaredCapabilities = Array.isArray(manifest.requiredCapabilities)
|
||||
? manifest.requiredCapabilities
|
||||
: [];
|
||||
const unknownCapabilities = declaredCapabilities.filter(
|
||||
(capability) => !capabilityKeys.includes(capability),
|
||||
);
|
||||
if (!industries.length) errors.push("No industry definitions found in brand-templates.ts");
|
||||
if (!capabilityKeys.length)
|
||||
errors.push("No capability definitions found in capability-contracts.ts");
|
||||
if (!rendererGlob) errors.push("Admin renderer package glob is not discoverable");
|
||||
if (!packageIndustries.length) errors.push(`${key}: supportedIndustryTemplates is empty`);
|
||||
if (unknownCapabilities.length)
|
||||
errors.push(`${key}: unknown capabilities ${unknownCapabilities.join(", ")}`);
|
||||
if (!toolchainCompatible)
|
||||
errors.push(`${key}: Taro/React package versions are incompatible with the platform toolchain`);
|
||||
for (const industry of packageIndustries) {
|
||||
if (!industries.includes(industry)) errors.push(`${key}: unknown industry ${industry}`);
|
||||
const incompatibleCapabilities = declaredCapabilities.filter(
|
||||
(capability) =>
|
||||
!unknownCapabilities.includes(capability) &&
|
||||
!industryCapabilities[industry]?.includes(capability),
|
||||
);
|
||||
const supported =
|
||||
industries.includes(industry) &&
|
||||
visualRegistered &&
|
||||
rendererExport &&
|
||||
toolchainCompatible &&
|
||||
!unknownCapabilities.length &&
|
||||
!incompatibleCapabilities.length;
|
||||
results.push({
|
||||
packageKey: key,
|
||||
version: manifest.version,
|
||||
industry,
|
||||
visualTemplateKey: visualKey,
|
||||
runtimeContract: manifest.runtimeContract,
|
||||
capabilities: declaredCapabilities,
|
||||
toolchain: {
|
||||
package: Object.fromEntries(
|
||||
Object.keys(platformRuntimeVersions).flatMap((name) => {
|
||||
const version =
|
||||
packageMetadata.dependencies?.[name] ?? packageMetadata.devDependencies?.[name];
|
||||
return version ? [[name, version]] : [];
|
||||
}),
|
||||
),
|
||||
platform: platformRuntimeVersions,
|
||||
compatible: toolchainCompatible,
|
||||
mismatches: toolchainMismatches,
|
||||
},
|
||||
renderer: rendererExists && rendererExport ? rendererPath : null,
|
||||
adminRendererDiscovery: Boolean(rendererGlob),
|
||||
status: supported ? "supported" : "rejected",
|
||||
reasons: [
|
||||
...(!industries.includes(industry) ? ["unknown industry"] : []),
|
||||
...(!visualRegistered ? ["platform visual renderer is not registered"] : []),
|
||||
...(!rendererExists ? ["Taro package renderer is missing"] : []),
|
||||
...(rendererExists && !rendererExport
|
||||
? ["Taro renderer does not export TemplatePage"]
|
||||
: []),
|
||||
...toolchainMismatches.map((mismatch) => `toolchain mismatch: ${mismatch}`),
|
||||
...incompatibleCapabilities.map(
|
||||
(capability) => `industry does not declare capability ${capability}`,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const report = {
|
||||
schemaVersion: 1,
|
||||
runtimeContract: "1.0",
|
||||
industries,
|
||||
platformVisualRenderers: visualKeys,
|
||||
capabilities: capabilityKeys,
|
||||
packages: results,
|
||||
};
|
||||
if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
||||
else {
|
||||
for (const item of results)
|
||||
process.stdout.write(
|
||||
`${item.status.padEnd(9)} ${item.packageKey}@${item.version} × ${item.industry} → ${item.visualTemplateKey}${item.reasons.length ? ` (${item.reasons.join(", ")})` : ""}\n`,
|
||||
);
|
||||
}
|
||||
if (errors.length) {
|
||||
process.stderr.write(`${errors.join("\n")}\n`);
|
||||
process.exitCode = 1;
|
||||
} else if (!packages.length) {
|
||||
process.stderr.write("No template packages found\n");
|
||||
process.exitCode = 1;
|
||||
} else if (results.some((item) => item.status === "rejected")) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { cpSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import test from "node:test";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const script = path.join(root, "scripts/template-compatibility.cjs");
|
||||
|
||||
test("compatibility report discovers deployed package, industry, visual and renderer combinations", () => {
|
||||
const report = JSON.parse(execFileSync(process.execPath, [script, "--json"], { cwd: root }));
|
||||
assert.equal(report.schemaVersion, 1);
|
||||
assert.ok(report.packages.length >= 3);
|
||||
assert.ok(report.packages.every((item) => item.status === "supported"));
|
||||
assert.ok(
|
||||
report.packages.some(
|
||||
(item) => item.packageKey === "linjing-editorial" && item.industry === "doors",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("compatibility check rejects renderer, capability and toolchain incompatibilities", () => {
|
||||
const packagesRoot = path.join(root, "packages");
|
||||
const sourcePath = path.join(packagesRoot, "template-atelier-solopreneur/template.json");
|
||||
const source = JSON.parse(readFileSync(sourcePath, "utf8"));
|
||||
const directory = mkdtempSync(path.join(os.tmpdir(), "template-compatibility-"));
|
||||
const original = {
|
||||
...source,
|
||||
packageKey: "compatibility-probe",
|
||||
visualTemplateKey: "missing-visual",
|
||||
requiredCapabilities: ["booking", "unknown-capability"],
|
||||
};
|
||||
try {
|
||||
const scriptSource = readFileSync(script, "utf8");
|
||||
const probeRoot = path.join(directory, "repo");
|
||||
const probePackages = path.join(probeRoot, "packages");
|
||||
const probeConfig = path.join(probePackages, "config/src");
|
||||
const probeRenderer = path.join(probeRoot, "apps/admin/src/features/brand");
|
||||
const probeTaro = path.join(probeRoot, "apps/taro");
|
||||
mkdirSync(probeConfig, { recursive: true });
|
||||
mkdirSync(probeRenderer, { recursive: true });
|
||||
mkdirSync(probeTaro, { recursive: true });
|
||||
cpSync(
|
||||
path.join(packagesRoot, "template-atelier-solopreneur"),
|
||||
path.join(probePackages, "template-compatibility-probe"),
|
||||
{ recursive: true },
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(probePackages, "template-compatibility-probe/template.json"),
|
||||
JSON.stringify(original),
|
||||
);
|
||||
cpSync(
|
||||
path.join(root, "packages/config/src/brand-templates.ts"),
|
||||
path.join(probeConfig, "brand-templates.ts"),
|
||||
);
|
||||
cpSync(
|
||||
path.join(root, "packages/config/src/visual-templates.ts"),
|
||||
path.join(probeConfig, "visual-templates.ts"),
|
||||
);
|
||||
cpSync(
|
||||
path.join(root, "packages/config/src/capability-contracts.ts"),
|
||||
path.join(probeConfig, "capability-contracts.ts"),
|
||||
);
|
||||
const platformPackage = JSON.parse(
|
||||
readFileSync(path.join(root, "apps/taro/package.json"), "utf8"),
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(probeTaro, "package.json"),
|
||||
JSON.stringify({
|
||||
...platformPackage,
|
||||
dependencies: { ...platformPackage.dependencies, "@tarojs/taro": "5.0.0" },
|
||||
}),
|
||||
);
|
||||
cpSync(
|
||||
path.join(root, "apps/admin/src/features/brand/component-renderers.jsx"),
|
||||
path.join(probeRenderer, "component-renderers.jsx"),
|
||||
);
|
||||
const probeScript = path.join(probeRoot, "scripts/template-compatibility.cjs");
|
||||
mkdirSync(path.dirname(probeScript), { recursive: true });
|
||||
writeFileSync(
|
||||
probeScript,
|
||||
scriptSource.replace(
|
||||
'require("typescript")',
|
||||
`require(${JSON.stringify(path.join(root, "node_modules/typescript"))})`,
|
||||
),
|
||||
);
|
||||
const result = spawnSync(process.execPath, [probeScript, "--json"], {
|
||||
encoding: "utf8",
|
||||
cwd: probeRoot,
|
||||
});
|
||||
assert.equal(result.status, 1, result.stdout);
|
||||
const report = JSON.parse(result.stdout);
|
||||
assert.match(result.stderr, /unknown capabilities unknown-capability/);
|
||||
assert.ok(report.packages.some((item) => item.packageKey === "compatibility-probe"));
|
||||
const probe = report.packages.find((item) => item.packageKey === "compatibility-probe");
|
||||
assert.ok(
|
||||
probe.status === "rejected" &&
|
||||
probe.reasons.includes("platform visual renderer is not registered") &&
|
||||
probe.reasons.includes("industry does not declare capability booking") &&
|
||||
probe.reasons.some((reason) => reason.includes("toolchain mismatch: @tarojs/taro")),
|
||||
JSON.stringify(probe),
|
||||
);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const packagesRoot = path.join(root, "packages");
|
||||
|
||||
function usage() {
|
||||
process.stderr.write("Usage: pnpm template:new <package-key>\n");
|
||||
}
|
||||
|
||||
function main() {
|
||||
const packageKey = process.argv[2];
|
||||
if (!packageKey || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(packageKey)) {
|
||||
usage();
|
||||
return 1;
|
||||
}
|
||||
const packageDirectory = path.join(packagesRoot, `template-${packageKey}`);
|
||||
if (fs.existsSync(packageDirectory))
|
||||
throw new Error(`Template package already exists: ${packageKey}`);
|
||||
const packageJson = {
|
||||
name: `@personal-brand/template-${packageKey}`,
|
||||
version: "0.1.0",
|
||||
private: true,
|
||||
type: "module",
|
||||
files: ["template.json", "README.md", "taro"],
|
||||
dependencies: {
|
||||
"@personal-brand/types": "workspace:*",
|
||||
"@tarojs/components": "4.3.0",
|
||||
"@tarojs/plugin-platform-h5": "4.3.0",
|
||||
"@tarojs/plugin-platform-weapp": "4.3.0",
|
||||
"@tarojs/taro": "4.3.0",
|
||||
react: "18.3.1",
|
||||
"react-dom": "18.3.1",
|
||||
},
|
||||
devDependencies: { "@types/react": "18.3.18" },
|
||||
};
|
||||
const manifest = {
|
||||
packageKey,
|
||||
version: "0.1.0",
|
||||
displayName: `${packageKey} (未验收模板)`,
|
||||
defaultBrandSlug: "replace-with-brand-slug",
|
||||
visualTemplateKey: packageKey,
|
||||
runtimeContract: "1.0",
|
||||
supportedIndustryTemplates: ["replace-with-supported-industry"],
|
||||
entrypoints: {
|
||||
home: "pages/home/index",
|
||||
offerings: "pages/offerings/index",
|
||||
detail: "pages/detail/index",
|
||||
inquiry: "pages/inquiry/index",
|
||||
success: "pages/success/index",
|
||||
records: "pages/records/index",
|
||||
profile: "pages/profile/index",
|
||||
},
|
||||
navigation: [],
|
||||
requiredCapabilities: ["offerings", "inquiry"],
|
||||
dataSlots: [],
|
||||
assetSlots: [],
|
||||
pages: ["home", "offerings", "detail", "inquiry", "success", "records", "profile"],
|
||||
admin: { sections: [] },
|
||||
previewFixture: {},
|
||||
};
|
||||
const renderer = `import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
|
||||
export function TemplatePage({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
return <main data-template="${packageKey}">{workspace.brand.name}</main>;
|
||||
}
|
||||
`;
|
||||
fs.mkdirSync(path.join(packageDirectory, "taro"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(packageDirectory, "package.json"),
|
||||
`${JSON.stringify(packageJson, null, 2)}\n`,
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(packageDirectory, "template.json"),
|
||||
`${JSON.stringify(manifest, null, 2)}\n`,
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(packageDirectory, "README.md"),
|
||||
`# ${packageKey}\n\nScaffold only. Complete manifest, renderer, assets, bindings and acceptance before import or release.\n`,
|
||||
);
|
||||
fs.writeFileSync(path.join(packageDirectory, "taro/index.tsx"), renderer);
|
||||
process.stdout.write(
|
||||
`Created ${path.relative(root, packageDirectory)}. Complete all replace-with values and register/deploy the platform visual renderer before validation.\n`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
process.exitCode = main();
|
||||
} catch (error) {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import test from "node:test";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const script = path.join(root, "scripts/template-new.cjs");
|
||||
|
||||
test("template:new scaffolds a package with manifest, renderer and an explicit incomplete status", () => {
|
||||
const temporary = mkdtempSync(path.join(os.tmpdir(), "template-new-test-"));
|
||||
const packagesDirectory = path.join(temporary, "packages");
|
||||
const isolatedScript = path.join(temporary, "scripts/template-new.cjs");
|
||||
mkdirSync(path.dirname(isolatedScript), { recursive: true });
|
||||
mkdirSync(packagesDirectory, { recursive: true });
|
||||
cpSync(script, isolatedScript);
|
||||
const source = readFileSync(script, "utf8").replace(
|
||||
'const root = path.resolve(__dirname, "..");',
|
||||
`const root = ${JSON.stringify(temporary)};`,
|
||||
);
|
||||
const patchedScript = path.join(temporary, "scripts/template-new-isolated.cjs");
|
||||
writeFileSync(patchedScript, source);
|
||||
try {
|
||||
execFileSync(process.execPath, [patchedScript, "example-brand"], { encoding: "utf8" });
|
||||
const directory = path.join(packagesDirectory, "template-example-brand");
|
||||
const manifest = JSON.parse(readFileSync(path.join(directory, "template.json"), "utf8"));
|
||||
assert.equal(manifest.packageKey, "example-brand");
|
||||
assert.match(manifest.supportedIndustryTemplates[0], /^replace-with-/);
|
||||
assert.match(readFileSync(path.join(directory, "README.md"), "utf8"), /Scaffold only/);
|
||||
assert.match(readFileSync(path.join(directory, "taro/index.tsx"), "utf8"), /TemplatePage/);
|
||||
const duplicate = spawnSync(process.execPath, [patchedScript, "example-brand"], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
assert.equal(duplicate.status, 1);
|
||||
} finally {
|
||||
rmSync(temporary, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user