feat(dacli): org/monitor/report/doc 小命令 wrapCommand 迁移 (8 exit 收口)

org/create (旧 printCommandEnd 升级) + org/tree, monitor/server, report/delete (保留 --cascade 级联清理), doc/search (无 appCode 本地文件搜索). process.exit → ctx.fail.

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-21 21:26:43 +08:00
1 parent 1ee19dd23c
commit 0d9151f343
5 files changed
+270 -225

No files matched your search

+73 -57
View File
@@ -10,6 +10,7 @@ import { existsSync } from 'node:fs'
import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { parseFile } from './_parser.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 (无 appCode, 跳过 L3); v2.2+ wrapCommand 收口 5c
interface Opts {
file: string
@@ -17,6 +18,8 @@ interface Opts {
context?: string
json?: boolean
stripMermaid?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
interface Match { sectionId: string; sectionTitle: string; line: number; snippet: string }
@@ -28,69 +31,82 @@ export function buildDocSearchCommand(): Command {
.requiredOption('--keyword <kw>', '搜索关键词 (支持正则)')
.option('--context <n>', '上下文行数 (默认 3)', '3')
.option('--strip-mermaid', '去除 Mermaid 代码块', false)
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: Opts) => {
const target = resolve(process.cwd(), opts.file)
if (!existsSync(target)) {
log.error(`文件不存在: ${target}`)
process.exit(1)
}
const ctx = parseInt(opts.context || '3', 10)
const { sections, fullText } = parseFile(target, opts.stripMermaid || false)
setupOutputFilter(opts)
let re: RegExp
try {
re = new RegExp(opts.keyword, 'i')
} catch (e) {
log.error(`--keyword 不是有效正则: ${(e as Error).message}`)
process.exit(2)
}
const matches: Match[] = []
for (const sec of sections.values()) {
const lines = sec.text.split('\n')
for (let i = 0; i < lines.length; i++) {
if (re.test(lines[i])) {
const from = Math.max(0, i - ctx)
const to = Math.min(lines.length, i + ctx + 1)
const snippet = lines
.slice(from, to)
.map((l, idx) => {
const lineNo = from + idx + 1
const marker = from + idx === i ? '>' : ' '
return `${marker} ${lineNo}: ${l}`
})
.join('\n')
matches.push({
sectionId: sec.id,
sectionTitle: sec.title,
line: i + 1,
snippet,
})
await wrapCommand({
command: 'doc search',
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const target = resolve(process.cwd(), opts.file)
if (!existsSync(target)) {
return ctx.fail(`文件不存在: ${target}`, { file: opts.file })
}
}
}
const ctxLines = parseInt(opts.context || '3', 10)
const { sections } = parseFile(target, opts.stripMermaid || false)
if (opts.json) {
printJson({ file: opts.file, keyword: opts.keyword, matchCount: matches.length, matches })
return
}
let re: RegExp
try {
re = new RegExp(opts.keyword, 'i')
} catch (e) {
return ctx.fail(`--keyword 不是有效正则: ${(e as Error).message}`, { keyword: opts.keyword })
}
log.info(`文件 ${opts.file} 关键词 "${opts.keyword}" 匹配 ${matches.length} 处`)
if (matches.length === 0) {
log.warn('无匹配')
return
}
let currentSection = ''
for (const m of matches) {
if (m.sectionId !== currentSection) {
console.log(`\n[${m.sectionId}] ${m.sectionTitle}`)
console.log('-'.repeat(80))
currentSection = m.sectionId
const matches: Match[] = []
for (const sec of sections.values()) {
const lines = sec.text.split('\n')
for (let i = 0; i < lines.length; i++) {
if (re.test(lines[i])) {
const from = Math.max(0, i - ctxLines)
const to = Math.min(lines.length, i + ctxLines + 1)
const snippet = lines
.slice(from, to)
.map((l, idx) => {
const lineNo = from + idx + 1
const marker = from + idx === i ? '>' : ' '
return `${marker} ${lineNo}: ${l}`
})
.join('\n')
matches.push({
sectionId: sec.id,
sectionTitle: sec.title,
line: i + 1,
snippet,
})
}
}
}
if (opts.json) {
printJson({ file: opts.file, keyword: opts.keyword, matchCount: matches.length, matches })
return ctx.success({ file: opts.file, keyword: opts.keyword, matchCount: matches.length })
}
log.info(`文件 ${opts.file} 关键词 "${opts.keyword}" 匹配 ${matches.length} 处`)
if (matches.length === 0) {
log.warn('无匹配')
return ctx.success({ file: opts.file, keyword: opts.keyword, matchCount: 0 })
}
let currentSection = ''
for (const m of matches) {
if (m.sectionId !== currentSection) {
console.log(`\n[${m.sectionId}] ${m.sectionTitle}`)
console.log('-'.repeat(80))
currentSection = m.sectionId
}
console.log(m.snippet)
console.log()
}
ctx.success({ file: opts.file, keyword: opts.keyword, matchCount: matches.length })
} catch (e) {
ctx.fail(`doc search 失败: ${(e as Error).message?.slice(0, 200)}`)
}
console.log(m.snippet)
console.log()
}
})
})
installHelpHook(cmd, {
+38 -22
View File
@@ -9,35 +9,51 @@ import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { initWebapi, loadMonitor } from '../../webapi/monitor.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface Opts { json?: boolean }
interface Opts { json?: boolean; verbose?: boolean }
export function buildMonitorServerCommand(): Command {
const cmd = new Command('server')
.description('服务器状态 (CPU/内存/磁盘/JVM, AI 性能诊断最高优先级, v0.11+ webapi)')
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: Opts) => {
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
await initWebapi(c)
// web getSysMonitor() 返回 { data: {...} } 格式, 需解 data 拿指标
const wrapper = (await loadMonitor.getSysMonitor()) as { data?: Record<string, unknown> } | Record<string, unknown>
const d = (wrapper as { data?: Record<string, unknown> }).data || (wrapper as Record<string, unknown>)
if (!d || Object.keys(d).length === 0) {
log.error(`monitor server 失败: 端点不可用`)
process.exit(1)
}
if (opts.json) {
printJson(d)
return
}
log.info('服务器状态')
console.log(` CPU : ${d.cpu || '-'} 核`)
console.log(` 内存 : 总 ${d.totalMemory || '-'} / 已用 ${d.usedMemory || '-'} / 空闲 ${d.freeMemory || '-'}`)
console.log(` 磁盘 : 总 ${d.totalDisk || '-'} / 已用 ${d.usedDisk || '-'} / 空闲 ${d.freeDisk || '-'}`)
console.log(` 系统 : ${d.os || '-'}`)
console.log(` JVM : 堆 ${d.jvmHeap || '-'} / 非堆 ${d.jvmNonHeap || '-'}`)
console.log(` 运行时间 : ${d.uptime || '-'}`)
console.log(` JDK版本 : ${d.jdkVersion || '-'}`)
await wrapCommand({
command: 'monitor server',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
await initWebapi(c)
// web getSysMonitor() 返回 { data: {...} } 格式, 需解 data 拿指标
const wrapper = (await loadMonitor.getSysMonitor()) as { data?: Record<string, unknown> } | Record<string, unknown>
const d = (wrapper as { data?: Record<string, unknown> }).data || (wrapper as Record<string, unknown>)
if (!d || Object.keys(d).length === 0) {
return ctx.fail('monitor server 失败: 端点不可用')
}
if (opts.json) {
printJson(d)
return ctx.success({})
}
log.info('服务器状态')
console.log(` CPU : ${d.cpu || '-'} 核`)
console.log(` 内存 : 总 ${d.totalMemory || '-'} / 已用 ${d.usedMemory || '-'} / 空闲 ${d.freeMemory || '-'}`)
console.log(` 磁盘 : 总 ${d.totalDisk || '-'} / 已用 ${d.usedDisk || '-'} / 空闲 ${d.freeDisk || '-'}`)
console.log(` 系统 : ${d.os || '-'}`)
console.log(` JVM : 堆 ${d.jvmHeap || '-'} / 非堆 ${d.jvmNonHeap || '-'}`)
console.log(` 运行时间 : ${d.uptime || '-'}`)
console.log(` JDK版本 : ${d.jdkVersion || '-'}`)
ctx.success({})
} catch (e) {
ctx.fail(`monitor server 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
purpose: '服务器状态 (CPU/内存/磁盘/JVM, AI 性能诊断最高优先级). v0.11+ webapi.',
+62 -84
View File
@@ -28,7 +28,7 @@ import {
getOrganizeList,
} from '../../webapi/permission.ts'
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): 跨命令 auto-fix (S-X1/S-X2 silent + G-X1 suggest)
import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): stdout 三模式 + CommandLog 落盘
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ stdout 三模式 + CommandLog; v2.2+ wrapCommand 收口 5c
interface CreateOpts {
fullName: string
@@ -50,8 +50,7 @@ export function buildOrgCreateCommand(): Command {
.requiredOption('--category <c>', '组织类型: 0=公司 1=部门 2=小组')
.option('--enabledMark <m>', '0/1 启用', '1')
.option('--sortCode <s>', '排序', '0')
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: CreateOpts) => {
// v2.1+ L1: stdout 三模式 — 默认 quiet, --verbose 全部输出, --json 原始 JSON
setupOutputFilter(opts)
@@ -59,97 +58,76 @@ export function buildOrgCreateCommand(): Command {
const startTime = Date.now()
// v2.1+ L2 silent+assertive+suggest: 跨命令 auto-fix pipeline (S-X1/S-X2/G-X1)
// - enCode 含 `-`/`_` 自动 strip (BS-新38 silent)
// - fullName 含 space/parens 自动 soften (BS-新52 silent)
// - 已有 org 重名 → suggest 加 `<appCode>` 前缀 (启用需 fetchExistingLists)
const fixCtx = await fetchExistingLists(c, c.appCode)
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, fixCtx)
if (cmdFix.silent.length > 0) {
Object.assign(opts, cmdFix.opts)
}
// v0.11e+ Phase D1: step machine 校验 (PS036 层级 + PS013 parentId)
const validation = validateOrgCreate({
fullName: opts.fullName,
enCode: opts.enCode,
parentId: opts.parentId,
category: opts.category,
enabledMark: opts.enabledMark,
sortCode: opts.sortCode,
})
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 })}`)
}
}
// v2.1+ L3: 失败也落 CommandLog (PS013/PS036 错误供 AI 查 dacli log last)
printCommandEnd({
command: 'org create',
appCode: c.appCode,
result: 'failure',
summary: { enCode: opts.enCode, fullName: opts.fullName },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
error: validation.steps.flatMap(s => s.errors).map(e => e.message).join('; '),
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
log.info(`✓ step machine 校验通过 (${validation.steps.length}/${validation.steps.length})`)
const body = {
fullName: opts.fullName,
enCode: opts.enCode,
parentId: opts.parentId,
category: opts.category,
enabledMark: parseInt(opts.enabledMark || '1', 10),
sortCode: parseInt(opts.sortCode || '0', 10),
}
// v3.0+ P0: 走 webapi/permission.createOrg (web 端 create 函数)
await initPermissionWebapi(c)
const r = (await createOrg(body as any)) as { id?: string; code?: number; msg?: string }
if (r.code !== 200 && r.code !== undefined) {
const enhanced = enhanceFromBackend(r.msg || '', 'org', { entity: 'org' })
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
// v2.1+ L3: API 失败也落 CommandLog
printCommandEnd({
command: 'org create',
appCode: c.appCode,
result: 'failure',
summary: { enCode: opts.enCode, fullName: opts.fullName, parentId: opts.parentId },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
error: r.msg || `code=${r.code}`,
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
let id = r.id
if (!id) {
const listR = (await getOrganizeList({ parentId: opts.parentId, pageSize: 50 })) as
| { list?: { id: string; enCode: string; fullName: string }[] }
| { id: string; enCode: string; fullName: string }[]
const list = Array.isArray(listR) ? listR : listR.list || []
const found = list.find(
(d) => d.enCode === opts.enCode || d.fullName === opts.fullName,
)
id = found?.id
}
log.ok(`✓ 组织创建成功 id=${id}`)
if (opts.json) printJson({ ...(r as object), id })
// v2.1+ L3: 落 CommandLog + 打印摘要 + "详情: dacli log last" 提示
printCommandEnd({
await wrapCommand({
command: 'org create',
appCode: c.appCode,
summary: { id, enCode: opts.enCode, fullName: opts.fullName, parentId: opts.parentId, category: opts.category },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
startTime,
verbose: opts.verbose,
json: opts.json,
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
}, async (ctx) => {
try {
// v0.11e+ Phase D1: step machine 校验 (PS036 层级 + PS013 parentId)
const validation = validateOrgCreate({
fullName: opts.fullName,
enCode: opts.enCode,
parentId: opts.parentId,
category: opts.category,
enabledMark: opts.enabledMark,
sortCode: opts.sortCode,
})
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(
validation.steps.flatMap(s => s.errors).map(e => e.message).join('; '),
{ enCode: opts.enCode, fullName: opts.fullName },
)
}
log.info(`✓ step machine 校验通过 (${validation.steps.length}/${validation.steps.length})`)
const body = {
fullName: opts.fullName,
enCode: opts.enCode,
parentId: opts.parentId,
category: opts.category,
enabledMark: parseInt(opts.enabledMark || '1', 10),
sortCode: parseInt(opts.sortCode || '0', 10),
}
// v3.0+ P0: 走 webapi/permission.createOrg (web 端 create 函数)
await initPermissionWebapi(c)
const r = (await createOrg(body as any)) as { id?: string; code?: number; msg?: string }
if (r.code !== 200 && r.code !== undefined) {
const enhanced = enhanceFromBackend(r.msg || '', 'org', { entity: 'org' })
log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`)
return ctx.fail(r.msg || `code=${r.code}`, { enCode: opts.enCode, fullName: opts.fullName, parentId: opts.parentId })
}
let id = r.id
if (!id) {
const listR = (await getOrganizeList({ parentId: opts.parentId, pageSize: 50 })) as
| { list?: { id: string; enCode: string; fullName: string }[] }
| { id: string; enCode: string; fullName: string }[]
const list = Array.isArray(listR) ? listR : listR.list || []
const found = list.find(
(d) => d.enCode === opts.enCode || d.fullName === opts.fullName,
)
id = found?.id
}
log.ok(`✓ 组织创建成功 id=${id}`)
if (opts.json) printJson({ ...(r as object), id })
ctx.success({ id, enCode: opts.enCode, fullName: opts.fullName, parentId: opts.parentId, category: opts.category })
} catch (e) {
ctx.fail(`org create 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
+31 -12
View File
@@ -7,6 +7,7 @@ import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log } from '../../core/log.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface OrgItem {
id?: string
@@ -21,6 +22,8 @@ interface OrgItem {
interface TreeOpts {
parentId?: string
maxDepth?: string
json?: boolean
verbose?: boolean
}
async function loadChildren(c: JnpfClient, parentId: string): Promise<OrgItem[]> {
@@ -46,21 +49,37 @@ export function buildOrgTreeCommand(): Command {
.description('组织树形结构 (单层展示, 递归用 --recursive)')
.option('--parentId <id>', '从指定父节点展开 (默认 "0" 根)', '0')
.option('--maxDepth <n>', '最大递归深度', '3')
addOutputOptions(cmd)
.action(async (opts: TreeOpts) => {
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
const r = await c.get<{ list: OrgItem[] }>('/permission/Organize/Selector', {
parentId: opts.parentId,
currentPage: 1,
pageSize: 200,
await wrapCommand({
command: 'org tree',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const r = await c.get<{ list: OrgItem[] }>('/permission/Organize/Selector', {
parentId: opts.parentId,
currentPage: 1,
pageSize: 200,
})
if (r.code !== 200) {
return ctx.fail(`org tree 失败: ${r.msg}`, { parentId: opts.parentId, code: r.code })
}
const list = r.data?.list || []
log.info(`根 parentId=${opts.parentId}, 共 ${list.length} 个节点`)
console.log('组织树 (单层, maxDepth=' + opts.maxDepth + '):')
printTree(list, 0, opts.parentId || '0')
ctx.success({ parentId: opts.parentId, total: list.length })
} catch (e) {
ctx.fail(`org tree 失败: ${(e as Error).message?.slice(0, 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')
})
installHelpHook(cmd, {
purpose: '组织树形结构 (单层展示)',
+66 -50
View File
@@ -13,6 +13,7 @@ import { JnpfClient } from '../../core/client.ts'
import { installHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { initWebapi as initReportWebapi, loadReport } from '../../webapi/report.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface DeleteOpts {
id: string
@@ -20,6 +21,8 @@ interface DeleteOpts {
// v0.15+ (P2-3): 级联清理 + 确认选项
cascade?: boolean
yes?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
export function buildReportDeleteCommand(): Command {
@@ -30,64 +33,77 @@ export function buildReportDeleteCommand(): Command {
.option('--cascade', '级联清理: 删报表 + 删挂的菜单 (f_module_type=report)', false)
// v0.15+ (P2-3): --yes 跳过 TTY 确认 (跟 form/delete 一致, 防误删)
.option('--yes', '跳过 TTY 确认 (强制删除)', false)
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: DeleteOpts) => {
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
await initReportWebapi(c)
// v0.15+ (P2-3): TTY 确认 (跟 form/delete 一致)
if (!opts.yes && process.stdin.isTTY) {
log.warn(`即将删除报表 id=${opts.id}${opts.cascade ? ' (含级联菜单清理)' : ''}, 此操作不可恢复`)
log.warn(' 提示: 加 --yes 跳过确认 (AI/脚本场景)')
process.exit(1)
}
// 镜像 web 端 delReport(id) → reportHttp.delete({url: `/api/Report/${id}`})
// webapi Proxy 自动调用 web 端函数
const r = (await loadReport.delReport(opts.id)) as unknown
let code: number | undefined
let msg: string | undefined
if (r && typeof r === 'object') {
const obj = r as { code?: number; msg?: string }
code = obj.code
msg = obj.msg
}
if (code !== undefined && code !== 200) {
log.error(`report delete 失败 (code=${code}): ${msg}`)
process.exit(1)
}
// v0.15+ (P2-3): --cascade 级联清理菜单
if (opts.cascade) {
await wrapCommand({
command: 'report delete',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const menuWebapi = await import('../../webapi/menu.ts')
await menuWebapi.initWebapi(c)
const { loadMenu } = menuWebapi
// 找挂这个报表的菜单 (f_module_type='report' + f_module_id=opts.id)
const menuList = (await loadMenu.getMenuList()) as { data?: unknown } | unknown
const list = (menuList as { data?: { list?: unknown[] } })?.data?.list
|| (Array.isArray(menuList) ? menuList as unknown[] : [])
const related = (list as Array<{ id?: string; moduleId?: string; type?: number }>).filter(
(m) => m.moduleId === opts.id || (m.type === 3 && m.moduleId === opts.id), // type=3 是 web 端 report module
)
for (const m of related) {
if (m.id) {
try {
await loadMenu.delMenu(String(m.id))
log.dim(` 级联清理菜单 id=${m.id}`)
} catch (e) {
log.warn(` 级联清理菜单 id=${m.id} 失败: ${(e as Error).message?.slice(0, 100)}`)
await initReportWebapi(c)
// v0.15+ (P2-3): TTY 确认 (跟 form/delete 一致)
if (!opts.yes && process.stdin.isTTY) {
log.warn(' 提示: 加 --yes 跳过确认 (AI/脚本场景)')
return ctx.fail(`即将删除报表 id=${opts.id}${opts.cascade ? ' (含级联菜单清理)' : ''}, 此操作不可恢复 (加 --yes 确认)`, { id: opts.id })
}
// 镜像 web 端 delReport(id) → reportHttp.delete({url: `/api/Report/${id}`})
const r = (await loadReport.delReport(opts.id)) as unknown
let code: number | undefined
let msg: string | undefined
if (r && typeof r === 'object') {
const obj = r as { code?: number; msg?: string }
code = obj.code
msg = obj.msg
}
if (code !== undefined && code !== 200) {
return ctx.fail(`report delete 失败 (code=${code}): ${msg}`, { id: opts.id, code })
}
// v0.15+ (P2-3): --cascade 级联清理菜单
if (opts.cascade) {
try {
const menuWebapi = await import('../../webapi/menu.ts')
await menuWebapi.initWebapi(c)
const { loadMenu } = menuWebapi
// 找挂这个报表的菜单 (f_module_type='report' + f_module_id=opts.id)
const menuList = (await loadMenu.getMenuList()) as { data?: unknown } | unknown
const list = (menuList as { data?: { list?: unknown[] } })?.data?.list
|| (Array.isArray(menuList) ? menuList as unknown[] : [])
const related = (list as Array<{ id?: string; moduleId?: string; type?: number }>).filter(
(m) => m.moduleId === opts.id || (m.type === 3 && m.moduleId === opts.id), // type=3 是 web 端 report module
)
for (const m of related) {
if (m.id) {
try {
await loadMenu.delMenu(String(m.id))
log.dim(` 级联清理菜单 id=${m.id}`)
} catch (e) {
log.warn(` 级联清理菜单 id=${m.id} 失败: ${(e as Error).message?.slice(0, 100)}`)
}
}
}
log.ok(`✓ 报表 + ${related.length} 个关联菜单已级联清理`)
} catch (e) {
log.warn(`--cascade 菜单清理失败 (报表已删): ${(e as Error).message?.slice(0, 100)}`)
}
}
log.ok(`✓ 报表 + ${related.length} 个关联菜单已级联清理`)
} catch (e) {
log.warn(`--cascade 菜单清理失败 (报表已删): ${(e as Error).message?.slice(0, 100)}`)
}
}
log.ok(`✓ 报表已删除 id=${opts.id} (BS-新116 配套, msg="${msg || '删除成功'}")`)
if (opts.json) printJson({ id: opts.id, code, msg, raw: r, cascade: opts.cascade })
log.ok(`✓ 报表已删除 id=${opts.id} (BS-新116 配套, msg="${msg || '删除成功'}")`)
if (opts.json) printJson({ id: opts.id, code, msg, raw: r, cascade: opts.cascade })
ctx.success({ id: opts.id, cascade: opts.cascade })
} catch (e) {
ctx.fail(`report delete 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
installHelpHook(cmd, {
purpose: '删除报表 (BS-新116 配套, 镜像 web report.ts:30 delReport, jnpf-datareport-univer /api/Report/{id})',