mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 19:49:19 +08:00
refacor: 重构目录架构
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { loadConfig, resolveApiUrl, resolveToken } from '../config.js';
|
||||
import { runSpinner } from '../ui/render.js';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseError(res: Response): Promise<string> {
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (typeof body?.message === 'string') return body.message;
|
||||
if (Array.isArray(body?.message)) return body.message.join(', ');
|
||||
return JSON.stringify(body);
|
||||
} catch {
|
||||
return res.statusText || `HTTP ${res.status}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
auth = true,
|
||||
): Promise<T> {
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
};
|
||||
if (auth && token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const doFetch = async () => {
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new ApiError(await parseError(res), res.status);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
const contentType = res.headers.get('content-type') || '';
|
||||
if (contentType.includes('application/json')) {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
return (await res.text()) as T;
|
||||
};
|
||||
|
||||
return runSpinner(doFetch, '请求中...');
|
||||
}
|
||||
|
||||
export async function apiDownload(path: string, outfile: string): Promise<string> {
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const doFetch = async () => {
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await parseError(res), res.status);
|
||||
const { writeFile } = await import('fs/promises');
|
||||
const text = await res.text();
|
||||
await writeFile(outfile, text, 'utf8');
|
||||
return outfile;
|
||||
};
|
||||
|
||||
return runSpinner(doFetch, '正在下载...');
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
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;
|
||||
maxCompanies: number | null;
|
||||
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 defaultMaxCompanies = fingerprint === '*' ? 100 : 2;
|
||||
const maxCompaniesInput = await input({
|
||||
message: `最大公司数量(默认 ${defaultMaxCompanies})`,
|
||||
default: String(defaultMaxCompanies),
|
||||
validate: (v) => /^\d+$/.test(v) || '请输入正整数',
|
||||
});
|
||||
const maxCompanies = Number(maxCompaniesInput);
|
||||
|
||||
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}`,
|
||||
`最大公司数: ${maxCompanies}`,
|
||||
`版本: ${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,
|
||||
maxCompanies,
|
||||
});
|
||||
|
||||
printBox(
|
||||
'签发成功',
|
||||
[
|
||||
`ID: ${result.id}`,
|
||||
`JTI: ${result.jti}`,
|
||||
`最大公司数: ${result.maxCompanies ?? (fingerprint === '*' ? 100 : 2)}`,
|
||||
`过期: ${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;
|
||||
}
|
||||
}
|
||||
@@ -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 || '登录失败');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { clearConfig } from '../config.js';
|
||||
import { printSuccess } from '../ui/render.js';
|
||||
|
||||
export async function logoutCommand() {
|
||||
await clearConfig();
|
||||
printSuccess('已退出登录');
|
||||
}
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
@@ -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'),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { mkdir, readFile, writeFile } from 'fs/promises';
|
||||
import { homedir } from 'os';
|
||||
import { dirname, join } from 'path';
|
||||
|
||||
export interface CliConfig {
|
||||
apiUrl: string;
|
||||
token?: string;
|
||||
username?: string;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG_PATH = join(
|
||||
homedir(),
|
||||
'.config',
|
||||
'ecom-license',
|
||||
'config.json',
|
||||
);
|
||||
|
||||
export function getConfigPath(): string {
|
||||
return process.env.ECOM_LICENSE_CONFIG || DEFAULT_CONFIG_PATH;
|
||||
}
|
||||
|
||||
export async function loadConfig(): Promise<CliConfig | null> {
|
||||
try {
|
||||
const raw = await readFile(getConfigPath(), 'utf8');
|
||||
return JSON.parse(raw) as CliConfig;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveConfig(config: CliConfig): Promise<void> {
|
||||
const path = getConfigPath();
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
export async function clearConfig(): Promise<void> {
|
||||
await saveConfig({ apiUrl: (await loadConfig())?.apiUrl || 'http://localhost:3100' });
|
||||
}
|
||||
|
||||
export function resolveApiUrl(flagUrl?: string, config?: CliConfig | null): string {
|
||||
return (
|
||||
flagUrl ||
|
||||
process.env.ECOM_LICENSE_API_URL ||
|
||||
config?.apiUrl ||
|
||||
'http://localhost:3100'
|
||||
).replace(/\/$/, '');
|
||||
}
|
||||
|
||||
export function resolveToken(flagToken?: string, config?: CliConfig | null): string | undefined {
|
||||
return flagToken || process.env.ECOM_LICENSE_TOKEN || config?.token;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function isInteractive(): boolean {
|
||||
return Boolean(process.stdout.isTTY) && !process.env.CI;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env node
|
||||
import { input, select } from '@inquirer/prompts';
|
||||
|
||||
import { customerMenu } from './commands/customer.js';
|
||||
import { licenseMenu } from './commands/license.js';
|
||||
import { loginCommand } from './commands/login.js';
|
||||
import { logoutCommand } from './commands/logout.js';
|
||||
import { statsCommand } from './commands/stats.js';
|
||||
import { whoamiCommand } from './commands/whoami.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { printBanner } from './ui/render.js';
|
||||
|
||||
async function mainMenu() {
|
||||
console.clear();
|
||||
printBanner();
|
||||
const config = await loadConfig();
|
||||
const isLoggedIn = Boolean(config?.token);
|
||||
|
||||
const choices: { name: string; value: string }[] = [];
|
||||
|
||||
if (!isLoggedIn) {
|
||||
choices.push({ name: '登录', value: 'login' });
|
||||
} else {
|
||||
choices.push(
|
||||
{ name: '当前会话', value: 'whoami' },
|
||||
{ name: '客户管理', value: 'customer' },
|
||||
{ name: '许可证管理', value: 'license' },
|
||||
{ name: '平台统计', value: 'stats' },
|
||||
{ name: '退出登录', value: 'logout' },
|
||||
);
|
||||
}
|
||||
choices.push({ name: '退出', value: 'exit' });
|
||||
|
||||
const action = await select({
|
||||
message: '主菜单',
|
||||
choices,
|
||||
pageSize: 10,
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'login':
|
||||
console.clear();
|
||||
await loginCommand({});
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'whoami':
|
||||
console.clear();
|
||||
await whoamiCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'customer':
|
||||
await customerMenu();
|
||||
break;
|
||||
case 'license':
|
||||
await licenseMenu();
|
||||
break;
|
||||
case 'stats':
|
||||
console.clear();
|
||||
await statsCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'logout':
|
||||
console.clear();
|
||||
await logoutCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'exit':
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
while (true) {
|
||||
try {
|
||||
await mainMenu();
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'ExitPromptError') process.exit(0);
|
||||
console.error(e?.message || e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,72 @@
|
||||
import boxen from 'boxen';
|
||||
import chalk from 'chalk';
|
||||
import Table from 'cli-table3';
|
||||
import gradient from 'gradient-string';
|
||||
import ora, { type Ora } from 'ora';
|
||||
|
||||
export function printBanner() {
|
||||
const title = gradient.pastel('Ecom License TUI');
|
||||
console.log(
|
||||
boxen(`${title}\n${chalk.gray('授权管理平台 · 运营端')}`, {
|
||||
padding: 1,
|
||||
borderColor: 'cyan',
|
||||
borderStyle: 'round',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function printSuccess(msg: string) {
|
||||
console.log(chalk.green('✔'), msg);
|
||||
}
|
||||
|
||||
export function printError(msg: string) {
|
||||
console.error(chalk.red('✖'), msg);
|
||||
}
|
||||
|
||||
export function printInfo(msg: string) {
|
||||
console.log(chalk.blue('ℹ'), msg);
|
||||
}
|
||||
|
||||
export function printBox(title: string, content: string, borderColor: 'green' | 'cyan' | 'yellow' = 'cyan') {
|
||||
console.log(
|
||||
boxen(content, {
|
||||
title: chalk.bold(title),
|
||||
padding: 1,
|
||||
borderColor,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function printTable(headers: string[], rows: string[][]) {
|
||||
const table = new Table({ head: headers.map((h) => chalk.cyan(h)) });
|
||||
rows.forEach((r) => table.push(r));
|
||||
console.log(table.toString());
|
||||
}
|
||||
|
||||
export function printEmptyHint(hint: string) {
|
||||
console.log(chalk.yellow('暂无数据。'), chalk.gray(hint));
|
||||
}
|
||||
|
||||
let activeSpinner: Ora | null = null;
|
||||
|
||||
export async function runSpinner<T>(fn: () => Promise<T>, text: string): Promise<T> {
|
||||
const spinner = ora(text).start();
|
||||
activeSpinner = spinner;
|
||||
try {
|
||||
const result = await fn();
|
||||
spinner.succeed();
|
||||
return result;
|
||||
} catch (e) {
|
||||
spinner.fail();
|
||||
throw e;
|
||||
} finally {
|
||||
activeSpinner = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function failSpinner(msg: string) {
|
||||
if (activeSpinner) {
|
||||
activeSpinner.fail(msg);
|
||||
activeSpinner = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user