feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user