refactor(license-server): cli重构成tui

This commit is contained in:
小蟑螂
2026-07-06 20:31:05 +08:00
parent 46c1388976
commit dd8cba9777
20 changed files with 499 additions and 649 deletions
+124
View File
@@ -0,0 +1,124 @@
import { confirm, input, select } from '@inquirer/prompts';
import { apiRequest } from '../api/client.js';
import { printEmptyHint, printSuccess, printTable } from '../ui/render.js';
async function pause() {
await input({ message: '按 Enter 返回' });
}
interface Customer {
id: number;
code: string;
name: string;
status: number;
contactName?: string;
contactPhone?: string;
}
interface PageResult<T> {
items: T[];
total: number;
page: number;
size: number;
}
async function customerList() {
const data = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=20');
if (!data.items.length) {
printEmptyHint('创建客户');
return;
}
printTable(
['ID', 'CODE', 'NAME', 'STATUS'],
data.items.map((c) => [
String(c.id),
c.code,
c.name,
c.status === 1 ? '启用' : '禁用',
]),
);
const totalPages = Math.ceil(data.total / data.size) || 1;
console.log(`共 ${data.total} 条 · 第 ${data.page}/${totalPages} 页`);
}
async function customerCreate() {
const name = await input({ message: '公司名称', validate: (v) => !!v || '必填' });
const contactName = await input({ message: '联系人', default: '' });
const contactPhone = await input({ message: '联系电话', default: '' });
const contactEmail = await input({ message: '联系邮箱', default: '' });
let code = await input({ message: '客户编码(留空自动生成)', default: '' });
if (!code) code = undefined as any;
const created = await apiRequest<Customer>('POST', '/customers', {
name,
contactName,
contactPhone,
contactEmail,
code,
});
printSuccess(`客户已创建: ${created.code} · ${created.name}`);
}
async function customerShow() {
const id = await input({ message: '客户 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
const customer = await apiRequest<Customer>('GET', `/customers/${Number(id)}`);
printTable(
['ID', 'CODE', 'NAME', 'STATUS', '联系人', '电话'],
[[
String(customer.id),
customer.code,
customer.name,
customer.status === 1 ? '启用' : '禁用',
customer.contactName || '-',
customer.contactPhone || '-',
]],
);
}
async function customerDelete() {
const id = await input({ message: '客户 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
const ok = await confirm({ message: `确认删除客户 #${id}?`, default: false });
if (!ok) return;
await apiRequest('DELETE', `/customers/${Number(id)}`);
printSuccess(`客户 #${id} 已删除`);
}
export async function customerMenu() {
console.clear();
const action = await select({
message: '客户管理',
choices: [
{ name: '列表', value: 'list' },
{ name: '创建', value: 'create' },
{ name: '查看', value: 'show' },
{ name: '删除', value: 'delete' },
{ name: '返回主菜单', value: 'back' },
],
});
switch (action) {
case 'list':
console.clear();
await customerList();
await pause();
break;
case 'create':
console.clear();
await customerCreate();
await pause();
break;
case 'show':
console.clear();
await customerShow();
await pause();
break;
case 'delete':
console.clear();
await customerDelete();
await pause();
break;
}
}
+249
View File
@@ -0,0 +1,249 @@
import { checkbox, confirm, input, search, select } from '@inquirer/prompts';
import { apiRequest, apiDownload } from '../api/client.js';
import { printBox, printEmptyHint, printSuccess, printTable } from '../ui/render.js';
async function pause() {
await input({ message: '按 Enter 返回' });
}
interface Customer {
id: number;
code: string;
name: string;
}
interface License {
id: number;
jti: string;
edition: string;
machineFingerprint: string;
status: string;
expiresAt: string;
licenseKey?: string;
customer?: Customer;
}
interface PageResult<T> {
items: T[];
total: number;
page: number;
size: number;
}
interface GenerateResult {
id: number;
licenseKey: string;
jti: string;
edition: string;
machineFingerprint: string;
expiresAt: string;
status: string;
}
async function licenseList() {
const data = await apiRequest<PageResult<License>>('GET', '/licenses?page=1&size=20');
if (!data.items.length) {
printEmptyHint('签发许可证');
return;
}
printTable(
['ID', 'JTI', 'EDITION', 'FINGERPRINT', 'STATUS', 'EXPIRES'],
data.items.map((l) => [
String(l.id),
l.jti.slice(0, 8) + '...',
l.edition,
l.machineFingerprint.slice(0, 16) + (l.machineFingerprint.length > 16 ? '...' : ''),
l.status,
l.expiresAt?.slice(0, 10) || '-',
]),
);
console.log(`共 ${data.total} 条`);
}
async function licenseShow() {
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
const license = await apiRequest<License>('GET', `/licenses/${Number(id)}`);
printBox(
`许可证 #${license.id}`,
[
`JTI: ${license.jti}`,
`版本: ${license.edition}`,
`指纹: ${license.machineFingerprint}`,
`状态: ${license.status}`,
`过期: ${license.expiresAt?.slice(0, 10) || '-'}`,
license.licenseKey ? `\n${license.licenseKey}` : '',
].join('\n'),
);
}
async function licenseGenerate() {
const customers = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=100');
if (!customers.items.length) {
console.error('暂无客户,请先创建客户');
return;
}
const customerId = await search({
message: '选择客户',
source: async (term) => {
const q = (term || '').toLowerCase();
return customers.items
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q))
.map((c) => ({ name: `${c.code} · ${c.name}`, value: c.id }));
},
});
const picked = customers.items.find((c) => c.id === customerId)!;
const company = await input({ message: '授权公司名', default: picked.name });
const fpMode = await select({
message: '机器指纹',
choices: [
{ name: '私有部署(输入 FP-xxx)', value: 'custom' },
{ name: 'SaaS 不限指纹 (*)', value: '*' },
],
});
const fingerprint =
fpMode === '*'
? '*'
: await input({
message: '机器指纹',
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
});
const edition = await select({
message: '版本类型',
choices: [
{ name: 'trial · 试用', value: 'trial' },
{ name: 'enterprise · 企业', value: 'enterprise' },
{ name: 'unlimited · 无限', value: 'unlimited' },
],
});
const expireChoice = await select({
message: '有效期',
choices: [
{ name: '+30 天', value: '30d' },
{ name: '+1 年', value: '1y' },
{ name: '自定义日期', value: 'custom' },
],
});
let expiresAt: string;
if (expireChoice === 'custom') {
expiresAt = await input({
message: '过期日期 (YYYY-MM-DD)',
validate: (v) => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式 YYYY-MM-DD',
});
} else {
const d = new Date();
if (expireChoice === '30d') d.setDate(d.getDate() + 30);
else d.setFullYear(d.getFullYear() + 1);
expiresAt = d.toISOString().slice(0, 10);
}
const features = await checkbox({
message: '授权功能',
choices: [
{ name: 'order-import · 订单导入', value: 'order-import', checked: true },
{ name: 'order-create · 创建订单', value: 'order-create', checked: true },
],
});
const summary = [
`客户 ID: ${customerId}`,
`公司: ${company}`,
`指纹: ${fingerprint}`,
`版本: ${edition}`,
`过期: ${expiresAt}`,
`功能: ${features.join(', ')}`,
].join('\n');
const ok = await confirm({ message: `确认签发?\n${summary}`, default: true });
if (!ok) return;
const result = await apiRequest<GenerateResult>('POST', '/licenses/generate', {
customerId,
company,
machineFingerprint: fingerprint,
edition,
expiresAt: new Date(expiresAt).toISOString(),
features,
});
printBox(
'签发成功',
[
`ID: ${result.id}`,
`JTI: ${result.jti}`,
`过期: ${result.expiresAt?.slice(0, 10)}`,
'',
result.licenseKey,
].join('\n'),
'green',
);
}
async function licenseRevoke() {
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
const license = await apiRequest<License>('GET', `/licenses/${Number(id)}`);
const ok = await confirm({
message: `确认吊销?\nJTI: ${license.jti}\n指纹: ${license.machineFingerprint}`,
default: false,
});
if (!ok) return;
await apiRequest('POST', `/licenses/${id}/revoke`);
printSuccess(`许可证 #${id} 已吊销`);
}
async function licenseDownload() {
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
const outfile = `license-${id}.key`;
const path = await apiDownload(`/licenses/${id}/download`, outfile);
printSuccess(`已保存到 ${path}`);
}
export async function licenseMenu() {
console.clear();
const action = await select({
message: '许可证管理',
choices: [
{ name: '列表', value: 'list' },
{ name: '查看', value: 'show' },
{ name: '签发', value: 'generate' },
{ name: '吊销', value: 'revoke' },
{ name: '下载', value: 'download' },
{ name: '返回主菜单', value: 'back' },
],
});
switch (action) {
case 'list':
console.clear();
await licenseList();
await pause();
break;
case 'show':
console.clear();
await licenseShow();
await pause();
break;
case 'generate':
console.clear();
await licenseGenerate();
await pause();
break;
case 'revoke':
console.clear();
await licenseRevoke();
await pause();
break;
case 'download':
console.clear();
await licenseDownload();
await pause();
break;
}
}
+52
View File
@@ -0,0 +1,52 @@
import { input, password } from '@inquirer/prompts';
import { apiRequest } from '../api/client.js';
import { loadConfig, resolveApiUrl, saveConfig } from '../config.js';
import { printError, printSuccess } from '../ui/render.js';
interface LoginResult {
token: string;
username: string;
expiresAt: string | null;
}
export async function loginCommand(opts: { url?: string; username?: string; password?: string }) {
const config = await loadConfig();
const apiUrl = resolveApiUrl(opts.url, config);
let username = opts.username || process.env.ECOM_LICENSE_USERNAME;
let pass = opts.password || process.env.ECOM_LICENSE_PASSWORD;
if (!username) {
username = await input({ message: '用户名', default: username || 'admin' });
}
if (!pass) {
pass = await password({ message: '密码', mask: '*' });
}
if (!username || !pass) {
printError('请提供用户名和密码');
return;
}
try {
const result = await apiRequest<LoginResult>(
'POST',
'/auth/login',
{ username, password: pass },
false,
);
await saveConfig({
apiUrl,
token: result.token,
username: result.username,
expiresAt: result.expiresAt || undefined,
});
printSuccess(
`登录成功 · ${result.username}` +
(result.expiresAt ? ` · Token 有效期至 ${result.expiresAt.slice(0, 10)}` : ''),
);
} catch (e: any) {
printError(e?.message || '登录失败');
}
}
+7
View File
@@ -0,0 +1,7 @@
import { clearConfig } from '../config.js';
import { printSuccess } from '../ui/render.js';
export async function logoutCommand() {
await clearConfig();
printSuccess('已退出登录');
}
+24
View File
@@ -0,0 +1,24 @@
import { apiRequest } from '../api/client.js';
import { printBox } from '../ui/render.js';
interface Stats {
customerCount: number;
activeLicenseCount: number;
expiringSoonCount: number;
totalLicenses: number;
}
export async function statsCommand() {
const stats = await apiRequest<Stats>('GET', '/dashboard/stats');
printBox(
'平台概览',
[
`客户数: ${stats.customerCount}`,
`有效许可证: ${stats.activeLicenseCount}`,
`即将过期: ${stats.expiringSoonCount}`,
`许可证总数: ${stats.totalLicenses}`,
].join('\n'),
'green',
);
}
+21
View File
@@ -0,0 +1,21 @@
import { loadConfig, resolveApiUrl } from '../config.js';
import { printBox, printError } from '../ui/render.js';
export async function whoamiCommand() {
const config = await loadConfig();
const apiUrl = resolveApiUrl(undefined, config);
if (!config?.token) {
printError('未登录,请先登录');
return;
}
printBox(
'当前会话',
[
`API: ${apiUrl}`,
`用户: ${config?.username || '(未知)'}`,
`过期: ${config?.expiresAt || '-'}`,
].join('\n'),
);
}