From 808de2c84553cac59d5ccd6a9f1bc79b217e6d60 Mon Sep 17 00:00:00 2001 From: ssw Date: Sat, 13 Jun 2026 00:44:40 +0800 Subject: [PATCH] =?UTF-8?q?W10:=20=E6=9D=83=E9=99=90=E4=B8=89=E8=A7=92=20(?= =?UTF-8?q?role+user+org,=2011=20=E5=AD=90)=20+=20permission-triangle=20E2?= =?UTF-8?q?E=20PASS=20+=204=20baseline=20+=2015=20=E5=8D=95=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../skills/dacli-ts/examples/baseline/org.sh | 38 +++++++ .../examples/baseline/permission-triangle.sh | 88 ++++++++++++++ .../skills/dacli-ts/examples/baseline/role.sh | 37 ++++++ .../skills/dacli-ts/examples/baseline/user.sh | 23 ++++ src/cli.ts | 9 ++ src/commands/org/create.ts | 70 ++++++++++++ src/commands/org/index.ts | 24 ++++ src/commands/org/list.ts | 77 +++++++++++++ src/commands/org/tree.ts | 76 +++++++++++++ src/commands/role/assign.ts | 59 ++++++++++ src/commands/role/create.ts | 68 +++++++++++ src/commands/role/delete.ts | 45 ++++++++ src/commands/role/index.ts | 27 +++++ src/commands/role/list.ts | 73 ++++++++++++ src/commands/user/create.ts | 79 +++++++++++++ src/commands/user/delete.ts | 45 ++++++++ src/commands/user/index.ts | 27 +++++ src/commands/user/list.ts | 76 +++++++++++++ src/commands/user/reset-pwd.ts | 45 ++++++++ tests/unit/role-user-org.test.ts | 107 ++++++++++++++++++ 20 files changed, 1093 insertions(+) create mode 100755 .claude/skills/dacli-ts/examples/baseline/org.sh create mode 100755 .claude/skills/dacli-ts/examples/baseline/permission-triangle.sh create mode 100755 .claude/skills/dacli-ts/examples/baseline/role.sh create mode 100755 .claude/skills/dacli-ts/examples/baseline/user.sh create mode 100644 src/commands/org/create.ts create mode 100644 src/commands/org/index.ts create mode 100644 src/commands/org/list.ts create mode 100644 src/commands/org/tree.ts create mode 100644 src/commands/role/assign.ts create mode 100644 src/commands/role/create.ts create mode 100644 src/commands/role/delete.ts create mode 100644 src/commands/role/index.ts create mode 100644 src/commands/role/list.ts create mode 100644 src/commands/user/create.ts create mode 100644 src/commands/user/delete.ts create mode 100644 src/commands/user/index.ts create mode 100644 src/commands/user/list.ts create mode 100644 src/commands/user/reset-pwd.ts create mode 100644 tests/unit/role-user-org.test.ts diff --git a/.claude/skills/dacli-ts/examples/baseline/org.sh b/.claude/skills/dacli-ts/examples/baseline/org.sh new file mode 100755 index 0000000..3b183b3 --- /dev/null +++ b/.claude/skills/dacli-ts/examples/baseline/org.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# examples/baseline/org.sh — org 端到端 baseline 验证 +set -e + +cd "$(dirname "$0")/../../../../.." + +echo "=== dacli org baseline ===" + +# 1. list +LIST_OUT=$(npx tsx src/cli.ts org list 2>&1) +# 兼容数字 id 和 UUID id (截断到 30 字符, 短横线 + 字母) +COUNT=$(echo "$LIST_OUT" | grep -E "^\s*[0-9a-fA-F][0-9a-fA-F-]+" | wc -l) +echo " list: $COUNT 个根组织" +if [ "$COUNT" -lt 1 ]; then + echo " ✗ baseline FAIL: 根组织数 < 1" + echo " Output: $LIST_OUT" + exit 1 +fi +echo " ✓ list PASS" + +# 2. tree +npx tsx src/cli.ts org tree 2>&1 | head -3 +echo " ✓ tree PASS" + +# 3. create — 兜底建一个子部门 +ROOT_ID=$(echo "$LIST_OUT" | grep -E "^\s*[0-9a-fA-F][0-9a-fA-F-]+" | head -1 | awk '{print $1}') +TS=$(date +%s) +echo "" +echo " 测试: create 子部门 dacli_dept_$TS" +npx tsx src/cli.ts org create \ + --fullName="dacli_dept_$TS" \ + --enCode="dacli_dept_$TS" \ + --parentId="$ROOT_ID" \ + --category=department 2>&1 | head -3 +echo " ✓ create PASS" + +echo "" +echo "=== baseline PASS: org list+tree+create 端到端 ===" diff --git a/.claude/skills/dacli-ts/examples/baseline/permission-triangle.sh b/.claude/skills/dacli-ts/examples/baseline/permission-triangle.sh new file mode 100755 index 0000000..ecf45f8 --- /dev/null +++ b/.claude/skills/dacli-ts/examples/baseline/permission-triangle.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# examples/baseline/permission-triangle.sh — 权限三角 E2E 验证 +# +# 决策 7: org (3 号) → user (2 号) → role (1 号) → assign +# 反模式: 先建用户再建组织 → user organizeId=null 报"组织不存在" +# +# 用法: bash examples/baseline/permission-triangle.sh +set -e + +cd "$(dirname "$0")/../../../../.." + +echo "=== dacli 权限三角 E2E baseline ===" + +# 0. 找根公司 ID (用 org list) +ROOT_ID=$(npx tsx src/cli.ts org list 2>&1 | grep -E "公司" | head -1 | awk '{print $1}') +if [ -z "$ROOT_ID" ]; then + echo " ✗ baseline FAIL: 找不到根公司" + exit 1 +fi +echo " 根公司: $ROOT_ID" + +# 1. 建组织 (决策 7 三号) +TS=$(date +%s) +echo "" +echo "1) 创建子部门: dacli_dept_$TS" +npx tsx src/cli.ts org create \ + --fullName="dacli_dept_$TS" \ + --enCode="dacli_dept_$TS" \ + --parentId="$ROOT_ID" \ + --category=department 2>&1 | head -3 +sleep 1 +DEPT_ID=$(npx tsx src/cli.ts org list --parentId="$ROOT_ID" 2>&1 | grep "dacli_dept_$TS" | head -1 | awk '{print $1}') +if [ -z "$DEPT_ID" ]; then + echo " ✗ baseline FAIL: 建组织后 list 找不到" + exit 1 +fi +echo " ✓ org create PASS id=$DEPT_ID" + +# 2. 建用户 (决策 7 二号) +echo "" +echo "2) 创建用户: dacli_$TS (绑 org)" +npx tsx src/cli.ts user create \ + --account="dacli_$TS" \ + --realName="dacli_user_$TS" \ + --password=Test1234 \ + --organizeId="$DEPT_ID" \ + --gender=1 2>&1 | head -3 +sleep 1 +USER_ID=$(npx tsx src/cli.ts user list 2>&1 | grep "dacli_$TS" | head -1 | awk '{print $1}') +if [ -z "$USER_ID" ]; then + echo " ✗ baseline FAIL: 建用户后 list 找不到" + exit 1 +fi +echo " ✓ user create PASS id=$USER_ID" + +# 3. 建角色 (决策 7 一号) +echo "" +echo "3) 创建角色: dacli_role_$TS" +npx tsx src/cli.ts role create \ + --fullName="dacli_role_$TS" \ + --enCode="dacli_role_$TS" 2>&1 | head -3 +sleep 1 +ROLE_ID=$(npx tsx src/cli.ts role list 2>&1 | grep "dacli_role_$TS" | head -1 | awk '{print $1}') +if [ -z "$ROLE_ID" ]; then + echo " ✗ baseline FAIL: 建角色后 list 找不到" + exit 1 +fi +echo " ✓ role create PASS id=$ROLE_ID" + +# 4. 角色赋用户 +echo "" +echo "4) 角色赋用户" +npx tsx src/cli.ts role assign --roleId="$ROLE_ID" --userIds="$USER_ID" --action=add 2>&1 | head -3 +if ! npx tsx src/cli.ts role assign --roleId="$ROLE_ID" --userIds="$USER_ID" --action=add 2>&1 | grep -q "OK"; then + echo " ✗ baseline FAIL: 角色赋权失败" + exit 1 +fi +echo " ✓ role assign PASS" + +# 5. 清理 +echo "" +echo "5) 清理: 删 role/user" +npx tsx src/cli.ts role delete --id="$ROLE_ID" --yes 2>&1 | head -2 +npx tsx src/cli.ts user delete --id="$USER_ID" --yes 2>&1 | head -2 +echo " ✓ 清理 OK" + +echo "" +echo "=== baseline PASS: 权限三角 E2E 跑通 (org → user → role → assign) ===" diff --git a/.claude/skills/dacli-ts/examples/baseline/role.sh b/.claude/skills/dacli-ts/examples/baseline/role.sh new file mode 100755 index 0000000..b88983c --- /dev/null +++ b/.claude/skills/dacli-ts/examples/baseline/role.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# examples/baseline/role.sh — role 端到端 baseline 验证 +set -e + +cd "$(dirname "$0")/../../../../.." + +echo "=== dacli role baseline ===" + +# 1. list +LIST_OUT=$(npx tsx src/cli.ts role list 2>&1) +COUNT=$(echo "$LIST_OUT" | grep -E "^\s*[0-9]+\s+" | wc -l) +echo " list: $COUNT 个角色" +if [ "$COUNT" -lt 1 ]; then + echo " ✗ baseline FAIL: 角色数 < 1" + exit 1 +fi +echo " ✓ list PASS" + +# 2. create +TS=$(date +%s) +NAME="dacli_role_$TS" +echo "" +echo " 测试: create $NAME" +npx tsx src/cli.ts role create --fullName="$NAME" --enCode="$NAME" 2>&1 | head -3 +sleep 1 +ROLE_ID=$(npx tsx src/cli.ts role list 2>&1 | grep "dacli_role_$TS" | head -1 | awk '{print $1}') +if [ -z "$ROLE_ID" ]; then + echo " ✗ baseline FAIL: 建角色后 list 找不到" + exit 1 +fi +echo " ✓ create PASS id=$ROLE_ID" + +# 3. delete (清理) +npx tsx src/cli.ts role delete --id="$ROLE_ID" --yes 2>&1 | head -2 + +echo "" +echo "=== baseline PASS: role list+create 端到端 ===" diff --git a/.claude/skills/dacli-ts/examples/baseline/user.sh b/.claude/skills/dacli-ts/examples/baseline/user.sh new file mode 100755 index 0000000..326b1d0 --- /dev/null +++ b/.claude/skills/dacli-ts/examples/baseline/user.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# examples/baseline/user.sh — user 端到端 baseline 验证 +set -e + +cd "$(dirname "$0")/../../../../.." + +echo "=== dacli user baseline ===" + +# 1. list +LIST_OUT=$(npx tsx src/cli.ts user list 2>&1) +COUNT=$(echo "$LIST_OUT" | grep -E "^\s*[0-9]+\s+" | wc -l) +echo " list: $COUNT 个用户" +if [ "$COUNT" -lt 1 ]; then + echo " ✗ baseline FAIL: 用户数 < 1" + exit 1 +fi +echo " ✓ list PASS" + +# 注: user create 必须绑组织, 已在 permission-triangle.sh 端到端验证 +# 这里只验 list (user create 单独跑要带 organizeId) + +echo "" +echo "=== baseline PASS: user list ===" diff --git a/src/cli.ts b/src/cli.ts index 695710f..6df37c7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -25,6 +25,9 @@ import { buildPortalCommand } from './commands/portal/index.ts' import { buildBigscreenCommand } from './commands/bigscreen/index.ts' import { buildAppCommand } from './commands/app/index.ts' import { buildPrintCommand } from './commands/print/index.ts' +import { buildRoleCommand } from './commands/role/index.ts' +import { buildUserCommand } from './commands/user/index.ts' +import { buildOrgCommand } from './commands/org/index.ts' import { maybeInterceptAiHelp } from './core/help.ts' import { log } from './core/log.ts' import { DacliError } from './core/types.ts' @@ -60,6 +63,12 @@ program.addCommand(buildBigscreenCommand()) program.addCommand(buildAppCommand()) // v0.8 W9-D3 新增 1 父命令 program.addCommand(buildPrintCommand()) +// v0.8 W10-D1 新增 1 父命令 +program.addCommand(buildRoleCommand()) +// v0.8 W10-D2 新增 1 父命令 +program.addCommand(buildUserCommand()) +// v0.8 W10-D3 新增 1 父命令 +program.addCommand(buildOrgCommand()) // ----- main ----- // AI flag 拦截 (在 parse 之前, 避免 requiredOption 校验失败) diff --git a/src/commands/org/create.ts b/src/commands/org/create.ts new file mode 100644 index 0000000..adb8d96 --- /dev/null +++ b/src/commands/org/create.ts @@ -0,0 +1,70 @@ +/** + * commands/org/create.ts — 新建组织 + * + * API: POST /api/permission/Organize + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface CreateOpts { + fullName: string + enCode: string + parentId?: string + category?: string + json?: boolean +} + +export function buildOrgCreateCommand(): Command { + const cmd = new Command('create') + .description('新建组织/部门 (P1 权限三角 3 号, 先建组织再建用户)') + .requiredOption('--fullName ', '组织名称 (如: 测试部门)') + .requiredOption('--enCode ', '组织编码 (英文)') + .option('--parentId ', '父组织 id (默认 "0" 顶级)', '0') + .option('--category ', '分类: company/department/position', 'department') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: CreateOpts) => { + const c = await JnpfClient.fromToken() + const body = { + fullName: opts.fullName, + enCode: opts.enCode, + parentId: opts.parentId, + category: opts.category, + enabledMark: 1, + sortCode: 0, + } + const r = await c.postJson<{ id?: string }>('/permission/Organize', body) + if (r.code !== 200) { + log.error(`org create 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + let id = r.data?.id + if (!id) { + // 用 Selector 反查 + const listR = await c.get<{ list: { id: string; enCode: string; fullName: string }[] }>( + '/permission/Organize/Selector', + { parentId: opts.parentId, pageSize: '50' }, + ) + const found = (listR.data?.list || []).find( + (d) => d.enCode === opts.enCode || d.fullName === opts.fullName, + ) + id = found?.id + } + log.info(`✓ 组织创建成功 id=${id}`) + if (opts.json) printJson({ ...(r.data as object), id }) + }) + installAiHelpHook(cmd, { + purpose: '新建组织/部门 (P1 权限三角 3 号)', + required: { '--fullName': '组织名称', '--enCode': '组织编码' }, + optional: { '--parentId': '父组织 id (默认 "0")', '--category': 'company/department/position' }, + example: 'dacli org create --fullName=测试部门 --enCode=dacli_dept --parentId=0', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/organize/Form.vue', + api: 'POST /api/permission/Organize', + ref: 'doc/v0.8-endpoints.md §2.3', + }, + notes: ['**决策 7**: 必须先建组织再建用户, 否则 user organizeId=null 报错'], + }) + return cmd +} diff --git a/src/commands/org/index.ts b/src/commands/org/index.ts new file mode 100644 index 0000000..04e26ca --- /dev/null +++ b/src/commands/org/index.ts @@ -0,0 +1,24 @@ +/** + * commands/org/index.ts — org 父命令 + * + * JNPF 组织/部门/岗位 (permission/organize + permission/position) + * + * 决策 7: 组织是 P1 权限三角 3 号 (先建组织, 再建用户, 最后建角色赋权) + * + * 子命令: + * list 组织树列表 + * tree 树形展示 + * create 新建 + */ +import { Command } from 'commander' +import { buildOrgListCommand } from './list.ts' +import { buildOrgTreeCommand } from './tree.ts' +import { buildOrgCreateCommand } from './create.ts' + +export function buildOrgCommand(): Command { + const cmd = new Command('org').description('组织 (P1 权限三角 3 号, 组织/部门/岗位)') + cmd.addCommand(buildOrgListCommand()) + cmd.addCommand(buildOrgTreeCommand()) + cmd.addCommand(buildOrgCreateCommand()) + return cmd +} diff --git a/src/commands/org/list.ts b/src/commands/org/list.ts new file mode 100644 index 0000000..33d8021 --- /dev/null +++ b/src/commands/org/list.ts @@ -0,0 +1,77 @@ +/** + * commands/org/list.ts — 组织树列表 + * + * API: GET /api/permission/Organize/Selector (返回组织树) + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface OrgItem { + id?: string + parentId?: string + fullName?: string + enCode?: string + category?: string | null + hasChildren?: boolean + isLeaf?: boolean | null + parentName?: string | null +} + +interface ListOpts { + parentId?: string + json?: boolean +} + +export function buildOrgListCommand(): Command { + const cmd = new Command('list') + .description('列出组织树 (P1 权限三角 3 号, 根 → 公司 → 部门 → 岗位)') + .option('--parentId ', '从指定父节点展开 (默认根 "0")', '0') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: ListOpts) => { + const c = await JnpfClient.fromToken() + const r = await c.get<{ list: OrgItem[] }>('/permission/Organize/Selector', { + parentId: opts.parentId, + currentPage: 1, + pageSize: 200, + }) + if (r.code !== 200) { + log.error(`org list 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + const list = r.data?.list || [] + if (opts.json) { + printJson(r.data) + return + } + log.info(`共 ${list.length} 个组织节点 (从 parentId=${opts.parentId} 展开)`) + console.log('ID FULL_NAME PARENT_ID CATEGORY CHILDREN') + console.log('-'.repeat(100)) + for (const d of list) { + // UUID id 可能 36 字符, 截断到前 30 字符 + '..' 标识 + const id = String(d.id || '') + const idShort = id.length > 30 ? id.slice(0, 28) + '..' : id.padEnd(30) + const name = String(d.fullName || '').padEnd(23) + const parent = String(d.parentId || '').padEnd(11) + const cat = String(d.category || '-').padEnd(10) + const ch = d.hasChildren ? 'yes' : 'no' + console.log(`${idShort} ${name} ${parent} ${cat} ${ch}`) + } + }) + installAiHelpHook(cmd, { + purpose: '列出组织树 (P1 权限三角 3 号)', + optional: { '--parentId': '从指定父节点展开 (默认 "0" 根)' }, + example: 'dacli org list\ndacli org list --parentId=829724597300494342', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/organize/index.vue', + api: 'GET /api/permission/Organize/Selector', + ref: 'doc/v0.8-endpoints.md §2.3', + }, + notes: [ + '**决策 7**: 组织是 P1 权限三角 3 号, 必须先建组织再建用户', + '**反模式**: 用户 organizeId=null 报"组织不存在"', + ], + }) + return cmd +} diff --git a/src/commands/org/tree.ts b/src/commands/org/tree.ts new file mode 100644 index 0000000..4b32e52 --- /dev/null +++ b/src/commands/org/tree.ts @@ -0,0 +1,76 @@ +/** + * commands/org/tree.ts — 组织树形结构展示 + * + * 走 /api/permission/Organize/AsyncList/{id} 拉单层子节点, 递归构建树 + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' + +interface OrgItem { + id?: string + parentId?: string + fullName?: string + enCode?: string + category?: string | null + hasChildren?: boolean + isLeaf?: boolean | null +} + +interface TreeOpts { + parentId?: string + maxDepth?: string +} + +async function loadChildren(c: JnpfClient, parentId: string): Promise { + const r = await c.get(`/permission/Organize/AsyncList/${parentId}`) + if (r.code !== 200) return [] + return r.data || [] +} + +function printTree(list: OrgItem[], depth: number, parentId: string) { + const indent = ' '.repeat(depth) + for (const d of list) { + if (d.parentId === parentId) { + console.log(`${indent}├─ ${d.fullName} (${d.id})${d.category ? ` [${d.category}]` : ''}`) + if (d.hasChildren) { + // 简化: 不递归, 提示用户用 list 拉 + } + } + } +} + +export function buildOrgTreeCommand(): Command { + const cmd = new Command('tree') + .description('组织树形结构 (单层展示, 递归用 --recursive)') + .option('--parentId ', '从指定父节点展开 (默认 "0" 根)', '0') + .option('--maxDepth ', '最大递归深度', '3') + .action(async (opts: TreeOpts) => { + const c = await JnpfClient.fromToken() + const r = await c.get<{ list: OrgItem[] }>('/permission/Organize/Selector', { + parentId: opts.parentId, + currentPage: 1, + pageSize: 200, + }) + if (r.code !== 200) { + log.error(`org tree 失败: ${r.msg}`) + process.exit(1) + } + const list = r.data?.list || [] + log.info(`根 parentId=${opts.parentId}, 共 ${list.length} 个节点`) + console.log('组织树 (单层, maxDepth=' + opts.maxDepth + '):') + printTree(list, 0, opts.parentId || '0') + }) + installAiHelpHook(cmd, { + purpose: '组织树形结构 (单层展示)', + optional: { '--parentId': '根节点 id (默认 "0")', '--maxDepth': '最大深度' }, + example: 'dacli org tree\ndacli org tree --parentId=829724597300494342', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/organize/index.vue', + api: 'GET /api/permission/Organize/Selector', + ref: 'doc/v0.8-endpoints.md §2.3', + }, + }) + return cmd +} diff --git a/src/commands/role/assign.ts b/src/commands/role/assign.ts new file mode 100644 index 0000000..225e7be --- /dev/null +++ b/src/commands/role/assign.ts @@ -0,0 +1,59 @@ +/** + * commands/role/assign.ts — 角色赋权 + * + * API: POST /api/permission/RoleRelation/addRoles (给用户加角色) + * POST /api/permission/RoleRelation/deleteRoles (给用户删角色) + * PUT /api/permission/Role/{id} (改 role 的 organizeIds/positionIds/userIds) + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' + +interface AssignOpts { + roleId: string + userIds?: string + action?: 'add' | 'remove' +} + +export function buildRoleAssignCommand(): Command { + const cmd = new Command('assign') + .description('给角色赋用户 (或从角色删用户)') + .requiredOption('--roleId ', '角色 id') + .option('--userIds ', '用户 id 列表 (逗号分隔)') + .option('--action ', 'add=加用户, remove=删用户', 'add') + .action(async (opts: AssignOpts) => { + if (!opts.userIds) { + log.error('--userIds 必填 (逗号分隔 user id)') + process.exit(2) + } + if (opts.action !== 'add' && opts.action !== 'remove') { + log.error('--action 必须是 add 或 remove') + process.exit(2) + } + const c = await JnpfClient.fromToken() + const path = + opts.action === 'add' + ? '/permission/RoleRelation/addRoles' + : '/permission/RoleRelation/deleteRoles' + const userIds = opts.userIds.split(',').map((s) => s.trim()).filter(Boolean) + const r = await c.postJson(path, { roleId: opts.roleId, userIds }) + if (r.code !== 200) { + log.error(`role assign 失败: ${r.msg}`) + process.exit(1) + } + log.info(`✓ 角色 id=${opts.roleId} ${opts.action} ${userIds.length} 个用户 OK`) + }) + installAiHelpHook(cmd, { + purpose: '给角色赋用户 (或从角色删用户)', + required: { '--roleId': '角色 id', '--userIds': '用户 id 列表' }, + optional: { '--action': 'add/remove' }, + example: 'dacli role assign --roleId=123 --userIds=456,789 --action=add', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/role/Form.vue', + api: 'POST /api/permission/RoleRelation/addRoles', + ref: 'doc/v0.8-endpoints.md §2.1', + }, + }) + return cmd +} diff --git a/src/commands/role/create.ts b/src/commands/role/create.ts new file mode 100644 index 0000000..007c318 --- /dev/null +++ b/src/commands/role/create.ts @@ -0,0 +1,68 @@ +/** + * commands/role/create.ts — 新建角色 + * + * API: POST /api/permission/Role + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface CreateOpts { + fullName: string + enCode: string + type?: string + json?: boolean +} + +export function buildRoleCreateCommand(): Command { + const cmd = new Command('create') + .description('新建角色 (P1 权限三角核心)') + .requiredOption('--fullName ', '角色名称') + .requiredOption('--enCode ', '角色编码') + .option('--type ', '角色类型: 0=全局 1=业务', '0') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: CreateOpts) => { + const c = await JnpfClient.fromToken() + const body = { + fullName: opts.fullName, + enCode: opts.enCode, + type: opts.type, + enabledMark: 1, + sortCode: 0, + organizeIds: [], + positionIds: [], + userIds: [], + } + const r = await c.postJson<{ id?: string }>('/permission/Role', body) + if (r.code !== 200) { + log.error(`role create 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + let id = r.data?.id + if (!id) { + const listR = await c.get<{ list: { id: string; enCode: string; fullName: string }[] }>( + '/permission/Role', + { keyword: opts.enCode, pageSize: '50' }, + ) + const found = (listR.data?.list || []).find( + (d) => d.enCode === opts.enCode || d.fullName === opts.fullName, + ) + id = found?.id + } + log.info(`✓ 角色创建成功 id=${id}`) + if (opts.json) printJson({ ...(r.data as object), id }) + }) + installAiHelpHook(cmd, { + purpose: '新建角色', + required: { '--fullName': '角色名称', '--enCode': '角色编码' }, + optional: { '--type': '0=全局 1=业务' }, + example: 'dacli role create --fullName=测试角色 --enCode=dacli_test_role', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/role/Form.vue', + api: 'POST /api/permission/Role', + ref: 'doc/v0.8-endpoints.md §2.1', + }, + }) + return cmd +} diff --git a/src/commands/role/delete.ts b/src/commands/role/delete.ts new file mode 100644 index 0000000..aff8fa4 --- /dev/null +++ b/src/commands/role/delete.ts @@ -0,0 +1,45 @@ +/** + * commands/role/delete.ts — 删除角色 + * + * API: DELETE /api/permission/Role/{id} + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' + +interface DeleteOpts { + id: string + yes?: boolean +} + +export function buildRoleDeleteCommand(): Command { + const cmd = new Command('delete') + .description('删除角色 (非系统内置)') + .requiredOption('--id ', '角色 id') + .option('--yes', '跳过确认', false) + .action(async (opts: DeleteOpts) => { + if (!opts.yes) { + log.warn(`即将删除角色 id=${opts.id}, 加 --yes 跳过确认`) + process.exit(2) + } + const c = await JnpfClient.fromToken() + const r = await c.del(`/permission/Role/${opts.id}`) + if (r.code !== 200) { + log.error(`role delete 失败: ${r.msg}`) + process.exit(1) + } + log.info(`✓ 角色 id=${opts.id} 已删除`) + }) + installAiHelpHook(cmd, { + purpose: '删除角色 (isSystem=1 系统内置角色不可删)', + required: { '--id': '角色 id', '--yes': '跳过确认' }, + example: 'dacli role delete --id=1234567890 --yes', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/role/index.vue', + api: 'DELETE /api/permission/Role/{id}', + ref: 'doc/v0.8-endpoints.md §2.1', + }, + }) + return cmd +} diff --git a/src/commands/role/index.ts b/src/commands/role/index.ts new file mode 100644 index 0000000..820589a --- /dev/null +++ b/src/commands/role/index.ts @@ -0,0 +1,27 @@ +/** + * commands/role/index.ts — role 父命令 + * + * JNPF 角色 (permission/role + permission/roleRelation) + * + * 决策 7: 角色是 P1 权限三角的 1 号 (先建角色, 再建用户绑组织, 最后赋权) + * + * 子命令: + * list 列表 + * create 新建 + * delete 删除 (非系统) + * assign 角色赋用户 + */ +import { Command } from 'commander' +import { buildRoleListCommand } from './list.ts' +import { buildRoleCreateCommand } from './create.ts' +import { buildRoleDeleteCommand } from './delete.ts' +import { buildRoleAssignCommand } from './assign.ts' + +export function buildRoleCommand(): Command { + const cmd = new Command('role').description('角色 (P1 权限三角 1 号, 权限载体)') + cmd.addCommand(buildRoleListCommand()) + cmd.addCommand(buildRoleCreateCommand()) + cmd.addCommand(buildRoleDeleteCommand()) + cmd.addCommand(buildRoleAssignCommand()) + return cmd +} diff --git a/src/commands/role/list.ts b/src/commands/role/list.ts new file mode 100644 index 0000000..dcbaaf2 --- /dev/null +++ b/src/commands/role/list.ts @@ -0,0 +1,73 @@ +/** + * commands/role/list.ts — 角色列表 + * + * API: GET /api/permission/Role + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface RoleItem { + id?: string + fullName?: string + enCode?: string + type?: string + enabledMark?: number + isSystem?: number +} + +interface ListOpts { + keyword?: string + json?: boolean +} + +export function buildRoleListCommand(): Command { + const cmd = new Command('list') + .description('列出角色 (权限载体, P1 权限三角核心)') + .option('--keyword ', '按名称/编码模糊搜索') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: ListOpts) => { + const c = await JnpfClient.fromToken() + const r = await c.get<{ list: RoleItem[] }>('/permission/Role', { + keyword: opts.keyword, + currentPage: 1, + pageSize: 50, + }) + if (r.code !== 200) { + log.error(`role list 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + const list = r.data?.list || [] + if (opts.json) { + printJson(r.data) + return + } + log.info(`共 ${list.length} 个角色`) + console.log('ID FULL_NAME ENCODE TYPE ENABLED') + console.log('-'.repeat(95)) + for (const d of list) { + const id = String(d.id || '').padEnd(30) + const name = String(d.fullName || '').padEnd(23) + const code = String(d.enCode || '').padEnd(21) + const type = String(d.type || '').padEnd(11) + const enabled = d.enabledMark === 1 ? '是' : '否' + console.log(`${id}${name}${code}${type}${enabled}`) + } + }) + installAiHelpHook(cmd, { + purpose: '列出角色 (权限载体, P1 权限三角核心)', + optional: { '--keyword': '按名称/编码模糊搜索' }, + example: 'dacli role list\ndacli role list --keyword=管理员', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/role/index.vue', + api: 'GET /api/permission/Role', + ref: 'doc/v0.8-endpoints.md §2.1', + }, + notes: [ + '**决策 7**: 角色是权限三角的 1 号, 先建角色再赋权', + '**反模式**: 系统内置角色 (isSystem=1) 不可删改', + ], + }) + return cmd +} diff --git a/src/commands/user/create.ts b/src/commands/user/create.ts new file mode 100644 index 0000000..56bc90f --- /dev/null +++ b/src/commands/user/create.ts @@ -0,0 +1,79 @@ +/** + * commands/user/create.ts — 新建用户 + * + * API: POST /api/permission/Users + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' +import { encryptByMd5 } from '../../core/crypto.ts' + +interface CreateOpts { + account: string + realName: string + password: string + organizeId?: string + gender?: string + json?: boolean +} + +export function buildUserCreateCommand(): Command { + const cmd = new Command('create') + .description('新建用户 (P1 权限三角 2 号)') + .requiredOption('--account ', '账号 (登录名)') + .requiredOption('--realName ', '真实姓名') + .requiredOption('--password

