feat: 新增交通银行数据导出插件及测试通道机制

This commit is contained in:
2026-11-05 15:20:34 +08:00
parent 85051f979b
commit 4bac1248ad
230 changed files with 19827 additions and 1440 deletions
@@ -20,8 +20,8 @@ export function fetchPlugins(params: { page?: number; page_size?: number; q?: st
return request.get<{ items: any[]; total: number }>({ url: '/api/admin/plugins', params })
}
/** 上传发布插件包(multipart) */
export function uploadPlugin(file: File, params: { plugin_id: string; name?: string; version: string }) {
/** 上传发布插件包(multipart;channel=test 进测试通道,仅管理员可见) */
export function uploadPlugin(file: File, params: { plugin_id: string; name?: string; version: string; channel?: string }) {
const fd = new FormData()
fd.append('file', file)
return request.post<any>({ url: '/api/admin/pkg', data: fd, params, timeout: 300000 })
@@ -22,10 +22,12 @@ const authorizedCount = computed(() => stats.value.users?.authorized || 0)
const pluginStatus = computed(() => {
const plugins = overview.value.plugins || []
const published = plugins.filter((p: any) => p.status === 'published').length
const testing = plugins.filter((p: any) => p.status === 'testing').length
const disabled = plugins.filter((p: any) => p.status === 'disabled').length
const revoked = plugins.filter((p: any) => p.status === 'revoked').length
return [
{ name: '已发布', value: published },
{ name: '测试中', value: testing },
{ name: '已停用', value: disabled },
{ name: '已吊销', value: revoked }
]
@@ -17,6 +17,7 @@ const query = reactive({ page: 1, page_size: 10, q: '' })
const statusMap: Record<string, { label: string; type: any }> = {
published: { label: '已发布', type: 'success' },
testing: { label: '测试中', type: 'primary' },
disabled: { label: '已禁用', type: 'warning' },
revoked: { label: '已下架', type: 'danger' }
}
@@ -40,10 +41,10 @@ function search() {
// ---- 上传发布 ----
const uploadOpen = ref(false)
const uploading = ref(false)
const uploadForm = reactive({ plugin_id: '', name: '', version: '', file: null as File | null })
const uploadForm = reactive({ plugin_id: '', name: '', version: '', channel: 'test', file: null as File | null })
function openUpload() {
Object.assign(uploadForm, { plugin_id: '', name: '', version: '', file: null })
Object.assign(uploadForm, { plugin_id: '', name: '', version: '', channel: 'test', file: null })
uploadOpen.value = true
}
@@ -57,9 +58,10 @@ async function submitUpload() {
await uploadPlugin(uploadForm.file, {
plugin_id: uploadForm.plugin_id,
name: uploadForm.name,
version: uploadForm.version
version: uploadForm.version,
channel: uploadForm.channel
})
ElMessage.success('上传发布成功')
ElMessage.success(uploadForm.channel === 'test' ? '测试版已上传(仅管理员可见)' : '已直发正式版')
uploadOpen.value = false
load()
} finally {
@@ -74,6 +76,22 @@ async function setStatus(row: any, status: string) {
load()
}
// ---- 测试版转正:把在测版本提升为正式版,全量已授权账号生效 ----
async function promote(row: any) {
try {
await ElMessageBox.confirm(
`确认把测试版 v${row.test_version} 转正?转正后所有已授权账号下次同步即升级到该版本(不再单独打包)。`,
'测试版转正',
{ type: 'warning', confirmButtonText: '转正发布', cancelButtonText: '取消' }
)
} catch {
return
}
await patchPlugin(row.id, { status: 'published' })
ElMessage.success(`v${row.test_version} 已转正为正式版`)
load()
}
// ---- 分类维护(字典 plugin_category:在「分类管理」弹窗中增删改/排序) ----
const DICT_KEY = 'plugin_category'
const categories = ref<{ id: number; label: string }[]>([])
@@ -246,7 +264,15 @@ onMounted(() => {
<el-table v-loading="loading" :data="list" border stripe>
<el-table-column prop="id" label="插件ID" min-width="140" />
<el-table-column prop="name" label="名称" min-width="160" />
<el-table-column prop="latest_version" label="最新版本" width="110" />
<el-table-column label="正式版本" width="110">
<template #default="{ row }">{{ row.latest_version || '-' }}</template>
</el-table-column>
<el-table-column label="在测版本" width="110">
<template #default="{ row }">
<el-tag v-if="row.test_version" size="small" type="primary">{{ row.test_version }}</el-tag>
<span v-else class="text-gray-300 text-xs">-</span>
</template>
</el-table-column>
<el-table-column prop="category" label="分类" width="150">
<template #default="{ row }">
<el-select
@@ -297,7 +323,12 @@ onMounted(() => {
@click="setStatus(row, 'published')"
>启用</el-button>
<el-button
v-if="row.status === 'published'"
v-if="row.status === 'testing' && row.test_version"
link type="primary"
@click="promote(row)"
>转正</el-button>
<el-button
v-if="row.status === 'published' || row.status === 'testing'"
link type="warning"
@click="setStatus(row, 'disabled')"
>禁用</el-button>
@@ -338,6 +369,16 @@ onMounted(() => {
<el-form-item label="安装包" required>
<input type="file" accept=".zip" @change="(e: any) => (uploadForm.file = e.target.files[0] || null)" />
</el-form-item>
<el-form-item label="发布通道">
<el-radio-group v-model="uploadForm.channel">
<el-radio value="test">测试版(仅管理员可见)</el-radio>
<el-radio value="prod">正式版(立即全量生效)</el-radio>
</el-radio-group>
<div class="text-xs text-gray-400 leading-5 mt-1">
测试版发布后状态为「测试中」:管理员账号同步到新版本,其他账号继续用当前正式版。
人工验证通过后点列表里的「转正」即全量生效。
</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="uploadOpen = false">取消</el-button>
@@ -0,0 +1,12 @@
-- 2026-10-31 插件测试通道:plugins 增加 test_version(在测版本)
-- 背景:新版本先发测试通道,仅管理员账号可见;人工验证通过后把 status 改为 published 即转正,
-- 服务端将 test_version 提升为 latest_version(复用同一版本号,不重新打包),全量生效。
-- 部署步骤:MySQL 执行本文件 → systemctl restart 37du-controlplane-next.service
-- ⚠️ 重复执行会报 Duplicate column name,属正常现象,可忽略。
ALTER TABLE `plugins`
ADD COLUMN `test_version` varchar(32) NOT NULL DEFAULT '' COMMENT '测试通道在测版本(空=无在测版本)'
AFTER `latest_version`;
-- status 取值扩展为 published / testing / disabled / revoked(无枚举约束,无需改列)
-- testing = 有新版本在测试:管理员账号取 test_version,其他账号继续取 latest_version
@@ -71,6 +71,7 @@ export class AdminOpsController extends BaseController {
pluginOut.push({
id: p.id, name: p.name, description: p.description || '', category: p.category || '',
icon: p.icon || '', status: p.status, latest_version: p.latestVersion,
test_version: p.testVersion || '',
force_min_version: p.forceMinVersion, force_deadline: p.forceDeadline,
manifest: m, capabilities: m.capabilities || [], permissions: m.permissions || {},
field_count: Object.keys((m.fields || {}).properties || {}).length,
@@ -99,6 +100,7 @@ export class AdminOpsController extends BaseController {
const plugins: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM plugins) AS total,
(SELECT COUNT(*) FROM plugins WHERE status='published') AS published,
(SELECT COUNT(*) FROM plugins WHERE status='testing') AS testing,
(SELECT COUNT(*) FROM plugins WHERE status='disabled') AS disabled,
(SELECT COUNT(*) FROM plugins WHERE status='revoked') AS revoked`))[0];
const runs: any = (await m.query(
@@ -140,7 +142,7 @@ export class AdminOpsController extends BaseController {
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
users: { total: Number(users.total || 0), admins: Number(users.admins || 0), authorized: Number(users.authorized || 0) },
plugins: { total: Number(plugins.total || 0), published: Number(plugins.published || 0), disabled: Number(plugins.disabled || 0), revoked: Number(plugins.revoked || 0) },
plugins: { total: Number(plugins.total || 0), published: Number(plugins.published || 0), testing: Number(plugins.testing || 0), disabled: Number(plugins.disabled || 0), revoked: Number(plugins.revoked || 0) },
runs: { total: Number(runs.started || 0), success: Number(runs.success || 0), failed: Number(runs.failed || 0), durationSec: Number(runs.duration_sec || 0), activeUsers: Number(runs.active_users || 0), activePlugins: Number(runs.active_plugins || 0) },
trend,
topPlugins: topPlugins.map((tp: any) => ({ ...tp, name: pnames[tp.pluginId] || tp.pluginId, runs: Number(tp.triggered || 0) })),
@@ -73,7 +73,7 @@ export class AdminPluginController extends BaseController {
const m = this.pluginRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM plugins${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, name, description, category, icon, status, latest_version,
`SELECT id, name, description, category, icon, status, latest_version, test_version,
force_min_version, force_deadline, manifest
FROM plugins${where} ORDER BY id LIMIT ? OFFSET ?`,
[...args, limit, offset]
@@ -94,6 +94,7 @@ export class AdminPluginController extends BaseController {
icon: p.icon || '',
status: p.status,
latest_version: p.latest_version,
test_version: p.test_version || '',
force_min_version: p.force_min_version,
force_deadline: p.force_deadline,
manifest,
@@ -106,13 +107,14 @@ export class AdminPluginController extends BaseController {
return { items, total: Number(total.c || 0) };
}
/** POST /api/admin/pkg — 上传发布插件包 */
/** POST /api/admin/pkg — 上传发布插件包(channel=test 进测试通道,仅管理员可见;channel=prod 直发正式) */
@Post('/pkg')
async pkg(
@File() file: any,
@Query('plugin_id') pluginId: string = '',
@Query('name') name: string = '',
@Query('version') version: string = '',
@Query('channel') channel: string = 'test',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
@@ -120,10 +122,18 @@ export class AdminPluginController extends BaseController {
pluginId = (pluginId || '').trim();
version = (version || '').trim();
name = (name || '').trim() || pluginId;
channel = (channel || 'test').trim().toLowerCase();
if (!pluginId || !version) throw new ApiError(400, 'plugin_id 与 version 不能为空');
if (!['test', 'prod'].includes(channel)) throw new ApiError(400, 'channel 仅支持 test / prod');
if (!SAFE_NAME_RE.test(pluginId) || !SAFE_NAME_RE.test(version)) {
throw new ApiError(400, 'plugin_id/version 仅允许字母数字及 . _ -');
}
// 执行机只升不降(plugin-sync 版本比较),测试版本号必须高于当前正式版,否则转正后无法全量生效
const before = await this.pluginRepo.findOneBy({ id: pluginId });
const prodVer = String(before?.latestVersion || '').trim();
if (channel === 'test' && prodVer && !versionGt(version, prodVer)) {
throw new ApiError(400, `测试版本号必须高于当前正式版 ${prodVer}(执行机不会降级,转正后无法生效)`);
}
const content: Buffer = readUploadFile(file);
if (!content || !content.length) throw new ApiError(400, '上传内容为空');
if (content.length > 200 * 1024 * 1024) throw new ApiError(413, '插件包超过大小上限(200MB)');
@@ -151,13 +161,15 @@ export class AdminPluginController extends BaseController {
const sha256 = crypto.createHash('sha256').update(content).digest('hex');
const manifestJson = JSON.stringify(manifest, null, 0) || '{}';
// 插件主记录 upsert(分类只在首次登记时取 plugin.json,之后以后台手动维护为准,不被新版本覆盖)
// 测试通道不写 latest_version:新插件首次以测试版发布时正式版号留空,转正后才有正式版
await this.pluginRepo.manager.query(
`INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest)
VALUES (?, ?, ?, ?, ?, ?, ?)
`INSERT INTO plugins(id, name, latest_version, test_version, description, category, icon, manifest)
VALUES (?, ?, ?, '', ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE name = VALUES(name), manifest = VALUES(manifest)
${manifest.description !== undefined ? ', description = VALUES(description)' : ''}
${manifest.icon !== undefined ? ', icon = VALUES(icon)' : ''}`,
[pluginId, name, version, manifest.description || '', manifest.category || '', manifest.icon || '', manifestJson]
[pluginId, name, channel === 'prod' ? version : prodVer, manifest.description || '',
manifest.category || '', manifest.icon || '', manifestJson]
);
// plugin.json 自带分类不在字典时自动收录进场景分类字典(幂等,重复项跳过)
const cat = String(manifest.category || '').trim();
@@ -174,24 +186,56 @@ export class AdminPluginController extends BaseController {
ON DUPLICATE KEY UPDATE filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)`,
[pluginId, version, filename, sha256, content.length]
);
// 更新 latest_version(若更高)
const cur = await this.pluginRepo.findOneBy({ id: pluginId });
if (cur && versionGt(version, cur.latestVersion)) {
await this.pluginRepo.update({ id: pluginId }, { latestVersion: version });
// prod:直接提升 latest_version;test:写 test_version 并进入 testing 状态(只有管理员可见)
if (channel === 'prod') {
// 直发正式时:更高版本号覆盖在测版本(避免 testing 状态把更低的在测版下发给管理员),并退出 testing
const curTest = String(before?.testVersion || '').trim();
const nextTest = curTest && versionGt(curTest, version) ? curTest : '';
await this.pluginRepo.manager.query(
`UPDATE plugins
SET latest_version = ?, test_version = ?,
status = CASE WHEN status = 'testing' THEN 'published' ELSE status END
WHERE id = ?`,
[versionGt(version, prodVer) ? version : prodVer, nextTest, pluginId]
);
} else {
// 只把"正常态"的插件切到 testing;disabled/revoked 保持原状态(避免发测试版把已停用/下架的插件复活)
await this.pluginRepo.manager.query(
`UPDATE plugins
SET test_version = ?,
status = CASE WHEN status IN ('published', 'testing') THEN 'testing' ELSE status END
WHERE id = ?`,
[version, pluginId]
);
}
// 仅保留最近 3 个版本(DB + 磁盘)
// 版本裁剪:latest_version / test_version 永远保留(否则回滚与在测包会被挤掉),其余保留最近 3 个
const cur = await this.pluginRepo.findOneBy({ id: pluginId });
const protectedVers = new Set<string>(
[String(cur?.latestVersion || '').trim(), String(cur?.testVersion || '').trim()].filter(Boolean)
);
const versions = await this.pluginVersionRepo
.createQueryBuilder('v')
.where('v.pluginId = :id', { id: pluginId })
.orderBy('v.id', 'DESC')
.getMany();
const stale = versions.slice(3);
const stale = versions.filter(v => !protectedVers.has(String(v.version))).slice(3);
for (const s of stale) {
await this.pluginVersionRepo.delete({ id: s.id });
try { fs.unlinkSync(path.join(PKG_DIR, s.filename)); } catch (e) { /* ignore */ }
}
await this.centerAuthService.audit(login, 'plugin-publish', pluginId, `version=${version}, filename=${filename}`);
return { ok: true, plugin_id: pluginId, version, filename };
await this.centerAuthService.audit(
login, 'plugin-publish', pluginId,
`channel=${channel}, version=${version}, filename=${filename}`);
return {
ok: true,
plugin_id: pluginId,
version,
channel,
filename,
status: cur?.status || (channel === 'test' ? 'testing' : 'published'),
latest_version: cur?.latestVersion || '',
test_version: cur?.testVersion || '',
};
}
/** POST /api/admin/plugin/delete */
@@ -227,15 +271,28 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const pid = (pluginId || '').trim();
if (!pid) throw new ApiError(400, 'plugin_id 必填');
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
const testVer = String(pl.testVersion || '').trim();
const set: Record<string, any> = {};
let newStatus = '';
if (d?.name && String(d.name).trim()) set.name = String(d.name).trim();
if (d?.description) set.description = String(d.description).trim();
if (d?.category !== undefined) set.category = String(d.category ?? '').trim();
if (d?.icon) set.icon = String(d.icon).trim();
if (['published', 'disabled', 'revoked'].includes(d?.status)) set.status = d.status;
if (d?.status !== undefined) {
newStatus = String(d.status || '').trim();
if (!['published', 'testing', 'disabled', 'revoked'].includes(newStatus)) {
throw new ApiError(400, `不支持的状态:${newStatus}(published/testing/disabled/revoked)`);
}
if (newStatus === 'testing' && !testVer) {
throw new ApiError(400, `${pid} 当前没有在测版本,请先发布测试版本`);
}
set.status = newStatus;
}
if (d?.force_min_version && d?.force_deadline) {
set.force_min_version = String(d.force_min_version).trim();
set.force_deadline = String(d.force_deadline).trim();
@@ -246,10 +303,23 @@ export class AdminPluginController extends BaseController {
set.force_deadline = null;
}
if (!Object.keys(set).length) return { ok: true };
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
// 转正:testing → published 时把在测版本提升为正式版本(复用同一版本号,保证"测过的就是发出去的")
if (newStatus === 'published' && testVer && String(pl.status || '') === 'testing') {
await this.pluginRepo.manager.query(
'UPDATE plugins SET latest_version = ?, test_version = ? WHERE id = ?',
[testVer, '', pid]
);
await this.centerAuthService.audit(login, 'plugin-promote', pid, `version=${testVer}`);
}
await this.pluginRepo.update({ id: pid }, set);
return { ok: true, plugin_id: pid };
const after = await this.pluginRepo.findOneBy({ id: pid });
return {
ok: true,
plugin_id: pid,
status: after?.status || '',
latest_version: after?.latestVersion || '',
test_version: after?.testVersion || '',
};
}
/** GET /api/admin/grant_data */
@@ -56,20 +56,33 @@ export class ApiPluginsController extends BaseController {
.select([
'p.id AS id',
'p.name AS name',
'p.latestVersion AS version',
'p.latestVersion AS latestVersion',
'p.testVersion AS testVersion',
'p.status AS status',
'p.category AS category',
])
// revoked=下架:不下发,执行机会按白名单清理;disabled=停用:仍下发但版本留空(不拉新、本地保留)
.where('ap.account = :account', { account: acct })
.andWhere("p.status <> 'revoked'")
.orderBy('p.id', 'ASC')
.getRawMany();
// 测试通道:status=testing 且账号是管理员 → 取在测版本;其他账号继续用正式版(业务不中断)
const isAdmin = await this.centerAuthService.accountIsAdmin(acct);
return {
account: acct,
plugins: rows.map(r => ({
id: r.id,
name: r.name,
version: r.version,
category: r.category || '',
})),
plugins: rows.map(r => {
const testVer = String(r.testVersion || '').trim();
const disabled = r.status === 'disabled';
const useTest = !disabled && isAdmin && r.status === 'testing' && !!testVer;
return {
id: r.id,
name: r.name,
version: disabled ? '' : (useTest ? testVer : String(r.latestVersion || '')),
category: r.category || '',
status: r.status,
channel: useTest ? 'test' : 'prod',
};
}),
};
}
@@ -5,8 +5,7 @@ import { Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { randomBytes } from 'node:crypto';
import { AccountPluginEntity } from '../../entity/plugin';
import { PluginVersionEntity } from '../../entity/plugin';
import { AccountPluginEntity, PluginEntity, PluginVersionEntity } from '../../entity/plugin';
import { DownloadTicketEntity } from '../../entity/account';
import { AuditLogEntity } from '../../entity/runtime';
import { CenterAuthService, ApiError } from '../../service/auth';
@@ -32,6 +31,9 @@ export class ApiTicketController extends BaseController {
@InjectEntityModel(PluginVersionEntity)
pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(DownloadTicketEntity)
downloadTicketRepo: Repository<DownloadTicketEntity>;
@@ -47,14 +49,28 @@ export class ApiTicketController extends BaseController {
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
if (!(account || '').trim()) throw new ApiError(400, 'account 不能为空');
const acct = (account || '').trim();
if (!acct) throw new ApiError(400, 'account 不能为空');
const grant = await this.accountPluginRepo.findOneBy({
account: account.trim(),
account: acct,
pluginId,
});
const ver = await this.pluginVersionRepo.findOneBy({ pluginId, version });
if (!ver) throw new ApiError(404, `未找到插件包 ${pluginId}@${version}`);
if (!grant || !Number(grant.canDownload)) throw new ApiError(403, '无该插件的下载授权');
const plugin = await this.pluginRepo.findOneBy({ id: pluginId });
if (!plugin) throw new ApiError(404, `插件 ${pluginId} 不存在`);
if (['disabled', 'revoked'].includes(String(plugin.status))) {
throw new ApiError(403, `插件 ${pluginId} 已停用/下架,禁止下载`);
}
// 版本可见性:正式版对所有已授权账号开放;在测版本仅管理员可拉取(与 /api/plugins 下发口径一致)
const prodVer = String(plugin.latestVersion || '').trim();
const testVer = String(plugin.testVersion || '').trim();
const isTestVisible = plugin.status === 'testing' && !!testVer &&
await this.centerAuthService.accountIsAdmin(acct);
if (version !== prodVer && !(isTestVisible && version === testVer)) {
throw new ApiError(403, `版本 ${version} 当前不可下载(在测版本仅管理员可见)`);
}
const pkgPath = path.join(PKG_DIR, ver.filename);
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${ver.filename}`);
// 票据落库共享(多实例通用);顺手清理过期票据
@@ -14,6 +14,9 @@ export class PluginEntity {
@Column({ name: 'latest_version', type: 'varchar', length: 32, comment: '最新版本号' })
latestVersion: string;
@Column({ name: 'test_version', type: 'varchar', length: 32, default: '', comment: '测试通道在测版本(空=无在测版本)' })
testVersion: string;
@Column({ name: 'description', type: 'varchar', length: 512, default: '', comment: '插件描述' })
description: string;
@@ -51,6 +51,12 @@ export class CenterAuthService {
return !!row && !Number(row.status);
}
/** 平台账号是否管理员(accounts.is_admin;用于测试通道可见性:在测版本仅管理员可下载) */
async accountIsAdmin(acct: string): Promise<boolean> {
const row = await this.accountRepo.findOneBy({ account: (acct || '').trim() });
return !!row && Number(row.isAdmin) === 1;
}
// ==================== 管理员票据(身份源 = base_sys_user) ====================
/** 仅校验登录态(票据有效 + 账号存在且启用),不要求管理员 */
async requireLogin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {