Files
dacli/src/commands/role/create.ts
T
sswandClaude f840f2961a fix: Round 12 drift batch 1 (enCode autoStrip + DI uniqueness + report cells)
Round 12 drift loop on ts2 (5 random baseline per module) surfaced:

- BS-新38: 5/8 modules fail BS-56 when --enCode='round12-foo' contains '-'.
  Add autoStripEnCode() helper + apply at 7 create.ts action entries.
  workflow/_validate.ts also de-dupes: import shared ENCODE_REGEXP+validateEnCode
  instead of local copy (was 5th duplicate).

- BS-新39: 4/5 DI hit 'name cannot be repeated' (BS-47 EXIST002) at backend.
  Root cause: di/create.ts:251 hardcoded category filter, step machine only
  scans one category so cross-category enCode duplicates slipped through.
  Fix: remove hardcoded filter, scan all DIs platform-wide. Better error msg.

- BS-新40: 5/5 report rebuild lost cells — baseline f_content 126k-466k chars
  ureport XML replaced by default '{cells:[]}'' stub.
  Fix: add --from-json-file option (mirrors di/create.ts pattern), reads full
  baseline body and overrides required fields.

Tests: 28/28 PASS
- tests/integration/drift/round12-cross-module.spec.ts (Round 12 sweep)
- tests/integration/drift/round12-fix-batch1.spec.ts (batch 1 regression)

Docs: docs/drift/2026-07-15-round12-summary.md + ...-fix-batch1.md

Co-Authored-By: Claude <[email protected]>
2026-07-15 10:11:12 +08:00

171 lines
7.0 KiB
TypeScript

/**
* commands/role/create.ts — 新建角色
*
* v0.14+ webapi 化 (loadRole.create + loadRole.getRoleList for step machine)
* 替代 v0.10/v0.13 直接 c.postJson / c.get
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { validateRoleCreate } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { initWebapi, loadRole } from '../../webapi/role.ts'
import { autoStripEnCode } from '../_encode_validator.ts'
interface CreateOpts {
fullName: string
enCode: string
type?: string
userIds?: string
json?: boolean
}
export function buildRoleCreateCommand(): Command {
const cmd = new Command('create')
.description('新建角色 (P1 权限三角核心, v0.14+ webapi)')
.requiredOption('--fullName <name>', '角色名称')
.requiredOption('--enCode <code>', '角色编码')
.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('--json', '原始 JSON 输出', false)
.action(async (opts: CreateOpts) => {
const c = await JnpfClient.fromToken()
await initWebapi(c)
// v0.21+ (Round 12 BS-新38): enCode 含 `-`/`_` 触发 BS-56 fail 时自动 strip + WARN
// 修法: enCode 默认接受 `round12-foo` 类格式, 自动 → `round12foo`, 让 AI 一次提交就跑通
const _encStrip = autoStripEnCode(opts.enCode)
if (_encStrip.wasStriped) {
log.warn(`! autoStrip enCode: ${_encStrip.original} → ${_encStrip.value} (BS-新38, 下次别用 - 或 _)`)
opts.enCode = _encStrip.value
}
// 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' })}`)
process.exit(1)
}
let id = r.data?.id
if (!id) {
const listR = (await loadRole.getRoleList({
keyword: opts.enCode,
pageSize: '50',
})) as { data?: { list?: { id: string; enCode: string; fullName: string }[] } }
const found = (listR.data?.list || []).find(
(d) => d.enCode === opts.enCode || d.fullName === opts.fullName,
)
id = found?.id
}
log.info(`✓ 角色创建成功 id=${id}${userIdsArray.length > 0 ? ` (含 ${userIdsArray.length} 个用户绑定)` : ''}`)
if (opts.json) printJson({ ...(r.data as object), id })
})
installAiHelpHook(cmd, {
purpose: '新建角色 (P1 权限三角核心). v0.11d+ 加 step machine 校验 (3 step 镜像 web role/Form.vue + 后端 RoleController.create, BS-47 唯一性预校验, 约束字段联动校验, 聚合错误). v0.11e+ Phase A3 加 --user-ids 跨命令事务 (建角色后批量绑用户, 镜像 web roleRelationService.create).',
required: { '--fullName': '角色名称', '--enCode': '角色编码' },
optional: { '--type': '0=全局 1=业务', '--user-ids': '关联用户 id 列表 (A3 跨命令事务)' },
example: [
'dacli role create --fullName=测试角色 --enCode=dacli_test_role',
'dacli role create --fullName=运营 --enCode=ops --type=1 --user-ids=1,2,3 (A3: 建角色 + 批量绑用户)',
],
source: {
web: 'web/apps/jnpf-web-apps-main/src/views/permission/role/Form.vue (后端: jnpf/.../RoleController.java:124-161)',
api: 'POST /api/permission/Role',
ref: 'web/.../api/permission/role.ts create()',
},
notes: [
'v0.11d+ step machine (镜像 web role/Form.vue:33-108 schemas + 后端 RoleController.create L124-161):',
' step 0 基础信息: fullName 必填 + enCode 正则 + type ∈ {0,1} + enabledMark + sortCode',
' step 1 约束: isCondition + constraintType + 联动校验 (互斥/基数/先决互斥)',
' step 2 唯一性 (BS-47): enCode 全平台唯一 (EXIST002) + fullName 按 type 分类 (EXIST001)',
'v0.14+ 改用 webapi 镜像 (loadRole.create + loadRole.getRoleList for step machine)',
],
})
return cmd
}
/**
* v0.11d+ Phase 3.4: role create step machine 校验 (3 步镜像)
* 在发 API 前暴露问题, 聚合错误一次报
*
* 镜像原型:
* - web permission/role/Form.vue:33-108 schemas (fullName/enCode/isCondition/constraintType/...)
* - 后端 RoleController.java:124-161 create (EXIST001/002 + 约束判断)
*
* v0.14+ webapi 化: 用 loadRole.getRoleList 拉已存在 role
*/
async function runRoleStepMachine(
_c: JnpfClient,
opts: {
fullName?: string
enCode?: string
type?: string
enabledMark?: number
sortCode?: number
},
): Promise<void> {
// 1. 拉已存在 role (供 step 2 唯一性预校验, BS-47)
let existingRoles: Array<{ fullName?: string; enCode?: string; type?: number | string }> = []
try {
const r = (await loadRole.getRoleList({
currentPage: 1,
pageSize: 1000,
})) as { data?: { list?: Array<any> } }
const list = (r.data as { list?: Array<any> })?.list || []
existingRoles = list.map((role: any) => ({
fullName: role.fullName,
enCode: role.enCode,
type: role.type,
}))
} catch {
// 拉列表失败不阻断 (step 2 跳过查重)
}
// 2. 跑 3 step 校验
const result = validateRoleCreate({
...opts,
type: opts.type !== undefined ? Number(opts.type) : undefined,
existingRoles,
})
// 3. 输出结果 (聚合错误 / 全部通过)
if (!result.ok) {
const allErrors = result.steps.flatMap((s) =>
s.errors.map((e) => ({ step: s.step, stepName: s.stepName, ...e })),
)
log.error(`✗ step machine 校验失败 (${allErrors.length} 个错误):`)
for (const e of allErrors) {
log.error(` [step ${e.step} ${e.stepName}] ${e.field || '?'}: ${e.message}`)
}
process.exit(1)
}
log.info(`✓ step machine 校验通过 (3/3): enCode=${opts.enCode}`)
}