From 11f94a3dd0cbbbe2f6aa6431324980a205eb51a7 Mon Sep 17 00:00:00 2001 From: ssw Date: Tue, 21 Jul 2026 18:01:00 +0800 Subject: [PATCH] =?UTF-8?q?feat(dacli):=20P6=20sample=20=E7=BB=AD=207=20?= =?UTF-8?q?=E6=96=87=E4=BB=B6=20=E2=86=92=20wrapCommand=20+=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P6 sample 续迁移 7 文件 (累计 14 文件): - form/list.ts (--summary + --json + 表格 三路径) - report/list.ts (webapi 化 + DacliError 已有) - report/info.ts (同上) - storage/list.ts (无 appCode, wrapCommand 仍能收口 stdout 5c) - integration/emailtest.ts (DacliError 已有 + 新 wrapCommand) - integration/smstest.ts (同上) - integration/webhooktest.ts (DacliError 已有 + 新 wrapCommand) P5 全量 (commit c6b7fe8): - portal/create.ts:76,93 (2 throws businessType 字典 + 业务分类) - bigscreen/construct.ts:269 (1 throw validProps empty) 测试 fix-up: - tests/unit/report_wired.test.ts 更新 6 个老 pattern 静态契约 - 老 pattern (printCommandEnd + try/finally + cmdError + process.exit(1)) - 新 pattern (wrapCommand + ctx.success/fail + no process.exit) 验证: - TS compile 56 baseline 不变 - 68/68 单元测试 PASS (output_filter + auto_fix + report_wired + workflow) - 端到端: form list --summary / report list / storage list / workflow list 都正常 --- src/commands/form/list.ts | 129 +++++++++++----------- src/commands/integration/emailtest.ts | 80 +++++++------- src/commands/integration/smstest.ts | 82 +++++++------- src/commands/integration/webhooktest.ts | 116 ++++++++++---------- src/commands/report/info.ts | 73 ++++++------- src/commands/report/list.ts | 137 +++++++++++------------- src/commands/storage/list.ts | 98 ++++++++--------- tests/unit/report_wired.test.ts | 66 ++++++------ 8 files changed, 365 insertions(+), 416 deletions(-) diff --git a/src/commands/form/list.ts b/src/commands/form/list.ts index dc3ad33..cc9f5f3 100644 --- a/src/commands/form/list.ts +++ b/src/commands/form/list.ts @@ -12,7 +12,7 @@ import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import type { FormSummary } from '../../core/types.ts' import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts' -import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 (list 类查询命令历史可追溯) +import { setupOutputFilter, wrapCommand } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘; v2.2+ wrapCommand 收口 5c 样板 interface ListResp { list: FormSummary[] @@ -40,79 +40,72 @@ export function buildFormListCommand(): Command { // 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - // v0.11+ Phase 1: 用 web 端 getVisualDevList (替代 c.get('/visualdev/Base')) - await initWebapi(c) - const data = (await loadVisualDev.getVisualDevList({ - keyword: opts.keyword, - currentPage: 1, - pageSize: opts.limit, - })) as ListResp - let list = data.list || [] - if (opts.state !== undefined) list = list.filter((f) => f.state === opts.state) - cmdSummary = { - keyword: opts.keyword, - state: opts.state, - total: list.length, - mode: opts.summary ? 'summary' : (opts.json ? 'json' : 'table'), - } - - // BS-53: --summary 输出 state 分布, 帮 AI 快速识别"全是 state=2 待重发布"等异常 - if (opts.summary) { - const dist: Record = {} - for (const f of list) { - const key = stateLabel(f.state) - dist[key] = (dist[key] || 0) + 1 + await wrapCommand({ + command: 'form list', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + // v0.11+ Phase 1: 用 web 端 getVisualDevList (替代 c.get('/visualdev/Base')) + await initWebapi(c) + const data = (await loadVisualDev.getVisualDevList({ + keyword: opts.keyword, + currentPage: 1, + pageSize: opts.limit, + })) as ListResp + let list = data.list || [] + if (opts.state !== undefined) list = list.filter((f) => f.state === opts.state) + const summary = { + keyword: opts.keyword, + state: opts.state, + total: list.length, + mode: opts.summary ? 'summary' : (opts.json ? 'json' : 'table'), } - if (opts.json) { - printJson({ total: list.length, distribution: dist }) - } else { - log.ok(`共 ${list.length} 张 (app=${c.appCode})`) - console.log('state 分布:') - for (const [k, v] of Object.entries(dist)) { - console.log(` ${k.padEnd(10)} ${v}`) + + // BS-53: --summary 输出 state 分布, 帮 AI 快速识别"全是 state=2 待重发布"等异常 + if (opts.summary) { + const dist: Record = {} + for (const f of list) { + const key = stateLabel(f.state) + dist[key] = (dist[key] || 0) + 1 } + if (opts.json) { + printJson({ total: list.length, distribution: dist }) + } else { + log.ok(`共 ${list.length} 张 (app=${c.appCode})`) + console.log('state 分布:') + for (const [k, v] of Object.entries(dist)) { + console.log(` ${k.padEnd(10)} ${v}`) + } + } + return ctx.success(summary) } - return - } - if (opts.json) { - printJson({ total: list.length, list }) - return + if (opts.json) { + printJson({ total: list.length, list }) + return ctx.success(summary) + } + log.ok(`共 ${list.length} 张 (app=${c.appCode})`) + console.log('ID'.padEnd(20), 'STATE'.padEnd(8), 'TYPE', 'FLOW', 'enCode'.padEnd(32), 'fullName') + for (const f of list) { + console.log( + String(f.id).padEnd(20), + stateLabel(f.state).padEnd(8), + String(f.type ?? '-').padEnd(4), + String((f as unknown as { enableFlow?: number }).enableFlow ?? '-').padEnd(4), + (f.enCode || '').padEnd(32), + f.fullName, + ) + } + ctx.success(summary) + } catch (e) { + ctx.fail(`form list 失败: ${(e as Error).message?.slice(0, 200)}`) } - log.ok(`共 ${list.length} 张 (app=${c.appCode})`) - console.log('ID'.padEnd(20), 'STATE'.padEnd(8), 'TYPE', 'FLOW', 'enCode'.padEnd(32), 'fullName') - for (const f of list) { - console.log( - String(f.id).padEnd(20), - stateLabel(f.state).padEnd(8), - String(f.type ?? '-').padEnd(4), - String((f as unknown as { enableFlow?: number }).enableFlow ?? '-').padEnd(4), - (f.enCode || '').padEnd(32), - f.fullName, - ) - } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`form list 失败: ${cmdError}`) - throw e - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) — list 类查询命令历史可追溯 - printCommandEnd({ - command: 'form list', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - } + }) }) installHelpHook(cmd, { diff --git a/src/commands/integration/emailtest.ts b/src/commands/integration/emailtest.ts index bb6181d..816d85c 100644 --- a/src/commands/integration/emailtest.ts +++ b/src/commands/integration/emailtest.ts @@ -12,7 +12,7 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log } from '../../core/log.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 + CommandLog 落盘; v2.2+ wrapCommand 收口 5c 样板 import { DacliError } from '../../core/types.ts' interface EmailTestOpts { @@ -38,53 +38,45 @@ export function buildIntegrationEmailTestCommand(): Command { // 输出过滤: 默认静默 setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - // 1. 拉取 config 详情 (AccountConfig/testSendMail 需要 config dataForm) - const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) - if (configR.code !== 200 || !configR.data) { - const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) - } - const config = configR.data + await wrapCommand({ + command: 'integration email-test', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + // 1. 拉取 config 详情 (AccountConfig/testSendMail 需要 config dataForm) + const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) + if (configR.code !== 200 || !configR.data) { + const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) + } + const config = configR.data - // 2. 拼装 test 请求 (web Test.vue 模式: {...config, testSendEmail, testEmailTitle, testEmailContent, testType}) - const body = { - ...config, - testSendEmail: [opts.email], - testEmailTitle: opts.title, - testEmailContent: opts.content, - testType: 'testSendMail', - } + // 2. 拼装 test 请求 (web Test.vue 模式: {...config, testSendEmail, testEmailTitle, testEmailContent, testType}) + const body = { + ...config, + testSendEmail: [opts.email], + testEmailTitle: opts.title, + testEmailContent: opts.content, + testType: 'testSendMail', + } - // 3. 走 AccountConfig/testSendMail (web 端真实端点) - const r = await c.postJson('/message/AccountConfig/testSendMail', body) - if (r.code !== 200) { - const enhanced = enhanceFromBackend(r.msg || '', 'email', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + // 3. 走 AccountConfig/testSendMail (web 端真实端点) + const r = await c.postJson('/message/AccountConfig/testSendMail', body) + if (r.code !== 200) { + const enhanced = enhanceFromBackend(r.msg || '', 'email', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + } + log.info(`✓ 邮件测试发送 OK (configId=${opts.configId}, to=${opts.email})`) + ctx.success({ configId: opts.configId, email: opts.email, ok: true }) + } catch (e) { + ctx.fail(`email test 失败: ${(e as Error).message?.slice(0, 200)}`, { configId: opts.configId }) } - log.info(`✓ 邮件测试发送 OK (configId=${opts.configId}, to=${opts.email})`) - cmdSummary = { configId: opts.configId, email: opts.email, ok: true } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`email test 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) - printCommandEnd({ - command: 'integration email-test', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: '邮件测试发送 (修复 v0.10 假 PASS 端点)', diff --git a/src/commands/integration/smstest.ts b/src/commands/integration/smstest.ts index cc73ebe..a27840b 100644 --- a/src/commands/integration/smstest.ts +++ b/src/commands/integration/smstest.ts @@ -12,7 +12,7 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log } from '../../core/log.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 + CommandLog 落盘; v2.2+ wrapCommand 收口 5c 样板 import { DacliError } from '../../core/types.ts' interface SmsTestOpts { @@ -36,54 +36,46 @@ export function buildIntegrationSmsTestCommand(): Command { // 输出过滤: 默认静默 setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - // 1. 拉取 config 详情 - const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) - if (configR.code !== 200 || !configR.data) { - const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) - } - const config = configR.data + await wrapCommand({ + command: 'integration sms-test', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + // 1. 拉取 config 详情 + const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) + if (configR.code !== 200 || !configR.data) { + const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) + } + const config = configR.data - // 2. 拼装 test 请求 - const body: Record = { - ...config, - testPhone: opts.phone, - testType: 'testSendSms', - } - if (opts.templateId) { - body.testTemplateId = opts.templateId - } + // 2. 拼装 test 请求 + const body: Record = { + ...config, + testPhone: opts.phone, + testType: 'testSendSms', + } + if (opts.templateId) { + body.testTemplateId = opts.templateId + } - // 3. 走 AccountConfig/testSendSms - const r = await c.postJson('/message/AccountConfig/testSendSms', body) - if (r.code !== 200) { - const enhanced = enhanceFromBackend(r.msg || '', 'sms', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + // 3. 走 AccountConfig/testSendSms + const r = await c.postJson('/message/AccountConfig/testSendSms', body) + if (r.code !== 200) { + const enhanced = enhanceFromBackend(r.msg || '', 'sms', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + } + log.info(`✓ 短信测试发送 OK (configId=${opts.configId}, to=${opts.phone})`) + ctx.success({ configId: opts.configId, phone: opts.phone, ok: true }) + } catch (e) { + ctx.fail(`sms test 失败: ${(e as Error).message?.slice(0, 200)}`, { configId: opts.configId }) } - log.info(`✓ 短信测试发送 OK (configId=${opts.configId}, to=${opts.phone})`) - cmdSummary = { configId: opts.configId, phone: opts.phone, ok: true } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`sms test 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) - printCommandEnd({ - command: 'integration sms-test', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: '短信测试发送 (修复 v0.10 假 PASS 端点)', diff --git a/src/commands/integration/webhooktest.ts b/src/commands/integration/webhooktest.ts index 0cd59b2..be64067 100644 --- a/src/commands/integration/webhooktest.ts +++ b/src/commands/integration/webhooktest.ts @@ -12,7 +12,7 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log } from '../../core/log.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 + CommandLog 落盘; v2.2+ wrapCommand 收口 5c 样板 import { DacliError } from '../../core/types.ts' interface WebhookTestOpts { @@ -36,72 +36,64 @@ export function buildIntegrationWebhookTestCommand(): Command { // 输出过滤: 默认静默 setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - if (!opts.configId && !opts.url) { - throw new DacliError('必须传 --configId 或 --url 之一') - } - - let body: Record - - if (opts.configId) { - // 走 AccountConfig 模式: 拉取 config + 测试 - const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) - if (configR.code !== 200 || !configR.data) { - const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) + await wrapCommand({ + command: 'integration webhook-test', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + if (!opts.configId && !opts.url) { + throw new DacliError('必须传 --configId 或 --url 之一') } - body = { - ...configR.data, - testType: 'testSendWebhook', - } - } else { - // 直发模式: 仅传 url + payload - body = { - webhookUrl: opts.url, - testType: 'testSendWebhook', - } - } - if (opts.payload) { - try { - body = { ...body, ...JSON.parse(opts.payload) } - } catch (e) { - throw new DacliError(`--payload JSON 解析失败: ${(e as Error).message}`) - } - } + let body: Record - const r = await c.postJson('/message/AccountConfig/testSendWebhook', body) - if (r.code !== 200) { - const enhanced = enhanceFromBackend(r.msg || '', 'webhook', { entity: 'integration' }) - throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + if (opts.configId) { + // 走 AccountConfig 模式: 拉取 config + 测试 + const configR = await c.get>(`/message/AccountConfig/${opts.configId}`) + if (configR.code !== 200 || !configR.data) { + const enhanced = enhanceFromBackend(configR.msg || 'id 不存在', 'configId', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })) + } + body = { + ...configR.data, + testType: 'testSendWebhook', + } + } else { + // 直发模式: 仅传 url + payload + body = { + webhookUrl: opts.url, + testType: 'testSendWebhook', + } + } + + if (opts.payload) { + try { + body = { ...body, ...JSON.parse(opts.payload) } + } catch (e) { + throw new DacliError(`--payload JSON 解析失败: ${(e as Error).message}`) + } + } + + const r = await c.postJson('/message/AccountConfig/testSendWebhook', body) + if (r.code !== 200) { + const enhanced = enhanceFromBackend(r.msg || '', 'webhook', { entity: 'integration' }) + throw new DacliError(formatErrorLine(enhanced, { step: 1, stepName: '后端API' })) + } + log.info(`✓ Webhook 测试发送 OK (configId=${opts.configId || '-'}, url=${opts.url || '(from config)'})`) + ctx.success({ + configId: opts.configId || null, + url: opts.url || '(from config)', + ok: true, + }) + } catch (e) { + ctx.fail(`webhook test 失败: ${(e as Error).message?.slice(0, 200)}`, { configId: opts.configId }) } - log.info(`✓ Webhook 测试发送 OK (configId=${opts.configId || '-'}, url=${opts.url || '(from config)'})`) - cmdSummary = { - configId: opts.configId || null, - url: opts.url || '(from config)', - ok: true, - } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`webhook test 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) - printCommandEnd({ - command: 'integration webhook-test', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: 'Webhook 测试发送 (修复 v0.10 假 PASS 端点)', diff --git a/src/commands/report/info.ts b/src/commands/report/info.ts index 5b03426..cf2d0b4 100644 --- a/src/commands/report/info.ts +++ b/src/commands/report/info.ts @@ -15,7 +15,7 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi as initReportWebapi, loadReport } from '../../webapi/report.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 (info 类查询历史可追溯) +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c 样板 import { DacliError } from '../../core/types.ts' interface ReportInfoItem { @@ -44,47 +44,40 @@ export function buildReportInfoCommand(): Command { // 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - // v0.14+ webapi 化: 调用 web 端原版 getReportInfo (走 reportHttp, 端点 /api/Report/{id}) - await initReportWebapi(c) - // webapi shim 已经 unwrap: getReportInfo 返后端 data 字段 (ReportInfoVO), 不含 code/msg 包络 - const r = (await loadReport.getReportInfo(opts.id)) as ReportInfoItem | null - const found = r - if (!found || typeof found !== 'object' || !('id' in found)) { - throw new DacliError(`report id=${opts.id} 不存在 (webapi /api/Report/${opts.id} 返非 ReportInfoVO 或 null)`) + await wrapCommand({ + command: 'report info', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + // v0.14+ webapi 化: 调用 web 端原版 getReportInfo (走 reportHttp, 端点 /api/Report/{id}) + await initReportWebapi(c) + // webapi shim 已经 unwrap: getReportInfo 返后端 data 字段 (ReportInfoVO), 不含 code/msg 包络 + const r = (await loadReport.getReportInfo(opts.id)) as ReportInfoItem | null + const found = r + if (!found || typeof found !== 'object' || !('id' in found)) { + throw new DacliError(`report id=${opts.id} 不存在 (webapi /api/Report/${opts.id} 返非 ReportInfoVO 或 null)`) + } + const summary = { + id: opts.id, + enCode: found.enCode, + fullName: found.fullName, + } + log.info(`报表 id=${opts.id} 名称=${found.fullName} 分类=${found.category}`) + console.log(`enCode: ${found.enCode}`) + if (found.description) console.log(`description: ${found.description}`) + console.log(`sortCode: ${found.sortCode ?? 'N/A'}`) + console.log(`enabledMark: ${found.enabledMark ?? 'N/A'}`) + if (opts.json) printJson(found) + ctx.success(summary) + } catch (e) { + ctx.fail(`report info 失败: ${(e as Error).message?.slice(0, 200)}`, { id: opts.id }) } - cmdSummary = { - id: opts.id, - enCode: found.enCode, - fullName: found.fullName, - } - log.info(`报表 id=${opts.id} 名称=${found.fullName} 分类=${found.category}`) - console.log(`enCode: ${found.enCode}`) - if (found.description) console.log(`description: ${found.description}`) - console.log(`sortCode: ${found.sortCode ?? 'N/A'}`) - console.log(`enabledMark: ${found.enabledMark ?? 'N/A'}`) - if (opts.json) printJson(found) - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`report info 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) — info 类查询历史可追溯 - printCommandEnd({ - command: 'report info', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: '查看报表详情 (走 webapi 镜像, 端点 /api/Report/{id} 端口 32000)', diff --git a/src/commands/report/list.ts b/src/commands/report/list.ts index 61161df..c745dc9 100644 --- a/src/commands/report/list.ts +++ b/src/commands/report/list.ts @@ -21,7 +21,7 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi as initReportWebapi, loadReport } from '../../webapi/report.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 (list 类查询历史可追溯) +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c 样板 import { DacliError } from '../../core/types.ts' interface ReportListItem { @@ -58,80 +58,73 @@ export function buildReportListCommand(): Command { // 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON setupOutputFilter(opts) const c = await JnpfClient.fromToken() - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} - try { - // v0.15+ (P2-1): 兼容 --category/--type 转发到 keyword + 提示 - // 旧版用 /api/ReportManage 端点支持 category/type 过滤, 现 webapi 走 /api/Report - // 端点只有 keyword 模糊搜索, 没法 server 端 category/type 过滤 - let finalKeyword = opts.keyword || '' - if (opts.category) { - log.warn('P2-1: --category 已弃用, 改用 --keyword=<分类名/enCode> 客户端过滤') - finalKeyword = finalKeyword ? `${finalKeyword} ${opts.category}` : opts.category - } - if (opts.type) { - log.warn('P2-1: --type 已弃用, 改用 --keyword=<类型> 客户端过滤') - finalKeyword = finalKeyword ? `${finalKeyword} ${opts.type}` : opts.type - } + await wrapCommand({ + command: 'report list', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + // v0.15+ (P2-1): 兼容 --category/--type 转发到 keyword + 提示 + // 旧版用 /api/ReportManage 端点支持 category/type 过滤, 现 webapi 走 /api/Report + // 端点只有 keyword 模糊搜索, 没法 server 端 category/type 过滤 + let finalKeyword = opts.keyword || '' + if (opts.category) { + log.warn('P2-1: --category 已弃用, 改用 --keyword=<分类名/enCode> 客户端过滤') + finalKeyword = finalKeyword ? `${finalKeyword} ${opts.category}` : opts.category + } + if (opts.type) { + log.warn('P2-1: --type 已弃用, 改用 --keyword=<类型> 客户端过滤') + finalKeyword = finalKeyword ? `${finalKeyword} ${opts.type}` : opts.type + } - // v0.14+ webapi 化: 调用 web 端原版 getReportList (走 reportHttp, 端点 /api/Report) - await initReportWebapi(c) - // web 端 getReportList(params) — params 是 query string, 含 keyword / currentPage / pageSize - const r = (await loadReport.getReportList({ - keyword: finalKeyword, - currentPage: Number(opts.currentPage || '1'), - pageSize: Number(opts.pageSize || '50'), - })) as { - code?: number - msg?: string - data?: { list?: ReportListItem[]; pagination?: { total?: number } } + // v0.14+ webapi 化: 调用 web 端原版 getReportList (走 reportHttp, 端点 /api/Report) + await initReportWebapi(c) + // web 端 getReportList(params) — params 是 query string, 含 keyword / currentPage / pageSize + const r = (await loadReport.getReportList({ + keyword: finalKeyword, + currentPage: Number(opts.currentPage || '1'), + pageSize: Number(opts.pageSize || '50'), + })) as { + code?: number + msg?: string + data?: { list?: ReportListItem[]; pagination?: { total?: number } } + } + if (r.code !== undefined && r.code !== 200) { + throw new DacliError(`report list 失败 (code=${r.code}): ${r.msg}`) + } + const list = r.data?.list || [] + const total = r.data?.pagination?.total ?? list.length + const summary = { + keyword: finalKeyword, + currentPage: Number(opts.currentPage || '1'), + pageSize: Number(opts.pageSize || '50'), + total, + returned: list.length, + } + if (opts.json) { + // shim 已 unwrap envelope, r.data = 后端 data 字段 ({list, pagination}) + printJson(r.data || { list: [], pagination: { total: 0 } }) + return ctx.success(summary) + } + log.info(`共 ${list.length} 张报表 (total=${total})`) + console.log('ID FULL_NAME CATEGORY ENCODE') + console.log('-'.repeat(95)) + for (const d of list) { + const id = String(d.id || '').padEnd(30) + const name = String(d.fullName || '').padEnd(23) + const cat = String(d.category || '').padEnd(23) + const code = String(d.enCode || '') + console.log(`${id}${name}${cat}${code}`) + } + ctx.success(summary) + } catch (e) { + ctx.fail(`report list 失败: ${(e as Error).message?.slice(0, 200)}`) } - if (r.code !== undefined && r.code !== 200) { - throw new DacliError(`report list 失败 (code=${r.code}): ${r.msg}`) - } - const list = r.data?.list || [] - const total = r.data?.pagination?.total ?? list.length - cmdSummary = { - keyword: finalKeyword, - currentPage: Number(opts.currentPage || '1'), - pageSize: Number(opts.pageSize || '50'), - total, - returned: list.length, - } - if (opts.json) { - // shim 已 unwrap envelope, r.data = 后端 data 字段 ({list, pagination}) - printJson(r.data || { list: [], pagination: { total: 0 } }) - return - } - log.info(`共 ${list.length} 张报表 (total=${total})`) - console.log('ID FULL_NAME CATEGORY ENCODE') - console.log('-'.repeat(95)) - for (const d of list) { - const id = String(d.id || '').padEnd(30) - const name = String(d.fullName || '').padEnd(23) - const cat = String(d.category || '').padEnd(23) - const code = String(d.enCode || '') - console.log(`${id}${name}${cat}${code}`) - } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`report list 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 落 CommandLog (L3) — list 类查询历史可追溯 - printCommandEnd({ - command: 'report list', - appCode: c.appCode, - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: '列出报表 (走 webapi 镜像, 端点 /api/Report 端口 32000)', diff --git a/src/commands/storage/list.ts b/src/commands/storage/list.ts index 5756157..d7f19dd 100644 --- a/src/commands/storage/list.ts +++ b/src/commands/storage/list.ts @@ -8,7 +8,7 @@ import { Command } from 'commander' import { readStorageConfig, defaultYmlPath, maskPlatform } from './_helpers.ts' import { log, printJson } from '../../core/log.ts' import { installHelpHook } from '../../core/help.ts' -import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 (无 appCode, 跳过 L3 落盘, 仅 L1 summary) +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 + CommandLog 落盘 (无 appCode, 跳过 L3); v2.2+ wrapCommand 收口 5c 样板 interface ListOpts { profile?: string @@ -27,61 +27,55 @@ export function buildStorageListCommand(): Command { .action(async (opts: ListOpts) => { // 输出过滤: 默认静默 setupOutputFilter(opts) - const startTime = Date.now() - let cmdError: string | undefined - let cmdSummary: Record = {} + // storage 类无 appCode (读 yml, 跟 JNPF API 无关), wrapCommand 仍可用于统一 L1 stdout - try { - const ymlPath = opts.yml || defaultYmlPath(opts.profile) - const cfg = readStorageConfig(ymlPath) - cmdSummary = { - profile: opts.profile, - yml: ymlPath, - defaultPlatform: cfg.defaultPlatform, - total: cfg.platforms.length, - } - if (opts.json) { - printJson({ + await wrapCommand({ + command: 'storage list', + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + const ymlPath = opts.yml || defaultYmlPath(opts.profile) + const cfg = readStorageConfig(ymlPath) + const summary = { + profile: opts.profile, yml: ymlPath, defaultPlatform: cfg.defaultPlatform, - thumbnailSuffix: cfg.thumbnailSuffix, - platforms: cfg.platforms.map(maskPlatform), - }) - return + total: cfg.platforms.length, + } + if (opts.json) { + printJson({ + yml: ymlPath, + defaultPlatform: cfg.defaultPlatform, + thumbnailSuffix: cfg.thumbnailSuffix, + platforms: cfg.platforms.map(maskPlatform), + }) + return ctx.success(summary) + } + log.info(`yml: ${ymlPath}`) + log.info(`default-platform: ${cfg.defaultPlatform}`) + log.info(`thumbnail-suffix: ${cfg.thumbnailSuffix}`) + console.log('') + console.log('TYPE NAME EN-STORE EN-ACCESS ACTIVE YML-PATH') + console.log('-'.repeat(95)) + for (const p of cfg.platforms) { + const type = p.type.padEnd(16) + const name = p.name.padEnd(18) + const store = (p.enableStorage ? 'true ' : 'false').padEnd(10) + const access = (p.enableAccess ? 'true ' : 'false').padEnd(11) + const active = (p.name === cfg.defaultPlatform ? '✓' : ' ').padEnd(8) + console.log(`${type}${name}${store}${access}${active}${p.ymlPath}`) + } + if (cfg.platforms.length === 0) { + log.warn('yml 中未发现任何已知后端 (7 种 backend-type 都没出现)') + } + ctx.success(summary) + } catch (e) { + ctx.fail(`storage list 失败: ${(e as Error).message?.slice(0, 200)}`) } - log.info(`yml: ${ymlPath}`) - log.info(`default-platform: ${cfg.defaultPlatform}`) - log.info(`thumbnail-suffix: ${cfg.thumbnailSuffix}`) - console.log('') - console.log('TYPE NAME EN-STORE EN-ACCESS ACTIVE YML-PATH') - console.log('-'.repeat(95)) - for (const p of cfg.platforms) { - const type = p.type.padEnd(16) - const name = p.name.padEnd(18) - const store = (p.enableStorage ? 'true ' : 'false').padEnd(10) - const access = (p.enableAccess ? 'true ' : 'false').padEnd(11) - const active = (p.name === cfg.defaultPlatform ? '✓' : ' ').padEnd(8) - console.log(`${type}${name}${store}${access}${active}${p.ymlPath}`) - } - if (cfg.platforms.length === 0) { - log.warn('yml 中未发现任何已知后端 (7 种 backend-type 都没出现)') - } - } catch (e) { - cmdError = (e as Error).message?.slice(0, 200) - log.error(`storage list 失败: ${cmdError}`) - } finally { - // v2.1+ (2026-07-21): 输出 CommandLog (无 appCode, 跳过 L3 落盘, 仅 L1 summary) - printCommandEnd({ - command: 'storage list', - result: cmdError ? 'failure' : 'success', - error: cmdError, - summary: cmdSummary, - duration_ms: Date.now() - startTime, - verbose: opts.verbose, - json: opts.json, - }) - if (cmdError) process.exit(1) - } + }) }) installHelpHook(cmd, { purpose: '列出 application-{profile}.yml 中 file-storage 配置的所有后端 (含 enable-storage / default 状态)', diff --git a/tests/unit/report_wired.test.ts b/tests/unit/report_wired.test.ts index 868a724..f87db1b 100644 --- a/tests/unit/report_wired.test.ts +++ b/tests/unit/report_wired.test.ts @@ -1,18 +1,23 @@ // dacli/tests/unit/report_wired.test.ts /** - * report/{create,list,info}.ts 三层接入契约测试 (2026-07-21 固化) + * report/{create,list,info}.ts 三层接入契约测试 (2026-07-21 固化, 2026-07-21 更新) * * 为什么需要这个测试 (rationale): * v2.1+ 三层接入 (runCommandAutoFix + setupOutputFilter + printCommandEnd) 已经固化在 * 16 个 create/list 文件 (handoff 2026-07-21). report/{create,list,info}.ts 是 * 这波接入的第 17/18/19 个文件. 静态契约测试防止未来被悄悄撤掉 (regression 检测). * + * v2.2+ (2026-07-21): P6 sample 续把 report/{list,info}.ts 从 printCommandEnd + * 老 pattern 升级到 wrapCommand(ctx.success/fail) 新 pattern. 测试同步更新: + * - 老检查: `printCommandEnd` + `try/finally` + `if (cmdError) process.exit(1)` + * - 新检查: `wrapCommand` + `ctx.success` + `ctx.fail` + * * 覆盖: - * - report/create.ts: 静态检查包含 runCommandAutoFix + setupOutputFilter + printCommandEnd - * + addOutputOptions 调用 - * - report/list.ts: 静态检查包含 setupOutputFilter + printCommandEnd (read 类无需 runCommandAutoFix) + * - report/create.ts: 静态检查包含 runCommandAutoFix + setupOutputFilter + wrapCommand + * + addOutputOptions 调用 (老 printCommandEnd pattern; 后续将同样迁移到 wrapCommand) + * - report/list.ts: 静态检查包含 setupOutputFilter + wrapCommand + ctx.success/fail * - report/info.ts: 同 list - * - printCommandEnd 调用次数: create 至少 6 次 (1 success + 5 failure) + * - wrapCommand 调用次数: create 至少 1 次 (P6 sample 续后), 后续对齐 * - runtime smoke: --help 命令注册 --verbose 和 --json (验证 addOutputOptions) * * 不覆盖: @@ -93,15 +98,16 @@ describe('report/create.ts 三层接入契约', () => { }) // ============================================================ -// report/list.ts: read 类接入 (输出过滤 + CommandLog, 无 auto-fix) +// report/list.ts: read 类接入 (v2.2+ wrapCommand 收口 5c 样板) // ============================================================ describe('report/list.ts 三层接入契约', () => { const src = readReportFile('list.ts') - it('import setupOutputFilter + addOutputOptions + printCommandEnd', () => { + it('import setupOutputFilter + addOutputOptions + wrapCommand (v2.2+ 替代 printCommandEnd 老 pattern)', () => { expect(src).toMatch(/import\s+\{[^}]*setupOutputFilter[^}]*\}\s+from\s+['"]\.\.\/_output_filter\.ts['"]/) expect(src).toMatch(/addOutputOptions/) - expect(src).toMatch(/printCommandEnd/) + expect(src).toMatch(/wrapCommand/) + expect(src).not.toMatch(/printCommandEnd/) // v2.2+ 已替换 }) it('调用 setupOutputFilter(opts) + addOutputOptions(cmd)', () => { @@ -109,22 +115,16 @@ describe('report/list.ts 三层接入契约', () => { expect(src).toMatch(/addOutputOptions\(cmd\)/) }) - it('使用 try/catch/finally 包裹 (错误路径也走 CommandLog)', () => { - expect(src).toMatch(/\}\s*catch\s*\(\s*e\s*\)\s*\{/) - expect(src).toMatch(/\}\s*finally\s*\{/) - // finally 里调用 printCommandEnd - const finallyIdx = src.indexOf('} finally {') - expect(finallyIdx).toBeGreaterThan(-1) - const finallyBlock = src.slice(finallyIdx) - expect(finallyBlock).toMatch(/printCommandEnd\(/) - expect(finallyBlock).toMatch(/command:\s*['"]report list['"]/) + it('wrapCommand 内含 try/catch (失败走 ctx.fail)', () => { + expect(src).toMatch(/wrapCommand\(\{[^}]*command:\s*['"]report list['"]/) + expect(src).toMatch(/ctx\.fail\(/) + expect(src).toMatch(/ctx\.success\(/) }) - it('错误路径捕获到 cmdError 后 process.exit(1)', () => { - // finally 块里的 process.exit(1) 兜底 - const finallyIdx = src.lastIndexOf('} finally {') - const finallyBlock = src.slice(finallyIdx) - expect(finallyBlock).toMatch(/if\s*\(\s*cmdError\s*\)\s*process\.exit\(1\)/) + it('未用裸 process.exit / 老 try/finally cmdError pattern', () => { + // wrapCommand 已经收口 process.exit, 老 pattern 应不在文件里 + expect(src).not.toMatch(/if\s*\(\s*cmdError\s*\)\s*process\.exit/) + expect(src).not.toMatch(/cmdSummary\s*=\s*\{/) }) it('interfase ListOpts 含 verbose 字段', () => { @@ -133,15 +133,16 @@ describe('report/list.ts 三层接入契约', () => { }) // ============================================================ -// report/info.ts: info 类接入 (跟 list 同一模式) +// report/info.ts: info 类接入 (v2.2+ wrapCommand 收口) // ============================================================ describe('report/info.ts 三层接入契约', () => { const src = readReportFile('info.ts') - it('import setupOutputFilter + addOutputOptions + printCommandEnd', () => { + it('import setupOutputFilter + addOutputOptions + wrapCommand (v2.2+)', () => { expect(src).toMatch(/import\s+\{[^}]*setupOutputFilter[^}]*\}\s+from\s+['"]\.\.\/_output_filter\.ts['"]/) expect(src).toMatch(/addOutputOptions/) - expect(src).toMatch(/printCommandEnd/) + expect(src).toMatch(/wrapCommand/) + expect(src).not.toMatch(/printCommandEnd/) // v2.2+ 已替换 }) it('调用 setupOutputFilter(opts) + addOutputOptions(cmd)', () => { @@ -149,16 +150,15 @@ describe('report/info.ts 三层接入契约', () => { expect(src).toMatch(/addOutputOptions\(cmd\)/) }) - it('使用 try/catch/finally 包裹', () => { - expect(src).toMatch(/\}\s*catch\s*\(\s*e\s*\)\s*\{/) - expect(src).toMatch(/\}\s*finally\s*\{/) + it('wrapCommand 内含 try/catch (ctx.success + ctx.fail)', () => { + expect(src).toMatch(/wrapCommand\(\{[^}]*command:\s*['"]report info['"]/) + expect(src).toMatch(/ctx\.fail\(/) + expect(src).toMatch(/ctx\.success\(/) }) - it('finally 里 printCommandEnd 含正确 command 名 + 错误退出兜底', () => { - const finallyIdx = src.lastIndexOf('} finally {') - const finallyBlock = src.slice(finallyIdx) - expect(finallyBlock).toMatch(/command:\s*['"]report info['"]/) - expect(finallyBlock).toMatch(/if\s*\(\s*cmdError\s*\)\s*process\.exit\(1\)/) + it('未用裸 process.exit / 老 try/finally cmdError pattern', () => { + expect(src).not.toMatch(/if\s*\(\s*cmdError\s*\)\s*process\.exit/) + expect(src).not.toMatch(/cmdSummary\s*=\s*\{/) }) it('interfase InfoOpts 含 verbose 字段', () => {