diff --git a/src/commands/dict/datacreate.ts b/src/commands/dict/datacreate.ts index 306c10d..3a1c29b 100644 --- a/src/commands/dict/datacreate.ts +++ b/src/commands/dict/datacreate.ts @@ -16,6 +16,7 @@ import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' import { lookupDataIdByEnCode } from './_lookup.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c interface Opts { typeId: string @@ -27,6 +28,8 @@ interface Opts { /** v0.12+ BS-New-1: 跳过已存在的 enCode/fullName 字典项 (避免 EXIST001/EXIST002) */ skipDuplicate?: boolean json?: boolean + /** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */ + verbose?: boolean } export function buildDictDataCreateCommand(): Command { @@ -41,129 +44,146 @@ export function buildDictDataCreateCommand(): Command { .option('--items ', '批量 JSON 数组 [{enCode, fullName, sortCode?}, ...] (与 --enCode/--fullName 互斥)') .option('--skip-duplicate', '跳过已存在 enCode/fullName 的项 (避免 EXIST001/EXIST002 报错, 默认 ON)', true) .option('--no-skip-duplicate', '强制创建, 遇重复返错误 (旧行为)') - .option('--json', '原始 JSON 输出', false) + addOutputOptions(cmd) .action(async (opts: Opts) => { - if (!opts.typeId) { - log.error('--typeId 必填') - process.exit(2) - } - if (!opts.items && (!opts.enCode || !opts.fullName)) { - log.error('单条模式必填 --enCode 和 --fullName; 或传 --items 批量') - process.exit(2) - } - - // === step 0 校验参数 + 解析 items === + setupOutputFilter(opts) const c = await JnpfClient.fromToken() - await initWebapi(c) - let items: Array<{ enCode: string; fullName: string; sortCode?: number; parentId?: string }> - if (opts.items) { + await wrapCommand({ + command: 'dict dataCreate', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { try { - items = JSON.parse(opts.items) - } catch (e) { - log.error(`--items JSON 解析失败: ${(e as Error).message}`) - process.exit(2) - } - if (!Array.isArray(items) || items.length === 0) { - log.error('--items 必是非空数组') - process.exit(2) - } - } else { - items = [ - { - enCode: opts.enCode!, - fullName: opts.fullName!, - sortCode: Number(opts.sortCode || '0'), - parentId: opts.parentId || '0', - }, - ] - } - - // === step 0.5 (v0.12+ BS-New-1): 预拉已有 items, 检测重复 === - // 后端约束 (jnpf-system-controller/DictionaryDataController.java:create L55-60): - // enCode/fullName 在同一 typeId 内唯一, 命中返 EXIST001(名称)/EXIST002(编码) - // 见 jnpf-common-core/MsgCode.java: EXIST001 = "名称不能重复"; EXIST002 = "编码不能重复" - const skipDup = opts.skipDuplicate !== false // 默认 ON - const existingEncodes = new Set() - const existingFullNames = new Set() - const skippedItems: Array<{ enCode: string; fullName: string; reason: string }> = [] - - if (skipDup && items.length >= 1) { - try { - const existing = (await loadDict.getDictionaryDataList({ typeId: opts.typeId })) as { - list?: Array<{ enCode?: string; fullName?: string }> + if (!opts.typeId) { + return ctx.fail('--typeId 必填') } - const existingList = (existing as { list?: unknown[] })?.list || (Array.isArray(existing) ? (existing as unknown[]) : []) - for (const e of existingList as Array<{ enCode?: string; fullName?: string }>) { - if (e.enCode) existingEncodes.add(e.enCode) - if (e.fullName) existingFullNames.add(e.fullName) + if (!opts.items && (!opts.enCode || !opts.fullName)) { + return ctx.fail('单条模式必填 --enCode 和 --fullName; 或传 --items 批量') } - if (existingEncodes.size > 0) { - log.info(` ↻ 检测到 ${existingEncodes.size} 个已存在字典项, --skip-duplicate 已开启`) + + // === step 0 校验参数 + 解析 items === + await initWebapi(c) + let items: Array<{ enCode: string; fullName: string; sortCode?: number; parentId?: string }> + + if (opts.items) { + try { + items = JSON.parse(opts.items) + } catch (e) { + return ctx.fail(`--items JSON 解析失败: ${(e as Error).message}`, { typeId: opts.typeId }) + } + if (!Array.isArray(items) || items.length === 0) { + return ctx.fail('--items 必是非空数组', { typeId: opts.typeId }) + } + } else { + items = [ + { + enCode: opts.enCode!, + fullName: opts.fullName!, + sortCode: Number(opts.sortCode || '0'), + parentId: opts.parentId || '0', + }, + ] + } + + // === step 0.5 (v0.12+ BS-New-1): 预拉已有 items, 检测重复 === + // 后端约束 (jnpf-system-controller/DictionaryDataController.java:create L55-60): + // enCode/fullName 在同一 typeId 内唯一, 命中返 EXIST001(名称)/EXIST002(编码) + // 见 jnpf-common-core/MsgCode.java: EXIST001 = "名称不能重复"; EXIST002 = "编码不能重复" + const skipDup = opts.skipDuplicate !== false // 默认 ON + const existingEncodes = new Set() + const existingFullNames = new Set() + const skippedItems: Array<{ enCode: string; fullName: string; reason: string }> = [] + + if (skipDup && items.length >= 1) { + try { + const existing = (await loadDict.getDictionaryDataList({ typeId: opts.typeId })) as { + list?: Array<{ enCode?: string; fullName?: string }> + } + const existingList = (existing as { list?: unknown[] })?.list || (Array.isArray(existing) ? (existing as unknown[]) : []) + for (const e of existingList as Array<{ enCode?: string; fullName?: string }>) { + if (e.enCode) existingEncodes.add(e.enCode) + if (e.fullName) existingFullNames.add(e.fullName) + } + if (existingEncodes.size > 0) { + log.info(` ↻ 检测到 ${existingEncodes.size} 个已存在字典项, --skip-duplicate 已开启`) + } + } catch (e) { + log.warn(` ⚠ 预拉已存在字典项失败: ${(e as Error).message}, 继续创建 (不跳过)`) + } + } + + // 过滤重复 + const toCreate = skipDup + ? items.filter(it => { + if (existingEncodes.has(it.enCode)) { + skippedItems.push({ enCode: it.enCode, fullName: it.fullName, reason: 'enCode 已存在' }) + return false + } + if (existingFullNames.has(it.fullName)) { + skippedItems.push({ enCode: it.enCode, fullName: it.fullName, reason: 'fullName 已存在' }) + return false + } + return true + }) + : items + + if (skippedItems.length > 0) { + for (const s of skippedItems) { + log.warn(` ⊘ 跳过 ${s.enCode} (${s.fullName}): ${s.reason}`) + } + } + + // === step 1 (批量调用 loadDict.createDictionaryData (后端API) === + const skipInfo = skippedItems.length > 0 ? ` (跳过 ${skippedItems.length})` : '' + log.info(`loadDict.createDictionaryData typeId=${opts.typeId} count=${toCreate.length}${skipInfo}`) + let ok = 0, + fail = 0 + const ids: string[] = [] + // B-15 fix: JNPF POST /system/DictionaryData 返 {data:null} 无 id. + // POST 全成功后用 list 接口反查 (按 enCode), 与 web 端"创建后列表刷新"对齐. + for (const it of toCreate) { + const body = { + dictionaryTypeId: opts.typeId, + enCode: it.enCode, + fullName: it.fullName, + parentId: it.parentId || '0', + sortCode: it.sortCode ?? 0, + } + const r = (await loadDict.createDictionaryData(body)) as { + id?: string + code?: number + msg?: string + } + if (r.code === 200 || r.code === undefined) { + let id = r.id || '' + if (!id) { + id = await lookupDataIdByEnCode(opts.typeId, it.enCode) + } + ok++ + ids.push(id || '') + log.ok(` ✓ ${it.enCode} → ${it.fullName} id=${id || ''}`) + } else { + fail++ + const enhanced = enhanceFromBackend(r.msg || '', 'dictData', { entity: 'dict' }) + log.warn(` ✗ ${it.enCode}: ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) + } + } + log.info(`完成: 成功 ${ok}, 跳过 ${skippedItems.length}, 失败 ${fail}`) + if (opts.json) printJson({ typeId: opts.typeId, success: ok, skipped: skippedItems.length, failed: fail, ids }) + const summary = { typeId: opts.typeId, success: ok, skipped: skippedItems.length, failed: fail } + if (fail > 0) { + ctx.partial(`${fail} 个字典项建失败`, summary) + } else { + ctx.success(summary) } } catch (e) { - log.warn(` ⚠ 预拉已存在字典项失败: ${(e as Error).message}, 继续创建 (不跳过)`) + ctx.fail(`dict dataCreate 失败: ${(e as Error).message?.slice(0, 200)}`) } - } - - // 过滤重复 - const toCreate = skipDup - ? items.filter(it => { - if (existingEncodes.has(it.enCode)) { - skippedItems.push({ enCode: it.enCode, fullName: it.fullName, reason: 'enCode 已存在' }) - return false - } - if (existingFullNames.has(it.fullName)) { - skippedItems.push({ enCode: it.enCode, fullName: it.fullName, reason: 'fullName 已存在' }) - return false - } - return true - }) - : items - - if (skippedItems.length > 0) { - for (const s of skippedItems) { - log.warn(` ⊘ 跳过 ${s.enCode} (${s.fullName}): ${s.reason}`) - } - } - - // === step 1 (批量调用 loadDict.createDictionaryData (后端API) === - const skipInfo = skippedItems.length > 0 ? ` (跳过 ${skippedItems.length})` : '' - log.info(`loadDict.createDictionaryData typeId=${opts.typeId} count=${toCreate.length}${skipInfo}`) - let ok = 0, - fail = 0 - const ids: string[] = [] - // B-15 fix: JNPF POST /system/DictionaryData 返 {data:null} 无 id. - // POST 全成功后用 list 接口反查 (按 enCode), 与 web 端"创建后列表刷新"对齐. - for (const it of toCreate) { - const body = { - dictionaryTypeId: opts.typeId, - enCode: it.enCode, - fullName: it.fullName, - parentId: it.parentId || '0', - sortCode: it.sortCode ?? 0, - } - const r = (await loadDict.createDictionaryData(body)) as { - id?: string - code?: number - msg?: string - } - if (r.code === 200 || r.code === undefined) { - let id = r.id || '' - if (!id) { - id = await lookupDataIdByEnCode(opts.typeId, it.enCode) - } - ok++ - ids.push(id || '') - log.ok(` ✓ ${it.enCode} → ${it.fullName} id=${id || ''}`) - } else { - fail++ - const enhanced = enhanceFromBackend(r.msg || '', 'dictData', { entity: 'dict' }) - log.warn(` ✗ ${it.enCode}: ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) - } - } - log.info(`完成: 成功 ${ok}, 跳过 ${skippedItems.length}, 失败 ${fail}`) - if (opts.json) printJson({ typeId: opts.typeId, success: ok, skipped: skippedItems.length, failed: fail, ids }) + }) }) installHelpHook(cmd, { diff --git a/src/commands/dict/datadelete.ts b/src/commands/dict/datadelete.ts index 1c6b0dc..efcf0b1 100644 --- a/src/commands/dict/datadelete.ts +++ b/src/commands/dict/datadelete.ts @@ -9,8 +9,9 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c -interface Opts { id: string; yes?: boolean } +interface Opts { id: string; yes?: boolean; json?: boolean; verbose?: boolean } export function buildDictDataDeleteCommand(): Command { const cmd = new Command('dataDelete') @@ -18,20 +19,35 @@ export function buildDictDataDeleteCommand(): Command { .description('字典项删除 (硬删, v0.11+ webapi)') .requiredOption('--id ', '字典项 id') .option('--yes', '跳过确认', false) + addOutputOptions(cmd) .action(async (opts: Opts) => { - if (!opts.yes) { - log.warn(`即将删除字典项 id=${opts.id}, 加 --yes 跳过确认`) - process.exit(2) - } + setupOutputFilter(opts) const c = await JnpfClient.fromToken() - await initWebapi(c) - log.info(`loadDict.delDictionaryData (id=${opts.id})`) - const r = (await loadDict.delDictionaryData(opts.id)) as { code?: number; msg?: string } - if (r.code !== 200 && r.code !== undefined) { - log.error(`dict dataDelete 失败: ${r.msg}`) - process.exit(1) - } - log.ok(`✓ 字典项已删除 (id=${opts.id})`) + + await wrapCommand({ + command: 'dict dataDelete', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + if (!opts.yes) { + return ctx.fail(`即将删除字典项 id=${opts.id}, 加 --yes 跳过确认`, { id: opts.id }) + } + await initWebapi(c) + log.info(`loadDict.delDictionaryData (id=${opts.id})`) + const r = (await loadDict.delDictionaryData(opts.id)) as { code?: number; msg?: string } + if (r.code !== 200 && r.code !== undefined) { + return ctx.fail(`dict dataDelete 失败: ${r.msg}`, { id: opts.id, code: r.code }) + } + log.ok(`✓ 字典项已删除 (id=${opts.id})`) + ctx.success({ id: opts.id }) + } catch (e) { + ctx.fail(`dict dataDelete 失败: ${(e as Error).message?.slice(0, 200)}`) + } + }) }) installHelpHook(cmd, { purpose: '字典项删除', diff --git a/src/commands/dict/dataupdate.ts b/src/commands/dict/dataupdate.ts index a9d9f4c..27b2509 100644 --- a/src/commands/dict/dataupdate.ts +++ b/src/commands/dict/dataupdate.ts @@ -9,8 +9,9 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' -import { dirtyCheck, dirtyCheckFailAndExit } from '../_dirty_check.ts' +import { dirtyCheck, dirtyCheckFailAndExit, DirtyCheckError } from '../_dirty_check.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c interface Opts { id: string @@ -21,6 +22,8 @@ interface Opts { expectedEnCode?: string force?: boolean json?: boolean + /** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */ + verbose?: boolean } export function buildDictDataUpdateCommand(): Command { @@ -34,53 +37,77 @@ export function buildDictDataUpdateCommand(): Command { .option('--enabledMark <0|1>', '启用/禁用') .option('--expected-enCode ', 'v0.11e+ Phase A2: 校验 enCode 未变 (防 AI session 误覆盖)') .option('--force', 'v0.11e+ Phase A2: 跳过 dirty check', false) - .option('--json', '原始 JSON 输出', false) + addOutputOptions(cmd) .action(async (opts: Opts) => { + setupOutputFilter(opts) const c = await JnpfClient.fromToken() - await initWebapi(c) - // === step 0 (拉原字典项 (loadDict.getDictionaryDataInfo) === - // v0.11+ Phase 2: 用 webapi 镜像 (loadDict.getDictionaryDataInfo + updateDictionaryData) - const orig = (await loadDict.getDictionaryDataInfo(opts.id)) as Record - if (!orig) { - const enhanced = enhanceFromBackend('拉原字典项失败, id 不存在', 'id', { entity: 'dict' }) - log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })}`) - process.exit(1) - } - // === step 1 (dirty check (Phase A2, 防 AI session 误覆盖) === - // v0.11e+ Phase A2: dirty check (防 AI session 误覆盖) - const dirtyResult = dirtyCheck({ - expectedEnCode: opts.expectedEnCode, - force: opts.force, - current: { - enCode: orig.enCode as string | undefined, - state: orig.enabledMark as string | number | undefined, - fullName: orig.fullName as string | undefined, - type: 'di', - }, - id: opts.id, + await wrapCommand({ + command: 'dict dataUpdate', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + await initWebapi(c) + // === step 0 (拉原字典项 (loadDict.getDictionaryDataInfo) === + // v0.11+ Phase 2: 用 webapi 镜像 (loadDict.getDictionaryDataInfo + updateDictionaryData) + const orig = (await loadDict.getDictionaryDataInfo(opts.id)) as Record + if (!orig) { + const enhanced = enhanceFromBackend('拉原字典项失败, id 不存在', 'id', { entity: 'dict' }) + log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '配置拉取' })}`) + return ctx.fail(`dict dataUpdate 失败: 拉原字典项 id=${opts.id} 失败`, { id: opts.id }) + } + + // === step 1 (dirty check (Phase A2, 防 AI session 误覆盖) === + // v0.11e+ Phase A2: dirty check (防 AI session 误覆盖) + const dirtyResult = dirtyCheck({ + expectedEnCode: opts.expectedEnCode, + force: opts.force, + current: { + enCode: orig.enCode as string | undefined, + state: orig.enabledMark as string | number | undefined, + fullName: orig.fullName as string | undefined, + type: 'di', + }, + id: opts.id, + }) + if (!dirtyResult.ok) { + // v2.2+ (2026-07-21): dirtyCheckFailAndExit 改 throw (DirtyCheckError), 下方 catch → ctx.fail + try { + dirtyCheckFailAndExit(dirtyResult, { type: 'di', id: opts.id, current: { enCode: orig.enCode as string | undefined, fullName: orig.fullName as string | undefined } }, log.error) + } catch (e) { + if (e instanceof DirtyCheckError) { + return ctx.fail(e.message, { id: opts.id, type: 'dictData', errorCount: e.errorCount }) + } + throw e + } + } else if (dirtyResult.skipped) { + log.info(`⚠ dirty check 已 --force 跳过`) + } + // === step 2 (PUT (loadDict.updateDictionaryData, 后端API) === + const body: Record = { ...orig, id: opts.id } + if (opts.enCode) body.enCode = opts.enCode + if (opts.fullName) body.fullName = opts.fullName + if (opts.sortCode !== undefined) body.sortCode = opts.sortCode + if (opts.enabledMark !== undefined) body.enabledMark = parseInt(opts.enabledMark, 10) + log.info(`loadDict.updateDictionaryData (id=${opts.id})`) + const r = (await loadDict.updateDictionaryData(body)) as { code?: number; msg?: string; data?: unknown } + if (r.code !== 200 && r.code !== undefined) { + const enhanced = enhanceFromBackend(r.msg || '', 'dictData', { entity: 'dict' }) + log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) + if (opts.json) printJson(r) + return ctx.fail(`dict dataUpdate 失败 (code=${r.code}): ${r.msg}`, { id: opts.id, code: r.code }) + } + log.ok(`✓ 字典项更新成功 (id=${opts.id})`) + if (opts.json) printJson(r.data) + ctx.success({ id: opts.id }) + } catch (e) { + ctx.fail(`dict dataUpdate 失败: ${(e as Error).message?.slice(0, 200)}`) + } }) - if (!dirtyResult.ok) { - dirtyCheckFailAndExit(dirtyResult, { type: 'di', id: opts.id, current: { enCode: orig.enCode as string | undefined, fullName: orig.fullName as string | undefined } }, log.error) - } else if (dirtyResult.skipped) { - log.info(`⚠ dirty check 已 --force 跳过`) - } - // === step 2 (PUT (loadDict.updateDictionaryData, 后端API) === - const body: Record = { ...orig, id: opts.id } - if (opts.enCode) body.enCode = opts.enCode - if (opts.fullName) body.fullName = opts.fullName - if (opts.sortCode !== undefined) body.sortCode = opts.sortCode - if (opts.enabledMark !== undefined) body.enabledMark = parseInt(opts.enabledMark, 10) - log.info(`loadDict.updateDictionaryData (id=${opts.id})`) - const r = (await loadDict.updateDictionaryData(body)) as { code?: number; msg?: string; data?: unknown } - if (r.code !== 200 && r.code !== undefined) { - const enhanced = enhanceFromBackend(r.msg || '', 'dictData', { entity: 'dict' }) - log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) - if (opts.json) printJson(r) - process.exit(1) - } - log.ok(`✓ 字典项更新成功 (id=${opts.id})`) - if (opts.json) printJson(r.data) }) installHelpHook(cmd, { purpose: '字典项修改 (改名/排序/启用). PUT 语义, 未传保留.', diff --git a/src/commands/dict/typecreate.ts b/src/commands/dict/typecreate.ts index f707dba..3c5f78b 100644 --- a/src/commands/dict/typecreate.ts +++ b/src/commands/dict/typecreate.ts @@ -43,10 +43,6 @@ export function buildDictTypeCreateCommand(): Command { .action(async (opts: Opts) => { // 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON setupOutputFilter(opts) - if (!opts.enCode || !opts.fullName) { - log.error('--enCode 和 --fullName 必填') - process.exit(2) - } const c = await JnpfClient.fromToken() await initWebapi(c) @@ -68,6 +64,9 @@ export function buildDictTypeCreateCommand(): Command { json: opts.json, fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions], }, async (ctx) => { + if (!opts.enCode || !opts.fullName) { + return ctx.fail('--enCode 和 --fullName 必填') + } // 解析 --items JSON 字符串 (step 2 校验需要 array) let itemsArray: DictItemLite[] = [] if (opts.items) { @@ -276,7 +275,8 @@ async function runDictStepMachine( for (const e of allErrors) { log.error(` [step ${e.step} ${e.stepName}] ${e.field || '?'}: ${e.message}`) } - process.exit(1) + // v2.2+ (2026-07-21): throw 替代 process.exit(1), wrapCommand handler catch → ctx.fail (落 L3 CommandLog) + throw new Error(`step machine 校验失败 (${allErrors.length} 个错误)`) } log.info(`✓ step machine 校验通过 (3/3): enCode=${opts.enCode}, items=${opts.items.length}`) diff --git a/src/commands/dict/typedelete.ts b/src/commands/dict/typedelete.ts index 49daa01..9e1c238 100644 --- a/src/commands/dict/typedelete.ts +++ b/src/commands/dict/typedelete.ts @@ -9,8 +9,9 @@ import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c -interface Opts { id: string; yes?: boolean } +interface Opts { id: string; yes?: boolean; json?: boolean; verbose?: boolean } export function buildDictTypeDeleteCommand(): Command { const cmd = new Command('typeDelete') @@ -18,20 +19,35 @@ export function buildDictTypeDeleteCommand(): Command { .description('字典类型删除 (递归删字典项, v0.11+ webapi)') .requiredOption('--id ', '字典类型 id') .option('--yes', '跳过确认', false) + addOutputOptions(cmd) .action(async (opts: Opts) => { - if (!opts.yes) { - log.warn(`即将删除字典类型 id=${opts.id}, 加 --yes 跳过确认`) - process.exit(2) - } + setupOutputFilter(opts) const c = await JnpfClient.fromToken() - await initWebapi(c) - log.info(`loadDict.delDictionaryType (id=${opts.id})`) - const r = (await loadDict.delDictionaryType(opts.id)) as { code?: number; msg?: string } - if (r.code !== 200 && r.code !== undefined) { - log.error(`dict typeDelete 失败: ${r.msg}`) - process.exit(1) - } - log.ok(`✓ 字典类型已删除 (id=${opts.id})`) + + await wrapCommand({ + command: 'dict typeDelete', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + if (!opts.yes) { + return ctx.fail(`即将删除字典类型 id=${opts.id}, 加 --yes 跳过确认`, { id: opts.id }) + } + await initWebapi(c) + log.info(`loadDict.delDictionaryType (id=${opts.id})`) + const r = (await loadDict.delDictionaryType(opts.id)) as { code?: number; msg?: string } + if (r.code !== 200 && r.code !== undefined) { + return ctx.fail(`dict typeDelete 失败: ${r.msg}`, { id: opts.id, code: r.code }) + } + log.ok(`✓ 字典类型已删除 (id=${opts.id})`) + ctx.success({ id: opts.id }) + } catch (e) { + ctx.fail(`dict typeDelete 失败: ${(e as Error).message?.slice(0, 200)}`) + } + }) }) installHelpHook(cmd, { purpose: '字典类型删除 (级联删字典项)', diff --git a/src/commands/dict/typeupdate.ts b/src/commands/dict/typeupdate.ts index 2260c0d..99a2781 100644 --- a/src/commands/dict/typeupdate.ts +++ b/src/commands/dict/typeupdate.ts @@ -10,7 +10,8 @@ import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' -import { dirtyCheck, dirtyCheckFailAndExit } from '../_dirty_check.ts' +import { dirtyCheck, dirtyCheckFailAndExit, DirtyCheckError } from '../_dirty_check.ts' +import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c interface Opts { id: string @@ -23,6 +24,8 @@ interface Opts { expectedState?: string force?: boolean json?: boolean + /** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */ + verbose?: boolean } export function buildDictTypeUpdateCommand(): Command { @@ -38,55 +41,78 @@ export function buildDictTypeUpdateCommand(): Command { .option('--expected-enCode ', 'v0.11e+ Phase A2: 校验 enCode 未变 (防 AI session 误覆盖)') .option('--expected-state ', 'v0.11e+ Phase A2: 校验 enabledMark 未变') .option('--force', 'v0.11e+ Phase A2: 跳过 dirty check', false) - .option('--json', '原始 JSON 输出', false) + addOutputOptions(cmd) .action(async (opts: Opts) => { + setupOutputFilter(opts) const c = await JnpfClient.fromToken() - await initWebapi(c) - // === step 0 (拉原字典类型 (loadDict.getDictionaryTypeInfo) === - // v0.11+ Phase 2: 用 webapi 镜像 (loadDict.getDictionaryTypeInfo + updateDictionaryType) - const orig = (await loadDict.getDictionaryTypeInfo(opts.id)) as Record - if (!orig) { - log.error(`dict typeUpdate 失败: 拉原字典类型 id=${opts.id} 失败`) - process.exit(1) - } - // === step 1 (dirty check (Phase A2, 防 AI session 误覆盖) === - // v0.11e+ Phase A2: dirty check (防 AI session 长时间保留误覆盖) - const dirtyResult = dirtyCheck({ - expectedEnCode: opts.expectedEnCode, - expectedState: opts.expectedState, - force: opts.force, - current: { - enCode: orig.enCode as string | undefined, - state: orig.enabledMark as string | number | undefined, - fullName: orig.fullName as string | undefined, - type: 'dict', - }, - id: opts.id, + await wrapCommand({ + command: 'dict typeUpdate', + appCode: c.appCode, + startTime: Date.now(), + verbose: opts.verbose, + json: opts.json, + fixes: [], + }, async (ctx) => { + try { + await initWebapi(c) + // === step 0 (拉原字典类型 (loadDict.getDictionaryTypeInfo) === + // v0.11+ Phase 2: 用 webapi 镜像 (loadDict.getDictionaryTypeInfo + updateDictionaryType) + const orig = (await loadDict.getDictionaryTypeInfo(opts.id)) as Record + if (!orig) { + return ctx.fail(`dict typeUpdate 失败: 拉原字典类型 id=${opts.id} 失败`, { id: opts.id }) + } + + // === step 1 (dirty check (Phase A2, 防 AI session 误覆盖) === + // v0.11e+ Phase A2: dirty check (防 AI session 长时间保留误覆盖) + const dirtyResult = dirtyCheck({ + expectedEnCode: opts.expectedEnCode, + expectedState: opts.expectedState, + force: opts.force, + current: { + enCode: orig.enCode as string | undefined, + state: orig.enabledMark as string | number | undefined, + fullName: orig.fullName as string | undefined, + type: 'dict', + }, + id: opts.id, + }) + if (!dirtyResult.ok) { + // v2.2+ (2026-07-21): dirtyCheckFailAndExit 改 throw (DirtyCheckError), 下方 catch → ctx.fail + try { + dirtyCheckFailAndExit(dirtyResult, { type: 'dict', id: opts.id, current: { enCode: orig.enCode as string | undefined, fullName: orig.fullName as string | undefined } }, log.error) + } catch (e) { + if (e instanceof DirtyCheckError) { + return ctx.fail(e.message, { id: opts.id, type: 'dict', errorCount: e.errorCount }) + } + throw e + } + } else if (dirtyResult.skipped) { + log.info(`⚠ dirty check 已 --force 跳过`) + } + + // === step 2 (PUT (loadDict.updateDictionaryType, 后端API) === + const body: Record = { ...orig, id: opts.id } + if (opts.fullName) body.fullName = opts.fullName + if (opts.enCode) body.enCode = opts.enCode + if (opts.category) body.category = opts.category + if (opts.isTree !== undefined) body.isTree = opts.isTree + if (opts.sortCode !== undefined) body.sortCode = opts.sortCode + log.info(`loadDict.updateDictionaryType (id=${opts.id})`) + const r = (await loadDict.updateDictionaryType(body)) as { code?: number; msg?: string; data?: unknown } + if (r.code !== 200 && r.code !== undefined) { + const enhanced = enhanceFromBackend(r.msg || '', 'dictType', { entity: 'dict' }) + log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) + if (opts.json) printJson(r) + return ctx.fail(`dict typeUpdate 失败 (code=${r.code}): ${r.msg}`, { id: opts.id, code: r.code }) + } + log.ok(`✓ 字典类型更新成功 (id=${opts.id})`) + if (opts.json) printJson(r.data) + ctx.success({ id: opts.id }) + } catch (e) { + ctx.fail(`dict typeUpdate 失败: ${(e as Error).message?.slice(0, 200)}`) + } }) - if (!dirtyResult.ok) { - dirtyCheckFailAndExit(dirtyResult, { type: 'dict', id: opts.id, current: { enCode: orig.enCode as string | undefined, fullName: orig.fullName as string | undefined } }, log.error) - } else if (dirtyResult.skipped) { - log.info(`⚠ dirty check 已 --force 跳过`) - } - - // === step 2 (PUT (loadDict.updateDictionaryType, 后端API) === - const body: Record = { ...orig, id: opts.id } - if (opts.fullName) body.fullName = opts.fullName - if (opts.enCode) body.enCode = opts.enCode - if (opts.category) body.category = opts.category - if (opts.isTree !== undefined) body.isTree = opts.isTree - if (opts.sortCode !== undefined) body.sortCode = opts.sortCode - log.info(`loadDict.updateDictionaryType (id=${opts.id})`) - const r = (await loadDict.updateDictionaryType(body)) as { code?: number; msg?: string; data?: unknown } - if (r.code !== 200 && r.code !== undefined) { - const enhanced = enhanceFromBackend(r.msg || '', 'dictType', { entity: 'dict' }) - log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) - if (opts.json) printJson(r) - process.exit(1) - } - log.ok(`✓ 字典类型更新成功 (id=${opts.id})`) - if (opts.json) printJson(r.data) }) installHelpHook(cmd, { purpose: '字典类型修改 (改名/分类/树形/排序). PUT 语义, 未传保留.',