Files
dacli/src/commands/user/create.ts
T
sswandClaude c6763c4129 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]>
2026-07-21 20:41:02 +08:00

145 lines
6.4 KiB
TypeScript

/**
* commands/user/create.ts — 新建用户
*
* v0.11+ Phase 2: webapi 化 (loadUser.createUser + getUserList)
* 替代 v0.10 直接 c.postJson/c.get
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { encryptByMd5 } from '../../core/crypto.ts'
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, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 + CommandLog; v2.2+ wrapCommand 收口 5c
interface CreateOpts {
account: string
realName: string
password: string
organizeId?: string
gender?: string
enabledMark?: string
sortCode?: string
description?: string
roleId?: string
json?: boolean
verbose?: boolean
}
export function buildUserCreateCommand(): Command {
const cmd = new Command('create')
.description('新建用户 (P1 权限三角 2 号, v0.11+ webapi + v0.11e+ step machine)')
.requiredOption('--account <a>', '账号 (登录名)')
.requiredOption('--realName <n>', '真实姓名')
.requiredOption('--password <p>', '明文密码 (后端会自动 md5 加密)')
.option('--organizeId <id>', '所属组织 id (决策 7: 必须)')
.option('--gender <g>', '性别: 1=男 2=女 3=未知', '1')
.option('--enabledMark <m>', '状态: 0=禁用 1=启用 2=锁定', '1')
.option('--sortCode <n>', '排序', '0')
.option('--description <d>', '说明')
.option('--roleId <id>', 'v0.11e+ Phase C1: 角色 id (PS012 必填, 镜像 web user/Form.vue)')
addOutputOptions(cmd)
.action(async (opts: CreateOpts) => {
// 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
const startTime = Date.now()
await initWebapi(c)
// v2.1+ (2026-07-21): 命令级 auto-fix pipeline (account ↔ enCode, realName ↔ fullName)
const fixCtx = await fetchExistingLists(c, c.appCode)
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, {
...fixCtx,
fieldAliases: { enCode: 'account', fullName: 'realName' },
})
if (cmdFix.silent.length > 0) {
Object.assign(opts, cmdFix.opts)
}
await wrapCommand({
command: 'user create',
appCode: c.appCode,
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, {
purpose: '新建用户 (P1 权限三角 2 号)',
required: { '--account': '账号', '--realName': '真实姓名', '--password': '明文密码' },
optional: { '--organizeId': '所属组织 id (决策 7 必填)' },
example:
'dacli user create --account=test001 --realName="测试用户" --password=123456 --organizeId=<orgId>',
source: {
web: 'web/apps/jnpf-web-apps-main/src/views/permission/user/Form.vue',
api: 'POST /api/permission/Users',
ref: 'doc/v0.8-endpoints.md §2.2',
},
notes: [
'**决策 7**: 用户必须绑组织 (organizeId 必填), 否则报"组织不存在"',
'**web Form.vue**: password = md5(plain), 不是 AES 加密 (与 datasource 不同)',
],
})
return cmd
}