form/create.ts (1572→1524):
- 删硬编码 BUSINESS_TYPE_ID 兜底分支 (compatible old NCPF, 真 dead)
- 删 rawFields/converted/total 空壳 (rawFields 在空数组循环是真 dead)
- 删老 ternary `__aiBuildFormData ? ... : { 默认空 schema }` 老分支 (--fields 已 ctx.fail, 走不到)
- 删 type=webType 默认值 override (commander declaration 已经默认)
- 简化"删 dead code (aiModelList[0].fields 手动映射)" 4 行注释 → 1 行
form/codegen.ts:
- 删 autoFixNames option (已废弃, 全文 0 引用)
- 修错 TODO: --auto-menu + L17 + L1022 (已实现 autoMountMenu)
- 修"auto-fix-names 已废弃" 注释
_post_reminders.ts (+5 factory):
- remindCategoryGuess (category 兜底提示)
- remindSmartPropsAIFallback (启发式标必填兜底)
- remindRelationFormAutoSkip (注入失败提示)
- remindCodeGenMenuAttachFail (codegen 成功但 menu 未挂)
- remindCodeGenPomConflict (互斥 flag 提示)
L3 落点 (7 inline log.warn → ctx.addSuggestion):
- form/create: categoryGuess × 4 + smartProps × 2 + relationForm × 1
- form/codegen: menuAttachFail + pomConflict × 1
类型校验: 0 新增 error (10 个 pre-existing id/fullName/aiModelList 类型错不动)
单测: 48/48 pass (output_filter 22 + auto_fix 26)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
1525 lines
87 KiB
TypeScript
1525 lines
87 KiB
TypeScript
/**
|
||
* 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 { installHelpHookWithPatterns } 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, applyHeuristicRequired, applyHeuristicRelationForm } from './_smart_props.ts'
|
||
import { repairFormDataFromString } from './_form_repair.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'
|
||
import { applyNamingConvention, type NamingConvention } from './_naming_convention.ts'
|
||
import { autoStripEnCode, autoStripFullName } from '../_encode_validator.ts'
|
||
import { runAutoFix, type FixContext } from '../_auto_fix.ts'
|
||
import { saveCommandLog, formatOneLineSummary, type CommandLog } from '../../core/logfile.ts'
|
||
import { remindAiLoginExpired, remindAiEnCodeDiverge, remindCategoryGuess, remindSmartPropsAIFallback, remindRelationFormAutoSkip } from '../_post_reminders.ts' // v2.3+ (2026-07-21): 7 高频 inline ⚠ 固化到 L3
|
||
import { wrapCommand } from '../_output_filter.ts' // v2.2+ (2026-07-21): wrapCommand 收口 5c (承接 precheck/guard throw + 11 process.exit)
|
||
|
||
interface CreateOpts {
|
||
fullName?: string
|
||
enCode?: string
|
||
type?: string
|
||
webType?: string
|
||
category?: string
|
||
dbLinkId?: string
|
||
fields?: string
|
||
tables?: string
|
||
/** : 绑现有物理表, 镜像 web "选表 → 自动生成字段" (跟 --ai 同 code path) */
|
||
table?: string
|
||
enableFlow?: string
|
||
flowId?: string
|
||
autoRelease?: boolean
|
||
/** --autoTable 强制从 --fields 推导 --tables (覆盖 --tables, 对齐 web formDesign Form.vue) */
|
||
autoTable?: boolean
|
||
/** (盲点 47): 建完发布后自动挂菜单到指定父目录, 避免浏览器验证 step check-list 找不到 vxe-table */
|
||
autoCreateMenu?: boolean
|
||
/** 父菜单 id (--autoCreateMenu 时必传, 用 dacli menu list --keyword=... 拿) */
|
||
menuParentId?: string
|
||
/**
|
||
* 关闭 relationForm 自动注入
|
||
* 默认 ON (启发式注入), --no-relation-form-auto 强制关闭
|
||
* 适用: 字段名含 _code 后缀 (业务编码, 不是关系字段) 时避免误判
|
||
*/
|
||
relationFormAuto?: boolean
|
||
json?: boolean
|
||
verbose?: boolean
|
||
/** 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields */
|
||
ai?: string
|
||
/** 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 不建表单 */
|
||
aiField?: string
|
||
// 删除 --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
|
||
/**
|
||
* 新增: 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
|
||
/** 兜底能力: 走 UI 路径 (playwright 模拟人类在 formDesign 操作) */
|
||
via?: 'api' | 'ui'
|
||
}
|
||
|
||
/**
|
||
* app-P1 完整版 + 增强: form category 自动派生 + AI 智能判断 + 缓存复用
|
||
* 整合进 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,
|
||
// v2.3+ (2026-07-21): 可选 ctx, 给 category 兜底提供 L3 落点
|
||
ctx?: { addSuggestion(s: import('../../core/logfile.ts').FixEntry): void },
|
||
): Promise<{ id: string; name: string } | null> {
|
||
|
||
// 每次 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(` 查 webapi businessType 字典失败: ${(e as Error).message?.slice(0, 100)}`)
|
||
}
|
||
|
||
if (items.length === 0) return null
|
||
|
||
// 3. : AI 推理业务分类 (替代默认第一项的死办法)
|
||
// form --ai / --table 都走这; AI 理解表单语义, 从可选分类中选最合适的
|
||
let picked: { id: string; enCode?: string; fullName: string } | null = null
|
||
|
||
// 优先用 appCode/formName 关键词匹配业务分类
|
||
// 历史: AI 推理失败时 fallback items[0] (默认"车辆管理"), 跨 appCode 不正确
|
||
// 拿 appCode + formName 关键词 (e.g. "app" / "数据要素" / "大赛") 跟 items.fullName 模糊匹配
|
||
const nameKeywords = [
|
||
appCode,
|
||
...(formName?.split(/[\s_-]+/) || []),
|
||
].filter(k => k && k.length >= 2)
|
||
for (const kw of nameKeywords) {
|
||
const kwLower = kw.toLowerCase()
|
||
const matched = items.find(it =>
|
||
it.fullName && it.fullName.toLowerCase().includes(kwLower),
|
||
)
|
||
if (matched) {
|
||
picked = matched
|
||
log.info(` ✓ R17 P1-3 关键词匹配 category: ${picked.fullName} (kw='${kw}', from ${items.length} 可选分类)`)
|
||
break
|
||
}
|
||
}
|
||
|
||
// fallback: AI 推理
|
||
if (!picked) {
|
||
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 {
|
||
// v2.3+ L3 落点: AI 给的 id 不在字典里
|
||
log.warn(` ! AI 推理 category id=${catResp.data.id} 不在字典中, 用默认第一项`)
|
||
ctx?.addSuggestion(remindCategoryGuess(items[0].id, items[0].fullName, 'item-not-found'))
|
||
}
|
||
} else {
|
||
// v2.3+ L3 落点: AI 端点失败
|
||
log.warn(` ! AI 推理 category 失败 (code=${catResp.code}): ${catResp.msg}, 用默认第一项`)
|
||
ctx?.addSuggestion(remindCategoryGuess(items[0].id, items[0].fullName, 'ai-fail'))
|
||
}
|
||
} catch (e) {
|
||
// v2.3+ L3 落点: AI 调用异常
|
||
log.warn(` ! AI 推理 category 异常: ${(e as Error).message?.slice(0, 80)}, 用默认第一项`)
|
||
ctx?.addSuggestion(remindCategoryGuess(items[0].id, items[0].fullName, 'ai-exception'))
|
||
}
|
||
}
|
||
if (!picked) {
|
||
picked = items[0]
|
||
// v2.3+ L3 落点: 任何兜底都至少提醒一次 "category 是猜的"
|
||
if (items[0]) ctx?.addSuggestion(remindCategoryGuess(items[0].id, items[0].fullName, 'default-item0'))
|
||
}
|
||
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 等业务编码字段被误判为关系字段时)')
|
||
// --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 推荐单字段, 只输出建议不建表单')
|
||
// 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)
|
||
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
|
||
// columnList / __vModel__ 命名规范适配
|
||
// auto = comInputField101, comSelectField102... (JNPF 设计器默认, baseline 34/60)
|
||
// snake = f_serial_num (带 f_ 前缀, baseline 6/60, JNPF 标准)
|
||
// f_prefix = F_SerialNum (UpperCamel + F_, baseline 2/60, 老 jnpf 2.x)
|
||
// 默认 = snake (JNPF 标准, f_ 前缀 + snake_case)
|
||
// 2026-07-20 jxcj: 默认从 "snake 语义 (0/60 baseline)" 改为 "snake (6/60 baseline, JNPF 标准)"
|
||
// 因为 AI 路径生成的 camelCase 字段名 (e.g. competition_name) 与 JNPF 规范 (f_name) 不匹配
|
||
// 应用 applyNamingConvention 重命名为 f_competition_name, 符合 JNPF 规范
|
||
// 不改 AI prompt: dacli 设计上不写 LLM prompt (跟 NCPF backend 透传, 见 _ai.ts:3-9)
|
||
.option('--column-naming <style>', 'columnList 命名规范: auto | snake | f_prefix (默认 snake, JNPF 标准)', 'snake')
|
||
.action(async (opts: CreateOpts) => {
|
||
log.setQuiet(!opts.verbose)
|
||
const startTime = Date.now()
|
||
const fixLog: { silent: any[]; assertive: any[]; suggestions: any[] } = {
|
||
silent: [], assertive: [], suggestions: [],
|
||
}
|
||
// P1-5 保存用户原始 enCode (BEFORE strip)
|
||
// 用途: AI 路径下若 AI 建议 enCode 与用户输入不一致, 打 warning 提示 mismatch.
|
||
// 案例: app 11 form 全部 enCode 被转换, 用户设计文档 enCode 与实际不一致 (snake_case vs camelCase).
|
||
const originalUserEnCode = opts.enCode
|
||
// (Round 12 enCode 含 `-`/`_` 自动 strip + WARN
|
||
// P1-5 强化 : warning 增强 - 含 NCPF 强制 camelCase 提示 + 表名同步 + 后续命令参考
|
||
// 历史: app 实战发现 warning 太轻量 ("下次别用 - 或 _"), 用户/AI 没注意 enCode 已被转换,
|
||
// 导致设计文档 enCode (snake_case) 与 JNPF 实际 enCode (camelCase) 不一致.
|
||
// warning 显式说明 (1) NCPF 强制 camelCase (2) 表名同步转换 (3) 后续命令必须用 camelCase.
|
||
// 必须在 ai 之前: options.ai 会基于修正后的 enCode 走 web buildFormData
|
||
if (opts.enCode) {
|
||
const _encStrip = autoStripEnCode(opts.enCode)
|
||
if (_encStrip.wasStriped) {
|
||
log.warn(`⚠ enCode 转换: ${_encStrip.original} → ${_encStrip.value} (NCPF 后端强制 camelCase, BS-新56 强化)`)
|
||
log.warn(` 表名同步转换: ${_encStrip.original} → ${_encStrip.value} (BS-55 同步规则, 后续 dm/table 引用请用转换后)`)
|
||
log.warn(` 后续命令参考: menu create / form update / form info 需用 ${_encStrip.value} 引用`)
|
||
opts.enCode = _encStrip.value
|
||
}
|
||
}
|
||
|
||
// fix (fullName 含 space/parens 自动 strip + WARN
|
||
// 现象: `round13 客户管理记录表(集成助手)` 被 step0 拒 → 改 fullName 后 retry
|
||
if (opts.fullName) {
|
||
const _fnStrip = autoStripFullName(opts.fullName)
|
||
if (_fnStrip.wasStriped) {
|
||
log.warn(`! autoStrip fullName: ${_fnStrip.original} → ${_fnStrip.value} (BS-新52, 下次别用空格/括号/标点)`)
|
||
opts.fullName = _fnStrip.value
|
||
}
|
||
}
|
||
|
||
const c = await JnpfClient.fromToken()
|
||
await wrapCommand({
|
||
command: 'form create',
|
||
appCode: c.appCode,
|
||
startTime,
|
||
verbose: opts.verbose,
|
||
json: opts.json,
|
||
fixes: [],
|
||
}, async (ctx) => {
|
||
try {
|
||
// 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) {
|
||
// v2.0+: AI token 预检 — 过期则自动重登
|
||
try {
|
||
const healthR = await c.get<{ code: number }>('/visualdev/Base', { currentPage: 1, pageSize: 1 })
|
||
if (healthR.code === 600) {
|
||
log.warn('⚠ AI token 过期, 自动重登...')
|
||
const { execSync } = await import('node:child_process')
|
||
const cliEntry = process.argv[1] || 'src/cli.ts'
|
||
execSync(`npx tsx ${cliEntry} app login --account=admin --password=123456 --appCode=${c.appCode}`, {
|
||
stdio: 'pipe', timeout: 15000,
|
||
})
|
||
log.info('✓ 重登完成, 继续 AI 调用')
|
||
}
|
||
} catch { /* 预检失败不阻塞 */ }
|
||
|
||
log.info(`--ai "${opts.ai}" — 调用平台 AI 生成表单 (白皮书 5.10.1)`)
|
||
const data = await callAiForm(opts.ai)
|
||
// P1-7 AI Login expired fallback
|
||
// 根因: NCPF + SSW 双双 Login expired (同 token 失效), AI 完全不可用
|
||
// 检测 loginExpired=true 后, 若 user 已传 --enCode/--fullName → 警告但继续
|
||
// 走 web buildFormData 默认空 schema (允许 form 创建, 后续 form update 加字段)
|
||
// 若 user 未传 → exit 2, 提示需手动 --enCode/--fullName
|
||
if (data.loginExpired) {
|
||
if (!opts.enCode || !opts.fullName) {
|
||
log.error('⚠ AI Login expired (NCPF + SSW 同 token 失效), 且未传 --enCode/--fullName, 无法自动建表单')
|
||
log.error(' 修复: 加 --enCode=<你的英文名> --fullName="<中文名>", 走 web buildFormData 默认空 schema')
|
||
log.error(' 后续: 用 dacli form update --fields=<完整 JSON> 加字段')
|
||
if (data._aiChain) {
|
||
log.error('AI 调用链 (排查失败原因):')
|
||
for (const step of data._aiChain) log.error(` - ${step}`)
|
||
}
|
||
return ctx.fail('AI Login expired (NCPF + SSW 同 token 失效), 且未传 --enCode/--fullName, 无法自动建表单', { enCode: opts.enCode })
|
||
}
|
||
// user 提供了 --enCode + --fullName → 走 web buildFormData 默认空 schema
|
||
log.warn(`⚠ P1-7: AI Login expired (NCPF + SSW 双失效), fallback 走 web buildFormData 默认空 schema`)
|
||
log.warn(` form 创建后会以 0 字段状态发布, 后续用 dacli form update --fields=<JSON> 添加字段`)
|
||
if (data._aiChain) {
|
||
for (const step of data._aiChain) log.warn(` ${step}`)
|
||
}
|
||
// v2.3+: 落 L3 (供 dacli log last --level=fix 查询)
|
||
ctx.addSuggestion(remindAiLoginExpired(opts.enCode))
|
||
// 关键: 把 user 输入注入 data, 后续代码走空 aiModelList 路径
|
||
data.enCode = opts.enCode
|
||
data.fullName = opts.fullName
|
||
data.aiModelList = [] // 空数组 → webBuildFormData 产出默认 schema (0 字段)
|
||
} else if (!data.enCode || !data.fullName) {
|
||
// 显式打印 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)
|
||
return ctx.fail('AI 响应缺 enCode/fullName, 无法自动建表单', { enCode: opts.enCode })
|
||
}
|
||
opts.enCode = opts.enCode || data.enCode
|
||
opts.fullName = opts.fullName || data.fullName
|
||
// P1-5 检测 AI 建议 enCode 与用户输入不一致
|
||
// 场景: 用户传 --enCode='topic_direction', AI 返回 enCode='topicdirection' (或反之)
|
||
// warning 告知用户 mismatch, 后续 menu/update 引用以最终 opts.enCode 为准
|
||
// P1-7 注: loginExpired fallback 时 data.enCode=user enCode, 不会触发 mismatch warning
|
||
if (!data.loginExpired && originalUserEnCode && data.enCode && originalUserEnCode !== data.enCode) {
|
||
log.warn(`⚠ AI 建议 enCode 与用户输入不一致: ${originalUserEnCode} (用户) vs ${data.enCode} (AI)`)
|
||
log.warn(` 最终用 opts.enCode=${opts.enCode} (优先用户输入, BS-新56 强化)`)
|
||
// v2.3+: 落 L3 (suggest AI 应尊重 user enCode)
|
||
ctx.addSuggestion(remindAiEnCodeDiverge(originalUserEnCode, data.enCode))
|
||
}
|
||
// 注: aiModelList[0].fields → formData.fields 手动映射已删 (强制 jnpfKey='input' 会丢日期/选择/关联), 改走 web buildFormData
|
||
log.info(`AI 建议 enCode=${opts.enCode} fullName=${opts.fullName}`)
|
||
// (Task 7 改造): --ai 路径用 web 端 buildFormData 而非 _simplify
|
||
// 解决: AI 返回的 switch/datePicker/select 在 _simplify 里被简化成 input
|
||
// buildFormData 100% 注入 formId/renderKey/isSubTable/options
|
||
await initBuildFormData()
|
||
const aiModelListForBfd = data.aiModelList || []
|
||
// wire up relationForm 自动注入
|
||
// 历史 函数 _relationForm_auto.ts:144 定义但 0 import/call
|
||
// 现在: --ai 路径自动检测 f_*_id 字段 + 注入 modelId/propsValue/relationField
|
||
// AI 不会自动给关联字段生成 relationForm, 用 dacli 启发式补救
|
||
// 关闭: --no-relation-form-auto (commander 默认 true, --no-* 传时设 false)
|
||
if ((opts as any).relationFormAuto !== false) {
|
||
try {
|
||
const { autoDetectAndInjectRelationForm } = await import('./_relationForm_auto.ts')
|
||
// cast: aiModelListForBfd 含 billRule/unique 等 extra fields, 函数签名只关心 4 项
|
||
const injected = await autoDetectAndInjectRelationForm(
|
||
aiModelListForBfd as unknown as Parameters<typeof autoDetectAndInjectRelationForm>[0],
|
||
)
|
||
if (injected > 0) {
|
||
log.info(` ↳ relationForm 自动注入 (BS-新117 R17): ${injected} 个字段`)
|
||
}
|
||
} catch (e) {
|
||
// v2.3+ L3: 落 suggest, AI 自检 fail 模式
|
||
log.warn(`relationForm 自动注入跳过 (${(e as Error).message?.slice(0, 80)})`)
|
||
ctx.addSuggestion(remindRelationFormAutoSkip((e as Error).message?.slice(0, 80) || 'unknown'))
|
||
}
|
||
} else {
|
||
log.info(` ↳ --no-relation-form-auto, 跳过 relationForm 自动注入`)
|
||
}
|
||
|
||
// v2.0+ auto_fix pipeline: 在 buildFormData 前修正字段
|
||
try {
|
||
// 构建上下文: 已有表单 (FK 匹配) + 已有字典 (建议)
|
||
const fixCtx: FixContext = {}
|
||
try {
|
||
const formListR = await c.get<{ list?: { id: string; enCode: string; fullName?: string }[] }>(
|
||
'/visualdev/Base', { currentPage: 1, pageSize: 500 },
|
||
)
|
||
fixCtx.existingForms = formListR.data?.list || []
|
||
} catch { /* FK 匹配失败不阻塞 */ }
|
||
try {
|
||
const dictListR = await c.get<{ list?: { id: string; enCode: string; fullName?: string }[] }>(
|
||
'/system/DictionaryType', { currentPage: 1, pageSize: 500 },
|
||
)
|
||
const flattenDicts = (nodes: any[]): any[] => {
|
||
const out: any[] = []
|
||
for (const n of nodes) {
|
||
if (n.enCode) out.push({ id: n.id, enCode: n.enCode, fullName: n.fullName })
|
||
if (Array.isArray(n.children)) out.push(...flattenDicts(n.children))
|
||
}
|
||
return out
|
||
}
|
||
fixCtx.existingDicts = flattenDicts(dictListR.data?.list || [])
|
||
} catch { /* dict 查询失败不阻塞 */ }
|
||
|
||
// 对每个 AiFormModel 的 fields 跑 auto_fix
|
||
for (const model of aiModelListForBfd) {
|
||
if (!model.fields?.length) continue
|
||
const result = runAutoFix(model.fields, fixCtx, !model.isMain)
|
||
model.fields = result.fields
|
||
fixLog.silent.push(...result.silent)
|
||
fixLog.assertive.push(...result.assertive)
|
||
fixLog.suggestions.push(...result.suggestions)
|
||
}
|
||
const totalFixes = fixLog.silent.length + fixLog.assertive.length + fixLog.suggestions.length
|
||
if (totalFixes > 0) {
|
||
log.info(` ↳ auto_fix: ${fixLog.silent.length} silent + ${fixLog.assertive.length} assertive + ${fixLog.suggestions.length} suggestions`)
|
||
}
|
||
} catch (e) {
|
||
// auto_fix 失败不阻塞主流程
|
||
log.debug(`auto_fix pipeline 跳过 (${(e as Error).message?.slice(0, 80)})`)
|
||
}
|
||
|
||
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}`)
|
||
|
||
// dos 26 P0 修复: --ai 默认 smartProps 选配组件属性
|
||
// 修复 4 类盲点 (字段名→字典/min-max/relationForm/regList)
|
||
// 合规扩展层 (CLAUDE.md §11.5): 不改 jnpf/NCPF, 在 dacli 端读已有 dict+form 列表启发式填
|
||
// 默认 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()
|
||
// 注: 这里 `ctx` 是 smartPropsContext (applySmartProps / applyHeuristicRelationForm 内部用),
|
||
// 跟外层 wrapCommand ctx 不同, 用 smartCtx 区分避免 shadow
|
||
const smartCtx = await loadSmartPropsContext(smartClient)
|
||
const parsedFormData = JSON.parse(bfdResult.formData)
|
||
const { formData: enhancedFormData, applied, source } = await applySmartProps(parsedFormData, smartCtx, { verbose: true })
|
||
// (Round 12 smartProps AI 失败 fallback 启发式 required
|
||
// 旧: source='none' → required 全 false → 5/5 form drift (web 默认 false)
|
||
// 新: fallback 跑启发式 (label 含* / 必, vmodel 末为 id/code/key → required=true)
|
||
let heuristicApplied = { applied: 0, alreadyHad: 0 }
|
||
let relationFormApplied = { applied: 0, matched: 0, skipped: 0 }
|
||
let finalFormData = enhancedFormData
|
||
if (source === 'none') {
|
||
heuristicApplied = applyHeuristicRequired(enhancedFormData)
|
||
if (heuristicApplied.applied > 0) {
|
||
log.warn(` ↳ smartProps AI 失败 + 启发式 required 兜底: ${heuristicApplied.applied} 字段标 required=true (BS-新41)`)
|
||
// v2.3+ L3: 告诉 AI 必填可能误标, web 设计器复核
|
||
ctx.addSuggestion(remindSmartPropsAIFallback(heuristicApplied.applied))
|
||
} else {
|
||
log.warn(` ↳ smartProps AI 推理失败/返回空, 启发式 required 无候选 (audit 兜底)`)
|
||
ctx.addSuggestion(remindSmartPropsAIFallback(0))
|
||
}
|
||
// 失败兜底
|
||
// 历史: (_smart_props.ts:230-241) 仅 AI 成功才执行 input FK → relationForm
|
||
// 失败兜底用 applyHeuristicRelationForm (字段名含 enCode 强匹配 + label 弱匹配)
|
||
// 注意: smartCtx 是 SmartPropsContext (smartProps 内部用), ≠ 外层 wrapCommand ctx
|
||
relationFormApplied = applyHeuristicRelationForm(enhancedFormData, smartCtx)
|
||
if (relationFormApplied.skipped > 0) {
|
||
log.warn(` ↳ applyHeuristicRelationForm: ${relationFormApplied.skipped} FK 字段 0 候选 (user 后续手工补 modelId)`)
|
||
}
|
||
}
|
||
// 写回 formData string
|
||
bfdResult.formData = JSON.stringify(finalFormData)
|
||
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(', ')
|
||
// 用户反馈: 单一源 AI 推理, 无关键词 fallback (避免双系统混淆)
|
||
if (source !== 'none') {
|
||
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 组件属性选配`)
|
||
}
|
||
|
||
// fix (in-process FormRepair 兜底 (type_drift + column_drift)
|
||
// 现象: NCPF AI 把 jnpfKey 改错 (organizeSelect→input), F_ 前缀列名被重命名.
|
||
// 尝试: 调 ssw /api/ssw/form/repair-fields HTTP — 被 JNPF Sa-Token AuthFilter 拒 (auth blocked).
|
||
// 改: 镜像 ssw FormRepairServiceImpl 到 TS (./_form_repair.ts), in-process 调用.
|
||
// 优势: 0 网络调用 / 0 auth 问题 / 跟 shared module 实现同步维护.
|
||
// baselineColumnList 可选 — 没传时只跑 type_drift 修复 (column 不动).
|
||
try {
|
||
const repaired = repairFormDataFromString(
|
||
bfdResult.formData,
|
||
(bfdResult as { baselineColumnList?: string }).baselineColumnList || null,
|
||
)
|
||
if (repaired?.formData) {
|
||
bfdResult.formData = JSON.stringify(repaired.formData)
|
||
log.info(
|
||
` ↳ in-process FormRepair (BS-新45): typeRepairs=${repaired.stats.typeRepairs}, columnRepairs=${repaired.stats.columnRepairs}`,
|
||
)
|
||
}
|
||
} catch (e) {
|
||
log.warn(`in-process FormRepair 兜底跳过 (${(e as Error).message?.slice(0, 80)})`)
|
||
}
|
||
// --ai 走 webapi 透传, type/webType 默认值已在 commander declaration (type='1' / webType='2')
|
||
log.info(` ↳ --ai 走 web 端 (NCPF backend /visualdev/ai/form + web buildFormData), 不再 dacli 自写 fields`)
|
||
// --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 发布)`)
|
||
}
|
||
}
|
||
// --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} 无字段, 无法自动生成表单`)
|
||
return ctx.fail(`表 ${opts.table} 无字段, 无法自动生成表单`, { table: opts.table })
|
||
}
|
||
// dm 字段 → aiModelList 格式 (跟 --ai 路径 NCPF 返回的 VisualAiModel 结构一致)
|
||
// 用后端 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(', ')
|
||
|
||
// 走 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)')
|
||
return ctx.fail(`SSW AI 推理失败 (code=${sswResp.code}): ${sswResp.msg || '返空'}`, { table: opts.table })
|
||
}
|
||
const aiModelList: any[] = sswResp.data.aiModelList
|
||
log.info(` ↳ SSW AI 推理完成: ${aiModelList[0].fields?.length || 0} 字段`)
|
||
// 存储 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}`)
|
||
// --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 自动生成)')
|
||
return ctx.fail('--fullName 和 --enCode 必填 (或传 --ai "<描述>")', { enCode: opts.enCode })
|
||
}
|
||
|
||
// --via=ui 走 UI 路径 (playwright 模拟人类操作)
|
||
if (opts.via === 'ui') {
|
||
log.info(`--via=ui 走 UI 路径 (playwright 模拟人类在 formDesign 创建表单)`)
|
||
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) return ctx.fail(`UI 路径失败: ${result.error}`, { enCode: opts.enCode })
|
||
return ctx.success({ id: result.id, enCode: result.enCode })
|
||
}
|
||
|
||
const type = Number(opts.type)
|
||
const webType = Number(opts.webType)
|
||
// '--dbLinkId=default' 字面量 → token.dbLinkId (与 web formDesign Form.vue 一致)
|
||
const dbLinkId = c.resolveDbLinkId(opts.dbLinkId)
|
||
|
||
// app-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 匹配
|
||
// (app 匹配 "项目管理" 之类业务分类) → 用 id; 找不到 fallback 通用 8f65...
|
||
if (!opts.category || !opts.category.trim()) {
|
||
const autoCat = await autoDeriveCategoryFromBusinessType(c, c.appCode, opts.fullName, ctx)
|
||
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'))
|
||
|
||
// cleanup: --fields 简化版已废弃, 走 --ai (web 端 buildFormData 自动保证 schema 完整性)
|
||
if (opts.fields) {
|
||
log.error('--fields 已废弃, 请用 --ai "<描述>" (v0.12+ 走 web 端 buildFormData, schema 自动完整)')
|
||
log.error('例: --ai "客户管理:姓名、电话、邮箱"')
|
||
return ctx.fail('--fields 已废弃, 请用 --ai "<描述>"', { enCode: opts.enCode })
|
||
}
|
||
// ai-json 路径下从 buildFormData 拿完整 fields (含 __config__ 全部 18 键)
|
||
// 注: 老 ternary `__aiBuildFormData ? ... : { formRef, ...默认空 schema }` 已删,
|
||
// 因为前面 L706-710 已 ctx.fail (--fields 已废弃), 走不到老分支
|
||
const formDataObj: any = (opts as any).__aiBuildFormData
|
||
? JSON.parse((opts as any).__aiBuildFormData.formData)
|
||
: null
|
||
const fieldsArr: any[] = formDataObj?.fields || []
|
||
|
||
// v0.11+ --ai / --table 路径: 必用 web buildFormData (formId/renderKey/isSubTable/options 100% 完整)
|
||
// 注: 老 ternary `__aiBuildFormData ? ... : { formRef, ...默认空 schema }` 默认分支真 dead,
|
||
// 因为上面 L684-688 已 ctx.fail (--fields 已废弃), 没有 --ai/--table 必无法到此分支, 删
|
||
if (!(opts as any).__aiBuildFormData) {
|
||
return ctx.fail('--ai 或 --table 必传其一 (--fields 已废弃, 走 web buildFormData 自动保证 schema 完整性)', { enCode: opts.enCode })
|
||
}
|
||
const formData: any = JSON.parse((opts as any).__aiBuildFormData.formData)
|
||
// tdd9 同步去 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
|
||
}
|
||
}
|
||
}
|
||
// (盲点 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',
|
||
])
|
||
// (审计修复): 与 web 真实 columnList entry 对齐 (参考 form id 624163990351643525)
|
||
// 关键修复:
|
||
// - 补 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: [],
|
||
},
|
||
}
|
||
}
|
||
// (审计修复): 与 web 真实 searchList entry 对齐 (参考 form id 585448937427567365)
|
||
// 关键修复:
|
||
// - `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,
|
||
// === 修复 : 与 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, // 数据源类型 (高代码字典类型等)
|
||
},
|
||
}
|
||
}
|
||
|
||
// (审计修复): 与 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,
|
||
// === 修复:补齐 web 默认字段(盲点 51 上游根因)===
|
||
ruleList: { matchLogic: 'and', conditionList: [] }, // 过滤规则(缺失会前端 NPE)
|
||
resizable: true, // 列表列拖拽
|
||
showOverflow: true, // 修复: 旧 useOverflow 命名错位
|
||
childTableStyle: 1, // 子表样式
|
||
showSummary: false, summaryField: [],
|
||
columnOptions: [], defaultColumnList: [], // 默认列选项
|
||
// 修复 (v0.11, app 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 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,
|
||
// === 列表/搜索字段 (自动填充, 见下方 326 行) ===
|
||
columnList: [], searchList: [],
|
||
// === APP 端独立字段 (web `defaultAppColumnData`, dacli 保留旧名 appColumnList) ===
|
||
appColumnOptions: [], appColumnList: [],
|
||
// === 标签面板 + 卡片布局 + 多级表头 ===
|
||
tabConfig: { on: false, relationField: '', hasAllTab: true }, // 修复 tabConfig 缺失
|
||
cardListConfig: {}, // web 默认有值, dacli 简化空对象
|
||
complexHeaderList: [],
|
||
// === 表格样式 + 关联表单 (修复 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,
|
||
}
|
||
// --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 循环, 表不存在抛 "请在数据库中添加对应的数据表"
|
||
|
||
// 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'
|
||
}
|
||
})
|
||
}
|
||
|
||
// 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 失败)`)
|
||
}
|
||
}
|
||
|
||
// B-8 修复 (防御深度 #2): form 提交前, 过滤 tables[].fields 中与 system 字段重名的列.
|
||
// 根因 (见 docs/app/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 (已知).
|
||
// 子表 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
|
||
// B-18 fix 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 镜像)`)
|
||
}
|
||
})
|
||
}
|
||
|
||
// 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'
|
||
}
|
||
})
|
||
}
|
||
|
||
// 反思: 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=... 引用已有物理表) 时, 按 旧逻辑推 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) {
|
||
// 注: 原 rawFields labelByField 桥已废弃, rawFields 在 v2.0+ 永远空数组,
|
||
// label 直接走 mainTable.fields[i].fieldName, 单测覆盖了此路径.
|
||
const entries = userFields.map((f: any) => {
|
||
const e = buildColumnListEntry(f)
|
||
const lbl = f.fieldName || 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)) {
|
||
// B-15 修复 --ai / --table 路径下, 从 formData.fields 推 columnList
|
||
// --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) {
|
||
// --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} 跳过: 只适合表单不适合列表)` : ''))
|
||
|
||
// 列命名规范适配 (跟 baseline 匹配)
|
||
if (opts.columnNaming && ['auto', 'snake', 'f_prefix'].includes(opts.columnNaming)) {
|
||
const conv = opts.columnNaming as NamingConvention
|
||
const r = applyNamingConvention(formData, columnDataObj, conv)
|
||
log.info(`BS-drift-1 修复: --column-naming=${conv}, 重命名 ${r.renamed} 个 __vModel__/prop (${r.skipped} 已合规跳过)`)
|
||
}
|
||
} else {
|
||
log.warn(`B-15: --ai 路径 formData.fields 为空, ★ 走 Web 设计器勾选`)
|
||
}
|
||
} else if (webType !== 1) {
|
||
log.info(`★ 场景 A: columnList 留空, 去 formDesign Web 设计器第二步"列表设计"手动勾选字段`)
|
||
}
|
||
|
||
// 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'
|
||
}
|
||
})
|
||
}
|
||
|
||
// trigger 默认值兜底
|
||
// 根因 (app 复盘, docs/app/dacli-fix-plan.md §7): NCPF CodePreview 在
|
||
// formData.fields[].__config__.trigger="" 时 → PublicMacro/FormMarco.vm:1226
|
||
// 调 substring(0,1) 抛 StringIndexOutOfBoundsException → "System abnormality" 400.
|
||
// app announcement (847163467923194821) + auditrecord (847169004752602053)
|
||
// 创建后 codegen 报 CodePreview System abnormality, controller 缺失.
|
||
// 防御: 遍历 formData.fields, 凡 trigger 空字符串/空数组/缺失 → 按 jnpfKey 设默认:
|
||
// input/textarea/editor → 'blur' (文本类控件)
|
||
// 其他 (select/checkbox/radio/datePicker/timePicker/...) → 'change' (选择类控件)
|
||
// 子表容器 (jnpfKey='table') 跳过 — 它们不在 mastForm 路径.
|
||
// 镜像 web 端 ColumnDesign/src/helper/config.ts:181 trigger 默认 'blur' 的语义.
|
||
if (Array.isArray(formData?.fields)) {
|
||
const TEXT_LIKE = new Set(['input', 'textarea', 'editor'])
|
||
let triggerFixed = 0
|
||
for (const fld of formData.fields as any[]) {
|
||
if (!fld || !fld.__config__) continue
|
||
// 子表容器不需要 trigger (它的字段在 subFormFields)
|
||
if (fld.__config__.jnpfKey === 'table') continue
|
||
const cur = fld.__config__.trigger
|
||
const isEmpty = cur === undefined || cur === null || cur === '' ||
|
||
(Array.isArray(cur) && cur.length === 0)
|
||
if (isEmpty) {
|
||
const jnpfKey = String(fld.__config__.jnpfKey || '')
|
||
fld.__config__.trigger = TEXT_LIKE.has(jnpfKey) ? 'blur' : 'change'
|
||
triggerFixed++
|
||
}
|
||
}
|
||
if (triggerFixed > 0) {
|
||
log.info(`✓ P0-5 fix: 自动设置 ${triggerFixed} 字段 __config__.trigger 默认值 (避免 CodePreview FormMarco.vm:1226 空串 crash)`)
|
||
}
|
||
}
|
||
|
||
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}`)
|
||
|
||
// 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}`)
|
||
}
|
||
}
|
||
}
|
||
// P1 修复: 提示这是参数校验问题 (跟 --ai 失败区分)
|
||
const bs56 = validation.steps.flatMap(s => s.errors).find(e => e.code?.startsWith('BS-56'))
|
||
if (bs56) {
|
||
log.error('')
|
||
log.error('⚠ 这是参数校验问题, 跟 --ai 是否成功无关:')
|
||
log.error(` 修复: ${bs56.code === 'BS-56' ? '去掉 enCode 中的下划线/连字符 (如 dyy_v1 → dyyv1)' : '检查 enCode 格式'}`)
|
||
} else {
|
||
log.error('')
|
||
log.error('⚠ 这是 step machine 参数校验, 跟 --ai 调用无关. 修复后再跑.')
|
||
}
|
||
if (opts.json) {
|
||
printJson({ ok: false, validation: validation.steps })
|
||
}
|
||
return ctx.fail('step machine 参数校验失败', { enCode: opts.enCode })
|
||
}
|
||
log.ok(`✓ step machine 校验通过 (3/3)`)
|
||
// step 0 基础信息 (P0 镜像 web Form.vue schemas)
|
||
|
||
// 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) {
|
||
// 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)
|
||
return ctx.fail(`创建失败 (code=${r.code}): ${r.msg}`, { enCode: opts.enCode, code: r.code })
|
||
}
|
||
|
||
// 拉 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})`)
|
||
// release 失败时重试 1 次 (500ms 间隔), 仍失败 process.exit(1)
|
||
// 后端: VisualdevController.java:593 publish() — state=1 + base_visual_release 行 saveOrUpdate (line 673)
|
||
// web 端: web/.../api/onlineDev/visualDev.ts:43 release(id) → POST /visualdev/Base/{id}/Actions/Release
|
||
const tryRelease = async (): Promise<void> => {
|
||
await loadVisualDev.release(newId) // unwrap() throws on non-200
|
||
}
|
||
let releaseOk = false
|
||
try {
|
||
await tryRelease()
|
||
log.ok('发布成功 (state=1)')
|
||
releaseOk = true
|
||
} catch (e1: any) {
|
||
log.warn(`首次发布失败 (${e1.message}), 500ms 后重试...`)
|
||
await new Promise((r) => setTimeout(r, 500))
|
||
try {
|
||
await tryRelease()
|
||
log.ok('发布成功 (state=1, 重试)')
|
||
releaseOk = true
|
||
} catch (e2: any) {
|
||
log.error(`✗ 发布失败 (重试仍失败): ${e2.message}`)
|
||
log.error(`手动发布: curl -X POST '${c.baseUrl}/visualdev/Base/${newId}/Actions/Release' -H 'Authorization: Bearer <token>'`)
|
||
if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType, releaseError: e2.message })
|
||
return ctx.fail(`发布失败 (重试仍失败): ${e2.message}`, { id: newId, enCode: opts.enCode })
|
||
}
|
||
}
|
||
if (!releaseOk) return ctx.fail('发布失败 (state 未切到 1)', { id: newId, enCode: opts.enCode })
|
||
|
||
// 透明化物理表状态
|
||
try {
|
||
const { initWebapi: initWebapiDM, loadDataModel } = await import('../../webapi/dataModel.ts')
|
||
await initWebapiDM(c)
|
||
const dmList = (await loadDataModel.getDataModelList({ dbLinkId })) as { data?: { list?: { table: string; tableFieldList?: unknown[] }[] } }
|
||
const tbl = dmList?.data?.list?.find((t) => t.table === opts.enCode)
|
||
if (tbl) {
|
||
const colCount = Array.isArray(tbl.tableFieldList) ? tbl.tableFieldList.length : 0
|
||
log.info(` ℹ 物理表: ${opts.enCode} (${colCount} 列)`)
|
||
} else {
|
||
log.warn(` ⚠ 物理表 ${opts.enCode} 未在数据建模列表中找到`)
|
||
}
|
||
} catch {
|
||
log.debug(' (物理表状态查询跳过)')
|
||
}
|
||
} else if (opts.autoRelease && type === 4) {
|
||
log.warn('type=4 视图自动跳过 release (会 400)')
|
||
}
|
||
|
||
// (盲点 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})`)
|
||
// 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 可绕过)
|
||
// 修复 (app 实战): 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 模式不抛, 继续
|
||
}
|
||
}
|
||
|
||
// v2.0+: 保存结构化日志 + 输出
|
||
try {
|
||
const cmdLog: CommandLog = {
|
||
command: 'form create',
|
||
timestamp: new Date().toISOString(),
|
||
duration_ms: Date.now() - startTime,
|
||
result: 'success',
|
||
appCode: c.appCode,
|
||
summary: {
|
||
target: opts.enCode || '(unknown)',
|
||
id: newId,
|
||
silent_fixes: fixLog.silent.length,
|
||
assertive_fixes: fixLog.assertive.length,
|
||
suggestions: fixLog.suggestions.length,
|
||
},
|
||
silent_fixes: fixLog.silent,
|
||
assertive_fixes: fixLog.assertive,
|
||
suggestions: fixLog.suggestions,
|
||
}
|
||
saveCommandLog(c.appCode, cmdLog)
|
||
|
||
if (opts.verbose) {
|
||
// --verbose: 输出完整过程日志 + 摘要
|
||
log.flush()
|
||
log.info('')
|
||
log.info(formatOneLineSummary(cmdLog))
|
||
log.info(` 详情: dacli log last`)
|
||
} else {
|
||
// 默认精简: 丢弃过程日志, 只输出摘要
|
||
log.discard()
|
||
// 临时切到非 quiet 以输出摘要 (process.stdout 直接写, 不走 log 缓冲)
|
||
const summary = formatOneLineSummary(cmdLog)
|
||
process.stdout.write(`\n${summary}\n`)
|
||
process.stdout.write(` 详情: dacli log last\n`)
|
||
}
|
||
} catch { /* 日志保存失败不阻塞 */ }
|
||
} catch (e) {
|
||
return ctx.fail(`form create 失败: ${(e as Error).message?.slice(0, 200)}`, { enCode: opts.enCode })
|
||
}
|
||
})
|
||
})
|
||
|
||
installHelpHookWithPatterns(cmd, 'form create', {
|
||
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
|
||
}
|