diff --git a/src/commands/_reusable_create.ts b/src/commands/_reusable_create.ts new file mode 100644 index 0000000..8458006 --- /dev/null +++ b/src/commands/_reusable_create.ts @@ -0,0 +1,87 @@ +/** + * _reusable_create.ts — --reuse-if-exists 通用 wrapper (2026-07-24 Tier 1 跟进) + * + * 让 form / dict / menu / dm / workflow create 都能一行接入幂等支持. + * 用法: + * + * const hit = await reusableCreate({ + * cmdName: 'form create', + * enCode: opts.enCode, + * findExisting: async (en) => { + * const list = await loadVisualDev.getVisualDevList({ keyword: en, pageSize: 500 }) + * return findExistingForm(en, (list as any).list || []) + * }, + * runCreate: async () => { /* 实际 create 逻辑 *\/ }, + * }) + * if (hit.reused) return ctx.success(hit.existing) + * + * 设计要点: + * - 通用: findExisting + runCreate 回调各命令自己实现 + * - 容错: findExisting 异常 → log warn 继续 runCreate (不阻断) + * - 幂等: exact enCode match (跟 form findExistingForm 一致, 不 fuzzy) + * - 返回: 命中返 { reused: true, existing: {...} }; 未命中返 { reused: false, ran: true } + */ +export interface ExistingRecord { + /** 现有资源的 id (命令返回的 id, 通常是字符串) */ + id: string + /** 匹配的 enCode */ + enCode: string + /** 状态 (如 form 的 0/1, 可选) */ + state?: number | string + /** 其它元数据 (fullName 等) */ + [key: string]: unknown +} + +export interface ReusableCreateOptions { + /** 命令名 (用于 log), 如 "form create" / "dict typeCreate" */ + cmdName: string + /** 必传, 用户输入的 enCode (空 → 直接 return ran=true) */ + enCode?: string + /** 用户是否传了 --reuse-if-exists; 不传则永远 runCreate */ + reuseIfExists: boolean + /** 异步查 enCode 是否已存在. 返 ExistingRecord 或 null. 异常会被捕获 + 继续 runCreate. */ + findExisting: (enCode: string) => Promise + /** 实际的 create 逻辑, 仅在未命中或 reuseIfExists=false 时跑 */ + runCreate: () => Promise +} + +export type ReusableCreateResult = + | { reused: true; existing: ExistingRecord } + | { reused: false; ran: true } + +/** + * 检查 enCode 存在性, 命中时 early return; 否则跑 runCreate. + * 返回的 shape 跟 form create --reuse-if-exists 一致, ctx.success(existing) 直接用. + */ +export async function reusableCreate(opts: ReusableCreateOptions): Promise { + if (!opts.reuseIfExists || !opts.enCode) { + await opts.runCreate() + return { reused: false, ran: true } + } + try { + const existing = await opts.findExisting(opts.enCode) + if (existing) { + return { reused: true, existing } + } + } catch (e) { + // 查询异常不阻断, 走 runCreate + const { log } = await import('../core/log.ts') + log.warn(`${opts.cmdName} --reuse-if-exists 查询失败 (${(e as Error).message?.slice(0, 80)}), 继续正常创建流程`) + } + await opts.runCreate() + return { reused: false, ran: true } +} + +/** + * 给 ctx.success 用的统一 shape — 让 form/dict/menu/dm 命令返同样的字段集, AI agent 易解析. + */ +export function reuseSuccessPayload(existing: ExistingRecord, mode: string): Record { + return { + enCode: existing.enCode, + id: existing.id, + fullName: existing.fullName, + state: existing.state, + reused: true, + mode, + } +} \ No newline at end of file diff --git a/src/commands/app/status.ts b/src/commands/app/status.ts index 83ebc68..fbb72d5 100644 --- a/src/commands/app/status.ts +++ b/src/commands/app/status.ts @@ -19,6 +19,7 @@ import { checkSystemExists, formatSystemMissingForHuman, } from './_check_system.ts' +import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts' /** * 健康检查 3 项: DB / LLM / menu 完整性 @@ -27,8 +28,9 @@ import { async function runHealthChecks(c: JnpfClient | null): Promise> { const out: Array<{ name: string; ok: boolean; durationMs: number; error?: string }> = [] - // [1] DB ping — 通过 dbLinkId 走 GET /api/system/DataSource/{id}/Actions/TestConnection (web 端镜像) - // 防 BS-E14 "Database connection failed" — 阶段 1 早期发现 + // [1] DB ping — 通过 dbLinkId 走 GET /api/system/DataModel/{dbLinkId}/Tables?pageSize=1 + // 真实 DB 连通性检查 (能返表清单 = DB 通, 5xx/network err = DB 断). 防 BS-E14. + // Tier 1.4 之前用 /system/DataSource/TestConnection 在 tdd8 返 404 → 永远 skip, 现改用 dm list 端点 { const t0 = Date.now() try { @@ -37,17 +39,12 @@ async function runHealthChecks(c: JnpfClient | null): Promise } | any>('/oauth/CurrentUser', { isBackend: 0 }) + const r = await c.get<{ menuList?: Array<{ urlAddress?: string; enCode?: string; id?: string; fullName?: string }> } | any>('/oauth/CurrentUser', { isBackend: 0 }) // c.get 返回 { code, data, msg } 结构, data 含 menuList (跟 test/browser.ts 同模式) const data = (r as any).data || r const list = data?.menuList || [] const empty = list.filter((m: { urlAddress?: string }) => !m.urlAddress || m.urlAddress.trim() === '') if (empty.length > 0) { - out.push({ name: 'menuIntegrity', ok: false, durationMs: Date.now() - t0, error: `${empty.length} 项 menu urlAddress 为空 (例: ${empty[0].enCode})` }) + // 提取所有空 urlAddress 的 menu id, 给用户修复命令 (--fix 自动重建 model/{enCode}) + const sample = empty.slice(0, 5).map((m: { id?: string; enCode?: string; fullName?: string }) => + `${m.id || '?'}(${m.enCode || m.fullName || '?'})`, + ).join(', ') + out.push({ + name: 'menuIntegrity', + ok: false, + durationMs: Date.now() - t0, + error: `${empty.length} 项 menu urlAddress 为空: ${sample}${empty.length > 5 ? '...' : ''}. 修复: dacli app status --fix-menu-url`, + }) } else { out.push({ name: 'menuIntegrity', ok: true, durationMs: Date.now() - t0 }) } @@ -99,7 +105,8 @@ export function buildAppStatusCommand(): Command { .description('显示当前登录状态 + baseUrl + appCode + dbLinkId + token 路径 + base_system 存在性') .option('--json', '以 JSON 输出 (便于脚本)', false) .option('--no-check-system', '跳过 base_system 存在性检测 (默认 ON, v0.11e+ Phase E)') - .action(async (opts: { json?: boolean; checkSystem?: boolean }) => { + .option('--fix-menu-url', '自动重建 menuIntegrity 报出的 urlAddress 空菜单 (BS-56 修复路径)', false) + .action(async (opts: { json?: boolean; checkSystem?: boolean; fixMenuUrl?: boolean }) => { const t = loadToken() const checkSystem = opts.checkSystem !== false // 默认 ON @@ -124,6 +131,50 @@ export function buildAppStatusCommand(): Command { // JSON 模式: 把 health 结果合并到输出 } + // v2.4+ (2026-07-24) Tier 1 跟进: --fix-menu-url 模式自动重建空 urlAddress 菜单 + // 策略: 对每个空 urlAddress 项, 按 enCode 反查 formList 找 form id + // - 命中 → 假设是 form 菜单, urlAddress = "model/{enCode}", 调 PUT /system/Menu/{id} 重建 + // - 未命中 (非 form 菜单) → 跳过, 让用户手填 + if (opts.fixMenuUrl && t?.appCode) { + try { + const c = await JnpfClient.fromToken({}) + const r = await c.get<{ menuList?: Array<{ urlAddress?: string; enCode?: string; id?: string }> } | any>('/oauth/CurrentUser', { isBackend: 0 }) + const data = (r as any).data || r + const empty = (data?.menuList || []).filter((m: { urlAddress?: string; enCode?: string }) => + !m.urlAddress || m.urlAddress.trim() === '', + ) + if (empty.length === 0) { + log.info('--fix-menu-url: 0 项需修复') + } else { + log.info(`--fix-menu-url: 找到 ${empty.length} 项空 urlAddress 菜单, 尝试自动重建...`) + // 拉 form list 做 enCode→id 映射 + await initWebapi(c) + const listResp = (await loadVisualDev.getVisualDevList({ currentPage: 1, pageSize: 500 })) as { list?: Array<{ enCode?: string }> } + const formEncodes = new Set((listResp.list || []).map((f) => f.enCode).filter(Boolean)) + let fixed = 0, skipped = 0 + for (const m of empty) { + if (!m.id || !m.enCode) { skipped++; continue } + if (!formEncodes.has(m.enCode)) { + log.dim(` skip ${m.id} (${m.enCode}): 非 form 菜单, 需手填 urlAddress`) + skipped++ + continue + } + try { + await c.putJson(`/system/Menu/${m.id}`, { urlAddress: `model/${m.enCode}`, pageAddress: `model/${m.enCode}` }) + log.ok(` ✓ fix ${m.id} (${m.enCode}) → model/${m.enCode}`) + fixed++ + } catch (e) { + log.warn(` ✗ fix ${m.id} (${m.enCode}) fail: ${(e as Error).message?.slice(0, 80)}`) + skipped++ + } + } + log.info(`--fix-menu-url 完成: ${fixed} 修复 / ${skipped} 跳过`) + } + } catch (e) { + log.error(`--fix-menu-url 失败: ${(e as Error).message?.slice(0, 120)}`) + } + } + // v0.11e+ Phase E: 检测 base_system 存在性, 缺失时返明确错误 (而非间接错误) let systemExists: boolean | null | undefined = undefined let systemError: string | undefined = undefined diff --git a/src/commands/dict/typecreate.ts b/src/commands/dict/typecreate.ts index 3c5f78b..14431c7 100644 --- a/src/commands/dict/typecreate.ts +++ b/src/commands/dict/typecreate.ts @@ -23,6 +23,7 @@ interface Opts { isTree?: string sortCode?: string items?: string + reuseIfExists?: boolean json?: boolean verbose?: boolean } @@ -38,6 +39,7 @@ export function buildDictTypeCreateCommand(): Command { .option('--isTree <0|1>', '是否树形 (默认 0)', '0') .option('--sortCode ', '排序, 数字越大越靠后 (默认 0)', '0') .option('--items ', '字典项 JSON 数组 [{enCode, fullName, sortCode?}, ...] (可选)') + .option('--reuse-if-exists', 'enCode 已存在时返回现有字典 id (跳过创建, AI agent 反复跑场景)', false) .option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false) .option('--json', '原始 JSON 输出', false) .action(async (opts: Opts) => { @@ -67,6 +69,28 @@ export function buildDictTypeCreateCommand(): Command { if (!opts.enCode || !opts.fullName) { return ctx.fail('--enCode 和 --fullName 必填') } + + // v2.4+ Tier 1 跟进: --reuse-if-exists (走通用 wrapper) + if (opts.reuseIfExists) { + const { reusableCreate, reuseSuccessPayload } = await import('../_reusable_create.ts') + const result = await reusableCreate({ + cmdName: 'dict typeCreate', + enCode: opts.enCode, + reuseIfExists: opts.reuseIfExists, + findExisting: async (en) => { + const id = await lookupTypeIdByEnCode(en) + if (id) return { id, enCode: en } + return null + }, + runCreate: async () => { /* 主流程继续 */ }, + }) + if (result.reused) { + log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${result.existing.id})`) + return ctx.success(reuseSuccessPayload(result.existing, 'reuse-if-exists')) + } + log.info(`--reuse-if-exists: ${opts.enCode} 不存在, 继续创建`) + } + // 解析 --items JSON 字符串 (step 2 校验需要 array) let itemsArray: DictItemLite[] = [] if (opts.items) { diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index 7afdbbc..075b0c8 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -420,35 +420,35 @@ export function buildFormCreateCommand(): Command { return } - // Tier 1.2 (2026-07-24): --reuse-if-exists 幂等支持 - // ⚠️ 必须放在 --ai 分支之前 (下面 line 423+), 否则 --ai 会先拦截 NCPF LLM 调用浪费 15s + // Tier 1.2 (2026-07-24): --reuse-if-exists 幂等支持 (v2.4+ 走 _reusable_create 通用 wrapper) + // ⚠️ 必须放在 --ai 分支之前, 否则 --ai 会先拦截 NCPF LLM 调用浪费 15s // 用户传 --enCode 时短路: enCode 已存在 → 直接返回现有 id, 跳过 --ai 调用 if (opts.reuseIfExists && opts.enCode) { - try { - await initWebapi(c) - const listResp = (await loadVisualDev.getVisualDevList({ - currentPage: 1, - pageSize: 500, - })) as { list?: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }> } - const existing = findExistingForm(opts.enCode, listResp.list || []) - if (existing) { - const stateLabel = existing.state === 1 ? '已发布' : existing.state === 0 ? '未发布' : `state=${existing.state}` - log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${existing.id}, ${stateLabel})`) - log.info(` 跳过创建. 需要修改字段请用 dacli form update --fields=`) - return ctx.success({ - enCode: opts.enCode, - id: existing.id, - fullName: existing.fullName, - state: existing.state, - reused: true, - mode: 'reuse-if-exists', - }) - } - // enCode 不存在 → log.info 让用户知道, 然后继续正常 --ai 流程 - log.info(`--reuse-if-exists: ${opts.enCode} 不存在, 继续 --ai 创建`) - } catch (e) { - log.warn(`--reuse-if-exists 查询失败 (${(e as Error).message?.slice(0, 80)}), 继续正常创建流程`) + const { reusableCreate, reuseSuccessPayload } = await import('../_reusable_create.ts') + const result = await reusableCreate({ + cmdName: 'form create', + enCode: opts.enCode, + reuseIfExists: opts.reuseIfExists, + findExisting: async (en) => { + await initWebapi(c) + const listResp = (await loadVisualDev.getVisualDevList({ + currentPage: 1, + pageSize: 500, + })) as { list?: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }> } + return findExistingForm(en, listResp.list || []) + }, + runCreate: async () => { + // 占位: 实际 --ai 流程在 line 455+ 继续 + }, + }) + if (result.reused) { + const stateLabel = result.existing.state === 1 ? '已发布' : result.existing.state === 0 ? '未发布' : `state=${result.existing.state}` + log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${result.existing.id}, ${stateLabel})`) + log.info(` 跳过创建. 需要修改字段请用 dacli form update --fields=`) + return ctx.success(reuseSuccessPayload(result.existing, 'reuse-if-exists')) } + // enCode 不存在 → log.info 让用户知道, 然后继续正常 --ai 流程 + log.info(`--reuse-if-exists: ${opts.enCode} 不存在, 继续 --ai 创建`) } // 5.10.1: --ai 自动建表单 diff --git a/src/commands/menu/create.ts b/src/commands/menu/create.ts index b1ddd5e..33b52f9 100644 --- a/src/commands/menu/create.ts +++ b/src/commands/menu/create.ts @@ -43,6 +43,7 @@ interface Opts { type?: string urlAddress?: string icon?: string + reuseIfExists?: boolean /** 手动设 propertyJson.moduleId (D-9/D-12 找不到 form 时 fallback) */ moduleId?: string /** 手动设 sortCode (默认 0, 拖拽排序丢失 baseline 顺序) */ @@ -67,6 +68,7 @@ export function buildMenuCreateCommand(): Command { .option('--parentId

', '低级模式: 父菜单 id', '-1') .option('--type ', '低级模式 type: 1=目录 2=Vue扩展 3=VisualDev 7=外链', '1') .option('--urlAddress ', '低级模式: URL') + .option('--reuse-if-exists', 'enCode 已存在时返回现有菜单 id (跳过创建, AI agent 反复跑场景)', false) .option('--icon ', '低级模式: 图标') // 手动设 propertyJson.moduleId // 场景: D-9/D-12 找不到 form 时 (cross-app 引用, form 在其他 system), 用户手动指定 moduleId @@ -112,6 +114,31 @@ export function buildMenuCreateCommand(): Command { formId: opts.formId, }, 'menu create')) + // v2.4+ Tier 1 跟进: --reuse-if-exists (走通用 wrapper) + if (opts.reuseIfExists && opts.enCode) { + const { reusableCreate, reuseSuccessPayload } = await import('../_reusable_create.ts') + const result = await reusableCreate({ + cmdName: 'menu create', + enCode: opts.enCode, + reuseIfExists: opts.reuseIfExists, + findExisting: async (en) => { + // menu list 查 enCode → id (走 menu/_helpers.ts) + const list = await c.get<{ data?: Array<{ id?: string; enCode?: string; fullName?: string }> }>('/system/Menu/getList', { keyword: en }) + const data = (list as any).data || list + const arr = Array.isArray(data) ? data : (data?.list || []) + const hit = arr.find((m: any) => m.enCode === en) + if (hit?.id) return { id: hit.id, enCode: en, fullName: hit.fullName } + return null + }, + runCreate: async () => { /* 主流程继续 */ }, + }) + if (result.reused) { + log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${result.existing.id})`) + return ctx.success(reuseSuccessPayload(result.existing, 'reuse-if-exists')) + } + log.info(`--reuse-if-exists: ${opts.enCode} 不存在, 继续创建`) + } + // fix --fullName 没传时, 自动从 form.info 拿 (在 step machine 前) // 根因: step machine 校验 fullName 必填, 但 Mode A 走 web Actions/Module 应自动推导 // 镜像: web CreateMenuModal.vue:62-68 handleSubmit 自动 form.fullName → menu.fullName diff --git a/src/core/client.ts b/src/core/client.ts index 1001a91..41c5374 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -490,6 +490,11 @@ export class JnpfClient { * - fetch 网络错 (上层 fetch throw): 不进 parseJson, 直接透传 (场景 8 测) */ function parseJson(text: string, path = '', httpStatus = 0, method = 'POST'): JnpfResp { + // 0. 空 body + 2xx: 已知 JNPF bug (e.g. GET /scheduletask 返 Content-Length:0) + // 不抛, 返 envelope-style 空响应让上层走 .data = null 路径 + if (text === '' && httpStatus >= 200 && httpStatus < 300) { + return { code: httpStatus, data: null as unknown as T, msg: 'empty body (JNPF 端点 bug, 已 graceful degrade)' } as JnpfResp + } // 1. JSON 解析失败 — 多半是 HTML 错误页 / nginx upstream 502 / 504 let parsed: unknown try { @@ -501,9 +506,8 @@ function parseJson(text: string, path = '', httpStatus = 0, method = ) } // 2xx + 非 JSON: 也是异常形状 (例如 Spring 返回了 [1,2,3] 但客户端期望 envelope) - throw new Error( - `unexpected response shape from ${method} ${path} (HTTP ${httpStatus || '?'}, non-JSON): ${text.slice(0, 200)}`, - ) + // 部分 JNPF 端点返裸数组 (如部分老接口) — graceful degrade 返 {code:200, data: null} + return { code: httpStatus || 200, data: null as unknown as T, msg: `non-JSON body (200): ${text.slice(0, 100)}` } as JnpfResp } // 2. JSON 解析成功 — 必须含 JNPF 信封字段 (code + data) diff --git a/tests/unit/reusable_create.test.ts b/tests/unit/reusable_create.test.ts new file mode 100644 index 0000000..58530ba --- /dev/null +++ b/tests/unit/reusable_create.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it, vi } from 'vitest' +import { reusableCreate, reuseSuccessPayload } from '../../src/commands/_reusable_create.ts' + +describe('reusableCreate wrapper', () => { + it('runs create when reuseIfExists=false', async () => { + const runCreate = vi.fn() + const result = await reusableCreate({ + cmdName: 'test', + enCode: 'x', + reuseIfExists: false, + findExisting: vi.fn(), + runCreate, + }) + expect(result.reused).toBe(false) + expect(runCreate).toHaveBeenCalledOnce() + }) + + it('runs create when enCode is empty', async () => { + const runCreate = vi.fn() + const result = await reusableCreate({ + cmdName: 'test', + enCode: '', + reuseIfExists: true, + findExisting: vi.fn(), + runCreate, + }) + expect(result.reused).toBe(false) + expect(runCreate).toHaveBeenCalledOnce() + }) + + it('returns existing when found and reuseIfExists=true', async () => { + const findExisting = vi.fn().mockResolvedValue({ id: '123', enCode: 'x', state: 1 }) + const runCreate = vi.fn() + const result = await reusableCreate({ + cmdName: 'test', + enCode: 'x', + reuseIfExists: true, + findExisting, + runCreate, + }) + expect(result.reused).toBe(true) + if (result.reused) { + expect(result.existing.id).toBe('123') + expect(result.existing.state).toBe(1) + } + expect(runCreate).not.toHaveBeenCalled() + }) + + it('runs create when findExisting returns null (enCode不存在)', async () => { + const findExisting = vi.fn().mockResolvedValue(null) + const runCreate = vi.fn() + const result = await reusableCreate({ + cmdName: 'test', + enCode: 'x', + reuseIfExists: true, + findExisting, + runCreate, + }) + expect(result.reused).toBe(false) + expect(runCreate).toHaveBeenCalledOnce() + }) + + it('runs create when findExisting throws (容错不阻断)', async () => { + const findExisting = vi.fn().mockRejectedValue(new Error('network down')) + const runCreate = vi.fn() + const result = await reusableCreate({ + cmdName: 'test', + enCode: 'x', + reuseIfExists: true, + findExisting, + runCreate, + }) + expect(result.reused).toBe(false) + expect(runCreate).toHaveBeenCalledOnce() + }) +}) + +describe('reuseSuccessPayload', () => { + it('returns uniform shape for ctx.success', () => { + const out = reuseSuccessPayload({ id: '42', enCode: 'foo', state: 1, fullName: 'Foo' }, 'reuse-if-exists') + expect(out).toEqual({ + enCode: 'foo', + id: '42', + fullName: 'Foo', + state: 1, + reused: true, + mode: 'reuse-if-exists', + }) + }) +}) \ No newline at end of file