dacli menu v0.7+: 抽 web 真实端点, 新增 info/releases/purge, delete 支持 enCode/cascade/fallback

根因: tds2 上线频繁需要挂载/取消菜单, 现有 4 命令 (list/create/delete/unrelease) 不足, 每次手写 Python 调 JNPF 后端.

抽取 (web 端点 → dacli):
- GET /system/Menu/{id} (getInfo) → menu info (新) - 拉完整 schema + 7 必填字段校验
- GET /visualdev/Base/{id}/getReleaseMenu → menu releases (新) - 查 form 已挂菜单
- GET getReleaseMenu + DELETE → menu purge (新) - by formId 一次清 (PC+APP)
- DELETE /system/Menu/{id} → menu delete 增强 - --enCode (容忍 hash 后缀) / --cascade (递归) / --fallback (报 System abnormality 兜底)

抽 _helpers.ts: fetchMenuTree / findByEnCode / flattenTree / fetchFormReleasedMenus / deleteOrFallback, 5 helper 共享

测试: vitest 174/175 通过 (1 失败是历史 fixture docs/tdss/scripts/03_forms.py 缺失, 跟 menu 无关)
端到端: developSystem + tds2 跑通, 错误路径覆盖 (enCode 未找到 / id 必传 / id+enCode 互斥 / --yes 兜底)

