feat(dacli): user/* 剩余 11 文件 wrapCommand 迁移 (batch2+batch-delete, 全模块收口)
baseinfo/batch-set-position/batch-state/online-kick/delete/resetpwd/ socials-unbind/batch-delete/update/info/create — 全部 process.exit → ctx.fail. create.ts 从旧 printCommandEnd 模式升级到 wrapCommand (保留 runCommandAutoFix fixes). update.ts 复用 DirtyCheckError catch → ctx.fail 模式. user/ 模块 20 文件 process.exit 归零 (100% 收口). Co-Authored-By: Claude <[email protected]>
This commit is contained in:
1 parent
2f7482c7c2
commit
c6763c4129
12 files changed
+513
-314
No files matched your search
@@ -13,30 +13,49 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface BaseinfoOpts {
|
||||
fields: string
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserBaseinfoCommand(): Command {
|
||||
const cmd = new Command('baseinfo')
|
||||
.description('修改当前用户个人资料 (self 操作, 任意字段子集)')
|
||||
.requiredOption('--fields <json>', '要更新的字段 JSON, 如 {"mobilePhone":"138...","email":"x@y","realName":"新名"}')
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: BaseinfoOpts) => {
|
||||
let fields: Record<string, unknown>
|
||||
try {
|
||||
fields = JSON.parse(opts.fields)
|
||||
} catch (e) {
|
||||
log.error(`JSON 解析失败: ${(e as Error).message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = await c.putJson('/permission/Users/Current/BaseInfo', fields)
|
||||
if (r.code !== 200) {
|
||||
log.error(`user baseinfo 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 个人资料已更新: ${Object.keys(fields).map((k) => `${k}=${fields[k]}`).join(', ')}`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user baseinfo',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
let fields: Record<string, unknown>
|
||||
try {
|
||||
fields = JSON.parse(opts.fields)
|
||||
} catch (e) {
|
||||
return ctx.fail(`JSON 解析失败: ${(e as Error).message}`)
|
||||
}
|
||||
const r = await c.putJson('/permission/Users/Current/BaseInfo', fields)
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`user baseinfo 失败 (code=${r.code}): ${r.msg}`, { code: r.code })
|
||||
}
|
||||
log.info(`✓ 个人资料已更新: ${Object.keys(fields).map((k) => `${k}=${fields[k]}`).join(', ')}`)
|
||||
ctx.success({ updatedFields: Object.keys(fields) })
|
||||
} catch (e) {
|
||||
ctx.fail(`user baseinfo 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '修改当前用户个人资料 (self 操作, 通用入口)',
|
||||
|
||||
@@ -9,10 +9,14 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface BatchDeleteOpts {
|
||||
ids: string
|
||||
yes?: boolean
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserBatchDeleteCommand(): Command {
|
||||
@@ -20,23 +24,37 @@ export function buildUserBatchDeleteCommand(): Command {
|
||||
.description('批量删除用户 (admin 操作, 不可恢复)')
|
||||
.requiredOption('--ids <list>', '用户 id 列表, 逗号分隔')
|
||||
.option('--yes', '跳过确认', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: BatchDeleteOpts) => {
|
||||
const ids = opts.ids.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!ids.length) {
|
||||
log.error('--ids 不能为空')
|
||||
process.exit(1)
|
||||
}
|
||||
if (!opts.yes) {
|
||||
log.warn(`即将删除 ${ids.length} 个用户, 加 --yes 跳过确认`)
|
||||
process.exit(1)
|
||||
}
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = await c.postJson('/permission/Users/BatchDelete', { ids })
|
||||
if (r.code !== 200) {
|
||||
log.error(`user batch-delete 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 已删除 ${ids.length} 个用户`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user batch-delete',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
const ids = opts.ids.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!ids.length) {
|
||||
return ctx.fail('--ids 不能为空')
|
||||
}
|
||||
if (!opts.yes) {
|
||||
return ctx.fail(`即将删除 ${ids.length} 个用户, 加 --yes 跳过确认`, { total: ids.length })
|
||||
}
|
||||
const r = await c.postJson('/permission/Users/BatchDelete', { ids })
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`user batch-delete 失败 (code=${r.code}): ${r.msg}`, { code: r.code })
|
||||
}
|
||||
log.info(`✓ 已删除 ${ids.length} 个用户`)
|
||||
ctx.success({ total: ids.length })
|
||||
} catch (e) {
|
||||
ctx.fail(`user batch-delete 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '批量删除用户 (admin 操作)',
|
||||
|
||||
@@ -10,10 +10,14 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface BatchSetPositionOpts {
|
||||
userIds: string
|
||||
positionIds: string
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserBatchSetPositionCommand(): Command {
|
||||
@@ -21,20 +25,35 @@ export function buildUserBatchSetPositionCommand(): Command {
|
||||
.description('批量设置用户岗位 (admin 操作)')
|
||||
.requiredOption('--userIds <list>', '用户 id 列表, 逗号分隔')
|
||||
.requiredOption('--positionIds <list>', '岗位 id 列表, 逗号分隔')
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: BatchSetPositionOpts) => {
|
||||
const userIds = opts.userIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
const ids = opts.positionIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!userIds.length || !ids.length) {
|
||||
log.error('--userIds 和 --positionIds 均不能为空')
|
||||
process.exit(1)
|
||||
}
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = await c.postJson('/permission/Users/SetPositionBatch', { userIds, ids })
|
||||
if (r.code !== 200) {
|
||||
log.error(`user batch-set-position 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 已为 ${userIds.length} 个用户设置 ${ids.length} 个岗位`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user batch-set-position',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
const userIds = opts.userIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
const ids = opts.positionIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!userIds.length || !ids.length) {
|
||||
return ctx.fail('--userIds 和 --positionIds 均不能为空')
|
||||
}
|
||||
const r = await c.postJson('/permission/Users/SetPositionBatch', { userIds, ids })
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`user batch-set-position 失败 (code=${r.code}): ${r.msg}`, { code: r.code })
|
||||
}
|
||||
log.info(`✓ 已为 ${userIds.length} 个用户设置 ${ids.length} 个岗位`)
|
||||
ctx.success({ userCount: userIds.length, positionCount: ids.length })
|
||||
} catch (e) {
|
||||
ctx.fail(`user batch-set-position 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '批量设置用户岗位 (admin 操作)',
|
||||
|
||||
@@ -9,11 +9,15 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
import { DacliError } from '../../core/types.ts'
|
||||
interface BatchStateOpts {
|
||||
ids: string
|
||||
state: string
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserBatchStateCommand(): Command {
|
||||
@@ -25,21 +29,36 @@ export function buildUserBatchStateCommand(): Command {
|
||||
if (![0, 1, 2].includes(n)) throw new DacliError('state 必须是 0/1/2')
|
||||
return v
|
||||
})
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: BatchStateOpts) => {
|
||||
const ids = opts.ids.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!ids.length) {
|
||||
log.error('--ids 不能为空')
|
||||
process.exit(1)
|
||||
}
|
||||
const enabledMark = parseInt(opts.state, 10)
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = await c.postJson('/permission/Users/BatchUpdateState', { ids, enabledMark })
|
||||
if (r.code !== 200) {
|
||||
log.error(`user batch-state 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const stateName = enabledMark === 1 ? '启用' : enabledMark === 2 ? '锁定' : '禁用'
|
||||
log.info(`✓ 已更新 ${ids.length} 个用户状态为${stateName}`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user batch-state',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
const ids = opts.ids.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
if (!ids.length) {
|
||||
return ctx.fail('--ids 不能为空')
|
||||
}
|
||||
const enabledMark = parseInt(opts.state, 10)
|
||||
const r = await c.postJson('/permission/Users/BatchUpdateState', { ids, enabledMark })
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`user batch-state 失败 (code=${r.code}): ${r.msg}`, { code: r.code })
|
||||
}
|
||||
const stateName = enabledMark === 1 ? '启用' : enabledMark === 2 ? '锁定' : '禁用'
|
||||
log.info(`✓ 已更新 ${ids.length} 个用户状态为${stateName}`)
|
||||
ctx.success({ total: ids.length, state: stateName })
|
||||
} catch (e) {
|
||||
ctx.fail(`user batch-state 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '批量启/禁/锁用户 (admin 操作)',
|
||||
|
||||
+61
-70
@@ -13,7 +13,7 @@ import { initWebapi, loadUser } from '../../webapi/user.ts'
|
||||
import { validateUserCreate } from './_validate.ts'
|
||||
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
|
||||
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): 跨命令 auto-fix pipeline
|
||||
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
|
||||
|
||||
interface CreateOpts {
|
||||
account: string
|
||||
@@ -41,8 +41,7 @@ export function buildUserCreateCommand(): Command {
|
||||
.option('--sortCode <n>', '排序', '0')
|
||||
.option('--description <d>', '说明')
|
||||
.option('--roleId <id>', 'v0.11e+ Phase C1: 角色 id (PS012 必填, 镜像 web user/Form.vue)')
|
||||
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
|
||||
.option('--json', '原始 JSON 输出', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: CreateOpts) => {
|
||||
// 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON
|
||||
setupOutputFilter(opts)
|
||||
@@ -60,77 +59,69 @@ export function buildUserCreateCommand(): Command {
|
||||
Object.assign(opts, cmdFix.opts)
|
||||
}
|
||||
|
||||
// v0.11e+ Phase C1: step machine 校验 (镜像 web user/Form.vue + PS007/008/012/204/EXIST006)
|
||||
const validation = validateUserCreate({
|
||||
account: opts.account,
|
||||
fullName: opts.realName,
|
||||
password: opts.password,
|
||||
roleId: opts.roleId,
|
||||
enabledMark: opts.enabledMark,
|
||||
isCreate: true,
|
||||
})
|
||||
if (!validation.ok) {
|
||||
for (const s of validation.steps) {
|
||||
for (const e of s.errors) {
|
||||
log.error(` ${formatErrorLine(e, { step: s.step, stepName: s.stepName })}`)
|
||||
}
|
||||
}
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ step machine 校验通过 (${validation.steps.length}/${validation.steps.length})`)
|
||||
// step 0 基础信息 (P0 镜像 web Form.vue schemas)
|
||||
|
||||
// JNPF 接收的 password 是 md5(plain) hex (32 字符), 不是 AES 加密
|
||||
const md5Pwd = encryptByMd5(opts.password)
|
||||
const body: Record<string, unknown> = {
|
||||
account: opts.account,
|
||||
realName: opts.realName,
|
||||
password: md5Pwd,
|
||||
gender: opts.gender || '1',
|
||||
enabledMark: opts.enabledMark || '1',
|
||||
sortCode: parseInt(opts.sortCode || '0', 10),
|
||||
}
|
||||
if (opts.organizeId) body.organizeId = opts.organizeId
|
||||
if (opts.description) body.description = opts.description
|
||||
if (opts.roleId) body.roleId = opts.roleId.split(',')
|
||||
log.info(`loadUser.createUser (account=${opts.account})`)
|
||||
const r = (await loadUser.createUser(body)) as { id?: string; code?: number; msg?: string; data?: { id?: string } }
|
||||
if (r.code !== 200 && r.code !== undefined) {
|
||||
const enhanced = enhanceFromBackend(r.msg || '', 'user', { entity: 'user' })
|
||||
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
|
||||
// v2.1+ (2026-07-21): 错误路径落 CommandLog
|
||||
printCommandEnd({
|
||||
command: 'user create',
|
||||
appCode: c.appCode,
|
||||
result: 'failure',
|
||||
error: `user create 失败 (code=${r.code}): ${r.msg}`,
|
||||
summary: { account: opts.account },
|
||||
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
|
||||
duration_ms: Date.now() - startTime,
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
})
|
||||
process.exit(1)
|
||||
}
|
||||
let id = r.id || r.data?.id
|
||||
if (!id) {
|
||||
const listR = (await loadUser.getUserList({ keyword: opts.account, pageSize: 50 })) as { list?: { id: string; account: string; realName: string }[] }
|
||||
const found = (listR.list || []).find(
|
||||
(d) => d.account === opts.account || d.realName === opts.realName,
|
||||
)
|
||||
id = found?.id
|
||||
}
|
||||
log.info(`✓ 用户创建成功 id=${id}`)
|
||||
if (opts.json) printJson({ ...(r.data as object || r), id })
|
||||
// v2.1+ (2026-07-21): 成功路径落 CommandLog
|
||||
printCommandEnd({
|
||||
await wrapCommand({
|
||||
command: 'user create',
|
||||
appCode: c.appCode,
|
||||
summary: { id, account: opts.account, realName: opts.realName },
|
||||
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.11e+ Phase C1: step machine 校验 (镜像 web user/Form.vue + PS007/008/012/204/EXIST006)
|
||||
const validation = validateUserCreate({
|
||||
account: opts.account,
|
||||
fullName: opts.realName,
|
||||
password: opts.password,
|
||||
roleId: opts.roleId,
|
||||
enabledMark: opts.enabledMark,
|
||||
isCreate: true,
|
||||
})
|
||||
if (!validation.ok) {
|
||||
for (const s of validation.steps) {
|
||||
for (const e of s.errors) {
|
||||
log.error(` ${formatErrorLine(e, { step: s.step, stepName: s.stepName })}`)
|
||||
}
|
||||
}
|
||||
return ctx.fail('step machine 校验失败', { account: opts.account })
|
||||
}
|
||||
log.info(`✓ step machine 校验通过 (${validation.steps.length}/${validation.steps.length})`)
|
||||
// step 0 基础信息 (P0 镜像 web Form.vue schemas)
|
||||
|
||||
// JNPF 接收的 password 是 md5(plain) hex (32 字符), 不是 AES 加密
|
||||
const md5Pwd = encryptByMd5(opts.password)
|
||||
const body: Record<string, unknown> = {
|
||||
account: opts.account,
|
||||
realName: opts.realName,
|
||||
password: md5Pwd,
|
||||
gender: opts.gender || '1',
|
||||
enabledMark: opts.enabledMark || '1',
|
||||
sortCode: parseInt(opts.sortCode || '0', 10),
|
||||
}
|
||||
if (opts.organizeId) body.organizeId = opts.organizeId
|
||||
if (opts.description) body.description = opts.description
|
||||
if (opts.roleId) body.roleId = opts.roleId.split(',')
|
||||
log.info(`loadUser.createUser (account=${opts.account})`)
|
||||
const r = (await loadUser.createUser(body)) as { id?: string; code?: number; msg?: string; data?: { id?: string } }
|
||||
if (r.code !== 200 && r.code !== undefined) {
|
||||
const enhanced = enhanceFromBackend(r.msg || '', 'user', { entity: 'user' })
|
||||
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
|
||||
return ctx.fail(`user create 失败 (code=${r.code}): ${r.msg}`, { account: opts.account })
|
||||
}
|
||||
let id = r.id || r.data?.id
|
||||
if (!id) {
|
||||
const listR = (await loadUser.getUserList({ keyword: opts.account, pageSize: 50 })) as { list?: { id: string; account: string; realName: string }[] }
|
||||
const found = (listR.list || []).find(
|
||||
(d) => d.account === opts.account || d.realName === opts.realName,
|
||||
)
|
||||
id = found?.id
|
||||
}
|
||||
log.info(`✓ 用户创建成功 id=${id}`)
|
||||
if (opts.json) printJson({ ...(r.data as object || r), id })
|
||||
ctx.success({ id, account: opts.account, realName: opts.realName })
|
||||
} catch (e) {
|
||||
ctx.fail(`user create 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
|
||||
+31
-12
@@ -9,10 +9,14 @@ import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { initWebapi, loadUser } from '../../webapi/user.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 buildUserDeleteCommand(): Command {
|
||||
@@ -20,20 +24,35 @@ export function buildUserDeleteCommand(): Command {
|
||||
.description('删除用户 (非超管, v0.11+ 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(1)
|
||||
}
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
await initWebapi(c)
|
||||
log.info(`loadUser.delUser (id=${opts.id})`)
|
||||
const r = (await loadUser.delUser(opts.id)) as { code?: number; msg?: string }
|
||||
if (r.code !== 200 && r.code !== undefined) {
|
||||
log.error(`user delete 失败: ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.id} 已删除`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user 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 跳过确认`, { userId: opts.id })
|
||||
}
|
||||
await initWebapi(c)
|
||||
log.info(`loadUser.delUser (id=${opts.id})`)
|
||||
const r = (await loadUser.delUser(opts.id)) as { code?: number; msg?: string }
|
||||
if (r.code !== 200 && r.code !== undefined) {
|
||||
return ctx.fail(`user delete 失败: ${r.msg}`, { userId: opts.id, code: r.code })
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.id} 已删除`)
|
||||
ctx.success({ userId: opts.id })
|
||||
} catch (e) {
|
||||
ctx.fail(`user delete 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '删除用户 (isAdministrator=1 不可删)',
|
||||
|
||||
+67
-55
@@ -25,12 +25,15 @@ import { log, printJson } from '../../core/log.ts'
|
||||
import { loadToken } from '../../core/config.ts'
|
||||
import { getUserInfoApi } from '../../webapi/user.ts'
|
||||
import { initWebapi as initUserWebapi, loadUser } from '../../webapi/user.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface InfoOpts {
|
||||
/** 后台管理端标志 (0=前台 1=后台), 默认 1 与 web 端后台管理端一致 */
|
||||
backend?: string
|
||||
/** JSON 输出 */
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserInfoCommand(): Command {
|
||||
@@ -38,67 +41,76 @@ export function buildUserInfoCommand(): Command {
|
||||
.description('用户信息查询 (v3.0+ 双入口: 无 id 走 CurrentUser, 有 id 走 web getUserInfo)')
|
||||
.argument('[id]', '用户 id (省略则查 CurrentUser)')
|
||||
.option('--backend <0|1>', '后台管理端标志 (CurrentUser 用, 0=前台 1=后台, 默认 1)', '1')
|
||||
.option('--json', '原始 JSON 输出', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (id: string | undefined, opts: InfoOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
|
||||
// 模式 1: 有 id → 查特定用户详情 (走 webapi/permission/user getUserInfo)
|
||||
if (id) {
|
||||
log.info(`查询用户详情: id=${id}`)
|
||||
await initUserWebapi(c)
|
||||
const r = (await loadUser.getUserInfo(id)) as Record<string, unknown>
|
||||
if (opts.json) {
|
||||
printJson(r)
|
||||
return
|
||||
}
|
||||
log.ok(`✓ 用户详情:`)
|
||||
console.log(` id: ${r.id || '-'}`)
|
||||
console.log(` account: ${r.account || '-'}`)
|
||||
console.log(` realName: ${r.realName || '-'}`)
|
||||
console.log(` roleName: ${r.roleName || '-'}`)
|
||||
console.log(` organize: ${r.organize || '-'}`)
|
||||
console.log(` enabledMark: ${r.enabledMark === undefined ? '-' : r.enabledMark}`)
|
||||
return
|
||||
}
|
||||
await wrapCommand({
|
||||
command: 'user info',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// 模式 1: 有 id → 查特定用户详情 (走 webapi/permission/user getUserInfo)
|
||||
if (id) {
|
||||
log.info(`查询用户详情: id=${id}`)
|
||||
await initUserWebapi(c)
|
||||
const r = (await loadUser.getUserInfo(id)) as Record<string, unknown>
|
||||
if (opts.json) {
|
||||
printJson(r)
|
||||
return ctx.success({ id })
|
||||
}
|
||||
log.ok(`✓ 用户详情:`)
|
||||
console.log(` id: ${r.id || '-'}`)
|
||||
console.log(` account: ${r.account || '-'}`)
|
||||
console.log(` realName: ${r.realName || '-'}`)
|
||||
console.log(` roleName: ${r.roleName || '-'}`)
|
||||
console.log(` organize: ${r.organize || '-'}`)
|
||||
console.log(` enabledMark: ${r.enabledMark === undefined ? '-' : r.enabledMark}`)
|
||||
return ctx.success({ id, account: r.account })
|
||||
}
|
||||
|
||||
// 模式 2: 无 id → 查 CurrentUser (服务器确认当前用户)
|
||||
const token = loadToken()
|
||||
const appCode = token?.appCode || ''
|
||||
if (!appCode) {
|
||||
log.error('无 token 或 appCode, 无法调 CurrentUser')
|
||||
log.info(` 请先: dacli app login --account=admin --password=123456 --appCode=<code>`)
|
||||
process.exit(1)
|
||||
}
|
||||
const isBackend = parseInt(opts.backend || '1', 10)
|
||||
log.info(`查询 CurrentUser: appCode=${appCode}, isBackend=${isBackend}`)
|
||||
// 模式 2: 无 id → 查 CurrentUser (服务器确认当前用户)
|
||||
const token = loadToken()
|
||||
const appCode = token?.appCode || ''
|
||||
if (!appCode) {
|
||||
log.info(` 请先: dacli app login --account=admin --password=123456 --appCode=<code>`)
|
||||
return ctx.fail('无 token 或 appCode, 无法调 CurrentUser')
|
||||
}
|
||||
const isBackend = parseInt(opts.backend || '1', 10)
|
||||
log.info(`查询 CurrentUser: appCode=${appCode}, isBackend=${isBackend}`)
|
||||
|
||||
try {
|
||||
const u = await getUserInfoApi(c, { systemCode: appCode, isBackend })
|
||||
if (opts.json) {
|
||||
printJson(u)
|
||||
return
|
||||
const u = await getUserInfoApi(c, { systemCode: appCode, isBackend })
|
||||
if (opts.json) {
|
||||
printJson(u)
|
||||
return ctx.success({ appCode })
|
||||
}
|
||||
log.ok(`✓ CurrentUser (服务器确认):`)
|
||||
const ui = (u as Record<string, unknown>).userInfo as Record<string, unknown> | undefined
|
||||
if (ui) {
|
||||
console.log(` userId: ${ui.userId || ui.id || '-'}`)
|
||||
console.log(` userAccount: ${ui.userAccount || ui.account || '-'}`)
|
||||
console.log(` userName: ${ui.userName || ui.realName || '-'}`)
|
||||
console.log(` isAdmin: ${ui.isAdministrator || '-'}`)
|
||||
console.log(` systemCode: ${ui.systemCode || appCode}`)
|
||||
console.log(` systemId: ${ui.systemId || '-'}`)
|
||||
console.log(` hasBackend: ${ui.hasBackend || '-'}`)
|
||||
} else {
|
||||
console.log(' (响应无 userInfo 字段, 完整响应见 --json)')
|
||||
printJson(u)
|
||||
}
|
||||
console.log('')
|
||||
log.dim(` 完整响应含 menuList/permissionList/sysConfigInfo, 用 --json 查看`)
|
||||
ctx.success({ appCode })
|
||||
} catch (e) {
|
||||
log.info(` 可能原因: token 过期 (600/601/602) / appCode 不存在`)
|
||||
ctx.fail(`user info 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
log.ok(`✓ CurrentUser (服务器确认):`)
|
||||
const ui = (u as Record<string, unknown>).userInfo as Record<string, unknown> | undefined
|
||||
if (ui) {
|
||||
console.log(` userId: ${ui.userId || ui.id || '-'}`)
|
||||
console.log(` userAccount: ${ui.userAccount || ui.account || '-'}`)
|
||||
console.log(` userName: ${ui.userName || ui.realName || '-'}`)
|
||||
console.log(` isAdmin: ${ui.isAdministrator || '-'}`)
|
||||
console.log(` systemCode: ${ui.systemCode || appCode}`)
|
||||
console.log(` systemId: ${ui.systemId || '-'}`)
|
||||
console.log(` hasBackend: ${ui.hasBackend || '-'}`)
|
||||
} else {
|
||||
console.log(' (响应无 userInfo 字段, 完整响应见 --json)')
|
||||
printJson(u)
|
||||
}
|
||||
console.log('')
|
||||
log.dim(` 完整响应含 menuList/permissionList/sysConfigInfo, 用 --json 查看`)
|
||||
} catch (e) {
|
||||
log.error(`✗ CurrentUser 失败: ${(e as Error).message}`)
|
||||
log.info(` 可能原因: token 过期 (600/601/602) / appCode 不存在`)
|
||||
process.exit(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
installHelpHook(cmd, {
|
||||
|
||||
@@ -11,28 +11,47 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface OnlineKickOpts {
|
||||
token: string
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserOnlineKickCommand(): Command {
|
||||
const cmd = new Command('online-kick')
|
||||
.description('强制下线某 token (admin/self 操作)')
|
||||
.requiredOption('--token <t>', '要踢的 token (从 onlineUser 列表获取)')
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: OnlineKickOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
// 防自踢: 当前登录 token 不能踢自己
|
||||
if (opts.token === c.getCurrentToken()) {
|
||||
log.error('不能踢自己下线 (当前登录 token), 会立即断连')
|
||||
process.exit(1)
|
||||
}
|
||||
const r = await c.del(`/system/OnlineUser/${opts.token}`)
|
||||
if (r.code !== 200) {
|
||||
log.error(`online-kick 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ token=${opts.token.slice(0, 8)}... 已踢下线`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user online-kick',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// 防自踢: 当前登录 token 不能踢自己
|
||||
if (opts.token === c.getCurrentToken()) {
|
||||
return ctx.fail('不能踢自己下线 (当前登录 token), 会立即断连')
|
||||
}
|
||||
const r = await c.del(`/system/OnlineUser/${opts.token}`)
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`online-kick 失败 (code=${r.code}): ${r.msg}`, { code: r.code })
|
||||
}
|
||||
log.info(`✓ token=${opts.token.slice(0, 8)}... 已踢下线`)
|
||||
ctx.success({ token: opts.token.slice(0, 8) + '...' })
|
||||
} catch (e) {
|
||||
ctx.fail(`user online-kick 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '强制下线某 token (admin/self 操作, 防自踢)',
|
||||
|
||||
@@ -13,11 +13,15 @@ import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { encryptByMd5 } from '../../core/crypto.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface ResetPwdOpts {
|
||||
id: string
|
||||
password: string
|
||||
account?: string // 可选, 不传则自动从 user info 拿
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserResetPwdCommand(): Command {
|
||||
@@ -27,35 +31,50 @@ export function buildUserResetPwdCommand(): Command {
|
||||
.requiredOption('--id <id>', '用户 id')
|
||||
.requiredOption('--password <p>', '新明文密码 (dacli 自动 md5 加密, 跟后端 web 端行为一致)')
|
||||
.option('--account <a>', '账号 (可选, 默认从 user info 拿)')
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: ResetPwdOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
// 1. 拿 user account (不传 --account 时自动查, 走 webapi 镜像)
|
||||
let account = opts.account
|
||||
if (!account) {
|
||||
const { initWebapi, loadUser } = await import('../../webapi/user.ts')
|
||||
await initWebapi(c)
|
||||
const info = (await loadUser.getUserInfo(opts.id)) as { account?: string; userAccount?: string }
|
||||
account = info?.account || info?.userAccount
|
||||
if (!account) {
|
||||
log.error(`✗ 拿不到用户 id=${opts.id} 的 account, 显式传 --account=xxx 重试`)
|
||||
process.exit(2)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user resetpwd',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// 1. 拿 user account (不传 --account 时自动查, 走 webapi 镜像)
|
||||
let account = opts.account
|
||||
if (!account) {
|
||||
const { initWebapi, loadUser } = await import('../../webapi/user.ts')
|
||||
await initWebapi(c)
|
||||
const info = (await loadUser.getUserInfo(opts.id)) as { account?: string; userAccount?: string }
|
||||
account = info?.account || info?.userAccount
|
||||
if (!account) {
|
||||
return ctx.fail(`拿不到用户 id=${opts.id} 的 account, 显式传 --account=xxx 重试`, { userId: opts.id })
|
||||
}
|
||||
log.dim(`自动从 user info 拿 account=${account}`)
|
||||
}
|
||||
// 2. md5 算两次 (userPassword + validatePassword, 镜像 web)
|
||||
const pwdHash = encryptByMd5(opts.password)
|
||||
// 3. 调重置端点
|
||||
const r = await c.postJson(`/permission/Users/${opts.id}/Actions/ResetPassword`, {
|
||||
id: opts.id,
|
||||
account,
|
||||
userPassword: pwdHash,
|
||||
validatePassword: pwdHash,
|
||||
})
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`user resetpwd 失败: ${r.msg}`, { userId: opts.id, code: r.code })
|
||||
}
|
||||
log.ok(`✓ 用户 id=${opts.id} (account=${account}) 密码已重置`)
|
||||
ctx.success({ userId: opts.id, account })
|
||||
} catch (e) {
|
||||
ctx.fail(`user resetpwd 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
log.dim(`自动从 user info 拿 account=${account}`)
|
||||
}
|
||||
// 2. md5 算两次 (userPassword + validatePassword, 镜像 web)
|
||||
const pwdHash = encryptByMd5(opts.password)
|
||||
// 3. 调重置端点
|
||||
const r = await c.postJson(`/permission/Users/${opts.id}/Actions/ResetPassword`, {
|
||||
id: opts.id,
|
||||
account,
|
||||
userPassword: pwdHash,
|
||||
validatePassword: pwdHash,
|
||||
})
|
||||
if (r.code !== 200) {
|
||||
log.error(`user resetpwd 失败: ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.ok(`✓ 用户 id=${opts.id} (account=${account}) 密码已重置`)
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '重置用户密码 (admin 操作, 镜像 web 端 ResetPassword.vue)',
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface SocialsItem {
|
||||
name?: string
|
||||
@@ -22,6 +23,9 @@ interface SocialsUnbindOpts {
|
||||
userId: string
|
||||
socialsId?: string
|
||||
list?: boolean
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserSocialsUnbindCommand(): Command {
|
||||
@@ -30,36 +34,50 @@ export function buildUserSocialsUnbindCommand(): Command {
|
||||
.requiredOption('--userId <uid>', '用户 id')
|
||||
.option('--socialsId <sid>', '社交账号 entity.id (web 端 entity.id)')
|
||||
.option('--list', '列出该用户的所有社交账号绑定, 不解绑', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: SocialsUnbindOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
|
||||
// Step 1: 查绑定列表
|
||||
const listRes = await c.get<SocialsItem[]>('/permission/socials', {
|
||||
userId: opts.userId,
|
||||
})
|
||||
if (listRes.code !== 200) {
|
||||
log.error(`socials 列表失败 (code=${listRes.code}): ${listRes.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const list = listRes.data || []
|
||||
if (opts.list || !opts.socialsId) {
|
||||
log.info(`用户 id=${opts.userId} 共 ${list.length} 个社交账号绑定`)
|
||||
for (const it of list) {
|
||||
console.log(` ${it.entity?.id || '(无 entity)'} ${it.name} (${it.description || ''})`)
|
||||
}
|
||||
if (!opts.socialsId) {
|
||||
log.info('用 --socialsId=<id> 解绑指定账号')
|
||||
}
|
||||
return
|
||||
}
|
||||
await wrapCommand({
|
||||
command: 'user socials-unbind',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// Step 1: 查绑定列表
|
||||
const listRes = await c.get<SocialsItem[]>('/permission/socials', {
|
||||
userId: opts.userId,
|
||||
})
|
||||
if (listRes.code !== 200) {
|
||||
return ctx.fail(`socials 列表失败 (code=${listRes.code}): ${listRes.msg}`, { userId: opts.userId, code: listRes.code })
|
||||
}
|
||||
const list = listRes.data || []
|
||||
if (opts.list || !opts.socialsId) {
|
||||
log.info(`用户 id=${opts.userId} 共 ${list.length} 个社交账号绑定`)
|
||||
for (const it of list) {
|
||||
console.log(` ${it.entity?.id || '(无 entity)'} ${it.name} (${it.description || ''})`)
|
||||
}
|
||||
if (!opts.socialsId) {
|
||||
log.info('用 --socialsId=<id> 解绑指定账号')
|
||||
}
|
||||
return ctx.success({ userId: opts.userId, total: list.length })
|
||||
}
|
||||
|
||||
// Step 2: 解绑
|
||||
const r = await c.del(`/permission/socials/${opts.userId}/${opts.socialsId}`)
|
||||
if (r.code !== 200) {
|
||||
log.error(`socials-unbind 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.userId} 社交账号 socialsId=${opts.socialsId} 已解绑`)
|
||||
// Step 2: 解绑
|
||||
const r = await c.del(`/permission/socials/${opts.userId}/${opts.socialsId}`)
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`socials-unbind 失败 (code=${r.code}): ${r.msg}`, { userId: opts.userId, code: r.code })
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.userId} 社交账号 socialsId=${opts.socialsId} 已解绑`)
|
||||
ctx.success({ userId: opts.userId, socialsId: opts.socialsId })
|
||||
} catch (e) {
|
||||
ctx.fail(`user socials-unbind 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '解绑社交账号 (admin 操作)',
|
||||
|
||||
+63
-35
@@ -9,14 +9,18 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.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 UpdateOpts {
|
||||
id: string
|
||||
fields: string
|
||||
expectedAccount?: string
|
||||
force?: boolean
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserUpdateCommand(): Command {
|
||||
@@ -26,42 +30,66 @@ export function buildUserUpdateCommand(): Command {
|
||||
.requiredOption('--fields <json>', '要更新的字段 JSON, 如 {"realName":"新名","email":"x@y"}')
|
||||
.option('--expected-account <a>', 'v0.11e+ Phase A2: 校验 account 未变 (防 AI 误覆盖)')
|
||||
.option('--force', 'v0.11e+ Phase A2: 跳过 dirty check', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: UpdateOpts) => {
|
||||
// === step 0 (校验 --fields JSON + 必填字段) ===
|
||||
let fields: Record<string, unknown>
|
||||
try {
|
||||
fields = JSON.parse(opts.fields)
|
||||
} catch (e) {
|
||||
log.error(`JSON 解析失败: ${(e as Error).message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// v0.11e+ Phase A2: dirty check
|
||||
// === step 1 dirty check 防 AI session 误覆盖 ===
|
||||
const dirtyResult = dirtyCheck({
|
||||
expectedEnCode: opts.expectedAccount,
|
||||
force: opts.force,
|
||||
current: {
|
||||
enCode: fields.account as string | undefined,
|
||||
type: 'role', // 借用 type union (user 不在原 3 类型中, role 接近)
|
||||
},
|
||||
id: opts.id,
|
||||
})
|
||||
if (!dirtyResult.ok) {
|
||||
dirtyCheckFailAndExit(dirtyResult, { type: 'role', id: opts.id, current: { enCode: fields.account as string | undefined } }, log.error)
|
||||
} else if (dirtyResult.skipped) {
|
||||
log.info(`⚠ dirty check 已 --force 跳过`)
|
||||
}
|
||||
|
||||
// === step 2 PUT 后端API ===
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
const r = await c.putJson(`/permission/Users/${opts.id}`, fields)
|
||||
if (r.code !== 200) {
|
||||
const enhanced = enhanceFromBackend(r.msg || '', 'user', { entity: 'user' })
|
||||
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.id} 已更新: ${Object.keys(fields).join(', ')}`)
|
||||
|
||||
await wrapCommand({
|
||||
command: 'user update',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// === step 0 (校验 --fields JSON + 必填字段) ===
|
||||
let fields: Record<string, unknown>
|
||||
try {
|
||||
fields = JSON.parse(opts.fields)
|
||||
} catch (e) {
|
||||
return ctx.fail(`JSON 解析失败: ${(e as Error).message}`, { id: opts.id })
|
||||
}
|
||||
|
||||
// v0.11e+ Phase A2: dirty check
|
||||
// === step 1 dirty check 防 AI session 误覆盖 ===
|
||||
const dirtyResult = dirtyCheck({
|
||||
expectedEnCode: opts.expectedAccount,
|
||||
force: opts.force,
|
||||
current: {
|
||||
enCode: fields.account as string | undefined,
|
||||
type: 'role', // 借用 type union (user 不在原 3 类型中, 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: fields.account as string | undefined } }, log.error)
|
||||
} catch (e) {
|
||||
if (e instanceof DirtyCheckError) {
|
||||
return ctx.fail(e.message, { id: opts.id, type: 'user', errorCount: e.errorCount })
|
||||
}
|
||||
throw e
|
||||
}
|
||||
} else if (dirtyResult.skipped) {
|
||||
log.info(`⚠ dirty check 已 --force 跳过`)
|
||||
}
|
||||
|
||||
// === step 2 PUT 后端API ===
|
||||
const r = await c.putJson(`/permission/Users/${opts.id}`, fields)
|
||||
if (r.code !== 200) {
|
||||
const enhanced = enhanceFromBackend(r.msg || '', 'user', { entity: 'user' })
|
||||
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
|
||||
return ctx.fail(`user update 失败 (code=${r.code}): ${r.msg}`, { id: opts.id, code: r.code })
|
||||
}
|
||||
log.info(`✓ 用户 id=${opts.id} 已更新: ${Object.keys(fields).join(', ')}`)
|
||||
ctx.success({ id: opts.id, updatedFields: Object.keys(fields) })
|
||||
} catch (e) {
|
||||
ctx.fail(`user update 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '编辑用户 (admin 操作, PUT /Users/{id} + v0.11e+ dirty check)',
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
|
||||
interface WorkItem {
|
||||
id?: string
|
||||
@@ -30,6 +31,9 @@ interface WorkHandoverOpts {
|
||||
excludeTasks?: boolean
|
||||
excludeFlows?: boolean
|
||||
excludeApps?: boolean
|
||||
json?: boolean
|
||||
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
|
||||
verbose?: boolean
|
||||
}
|
||||
|
||||
export function buildUserWorkHandoverCommand(): Command {
|
||||
@@ -40,39 +44,53 @@ export function buildUserWorkHandoverCommand(): Command {
|
||||
.option('--excludeTasks', '排除流程待办', false)
|
||||
.option('--excludeFlows', '排除流程实例', false)
|
||||
.option('--excludeApps', '排除我的应用', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: WorkHandoverOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
|
||||
// Step 1: 查可交接内容
|
||||
const workRes = await c.get<WorkByUserResp>('/permission/Users/getWorkByUser', {
|
||||
fromId: opts.fromUserId,
|
||||
})
|
||||
if (workRes.code !== 200) {
|
||||
log.error(`getWorkByUser 失败 (code=${workRes.code}): ${workRes.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const work = workRes.data || {}
|
||||
const flowTaskList = opts.excludeTasks ? [] : (work.flowTask || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
const flowList = opts.excludeFlows ? [] : (work.flow || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
const appList = opts.excludeApps ? [] : (work.app || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
await wrapCommand({
|
||||
command: 'user workHandover',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// Step 1: 查可交接内容
|
||||
const workRes = await c.get<WorkByUserResp>('/permission/Users/getWorkByUser', {
|
||||
fromId: opts.fromUserId,
|
||||
})
|
||||
if (workRes.code !== 200) {
|
||||
return ctx.fail(`getWorkByUser 失败 (code=${workRes.code}): ${workRes.msg}`, { fromUserId: opts.fromUserId, code: workRes.code })
|
||||
}
|
||||
const work = workRes.data || {}
|
||||
const flowTaskList = opts.excludeTasks ? [] : (work.flowTask || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
const flowList = opts.excludeFlows ? [] : (work.flow || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
const appList = opts.excludeApps ? [] : (work.app || []).map((x) => x.id).filter(Boolean) as string[]
|
||||
|
||||
log.info(
|
||||
`查询到: ${flowTaskList.length} 待办, ${flowList.length} 流程, ${appList.length} 应用 (将全交接, 除非 --exclude*)`,
|
||||
)
|
||||
log.info(
|
||||
`查询到: ${flowTaskList.length} 待办, ${flowList.length} 流程, ${appList.length} 应用 (将全交接, 除非 --exclude*)`,
|
||||
)
|
||||
|
||||
// Step 2: 执行交接
|
||||
const r = await c.postJson('/permission/Users/workHandover', {
|
||||
fromId: opts.fromUserId,
|
||||
handoverUser: opts.toUserId,
|
||||
flowTaskList,
|
||||
flowList,
|
||||
appList,
|
||||
// Step 2: 执行交接
|
||||
const r = await c.postJson('/permission/Users/workHandover', {
|
||||
fromId: opts.fromUserId,
|
||||
handoverUser: opts.toUserId,
|
||||
flowTaskList,
|
||||
flowList,
|
||||
appList,
|
||||
})
|
||||
if (r.code !== 200) {
|
||||
return ctx.fail(`workHandover 失败 (code=${r.code}): ${r.msg}`, { fromUserId: opts.fromUserId, code: r.code })
|
||||
}
|
||||
log.info(`✓ 工作已从 id=${opts.fromUserId} 交接给 id=${opts.toUserId}`)
|
||||
ctx.success({ fromUserId: opts.fromUserId, toUserId: opts.toUserId, tasks: flowTaskList.length, flows: flowList.length, apps: appList.length })
|
||||
} catch (e) {
|
||||
ctx.fail(`user workHandover 失败: ${(e as Error).message?.slice(0, 200)}`)
|
||||
}
|
||||
})
|
||||
if (r.code !== 200) {
|
||||
log.error(`workHandover 失败 (code=${r.code}): ${r.msg}`)
|
||||
process.exit(1)
|
||||
}
|
||||
log.info(`✓ 工作已从 id=${opts.fromUserId} 交接给 id=${opts.toUserId}`)
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '工作交接 (admin 操作, 默认全交接)',
|
||||
|
||||
Reference in new issue
Block a user