feat(dacli): role/* 模块 wrapCommand 迁移 (create/delete/info/update, 8 exit 收口)

create.ts 从旧 printCommandEnd 升级到 wrapCommand (runRoleStepMachine 内部 process.exit → throw).
update.ts 复用 DirtyCheckError catch → ctx.fail 模式.
delete/info process.exit → ctx.fail. assign.ts 已迁移 (无变更).
role/ 模块 process.exit 归零.

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-21 20:44:07 +08:00
1 parent c6763c4129
commit 17c0f353ab
4 files changed
+198 -145

No files matched your search

+51 -59
View File
@@ -12,7 +12,7 @@ import { validateRoleCreate } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { initWebapi, loadRole } from '../../webapi/role.ts'
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): 跨命令 auto-fix pipeline (替代原 inline autoStripEnCode)
import { setupOutputFilter, 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 { lookupRoleIdByEnCode } from './_lookup.ts'
interface CreateOpts {
@@ -32,8 +32,7 @@ export function buildRoleCreateCommand(): Command {
.option('--type <t>', '角色类型: 0=全局 1=业务', '0')
// v0.11e+ Phase A3: 跨命令事务 — 镜像 web roleRelationService.create (建角色后批量绑用户)
.option('--user-ids <ids>', '关联用户 id 列表 (逗号分隔, 例: 1,2,3). v0.11e+ Phase A3 跨命令事务 (镜像 web roleRelationService.create)')
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: CreateOpts) => {
// 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON
setupOutputFilter(opts)
@@ -50,65 +49,57 @@ export function buildRoleCreateCommand(): Command {
Object.assign(opts, cmdFix.opts)
}
// v0.11d+ Phase 3.4: step machine 校验 (镜像 web role/Form.vue + 后端 RoleController.create)
// 跑 3 step 校验, 失败 → exit 1
await runRoleStepMachine(c, {
fullName: opts.fullName,
enCode: opts.enCode,
type: opts.type,
enabledMark: 1,
sortCode: 0,
})
// 解析 --user-ids (Phase A3 跨命令事务)
const userIdsArray = opts.userIds ? opts.userIds.split(',').map((s) => s.trim()).filter(Boolean) : []
const body = {
fullName: opts.fullName,
enCode: opts.enCode,
type: opts.type,
enabledMark: 1,
sortCode: 0,
organizeIds: [],
positionIds: [],
userIds: userIdsArray,
}
const r = (await loadRole.create(body)) as { code?: number; msg?: string; data?: { id?: string } }
if (r.code !== 200) {
log.error(`role create 失败 (code=${r.code}): ${r.msg}`)
// v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode
const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
// v2.1+ (2026-07-21): 错误路径落 CommandLog
printCommandEnd({
command: 'role create',
appCode: c.appCode,
result: 'failure',
error: `role create 失败 (code=${r.code}): ${r.msg}`,
summary: { enCode: opts.enCode },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
let id = r.data?.id
if (!id) {
// v0.21+ (Round 12 BS-新42): 用共享 _lookup.ts 替代 inline list fallback
id = (await lookupRoleIdByEnCode(opts.enCode, opts.fullName)) ?? id
}
log.info(`✓ 角色创建成功 id=${id}${userIdsArray.length > 0 ? ` (含 ${userIdsArray.length} 个用户绑定)` : ''}`)
if (opts.json) printJson({ ...(r.data as object), id })
// v2.1+ (2026-07-21): 成功路径落 CommandLog
printCommandEnd({
await wrapCommand({
command: 'role create',
appCode: c.appCode,
summary: { id, enCode: opts.enCode, userIdsCount: userIdsArray.length },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
startTime,
verbose: opts.verbose,
json: opts.json,
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
}, async (ctx) => {
try {
// v0.11d+ Phase 3.4: step machine 校验 (镜像 web role/Form.vue + 后端 RoleController.create)
// 跑 3 step 校验, 失败 → throw (wrapCommand handler catch → ctx.fail)
await runRoleStepMachine(c, {
fullName: opts.fullName,
enCode: opts.enCode,
type: opts.type,
enabledMark: 1,
sortCode: 0,
})
// 解析 --user-ids (Phase A3 跨命令事务)
const userIdsArray = opts.userIds ? opts.userIds.split(',').map((s) => s.trim()).filter(Boolean) : []
const body = {
fullName: opts.fullName,
enCode: opts.enCode,
type: opts.type,
enabledMark: 1,
sortCode: 0,
organizeIds: [],
positionIds: [],
userIds: userIdsArray,
}
const r = (await loadRole.create(body)) as { code?: number; msg?: string; data?: { id?: string } }
if (r.code !== 200) {
log.error(`role create 失败 (code=${r.code}): ${r.msg}`)
// v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode
const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
return ctx.fail(`role create 失败 (code=${r.code}): ${r.msg}`, { enCode: opts.enCode })
}
let id = r.data?.id
if (!id) {
// v0.21+ (Round 12 BS-新42): 用共享 _lookup.ts 替代 inline list fallback
id = (await lookupRoleIdByEnCode(opts.enCode, opts.fullName)) ?? id
}
log.info(`✓ 角色创建成功 id=${id}${userIdsArray.length > 0 ? ` (含 ${userIdsArray.length} 个用户绑定)` : ''}`)
if (opts.json) printJson({ ...(r.data as object), id })
ctx.success({ id, enCode: opts.enCode, userIdsCount: userIdsArray.length })
} catch (e) {
ctx.fail(`role create 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
@@ -188,7 +179,8 @@ async function runRoleStepMachine(
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}`)
+30 -11
View File
@@ -9,10 +9,14 @@ import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
import { initWebapi, loadRole } from '../../webapi/role.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface DeleteOpts {
id: string
yes?: boolean
json?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
export function buildRoleDeleteCommand(): Command {
@@ -20,19 +24,34 @@ export function buildRoleDeleteCommand(): Command {
.description('删除角色 (非系统内置, v0.14+ webapi)')
.requiredOption('--id <id>', '角色 id')
.option('--yes', '跳过确认', false)
addOutputOptions(cmd)
.action(async (opts: DeleteOpts) => {
if (!opts.yes) {
log.warn(`即将删除角色 id=${opts.id}, 加 --yes 跳过确认`)
process.exit(2)
}
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
await initWebapi(c)
const r = (await loadRole.delRole(opts.id)) as { code?: number; msg?: string }
if (r.code !== 200) {
log.error(`role delete 失败: ${r.msg}`)
process.exit(1)
}
log.info(`✓ 角色 id=${opts.id} 已删除`)
await wrapCommand({
command: 'role delete',
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)
const r = (await loadRole.delRole(opts.id)) as { code?: number; msg?: string }
if (r.code !== 200) {
return ctx.fail(`role delete 失败: ${r.msg}`, { id: opts.id, code: r.code })
}
log.info(`✓ 角色 id=${opts.id} 已删除`)
ctx.success({ id: opts.id })
} catch (e) {
ctx.fail(`role delete 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
purpose: '删除角色 (isSystem=1 系统内置角色不可删)',
+35 -19
View File
@@ -9,33 +9,49 @@ import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { initWebapi, loadRole } from '../../webapi/role.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface Opts { id: string; json?: boolean }
interface Opts { id: string; json?: boolean; verbose?: boolean }
export function buildRoleInfoCommand(): Command {
const cmd = new Command('info')
.description('角色详情 (含 isSystem / enabledMark / 约束配置, v0.11+ webapi)')
.requiredOption('--id <id>', '角色 id')
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: Opts) => {
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
await initWebapi(c)
const d = (await loadRole.getInfo(opts.id)) as Record<string, unknown>
if (!d) {
log.error(`role info 失败: id=${opts.id} 不存在`)
process.exit(1)
}
if (opts.json) {
printJson(d)
return
}
log.info(`角色详情 (id=${opts.id})`)
console.log(` fullName : ${d.fullName}`)
console.log(` enCode : ${d.enCode}`)
console.log(` type : ${d.type} (0=全局 1=部门)`)
console.log(` enabledMark : ${d.enabledMark === 1 ? '启用' : '禁用'}`)
console.log(` isSystem : ${d.isSystem} (1=系统内置, 不可删改)`)
console.log(` description : ${d.description || '-'}`)
await wrapCommand({
command: 'role info',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
await initWebapi(c)
const d = (await loadRole.getInfo(opts.id)) as Record<string, unknown>
if (!d) {
return ctx.fail(`role info 失败: id=${opts.id} 不存在`, { id: opts.id })
}
if (opts.json) {
printJson(d)
return ctx.success({ id: opts.id })
}
log.info(`角色详情 (id=${opts.id})`)
console.log(` fullName : ${d.fullName}`)
console.log(` enCode : ${d.enCode}`)
console.log(` type : ${d.type} (0=全局 1=部门)`)
console.log(` enabledMark : ${d.enabledMark === 1 ? '启用' : '禁用'}`)
console.log(` isSystem : ${d.isSystem} (1=系统内置, 不可删改)`)
console.log(` description : ${d.description || '-'}`)
ctx.success({ id: opts.id, enCode: d.enCode })
} catch (e) {
ctx.fail(`role info 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
purpose: '角色详情. AI 创建角色后验证 (P0 闭环, v0.11+ webapi).',
+82 -56
View File
@@ -10,8 +10,9 @@ import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { initWebapi, loadRole } from '../../webapi/role.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { dirtyCheck, dirtyCheckFailAndExit } from '../_dirty_check.ts'
import { dirtyCheck, dirtyCheckFailAndExit, DirtyCheckError } from '../_dirty_check.ts'
import { validateBasicInfo as validateRoleBasicInfo } from './_validate.ts' // v0.15+ (R3.4)
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 buildRoleUpdateCommand(): Command {
@@ -36,66 +39,89 @@ export function buildRoleUpdateCommand(): Command {
.option('--expected-enCode <e>', 'v0.11e+ Phase A2: 校验 enCode 未变 (防 AI session 误覆盖)')
.option('--expected-state <s>', '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 (拉原角色 (loadRole.getInfo) ===
const orig = (await loadRole.getInfo(opts.id)) as Record<string, unknown>
if (!orig) {
log.error(`role update 失败: 拉原角色 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: 'role',
},
id: opts.id,
})
if (!dirtyResult.ok) {
dirtyCheckFailAndExit(dirtyResult, { type: 'role', 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 跳过`)
}
await wrapCommand({
command: 'role update',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
await initWebapi(c)
// === step 0 (拉原角色 (loadRole.getInfo) ===
const orig = (await loadRole.getInfo(opts.id)) as Record<string, unknown>
if (!orig) {
return ctx.fail(`role update 失败: 拉原角色 id=${opts.id} 失败`, { id: opts.id })
}
// v0.15+ (R3.4): 校验用户传入的字段 (fullName/enCode) 走 _validate.ts 防 BS-56
// 旧版 update 跳过 _validate, AI 跑 --enCode=foo_bar (下划线) → 后端静默接受 → 漂移
const toValidate: Record<string, unknown> = {}
if (opts.fullName !== undefined) toValidate.fullName = opts.fullName
if (opts.enCode !== undefined) toValidate.enCode = opts.enCode
if (Object.keys(toValidate).length > 0) {
const v = validateRoleBasicInfo(toValidate as { fullName?: string; enCode?: string; category?: string })
if (!v.ok) {
for (const err of v.errors) log.error(` [${v.stepName}] ${err.message}`)
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: 'role',
},
id: opts.id,
})
if (!dirtyResult.ok) {
// v2.2+ (2026-07-21): dirtyCheckFailAndExit 改 throw (DirtyCheckError), 下方 catch → ctx.fail
try {
dirtyCheckFailAndExit(dirtyResult, { type: 'role', 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: 'role', errorCount: e.errorCount })
}
throw e
}
} else if (dirtyResult.skipped) {
log.info(`⚠ dirty check 已 --force 跳过`)
}
// v0.15+ (R3.4): 校验用户传入的字段 (fullName/enCode) 走 _validate.ts 防 BS-56
// 旧版 update 跳过 _validate, AI 跑 --enCode=foo_bar (下划线) → 后端静默接受 → 漂移
const toValidate: Record<string, unknown> = {}
if (opts.fullName !== undefined) toValidate.fullName = opts.fullName
if (opts.enCode !== undefined) toValidate.enCode = opts.enCode
if (Object.keys(toValidate).length > 0) {
const v = validateRoleBasicInfo(toValidate as { fullName?: string; enCode?: string; category?: string })
if (!v.ok) {
for (const err of v.errors) log.error(` [${v.stepName}] ${err.message}`)
return ctx.fail(`role update 字段校验失败 (${v.stepName})`, { id: opts.id })
}
}
// === step 2 (PUT (loadRole.update, 后端API) ===
const body: Record<string, unknown> = { ...orig, id: opts.id }
if (opts.fullName) body.fullName = opts.fullName
if (opts.enCode) body.enCode = opts.enCode
if (opts.enabledMark !== undefined) body.enabledMark = opts.enabledMark
if (opts.description) body.description = opts.description
log.info(`loadRole.update (id=${opts.id})`)
const r = (await loadRole.update(body)) as { code?: number; msg?: string; data?: unknown }
if (r.code !== 200 && r.code !== undefined) {
const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
if (opts.json) printJson(r)
return ctx.fail(`role update 失败 (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(`role update 失败: ${(e as Error).message?.slice(0, 200)}`)
}
}
// === step 2 (PUT (loadRole.update, 后端API) ===
const body: Record<string, unknown> = { ...orig, id: opts.id }
if (opts.fullName) body.fullName = opts.fullName
if (opts.enCode) body.enCode = opts.enCode
if (opts.enabledMark !== undefined) body.enabledMark = opts.enabledMark
if (opts.description) body.description = opts.description
log.info(`loadRole.update (id=${opts.id})`)
const r = (await loadRole.update(body)) as { code?: number; msg?: string; data?: unknown }
if (r.code !== 200 && r.code !== undefined) {
const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
if (opts.json) printJson(r)
process.exit(1)
}
log.ok(`✓ 角色更新成功 (id=${opts.id})`)
if (opts.json) printJson(r.data)
})
})
installHelpHook(cmd, {
purpose: '角色修改 (改 fullName/enCode/enabledMark/description). PUT 语义, 未传字段保留原值.',