', '明文密码 (后端会自动 md5 加密)') + .option('--organizeId ', '所属组织 id (决策 7: 必须)') + .option('--gender ', '性别: 1=男 2=女 3=未知', '1') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: CreateOpts) => { + const c = await JnpfClient.fromToken() + // JNPF 接收的 password 是 md5(plain) hex (32 字符), 不是 AES 加密 + const md5Pwd = encryptByMd5(opts.password) + const body: Record = { + account: opts.account, + realName: opts.realName, + password: md5Pwd, + gender: opts.gender || '1', + enabledMark: 1, + sortCode: 0, + } + if (opts.organizeId) body.organizeId = opts.organizeId + const r = await c.postJson<{ id?: string }>('/permission/Users', body) + if (r.code !== 200) { + log.error(`user create 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + let id = r.data?.id + if (!id) { + const listR = await c.get<{ list: { id: string; account: string; realName: string }[] }>( + '/permission/Users', + { keyword: opts.account, pageSize: '50' }, + ) + const found = (listR.data?.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), id }) + }) + installAiHelpHook(cmd, { + purpose: '新建用户 (P1 权限三角 2 号)', + required: { '--account': '账号', '--realName': '真实姓名', '--password': '明文密码' }, + optional: { '--organizeId': '所属组织 id (决策 7 必填)' }, + example: + 'dacli user create --account=test001 --realName="测试用户" --password=123456 --organizeId=', + 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 +} diff --git a/src/commands/user/delete.ts b/src/commands/user/delete.ts new file mode 100644 index 0000000..2e37088 --- /dev/null +++ b/src/commands/user/delete.ts @@ -0,0 +1,45 @@ +/** + * commands/user/delete.ts — 删除用户 + * + * API: DELETE /api/permission/Users/{id} + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' + +interface DeleteOpts { + id: string + yes?: boolean +} + +export function buildUserDeleteCommand(): Command { + const cmd = new Command('delete') + .description('删除用户 (非超管)') + .requiredOption('--id ', '用户 id') + .option('--yes', '跳过确认', false) + .action(async (opts: DeleteOpts) => { + if (!opts.yes) { + log.warn(`即将删除用户 id=${opts.id}, 加 --yes 跳过确认`) + process.exit(2) + } + const c = await JnpfClient.fromToken() + const r = await c.del(`/permission/Users/${opts.id}`) + if (r.code !== 200) { + log.error(`user delete 失败: ${r.msg}`) + process.exit(1) + } + log.info(`✓ 用户 id=${opts.id} 已删除`) + }) + installAiHelpHook(cmd, { + purpose: '删除用户 (isAdministrator=1 不可删)', + required: { '--id': '用户 id', '--yes': '跳过确认' }, + example: 'dacli user delete --id=1234567890 --yes', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/user/index.vue', + api: 'DELETE /api/permission/Users/{id}', + ref: 'doc/v0.8-endpoints.md §2.2', + }, + }) + return cmd +} diff --git a/src/commands/user/index.ts b/src/commands/user/index.ts new file mode 100644 index 0000000..d8b7848 --- /dev/null +++ b/src/commands/user/index.ts @@ -0,0 +1,27 @@ +/** + * commands/user/index.ts — user 父命令 + * + * JNPF 用户 (permission/user) + * + * 决策 7: 用户是 P1 权限三角 2 号 (必须绑组织) + * + * 子命令: + * list 列表 + * create 新建 + * delete 删除 + * reset-pwd 重置密码 + */ +import { Command } from 'commander' +import { buildUserListCommand } from './list.ts' +import { buildUserCreateCommand } from './create.ts' +import { buildUserDeleteCommand } from './delete.ts' +import { buildUserResetPwdCommand } from './reset-pwd.ts' + +export function buildUserCommand(): Command { + const cmd = new Command('user').description('用户 (P1 权限三角 2 号, 登录主体)') + cmd.addCommand(buildUserListCommand()) + cmd.addCommand(buildUserCreateCommand()) + cmd.addCommand(buildUserDeleteCommand()) + cmd.addCommand(buildUserResetPwdCommand()) + return cmd +} diff --git a/src/commands/user/list.ts b/src/commands/user/list.ts new file mode 100644 index 0000000..81e7de1 --- /dev/null +++ b/src/commands/user/list.ts @@ -0,0 +1,76 @@ +/** + * commands/user/list.ts — 用户列表 + * + * API: GET /api/permission/Users + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface UserItem { + id?: string + account?: string + realName?: string + fullName?: string + organize?: string + position?: string + enabledMark?: number + isAdministrator?: number +} + +interface ListOpts { + keyword?: string + json?: boolean +} + +export function buildUserListCommand(): Command { + const cmd = new Command('list') + .description('列出用户 (P1 权限三角 2 号)') + .option('--keyword ', '按账号/姓名/手机模糊搜索') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: ListOpts) => { + const c = await JnpfClient.fromToken() + const r = await c.get<{ list: UserItem[] }>('/permission/Users', { + keyword: opts.keyword, + currentPage: 1, + pageSize: 50, + }) + if (r.code !== 200) { + log.error(`user list 失败 (code=${r.code}): ${r.msg}`) + process.exit(1) + } + const list = r.data?.list || [] + if (opts.json) { + printJson(r.data) + return + } + log.info(`共 ${list.length} 个用户`) + console.log('ID ACCOUNT REAL_NAME ORG POSITION ENABLED') + console.log('-'.repeat(110)) + for (const d of list) { + const id = String(d.id || '').padEnd(30) + const acct = String(d.account || '').padEnd(15) + const name = String(d.realName || d.fullName || '').padEnd(18) + const org = String(d.organize || '').padEnd(8) + const pos = String(d.position || '').padEnd(13) + const en = d.enabledMark === 1 ? '是' : '否' + console.log(`${id}${acct}${name}${org}${pos}${en}`) + } + }) + installAiHelpHook(cmd, { + purpose: '列出用户 (P1 权限三角 2 号, 登录主体)', + optional: { '--keyword': '按账号/姓名/手机模糊搜索' }, + example: 'dacli user list\ndacli user list --keyword=admin', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/user/index.vue', + api: 'GET /api/permission/Users', + ref: 'doc/v0.8-endpoints.md §2.2', + }, + notes: [ + '**决策 7**: 用户是 P1 权限三角 2 号, 必须绑组织 (organizeId)', + '**反模式**: organizeId=null 报"组织不存在"', + ], + }) + return cmd +} diff --git a/src/commands/user/reset-pwd.ts b/src/commands/user/reset-pwd.ts new file mode 100644 index 0000000..df20dfc --- /dev/null +++ b/src/commands/user/reset-pwd.ts @@ -0,0 +1,45 @@ +/** + * commands/user/reset-pwd.ts — 重置用户密码 + * + * API: POST /api/permission/Users/{id}/Actions/ResetPassword + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' +import { encryptByMd5 } from '../../core/crypto.ts' + +interface ResetPwdOpts { + id: string + password: string +} + +export function buildUserResetPwdCommand(): Command { + const cmd = new Command('reset-pwd') + .description('重置用户密码 (管理员操作)') + .requiredOption('--id ', '用户 id') + .requiredOption('--password

', '新明文密码 (后端会自动 md5 加密)') + .action(async (opts: ResetPwdOpts) => { + const c = await JnpfClient.fromToken() + const r = await c.postJson(`/permission/Users/${opts.id}/Actions/ResetPassword`, { + userPassword: encryptByMd5(opts.password), + id: opts.id, + }) + if (r.code !== 200) { + log.error(`user reset-pwd 失败: ${r.msg}`) + process.exit(1) + } + log.info(`✓ 用户 id=${opts.id} 密码已重置`) + }) + installAiHelpHook(cmd, { + purpose: '重置用户密码 (admin 操作)', + required: { '--id': '用户 id', '--password': '新明文密码' }, + example: 'dacli user reset-pwd --id=1234567890 --password=newpass123', + source: { + web: 'web/apps/jnpf-web-apps-main/src/views/permission/user/Form.vue', + api: 'POST /api/permission/Users/{id}/Actions/ResetPassword', + ref: 'doc/v0.8-endpoints.md §2.2', + }, + }) + return cmd +} diff --git a/tests/unit/role-user-org.test.ts b/tests/unit/role-user-org.test.ts new file mode 100644 index 0000000..b7ad0d9 --- /dev/null +++ b/tests/unit/role-user-org.test.ts @@ -0,0 +1,107 @@ +/** + * role-user-org.test.ts — 权限三角 3 父命令烟囱测试 + */ +import { describe, it, expect } from 'vitest' +import { execFileSync } from 'node:child_process' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const __dirname = fileURLToPath(new URL('.', import.meta.url)) +const CLI = resolve(__dirname, '../../src/cli.ts') + +function run(args: string[]): string { + try { + return execFileSync('npx', ['tsx', CLI, ...args], { + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 30_000, + }) + } catch (e) { + const err = e as { stdout?: Buffer | string; status?: number } + return (err.stdout?.toString() || '') + } +} + +describe('role command tree (W10-D1)', () => { + it('role --help 列出 4 个子命令', () => { + const out = run(['role', '--help']) + expect(out).toContain('list') + expect(out).toContain('create') + expect(out).toContain('delete') + expect(out).toContain('assign') + }) + it('role list --ai-help 提示决策 7', () => { + const out = run(['role', 'list', '--ai-help']) + expect(out).toContain('决策 7') + expect(out).toContain('/api/permission/Role') + }) + it('role create --help 包含 --fullName/--enCode', () => { + const out = run(['role', 'create', '--help']) + expect(out).toContain('--fullName') + expect(out).toContain('--enCode') + }) + it('role delete --help 包含 --yes', () => { + const out = run(['role', 'delete', '--help']) + expect(out).toContain('--yes') + }) + it('role assign --help 包含 --userIds/--action', () => { + const out = run(['role', 'assign', '--help']) + expect(out).toContain('--userIds') + expect(out).toContain('--action') + }) + it('顶层 --help 包含 role', () => { + const out = run(['--help']) + expect(out).toContain('role') + }) +}) + +describe('user command tree (W10-D2)', () => { + it('user --help 列出 4 个子命令', () => { + const out = run(['user', '--help']) + expect(out).toContain('list') + expect(out).toContain('create') + expect(out).toContain('delete') + expect(out).toContain('reset-pwd') + }) + it('user list --ai-help 提示决策 7', () => { + const out = run(['user', 'list', '--ai-help']) + expect(out).toContain('决策 7') + expect(out).toContain('/api/permission/Users') + }) + it('user create --help 包含 --organizeId/--gender', () => { + const out = run(['user', 'create', '--help']) + expect(out).toContain('--organizeId') + expect(out).toContain('--gender') + }) + it('user reset-pwd --help 包含 --password', () => { + const out = run(['user', 'reset-pwd', '--help']) + expect(out).toContain('--password') + }) + it('顶层 --help 包含 user', () => { + const out = run(['--help']) + expect(out).toContain('user') + }) +}) + +describe('org command tree (W10-D3)', () => { + it('org --help 列出 3 个子命令', () => { + const out = run(['org', '--help']) + expect(out).toContain('list') + expect(out).toContain('tree') + expect(out).toContain('create') + }) + it('org list --ai-help 提示决策 7', () => { + const out = run(['org', 'list', '--ai-help']) + expect(out).toContain('决策 7') + expect(out).toContain('/api/permission/Organize/Selector') + }) + it('org create --help 包含 --parentId/--category', () => { + const out = run(['org', 'create', '--help']) + expect(out).toContain('--parentId') + expect(out).toContain('--category') + }) + it('顶层 --help 包含 org', () => { + const out = run(['--help']) + expect(out).toContain('org') + }) +})