Files
dacli/src/commands/form/create.ts
T

1071 lines
59 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 { callAiForm, printAiFormResult } from './_ai.ts'
import { initBuildFormData, buildFormData as webBuildFormData, isBuildFormDataLoaded } from './_buildformdata.ts'
import { browserVerify } from './_browser_verify.ts'
import { createFormViaUi } from './_create_ui.ts'
import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
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
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
json?: boolean
/** 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields */
ai?: string
/** 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 不建表单 */
aiField?: string
/**
* v0.11+ Task 10: --ai-json 直入 JSON (跳过 AI 调用)
* 接受 List<AiFormModel> 数组, 直接喂给 web 端 buildFormData
* 用于: AI/用户在会话里已生成 JSON, 不需要再调 LLM
* 例: --ai-json '[{"tableTitle":"客户表","tableName":"customer","isMain":true,"fields":[...]}]'
*/
aiJson?: string
/** 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'
}
export function buildFormCreateCommand(): Command {
const cmd = new Command('create')
.description('★ AI 快速建表单 (默认 --ai-json --autoRelease 一条命令完整: 不建物理表, dacli 自动 fallback schema, 走 formDesign Web 设计器调字段). 高级模式: --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 看真实值)')
.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('--ai <desc>', '白皮书 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields (推荐走 --ai-json 路径跳过 LLM 调用, v0.11+)')
.option('--ai-field <desc>', '白皮书 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 只输出建议不建表单')
.option('--ai-json <json>', 'v0.11+ Task 10: AI 描述直接转 JSON 直入 — 跳过 LLM 调用, AI/用户在会话里生成 List<AiFormModel> 喂给 buildFormData. 适合会话内已有 JSON 的场景')
.option('--no-verify', '跳过浏览器层验证 (默认硬阻塞)')
.option('--verify <mode>', '失败模式: block (默认) | warn', 'block')
.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
}
// v0.11+ Task 10: --ai-json 直入 JSON (跳过 AI 调用)
// 接受 List<AiFormModel> JSON, 直接喂给 buildFormData
if (opts.aiJson) {
log.info(`--ai-json — 直入 JSON (跳过 LLM 调用, v0.11+ 新路径)`)
let aiModelList: any[]
try {
aiModelList = JSON.parse(opts.aiJson)
} catch (e: any) {
log.error(`--ai-json JSON 解析失败: ${e.message}`)
log.error('期望格式: [{"tableTitle":"...", "tableName":"...", "isMain":true, "fields":[...]}])')
process.exit(2)
}
if (!Array.isArray(aiModelList) || aiModelList.length === 0) {
log.error('--ai-json 必须是 List<AiFormModel> 非空数组')
process.exit(2)
}
// 2026-06-26 v0.11d 兼容: AI prompt 规范字段名是 fieldName, 但 dacli 历史示例用 field
// web buildFormData (formUtils.ts:29) 读 child.fieldName, 缺则 __vModel__=undefined → form 字段丢 vmodel
// 这里兼容映射: field → fieldName (有 fieldName 优先用, 没有再 fallback field)
for (const m of aiModelList) {
if (Array.isArray(m?.fields)) {
for (const fld of m.fields) {
if (fld && !fld.fieldName && fld.field) {
fld.fieldName = fld.field
log.info(` 字段兼容映射: field → fieldName (${fld.field})`)
}
// v0.11f+ DEV-4 fix (2026-06-27 tds_batch2): dataType 自动映射 → fieldComponent
// 原 dacli 仅兼容 `field` → `fieldName`, 但 buildFormData 读 `child.fieldComponent`
// 缺 fieldComponent 时回退到 componentList[0] = input, datetime 字段变 input
// → 后端 swapDatetime 不触发 → "Data truncation: Incorrect datetime value"
// 修: dataType → fieldComponent 映射 (兼容 v0.11a 旧 AI JSON 写法)
if (fld && !fld.fieldComponent && fld.dataType) {
const dtMap: Record<string, string> = {
datetime: 'datePicker',
date: 'datePicker',
time: 'timePicker',
int: 'inputNumber',
bigint: 'inputNumber',
decimal: 'inputNumber',
text: 'textarea',
longtext: 'textarea',
boolean: 'switch',
tinyint: 'switch',
}
const fc = dtMap[String(fld.dataType).toLowerCase()]
if (fc) {
fld.fieldComponent = fc
log.info(` dataType ${fld.dataType} → fieldComponent ${fc} (${fld.fieldName || fld.field})`)
}
}
}
}
}
// 强制 isMain (对齐 JNPF 后端 VisualAiServiceImpl.setIsMain(0, i==0))
aiModelList.forEach((m: any, i: number) => { m.isMain = (i === 0) })
// 自动填 enCode/fullName (用户未传时)
if (!opts.enCode) opts.enCode = aiModelList[0].tableName || `form_${Date.now().toString(36)}`
if (!opts.fullName) opts.fullName = aiModelList[0].tableTitle || opts.enCode
log.info(` enCode: ${opts.enCode} fullName: ${opts.fullName}`)
log.info(` 表数: ${aiModelList.length} (主表 ${aiModelList[0].fields?.length || 0} 字段)`)
// 走 buildFormData (同 --ai 路径)
await initBuildFormData()
const bfdResult = webBuildFormData(aiModelList)
// v0.11f+ (2026-06-27 B-13 fix): 注入 relationForm 字段必填 3 项
// web FormGenerator.vue:272-276 校验: !modelId → "关联功能不能为空"
// web buildFormData 不识别 AiFormModel.fields[].fieldRelationConfig, 需手动注入
// 主子表场景: 子表字段在 formData.fields[].__config__.children[] 里 (jnpfKey=table)
const formDataObjInject = JSON.parse(bfdResult.formData)
const aiFieldsMap = new Map<string, any>() // vmodel → ai field (含 fieldRelationConfig)
for (const m of aiModelList) {
if (Array.isArray(m?.fields)) {
for (const fld of m.fields) {
if (fld?.fieldName) aiFieldsMap.set(fld.fieldName, fld)
}
}
}
let relationInjected = 0
const injectRelationForm = (fld: any) => {
const cfg = fld?.__config__
if (cfg?.jnpfKey === 'relationForm') {
const vmodel = fld.__vModel__
const aiFld = aiFieldsMap.get(vmodel)
const relCfg = aiFld?.fieldRelationConfig
if (!relCfg) {
log.warn(` ⚠ B-13: relationForm 字段 ${vmodel} 缺 fieldRelationConfig, 必填 modelId/propsValue/relationField (web 校验会拒)`)
} else {
// 注入 modelId / propsValue / relationField / columnOptions (镜像 web componentMap.ts:1386-1400)
if (relCfg.modelId) fld.modelId = relCfg.modelId
if (relCfg.propsValue) fld.propsValue = relCfg.propsValue
if (relCfg.relationField) fld.relationField = relCfg.relationField
if (Array.isArray(relCfg.columnOptions) && relCfg.columnOptions.length > 0) {
fld.columnOptions = relCfg.columnOptions.map((c: any) => ({
label: c.label || c.value || c.enCode || '',
value: c.value || c.enCode || c.label || '',
enCode: c.enCode || c.value || '',
}))
}
// 默认补全 web 默认值 (用户没传时)
fld.hasPage = fld.hasPage ?? false
fld.pageSize = fld.pageSize ?? 20
fld.popupType = fld.popupType ?? 'dialog'
fld.popupTitle = fld.popupTitle ?? '选择数据'
fld.popupWidth = fld.popupWidth ?? '800px'
relationInjected++
}
}
// 递归: 主子表场景下子表字段在 jnpfKey=table 的 __config__.children[] 里
if (Array.isArray(cfg?.children)) {
for (const child of cfg.children) injectRelationForm(child)
}
}
for (const fld of formDataObjInject.fields || []) injectRelationForm(fld)
if (relationInjected > 0) {
log.info(`v0.11f+ B-13 fix: 注入 ${relationInjected} 个 relationForm 字段 modelId/propsValue/relationField`)
}
// v0.11g+ B-16 fix (2026-06-27 tds_batch3): 注入主子表 tableName + 子表字段 relationTable
// web buildFormData (formUtils.ts:39-50) 不设置 table 容器 __config__.tableName (web 端由用户拖拽触发 RightPanel.vue:137/342 设)
// web buildFormData 不设置子表字段 __config__.relationTable (web 端由拖拽触发 FormGenerator.vue:491 设)
// 后端 FlowFormDataUtil.createTable:758 查 tableModelList.filter(k.getTable()==tableName), tableName 来自 childModel.getTableName()
// tableName 为空 → 找不到 tableModel → NPE "tableModel is null" → 400 "Failed to add data"
// 修复: 镜像 web 拖拽行为, 根据 aiModelList[i].tableName 注入 formData 字段 __config__.tableName
let subTableInjected = 0
const mainTable = aiModelList.find((m: any) => m.isMain)
if (mainTable && mainTable.tableName) {
// 主表字段 tableName 设为物理主表名 (对齐 web 主表字段行为)
let mainFieldSet = false
for (const fld of formDataObjInject.fields || []) {
if (fld?.__config__?.jnpfKey && fld.__config__.jnpfKey !== 'table' && fld.__config__.layout === 'colFormItem' && !mainFieldSet) {
fld.__config__.tableName = mainTable.tableName
mainFieldSet = true
}
}
}
for (const m of aiModelList) {
if (!m.isMain && m.tableName) {
const idx = (formDataObjInject.fields || []).findIndex((f: any) => f?.__config__?.jnpfKey === 'table')
if (idx >= 0) {
const tbl = formDataObjInject.fields[idx]
tbl.__config__.tableName = m.tableName
const children = tbl.__config__.children || []
for (const c of children) {
c.__config__.relationTable = m.tableName
c.__config__.tableName = mainTable?.tableName || ''
}
subTableInjected++
}
}
}
if (subTableInjected > 0) {
log.info(`v0.11g+ B-16 fix: 注入 ${subTableInjected} 个主子表 tableName + 子表字段 relationTable (避免后端 createTable NPE)`)
}
// 序列化回 bfdResult
;(opts as any).__aiBuildFormData = { ...bfdResult, formData: JSON.stringify(formDataObjInject) }
log.info(`v0.11+ --ai-json 走 web buildFormData, formData.fields=${formDataObjInject.fields.length}`)
// v0.11+ cleanup: 不再强制 type=4, 保持 --type 用户传入 (默认 1 formDesign)
// ai-json 含完整 tableName, 用户可走 type=1 + 物理表 (type=1 是 formDesign 列表)
// 2026-06-26: webType 默认 '1' → '2' (生产场景 99% 都要列表页)
opts.webType = opts.webType || '2'
}
// 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) {
log.error('AI 响应缺 enCode/fullName, 无法自动建表单')
printAiFormResult(data)
process.exit(2)
}
opts.enCode = opts.enCode || data.enCode
opts.fullName = opts.fullName || data.fullName
// 把 aiModelList[0].fields 映射成 formData.fields (粗略: 只取 fieldName + fieldTitle, type=input)
if (!opts.fields && data.aiModelList?.[0]?.fields?.length) {
const fields = data.aiModelList[0].fields.map((f) => ({
__config__: { label: f.fieldTitle || f.fieldName, jnpfKey: 'input' },
__id__: f.fieldName,
__vModel__: f.fieldName,
...(f.fieldOptions?.length ? { options: f.fieldOptions } : {}),
}))
opts.fields = JSON.stringify(fields)
log.info(`AI 生成 ${fields.length} 个字段, 已塞进 --fields`)
}
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.11+ 默认 type=1 (formDesign 自定义); 旧 type=2/4 兜底已废弃
opts.type = opts.type || '1'
opts.webType = opts.webType || '1'
}
// 校验必填
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)
// 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-json (web 端 buildFormData 自动保证 schema 完整性)
if (opts.fields) {
log.error('--fields 已废弃, 请用 --ai-json (v0.11+ 走 web 端 buildFormData, schema 自动完整)')
log.error('例: --ai-json \'[{"tableTitle":"客户表","tableName":"customer","isMain":true,"fields":[...]}]\'')
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) => ({
...entry,
// === 控件行为字段 (与 columnList 对齐) ===
fullNameI18nCode: [entry.fullNameI18nCode || ''], // 数组
clearable: true, disabled: 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', 其他类型透传
// === 搜索特有 (修复 value 类型 + searchMultiple bool) ===
sourceType: 2,
value: [], // 修复: 数组 (dacli 旧 value: '')
searchType: 1,
searchMultiple: false, // 修复: bool (dacli 旧 searchMultiple: 0)
isKeyword: false,
noShow: false,
})
// 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.11+ cleanup: --ai-json 路径下从 ai-json 推导 tables (含字段 schema)
// 优先 --tables 用户传入, 否则从 ai-json 推, 否则 type=4 空, 否则默认主表
const stripAppPrefix = (t: string) =>
c.appCode && t.startsWith(`${c.appCode}_`) ? t.slice(c.appCode.length + 1) : t
let aiJsonTables: any[] | null = null
if (opts.aiJson && (opts as any).__aiBuildFormData?.tables) {
// 从 buildFormData.tables 拿 (web 端已生成, 含 use*Permission 等关键字段)
try { aiJsonTables = JSON.parse((opts as any).__aiBuildFormData.tables) } catch { /* fallthrough */ }
}
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
})
: (Array.isArray(aiJsonTables) && aiJsonTables.length > 0) // 2026-06-26 修复: [] 在 JS 里 truthy, 必须查 length
? aiJsonTables.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.aiJson) {
// v0.11f+ B-15 修复 (2026-06-27 tds_batch3): --ai-json 路径下, 从 formData.fields 推 columnList
// 根因: --ai-json 走 web buildFormData, formData.fields 有完整 __config__/__vModel__/jnpfKey
// 旧逻辑只对 --tables 路径 (场景 B) 自动推 columnList, --ai-json (场景 A) 留空
// → webType=2 校验失败: "列表字段不允许为空"
// 修: 复用 buildColumnListEntry (与场景 B 同结构), 数据源从 formData.fields 来
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) {
const entries = userFormFields.map((f: any) => {
const jnpfKey = f.__config__?.jnpfKey || 'input'
const label = f.__config__?.label || f.__vModel__ || ''
const prop = f.__vModel__ || f.id || label
const e = buildColumnListEntry({ field: prop, fieldName: label }, jnpfKey)
return e
})
columnDataObj.columnList = entries
columnDataObj.searchList = entries.map(buildSearchListEntry)
log.info(`B-15 修复: --ai-json 路径从 formData.fields 自动生成 columnList: ${entries.length} 个字段`)
} else {
log.warn(`B-15: --ai-json 路径 formData.fields 为空, ★ 走 Web 设计器勾选`)
}
} else if (webType !== 1) {
log.info(`★ 场景 A: columnList 留空, 去 formDesign Web 设计器第二步"列表设计"手动勾选字段`)
}
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,
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 拿)',
'--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-json=\'[{"tableTitle":"请假","tableName":"leave","isMain":true,"fields":[{"field":"f_name","fieldTitle":"姓名","dataType":"varchar","dataLength":"100","required":true}]}]\' --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-json 建表单',
'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
}