diff --git a/src/commands/di/list.ts b/src/commands/di/list.ts index e34642c..6148bd9 100644 --- a/src/commands/di/list.ts +++ b/src/commands/di/list.ts @@ -8,9 +8,42 @@ import { Command } from 'commander' import { JnpfClient } from '../../core/client.ts' import { installHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' -import { initWebapi, loadDataInterface } from '../../webapi/di.ts' +import { initWebapi, getDataInterfaceSelector } from '../../webapi/di.ts' import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c +/** + * Flatten the selector response used by the web data-interface picker. + * + * The paged endpoint requires a category query, and the backend treats a + * missing category as `category IS NULL`, returning an empty page. Selector + * is the platform's category-independent source, so list uses its leaves. + */ +export interface DataInterfaceListItem { + id?: string + enCode?: string + fullName?: string + category?: string | number + [key: string]: unknown +} + +export function flattenDataInterfaceSelector(input: unknown): DataInterfaceListItem[] { + const result: DataInterfaceListItem[] = [] + const walk = (nodes: unknown): void => { + if (!Array.isArray(nodes)) return + for (const node of nodes as DataInterfaceListItem[]) { + if (node?.id && (node.category === '1' || node.category === 1)) { + result.push(node) + } + if (node?.children) walk(node.children) + } + } + const nodes = Array.isArray(input) + ? input + : (input as { data?: unknown } | null)?.data + walk(nodes) + return result +} + interface Opts { json?: boolean; keyword?: string; currentPage?: string; pageSize?: string; verbose?: boolean } export function buildDiListCommand(): Command { @@ -34,26 +67,31 @@ export function buildDiListCommand(): Command { }, async (ctx) => { try { await initWebapi(c) - // 镜像 web getDataInterfaceList: 传 { keyword, currentPage, pageSize, category? } - // web 端默认不传 category (后端 mapper 默认 eq(null) → 0 行, web 端从 store 拿选中分类) - // dacli 简化: 不传 category, 拉全部 (pageSize 限制) - log.info(`loadDataInterface.getDataInterfaceList`) - // defHttp shim 已解外层 envelope, 这里 r 已是 data 部分: { list, pagination } - const r = (await loadDataInterface.getDataInterfaceList({ - keyword: opts.keyword, - currentPage: Number(opts.currentPage || '1'), - pageSize: Number(opts.pageSize || '50'), - })) as { list?: { id: string; fullName: string; enCode: string; categoryId?: string }[] } - const list = r.list || [] + log.info('loadDataInterface.getDataInterfaceSelector (category-independent)') + + const selector = await getDataInterfaceSelector() + const all = flattenDataInterfaceSelector(selector) + const keyword = opts.keyword?.trim().toLowerCase() + const filtered = keyword + ? all.filter((item) => `${item.enCode || ''} ${item.fullName || ''}`.toLowerCase().includes(keyword)) + : all + const currentPage = Math.max(1, Number(opts.currentPage || '1')) + const pageSize = Math.max(1, Number(opts.pageSize || '50')) + const start = (currentPage - 1) * pageSize + const list = filtered.slice(start, start + pageSize) + const result = { + pagination: { currentPage, pageSize, total: filtered.length }, + list, + } const summary = { - total: list.length, + total: filtered.length, keyword: opts.keyword, } if (opts.json) { - printJson(r) + printJson(result) return ctx.success(summary) } - log.info(`共 ${list.length} 个数据接口`) + log.info(`共 ${filtered.length} 个数据接口`) log.printRawTable( ['ID', 'FULL_NAME', 'ENCODE'], list.map((d) => [String(d.id), d.fullName || '', d.enCode || '']), diff --git a/src/commands/form/codegen.ts b/src/commands/form/codegen.ts index fdd81b8..85574b4 100644 --- a/src/commands/form/codegen.ts +++ b/src/commands/form/codegen.ts @@ -27,6 +27,7 @@ import { wrapCommand } from '../_output_filter.ts' // v2.2+ (2026-07-21): wrapCo import { remindCodeGenMenuAttachFail, remindCodeGenPomConflict, remindCodeGenMenuMountFail } from '../_post_reminders.ts' // v2.4+ (2026-07-21): 3 codegen 兜底 → L3 import { log, printJson } from '../../core/log.ts' import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts' +import { normalizeCodegenSearchList } from './_codegen_schema.ts' interface CodegenOpts { /** 企业代码 (aibridge company_code), 默认 ssw */ @@ -589,6 +590,43 @@ async function ensureAlias( return true } +async function repairCodegenSearchList(formId: string): Promise { + const raw = await loadVisualDev.getInfo(formId) as Record + const parseJson = (value: unknown): Record => { + if (value && typeof value === 'object') return value as Record + if (typeof value === 'string') { + try { return JSON.parse(value) as Record } catch { return {} } + } + return {} + } + + const formData = parseJson(raw.formData) + const columnData = parseJson(raw.columnData) + const repaired = normalizeCodegenSearchList(columnData, formData) + if (repaired.changed === 0) return 0 + + const body: Record = { + ...raw, + id: raw.id || formId, + columnData: JSON.stringify(repaired.columnData), + } + if (raw.appColumnData !== undefined && raw.appColumnData !== null) { + const appColumnData = parseJson(raw.appColumnData) + const appRepaired = normalizeCodegenSearchList(appColumnData, formData) + body.appColumnData = JSON.stringify(appRepaired.columnData) + } + + const updated = await loadVisualDev.update(body) as { code?: number; msg?: string } + if (updated.code !== undefined && updated.code !== 200) { + throw new Error(`searchList 自动修复失败 (code=${updated.code}): ${updated.msg || ''}`) + } + const released = await loadVisualDev.release(formId) as { code?: number; msg?: string } + if (released.code !== undefined && released.code !== 200) { + throw new Error(`searchList 修复后重新发布失败 (code=${released.code}): ${released.msg || ''}`) + } + return repaired.changed +} + export function buildFormCodegenCommand(): Command { const cmd = new Command('codegen') .description('表单代码生成 (白皮书 5.5, 参考 aibridge CodeGenerator)') @@ -697,6 +735,13 @@ export function buildFormCodegenCommand(): Command { // 2. (可选) --auto-alias / --alias-file / --alias: 通过 JNPF 原生别名系统 // 推荐方式 (写 base_visual_alias, JNPF 原生) await ensureAlias(c, formId, opts, formTables) + // CodeGenerateFactoryV3 currently dereferences SearchTypeModel.id. Repair + // legacy/table-generated searchList entries before calling CodePreview; + // this is a dacli-side schema repair, not a platform-source change. + const repairedSearchItems = await repairCodegenSearchList(formId) + if (repairedSearchItems > 0) { + log.warn(`⚠ codegen 预修复 searchList: ${repairedSearchItems} 项补齐 id/prop,并重新发布 form`) + } // aibridge 派生规则: modulePackage = ${company}.${app_code} const modulePackage = opts.modulePackage || `${company}.${module}` // Maven 模块目录名 (aibridge §POM 依赖规则): ${company}-${app_code} diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index af67eca..82c8bbb 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -88,6 +88,53 @@ interface CreateOpts { via?: 'api' | 'ui' } +/** + * Re-apply smart component props after the final form-data producer. + * + * `--ai` and `--table` are independent producers: when both are supplied, + * the table branch rebuilds `__aiBuildFormData` after the AI branch has run + * smartProps. Keep the post-processing at the final boundary so dictionary, + * numeric-range, validation and relation props cannot be discarded. + */ +async function applyFinalSmartProps( + c: JnpfClient, + buildResult: { formData: string }, + ctx: { addSuggestion: (entry: any) => void }, +): Promise { + try { + const smartCtx = await loadSmartPropsContext(c) + const parsed = JSON.parse(buildResult.formData) + const { formData: enhancedFormData, applied, source } = await applySmartProps( + parsed, + smartCtx, + { verbose: true }, + ) + let finalFormData = enhancedFormData + + if (source === 'none') { + const heuristicApplied = applyHeuristicRequired(enhancedFormData) + if (heuristicApplied.applied > 0) { + log.warn(` ↳ final smartProps AI 失败 + 启发式 required 兜底: ${heuristicApplied.applied} 字段`) + ctx.addSuggestion(remindSmartPropsAIFallback(heuristicApplied.applied)) + } + const relationFormApplied = applyHeuristicRelationForm(enhancedFormData, smartCtx) + if (relationFormApplied.skipped > 0) { + log.warn(` ↳ final applyHeuristicRelationForm: ${relationFormApplied.skipped} 字段无候选`) + ctx.addSuggestion(remindHeuristicRelFormSkipped(relationFormApplied.skipped)) + } + } + + buildResult.formData = JSON.stringify(finalFormData) + if (applied.length > 0) { + log.info(` ↳ final smartProps 应用 ${applied.length} 项 (${source})`) + } + } catch (e) { + log.warn(`final smartProps 后处理跳过 (${(e as Error).message?.slice(0, 100)})`) + ctx.addSuggestion(remindSmartPropsPostProcessFailed((e as Error).message?.slice(0, 100) || 'unknown')) + } +} + + /** * app-P1 完整版 + 增强: form category 自动派生 + AI 智能判断 + 缓存复用 * 整合进 webapi 镜像, 不再硬编码 BUSINESS_TYPE_ID @@ -659,6 +706,13 @@ export function buildFormCreateCommand(): Command { tableDmFields = dmFields tablePhysicalName = opts.table } + + // --table is the final form-data producer when combined with --ai. + // Re-run smartProps here so the table rebuild cannot erase dictionary, + // range, validation or relation metadata inferred by the AI pass. + if (opts.table && (opts as any).__aiBuildFormData) { + await applyFinalSmartProps(c, (opts as any).__aiBuildFormData, ctx) + } // 校验必填 if (!opts.fullName || !opts.enCode) { log.error('--fullName 和 --enCode 必填 (或传 --ai "<描述>" 由平台 AI 自动生成)') @@ -916,8 +970,11 @@ export function buildFormCreateCommand(): Command { // 详见 docs/dacli/audit-form-create-deviations.md 任务4 const buildSearchListEntry = (entry: any) => { const jnpfKey = entry.jnpfKey || 'input' - const label = entry.fieldName || entry.field - const prop = entry.field + const label = entry.fieldName || entry.field || entry.fullName || entry.label || '' + // Accept both raw DM fields and generated column-list entries. The + // latter carry `prop`/`id`, not `field`; using only entry.field made + // every table-path search item persist with a null id. + const prop = entry.field || entry.prop || entry.id || entry.__vModel__ || '' const tag = JNPF_TAG_MAP[jnpfKey] || 'JnpfInput' const tagIcon = JNPF_ICON_MAP[jnpfKey] || 'icon-ym icon-ym-generator-input' // HIGH1 (eventhub blocker 阶段 6): --table 路径用物理表名, --ai 路径用 opts.enCode diff --git a/src/commands/form/update.ts b/src/commands/form/update.ts index 827eb96..2bec7d5 100644 --- a/src/commands/form/update.ts +++ b/src/commands/form/update.ts @@ -41,6 +41,37 @@ interface Opts { verbose?: boolean } +export function mergeFormFieldUpdates(existing: unknown[], updates: unknown[]): any[] { + const merged: any[] = [...existing] + for (const raw of updates) { + const update = (raw && typeof raw === 'object') ? raw as Record : {} + const key = update.vmodel || update.__vModel__ + if (!key) { + merged.push(raw) + continue + } + const index = merged.findIndex((entry) => { + const item = entry as Record + return (item?.vmodel || item?.__vModel__) === key + }) + if (index < 0) { + merged.push(raw) + continue + } + const current = merged[index] as Record + merged[index] = { + ...current, + ...update, + __vModel__: update.__vModel__ || current.__vModel__, + __config__: { + ...(current.__config__ || {}), + ...(update.__config__ || {}), + }, + } + } + return merged +} + export function buildFormUpdateCommand(): Command { const cmd = new Command('update') .description('表单修改 (改 schema/字段/enCode, PUT 语义, 自动 BS-49/50 防御 + 重新发布)') @@ -186,17 +217,10 @@ export function buildFormUpdateCommand(): Command { formData = fd as Record } const existingFields = Array.isArray(formData.fields) ? (formData.fields as unknown[]) : [] - // 增量合并: 按 vmodel 去重, 新增追加 - const merged: unknown[] = [...existingFields] - for (const f of parsed) { - const fObj = f as Record - const idx = merged.findIndex((e) => (e as Record).vmodel === fObj.vmodel) - if (idx >= 0) merged[idx] = fObj - else merged.push(fObj) - } + const merged = mergeFormFieldUpdates(existingFields, parsed) formData.fields = merged body.formData = JSON.stringify(formData) - log.info(`字段合并: ${existingFields.length} → ${merged.length} (新增 ${parsed.length - (merged.length - existingFields.length)})`) + log.info(`字段合并: ${existingFields.length} → ${merged.length} (按 vmodel/__vModel__ 增量合并)`) } // === step 3 PUT / 后端API === diff --git a/tests/unit/form_create_json_stdout.test.ts b/tests/unit/form_create_json_stdout.test.ts index e88f10d..373df18 100644 --- a/tests/unit/form_create_json_stdout.test.ts +++ b/tests/unit/form_create_json_stdout.test.ts @@ -100,6 +100,9 @@ vi.mock('../../src/webapi/dict.ts', () => ({ dictionaryList: [ { id: 'cat-test-id', enCode: 'testCat', fullName: '测试分类' }, ], + children: [ + { id: 'cat-test-id', enCode: 'testCat', fullName: '测试分类' }, + ], }, ], }, @@ -525,6 +528,23 @@ describe('form create --table: tables payload + formData.tableName 契约 (event } }) + it('--table 路径: columnData.searchList[*] 保留 id/prop, 供 CodePreview 使用 (REGRESSION)', async () => { + const body = await runAndCaptureBody([ + '--table', 'eventaudit', + '--fullName', '活动审核', + '--enCode', 'eventAudit', + '--no-verify', + ]) + + const columnData = JSON.parse(body.columnData as string) as { searchList?: Array } + expect(Array.isArray(columnData.searchList)).toBe(true) + expect(columnData.searchList!.length).toBeGreaterThan(0) + for (const entry of columnData.searchList!) { + expect(entry.id).toBeTruthy() + expect(entry.prop).toBe(entry.id) + } + }) + it('--table 路径: appColumnData.columnList[*].__config__.tableName === opts.table (HIGH1)', async () => { const body = await runAndCaptureBody([ '--table', 'eventaudit', @@ -563,4 +583,81 @@ describe('form create --table: tables payload + formData.tableName 契约 (event // 应有错误退出 expect(mocks.exit).toHaveBeenCalledWith(1) }) +}) + +describe('form create --ai + --table: final smartProps must survive table rebuild', () => { + it('preserves dictionaryType on the final generated select field', async () => { + mocks.getDataModelFieldList.mockResolvedValue([ + { field: 'f_topic_direction', fieldName: '赛题方向', dataType: 'varchar', dataLength: '50' }, + ]) + mocks.postJson.mockImplementation(async (path: string) => { + if (path.includes('/visualdev/ai/form')) { + return { + code: 200, + msg: 'ok', + data: { + enCode: 'eventSignup', + fullName: '活动报名', + aiModelList: [{ isMain: true, fields: [{ + fieldName: 'f_topic_direction', + fieldComponent: 'select', + __list__: true, + __form__: true, + __query__: true, + }] }], + }, + } + } + if (path.includes('/ssw/ai/infer-fields')) { + return { + code: 200, + msg: 'ok', + data: { + enCode: 'eventSignup', + fullName: '活动报名', + aiModelList: [{ isMain: true, fields: [{ + fieldName: 'f_topic_direction', + fieldComponent: 'select', + __list__: true, + __form__: true, + __query__: true, + }] }], + }, + } + } + if (path.includes('/ssw/ai/infer-component-props')) { + return { + code: 200, + msg: 'ok', + data: { + props: [{ + vModel: 'f_topic_direction', + dictionaryType: 'testCat', + reason: 'test dictionary inference', + }], + }, + } + } + return { code: 404, msg: 'not mocked', data: null } + }) + + const cmd = buildFormCreateCommand() + await cmd.parseAsync([ + 'node', 'test', + '--ai', '活动报名', + '--table', 'event_signup', + '--fullName', '活动报名', + '--enCode', 'eventSignup', + '--category', 'cat-test-id', + '--no-verify', + '--json', + ]) + + expect(mocks.create).toHaveBeenCalledTimes(1) + const body = mocks.create.mock.calls[0][0] as Record + const formData = JSON.parse(body.formData as string) as { fields: Array } + const field = formData.fields.find((item) => item.__vModel__ === 'f_topic_direction') + expect(field?.__config__?.dataType).toBe('dictionary') + expect(field?.__config__?.dictionaryType).toBe('cat-test-id') + }) }) \ No newline at end of file