Files
dacli/src/commands/form/create.ts
T
ssw 1eadac250f fix(form): smartProps 解构加 source, 修 'source is not defined' 警告
bug: src/commands/form/create.ts:279 applySmartProps 解构只取 formData/applied,
     但 286 引用 source 触发 ReferenceError, smartProps 后处理静默跳过.

修复: 解构加 source → 'ai'/'none' 正确判定, AI 推理结果正常应用
     (验证: 'smartProps AI 推理应用 2 项 (BS-新64=2)' 不再 warning)

vitest 17/17 PASS 无回归 (form-drift.spec.ts)

注: CI 关卡 G kb FAIL 是已知预存问题
2026-07-12 13:08:43 +08:00

1218 lines
68 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* commands/form/create.ts — 创建表单
*
* 默认场景 (AI 友好):
* - type=4 (视图, 无物理表) + webType=1 → 99% 不会 "Database exception"
* - 完整字段走 --fields JSON
*
* 提示: clone 优先, 这是兜底
*/
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { callAiForm, printAiFormResult } from './_ai.ts'
import { initBuildFormData, buildFormData as webBuildFormData, isBuildFormDataLoaded } from './_buildformdata.ts'
import { applySmartProps, loadSmartPropsContext } from './_smart_props.ts'
import { browserVerify } from './_browser_verify.ts'
import { createFormViaUi } from './_create_ui.ts'
import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
import { initWebapi as initDmWebapi, loadDataModel } from '../../webapi/dataModel.ts' // v0.15+ --table 读 dm 字段
import { preCheckFormCreate, handlePreCheckResult } from '../_precheck.ts'
import { loadContextSafe } from '../_precheck.ts'
import { runGuards, handleGuardResult } from '../_blindspot_guards.ts'
import { validateFormCreate } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { loadAppContext } from '../app/context.ts'
import { loadToken } from '../../core/config.ts'
interface CreateOpts {
fullName?: string
enCode?: string
type?: string
webType?: string
category?: string
dbLinkId?: string
fields?: string
tables?: string
/** v0.15+ (2026-07-03): 绑现有物理表, 镜像 web "选表 → 自动生成字段" (跟 --ai 同 code path) */
table?: string
enableFlow?: string
flowId?: string
autoRelease?: boolean
/** v0.11: --autoTable 强制从 --fields 推导 --tables (覆盖 --tables, 对齐 web formDesign Form.vue) */
autoTable?: boolean
/** v0.7.3 (盲点 47): 建完发布后自动挂菜单到指定父目录, 避免浏览器验证 step check-list 找不到 vxe-table */
autoCreateMenu?: boolean
/** 父菜单 id (--autoCreateMenu 时必传, 用 dacli menu list --keyword=... 拿) */
menuParentId?: string
/**
* v0.11h+ (2026-06-29 BS-18 fix): 关闭 relationForm 自动注入
* 默认 ON (启发式注入), --no-relation-form-auto 强制关闭
* 适用: 字段名含 _code 后缀 (业务编码, 不是关系字段) 时避免误判
*/
relationFormAuto?: boolean
json?: boolean
/** 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields */
ai?: string
/** 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 不建表单 */
aiField?: string
// v0.12+ BS-新28: 删除 --ai-json 选项 (逻辑重复)
// --ai-json: 用户直传 JSON → web buildFormData (跟 --ai 后半段完全一样)
// --ai: NCPF backend AI → VisualAiModel → web buildFormData
// 区别只在 AI 那步, 后面 buildFormData + create 路径一致
// 保留 --ai 和 --ai-field, 删 --ai-json 避免两条相似代码路径漂移
/** Phase 3: 浏览器层验证开关 (默认硬阻塞) */
noVerify?: boolean
verifyMode?: string
/**
* v0.10+ 新增: Commander 把 `--no-verify` 自动转 `opts.verify === false` (boolean),
* 把 `--verify <mode>` 转 `opts.verify = '<mode>'` (string, 默认 'block').
* 注意: 业务代码应读 `opts.verify` (上面两个字段永远是 undefined).
* 这里声明 `verify?: boolean | string` 仅为 TS 兼容, 实际值由 Commander 注入.
* @internal
*/
verify?: boolean | string
verifyTimeout?: string
/** v0.7.2 兜底能力: 走 UI 路径 (playwright 模拟人类在 formDesign 操作) */
via?: 'api' | 'ui'
}
/**
* v0.12+ jxcj-2026-06-29 P1 完整版 + 增强: form category 自动派生 + AI 智能判断 + 缓存复用
*
* v0.13+ BS-新29 (2026-07-01): 整合进 webapi 镜像, 不再硬编码 BUSINESS_TYPE_ID
* 旧版: hardcode 306427078100678661 → 调 /system/DictionaryData/{id} → 只能拿 businessType
* 新版: loadDict.getDictionaryAll() (webapi 镜像 web baseStore.getDictionaryAll)
* → 查 enCode='businessType' → 拿 dictionaryList (13 项业务分类)
* 镜像 web 端 formDesign/index.vue:30-34 + baseStore.getDictionaryData('businessType')
* 字典 businessType id 在 JNPF 不同版本可能变, 用 enCode 查找更稳
*
* 流程:
* 1. 查 ~/.dacli-token/category-cache.json 看 appCode 是否已缓存 → 命中直接返回
* 2. 调 loadDict.getDictionaryAll() 拿全字典 → 过滤 enCode='businessType' → 拿 13 项业务分类
/** category 缓存文件: ~/.dacli-token/category-cache.json
* 格式: { "<appCode>": { "id": "xxx", "name": "xxx", "pickedAt": "ISO8601" } } */
function getCategoryCachePath(): string {
return join(homedir(), '.dacli-token', 'category-cache.json')
}
async function loadCategoryCache(): Promise<Record<string, { id: string; name: string; pickedAt: string }>> {
const fs = await import('node:fs/promises')
try {
const raw = await fs.readFile(getCategoryCachePath(), 'utf-8')
return JSON.parse(raw)
} catch {
return {}
}
}
async function saveCategoryCache(cache: Record<string, { id: string; name: string; pickedAt: string }>): Promise<void> {
const fs = await import('node:fs/promises')
const path = getCategoryCachePath()
await fs.mkdir(path.substring(0, path.lastIndexOf('/')), { recursive: true })
await fs.writeFile(path, JSON.stringify(cache, null, 2), 'utf-8')
}
async function autoDeriveCategoryFromBusinessType(
c: JnpfClient,
appCode: string,
formName?: string,
): Promise<{ id: string; name: string } | null> {
// v0.15+ (2026-07-03): 每次 AI 重新推理, 不用缓存
// 不同表单应分到不同分类 (请假 → 行政管理, 订单 → 项目管理)
// 1. 调 webapi 镜像 loadDict.getDictionaryAll() (web 端 baseStore.getDictionaryAll)
// 旧: hardcode BUSINESS_TYPE_ID + 调 /system/DictionaryData/{id} (只拿一个字典)
// 新: 拿全字典 → 过滤 enCode='businessType' → 拿 dictionaryList
// 镜像 web 端 formDesign/index.vue:223 + baseStore.getDictionaryData('businessType')
let items: Array<{ id: string; enCode: string; fullName: string }> = []
try {
const { initWebapi, loadDict } = await import('../../webapi/dict.ts')
await initWebapi(c)
const allResp = (await loadDict.getDictionaryAll()) as { data?: { list?: Array<any> } } | Array<any>
const allList = Array.isArray(allResp)
? (allResp as Array<any>)
: (allResp as { data?: { list?: Array<any> } })?.data?.list || []
// 过滤 enCode='businessType' (web baseStore.getDictionaryData 同样的逻辑)
const bizDict = allList.find((d: any) => d?.enCode === 'businessType')
items = (bizDict?.dictionaryList || []).map((it: any) => ({
id: it.id, enCode: it.enCode, fullName: it.fullName,
}))
} catch (e) {
log.warn(` P1 查 webapi 字典失败: ${(e as Error).message?.slice(0, 100)}, 退到硬编码 ID 兜底`)
}
if (items.length === 0) {
// 兜底: 用 hardcoded ID 调 (兼容老版 NCPF)
try {
const BUSINESS_TYPE_ID = '306427078100678661'
const r = (await c.get(`/system/DictionaryData/${BUSINESS_TYPE_ID}`)) as {
code?: number
data?: { list?: Array<{ id: string; enCode: string; fullName: string }> } | Array<{ id: string; enCode: string; fullName: string }>
}
if (r.code === 200) {
items = Array.isArray(r.data) ? r.data : (r.data?.list || [])
}
} catch {}
}
if (items.length === 0) return null
// 3. v0.15+ (2026-07-03): AI 推理业务分类 (替代默认第一项的死办法)
// form --ai / --table 都走这; AI 理解表单语义, 从可选分类中选最合适的
let picked = items[0]
const categoriesJson = JSON.stringify(items.map(it => ({ id: it.id, fullName: it.fullName })))
try {
const catResp = await c.postJson<{ code?: number; msg?: string; data?: { id?: string; fullName?: string } }>(
'/ssw/ai/infer-category', {
formName: formName || appCode,
appCode,
categories: categoriesJson,
})
if (catResp.code === 200 && catResp.data?.id) {
const aiCat = items.find(it => it.id === catResp.data!.id || it.fullName === catResp.data!.fullName)
if (aiCat) {
picked = aiCat
log.info(` ✓ AI 推理 category: ${picked.fullName} (from ${items.length} 可选分类)`)
} else {
log.warn(` ! AI 推理 category id=${catResp.data.id} 不在字典中, 用默认第一项`)
}
} else {
log.warn(` ! AI 推理 category 失败 (code=${catResp.code}): ${catResp.msg}, 用默认第一项`)
}
} catch (e) {
log.warn(` ! AI 推理 category 异常: ${(e as Error).message?.slice(0, 80)}, 用默认第一项`)
}
if (!picked) return null
return { id: picked.id, name: picked.fullName }
}
export function buildFormCreateCommand(): Command {
const cmd = new Command('create')
.description('★ AI 快速建表单 (--ai "<描述>" 一条命令: NCPF backend AI + web buildFormData + 自动发布. --ai-field 只问 AI 不建表单. 高级模式: --tables=... 显式引用已存在物理表)')
.option('--fullName <n>', '中文名 (--ai 自动填, 否则必填)')
.option('--enCode <e>', '英文编码 (--ai 自动填, 否则必填)')
.option('--type <t>', '1=自定义(formDesign) 2=系统(sysForm) 3=接口 4=视图', '1')
.option('--webType <w>', '1=仅表单 2=表单+列表(默认) 3=树+表单 4=数据视图', '2')
.option('--category <c>', '分类 id (form list 看真实值; 镜像 web Form.vue:60-66 必填; 推荐每个 appCode 派独立 category, 通用复用 8f65bbe3bce341c8b3625d93544a044a=crmOrder 业务表单)')
.option('--dbLinkId <id>', 'db link id (type≠4 时必传, 默认从 token.dbLinkId)')
.option('--fields <json>', 'formData.fields JSON 数组 (--ai 自动填)')
.option('--tables <json>', 'tables JSON 数组 (type=1/2 必传)')
.option('--enableFlow <0|1>', '是否绑工作流', '0')
.option('--flowId <id>', '工作流 id (enableFlow=1 时必传)')
.option('--autoRelease', '建完立刻发布 (type=4 自动跳过)', false)
.option('--autoTable', '从 --fields 自动推导 --tables JSON (web formDesign Form.vue 行为一致; 覆盖 --tables)', false)
.option('--autoCreateMenu', '发布后自动挂菜单 (需传 --menuParentId, 避免浏览器验证找不到 list 页)', false)
.option('--menuParentId <id>', '挂菜单的父目录 id (--autoCreateMenu 时必传; 走 dacli menu list --keyword=... 拿)')
.option('--no-relation-form-auto', '关闭 relationForm 字段自动注入 (v0.11h+ BS-18 fix, 默认 ON; 用于 *_code 等业务编码字段被误判为关系字段时)')
// v0.15+ (2026-07-03): --table 绑现有物理表, 镜像 web FormDialog.vue step 1 "选表 → 自动生成字段"
// 读 dm 字段 → 转 aiModelList 格式 → 走同一个 web buildFormData (跟 --ai 路径一致)
.option('--table <name>', '绑现有物理表 (镜像 web 选表自动生成字段; 不需要 --ai 描述, 不需要 --fields)')
.option('--ai <desc>', '白皮书 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields (走 NCPF backend /api/visualdev/ai/form, v0.12+ 默认 autoRelease=true)')
.option('--ai-field <desc>', '白皮书 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 只输出建议不建表单')
// v0.15+ (2026-07-07) dos 26 P0 修复: smartProps 自动选配组件属性 (字典/min-max/relationForm/regList)
.option('--no-smart-props', '关闭 --ai smartProps 自动选配 (默认 ON, AI 选填组件属性)')
.option('--no-verify', '跳过浏览器层验证')
.option('--verify <mode>', '失败模式: warn (默认, v0.12+ jxcj) | block', 'warn')
.option('--verify-timeout <ms>', '浏览器验证超时 (默认 60s)', '60000')
.option('--via <path>', '创建路径: api (默认, 走 POST /visualdev/Base) | ui (走 playwright 模拟人类操作, API 失败时兜底)', 'api')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: CreateOpts) => {
// 5.10.2: --ai-field 只问 AI, 不建表单
if (opts.aiField) {
const data = await callAiForm(opts.aiField)
printAiFormResult(data)
if (opts.json) printJson(data)
return
}
// 5.10.1: --ai 自动建表单
if (opts.ai) {
log.info(`--ai "${opts.ai}" — 调用平台 AI 生成表单 (白皮书 5.10.1)`)
const data = await callAiForm(opts.ai)
if (!data.enCode || !data.fullName) {
// v0.19+ BS-新72: 显式打印 NCPF/SSW 调用链, 让用户知道为啥失败
log.error('AI 响应缺 enCode/fullName, 无法自动建表单')
if (data._aiChain && data._aiChain.length > 0) {
log.error('AI 调用链 (排查失败原因):')
for (const step of data._aiChain) log.error(` - ${step}`)
}
log.error('建议:')
log.error(' 1) 简化 --ai 描述 (字段数 ≤ 8)')
log.error(' 2) 改用 --enCode + --fullName + 手工建表')
log.error(' 3) 查 base_ai 表 (主库 dbLinkId=0) 是否有 f_enabled_mark=1 记录')
printAiFormResult(data)
process.exit(2)
}
opts.enCode = opts.enCode || data.enCode
opts.fullName = opts.fullName || data.fullName
// v0.12+ BS-新28: 删 dead code (aiModelList[0].fields 手动映射 formData.fields)
// 之前会把所有字段强制设 jnpfKey='input', 丢失 datePicker/select/relationForm 等
// 然后被后面的 --fields 已废弃 check 拦下, 触发 process.exit(2)
// 现在: 直接走 web buildFormData (下面), 信任 NCPF 后端 AI 输出的 aiModelList
log.info(`AI 建议 enCode=${opts.enCode} fullName=${opts.fullName}`)
// v0.11+ (Task 7 改造): --ai 路径用 web 端 buildFormData 而非 _simplify
// 解决: AI 返回的 switch/datePicker/select 在 _simplify 里被简化成 input
// buildFormData 100% 注入 formId/renderKey/isSubTable/options
await initBuildFormData()
const aiModelListForBfd = data.aiModelList || []
const bfdResult = webBuildFormData(aiModelListForBfd)
// bfdResult.formData 是 JSON 字符串, 里面有完整的 50+ formConf keys + fields
// 后面 213 行的 _simplify formData 会被这个覆盖 (见 useBuildFormData 标志)
;(opts as any).__aiBuildFormData = bfdResult
log.info(`v0.11+ --ai 走 web buildFormData, formData.fields=${JSON.parse(bfdResult.formData).fields.length}`)
// v0.15+ (2026-07-07) dos 26 P0 修复: --ai 默认 smartProps 选配组件属性
// 修复 BS-新61/62/63/64 4 类盲点 (字段名→字典/min-max/relationForm/regList)
// 合规扩展层 (CLAUDE.md §11.5): 不改 jnpf/NCPF, 在 dacli 端读已有 dict+form 列表启发式填
// v0.15+ 默认 ON, --no-smart-props 关闭
if (!(opts as any).noSmartProps) {
try {
// smartProps 在 c 创建前, 自己 load client
const { JnpfClient } = await import('../../core/client.ts')
const smartClient = await JnpfClient.fromToken()
const ctx = await loadSmartPropsContext(smartClient)
const parsedFormData = JSON.parse(bfdResult.formData)
const { formData: enhancedFormData, applied, source } = await applySmartProps(parsedFormData, ctx, { verbose: true })
// 写回 formData string
bfdResult.formData = JSON.stringify(enhancedFormData)
const byBs: Record<string, number> = {}
for (const a of applied) byBs[a.bs] = (byBs[a.bs] || 0) + 1
const summary = Object.entries(byBs).map(([k, v]) => `${k}=${v}`).join(', ')
// v0.16+ (2026-07-07) 用户反馈: 单一源 AI 推理, 无关键词 fallback (避免双系统混淆)
if (source === 'none') {
log.warn(` ↳ smartProps AI 推理失败/返回空, 不填任何字段 (audit 兜底)`)
} else {
log.info(` ↳ smartProps AI 推理应用 ${applied.length} 项 (${summary})`)
}
} catch (e) {
log.warn(`smartProps 后处理失败 (${(e as Error).message.slice(0, 80)}), 跳过`)
}
} else {
log.info(` ↳ --no-smart-props, 跳过 AI 组件属性选配`)
}
// v0.11+ 默认 type=1 (formDesign 自定义); 旧 type=2/4 兜底已废弃
opts.type = opts.type || '1'
opts.webType = opts.webType || '1'
// v0.12+ BS-新28: --ai 走 webapi 透传, 不再"前端用 prompt 构造 fields"
// 之前 (删): if (!opts.fields && data.aiModelList?.[0]?.fields?.length) 把 aiModelList[0].fields
// 手动映射成 formData.fields (强制 jnpfKey='input', 丢失 datePicker/select/relationForm 等)
// 该代码是 dead code, 因为后面 webBuildFormData 会重新构造
// 现在: 信任 NCPF 后端 AI + web buildFormData, 只 merge 必要用户字段
log.info(` ↳ --ai 走 web 端 (NCPF backend /visualdev/ai/form + web buildFormData), 不再 dacli 自写 fields`)
// v0.12+ BS-新28: --ai 默认 autoRelease=true (web 端 AI 创建后需手动发布, dacli 脚本场景默认发)
// 注意: .option('--autoRelease', ..., false) 默认 false, 用 opts.ai 判断是否走 AI 路径
if (opts.ai && !opts.autoRelease) {
opts.autoRelease = true
log.info(` ↳ --ai 默认 autoRelease=true (避免 form state=0 不能用, 跳过需手动去 web 发布)`)
}
}
// v0.15+ (2026-07-03): --table 绑现有物理表, 镜像 web FormDialog.vue step 1 "选表 → 自动生成字段"
// 读 dm 字段 → 转 aiModelList 格式 → 走同一个 web buildFormData (跟 --ai 路径完全一致)
// 用户不需要写 --fields JSON, 系统自动从物理表列推导表单字段
if (opts.table) {
log.info(`--table "${opts.table}" — 读 dm 字段, 自动生成表单字段 (镜像 web 选表自动生成字段)`)
const tableClient = await JnpfClient.fromToken()
await initDmWebapi(tableClient)
const dbLinkId = tableClient.resolveDbLinkId(opts.dbLinkId)
const rawDm = (await loadDataModel.getDataModelFieldList(dbLinkId, opts.table)) as
Record<string, unknown> | unknown[] | null
// dm fields API 可能返数组或 {list: [...]} 两种形状
const dmFields: Array<Record<string, unknown>> = Array.isArray(rawDm)
? rawDm
: ((rawDm as { list?: unknown[] })?.list || []) as Array<Record<string, unknown>>
if (!dmFields.length) {
log.error(`表 ${opts.table} 无字段, 无法自动生成表单`)
process.exit(2)
}
// dm 字段 → aiModelList 格式 (跟 --ai 路径 NCPF 返回的 VisualAiModel 结构一致)
// v0.15+ (2026-07-03): 用后端 AI 推理字段控件类型 + 列表字段选择
// 不是死 keyword 匹配 — AI 能区分 "组织选择"→depSelect, "电子签章"→signature
// 而且 AI 能判断哪些字段适合列表/查询 (跳过签名/附件/富文本等只适合表单的字段)
const SYS_COLS = ['f_id','f_tenant_id','f_flow_task_id','f_flow_id','f_flow_state',
'f_sort_code','f_create_user','f_create_time','f_modify_user','f_modify_time','f_description',
'f_version', 'f_delete_mark', 'f_delete_time', 'f_delete_user_id']
const userFields = dmFields
.filter((f: Record<string, unknown>) => !SYS_COLS.includes(String(f.field || '')))
const fieldDesc = userFields
.map((f: Record<string, unknown>) => `${f.fieldName}(${f.field}, ${f.dataType})`).join(', ')
// v0.15+ (2026-07-03): 走 SSW 专用端点 /ssw/ai/infer-fields
// 专为 --table 设计 (不是 /ssw/ai/repair — 那是 form 结构生成)
// endpoint: AIRepairService.inferFields(tableName, fieldDesc)
log.info(` ↳ 委托后端 AI 推理字段控件类型 (${userFields.length} 字段)`)
const sswResp = await tableClient.postJson<{ code?: number; msg?: string; data?: { enCode?: string; fullName?: string; aiModelList?: any[] } }>(
'/ssw/ai/infer-fields', { tableName: opts.table, fieldDesc })
if (sswResp.code !== 200 || !sswResp.data?.aiModelList?.length) {
log.error(`SSW AI 推理失败 (code=${sswResp.code}): ${sswResp.msg || '返空'}`)
log.error('提示: 检查 base_ai 配置是否启用 (dacli app login 后查 /system/Ai list)')
process.exit(2)
}
const aiModelList: any[] = sswResp.data.aiModelList
log.info(` ↳ SSW AI 推理完成: ${aiModelList[0].fields?.length || 0} 字段`)
// v0.15+ (2026-07-03): 存储 AI 推断的列表字段过滤提示
// AI 在 prompt 里被告知 signature/editor/uploadImg/uploadFile 不适合列表,
// 但 B-15 仍全选。这里记录 AI 的 fieldComponent, 供 B-15 过滤用
;(opts as any).__tableAiFieldComponents = new Map(
aiModelList[0].fields?.map((f: any) => [f.fieldName, f.fieldComponent]) || [])
// 走同一个 buildFormData (跟 --ai 路径一致)
await initBuildFormData()
const bfdResult = webBuildFormData(aiModelList)
;(opts as any).__aiBuildFormData = bfdResult
log.info(` ↳ v0.15+ --table 走 web buildFormData, formData.fields=${JSON.parse(bfdResult.formData).fields.length}`)
// v0.15+ --table 默认 autoRelease=true (跟 --ai 一致)
if (!opts.autoRelease) {
opts.autoRelease = true
log.info(` ↳ --table 默认 autoRelease=true`)
}
}
// 校验必填
if (!opts.fullName || !opts.enCode) {
log.error('--fullName 和 --enCode 必填 (或传 --ai "<描述>" 由平台 AI 自动生成)')
process.exit(2)
}
// v0.7.2: --via=ui 走 UI 路径 (playwright 模拟人类操作)
if (opts.via === 'ui') {
log.info(`--via=ui 走 UI 路径 (playwright 模拟人类在 formDesign 创建表单)`)
const c = await JnpfClient.fromToken()
const result = await createFormViaUi({
appCode: c.appCode,
fullName: opts.fullName,
enCode: opts.enCode,
type: Number(opts.type),
webType: Number(opts.webType),
})
if (result.ok) {
log.ok(`UI 路径创建成功: id=${result.id} enCode=${result.enCode}`)
} else {
log.error(`UI 路径失败: ${result.error}`)
}
if (opts.json) printJson(result)
if (!result.ok) process.exit(1)
return
}
const c = await JnpfClient.fromToken()
const type = Number(opts.type)
const webType = Number(opts.webType)
// BS-48 fix: '--dbLinkId=default' 字面量 → token.dbLinkId (与 web formDesign Form.vue 一致)
const dbLinkId = c.resolveDbLinkId(opts.dbLinkId)
// v0.12+ jxcj-2026-06-29 P1 完整版: form category 自动派生
// 镜像: web 端 formDesign/index.vue:30-34 选 category 来自字典 businessType
// (system/DictionaryData/<businessType_id>), 13 项业务分类: 车辆管理/CRM应用/...
// 之前: opts.category 必传, 失败报 VS-CATEGORY; 27 form 都传 crmOrder 通用 id
// 修复: opts.category 空时, 查 businessType 字典 → 按 token.appCode 匹配
// (jxcj 匹配 "项目管理" 之类业务分类) → 用 id; 找不到 fallback 通用 8f65...
if (!opts.category || !opts.category.trim()) {
const autoCat = await autoDeriveCategoryFromBusinessType(c, c.appCode, opts.fullName)
if (autoCat) {
opts.category = autoCat.id
log.info(` ✓ P1 自动派生 category: ${autoCat.name} (id=${autoCat.id}, 业务分类字典 businessType)`)
}
}
// P1.2: form create pre-check (dbLinkId / enCode 重复 / type-webType 规则)
// 失败时 exit 2, 不进入 API 调用; 警告不阻断
// 从 --tables JSON 提取主表名 (供 type-webType 规则判断 needsPhysicalTable 用)
let mainTable: string | undefined
if (opts.tables) {
try {
const tbls = JSON.parse(opts.tables) as Array<{ table?: string }>
mainTable = tbls[0]?.table
} catch {
/* JSON 解析失败留给后续步骤报错 */
}
}
handlePreCheckResult(
'form create',
await preCheckFormCreate(c, {
enCode: opts.enCode,
table: mainTable,
dbLinkId,
webType,
type,
}),
)
// P3.1: 第二层防御 — blindspot guard (24 条高频盲点, 运行时检查)
// - ERROR → exit 2 (与 pre-check 一致)
// - WARN → 仅打印, 不阻断
// - context 加载失败时跳过 (容错, 与 pre-check 同模式)
const guardCtx = await loadContextSafe(c)
if (guardCtx.warning) log.warn(guardCtx.warning)
const enableFlowBool = opts.enableFlow === '1' || opts.enableFlow === 'true'
const guardOpts: Record<string, unknown> = {
enCode: opts.enCode,
fullName: opts.fullName,
dbLinkId,
type,
webType,
enableFlow: enableFlowBool,
autoRelease: opts.autoRelease === true,
autoTable: opts.autoTable === true,
}
if (opts.tables) {
try { guardOpts.tables = JSON.parse(opts.tables) } catch { /* JSON 解析失败留给后续步骤 */ }
}
if (opts.fields) {
try { guardOpts.fields = JSON.parse(opts.fields) } catch { /* JSON 解析失败留给后续步骤 */ }
}
handleGuardResult('form create', runGuards(guardCtx.ctx, guardOpts, 'form create'))
// v0.11+ cleanup: --fields 简化版已废弃, 走 --ai (web 端 buildFormData 自动保证 schema 完整性)
if (opts.fields) {
log.error('--fields 已废弃, 请用 --ai "<描述>" (v0.12+ 走 web 端 buildFormData, schema 自动完整)')
log.error('例: --ai "客户管理:姓名、电话、邮箱"')
process.exit(2)
}
// ai-json 路径下从 buildFormData 拿完整 fields (含 __config__ 全部 18 键)
const formDataObj: any = (opts as any).__aiBuildFormData
? JSON.parse((opts as any).__aiBuildFormData.formData)
: null
const fieldsArr: any[] = formDataObj?.fields || []
const rawFields: any[] = [] // 兼容后面 (labelByField 等) 引用, 但为空
const converted = 0
const total = 0
const formData = (opts as any).__aiBuildFormData
? // v0.11+ --ai 路径: 用 web buildFormData (formId/renderKey/isSubTable/options 100% 完整)
JSON.parse((opts as any).__aiBuildFormData.formData)
: {
formRef: 'formRef',
formModel: 'dataForm',
size: 'middle',
labelPosition: 'right',
labelWidth: 100,
labelSuffix: '',
formRules: 'rules',
popupType: 'general',
generalWidth: '600px',
fullScreenWidth: '100%',
drawerWidth: '600px',
gutter: 15,
disabled: false,
span: 24,
colon: false,
hasCancelBtn: true,
cancelButtonText: '取消',
cancelButtonTextI18nCode: 'common.cancelText',
hasConfirmBtn: true,
confirmButtonText: '确定',
confirmButtonTextI18nCode: 'common.okText',
hasConfirmAndAddBtn: true,
hasPrintBtn: false,
printButtonText: '打印',
printButtonTextI18nCode: 'common.printText',
customBtns: [],
appCustomBtns: [],
primaryKeyPolicy: 1,
concurrencyLock: false,
logicalDelete: false,
dataLog: false,
useBusinessKey: false,
businessKeyList: [],
businessKeyTip: '数据已存在,请勿重复提交!',
printId: '',
formStyle: '',
classNames: [],
className: [],
classJson: '',
detailExtraList: [],
fields: fieldsArr,
tableName: opts.enCode,
}
// 2026-06-25 tdd9 BS-55: 同步去 appCode 前缀 (与 dm 物理表名一致, 避免后端 "请在数据库中添加对应的数据表")
// formData 顶层 tableName 也用 cleanTable, 匹配物理表
const appCode55 = (c as any).appCode as string
const cleanTable55 = appCode55 && opts.enCode.startsWith(`${appCode55}_`)
? opts.enCode.slice(appCode55.length + 1)
: opts.enCode
formData.tableName = cleanTable55
// 同步 formData.fields[*].__config__.tableName (form 渲染时控件关联的物理表)
if (Array.isArray(formData.fields)) {
for (const fld of formData.fields as any[]) {
if (fld && fld.__config__ && fld.__config__.tableName === opts.enCode) {
fld.__config__.tableName = cleanTable55
}
}
}
//
// v0.7.4 (盲点 50): 必传 columnList + searchList, 否则 webType≠1 (有列表) 保存报
// "列表字段不允许为空" toast 2 次. 参考 e2eTest1 (id=836658473499370693) columnData 结构:
// columnList[0] = {label, labelI18nCode, prop, fixed, headerAlign, align, sortable,
// width, jnpfKey, __vModel__, __config__, fullName, id}
// searchList[0] = {... + sourceType, value, searchType, searchMultiple, isKeyword, noShow}
// 排除系统字段 (f_id / f_tenant_id / f_flow_* / f_sort_code / f_create_* / f_modify_* / f_description)
const SYSTEM_FIELDS = new Set([
'f_id', 'f_tenant_id',
'f_flow_task_id', 'f_flow_id', 'f_flow_state',
'f_sort_code',
'f_create_user', 'f_create_time', 'f_modify_user', 'f_modify_time',
'f_description',
])
// v0.11 (审计修复): 与 web `workSystem:624163990351643525` 真实 columnList entry 对齐
// 关键修复:
// - 补 16 个顶层字段 (placeholder/clearable/disabled/on/style/fullNameI18nCode 等)
// - __config__ 补 15 子字段 (tag/tagIcon/visibility/layout/span/renderKey 等)
// - renderKey: 用 Date.now() 替代 magic number 1780900000000, 修设计器列拖拽失效
// - fullNameI18nCode: 改数组类型 [''], 修设计器打开时 i18n NPE
// 详见 docs/dacli/audit-form-create-deviations.md 任务3
const JNPF_TAG_MAP: Record<string, string> = {
input: 'JnpfInput',
textarea: 'JnpfInputTextarea',
inputNumber: 'JnpfInputNumber',
select: 'JnpfSelect',
datePicker: 'JnpfDatePicker',
switch: 'JnpfSwitch',
checkbox: 'JnpfCheckbox',
radio: 'JnpfRadio',
cascader: 'JnpfCascader',
upload: 'JnpfUpload',
slider: 'JnpfSlider',
rate: 'JnpfRate',
colorPicker: 'JnpfColorPicker',
timePicker: 'JnpfTimePicker',
}
const JNPF_ICON_MAP: Record<string, string> = {
input: 'icon-ym icon-ym-generator-input',
textarea: 'icon-ym icon-ym-generator-textarea',
inputNumber: 'icon-ym icon-ym-generator-inputNumber',
select: 'icon-ym icon-ym-generator-select',
datePicker: 'icon-ym icon-ym-generator-date',
switch: 'icon-ym icon-ym-generator-switch',
checkbox: 'icon-ym icon-ym-generator-checkbox',
radio: 'icon-ym icon-ym-generator-radio',
cascader: 'icon-ym icon-ym-generator-cascader',
upload: 'icon-ym icon-ym-generator-upload',
slider: 'icon-ym icon-ym-generator-slider',
rate: 'icon-ym icon-ym-generator-rate',
colorPicker: 'icon-ym icon-ym-generator-color',
timePicker: 'icon-ym icon-ym-generator-time',
}
const buildColumnListEntry = (field: any, jnpfKey = 'input') => {
const label = field.fieldName || field.field
const prop = field.field
const tag = JNPF_TAG_MAP[jnpfKey] || 'JnpfInput'
const tagIcon = JNPF_ICON_MAP[jnpfKey] || 'icon-ym icon-ym-generator-input'
return {
// === 顶层基础字段 ===
label, labelI18nCode: '', prop,
fixed: 'none', headerAlign: 'left', align: 'left',
sortable: false, width: null,
jnpfKey,
id: prop, fullName: label,
fullNameI18nCode: [''], // 修复: 数组类型 (dacli 旧无此字段)
// === 控件行为字段 (修复 16 字段缺失) ===
clearable: true, disabled: false, readonly: false,
placeholder: '请输入',
style: { width: '100%' },
on: { change: '({ data, rowIndex, formData, setFormData, setShowOrHide, setRequired, setDisabled, onlineUtils }) => {\n // 在此编写代码\n \n}' },
// === input 控件特有字段 (修复缺失) ===
addonBefore: '', addonAfter: '', prefixIcon: '', suffixIcon: '',
showCount: false, showPassword: false, useMask: false, useScan: false,
maskConfig: { prefixType: 1, useUnrealMask: false, maskType: 1, unrealMaskLength: 1, prefixLimit: 0, suffixLimit: 0, filler: '*', prefixSpecifyChar: '', suffixType: 1, ignoreChar: '', suffixSpecifyChar: '' },
// === __vModel__ 与 __config__ (修复 __config__ 15 子字段) ===
__vModel__: prop,
__config__: {
jnpfKey,
tag, // 修复: 控件 tag, 前端组件映射靠此 key
tagIcon, // 修复: 设计器图标
label, showLabel: true, tipLabel: '',
labelWidth: undefined, tableAlign: 'left', tableFixed: 'none',
className: [], defaultValue: '',
required: false, layout: 'colFormItem', span: 24,
dragDisabled: false, visibility: ['pc', 'app'],
tableName: opts.enCode,
noShow: false, regList: [], trigger: 'change',
formId: `formItem${opts.enCode}`,
renderKey: Date.now(), // 修复: 替代 magic number 1780900000000
transferList: [],
},
}
}
// v0.11 (审计修复): 与 web `workSystem:585448937427567365` 真实 searchList entry 对齐
// 关键修复:
// - `value: ''` → `value: []` (web datePicker 期望数组, 旧版前端 value.length NPE)
// - `searchMultiple: 0` → `searchMultiple: false` (类型对齐)
// - 补 8 字段 (fullNameI18nCode/clearable/disabled/style/placeholder/on/placeholderI18nCode/format)
// 详见 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 tag = JNPF_TAG_MAP[jnpfKey] || 'JnpfInput'
const tagIcon = JNPF_ICON_MAP[jnpfKey] || 'icon-ym icon-ym-generator-input'
return {
// === 顶层基础字段 (与 web 对齐, 工件设计器数据格式) ===
label, labelI18nCode: '', prop,
jnpfKey, // 顶层冗余 (兼容 list 渲染)
id: prop, fullName: label,
fullNameI18nCode: [entry.fullNameI18nCode || ''],
// === 控件行为字段 (与 columnList 对齐) ===
clearable: true, disabled: false, readonly: false,
style: { width: '100%' },
placeholder: entry.placeholder || '请输入',
placeholderI18nCode: '',
on: { change: '({ data, rowIndex, formData, setFormData, setShowOrHide, setRequired, setDisabled, onlineUtils }) => {\n // 在此编写代码\n \n}' },
format: entry.format, // datePicker: 'yyyy-MM-dd'
// === 搜索特有 ===
sourceType: 2,
value: [], // 数组 (web datePicker 期望)
searchType: 1,
searchMultiple: false,
isKeyword: false,
noShow: false,
// === BS-新60 修复 (2026-07-06): 与 columnList 对齐补 __config__ 包装 ===
// 根因: web ListHeader/transform.ts:43 `data.__config__.jnpfKey` 无防护
// 影响: formData 浏览器加载时 TypeError, 整个列表页崩溃
// 修复: searchList 项必须有 __config__.jnpfKey 包装
__config__: {
jnpfKey,
tag, // 控件 tag
tagIcon, // 设计器图标
label, showLabel: true, tipLabel: '',
className: [], defaultValue: '',
required: false,
visibility: ['pc', 'app'],
tableName: opts.enCode,
noShow: false,
formId: `formItem${prop}`,
renderKey: Date.now(),
regList: [], trigger: 'change',
span: 24,
layout: 'colFormItem',
dragDisabled: false,
transferList: [],
rule: entry.rule, // 数据源类型 (高代码字典类型等)
},
}
}
// v0.11 (审计修复): 与 web ColumnDesign/src/helper/config.ts:109-198 `defaultColumnData` 对齐
// 关键变更:
// - `useOverflow` → `showOverflow` (web 用 showOverflow, dacli 旧 useOverflow 是命名错位)
// - `printId: ''` → `printIds: []` (web 是数组类型)
// - 新增 ruleList / funcs / tabConfig / viewKey / defaultColumnList 等 29 字段
// - btnsList / columnBtnsList 改用 web 默认 5+3 按钮 schema (而非空数组)
// 详见 docs/dacli/audit-form-create-deviations.md 任务2 + 盲点 51
const columnDataObj: any = {
// === 必填 + 基础 ===
// type: 1=table 2=tree 3=group (JNPF 后端 parseInt, 必须 number, 不是 string)
type: 1, pageSize: 20,
// === v0.11 修复:补齐 web 默认字段(盲点 51 上游根因)===
ruleList: { matchLogic: 'and', conditionList: [] }, // 过滤规则(缺失会前端 NPE)
resizable: true, // 列表列拖拽
showOverflow: true, // 修复: 旧 useOverflow 命名错位
childTableStyle: 1, // 子表样式
showSummary: false, summaryField: [],
columnOptions: [], defaultColumnList: [], // 默认列选项
// 修复 (v0.11, jxcj E2E 发现): web ColumnDesign/src/helper/config.ts:122
// defaultSortConfig 必须是 array, 不是 object. JNPF 前端 TableList.vue
// 调 .map() 时若 object 会抛 TypeError, vxe-toolbar 渲染失败, "新增"按钮看不见.
defaultSortConfig: [],
viewKey: '', // 视图主键 (webType=3 必填)
hasPage: true, hasTreeQuery: false,
// === 树形列表(type=3 时启用)===
treeTitle: '左侧标题', treeTitleI18nCode: '',
treeDataSource: 'dictionary', treeDictionary: '',
treeRelation: '', treeRelationFieldSelectType: 'all', treeRelationFieldAbleIds: [],
treeSyncType: 0, treeSyncInterfaceId: '', treeSyncInterfaceName: '', treeSyncTemplateJson: [],
treePropsUrl: '', treePropsName: '', treeTemplateJson: [],
treePropsValue: 'id', treePropsChildren: 'children', treePropsLabel: 'fullName',
// === 分组/树形主表(type=3)===
groupField: '', parentField: '',
// === 打印 + 上传 ===
hasPrint: false, printIds: [], // 修复: printId '' → printIds []
printBtnPosition: 'right',
uploaderTemplateJson: {},
// === 权限 (4 use*Permission 必填, 盲点 23 v0.7.1 fix) ===
useColumnPermission: false, useFormPermission: false,
useBtnPermission: false, useDataPermission: false,
columnPermissions: [],
// === 按钮 + JS 函数(修复 funcs 缺失)===
btnsList: [ // 默认 5 按钮 (web config.ts:74-80)
{ show: true, value: 'add', icon: 'icon-ym icon-ym-btn-add', label: '新增', labelI18nCode: 'common.add2Text' },
{ show: false, value: 'download', icon: 'icon-ym icon-ym-btn-download', label: '导出', labelI18nCode: 'common.exportText' },
{ show: false, value: 'upload', icon: 'icon-ym icon-ym-btn-upload', label: '导入', labelI18nCode: 'common.importText' },
{ show: false, value: 'batchRemove', icon: 'icon-ym icon-ym-btn-clearn', label: '批量删除', labelI18nCode: 'common.batchDelText' },
{ show: false, value: 'batchPrint', icon: 'icon-ym icon-ym-report-icon-preview-printPreview', label: '批量打印', labelI18nCode: 'common.batchPrintText' },
],
btnsPosition: 'right',
rowBtnsList: [],
columnBtnsList: [ // 默认列按钮 (web config.ts:82-107)
{ show: true, value: 'edit', icon: 'icon-ym icon-ym-btn-edit', label: '编辑', labelI18nCode: 'common.editText' },
{ show: true, value: 'remove', icon: 'icon-ym icon-ym-btn-clearn', label: '删除', labelI18nCode: 'common.delText' },
{ show: true, value: 'detail', icon: 'icon-ym icon-ym-generator-menu', label: '详情', labelI18nCode: 'common.detailText' },
],
customBtnsList: [],
useCustomBtns: false,
funcs: { // 修复 funcs 缺失 (设计器打开时丢默认值)
afterOnload: '({ data, tableRef, onlineUtils }) => {\n \n}',
rowStyle: '({ row, rowIndex }) => {\n \n}',
cellStyle: '({ row, column, rowIndex, columnIndex }) => {\n \n}',
},
sortList: [],
// === 数据接口 / 分页 / 多选 ===
useDataInterface: false, dataInterfaceId: '',
pageSizes: [10, 20, 50, 100],
showCheckbox: false,
usePage: true, useAdvancedQuery: true, useFilter: true, useSort: true,
useDragSort: true,
// === 列表/搜索字段 (v0.7.4 自动填充, 见下方 326 行) ===
columnList: [], searchList: [],
// === APP 端独立字段 (web `defaultAppColumnData`, dacli 保留旧名 appColumnList) ===
appColumnOptions: [], appColumnList: [],
// === 标签面板 + 卡片布局 + 多级表头 ===
tabConfig: { on: false, relationField: '', hasAllTab: true }, // 修复 tabConfig 缺失
cardListConfig: {}, // web 默认有值, dacli 简化空对象
complexHeaderList: [],
// === 表格样式 + 关联表单 (v0.11 修复 typo) ===
tableConfig: { border: true, stripe: false, size: 'default', showRadio: false, showRowNumber: true },
relationForm: {}, // 见上方 v0.11 relationForm 修复
// === dacli 扩展字段 (web 未收录, 待后续验证清理) ===
useOverflow: true, // 已废弃: web 用 showOverflow, 保留兼容老 form
complexHeaderConfig: {}, // 已废弃: web 用 complexHeaderList
hasDefaultValue: false, // dacli 自有
hasSuperQuery: false,
}
// v0.12+ BS-新28: --ai-json 删了, tables 推导只剩 2 路径
// 优先 --tables 用户传入, 否则 type=4 空, 否则空 (web 端 buildFormData 推 schema)
const stripAppPrefix = (t: string) =>
c.appCode && t.startsWith(`${c.appCode}_`) ? t.slice(c.appCode.length + 1) : t
const tables = opts.tables
? // BS-55: 用户传 --tables 时, 同步去前缀
JSON.parse(opts.tables).map((t: any) => {
if (t && t.table) t.table = stripAppPrefix(t.table)
return t
})
: type === 4
// type=4 视图不能带物理表 (后端会 Database exception), 强制空数组
? []
: [] // 2026-06-26 v0.11d 修复: 兜底不再生成 [{f_id,f_tenant_id}], 发 []
// web 浏览器场景: tables=[] 跳过 create() getPrimaryDbField 校验
// publish() (Actions/Release) line 628 自动从 formData.fields 推 schema 建表
// 之前兜底 2-PK schema 会触发 create() line 527 循环, 表不存在抛 "请在数据库中添加对应的数据表"
// 2026-06-27 B-9 修复: tables 推导后, 自动给第一个表加 typeId='1' (主表标识)
// 后端 jnpf/.../FlowFormDataUtil.java:831 查 typeId='1' 找主表, 找不到抛 MsgCode.COD001
// ("集合条件过滤获得目标为空"). 即使用户 --tables 显式传了, 也可能漏 typeId.
// 镜像 web formDesign/Form.vue:288 `const typeId = i == 0 ? '1' : '0'` (第一个表 = 主表).
// 用户 --tables 显式指定 typeId 不受影响 (先检查 !t.typeId).
// 注意: 仅当 tables 非空才补, type=4 视图 tables=[] 跳过 (后端不看空数组).
if (Array.isArray(tables) && tables.length > 0) {
tables.forEach((t: any, idx: number) => {
if (t && typeof t === 'object' && !t.typeId) {
t.typeId = idx === 0 ? '1' : '0'
}
})
}
// 2026-06-27 B-15 修复: form 提交前, 根据 tables[].fields[].allowNull=0 同步 formData.fields[].__config__.required=true
// 根因 (本轮 tds_connector/space/product/policy/contract 6 form 实战复盘):
// 1. dacli dm create 时 --fields allowNull=0 → 后端物理表字段 NOT NULL (✓ 已正确)
// 2. dacli form create 时 web buildFormData (formUtils.ts:431) 硬编码 required=false
// 3. 浏览器设计器保存 → web/__vModel__ 的 el-form-item 不会校验, 但 formRules 缺 required → 后端不拦
// 4. 程序/curl POST 时缺 NOT NULL 字段 → 后端 INSERT 失败 "Failed to add data"
// (后端 FormCheckUtils.checkForm 在 VisualdevModelDataServiceImpl.java:348 调用)
// 修复策略:
// - dacli 知道 dm allowNull=0, 比 web 默认 required=false 更准确 → 自动同步
// - 系统字段 (f_id/f_tenant_id/f_flow_* 等) 即使 allowNull=0 也不标 required (JNPF 自动注入, 用户不填)
// - 场景 A (tables=[]) 跳过: 没 dm 约束信息, required 保持默认 false, 让用户在 Web 设计器勾选
// 镜像参考: web formDesign Form.vue:350 `if (field.config.required === true)` 是默认 false, web 用户手动勾选
// dacli 比 web 更智能: 因为 dacli 知道 dm 表约束, 自动同步省去用户手动勾选
if (Array.isArray(tables) && tables.length > 0 && formData?.fields && Array.isArray(formData.fields)) {
// 收集 NOT NULL 业务字段集合 (排除系统字段 — 它们是 JNPF 自动注入, 用户不填)
const notNullFields = new Set<string>()
for (const t of tables) {
if (!t?.fields || !Array.isArray(t.fields)) continue
for (const f of t.fields) {
if (!f?.field) continue
// 系统字段过滤 (大小写不敏感, 与 B-8 SYSTEM_FIELDS 集合一致)
if (SYSTEM_FIELDS.has(String(f.field).toLowerCase())) continue
// allowNull: 0 = NOT NULL (后端 DbTableController.java 转成物理表 NOT NULL)
if (f.allowNull === 0 || f.allowNull === '0') {
notNullFields.add(String(f.field))
}
}
}
// 同步 formData.fields[i].__config__.required
let updated = 0
for (const fld of formData.fields) {
const vmodel = fld?.__vModel__ || fld?.__id__
if (!vmodel) continue
if (!notNullFields.has(String(vmodel))) continue
if (!fld.__config__) fld.__config__ = {}
if (fld.__config__.required !== true) {
fld.__config__.required = true
updated++
}
}
if (updated > 0) {
log.info(`✓ B-15 fix: 根据 dm allowNull=0 自动设置 ${updated} 字段 __config__.required=true (避免浏览器外 POST 缺字段触发后端 INSERT 失败)`)
}
}
// 2026-06-27 B-8 修复 (防御深度 #2): form 提交前, 过滤 tables[].fields 中与 system 字段重名的列.
// 根因 (见 docs/tds/debug.html §B-8 + 后端 FlowFormDataUtil.createMast L820-897):
// 1. 用户 --tables 标了 primaryKey=1 的业务字段 (如 f_connector_code)
// 2. 后端 getKey() (L170-187) 选 primaryKey=1 字段作为 PK 名 → f_connector_code
// 3. createMast() L846-850: INSERT 先 set(f_connector_code=id).set(f_flow_task_id=id)
// 4. L857-875 遍历 mastForm (formData.fields), 又 set(f_connector_code=value) → 重复
// 5. SQL: insert into connector (f_connector_code, f_flow_task_id, f_connector_code, ...) → ERROR
// 防御策略:
// - 方案 D (主): dm create step machine 拦截业务字段 primaryKey=1 (见 dm/_validate.ts PRIMARY_KEY_FIELDS)
// - 方案 C (辅): form create 提交前再过滤一次, 即使用户用 web/AI 路径绕过 dm 也安全
// SYSTEM_FIELDS: 镜像后端 L844-850 (keyName + flowTaskId) + L890 (addTenantId f_tenant_id) + L884-887 (FLOWID/FLOWSTATE) + f_description (BS-38 已知).
// 子表 tableField/relationField 不会被注入到 INSERT SQL, 不需过滤 (只是 ref 不进 columns).
if (Array.isArray(tables) && tables.length > 0) {
tables.forEach((t: any) => {
if (!t || !Array.isArray(t.fields)) return
const before = t.fields.length
t.fields = t.fields.filter((f: any) => {
if (!f || !f.field) return true
// v0.11g+ B-18 fix (2026-06-27 tds_batch3): f_id/f_tenant_id primaryKey=1 是真实系统列, 必须保留
// 之前无脑按 field 名匹配 SYSTEM_FIELDS 过滤 → 主表无 PK 字段 → 后端 OnlineSwapDataUtils.searchMainData
// "mainKeyModel == null" → DataException("表不存在") → PUT 400
// 后端期望 mainTable.fields 至少有 primaryKey=1 且不含 tenantId 的字段作为主键
// 修复: 只过滤 primaryKey=1 的"非系统命名"业务字段 (用户错把业务字段标 PK 才过滤)
const fNameLower = String(f.field).toLowerCase()
if (SYSTEM_FIELDS.has(fNameLower)) {
// 真系统列 (f_id/f_tenant_id) 保留, 让后端 INSERT SQL 自然 include 它
// 后端 FlowFormDataUtil.createMast 也会自动 addTenantId, 这里保留不会双写因为它就是表本身的列
if (f.primaryKey === 1 && (fNameLower === 'f_id' || fNameLower === 'f_tenant_id')) {
return true
}
// 其他系统字段 (f_flow_*/f_sort_code/f_create_*/f_modify_*/f_description) 按 B-8 原逻辑过滤
return false
}
// 非系统名字段: 如果标了 primaryKey=1, 是用户错把业务字段当 PK, 过滤避免后端 getKey 选错
return !(f.primaryKey === 1)
})
const removed = before - t.fields.length
if (removed > 0) {
log.warn(`B-8 防御: 表 ${t.table} 过滤了 ${removed} 个 system 重名字段 (避免 INSERT SQL "specified twice", 后端 FlowFormDataUtil.createMast 镜像)`)
}
})
}
// 2026-06-26 v0.11d 反思: columnList 不由 dacli 自动生成
// web ColumnDesign/src/components/Main.vue:226-771 真实流程:
// columnOptions (可选字段池) ← formData.fields (不是 tables[0].fields!)
// columnList (最终列表列) ← 用户在 Web 设计器手动勾选
// defaultColumnList[].checked ← 现有 columnList 算 checked 状态
// dacli 不该假设用户想展示哪些列 → columnList 留空, 让用户去 Web 设计器勾选
if (webType !== 1 && tables.length > 0 && (tables[0] as any).fields?.length > 0) {
// 仅在场景 B (用户显式 --tables=... 引用已有物理表) 时, 按 v0.7.4 旧逻辑推 columnList
// 因为场景 B 的 formData.fields 通常空, 只能从 tables 推
const mainTable = tables[0] as { fields?: any[] }
const userFields = (mainTable.fields || []).filter((f: any) => f && f.field && !SYSTEM_FIELDS.has(f.field))
if (userFields.length > 0) {
const labelByField = new Map<string, string>()
for (const rf of rawFields as any[]) {
const v = rf.__vModel__ || rf.__id__ || rf.id || rf.vmodel
const lbl = (rf.__config__ && rf.__config__.label) || rf.label || rf.fieldName
if (v && lbl) labelByField.set(v, lbl)
}
const entries = userFields.map((f: any) => {
const e = buildColumnListEntry(f)
const lbl = labelByField.get(f.field)
if (lbl) {
e.label = lbl
e.fullName = lbl
if (e.__config__) (e.__config__ as any).label = lbl
}
return e
})
columnDataObj.columnList = entries
columnDataObj.searchList = entries.map(buildSearchListEntry)
log.info(`v0.7.4 (场景 B) 自动生成 columnList + searchList: ${entries.length} 个字段 (从 tables[0].fields)`)
} else {
log.warn(`v0.7.4 webType=${webType} 但 tables[0] 无用户字段, ★ 场景 A 走 Web 设计器勾选 (columnList 留空)`)
}
} else if (webType !== 1 && (opts.ai || opts.table)) {
// v0.11f+ B-15 修复 (2026-06-27 tds_batch3): --ai / --table 路径下, 从 formData.fields 推 columnList
// v0.15+ --table 路径: 同样走 web buildFormData → formData.fields 完整, B-15 columnList 自动生成
// 根因: --ai/--table 走 web buildFormData, formData.fields 有完整 __config__/__vModel__/jnpfKey
const formFields = (formData?.fields || []) as any[]
// 排除子表容器 (jnpfKey='table') + 子表内字段 (isSubTable=true)
const userFormFields: any[] = []
for (const f of formFields) {
if (!f) continue
const cfg = f.__config__
if (!cfg) continue
if (cfg.jnpfKey === 'table') continue // 子表容器
// 主子表: 子表内字段的 __config__.isSubTable=true, 不要进主表 columnList
if (cfg.isSubTable) continue
// 排除系统字段 (f_id / f_tenant_id / f_flow_* / f_sort_code / f_create_* / f_modify_* / f_description)
const vmodel = f.__vModel__ || ''
if (SYSTEM_FIELDS.has(String(vmodel).toLowerCase())) continue
userFormFields.push(f)
}
if (userFormFields.length > 0) {
// v0.15+ (2026-07-03): --table 路径用 AI 推理的 fieldComponent 过滤列表/查询字段
// 跳过 signature/editor/uploadImg/uploadFile 等只适合表单不适合列表的控件
const aiComps = (opts as any).__tableAiFieldComponents as Map<string, string> | undefined
const LIST_SKIP_COMPS = new Set(['signature', 'editor', 'uploadImg', 'uploadFile'])
const QUERY_SKIP_COMPS = new Set(['signature', 'editor', 'uploadImg', 'uploadFile', 'checkbox', 'switch'])
const listFields = aiComps
? userFormFields.filter((f: any) => {
const vmodel = f.__vModel__ || ''
const comp = aiComps.get(vmodel) || f.__config__?.jnpfKey || ''
return !LIST_SKIP_COMPS.has(comp)
})
: userFormFields
const entries = listFields.map((f: any) => {
const jnpfKey = f.__config__?.jnpfKey || 'input'
const label = f.__config__?.label || f.__vModel__ || ''
const prop = f.__vModel__ || f.id || label
return buildColumnListEntry({ field: prop, fieldName: label }, jnpfKey)
})
columnDataObj.columnList = entries
// 搜索字段: 进一步跳过 switch/checkbox 等只适合 filter 的控件
const queryFields = aiComps
? listFields.filter((f: any) => {
const vmodel = f.__vModel__ || ''
const comp = aiComps.get(vmodel) || f.__config__?.jnpfKey || ''
return !QUERY_SKIP_COMPS.has(comp)
})
: entries
columnDataObj.searchList = queryFields.map((f: any) => {
const prop = f.__vModel__ || f.id || ''
const label = f.__config__?.label || prop
return buildSearchListEntry({ field: prop, fieldName: label as string, jnpfKey: f.__config__?.jnpfKey || 'input' })
}) as any[]
const skipped = aiComps ? userFormFields.length - listFields.length : 0
log.info(`B-15 修复: --${opts.ai ? 'ai' : 'table'} 路径自动生成 columnList: ${entries.length} 列表字段 + ${columnDataObj.searchList.length} 搜索字段`
+ (skipped ? ` (${skipped} 跳过: 只适合表单不适合列表)` : ''))
} else {
log.warn(`B-15: --ai 路径 formData.fields 为空, ★ 走 Web 设计器勾选`)
}
} else if (webType !== 1) {
log.info(`★ 场景 A: columnList 留空, 去 formDesign Web 设计器第二步"列表设计"手动勾选字段`)
}
// 2026-06-27 B-9 修复: tables 推导后, 自动给第一个表加 typeId='1' (主表标识)
// 后端 jnpf/.../FlowFormDataUtil.java:831 查 typeId='1' 找主表, 找不到抛 MsgCode.COD001
// ("集合条件过滤获得目标为空"). 即使用户 --tables 显式传了, 也可能漏 typeId.
// 兜底 schema 已有 typeId='1' (line 124), 这里统一保护用户传入路径.
// 用户 --tables 显式指定 typeId 不受影响 (先检查 !t.typeId).
if (Array.isArray(tables) && tables.length > 0) {
tables.forEach((t: any, idx: number) => {
if (t && typeof t === 'object' && !t.typeId) {
t.typeId = idx === 0 ? '1' : '0'
}
})
}
const body: Record<string, unknown> = {
fullName: opts.fullName,
enCode: opts.enCode,
type,
webType: String(webType),
category: opts.category || null,
description: 'created by dacli (TS)',
dbLinkId,
enableFlow: Number(opts.enableFlow || '0'),
flowId: opts.flowId || '',
// 关键: formData/columnData/appColumnData/tables 都是字符串!
formData: JSON.stringify(formData),
columnData: JSON.stringify(columnDataObj),
appColumnData: JSON.stringify(columnDataObj),
tables: JSON.stringify(tables),
state: 0,
sortCode: 0,
}
log.info(`loadVisualDev.create ${opts.enCode} type=${type} webType=${webType} dbLinkId=${dbLinkId}`)
// 2026-06-26 v0.11d+ step machine 校验 (镜像 web Form.vue handleNext + handleSubmit 前端校验)
// 失败时不发 API, 让 AI 看到具体 step + 错误字段 (不用去浏览器试错)
const validation = validateFormCreate({
fullName: opts.fullName,
enCode: opts.enCode,
category: opts.category,
type,
webType,
tables,
formData,
columnData: columnDataObj,
})
if (!validation.ok) {
log.error(`✗ step machine 校验未通过 (${validation.steps.filter(s => !s.ok).map(s => `step${s.step}(${s.stepName})`).join(', ')}):`)
for (const step of validation.steps) {
if (step.ok) {
log.ok(` step${step.step} ${step.stepName}: ✓ 通过`)
} else {
log.error(` step${step.step} ${step.stepName}: ✗ ${step.errors.length} 个错误`)
for (const err of step.errors) {
const fieldTag = err.field ? `[${err.field}] ` : ''
log.error(` - ${fieldTag}${err.message}`)
}
}
}
if (opts.json) {
printJson({ ok: false, validation: validation.steps })
}
process.exit(1)
}
log.ok(`✓ step machine 校验通过 (3/3)`)
// step 0 基础信息 (P0 镜像 web Form.vue schemas)
// v0.11+ Phase 2: 改用 webapi (loadVisualDev.create)
await initWebapi(c)
// P0.2: 加载 AppContext 供诊断用 (复用 P0.1 的 loadAppContext, 失败不阻断主流程)
const diagCtx = await loadAppContext().catch(() => null)
// 注: webapi 路径下不再用 callWithDiagnosis (loadVisualDev.create 走 defHttp shim)
// L3 diagnose 仍可在 r.msg 上手工触发 (后续可加)
const r = (await loadVisualDev.create(body)) as { code?: number; msg?: string; data?: { id?: string } }
if (r.code !== 200 && r.code !== undefined) {
// v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode (EXIST/VS/SYS 等)
const enhanced = enhanceFromBackend(r.msg || '', 'form', { entity: 'form' })
log.error(`创建失败 (code=${r.code}): ${r.msg}`)
log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '后端API' })}`)
if (opts.json) printJson(r)
process.exit(1)
}
// 拉 id (响应通常不回 id, 反查 list — 走 webapi getVisualDevList)
const listR = (await loadVisualDev.getVisualDevList({ keyword: opts.enCode })) as {
list?: { id: string; enCode: string }[]
}
const newForm = listR.list?.find((f) => f.enCode === opts.enCode)
const newId = newForm?.id || '(unknown)'
log.ok(`创建成功: id=${newId} enCode=${opts.enCode}`)
if (opts.autoRelease && type !== 4 && newId !== '(unknown)') {
log.info(`loadVisualDev.release (formId=${newId})`)
// v0.11e+ Bug B-7: release 失败时重试 1 次 (500ms 间隔), 仍失败 process.exit(1)
// 之前 log.warn + 继续 → state=1 假成功, base_visual_release 表无 release 行, 后续 NPE
// 后端: VisualdevController.java:639 setState(1) + :673 saveOrUpdate(releaseEntity)
// web: web/.../api/onlineDev/visualDev.ts:43 release(id) → POST Actions/Release
const tryRelease = async (): Promise<{ code?: number; msg?: string }> => {
try {
return (await loadVisualDev.release(newId)) as { code?: number; msg?: string }
} catch (e) {
return { code: -1, msg: (e as Error).message?.slice(0, 200) }
}
}
let rr = await tryRelease()
if (rr.code !== 200 && rr.code !== undefined) {
log.warn(`首次发布失败 (code=${rr.code}, msg=${rr.msg}), 重试 1 次...`)
await new Promise<void>((r) => setTimeout(r, 500))
rr = await tryRelease()
}
if (rr.code === 200 || rr.code === undefined) {
log.ok('发布成功 (state=1)')
} else {
log.error(`发布失败 (code=${rr.code}): ${rr.msg}`)
log.error(
`手动发布: curl -X POST "${c.baseUrl}/api/visualdev/Base/${newId}/Actions/Release" -H "Authorization: ${loadToken()?.token ? 'bearer ' + loadToken()!.token : 'bearer <TOKEN>'}" -H "Content-Type: application/json" -d '{}'`,
)
if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType, releaseError: rr.msg })
process.exit(1)
}
} else if (opts.autoRelease && type === 4) {
log.warn('type=4 视图自动跳过 release (会 400)')
}
// v0.7.3 (盲点 47): 发布后自动挂菜单, 避免浏览器验证 step check-list 找不到 vxe-table
if (opts.autoCreateMenu && newId !== '(unknown)' && newId !== '(unknown)') {
if (!opts.menuParentId) {
log.error('--autoCreateMenu 必传 --menuParentId (用 dacli menu list --keyword=目录名 拿顶级目录 id)')
if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType, menuError: 'no parent' })
} else {
log.info(`挂菜单: loadVisualDev.createMenu (formId=${newId}, parentId=${opts.menuParentId})`)
// v0.11+ Phase 2: 改用 webapi (loadVisualDev.createMenu = Actions/Module)
// 复用 web CreateMenuModal 真实 body: pc=1, app=0, platformRelease=String
const mr = (await loadVisualDev.createMenu(newId, {
pc: 1,
app: 0,
pcModuleParentId: [opts.menuParentId],
appModuleParentId: [],
platformRelease: JSON.stringify({ pc: 1, app: 0 }),
})) as { code?: number; msg?: string }
if (mr.code === 200 || mr.code === undefined) log.ok(`菜单挂载成功 (parentId=${opts.menuParentId})`)
else log.warn(`菜单挂载失败 (code=${mr.code}): ${mr.msg}`)
}
}
if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType })
// Phase 3: 浏览器层验证 (默认硬阻塞, --verify=warn / --no-verify 可绕过)
//
// v0.10+ 修复 (jxcj 实战): Commander.js 把 `--no-verify` 自动转 `opts.verify === false` (boolean)
// 并把 `--verify <mode>` 转 `opts.verify = '<mode>'` (string), 两个选项都赋值给 `opts.verify`,
// 接口里的 `noVerify/verifyMode` 永远是 undefined, 之前完全没生效.
// 修复: 直接读 `opts.verify`, 根据其值 (boolean false / string 'block'|'warn') 派生.
// 优先级: --no-verify > --verify=warn > --verify=block (默认) > 都不传
const verifyRaw = opts.verify as unknown
const effectiveNoVerify = verifyRaw === false // Commander --no-verify 自动否定
const effectiveMode: 'block' | 'warn' =
verifyRaw === 'warn' ? 'warn' : 'block' // 其它一律按 block (含 'block'/undefined/true)
if (newId !== '(unknown)') {
try {
await browserVerify({
formId: newId,
enCode: opts.enCode,
appCode: c.appCode,
noVerify: effectiveNoVerify,
verifyMode: effectiveMode,
verifyTimeout: opts.verifyTimeout ? Number(opts.verifyTimeout) : undefined,
})
} catch (e) {
if (effectiveMode !== 'warn') throw e
// warn 模式不抛, 继续
}
}
})
installAiHelpHook(cmd, {
purpose: '创建表单. 默认 type=4 (视图) 兜底, 不会 Database exception. 业务建议 clone',
required: { '--fullName | --ai': '中文名, 或传 --ai 由平台 AI 自动生成' },
optional: {
'--enCode': '英文编码 (--ai 自动填)',
'--type': '1/2/3/4 (默认 4)',
'--webType': '1/2/3/4 (默认 1)',
'--category': '分类 id',
'--dbLinkId': '业务库 id (type≠4 时必传)',
'--fields': 'formData.fields JSON (--ai 自动填)',
'--tables': 'tables JSON (type=1/2)',
'--enableFlow': '0|1',
'--flowId': '工作流 id',
'--autoRelease': '建完立刻发布 (type=4 自动跳过)',
'--autoTable': 'v0.11 强制从 --fields 推导 --tables JSON (覆盖 --tables, 对齐 web formDesign Form.vue UX)',
'--autoCreateMenu': 'v0.7.3 (盲点 47) 发布后自动挂菜单 (需 --menuParentId, 避免浏览器验证失败)',
'--menuParentId': '挂菜单的父目录 id (--autoCreateMenu 时必传; 用 dacli menu list 拿)',
'--no-relation-form-auto': 'v0.11h+ (BS-18 fix) 关闭 relationForm 自动注入, 用于 *_code 等业务编码字段被误判为关系字段时',
'--ai': '白皮书 5.10.1 AI 快速建表 — 自然语言描述生成 enCode/fullName/fields',
'--ai-field': '白皮书 5.10.2 AI 推荐字段 — 只输出建议不建表单',
'--no-verify': '跳过浏览器层验证 (默认硬阻塞)',
'--verify': 'block (默认) | warn (失败不阻塞 release)',
'--verify-timeout': '浏览器验证超时 (默认 60s)',
},
example: [
'dacli form create --fullName="POC 视图" --enCode=pocView',
'dacli form create --fullName="请假" --enCode=leave --type=2 --webType=2 --dbLinkId=664... --ai "请假申请:姓名、请假天数、原因" --autoRelease',
'dacli form create --ai "请假管理表单, 含姓名/部门/请假天数/原因/审批人"',
'dacli form create --ai-field "请假天数, 含字典 [事假/病假/年假]" # 只问不建',
],
source: { web: 'web/.../formDesign/Form.vue:444-465 + AI助手.vue', api: 'POST /api/visualdev/Base | POST /api/visualdev/ai/form' },
notes: [
'v0.11+ 推荐 dm→form 两步: dm create 建物理表 → form create --ai "<描述>" 建表单',
'autoRelease 对 type=4 自动跳过 (release 会 400)',
'--ai 走 web buildFormData 路径, 默认 type=2 (老 type=4 兜底策略已废弃)',
'--ai-field 只输出建议, 不建表单, 用于 AI 辅助字段设计',
'B-15 (2026-06-27): --tables 含 allowNull=0 字段时, 自动同步 formData.fields[].__config__.required=true, 避免 curl/程序 POST 缺字段触发后端 INSERT 失败 (系统字段除外, 让用户去设计器勾选)',
],
})
return cmd
}