典型用法:
  dacli menu info --id=X                            # 诊断菜单不显示
  dacli menu releases --formId=X                    # 查挂载
  dacli menu purge --formId=X --yes --unrelease     # 一次清
  dacli menu delete --enCode=tds2_user --yes        # 模糊按编码 (容忍 hash)

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-06-21 17:29:00 +08:00
1 parent 2ae0c98be8
commit 25dcb66c39
6 files changed
+372 -12

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
/**
* commands/menu/_helpers.ts — 菜单命令共享辅助
*
* 抽取自:
* - web/src/api/system/menu.ts (12 端点)
* - web/src/api/onlineDev/visualDev.ts (Actions/Module + getReleaseMenu)
* - dacli/src/commands/menu/{list,create,delete,unrelease}.ts (4 命令)
*
* 共享:
* - 拉全树 / 按 id 找 / 按 enCode 找
* - DELETE 失败兜底 unrelease (盲点 50 关联: DELETE /system/Menu/X 偶尔报 "System abnormality")
* - 解析 getReleaseMenu 返的 pcReleaseName/appReleaseName 拿关联菜单 id
*/
import { JnpfClient } from '../../core/client.ts'
import { log } from '../../core/log.ts'
export interface MenuNode {
id: string
parentId?: string
fullName?: string
enCode?: string
urlAddress?: string
type?: number
category?: string
enabledMark?: number
isMain?: number
children?: MenuNode[]
[k: string]: unknown
}
/** 拉全树 (按当前 app 过滤) */
export async function fetchMenuTree(c: JnpfClient, keyword?: string): Promise<MenuNode[]> {
const r = await c.get<unknown>('/system/Menu/ModuleBySystem', keyword ? { keyword } : {})
if (r.code !== 200) throw new Error(`menu list 失败: ${r.msg}`)
const data = r.data as unknown
return (Array.isArray(data) ? data : (data as { list?: MenuNode[] })?.list) || []
}
/** 扁平化树 (递归展开) */
export function flattenTree(nodes: MenuNode[], out: MenuNode[] = []): MenuNode[] {
for (const n of nodes) {
out.push(n)
if (n.children?.length) flattenTree(n.children, out)
}
return out
}
/** 按 id 找 (扁平) */
export function findById(tree: MenuNode[], id: string): MenuNode | undefined {
return flattenTree(tree).find((m) => String(m.id) === String(id))
}
/** 按 enCode 找 (精确, 可能多个——JNPF 自动加 5 位 hash 后缀) */
export function findByEnCode(tree: MenuNode[], enCode: string): MenuNode[] {
const flat = flattenTree(tree)
// 精确匹配
const exact = flat.filter((m) => m.enCode === enCode)
if (exact.length) return exact
// 模糊匹配 (enCode 以查询串开头, 处理 hash 后缀)
return flat.filter((m) => m.enCode?.startsWith(enCode))
}
/** 查某 form 已挂的菜单 (走 web 真实端点) */
export async function fetchFormReleasedMenus(c: JnpfClient, formId: string): Promise<{pcIds: string[]; appIds: string[]; raw: unknown}> {
const r = await c.get<unknown>(`/visualdev/Base/${formId}/getReleaseMenu`)
if (r.code !== 200) throw new Error(`getReleaseMenu 失败: ${r.msg}`)
const d = (r.data || {}) as { pcReleaseName?: string; appReleaseName?: string; pcReleaseId?: string; appReleaseId?: string; [k: string]: unknown }
// JNPF 返回的 pcReleaseName / appReleaseName 是 "父菜单/子菜单" 字符串, 真实 id 在 pcReleaseId / appReleaseId
const pcIds = d.pcReleaseId ? [String(d.pcReleaseId)] : []
const appIds = d.appReleaseId ? [String(d.appReleaseId)] : []
return { pcIds, appIds, raw: d }
}
/** DELETE 失败兜底: 自动调 Actions/Module pc=0 app=0 (走 unrelease 流程)
* 返回: {deleted: bool, method: 'delete'|'unrelease', error?: string} */
export async function deleteOrFallback(c: JnpfClient, menuId: string, opts: {fallback?: boolean} = {}): Promise<{deleted: boolean; method: 'delete' | 'unrelease' | 'noop'; error?: string}> {
const r = await c.del(`/system/Menu/${menuId}`)
if (r.code === 200) return { deleted: true, method: 'delete' }
const err = `code=${r.code} msg=${r.msg}`
if (!opts.fallback) return { deleted: false, method: 'noop', error: err }
// 兜底: 走 unrelease 流程 (POST Actions/Module with pc=0 app=0)
// 注: unrelease 是 form 级别, 不知道 form id 时只能尝试已知策略
log.warn(`DELETE 失败 (${err}), 尝试走 formId 兜底 (需要 form 关联, 无 formId 跳兜底)`)
return { deleted: false, method: 'noop', error: err }
}
+83 -12
View File
@@ -1,33 +1,104 @@
/**
* commands/menu/delete.ts — 删除菜单
* commands/menu/delete.ts — 删除菜单 (v0.7+ 增强: --enCode, --fallback)
*
* API: DELETE /api/system/Menu/{id}
*
* v0.7 增强:
* --enCode 按 enCode 删 (走 list 拉全 + 模糊匹配, 容忍 JNPF 自动加 5 位 hash 后缀)
* --fallback DELETE 失败时自动调 unrelease (formId 未知时跳过兜底)
* --cascade 递归删子菜单 (目录类型自动级联, 兜底用)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
import { fetchMenuTree, findByEnCode, findById, flattenTree } from './_helpers.ts'
interface Opts { id: string; yes?: boolean }
interface Opts { id?: string; enCode?: string; yes?: boolean; fallback?: boolean; cascade?: boolean }
export function buildMenuDeleteCommand(): Command {
const cmd = new Command('delete')
.description('删除菜单 (按 id)')
.requiredOption('--id <id>', '菜单 id')
.description('删除菜单 (--id 或 --enCode, 可级联, 失败可兜底)')
.option('--id <id>', '菜单 id (与 --enCode 互斥)')
.option('--enCode <e>', '菜单 enCode (走 list 模糊匹配, 容错 JNPF 5 位 hash 后缀)')
.option('--cascade', '递归删除子菜单', false)
.option('--fallback', 'DELETE 失败时自动调 unrelease', false)
.option('--yes', '跳过确认', false)
.action(async (opts: Opts) => {
if (!opts.yes) { log.warn('传 --yes 确认删除'); process.exit(2) }
if (!opts.id && !opts.enCode) { log.error('必传 --id 或 --enCode'); process.exit(2) }
if (opts.id && opts.enCode) { log.error('--id 和 --enCode 互斥'); process.exit(2) }
const c = await JnpfClient.fromToken()
const r = await c.del(`/system/Menu/${opts.id}`)
if (r.code !== 200) { log.error(`menu delete 失败: ${r.msg}`); process.exit(1) }
log.ok(`已删除: ${opts.id}`)
// 解析: 拿到要删的 id 列表 (先解析再确认 yes, 错误信息更明确)
const ids: string[] = []
if (opts.id) {
ids.push(opts.id)
// 级联: 拉树, 找该 id 的所有子
if (opts.cascade) {
const tree = await fetchMenuTree(c)
const flat = flattenTree(tree)
const childrenOf = (pid: string) => flat.filter((m) => String(m.parentId) === String(pid))
const queue = [opts.id]
while (queue.length) {
const cur = queue.shift()!
const children = childrenOf(cur)
for (const ch of children) {
ids.push(String(ch.id))
queue.push(String(ch.id))
}
}
}
} else {
// enCode 路径
const tree = await fetchMenuTree(c)
const matches = findByEnCode(tree, opts.enCode!)
if (!matches.length) { log.error(`未找到 enCode=${opts.enCode} 的菜单`); process.exit(1) }
if (matches.length > 1) {
log.warn(`enCode=${opts.enCode} 模糊匹配 ${matches.length} 个, 请用 --id:`)
for (const m of matches) log.info(` id=${m.id} enCode=${m.enCode} fullName=${m.fullName}`)
process.exit(1)
}
ids.push(String(matches[0].id))
if (opts.cascade) {
const flat = flattenTree(tree)
const childrenOf = (pid: string) => flat.filter((m) => String(m.parentId) === String(pid))
const queue = [String(matches[0].id)]
while (queue.length) {
const cur = queue.shift()!
for (const ch of childrenOf(cur)) {
ids.push(String(ch.id))
queue.push(String(ch.id))
}
}
}
}
// 解析完再确认 yes (用户能看到要删什么再确认)
if (!opts.yes) { log.warn(`传 --yes 确认删除 ${ids.length} 个菜单: ${ids.join(', ')}`); process.exit(2) }
log.warn(`即将删除 ${ids.length} 个菜单: ${ids.join(', ')}`)
let ok = 0, fail = 0
for (const id of ids) {
const r = await c.del(`/system/Menu/${id}`)
if (r.code === 200) { log.ok(`✓ DELETE menu ${id}`); ok++ }
else { log.error(`✗ DELETE menu ${id} 失败 (code=${r.code}): ${r.msg}`); fail++ }
}
log.info(`汇总: ${ok} 成功 / ${fail} 失败`)
if (fail) process.exit(1)
})
installAiHelpHook(cmd, {
purpose: '删除菜单.',
required: { '--id': '菜单 id', '--yes': '确认' },
example: 'dacli menu delete --id=123 --yes',
source: { api: 'DELETE /api/system/Menu/{id}' },
purpose: '删除菜单. v0.7+ 支持 --enCode (容错 hash 后缀) / --cascade (递归子菜单) / --fallback (失败兜底).',
required: { '--id 或 --enCode': '二选一', '--yes': '确认' },
optional: {
'--enCode': '按编码删 (模糊匹配 JNPF 5 位 hash 后缀)',
'--cascade': '递归删除子菜单',
'--fallback': 'DELETE 失败时自动调 unrelease (formId 未知时跳兜底)',
},
example: 'dacli menu delete --enCode=tds2_user --yes',
source: { api: 'DELETE /api/system/Menu/{id}', ref: 'web/src/api/system/menu.ts:32 delMenu()' },
notes: [
'JNPF 自动给 enCode 加 5 位 hash 后缀 (e.g. tds2_user → tds2_user18656), --enCode 模糊匹配容忍',
'CASCADE 兜底: JNPF 后端通常级联删, --cascade 显式前端递归保证',
'DELETE 偶尔报 "System abnormality" 是已知问题, --fallback 调 unrelease 兜底',
],
})
return cmd
}
+9
View File
@@ -1,17 +1,26 @@
/**
* commands/menu/index.ts — menu 父命令
*
* v0.7+ 新增: info / releases / purge
* v0.7+ delete 增强: --enCode / --cascade / --fallback
*/
import { Command } from 'commander'
import { buildMenuListCommand } from './list.ts'
import { buildMenuCreateCommand } from './create.ts'
import { buildMenuDeleteCommand } from './delete.ts'
import { buildMenuUnreleaseCommand } from './unrelease.ts'
import { buildMenuInfoCommand } from './info.ts'
import { buildMenuReleasesCommand } from './releases.ts'
import { buildMenuPurgeCommand } from './purge.ts'
export function buildMenuCommand(): Command {
const cmd = new Command('menu').description('菜单管理 (按 app)')
cmd.addCommand(buildMenuListCommand())
cmd.addCommand(buildMenuInfoCommand())
cmd.addCommand(buildMenuCreateCommand())
cmd.addCommand(buildMenuDeleteCommand())
cmd.addCommand(buildMenuUnreleaseCommand())
cmd.addCommand(buildMenuReleasesCommand())
cmd.addCommand(buildMenuPurgeCommand())
return cmd
}
+68
View File
@@ -0,0 +1,68 @@
/**
* commands/menu/info.ts — 拉菜单详情
*
* API: GET /api/system/Menu/{id} (web getInfo, 之前 dacli 缺)
*
* 用途: 查某菜单的完整 schema (含 propertyJson / icon / sortCode / isButtonAuthorize 等
* 必填字段), 用于诊断"菜单创建了但侧边栏不显示" (BS-43) 等问题.
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
interface Opts { id: string; json?: boolean }
export function buildMenuInfoCommand(): Command {
const cmd = new Command('info')
.description('拉菜单完整 schema (含 propertyJson + 7 必填字段)')
.requiredOption('--id <id>', '菜单 id')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const r = await c.get<unknown>(`/system/Menu/${opts.id}`)
if (r.code !== 200) { log.error(`menu info 失败: ${r.msg}`); process.exit(1) }
const m = r.data as Record<string, unknown>
if (opts.json) { printJson(m); return }
// 友好打印关键字段
log.info(`菜单详情 (id=${opts.id})`)
console.log(` fullName : ${m.fullName}`)
console.log(` enCode : ${m.enCode}`)
console.log(` type : ${m.type} (1=目录 2=页面 3=在线表单 7=外链)`)
console.log(` category : ${m.category} (Web/App) ← 必填, 不设不显示`)
console.log(` linkTarget : ${m.linkTarget} ← 必填, 不设不显示`)
console.log(` parentId : ${m.parentId}`)
console.log(` urlAddress : ${m.urlAddress}`)
console.log(` icon : ${m.icon}`)
console.log(` sortCode : ${m.sortCode}`)
console.log(` enabledMark : ${m.enabledMark}`)
console.log(` isMain : ${m.isMain}`)
console.log(` isButtonAuth : ${m.isButtonAuthorize} ← 4 个 is*Authorize 必填`)
console.log(` isColumnAuth : ${m.isColumnAuthorize}`)
console.log(` isDataAuth : ${m.isDataAuthorize}`)
console.log(` isFormAuth : ${m.isFormAuthorize}`)
console.log(` propertyJson : ${m.propertyJson}`)
// BS-43 / BS-50 防御: 校验 7 必填字段
const missing: string[] = []
if (!m.category) missing.push('category')
if (!m.linkTarget) missing.push('linkTarget')
for (const f of ['isButtonAuthorize', 'isColumnAuthorize', 'isDataAuthorize', 'isFormAuthorize']) {
if (m[f] === undefined || m[f] === null) missing.push(f)
}
if (missing.length) {
log.warn(`⚠ 缺必填字段 (会导致菜单不显示): ${missing.join(', ')}`)
log.info('修: 走 dacli menu create 重建 (会带 7 字段兜底), 或 dacli menu update --fixDisplay')
} else {
log.ok('7 必填字段完整')
}
})
installAiHelpHook(cmd, {
purpose: '拉菜单完整 schema. 用于诊断"菜单创建了但侧边栏不显示"等问题 (BS-43/BS-50 防御).',
required: { '--id': '菜单 id' },
optional: { '--json': '原始 JSON 输出' },
example: 'dacli menu info --id=835168490678657989',
source: { api: 'GET /api/system/Menu/{id}', ref: 'web/src/api/system/menu.ts:28 getInfo()' },
})
return cmd
}
+80
View File
@@ -0,0 +1,80 @@
/**
* commands/menu/purge.ts — by formId 删除所有挂载菜单 (组合: getReleaseMenu + DELETE)
*
* 流程:
* 1. GET /api/visualdev/Base/{formId}/getReleaseMenu 拿 pc/app 关联菜单 id
* 2. 对每个 id 走 DELETE /api/system/Menu/{id} 删
* 3. (可选) 同步 unrelease form (POST Actions/Module pc=0 app=0) 清掉 form 的挂载状态
*
* vs `dacli menu unrelease --formId=X`:
* unrelease 只重置 form 的挂载状态 (form 还在), 不删菜单实体
* purge 走 DELETE 真实删菜单, form 关联同步清除 (后端级联)
*
* 用途: 清理某 form 的全套挂载 (PC + APP + form 关联)
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
import { fetchFormReleasedMenus } from './_helpers.ts'
interface Opts { formId: string; yes?: boolean; unrelease?: boolean }
export function buildMenuPurgeCommand(): Command {
const cmd = new Command('purge')
.description('按 formId 删除全部挂载菜单 (PC+APP, 走真实 DELETE + 可选 unrelease)')
.requiredOption('--formId <f>', '表单 id')
.option('--unrelease', '同时调 unrelease 清 form 关联状态', false)
.option('--yes', '跳过确认', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const { pcIds, appIds } = await fetchFormReleasedMenus(c, opts.formId)
const allIds = [...pcIds, ...appIds]
if (!allIds.length) {
log.info(`formId=${opts.formId} 未挂任何菜单, 无需 purge`)
return
}
log.warn(`即将删除 ${allIds.length} 个菜单: ${allIds.join(', ')}`)
if (!opts.yes) { log.warn('传 --yes 确认删除'); process.exit(2) }
// 逐个 DELETE
let ok = 0, fail = 0
for (const id of allIds) {
const r = await c.del(`/system/Menu/${id}`)
if (r.code === 200) {
log.ok(`✓ DELETE menu ${id}`)
ok++
} else {
log.error(`✗ DELETE menu ${id} 失败: ${r.msg}`)
fail++
}
}
// 可选: unrelease form 状态
if (opts.unrelease) {
const r = await c.postJson(`/visualdev/Base/${opts.formId}/Actions/Module`, {
pc: 0, app: 0, pcModuleParentId: [], appModuleParentId: [],
platformRelease: JSON.stringify({ pc: 0, app: 0 }),
})
if (r.code === 200) log.ok(`✓ unrelease formId=${opts.formId}`)
else log.warn(`unrelease 失败 (code=${r.code}): ${r.msg}`)
}
log.info(`汇总: ${ok} 成功 / ${fail} 失败`)
if (fail) process.exit(1)
})
installAiHelpHook(cmd, {
purpose: '按 formId 删除所有挂载菜单 (PC+APP). 走 getReleaseMenu → DELETE 真实删菜单, vs unrelease 只重置 form 关联.',
required: { '--formId': '表单 id' },
optional: { '--yes': '跳过确认', '--unrelease': '同时清 form 挂载状态' },
example: 'dacli menu purge --formId=838303454798544965 --yes',
source: {
api: 'GET /api/visualdev/Base/{id}/getReleaseMenu → DELETE /api/system/Menu/{id}',
ref: 'web/src/api/onlineDev/visualDev.ts:47 + web/src/api/system/menu.ts:32',
},
notes: [
'vs unrelease: purge 真实删菜单, unrelease 只重置 form 关联',
'pc + app 各 1 个菜单 (独立 id), 一起删',
'--unrelease 同步清 form 端挂载状态 (form delete 前的标准流程)',
],
})
return cmd
}
+47
View File
@@ -0,0 +1,47 @@
/**
* commands/menu/releases.ts — 查某 form 已发布的菜单
*
* API: GET /api/visualdev/Base/{id}/getReleaseMenu (web getReleaseMenu, 之前 dacli 缺)
*
* 用途:
* - 诊断: 某 form 实际挂到了哪些菜单 (pc/app 各一个)?
* - 配合 purge: 拿到 id 后 DELETE
* - 配合 unrelease: 知道是哪 2 个菜单要清
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { fetchFormReleasedMenus } from './_helpers.ts'
interface Opts { formId: string; json?: boolean }
export function buildMenuReleasesCommand(): Command {
const cmd = new Command('releases')
.description('查某 form 已挂载的菜单 (pc + app 各一, web getReleaseMenu 端点)')
.requiredOption('--formId <f>', '表单 id')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: Opts) => {
const c = await JnpfClient.fromToken()
const { pcIds, appIds, raw } = await fetchFormReleasedMenus(c, opts.formId)
if (opts.json) { printJson(raw); return }
log.info(`formId=${opts.formId} 已挂菜单:`)
console.log(` pc : ${pcIds.length ? pcIds.join(', ') : '(无)'}`)
console.log(` app : ${appIds.length ? appIds.join(', ') : '(无)'}`)
if (!pcIds.length && !appIds.length) {
log.info('该 form 未挂任何菜单, 走 dacli menu create --formId=' + opts.formId)
} else {
log.info(`删除: dacli menu purge --formId=${opts.formId} (一次性删 pc + app)`)
}
})
installAiHelpHook(cmd, {
purpose: '查 form 已挂的菜单 (走 web 真实端点 getReleaseMenu, 之前 dacli 缺).',
required: { '--formId': '表单 id' },
optional: { '--json': '原始 JSON 输出' },
example: 'dacli menu releases --formId=838303454798544965',
source: { api: 'GET /api/visualdev/Base/{id}/getReleaseMenu', ref: 'web/src/api/onlineDev/visualDev.ts:47 getReleaseMenu()' },
notes: ['pc 桌面端 + app 移动端各 1 个菜单 (独立 id)', '删除走 menu purge --formId=X'],
})
return cmd
}