318 lines
12 KiB
TypeScript
318 lines
12 KiB
TypeScript
import { useRef, useState } from "react";
|
||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import { Alert, Button, List, Modal, Table, Tag, Typography, message } from "antd";
|
||
import { EyeOutlined, ReloadOutlined, UploadOutlined } from "@ant-design/icons";
|
||
import type { TemplatePackageVersion } from "@personal-brand/api-client";
|
||
import { createApiClient } from "../../lib/api.js";
|
||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||
import { AdminSection } from "../../components/AdminSection.js";
|
||
import { EmptyState } from "../../components/EmptyState.js";
|
||
import { ErrorNote, QueryState } from "../../components/QueryState.js";
|
||
import { TemplatePackagePreviewModal } from "./TemplatePackagePreviewModal.js";
|
||
|
||
const client = createApiClient();
|
||
|
||
const failureActionLabels: Record<string, string> = {
|
||
import: "模板导入失败",
|
||
preview: "模板预览失败",
|
||
install: "模板安装失败",
|
||
upgrade: "模板升级失败",
|
||
rollback: "模板回滚失败",
|
||
install_conflict: "模板操作冲突",
|
||
build: "小程序构建失败",
|
||
upload: "小程序上传失败",
|
||
};
|
||
|
||
function formatBytes(value: unknown): string {
|
||
const bytes = typeof value === "number" ? value : 0;
|
||
if (bytes < 1024) return `${bytes} B`;
|
||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||
}
|
||
|
||
export function TemplateManagementPage() {
|
||
const inputRef = useRef<HTMLInputElement>(null);
|
||
const [page, setPage] = useState(1);
|
||
const [pageSize, setPageSize] = useState(20);
|
||
const [auditId, setAuditId] = useState<string | null>(null);
|
||
const [previewVersion, setPreviewVersion] = useState<TemplatePackageVersion | null>(null);
|
||
const queryClient = useQueryClient();
|
||
const packages = useQuery({
|
||
queryKey: ["admin-template-packages", page, pageSize],
|
||
queryFn: () => client.listAdminTemplatePackages({ page, pageSize }),
|
||
});
|
||
const audit = useQuery({
|
||
queryKey: ["admin-template-package-audit", auditId],
|
||
queryFn: () => client.listAdminTemplatePackageAudit(auditId as string),
|
||
enabled: Boolean(auditId),
|
||
});
|
||
const 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"
|
||
? client.publishAdminTemplatePackage(id)
|
||
: client.retireAdminTemplatePackage(id),
|
||
onSuccess: (result) => {
|
||
void queryClient.invalidateQueries({ queryKey: ["admin-template-packages"] });
|
||
message.success(result.changed ? "模板目录状态已更新" : "模板目录状态未变化");
|
||
},
|
||
});
|
||
const importing = useMutation({
|
||
mutationFn: (file: File) => {
|
||
const form = new FormData();
|
||
form.append("archive", file, file.name);
|
||
return client.importAdminTemplatePackage(form);
|
||
},
|
||
onSuccess: () => {
|
||
void queryClient.invalidateQueries({ queryKey: ["admin-template-packages"] });
|
||
},
|
||
});
|
||
const chooseFile = () => inputRef.current?.click();
|
||
const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||
const file = event.target.files?.[0];
|
||
event.target.value = "";
|
||
if (!file) return;
|
||
if (!file.name.endsWith(".tar.gz")) {
|
||
importing.reset();
|
||
return;
|
||
}
|
||
importing.mutate(file);
|
||
};
|
||
const rows = packages.data?.items ?? [];
|
||
return (
|
||
<div className="admin-stack admin-stack-lg">
|
||
<AdminPageHeader
|
||
title="模板管理"
|
||
description="导入通过本地模板检查的确定性 archive,登记版本、校验摘要并供后续预览与安装使用。"
|
||
extra={
|
||
<>
|
||
<input
|
||
ref={inputRef}
|
||
type="file"
|
||
accept=".tar.gz,application/gzip"
|
||
onChange={onFileChange}
|
||
hidden
|
||
/>
|
||
<Button
|
||
type="primary"
|
||
icon={<UploadOutlined />}
|
||
loading={importing.isPending}
|
||
onClick={chooseFile}
|
||
>
|
||
导入模板包
|
||
</Button>
|
||
</>
|
||
}
|
||
/>
|
||
<Alert
|
||
type="info"
|
||
showIcon
|
||
message="导入规则"
|
||
description="系统会校验文件路径、链接、文件数量、解压体积、template.json、package.json 和 checksums.json;包内脚本不会被执行。"
|
||
/>
|
||
{importing.isError ? <ErrorNote error={importing.error} /> : null}
|
||
{importing.isSuccess ? (
|
||
<Alert
|
||
type="success"
|
||
showIcon
|
||
message={importing.data.idempotent ? "模板版本已存在,未重复写入" : "模板版本导入成功"}
|
||
description={`${importing.data.version.packageKey}@${importing.data.version.version}`}
|
||
/>
|
||
) : null}
|
||
{lifecycle.isError ? <ErrorNote error={lifecycle.error} /> : null}
|
||
<AdminSection title="近 30 天失败概览" description="按操作类别统计失败次数。">
|
||
<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>
|
||
{failureActionLabels[item.action] ?? "其他操作失败"}:
|
||
<Typography.Text strong>{item.count}</Typography.Text>
|
||
</Typography.Text>
|
||
</List.Item>
|
||
)}
|
||
/>
|
||
</QueryState>
|
||
</AdminSection>
|
||
<AdminSection
|
||
title="已导入版本"
|
||
description="同一 package key 的不同版本并列保留,发布品牌时再选择安装版本。"
|
||
>
|
||
<QueryState
|
||
loading={packages.isLoading}
|
||
error={packages.error}
|
||
onRetry={() => void packages.refetch()}
|
||
>
|
||
{rows.length ? (
|
||
<Table<TemplatePackageVersion>
|
||
rowKey="id"
|
||
dataSource={rows}
|
||
pagination={{
|
||
current: packages.data?.page ?? page,
|
||
pageSize: packages.data?.pageSize ?? pageSize,
|
||
total: packages.data?.total ?? 0,
|
||
showSizeChanger: true,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPageSize === pageSize ? nextPage : 1);
|
||
setPageSize(nextPageSize);
|
||
},
|
||
}}
|
||
scroll={{ x: 980 }}
|
||
columns={[
|
||
{
|
||
title: "模板",
|
||
key: "template",
|
||
render: (_, item) => (
|
||
<div>
|
||
<Typography.Text strong>{item.displayName}</Typography.Text>
|
||
<div className="admin-muted-text">{item.packageKey}</div>
|
||
</div>
|
||
),
|
||
},
|
||
{ title: "版本", dataIndex: "version", key: "version" },
|
||
{
|
||
title: "状态",
|
||
dataIndex: "status",
|
||
key: "status",
|
||
render: (value: TemplatePackageVersion["status"]) => (
|
||
<Tag
|
||
color={
|
||
value === "published" ? "green" : value === "imported" ? "blue" : "default"
|
||
}
|
||
>
|
||
{value === "published"
|
||
? "已发布"
|
||
: value === "imported"
|
||
? "待发布"
|
||
: value === "retired"
|
||
? "已撤回"
|
||
: "已停用"}
|
||
</Tag>
|
||
),
|
||
},
|
||
{
|
||
title: "文件",
|
||
key: "report",
|
||
render: (_, item) => {
|
||
const report = item.validationReport;
|
||
return `${typeof report.fileCount === "number" ? report.fileCount : "-"} 个,${formatBytes(report.extractedBytes)}`;
|
||
},
|
||
},
|
||
{
|
||
title: "内容 checksum",
|
||
dataIndex: "contentChecksum",
|
||
key: "contentChecksum",
|
||
render: (value: string) => (
|
||
<Typography.Text copyable>{value.slice(0, 16)}…</Typography.Text>
|
||
),
|
||
},
|
||
{
|
||
title: "导入人",
|
||
key: "importedBy",
|
||
render: (_, item) => item.importedBy.displayName,
|
||
},
|
||
{
|
||
title: "操作",
|
||
key: "actions",
|
||
render: (_, item) => (
|
||
<span>
|
||
<Button
|
||
type="link"
|
||
icon={<EyeOutlined />}
|
||
onClick={() => setPreviewVersion(item)}
|
||
disabled={
|
||
item.status === "retired" ||
|
||
item.status === "disabled" ||
|
||
!item.manifestSummary?.supportedIndustryTemplates?.length
|
||
}
|
||
>
|
||
预览
|
||
</Button>
|
||
<Button
|
||
type="link"
|
||
loading={lifecycle.isPending && lifecycle.variables?.id === item.id}
|
||
onClick={() =>
|
||
lifecycle.mutate({
|
||
id: item.id,
|
||
action: item.status === "published" ? "retire" : "publish",
|
||
})
|
||
}
|
||
disabled={item.status === "disabled"}
|
||
>
|
||
{item.status === "published" ? "撤回" : "发布"}
|
||
</Button>
|
||
<Button type="link" onClick={() => setAuditId(item.id)}>
|
||
审计
|
||
</Button>
|
||
</span>
|
||
),
|
||
},
|
||
]}
|
||
/>
|
||
) : (
|
||
<EmptyState
|
||
title="还没有导入模板"
|
||
description="从本地执行 template:pack 后导入 tar.gz。"
|
||
/>
|
||
)}
|
||
</QueryState>
|
||
</AdminSection>
|
||
{packages.isError ? (
|
||
<Button icon={<ReloadOutlined />} onClick={() => void packages.refetch()}>
|
||
重试加载
|
||
</Button>
|
||
) : null}
|
||
<Modal
|
||
title="模板版本审计"
|
||
open={Boolean(auditId)}
|
||
footer={null}
|
||
onCancel={() => setAuditId(null)}
|
||
>
|
||
<QueryState
|
||
loading={audit.isLoading}
|
||
error={audit.error}
|
||
onRetry={() => void audit.refetch()}
|
||
>
|
||
<List
|
||
dataSource={audit.data ?? []}
|
||
locale={{ emptyText: "暂无审计记录" }}
|
||
renderItem={(item) => (
|
||
<List.Item>
|
||
<List.Item.Meta
|
||
title={`${item.action === "previewed" ? "预览模板" : item.action} · ${item.actor.displayName}`}
|
||
description={
|
||
item.action === "previewed"
|
||
? `行业 ${typeof item.metadata?.industry === "string" ? item.metadata.industry : "-"} · ${new Date(item.createdAt).toLocaleString()}`
|
||
: `${item.fromStatus ?? "-"} -> ${item.toStatus ?? "-"} · ${new Date(item.createdAt).toLocaleString()}`
|
||
}
|
||
/>
|
||
</List.Item>
|
||
)}
|
||
/>
|
||
</QueryState>
|
||
</Modal>
|
||
{previewVersion ? (
|
||
<TemplatePackagePreviewModal
|
||
version={previewVersion}
|
||
onClose={() => {
|
||
setPreviewVersion(null);
|
||
void queryClient.invalidateQueries({
|
||
queryKey: ["admin-template-package-audit", previewVersion.id],
|
||
});
|
||
}}
|
||
/>
|
||
) : null}
|
||
</div>
|
||
);
|
||
}
|