feat(dacli): mirror authority and read-only form controls
- dacli/src/webapi/authority.ts: 真镜像 web/apps/jnpf-web-apps-main/src/api/permission/auth.ts (getAuthValues/updateAuthList, 0 复刻 0 漂移) - dacli/src/commands/role/authorize.ts + _authorize.ts: 角色绑定菜单 (sswflow M1 §11 必需) - dacli/src/commands/form/update.ts + _readonly.ts: form update --read-only 锁定表单为只读 (设计 §4.3 受保护字段) - 18/18 单测 PASS (validateAuthorizeInput/buildAuthorizePayload/makeFormReadOnly) Co-Authored-By: Claude <[email protected]>
This commit is contained in:
1 parent
244f204864
commit
a4fec463ca
8 files changed
+694
-1
No files matched your search
@@ -0,0 +1,98 @@
|
||||
# sswflow Authority & Read-Only — dacli 镜像扩展
|
||||
|
||||
> 记录日期: 2026-08-01 (sswflow M1 Task 9)
|
||||
> 关联任务: design §7.6 (依赖顺序: app → schema 审计 → dict → role → dm 缺口 → form → workflow → menu → permissions → test)
|
||||
|
||||
## 背景
|
||||
|
||||
sswflow M1 需要两种 dacli 命令能力, 平台 JNPF dacli v0.22+ 之前未提供:
|
||||
|
||||
1. **角色绑定菜单** (`dacli role authorize`) — 设计 §3.7 给 7 个 sswflow 角色绑定 18 个菜单, 没有此命令无法跑通
|
||||
2. **表单置为只读** (`dacli form update --read-only`) — 设计 §4.2 + §7.4 给状态受控 + 运行审计表单禁用增删改按钮, 没有此能力无法满足只读契约
|
||||
|
||||
两份补丁均按 dacli 铁律 3 (0 复刻 0 漂移) 通过 webapi 真镜像实现, 不新增 HTTP 路径, 不抄 web 端代码.
|
||||
|
||||
## 源文件 → 镜像文件
|
||||
|
||||
### 1. 角色绑定菜单
|
||||
|
||||
| 维度 | web 权威源 | dacli 镜像 |
|
||||
|------|-----------|-----------|
|
||||
| web API | `web/apps/jnpf-web-apps-main/src/api/permission/auth.ts` | `dacli/src/webapi/authority.ts` |
|
||||
| dacli 命令 | (无) | `dacli/src/commands/role/authorize.ts` |
|
||||
|
||||
**镜像函数**: `loadAuth.getAuthValues / updateAuthList / getCommonAuthValues / updateCommonAuthList` (web permission/auth.ts 已存在)
|
||||
|
||||
**后端契约** (从 web `views/permission/role/Form.vue:save()` 推):
|
||||
- HTTP PUT `/api/permission/Authority/Data/{objectId}`
|
||||
- Body: `{ button: [], column: [], moduleId: [...], resource: [], form: [] }`
|
||||
- `moduleId` 即菜单 id 数组 (`moduleId` 是 web 端字段名, 与 `--menuIds` 等价)
|
||||
|
||||
### 2. 表单置为只读
|
||||
|
||||
| 维度 | web 权威源 | dacli 镜像 |
|
||||
|------|-----------|-----------|
|
||||
| web API | `web/apps/jnpf-web-apps-main/src/api/onlineDev/visualDev.ts` | `dacli/src/webapi/visualDev.ts` (已存在, 复用 update) |
|
||||
| dacli 命令 | (无) | `dacli/src/commands/form/update.ts` 新增 `--read-only` 选项 |
|
||||
|
||||
**镜像函数**: `loadVisualDev.getInfo(id)` 拉原 schema → 在内存修改 → `loadVisualDev.update({id, ...orig})` PUT
|
||||
|
||||
**修改契约**:
|
||||
- `formData.btnsList` 清空 (列表工具栏: 新增/编辑/删除/批量导入/导出等)
|
||||
- `formData.tableBtns` 清空 (表格列按钮)
|
||||
- `formData.fields[].disabled = true` + `readOnly = true` (表单字段)
|
||||
- `formData.columnList[].disabled = true` + `children[].disabled = true` (列表列)
|
||||
- **tables 字段不动** (禁止 ALTER 物理表)
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 1. 角色绑定菜单 (M1 §11 授权用)
|
||||
dacli role authorize \
|
||||
--roleId=643238393602117 \
|
||||
--menuIds=100,101,102,103
|
||||
|
||||
# dry-run (不写库)
|
||||
dacli role authorize --roleId=... --menuIds=... --dry-run
|
||||
|
||||
# 2. 表单置为只读 (M1 §10 受控/只读资源)
|
||||
dacli form update --id=sswflowFlowRun_formId --read-only
|
||||
dacli form update --id=sswflowProjectParty_formId --read-only
|
||||
```
|
||||
|
||||
## 验证命令
|
||||
|
||||
```bash
|
||||
# 单元测试
|
||||
npx vitest run tests/unit/role_authorize.test.ts tests/unit/form_update_read_only.test.ts
|
||||
|
||||
# 实际打通 (待 sswflow DB 上线 + 实际 form id 拿到后)
|
||||
dacli role authorize --roleId=... --menuIds=... --dry-run
|
||||
dacli form update --id=<flow_run_form_id> --read-only
|
||||
npx tsx src/cli.ts test render --module=form --formId=<id>
|
||||
```
|
||||
|
||||
## 升级重放
|
||||
|
||||
后续 JNPF / dacli 升级时:
|
||||
|
||||
1. **web permission/auth.ts** 字段调整: `updateAuthList` 签名/Body 字段名变更 → 同步 `dacli/src/webapi/authority.ts` `AuthorityApi.updateAuthList` 的 data shape
|
||||
2. **web visualDev.ts update** Body 字段调整: 影响 `dacli/src/commands/form/update.ts` 的 read-only transform 路径 (字段 `btnsList`/`tableBtns`/`columnList`/`fields` 是 web FormGenerator 共有概念, 升级时优先观察这些字段命名变化)
|
||||
3. **dacli 自身 `form update`**: 不破坏 `--read-only` 流程, 避免与既有 `--fields`/`--ai`/`--releaseOnly` 等分支相互覆盖
|
||||
|
||||
## 不修改的内容
|
||||
|
||||
- **dacli 既有 8 子命令的 role 不变**, 仅追加 `authorize` 子命令 (`commands/role/index.ts`)
|
||||
- **form update 既有 24 选项不变**, 仅追加 `--read-only`
|
||||
- **不抄 web 端实现**: 通过 `_loader.ts` + `_defhttp_shim.ts` 真镜像, 0 复刻
|
||||
- **不修 jnpf/**: 红线 #7
|
||||
- **不动 web/**: dacli 镜像架构, 不需要改 web
|
||||
|
||||
## 关联文件
|
||||
|
||||
- `dacli/README.md` §3 (镜像架构 0 复刻 0 漂移)
|
||||
- `dacli/src/webapi/_loader.ts` (通用 web 源码加载器)
|
||||
- `dacli/src/webapi/_defhttp_shim.ts` (Node CLI 环境的 defHttp shim)
|
||||
- `dacli/src/webapi/auth.ts` (历史 webapi/auth.ts 镜像, 可参考 initWebapi 模式)
|
||||
- `dacli/src/webapi/visualDev.ts` (已存在的 visualDev 镜像, 复用 update)
|
||||
- `dacli/src/commands/role/assign.ts` (参考的 role 子命令模式)
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* form/_readonly.ts — sswflow M1 Task 9 (2026-08-01)
|
||||
*
|
||||
* 把 formData 转成"只读"形态:
|
||||
* - 清空 btnsList + tableBtns (列表/工具栏所有按钮)
|
||||
* - fields[] 每个字段 disabled = readOnly = true
|
||||
* - columnList[] 每个列 disabled = true, 含 children 嵌套
|
||||
* - 不修改 tables 字段 (禁止 ALTER 物理表)
|
||||
*
|
||||
* 这是纯函数, 单元测试友好, 不依赖 commander.
|
||||
*/
|
||||
|
||||
export interface FormDataShape {
|
||||
fields?: Array<Record<string, unknown>>
|
||||
columnList?: Array<Record<string, unknown>>
|
||||
btnsList?: Array<unknown>
|
||||
tableBtns?: Array<unknown>
|
||||
[k: string]: unknown
|
||||
}
|
||||
|
||||
export interface FormSchemaLike {
|
||||
enCode?: string
|
||||
fullName?: string
|
||||
formData?: string | FormDataShape | null
|
||||
tables?: unknown
|
||||
[k: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 form schema 转成只读版本 (返回新对象, 不修改输入).
|
||||
* @returns { schema, modified: { buttonsCleared, fieldsLocked, columnsLocked } }
|
||||
*/
|
||||
export function makeFormReadOnly(schema: FormSchemaLike): {
|
||||
schema: FormSchemaLike
|
||||
modified: { buttonsCleared: boolean; fieldsLocked: number; columnsLocked: number }
|
||||
} {
|
||||
const fdRaw = schema.formData
|
||||
const fd: FormDataShape =
|
||||
typeof fdRaw === 'string'
|
||||
? (JSON.parse(fdRaw) as FormDataShape)
|
||||
: fdRaw
|
||||
? fdRaw
|
||||
: ({} as FormDataShape)
|
||||
|
||||
const buttonsCleared = Array.isArray(fd.btnsList) || Array.isArray(fd.tableBtns)
|
||||
if (Array.isArray(fd.btnsList)) fd.btnsList = []
|
||||
if (Array.isArray(fd.tableBtns)) fd.tableBtns = []
|
||||
|
||||
let fieldsLocked = 0
|
||||
let columnsLocked = 0
|
||||
|
||||
const lockField = (f: unknown) => {
|
||||
if (!f || typeof f !== 'object') return
|
||||
const obj = f as Record<string, unknown>
|
||||
obj.disabled = true
|
||||
obj.readOnly = true
|
||||
if (Array.isArray(obj.options)) {
|
||||
for (const o of obj.options) {
|
||||
if (o && typeof o === 'object') (o as Record<string, unknown>).disabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(fd.fields)) {
|
||||
for (const f of fd.fields) {
|
||||
lockField(f)
|
||||
fieldsLocked++
|
||||
}
|
||||
}
|
||||
if (Array.isArray(fd.columnList)) {
|
||||
for (const c of fd.columnList) {
|
||||
lockField(c)
|
||||
columnsLocked++
|
||||
const ch = (c as Record<string, unknown>).children
|
||||
if (Array.isArray(ch)) {
|
||||
for (const cc of ch) {
|
||||
lockField(cc)
|
||||
columnsLocked++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const out: FormSchemaLike = {
|
||||
...schema,
|
||||
formData: JSON.stringify(fd),
|
||||
}
|
||||
// 显式不携带 tables (契约: 物理表零变更)
|
||||
delete (out as Record<string, unknown>).tables
|
||||
|
||||
return {
|
||||
schema: out,
|
||||
modified: { buttonsCleared, fieldsLocked, columnsLocked },
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,8 @@ import { DacliError } from '../../core/types.ts'
|
||||
import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
|
||||
import { dirtyCheck, dirtyCheckFailAndExit, DirtyCheckError, logDirtyCheckSkip, buildDirtyCheckSkipFix } 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
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts'
|
||||
import { makeFormReadOnly } from './_readonly.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
import { applyNormalizedPatch, validateStrictSchema, closeFormContract, buildGetFormAdapter, FormSchemaInvalidError, FORM_SCHEMA_INVALID_TAG, type FormField } from './_schema_normalize.ts' // schema 归一化 + 严格校验 + T3 闭环 (webapi hardening)
|
||||
import { SMART_PROPS } from './_smart_props.ts' // v2.5+ BS-新141: form update 集成 smartProps (跟 create 一致)
|
||||
import { isLoginExpired } from '../_ssw_retry.ts' // P1-7 Login expired 检测 (BS-新113)
|
||||
@@ -129,6 +130,12 @@ export function buildFormUpdateCommand(): Command {
|
||||
// v2.5+ BS-新141 (jxcj M2 2026-07-23): form update --fields 集成 smartProps (跟 create 一致)
|
||||
.option('--smart-props', 'PUT 前跑 SMART_PROPS (AI 失败 tolerant, 启发式兜底 + 接受手工 JSON)', true)
|
||||
.option('--no-smart-props', '不跑 SMART_PROPS (跟 create --no-smart-props 一致)')
|
||||
// sswflow M1 Task 9 (2026-08-01): form update --read-only
|
||||
// - 读取完整 form info, 保持 tables/formData/columnList 结构
|
||||
// - 仅清空按钮权限 + 标记字段 disabled, 不修改 table schema
|
||||
// - 适用: 状态受控表单 (sswflowProjectParty/sswflowDatasetAuth)
|
||||
// + 运行审计只读表单 (sswflowFlowRun/sswflowFlowStepRun/sswflowRunEvent/sswflowArtifact)
|
||||
.option('--read-only', '锁定表单为只读 (清按钮 + 字段 disabled, 不 ALTER 物理表)', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: Opts) => {
|
||||
setupOutputFilter(opts)
|
||||
@@ -145,6 +152,49 @@ export function buildFormUpdateCommand(): Command {
|
||||
try {
|
||||
await initWebapi(c)
|
||||
|
||||
// === step -1 read-only 分支 (sswflow M1 Task 9, 2026-08-01) ===
|
||||
// 拉完整 form → 锁字段 + 清按钮 → PUT + release
|
||||
// 不触碰 tables/formData/columnList 结构 (物理表零变更)
|
||||
if ((opts as any).readOnly) {
|
||||
log.info(`loadVisualDev.getInfo (formId=${opts.id}) — read-only transform`)
|
||||
const orig = (await loadVisualDev.getInfo(opts.id)) as Record<string, any>
|
||||
log.info(`原 form: enCode=${orig.enCode} fullName=${orig.fullName}`)
|
||||
|
||||
// 复用 _readonly.ts 纯函数 (单测覆盖)
|
||||
const { schema: locked, modified } = makeFormReadOnly(orig)
|
||||
log.info(
|
||||
` ↳ 锁定: 字段 ${modified.fieldsLocked} + 列 ${modified.columnsLocked}` +
|
||||
(modified.buttonsCleared ? ` (按钮已清空)` : ` (无按钮)`),
|
||||
)
|
||||
|
||||
// PUT (走 webapi 真镜像, 不重写 HTTP)
|
||||
log.info(`loadVisualDev.update (formId=${opts.id})`)
|
||||
const r = (await loadVisualDev.update({ id: opts.id, ...locked })) as { code?: number; msg?: string }
|
||||
if (r.code !== undefined && r.code !== 200) {
|
||||
return ctx.fail(`read-only PUT 失败 (code=${r.code}): ${r.msg}`, { id: opts.id })
|
||||
}
|
||||
|
||||
// autoRelease 默认 ON (与既有行为一致)
|
||||
if (opts.autoRelease) {
|
||||
log.info(`loadVisualDev.release (formId=${opts.id})`)
|
||||
const rr = (await loadVisualDev.release(opts.id)) as { code?: number; msg?: string }
|
||||
if (rr.code !== undefined && rr.code !== 200) {
|
||||
log.warn(`发布失败 (code=${rr.code}: ${rr.msg}); form 已锁定但需手动发布`)
|
||||
} else {
|
||||
log.ok(`✓ 表单已锁定为只读并发布 (id=${opts.id})`)
|
||||
}
|
||||
}
|
||||
|
||||
const summary = {
|
||||
id: opts.id,
|
||||
action: 'read-only-locked',
|
||||
fields: modified.fieldsLocked,
|
||||
columns: modified.columnsLocked,
|
||||
}
|
||||
if (opts.json) printJson(summary)
|
||||
return ctx.success(summary)
|
||||
}
|
||||
|
||||
// === step 0 releaseOnly 分支 ===
|
||||
if (opts.releaseOnly) {
|
||||
log.info(`loadVisualDev.release (formId=${opts.id})`)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* role/_authorize.ts — sswflow M1 Task 9 (2026-08-01)
|
||||
*
|
||||
* 把 authorize 命令里的纯逻辑拆出来, 方便单元测试, 不依赖 commander.
|
||||
*/
|
||||
|
||||
export interface AuthorizeInput {
|
||||
roleId: string
|
||||
menuIds?: string[]
|
||||
moduleIds?: string[]
|
||||
}
|
||||
|
||||
export interface AuthorizePayload {
|
||||
objectId: string
|
||||
data: {
|
||||
button: never[]
|
||||
column: never[]
|
||||
moduleId: string[]
|
||||
resource: never[]
|
||||
form: never[]
|
||||
}
|
||||
}
|
||||
|
||||
/** JNPF 雪花 id 必须是纯数字 10-30 位 (跟 assign.ts 一致) */
|
||||
const ID_REGEX = /^\d{10,30}$/
|
||||
|
||||
export function validateAuthorizeInput(input: AuthorizeInput):
|
||||
| { ok: true; ids: string[]; objectId: string }
|
||||
| { ok: false; msg: string } {
|
||||
const { roleId, menuIds, moduleIds } = input
|
||||
if (!roleId) return { ok: false, msg: '--roleId 必填' }
|
||||
if (!ID_REGEX.test(roleId)) {
|
||||
return {
|
||||
ok: false,
|
||||
msg: `--roleId "${roleId}" 不是合法 JNPF id (期望纯数字 10-30 位)`,
|
||||
}
|
||||
}
|
||||
const raw = menuIds ?? moduleIds ?? []
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
return { ok: false, msg: '必须传 --menuIds 或 --moduleIds (至少 1 个)' }
|
||||
}
|
||||
const ids = raw.map((s) => String(s).trim()).filter(Boolean)
|
||||
if (ids.length === 0) return { ok: false, msg: '--menuIds/--moduleIds 解析后为空' }
|
||||
for (const id of ids) {
|
||||
if (!ID_REGEX.test(id)) {
|
||||
return {
|
||||
ok: false,
|
||||
msg: `--menuIds 含非法 id "${id}" (期望纯数字 10-30 位)`,
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ok: true, ids, objectId: roleId }
|
||||
}
|
||||
|
||||
/** 构造 web 后端契约 payload (PUT /api/permission/Authority/Data/{objectId}) */
|
||||
export function buildAuthorizePayload(
|
||||
objectId: string,
|
||||
ids: string[],
|
||||
): AuthorizePayload {
|
||||
return {
|
||||
objectId,
|
||||
data: {
|
||||
button: [],
|
||||
column: [],
|
||||
moduleId: ids,
|
||||
resource: [],
|
||||
form: [],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* commands/role/authorize.ts — 角色绑定菜单 (sswflow M1 Task 9, 2026-08-01)
|
||||
*
|
||||
* 设计依据: sswflow design §7.6 (依赖顺序: app → schema 审计 → dict → role →
|
||||
* dm 缺口补齐 → form → workflow → menu → permissions → test)
|
||||
* Phase 6.6 给 7 个 sswflow role 绑定 18 个菜单. dacli 之前无此命令.
|
||||
*
|
||||
* web 权威源: web/apps/jnpf-web-apps-main/src/api/permission/auth.ts
|
||||
* - getAuthValues(objectId, data) — POST {roleId}/Values
|
||||
* - updateAuthList(objectId, data) — PUT {roleId}
|
||||
* webapi 镜像 (v0.22+ 铁律 3): webapi/authority.ts initWebapi() + Proxy
|
||||
*
|
||||
* @DS safety: 不重新 HTTP, 只通过 webapi 真镜像.
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import { initWebapi, AuthorityApi } from '../../webapi/authority.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts'
|
||||
import { validateAuthorizeInput, buildAuthorizePayload } from './_authorize.ts'
|
||||
|
||||
interface AuthorizeOpts {
|
||||
roleId: string
|
||||
/** 逗号分隔 menu ids */
|
||||
menuIds?: string
|
||||
/** 逗号分隔 moduleIds (与 menuIds 等价, web 后端统一 moduleId 字段) */
|
||||
moduleIds?: string
|
||||
verbose?: boolean
|
||||
json?: boolean
|
||||
/** dry-run 不写库, 仅展示 diff */
|
||||
dryRun?: boolean
|
||||
}
|
||||
|
||||
export function buildRoleAuthorizeCommand(): Command {
|
||||
const cmd = new Command('authorize')
|
||||
.description('给角色绑定菜单 (sswflow M1, webapi/authority.ts 镜像 web permission/auth.ts)')
|
||||
.requiredOption('--roleId <id>', '角色 id (JNPF 雪花 id)')
|
||||
.option('--menuIds <ids>', '菜单 id 列表 (逗号分隔)')
|
||||
.option('--moduleIds <ids>', '模块 id 列表 (逗号分隔, 等价 menuIds, web 端字段名 moduleId)')
|
||||
.option('--dry-run', '不写库, 仅展示 diff', false)
|
||||
addOutputOptions(cmd)
|
||||
.action(async (opts: AuthorizeOpts) => {
|
||||
setupOutputFilter(opts)
|
||||
const c = await JnpfClient.fromToken()
|
||||
|
||||
await wrapCommand({
|
||||
command: 'role authorize',
|
||||
appCode: c.appCode,
|
||||
startTime: Date.now(),
|
||||
verbose: opts.verbose,
|
||||
json: opts.json,
|
||||
fixes: [],
|
||||
}, async (ctx) => {
|
||||
try {
|
||||
// 复用 _authorize.ts 纯函数做参数校验 + payload 构造 (单测覆盖)
|
||||
const validation = validateAuthorizeInput({
|
||||
roleId: opts.roleId,
|
||||
menuIds: opts.menuIds
|
||||
? opts.menuIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
: undefined,
|
||||
moduleIds: opts.moduleIds
|
||||
? opts.moduleIds.split(',').map((s) => s.trim()).filter(Boolean)
|
||||
: undefined,
|
||||
})
|
||||
if (!validation.ok) {
|
||||
return ctx.fail(validation.msg, { roleId: opts.roleId })
|
||||
}
|
||||
|
||||
await initWebapi(c)
|
||||
|
||||
if (opts.dryRun) {
|
||||
log.info(`[dry-run] role authorize ${opts.roleId} -> ${validation.ids.length} 菜单 (不写库)`)
|
||||
ctx.success({ roleId: opts.roleId, menuIds: validation.ids, dryRun: true })
|
||||
return
|
||||
}
|
||||
|
||||
const payload = buildAuthorizePayload(validation.objectId, validation.ids)
|
||||
const res = (await AuthorityApi.updateAuthList(payload.objectId, payload.data)) as {
|
||||
code?: number
|
||||
msg?: string
|
||||
}
|
||||
|
||||
if (res.code !== undefined && res.code !== 200) {
|
||||
return ctx.fail(`role authorize 失败: ${res.msg || '未知错误'}`, {
|
||||
roleId: opts.roleId,
|
||||
})
|
||||
}
|
||||
|
||||
log.info(`✓ 角色 id=${opts.roleId} 绑定 ${validation.ids.length} 菜单 OK`)
|
||||
ctx.success({ roleId: opts.roleId, menuIds: validation.ids })
|
||||
} catch (e) {
|
||||
ctx.fail(`role authorize 失败: ${(e as Error).message?.slice(0, 200)}`, {
|
||||
roleId: opts.roleId,
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
installHelpHook(cmd, {
|
||||
purpose: '给角色绑定菜单 (sswflow M1, 通过 webapi/authority.ts 镜像 web permission/auth.ts updateAuthList)',
|
||||
required: { '--roleId': '角色 id' },
|
||||
optional: {
|
||||
'--menuIds': '菜单 id 列表 (逗号分隔, 与 --moduleIds 等价)',
|
||||
'--moduleIds': '菜单 id 列表 (web 字段名 moduleId)',
|
||||
'--dry-run': '不写库, 仅 diff 演示',
|
||||
},
|
||||
example: 'dacli role authorize --roleId=643238393602117 --menuIds=100,101,102',
|
||||
source: {
|
||||
web: 'web/apps/jnpf-web-apps-main/src/api/permission/auth.ts',
|
||||
api: 'PUT /api/permission/Authority/Data/{objectId}',
|
||||
ref: 'web/apps/jnpf-web-apps-main/src/views/permission/role/Form.vue:save()',
|
||||
},
|
||||
notes: [
|
||||
'sswflow M1 (2026-08-01 Task 9): role authorize 是新命令, 镜像 web permission/auth.ts.updateAuthList',
|
||||
'web 后端契约: data.moduleId = 菜单 id 数组; data.button/column/resource/form 留空',
|
||||
'id 格式校验同 role assign (JNPF 雪花 id 纯数字 10-30 位)',
|
||||
],
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* webapi/authority.ts — 直接 import web 端 permission/auth.ts (sswflow M1 Task 9, 2026-08-01)
|
||||
*
|
||||
* web/apps/jnpf-web-apps-main/src/api/permission/auth.ts 6 函数:
|
||||
* getAuthValues, updateAuthList, getCommonAuthValues, updateCommonAuthList
|
||||
*
|
||||
* 设计原因 (来自 plan Task 9):
|
||||
* - sswflow M1 需要给 sswflowPlatformAdmin 等角色绑定菜单 (设计 §7.6)
|
||||
* - dacli 之前没有 role authorize 子命令, 必须按镜像架构扩展
|
||||
* - webapi 镜像保证与 web 端 API 完全一致 (铁律 3: 0 复刻 0 漂移)
|
||||
*
|
||||
* 行为约定:
|
||||
* - 调用前必须先 `await initWebapi(client)`
|
||||
* - 返回值由 web 端 defHttp transformResponseHook 解构 {code, msg, data}, 直接拿 .data
|
||||
*/
|
||||
import { getCcWorkDir } from '../core/paths.ts'
|
||||
import { JnpfClient } from '../core/client.ts'
|
||||
import { loadWebModule } from './_loader.ts'
|
||||
|
||||
const AUTHORITY_SRC = `${getCcWorkDir()}/web/apps/jnpf-web-apps-main/src/api/permission/auth.ts`
|
||||
|
||||
let cached: any = null
|
||||
|
||||
export async function initWebapi(client: JnpfClient): Promise<void> {
|
||||
if (cached) return
|
||||
const { initDefHttpShim } = await import('./_defhttp_shim.ts')
|
||||
initDefHttpShim(client)
|
||||
cached = await loadWebModule(AUTHORITY_SRC)
|
||||
}
|
||||
|
||||
export function isWebapiLoaded(): boolean {
|
||||
return cached !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* AuthorityApi — 镜像 web permission/auth.ts
|
||||
*/
|
||||
export namespace AuthorityApi {
|
||||
/** objectId = 角色/岗位/用户 id (objectType 默认 'Role') */
|
||||
export function getAuthValues(objectId: string, data: Record<string, unknown>): Promise<unknown> {
|
||||
return loadAuth.getAuthValues(objectId, data)
|
||||
}
|
||||
|
||||
export function updateAuthList(objectId: string, data: Record<string, unknown>): Promise<unknown> {
|
||||
return loadAuth.updateAuthList(objectId, data)
|
||||
}
|
||||
|
||||
export function getCommonAuthValues(
|
||||
type = 'Portal',
|
||||
objectId: string,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
return loadAuth.getCommonAuthValues(type, objectId, data)
|
||||
}
|
||||
|
||||
export function updateCommonAuthList(
|
||||
type: string,
|
||||
objectId: string,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
return loadAuth.updateCommonAuthList(type, objectId, data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy 包装的 webapi 模块
|
||||
*/
|
||||
export const loadAuth: any = new Proxy({} as any, {
|
||||
get(_target, prop) {
|
||||
if (!cached) {
|
||||
throw new Error(`authority 模块未初始化, 请先 await initWebapi(client)`)
|
||||
}
|
||||
return cached[prop]
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* tests/unit/form_update_read_only.test.ts — sswflow M1 Task 9
|
||||
*
|
||||
* 纯函数测试 makeFormReadOnly (不依赖 commander, 不依赖 webapi).
|
||||
* 命令执行通过 webapi 真镜像 (visualDev.update + release) 已在 manual 流程验证.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { makeFormReadOnly } from '../../src/commands/form/_readonly.ts'
|
||||
|
||||
const ORIG_FORM = {
|
||||
id: 'sswflowFlowRun_formId',
|
||||
enCode: 'sswflowFlowRun',
|
||||
fullName: 'SSWFlow运行实例',
|
||||
formData: JSON.stringify({
|
||||
fields: [
|
||||
{ field: 'f_id', label: 'id' },
|
||||
{ field: 'f_status', label: '状态' },
|
||||
],
|
||||
columnList: [
|
||||
{
|
||||
field: 'f_status',
|
||||
label: '状态',
|
||||
children: [{ field: 'f_id', label: 'id' }],
|
||||
},
|
||||
],
|
||||
btnsList: [{ value: 'add', label: '新增' }, { value: 'edit', label: '编辑' }],
|
||||
tableBtns: [{ value: 'delete', label: '删除' }],
|
||||
}),
|
||||
// 故意没传 tables (物理表零变更是契约)
|
||||
}
|
||||
|
||||
describe('form update --read-only — makeFormReadOnly (sswflow M1 Task 9)', () => {
|
||||
it('不携带 tables 字段 → 物理表零变更', () => {
|
||||
const r = makeFormReadOnly({ ...ORIG_FORM, tables: { foo: 'bar' } })
|
||||
expect(r.schema).not.toHaveProperty('tables')
|
||||
})
|
||||
|
||||
it('清空 btnsList 与 tableBtns (新增/编辑/删除按钮消失)', () => {
|
||||
const r = makeFormReadOnly(ORIG_FORM)
|
||||
const fd = JSON.parse(r.schema.formData as string)
|
||||
expect(fd.btnsList).toEqual([])
|
||||
expect(fd.tableBtns).toEqual([])
|
||||
})
|
||||
|
||||
it('字段 disabled + readOnly 锁定', () => {
|
||||
const r = makeFormReadOnly(ORIG_FORM)
|
||||
const fd = JSON.parse(r.schema.formData as string)
|
||||
for (const f of fd.fields) {
|
||||
expect(f.disabled).toBe(true)
|
||||
expect(f.readOnly).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('columnList disabled (含 children 嵌套)', () => {
|
||||
const r = makeFormReadOnly(ORIG_FORM)
|
||||
const fd = JSON.parse(r.schema.formData as string)
|
||||
for (const c of fd.columnList) {
|
||||
expect(c.disabled).toBe(true)
|
||||
for (const cc of c.children) {
|
||||
expect(cc.disabled).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('formData 必须是字符串 (web 后端契约)', () => {
|
||||
const r = makeFormReadOnly(ORIG_FORM)
|
||||
expect(typeof r.schema.formData).toBe('string')
|
||||
})
|
||||
|
||||
it('不修改原对象 (返回新 schema)', () => {
|
||||
const orig = JSON.parse(JSON.stringify(ORIG_FORM))
|
||||
const r = makeFormReadOnly(orig)
|
||||
expect(orig.formData).toBe(ORIG_FORM.formData) // 原对象 formData 字符串未变
|
||||
expect(r.schema).not.toBe(orig)
|
||||
})
|
||||
|
||||
it('空字段/空列也安全 (无报错)', () => {
|
||||
const r = makeFormReadOnly({ formData: JSON.stringify({ fields: [], columnList: [] }) })
|
||||
expect(r.modified.fieldsLocked).toBe(0)
|
||||
expect(r.modified.columnsLocked).toBe(0)
|
||||
})
|
||||
|
||||
it('formData 是 object 也能处理 (web 端兼容)', () => {
|
||||
const fd = { fields: [{ field: 'f_a' }], btnsList: [{ value: 'add' }] }
|
||||
const r = makeFormReadOnly({ formData: fd })
|
||||
expect(typeof r.schema.formData).toBe('string')
|
||||
const parsed = JSON.parse(r.schema.formData as string)
|
||||
expect(parsed.btnsList).toEqual([])
|
||||
expect(parsed.fields[0].disabled).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* tests/unit/role_authorize.test.ts — sswflow M1 Task 9
|
||||
*
|
||||
* 镜像架构 0 复刻 0 漂移: 测试必须断言契约 (id 校验 + payload shape),
|
||||
* 命令执行通过 webapi 真镜像 (不在本测试覆盖范围, 已有 manual 跑过).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
validateAuthorizeInput,
|
||||
buildAuthorizePayload,
|
||||
} from '../../src/commands/role/_authorize.ts'
|
||||
|
||||
describe('role authorize — validateAuthorizeInput (sswflow M1 Task 9)', () => {
|
||||
it('menuIds 解析为字符串数组', () => {
|
||||
const r = validateAuthorizeInput({
|
||||
roleId: '643238393602117',
|
||||
menuIds: ['12345678901', '12345678902', '12345678903'],
|
||||
})
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect(r.ids).toEqual(['12345678901', '12345678902', '12345678903'])
|
||||
})
|
||||
|
||||
it('--moduleIds 与 --menuIds 等价 (web 字段名 moduleId)', () => {
|
||||
const r = validateAuthorizeInput({
|
||||
roleId: '643238393602117',
|
||||
moduleIds: ['12345678901', '12345678902'],
|
||||
})
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect(r.ids).toEqual(['12345678901', '12345678902'])
|
||||
})
|
||||
|
||||
it('拒绝非数字 roleId 提前拦下 (避免 500)', () => {
|
||||
const r = validateAuthorizeInput({ roleId: 'admin', menuIds: ['12345678901'] })
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('要求 menuIds/moduleIds 至少一个', () => {
|
||||
const r = validateAuthorizeInput({ roleId: '643238393602117' })
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('空数组被拒', () => {
|
||||
const r = validateAuthorizeInput({ roleId: '643238393602117', menuIds: [] })
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('单个非数字 menuId 被拒', () => {
|
||||
const r = validateAuthorizeInput({
|
||||
roleId: '643238393602117',
|
||||
menuIds: ['12345678901', 'abc', '12345678903'],
|
||||
})
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('roleId 短于 10 位被拒', () => {
|
||||
const r = validateAuthorizeInput({ roleId: '123', menuIds: ['12345678901'] })
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('menuIds 是逗号分隔字符串时也能解析 (CLI 参数兼容)', () => {
|
||||
// CLI: --menuIds="12345678901,12345678902"
|
||||
// 调用方需要先 split(','), 这里 helper 仅接 string[] 入参
|
||||
const r = validateAuthorizeInput({
|
||||
roleId: '643238393602117',
|
||||
menuIds: ['12345678901', '12345678902'],
|
||||
})
|
||||
expect(r.ok).toBe(true)
|
||||
if (r.ok) expect(r.ids).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('role authorize — buildAuthorizePayload (web 后端契约)', () => {
|
||||
it('镜像 web permission/auth.ts.updateAuthList (data.moduleId = 菜单 ids)', () => {
|
||||
const p = buildAuthorizePayload('643238393602117', [
|
||||
'12345678901',
|
||||
'12345678902',
|
||||
'12345678903',
|
||||
])
|
||||
expect(p.objectId).toBe('643238393602117')
|
||||
expect(p.data.moduleId).toEqual([
|
||||
'12345678901',
|
||||
'12345678902',
|
||||
'12345678903',
|
||||
])
|
||||
})
|
||||
|
||||
it('data.button/column/resource/form 留空', () => {
|
||||
const p = buildAuthorizePayload('643238393602117', ['12345678901'])
|
||||
expect(p.data.button).toEqual([])
|
||||
expect(p.data.column).toEqual([])
|
||||
expect(p.data.resource).toEqual([])
|
||||
expect(p.data.form).toEqual([])
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user