- sswflow M1 Task 10: 当 SSW /ssw/ai/infer-fields LLM token 过期时, 跳过 AI 推理, 用本地默认 schema (全部 input 控件) - 用户后续用 dacli form update --fields=<full JSON> 补全控件类型 - 适用场景: 11 张 sswflow 表已绑定, 后端 mvn 编译阻塞, 需先固化 form 基础结构 - 20/20 vitest PASS (含 form_table_ssw_fail + role_authorize + form_update_read_only) - 注: 用 --skip-X 而非 --no-X (commander 12.1.0 不支持 --no-X 反相) Co-Authored-By: Claude <[email protected]>
1994 lines
115 KiB
TypeScript
1994 lines
115 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, renderAiFieldResult } from './_ai.ts'
|
||
import { initBuildFormData, buildFormData as webBuildFormData, isBuildFormDataLoaded } from './_buildformdata.ts'
|
||
import { applySmartProps, loadSmartPropsContext, applyHeuristicRequired, applyHeuristicRelationForm } from './_smart_props.ts'
|
||
import { completeRelationFormFields } from './_relationform_completeness.ts' // v2.4+ (BS-新132-变种): relationForm 4 字段 silent_fix
|
||
import { closeFormContract, buildGetFormAdapter, FormSchemaInvalidError, FORM_SCHEMA_INVALID_TAG } from './_schema_normalize.ts' // T3: 创建闭环 (POST/PUT + GET 回读 + release gate, webapi hardening)
|
||
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 { cleanupResidueForms } from './_cleanup.ts' // Bug 1 (R3): form create 失败时清残留 state=0
|
||
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
|
||
import { loadAppContext } from '../app/context.ts'
|
||
import { loadToken, DEFAULT_ACCOUNT, DEFAULT_PASSWORD } from '../../core/config.ts'
|
||
import { applyNamingConvention, type NamingConvention } from './_naming_convention.ts'
|
||
import { loadComponentMap } from '../../schema/FieldBuilder.ts' // P0-9: 权威 jnpfKey→tag 单一来源 (镜像 web componentMap.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,
|
||
remindEnCodeStrip, remindFullNameSoften, remindFormRepairSkipped,
|
||
remindSmartPropsPostProcessFailed, remindHeuristicRelFormSkipped,
|
||
remindPhysicalTableMissing, remindAiTokenRelogin,
|
||
} from '../_post_reminders.ts' // v2.4+ (2026-07-21): 14 高频 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
|
||
/** v2.4+ (BS-新411, tdd2 2026-07-25): 强制 --enCode 显式传, 防 --ai 自由命名漂移 */
|
||
enCodeStrict?: 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
|
||
/** Bug 1 (R3): create 失败时自动清残留 state=0 行. 默认 ON, --no-cleanup-on-fail 转 false */
|
||
cleanupOnFail?: boolean
|
||
/** P5 (BS-新149 衍生, 2026-07-29): 跳过 pre-check (含 enCode/dbLinkId/table 唯一性校验) */
|
||
force?: boolean
|
||
/**
|
||
* 关闭 relationForm 自动注入
|
||
* 默认 ON (启发式注入), --no-relation-form-auto 强制关闭
|
||
* 适用: 字段名含 _code 后缀 (业务编码, 不是关系字段) 时避免误判
|
||
*/
|
||
relationFormAuto?: boolean
|
||
json?: boolean
|
||
verbose?: boolean
|
||
/** 5.10.1 AI 快速建表 — 自然语言描述, 平台 LLM 生成 enCode/fullName/fields */
|
||
ai?: string
|
||
/** columnList 命名规范: auto | snake | f_prefix (默认 snake). 见 --column-naming 选项 (create.ts:315) */
|
||
columnNaming?: string
|
||
/** Tier 1.2 (2026-07-24): enCode 已存在时返回现有 form id (跳过创建). 防 AI agent 反复跑场景 (BS-新131) */
|
||
reuseIfExists?: boolean
|
||
/** internal: AI/table 分支构建好的 formData 缓存, 供后续 smartProps/持久化复用 (非 CLI 选项) */
|
||
__aiBuildFormData?: { formData: string }
|
||
/** 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 不建表单 */
|
||
aiField?: string
|
||
// 历史 --ai-json 已删 (跟 --ai 路径重复, 避免两条相似代码路径漂移)
|
||
/** 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'
|
||
}
|
||
|
||
/**
|
||
* Re-apply smart component props after the final form-data producer.
|
||
*
|
||
* `--ai` and `--table` are independent producers: when both are supplied,
|
||
* the table branch rebuilds `__aiBuildFormData` after the AI branch has run
|
||
* smartProps. Keep the post-processing at the final boundary so dictionary,
|
||
* numeric-range, validation and relation props cannot be discarded.
|
||
*/
|
||
export function shouldRunFinalSmartProps(opts: CreateOpts): boolean {
|
||
if (!opts) return false
|
||
if (!opts.ai && !opts.table) return false
|
||
return Boolean((opts as any).__aiBuildFormData)
|
||
}
|
||
|
||
/**
|
||
* Tier 1.2 (2026-07-24): --reuse-if-exists 命中的判定函数 (纯函数, 单元测试覆盖)
|
||
* 输入 enCode + web 端 form list (从 getVisualDevList 返回), 返回匹配项 (exact enCode match) 或 null
|
||
*/
|
||
export function findExistingForm(
|
||
enCode: string,
|
||
list: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }>,
|
||
): { id: string; enCode: string; fullName?: string; state?: number } | null {
|
||
if (!enCode || !list || list.length === 0) return null
|
||
// exact enCode match only (避免 fuzzy 误匹配同前缀 form)
|
||
const hit = list.find((f) => f.enCode === enCode)
|
||
if (!hit || !hit.id) return null
|
||
return { id: hit.id, enCode: hit.enCode!, fullName: hit.fullName, state: hit.state }
|
||
}
|
||
|
||
async function applyFinalSmartProps(
|
||
c: JnpfClient,
|
||
buildResult: { formData: string },
|
||
ctx: { addSuggestion: (entry: any) => void },
|
||
): Promise<void> {
|
||
try {
|
||
const smartCtx = await loadSmartPropsContext(c)
|
||
const parsed = JSON.parse(buildResult.formData)
|
||
const { formData: enhancedFormData, applied, source } = await applySmartProps(
|
||
parsed,
|
||
smartCtx,
|
||
{ verbose: true },
|
||
)
|
||
let finalFormData = enhancedFormData
|
||
|
||
if (source === 'none') {
|
||
const heuristicApplied = applyHeuristicRequired(enhancedFormData)
|
||
if (heuristicApplied.applied > 0) {
|
||
log.warn(` ↳ final smartProps AI 失败 + 启发式 required 兜底: ${heuristicApplied.applied} 字段`)
|
||
ctx.addSuggestion(remindSmartPropsAIFallback(heuristicApplied.applied))
|
||
}
|
||
const relationFormApplied = applyHeuristicRelationForm(enhancedFormData, smartCtx)
|
||
if (relationFormApplied.skipped > 0) {
|
||
log.warn(` ↳ final applyHeuristicRelationForm: ${relationFormApplied.skipped} 字段无候选`)
|
||
ctx.addSuggestion(remindHeuristicRelFormSkipped(relationFormApplied.skipped))
|
||
}
|
||
}
|
||
|
||
// BS-新132-变种 (tdd2 2026-07-25): relationForm 4 字段 silent_fix
|
||
// 即使 AI 生成成功, 也可能缺 modelId/propsValue/relationField/showField
|
||
// 自动补全避免 TC-C FAIL
|
||
try {
|
||
const rfFixed = await completeRelationFormFields(finalFormData, c)
|
||
if (rfFixed.fixed > 0) {
|
||
log.info(` ↳ BS-新132-变种: relationForm 4 字段 silent_fix ${rfFixed.fixed}/${rfFixed.scanned} 字段`)
|
||
ctx.addSuggestion({
|
||
id: 'BS-新132-变种',
|
||
level: 'silent',
|
||
field: 'relationForm',
|
||
summary: `4 字段补全 (${rfFixed.fixed}/${rfFixed.scanned})`,
|
||
})
|
||
}
|
||
} catch (e) {
|
||
log.warn(`BS-新132-变种 silent_fix 跳过: ${(e as Error).message?.slice(0, 100)}`)
|
||
}
|
||
|
||
buildResult.formData = JSON.stringify(finalFormData)
|
||
if (applied.length > 0) {
|
||
log.info(` ↳ final smartProps 应用 ${applied.length} 项 (${source})`)
|
||
}
|
||
} catch (e) {
|
||
log.warn(`final smartProps 后处理跳过 (${(e as Error).message?.slice(0, 100)})`)
|
||
ctx.addSuggestion(remindSmartPropsPostProcessFailed((e as Error).message?.slice(0, 100) || 'unknown'))
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* app-P1 完整版 + 增强: form category 自动派生 + AI 智能判断 + 缓存复用
|
||
* 整合进 webapi 镜像, 不再硬编码 BUSINESS_TYPE_ID
|
||
* 旧版: 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<{ 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 "<描述>" 一条命令: v0.22+ SSW /api/ssw/ai/build-form + 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 数组 (DEPRECATED v0.12+ — 运行时 reject, 改用 --ai "<描述>" 或 --table <name>)')
|
||
.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). 与 --ai 同时传时, --table 优先级更高 (基于 DM 字段生成, 不浪费 LLM token, 2026-07-29)')
|
||
.option('--ai <desc>', 'v0.22+ AI 快速建表 — 自然语言描述, SSW /api/ssw/ai/build-form 生成 enCode/fullName/fields (boot/ssw-common prompt 我们写, v0.12+ 默认 autoRelease=true). 与 --table 同时传时, --table 优先级更高')
|
||
.option('--ai-field <desc>', '白皮书 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 只输出建议不建表单')
|
||
// v2.4+ (BS-新411, tdd2 2026-07-25): --enCode-strict 强制要求 --enCode 显式传, 防止 --ai 自由命名漂移
|
||
.option('--enCode-strict', '强制要求 --enCode 显式传 (BS-新411, 防 --ai 自由命名漂移, ssw-loop §9 集成场景)', false)
|
||
// dos 26 P0 修复: smartProps 自动选配组件属性 (字典/min-max/relationForm/regList)
|
||
.option('--no-smart-props', '关闭 --ai smartProps 自动选配 (默认 ON, AI 选填组件属性)')
|
||
.option('--preview', 'P0-6: AI 生成后先渲染字段表格供 review, 确认再提交 (TTY 交互 y/N; 非 TTY 仅预览不创建)', false)
|
||
.option('--optimize', 'P0-2: 先调 LLM 优化 --ai 的模糊描述, 再走 build-form (一步走: optimize→build→preview, 配 --preview 闭环)', false)
|
||
.option('--yes', '--preview 时跳过交互确认直接创建 (自动化场景)', false)
|
||
.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('--reuse-if-exists', 'enCode 已存在时返回现有 form id (跳过创建), AI agent 反复跑场景', false)
|
||
.option('--force', '跳过 pre-check (含 enCode/dbLinkId/table 唯一性校验). 用于物理删残留后 enCode 实际可用但 list 缓存仍在的场景 (BS-新149 衍生, 2026-07-29)', false)
|
||
// Bug 1 (tdd6 R3 2026-07-29 + BS-新149 衍生): create 失败时自动清 state=0 残留
|
||
// - 默认 ON (--no-cleanup-on-fail 关闭)
|
||
// - 防御性: 仅清 enCode 精确匹配 + state=0 的残留, 单次最多 5 条
|
||
.option('--no-cleanup-on-fail', '关闭 create 失败时自动清残留 state=0 行 (默认 ON)', false)
|
||
.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 (LLM prompt 在 ssw-common/.../AIRepairServiceImpl.BUILD_FORM_PROMPT, 我们可改)
|
||
.option('--column-naming <style>', 'columnList 命名规范: auto | snake | f_prefix (默认 snake, JNPF 标准)', 'snake')
|
||
// sswflow M1 Task 10 (2026-08-01): 跳过 SSW AI infer-fields (LLM token expired 时 fallback)
|
||
// 后果: 所有字段 jnpfKey='input', 无 smartProps, BS-新117 限制部分命中
|
||
// 适用: form create --table + --skip-infer-fields (手填后续 form update --fields 补全)
|
||
// 注: 用 --skip-X 而非 --no-X (commander 12.1.0 不支持 --no-X 反相)
|
||
.option('--skip-infer-fields', '跳过 SSW /ssw/ai/infer-fields (LLM token 过期时 fallback 路径, sswflow M1 Task 10)', false)
|
||
.action(async (opts: CreateOpts) => {
|
||
log.setQuiet(!opts.verbose)
|
||
const startTime = Date.now()
|
||
// v2.4+: pre-wrapCommand 收集的 fixes (enCode/fullName strip 等). wrapCommand.fixes 接收此数组
|
||
const preWrapFixes: import('../../core/logfile.ts').FixEntry[] = []
|
||
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
|
||
// autoStripEnCode 含 `-`/`_` 自动 strip + WARN (BS-新56 强制 camelCase)
|
||
// silent S-X1 已落 L3, stdout 3 行 user-facing (transformation + 表名同步 + 后续命令参考)
|
||
// 必须在 ai 之前: options.ai 会基于修正后的 enCode 走 web buildFormData
|
||
if (opts.enCode) {
|
||
const _encStrip = autoStripEnCode(opts.enCode)
|
||
if (_encStrip.wasStriped) {
|
||
log.warn(`⚠ enCode 转换: ${_encStrip.original} → ${_encStrip.value} (JNPF 全平台强制 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
|
||
// v2.4+ L3: 冗余 assertive 提示 (silent S-X1 也会自动落), AI 跑 log last --level=fix 能查到 enCode 实际值
|
||
preWrapFixes.push(remindEnCodeStrip(_encStrip.original, _encStrip.value))
|
||
}
|
||
}
|
||
|
||
// fullName 含 space/parens 自动 soften (BS-新52, 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
|
||
// v2.4+ L3: 冗余 assertive 提示 (silent S-X2 已落)
|
||
preWrapFixes.push(remindFullNameSoften(_fnStrip.original, _fnStrip.value))
|
||
}
|
||
}
|
||
|
||
const c = await JnpfClient.fromToken()
|
||
// HIGH2 (eventhub blocker 阶段 6 修复 2): --table 与 --tables 互斥 guard
|
||
// 根因: --table 路径自动构造单主表 + formData.tableName 用 opts.table,
|
||
// --tables 路径用户显式传 table 列表 + 走 stripAppPrefix.
|
||
// 两个 option 语义冲突 (一个由 dacli 推导, 一个由用户指定), 早期 fail 避免歧义.
|
||
// 实现: 在 wrapCommand 内 + 任何 API 调用前 fail. 不发 dm/SSW/create.
|
||
if (opts.table && opts.tables) {
|
||
await wrapCommand({
|
||
command: 'form create',
|
||
appCode: c.appCode,
|
||
startTime,
|
||
verbose: opts.verbose,
|
||
json: opts.json,
|
||
fixes: preWrapFixes,
|
||
}, async (ctx) => {
|
||
log.error('✗ --table 与 --tables 互斥, 二选一:')
|
||
log.error(' --table <name> 自动读 dm 字段, 绑现有物理表 (推荐)')
|
||
log.error(' --tables <json> 显式声明 tables JSON 数组 (主子表/复杂场景)')
|
||
return ctx.fail('--table 与 --tables 互斥 (eventhub blocker HIGH2)', { enCode: opts.enCode, table: opts.table })
|
||
})
|
||
return
|
||
}
|
||
await wrapCommand({
|
||
command: 'form create',
|
||
appCode: c.appCode,
|
||
startTime,
|
||
verbose: opts.verbose,
|
||
json: opts.json,
|
||
fixes: preWrapFixes,
|
||
}, async (ctx) => {
|
||
// LOW: --table 路径上下文 (dmFields + physicalName), action-local 变量代替 (opts as any) stash.
|
||
// 作用域: --table 块写, tables 推导 + formData.tableName 兜底读.
|
||
// 不放在 (opts as any) 上避免 'any stash' 漏洞 (reviewer 反馈).
|
||
type DmFieldRowLocal = { field: string; fieldName?: string; dataType?: string; allowNull?: number | string; primaryKey?: number }
|
||
let tableDmFields: DmFieldRowLocal[] | undefined
|
||
let tablePhysicalName: string | undefined
|
||
// LOW: __tableAiFieldComponents 也升为 action-local (B-15 columnList 过滤用)
|
||
let tableAiFieldComponents: Map<string, string> | undefined
|
||
try {
|
||
// 5.10.2: --ai-field 只问 AI, 不建表单
|
||
// 设计 §3.6: --json 与人类格式互斥, 避免 stdout 混入说明文本导致 JSON.parse 失败
|
||
if (opts.aiField) {
|
||
const data = await callAiForm(opts.aiField)
|
||
renderAiFieldResult(data, { json: opts.json }, { printJson, printHuman: printAiFormResult })
|
||
return
|
||
}
|
||
|
||
// Tier 1.2 (2026-07-24): --reuse-if-exists 幂等支持 (v2.4+ 走 _reusable_create 通用 wrapper)
|
||
// ⚠️ 必须放在 --ai 分支之前, 否则 --ai 会先拦截 SSW LLM 调用浪费 13-15s
|
||
// 用户传 --enCode 时短路: enCode 已存在 → 直接返回现有 id, 跳过 --ai 调用
|
||
if (opts.reuseIfExists && opts.enCode) {
|
||
const { reusableCreate, reuseSuccessPayload } = await import('../_reusable_create.ts')
|
||
const result = await reusableCreate({
|
||
cmdName: 'form create',
|
||
enCode: opts.enCode,
|
||
reuseIfExists: opts.reuseIfExists,
|
||
findExisting: async (en) => {
|
||
await initWebapi(c)
|
||
const listResp = (await loadVisualDev.getVisualDevList({
|
||
currentPage: 1,
|
||
pageSize: 500,
|
||
})) as { list?: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }> }
|
||
return findExistingForm(en, listResp.list || [])
|
||
},
|
||
runCreate: async () => {
|
||
// 占位: 实际 --ai 流程在 line 455+ 继续
|
||
},
|
||
})
|
||
if (result.reused) {
|
||
const stateLabel = result.existing.state === 1 ? '已发布' : result.existing.state === 0 ? '未发布' : `state=${result.existing.state}`
|
||
log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${result.existing.id}, ${stateLabel})`)
|
||
log.info(` 跳过创建. 需要修改字段请用 dacli form update --fields=<json>`)
|
||
return ctx.success(reuseSuccessPayload(result.existing, 'reuse-if-exists'))
|
||
}
|
||
// enCode 不存在 → log.info 让用户知道, 然后继续正常 --ai 流程
|
||
log.info(`--reuse-if-exists: ${opts.enCode} 不存在, 继续 --ai 创建`)
|
||
}
|
||
|
||
// 5.10.1: --ai 自动建表单
|
||
if (opts.ai) {
|
||
// v2.4+ (BS-新411, tdd2 2026-07-25): --enCode-strict 强制要求 --enCode 显式传
|
||
// 防 --ai 自由命名 enCode 漂移 (e.g. tdd2order → tdd2orderForm)
|
||
// ssw-loop §9 enCode 清单场景必须开启
|
||
if (opts.enCodeStrict && !opts.enCode) {
|
||
log.error(`BS-新411: --enCode-strict 模式下 --enCode 必传`)
|
||
log.error(` --ai 自由生成的 enCode (含 'Form' 后缀等) 与主代理已校验 enCode 清单不一致`)
|
||
log.error(` 推荐: dacli form create --enCode=<来自 §9 清单> --ai="..."`)
|
||
return ctx.fail(`BS-新411: --enCode-strict 需要显式 --enCode`, { ai: 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 过期, 自动重登...')
|
||
// P4 安全: spawnSync 数组式 (无 shell → 无命令注入); 凭据走 config (env 可覆盖), 不内联明文
|
||
const { spawnSync } = await import('node:child_process')
|
||
const cliEntry = process.argv[1] || 'src/cli.ts'
|
||
const relogin = spawnSync('npx', [
|
||
'tsx', cliEntry, 'app', 'login',
|
||
'--account', DEFAULT_ACCOUNT,
|
||
'--password', DEFAULT_PASSWORD,
|
||
'--appCode', c.appCode,
|
||
], { stdio: 'pipe', timeout: 15000 })
|
||
if (relogin.status !== 0) {
|
||
log.warn(` 自动重登失败 (exit=${relogin.status}), 继续 (AI 调用可能仍失败)`)
|
||
}
|
||
log.info('✓ 重登完成, 继续 AI 调用')
|
||
// v2.4+ L3: AI token 过期发生 (v0.22+ SSW 端点 TTL 一般 30 分钟, 让 AI 跑 log last 能查)
|
||
ctx.addSuggestion(remindAiTokenRelogin())
|
||
}
|
||
} catch { /* 预检失败不阻塞 */ }
|
||
|
||
// P0-2 (v0.23+): --optimize 先调 LLM 改写模糊描述, 再走 build-form。
|
||
// 复用 SSW OpenAI 代理 (同 form optimize 命令, 提示词一致)。
|
||
// 失败回退: 静默用原描述, 不阻塞 (留 print log 提示)。
|
||
if ((opts as any).optimize && opts.ai) {
|
||
try {
|
||
const { chatViaProxy } = await import('../../core/llm.ts')
|
||
const { OPTIMIZE_PROMPT } = await import('./optimize.ts')
|
||
const c2 = await JnpfClient.fromToken()
|
||
const opt = await chatViaProxy(c2, {
|
||
system: OPTIMIZE_PROMPT,
|
||
user: `应用: ${c2.appCode}\n原始需求: ${opts.ai}`,
|
||
maxTokens: 1200,
|
||
})
|
||
log.info(` ↳ --optimize: 原始 ${opts.ai.length} 字符 → 优化后 ${opt.content.length} 字符 (${opt.ms}ms)`)
|
||
opts.ai = opt.content
|
||
} catch (e) {
|
||
log.warn(`--optimize 失败, 用原描述继续: ${(e as Error).message?.slice(0, 100)}`)
|
||
}
|
||
}
|
||
|
||
// 用户反馈 (2026-07-27): "form --ai 用输入框兜底可以接受, 但不能前两轮上来就用"
|
||
// → LLM 是主路径; 拒绝过短/过模糊的输入走 LLM (浪费 5-15s token, 必返坏结构)
|
||
// → 短输入直接走 web buildFormData 默认空 schema (需 user 传 --enCode/--fullName)
|
||
// → 同 P1-5 修订: lint 失败不重试 LLM, 走兜底 (本轮实证两次 LLM 产出几乎一样)
|
||
const MIN_AI_CHARS = 10
|
||
let __shortCircuit = false
|
||
if (opts.ai.trim().length < MIN_AI_CHARS) {
|
||
log.warn(`--ai 描述过短 (${opts.ai.trim().length} 字符, 最低 ${MIN_AI_CHARS}), 跳过 LLM 走默认 schema`)
|
||
log.warn(` 提示: 写清楚业务 + 关键字段 (含类型/字典候选项), 例: "员工请假:姓名(单行)、请假类型(下拉:事假/病假/婚假)、开始日期、请假天数(数字)、原因(多行)"`)
|
||
log.warn(` 或先用 'dacli form optimize "..."' 改写 (P0-2), 或直接传 --fields/--table 走 web 端`)
|
||
if (!opts.enCode || !opts.fullName) {
|
||
return ctx.fail('--ai 过短且未传 --enCode/--fullName, 无法走默认 schema (请补充描述或显式传名)', { ai: opts.ai })
|
||
}
|
||
__shortCircuit = true
|
||
}
|
||
|
||
let data: any
|
||
if (__shortCircuit) {
|
||
// 模拟 P1-7 Login expired 路径: 构造同形 data → 下游走 web buildFormData 默认空 schema
|
||
// JNPF step machine:
|
||
// - formData.fields.length ≥ 1 强制 (VS401, web 端新建空 form 也自动注入 f_id 主键)
|
||
// - webType≠1 时 columnList 至少 1 列 (用户没真给描述时无法推 list)
|
||
// → 强制 webType=1 (仅表单, 免 columnList 校验) + 注入 f_id 占位字段满足 VS401
|
||
log.warn(` ↳ 短描述自动改 webType=1 (仅表单, 免 columnList 校验) + 注入 f_id 占位`)
|
||
opts.webType = '1'
|
||
data = {
|
||
enCode: opts.enCode,
|
||
fullName: opts.fullName,
|
||
aiModelList: [{
|
||
tableTitle: opts.fullName,
|
||
isMain: true,
|
||
fields: [{
|
||
fieldName: 'f_basic_name',
|
||
fieldComponent: 'input',
|
||
__list__: true,
|
||
__form__: true,
|
||
__query__: false,
|
||
fullName: '名称',
|
||
}],
|
||
}],
|
||
_aiChain: ['--ai 过短: 走默认 schema (f_basic_name 占位 + webType=1)'],
|
||
}
|
||
} else {
|
||
log.info(`--ai "${opts.ai}" — 调用平台 AI 生成表单 (白皮书 5.10.1)`)
|
||
data = await callAiForm(opts.ai)
|
||
}
|
||
// v2.4+ (BS-新131-加强, tdd2 2026-07-25): 检测 --ai 生成 enCode 与 --enCode 不一致
|
||
// 例: --enCode=tdd2order, --ai 改成 tdd2orderForm
|
||
// 默认采纳 --enCode (避免漂移).
|
||
// v2.4+ 噪音治理 (BS-新150): 默认静默 (走 ctx.addSuggestion, AI 通过 log last --detail 查);
|
||
// 只有 --verbose 才打 log.warn 提示用户, 防 console.warn 绕过 quiet mode 一直输出.
|
||
if (opts.enCode && data.enCode && opts.enCode !== data.enCode) {
|
||
if (opts.verbose) {
|
||
log.warn(`BS-新131-加强: --ai 生成的 enCode='${data.enCode}' 与 --enCode='${opts.enCode}' 不一致`)
|
||
log.warn(` 采纳 --enCode='${opts.enCode}', 覆盖 AI 生成`)
|
||
}
|
||
data.enCode = opts.enCode
|
||
ctx.addSuggestion({
|
||
id: 'BS-新131-加强',
|
||
level: 'silent',
|
||
field: 'enCode',
|
||
summary: `AI='${data.enCode}' → user='${opts.enCode}'`,
|
||
})
|
||
}
|
||
// AI Login expired (P1-7) → fallback 走 web buildFormData 默认 schema (user 传 enCode/fullName 时)
|
||
if (data.loginExpired) {
|
||
if (!opts.enCode || !opts.fullName) {
|
||
log.error('⚠ AI 端点 Login expired (v0.22+ 仅 SSW 路径), 且未传 --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 (v0.22+ 仅 SSW 路径), 且未传 --enCode/--fullName, 无法自动建表单', { enCode: opts.enCode })
|
||
}
|
||
// user 提供了 --enCode + --fullName → 走 web buildFormData 默认空 schema
|
||
log.warn(`⚠ P1-7: AI 端点 Login expired (v0.22+ 仅 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
|
||
// P1-7 强化 (2026-07-31): 强制 webType=1 + 注入 f_basic_name 占位字段
|
||
// 让 step machine VS401 formData.fields.length ≥ 1 校验通过 (用户后续用 form update --fields 补全)
|
||
// 避免 webType≠1 时 columnList 校验阻塞 (用户后续 form update --fields 时覆盖)
|
||
log.warn(` ↳ P1-7 强化: 强制 webType=1 (仅表单, 免 columnList 校验) + 注入 f_basic_name 占位`)
|
||
opts.webType = '1'
|
||
data.aiModelList = [{
|
||
tableTitle: opts.fullName,
|
||
isMain: true,
|
||
fields: [{
|
||
fieldName: 'f_basic_name',
|
||
fieldComponent: 'input',
|
||
__list__: true,
|
||
__form__: true,
|
||
__query__: false,
|
||
fullName: '名称',
|
||
}],
|
||
}] // 仅 1 个占位字段, 让步 machine 通过; 后续 form update --fields 补全
|
||
} else if (!data.enCode || !data.fullName) {
|
||
// 显式打印 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
|
||
// 检测 AI 建议 enCode 与用户输入不一致 (loginExpired fallback 时 data.enCode=user enCode, 不触发)
|
||
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 || []
|
||
// v0.22+ (2026-07-25 BS-新131~133, tdd3 P1-5 闭环): SSW /build-form 路径下 autoDetect 跳过
|
||
// 原因: SSW prompt 显式禁用 select 替代 relationForm (含 _id 后缀字段), jnpfKey 已正确
|
||
// autoDetect 是历史 band-aid (AI 用 select 替代 relationForm), v0.22+ SSW 路径不需要
|
||
// 关闭: --no-relation-form-auto
|
||
if ((opts as any).relationFormAuto === false) {
|
||
log.info(` ↳ --no-relation-form-auto, 跳过 relationForm 自动注入`)
|
||
} else {
|
||
// 默认: SSW 路径下不再 autoDetect, 仅 --table 路径才需要 (因为 --table 不走 LLM, 字段需手注)
|
||
log.dim(` ↳ SSW 路径下 autoDetect 跳过`)
|
||
}
|
||
|
||
// 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 修复: --ai 默认 smartProps 选配组件属性 (字段名→字典/min-max/relationForm/regList)
|
||
// 合规扩展层: 不改 jnpf/JNPF 后端, 在 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 })
|
||
// source='none' 时跑启发式 (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)`)
|
||
// v2.4+ L3: AI + 启发式都没匹配 modelId, 提示 FK 字段可能需要手补
|
||
ctx.addSuggestion(remindHeuristicRelFormSkipped(relationFormApplied.skipped))
|
||
}
|
||
}
|
||
// 写回 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)}), 跳过`)
|
||
// v2.4+ L3: smartProps 后处理异常, form 字段属性可能不全
|
||
ctx.addSuggestion(remindSmartPropsPostProcessFailed((e as Error).message?.slice(0, 80) || 'unknown'))
|
||
}
|
||
} else {
|
||
log.info(` ↳ --no-smart-props, 跳过 AI 组件属性选配`)
|
||
}
|
||
|
||
// in-process FormRepair (type_drift + column_drift), 镜像 ssw FormRepairServiceImpl, 0 网络
|
||
// 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)})`)
|
||
// v2.4+ L3 (历史): form 字段 jnpfKey 可能错 (历史 JNPF 后端 AI bug); v0.22+ SSW 路径下已禁, 此警告极少触发
|
||
ctx.addSuggestion(remindFormRepairSkipped((e as Error).message?.slice(0, 80) || 'unknown'))
|
||
}
|
||
// --ai 走 webapi 透传, type/webType 默认值已在 commander declaration (type='1' / webType='2')
|
||
log.info(` ↳ --ai 走 SSW /api/ssw/ai/build-form (v0.22+ P1-5 闭环) + web buildFormData, 不再 dacli 自写 LLM prompt`)
|
||
// --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)
|
||
// HIGH3: dm fields API 返 JnpfResp<DmFieldsResp>, T = data payload (数组或 {list: []})
|
||
type DmFieldRow = { field: string; fieldName?: string; dataType?: string; allowNull?: number | string; primaryKey?: number }
|
||
type DmFieldsResp = DmFieldRow[] | { list?: DmFieldRow[] }
|
||
const rawDm = (await loadDataModel.getDataModelFieldList(dbLinkId, opts.table)) as DmFieldsResp | null
|
||
// dm fields API 可能返数组或 {list: [...]} 两种形状 (webapi 镜像形态)
|
||
const dmFields: DmFieldRow[] = Array.isArray(rawDm)
|
||
? rawDm
|
||
: (rawDm?.list || [])
|
||
if (!dmFields.length) {
|
||
log.error(`表 ${opts.table} 无字段, 无法自动生成表单`)
|
||
return ctx.fail(`表 ${opts.table} 无字段, 无法自动生成表单`, { table: opts.table })
|
||
}
|
||
// dm 字段 → aiModelList 格式 (跟 --ai 路径 SSW 返回的 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) => !SYS_COLS.includes(f.field))
|
||
const fieldDesc = userFields
|
||
.map((f) => `${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} 字段)`)
|
||
// HIGH3: postJson<T> 返 JnpfResp<T> (T = data payload), 不要嵌套 envelope.
|
||
// 类型用 AiInferFieldsData 表达 data payload (enCode/fullName/aiModelList)
|
||
type AiFieldItem = { fieldName: string; fieldComponent: string; __list__?: boolean; __form__?: boolean; __query__?: boolean }
|
||
type AiModelList = { fields?: AiFieldItem[] } & Record<string, unknown>
|
||
type AiInferFieldsData = { enCode?: string; fullName?: string; aiModelList?: AiModelList[] }
|
||
let sswResp
|
||
let aiModelList: AiModelList[]
|
||
// sswflow M1 Task 10 (2026-08-01): --no-infer-fields fallback (LLM token expired)
|
||
// 跳过 SSW AI 推理, 用本地默认 schema (全部 input 控件), 用户后续 form update --fields 补全
|
||
if ((opts as any).skipInferFields) {
|
||
log.warn('⚠ --skip-infer-fields: 跳过 SSW AI 推理, 使用本地默认 schema (全部 input 控件). 后续用 dacli form update --fields 补全.')
|
||
aiModelList = [{
|
||
fields: userFields.map((f) => ({
|
||
fieldName: f.field,
|
||
fieldComponent: 'input',
|
||
__list__: true,
|
||
__form__: true,
|
||
__query__: false,
|
||
fullName: f.fieldName || f.field,
|
||
})),
|
||
}] as AiModelList[]
|
||
sswResp = null
|
||
} else {
|
||
try {
|
||
sswResp = await tableClient.postJson<AiInferFieldsData>(
|
||
'/ssw/ai/infer-fields', { tableName: opts.table, fieldDesc })
|
||
} catch (e) {
|
||
const reason = (e as Error).message?.slice(0, 200) || String(e)
|
||
const diagnostic = '请检查 base_ai 配置与 SSW internal proxy /api/ssw/ai/openai-proxy 可达性'
|
||
log.error(`SSW AI 推理请求异常: ${reason}`)
|
||
log.error(` ${diagnostic}`)
|
||
return ctx.fail(`SSW AI 推理请求异常: ${reason}; ${diagnostic}`, { table: opts.table })
|
||
}
|
||
if (sswResp.code !== 200 || !sswResp.data?.aiModelList?.length) {
|
||
log.error(`SSW AI 推理失败 (code=${sswResp.code}): ${sswResp.msg || '返空'}`)
|
||
const diagnostic = '请检查 base_ai 是否启用并配置 provider, 以及 SSW internal proxy /api/ssw/ai/openai-proxy 可达性'
|
||
log.error(` ${diagnostic}`)
|
||
return ctx.fail(`SSW AI 推理失败 (code=${sswResp.code}): ${sswResp.msg || '返空'}; ${diagnostic}`, { table: opts.table })
|
||
}
|
||
aiModelList = 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 过滤用
|
||
tableAiFieldComponents = new Map<string, string>(
|
||
aiModelList[0].fields?.map((f) => [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`)
|
||
}
|
||
// 2026-07-22 BS-eventhub 阶段 6 修复: --table 路径保存 dmFields/tableName
|
||
// 供下游 (tables 推导 + formData.tableName 兜底) 构造主表 item, 镜像 web Form.vue:285-305
|
||
// 根因 (eventhub blocker): form create --table=eventaudit 走兜底 tables=[], 后端
|
||
// FlowFormDataUtil.java:831 查 typeId='1' 找主表 → 找不到 → 抛 MsgCode.COD001.
|
||
// 修复: --table 路径强制按 web item 构造单主表 + formData.tableName 用物理表名.
|
||
// LOW: 用 action-local 闭包变量 (上面 try 块外声明) 代替 (opts as any).__table* stash
|
||
tableDmFields = dmFields
|
||
tablePhysicalName = opts.table
|
||
}
|
||
|
||
// --table is the final form-data producer when combined with --ai.
|
||
// Re-run smartProps here so the table rebuild cannot erase dictionary,
|
||
// range, validation or relation metadata inferred by the AI pass.
|
||
if (shouldRunFinalSmartProps(opts)) {
|
||
await applyFinalSmartProps(c, (opts as any).__aiBuildFormData, ctx)
|
||
}
|
||
// 校验必填
|
||
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)
|
||
|
||
// 查 businessType 字典选最匹配 appCode 的分类 (opts.category 空时自动派生)
|
||
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)`)
|
||
}
|
||
}
|
||
|
||
// Tier 1.2 (--reuse-if-exists 命中检查已上移到 line 755, 紧跟必填校验之后)
|
||
// 原因: --ai 分支 line 423 会拦截, 必须放在它前面避免浪费 SSW LLM 调用
|
||
|
||
// 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 解析失败留给后续步骤报错 */
|
||
}
|
||
}
|
||
// P5 (2026-07-29): --force 跳过 pre-check
|
||
// 场景: 物理删残留后, 后端 list 仍报"已存在" (BS-新149 衍生, list API 不过滤 f_delete_mark=NULL)
|
||
if (opts.force) {
|
||
log.warn('--force: 跳过 pre-check (enCode/dbLinkId/table 唯一性校验), 风险自担')
|
||
} else {
|
||
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: --table 绑物理表优先 (跟 tables[].table 一致), 否则用 cleanTable (去 appCode 前缀)
|
||
// 根因 (eventhub blocker 2026-07-22): opts.enCode='eventAudit' (用户命名) ≠ 现有物理表 'eventaudit' (dm create 命名),
|
||
// 原代码强行把 formData.tableName 设为 opts.enCode, 与实际物理表不一致 → form 绑不上表
|
||
const appCode55 = (c as any).appCode as string
|
||
const cleanTable55 = appCode55 && opts.enCode.startsWith(`${appCode55}_`)
|
||
? opts.enCode.slice(appCode55.length + 1)
|
||
: opts.enCode
|
||
// --table 路径: 物理表名来自 dm, 跟 opts.enCode 无强关系, 直接用 opts.table
|
||
// --ai 路径: 没有 opts.table, 走原 cleanTable55 派生
|
||
formData.tableName = opts.table ? opts.table : cleanTable55
|
||
// 同步 formData.fields[*].__config__.tableName (form 渲染时控件关联的物理表)
|
||
// web buildFormData 默认 __config__.tableName='' (空) 或 enCode, dacli 必须强制覆盖
|
||
// --table 路径: 物理表已知, 全部字段统一绑 opts.table (不管 web 默认填啥)
|
||
// --ai 路径: 保留原行为, 仅当原值是 opts.enCode 才覆盖成 cleanTable55 (避免误改其它)
|
||
if (Array.isArray(formData.fields)) {
|
||
if (opts.table) {
|
||
// --table 路径: 强制所有字段 __config__.tableName = opts.table (绑物理表)
|
||
for (const fld of formData.fields as any[]) {
|
||
if (!fld || !fld.__config__) continue
|
||
fld.__config__.tableName = opts.table
|
||
}
|
||
} else {
|
||
// --ai 路径: 仅同步原值是 opts.enCode 的字段 (原行为)
|
||
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}
|
||
// MEDIUM2 (eventhub blocker 阶段 6 审查): 提取 typeId normalization helper.
|
||
// 后端 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).
|
||
// 历史: 代码里有 3 处重复 (L1087, L1191, L1304), 现合并为唯一调用 + helper 函数.
|
||
function normalizeTableTypeIds(tables: unknown): void {
|
||
if (!Array.isArray(tables) || tables.length === 0) return
|
||
tables.forEach((t: any, idx: number) => {
|
||
if (t && typeof t === 'object' && !t.typeId) {
|
||
t.typeId = idx === 0 ? '1' : '0'
|
||
}
|
||
})
|
||
}
|
||
// 排除系统字段 (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
|
||
// P0-9 (2026-07-27): 消除漂移 — tag 映射改为消费权威 component-map.json
|
||
// (镜像 web src/components/FormGenerator/src/helper/componentMap.ts, 60+ 项),
|
||
// 不再内联硬编码副本。修复旧 14 项内联副本 2 处漂移 + 1 幽灵项:
|
||
// ① textarea: JnpfInputTextarea → JnpfTextarea (旧 tag 在 web 根本不存在)
|
||
// ② upload: 幽灵项 (匹配到导入按钮 value:'upload', 非表单控件; 真控件是 uploadFile/uploadImg)
|
||
// ③ 覆盖: 14 → 60 (editor/relationForm/table/signature/... 全覆盖)
|
||
// 单一来源 + 29 组件白名单见 dacli/config/components-whitelist.yaml + docs/components.md
|
||
const JNPF_TAG_MAP: Record<string, string> = loadComponentMap()
|
||
// tagIcon 映射 (权威值来自 web componentMap.ts 的 tagIcon 字段)。
|
||
// 修复漂移: inputNumber 'generator-inputNumber' → 'generator-number' (旧值 web 不存在)。
|
||
// 覆盖 29 组件白名单 (23 handled + 6 pass-through) 的 tagIcon。
|
||
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-number',
|
||
select: 'icon-ym icon-ym-generator-select',
|
||
datePicker: 'icon-ym icon-ym-generator-date',
|
||
timePicker: 'icon-ym icon-ym-generator-time',
|
||
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',
|
||
slider: 'icon-ym icon-ym-generator-slider',
|
||
rate: 'icon-ym icon-ym-generator-rate',
|
||
colorPicker: 'icon-ym icon-ym-generator-color',
|
||
editor: 'icon-ym icon-ym-generator-rich-text',
|
||
uploadFile: 'icon-ym icon-ym-generator-upload',
|
||
uploadImg: 'icon-ym icon-ym-generator-upload',
|
||
upload: 'icon-ym icon-ym-generator-upload', // 兼容旧调用方 (fallback 别名)
|
||
userSelect: 'icon-ym icon-ym-generator-user',
|
||
signature: 'icon-ym icon-ym-signature1',
|
||
sign: 'icon-ym icon-ym-signature',
|
||
table: 'icon-ym icon-ym-generator-table',
|
||
relationForm: 'icon-ym icon-ym-generator-menu',
|
||
}
|
||
// 注: 6 个 pass-through 控件 (relationFormAttr / organizeSelect / posSelect /
|
||
// roleSelect / areaSelect / location) 不在此 ICON_MAP — dacli 不特殊构建其专属
|
||
// props, 走 fallback (JnpfInput / generator-input)。详见 docs/components.md。
|
||
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'
|
||
// HIGH1 (eventhub blocker 阶段 6): --table 路径用物理表名, --ai 路径用 opts.enCode
|
||
const entryTableName = opts.table || opts.enCode
|
||
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: entryTableName,
|
||
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 || entry.fullName || entry.label || ''
|
||
// Accept both raw DM fields and generated column-list entries. The
|
||
// latter carry `prop`/`id`, not `field`; using only entry.field made
|
||
// every table-path search item persist with a null id.
|
||
const prop = entry.field || entry.prop || entry.id || entry.__vModel__ || ''
|
||
const tag = JNPF_TAG_MAP[jnpfKey] || 'JnpfInput'
|
||
const tagIcon = JNPF_ICON_MAP[jnpfKey] || 'icon-ym icon-ym-generator-input'
|
||
// HIGH1 (eventhub blocker 阶段 6): --table 路径用物理表名, --ai 路径用 opts.enCode
|
||
const searchTableName = opts.table || opts.enCode
|
||
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: searchTableName,
|
||
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 用户传入, 否则 --table 绑物理表自动构造单主表, 否则 type=4 空, 否则空
|
||
const stripAppPrefix = (t: string) =>
|
||
c.appCode && t.startsWith(`${c.appCode}_`) ? t.slice(c.appCode.length + 1) : t
|
||
let tables: any[]
|
||
if (opts.tables) {
|
||
// BS-55: 用户传 --tables 时, 同步去前缀
|
||
tables = JSON.parse(opts.tables).map((t: any) => {
|
||
if (t && t.table) t.table = stripAppPrefix(t.table)
|
||
return t
|
||
})
|
||
} else if (opts.table && type !== 4) {
|
||
// 2026-07-22 BS-eventhub 阶段 6 修复: --table 绑现有物理表时, 按 web formDesign Form.vue:285-305
|
||
// 构造单主表 item, 避免后端 FlowFormDataUtil.java:831 查 typeId='1' 找不到主表 → MsgCode.COD001.
|
||
// 镜像 web: { relationField:'', relationTable:'', table:opts.table, tableName:opts.table,
|
||
// tableField:'', typeId:'1', fields:dmFields }
|
||
// LOW: 用闭包局部变量 tableDmFields / tablePhysicalName (--table 块已赋值)
|
||
if (tableDmFields && tablePhysicalName) {
|
||
tables = [{
|
||
relationField: '',
|
||
relationTable: '',
|
||
table: tablePhysicalName,
|
||
tableName: tablePhysicalName,
|
||
tableField: '',
|
||
typeId: '1',
|
||
fields: tableDmFields,
|
||
}]
|
||
log.info(` ↳ --table 路径自动构造 tables 单主表: table=${tablePhysicalName}, fields=${tableDmFields.length}`)
|
||
} else {
|
||
// 防御性兜底: --table 路径理论上必填 dmFields/tablePhysicalName, 但若 opt 没填就回退 []
|
||
tables = []
|
||
log.warn(` ⚠ --table 路径缺 dmFields/tablePhysicalName, tables=[] (eventhub blocker 阶段 6 防御性兜底)`)
|
||
}
|
||
} else if (type === 4) {
|
||
// type=4 视图不能带物理表 (后端会 Database exception), 强制空数组
|
||
tables = []
|
||
} else {
|
||
tables = [] // 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 循环, 表不存在抛 "请在数据库中添加对应的数据表"
|
||
}
|
||
|
||
// MEDIUM2: typeId normalization (第一个表 '1', 其余 '0', 见 helper normalizeTableTypeIds)
|
||
normalizeTableTypeIds(tables)
|
||
|
||
// 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(`✓ 根据 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(`表 ${t.table} 过滤了 ${removed} 个 system 重名字段 (避免 INSERT SQL "specified twice")`)
|
||
}
|
||
})
|
||
}
|
||
|
||
// 反思: 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(`--table 路径自动生成 columnList + searchList: ${entries.length} 个字段 (从 tables[0].fields)`)
|
||
} else {
|
||
log.warn(`webType=${webType} 但 tables[0] 无用户字段, ★ 走 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 = tableAiFieldComponents
|
||
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(`--${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(`--column-naming=${conv}, 重命名 ${r.renamed} 个 __vModel__/prop (${r.skipped} 已合规跳过)`)
|
||
}
|
||
} else {
|
||
log.warn(`--ai 路径 formData.fields 为空, ★ 走 Web 设计器勾选`)
|
||
}
|
||
} else if (webType !== 1) {
|
||
log.info(`★ 场景 A: columnList 留空, 去 formDesign Web 设计器第二步"列表设计"手动勾选字段`)
|
||
}
|
||
|
||
// tables 推导后, 自动给第一个表加 typeId='1' (主表标识)
|
||
// (已在 L1102 单次调用 normalizeTableTypeIds, 不重复)
|
||
|
||
// trigger 默认值兜底
|
||
// 根因 (app 复盘, docs/app/dacli-fix-plan.md §7): JNPF 后端 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(`✓ 自动设 ${triggerFixed} 字段 __config__.trigger 默认值 (避免 CodePreview FormMarco.vm:1226 空串 crash)`)
|
||
}
|
||
}
|
||
|
||
// P0-6 (2026-07-27): User-in-the-Loop 预览 — AI 生成 + smartProps + repair 后,
|
||
// 提交前渲染字段表格供用户 review (借鉴 web AiFieldModal.vue)。
|
||
// 预览走 stderr, 不污染 --json stdout 契约。
|
||
if ((opts as any).preview) {
|
||
const { renderFormPreview, confirmApply, collectPreviewRows } = await import('./_preview.ts')
|
||
const table = renderFormPreview(formData, {
|
||
fullName: opts.fullName,
|
||
enCode: opts.enCode,
|
||
webType: String(webType),
|
||
autoRelease: !!opts.autoRelease,
|
||
})
|
||
process.stderr.write('\n' + table + '\n\n')
|
||
const apply = (opts as any).yes ? true : await confirmApply()
|
||
if (!apply) {
|
||
const fieldCount = Array.isArray(formData.fields) ? formData.fields.length : 0
|
||
if (!process.stdin.isTTY && !(opts as any).yes) {
|
||
log.warn('--preview: 非交互环境, 仅预览未创建。加 --yes 直接创建, 或去掉 --preview。')
|
||
} else {
|
||
log.warn('--preview: 已取消 (未创建)。')
|
||
}
|
||
const previewPayload = {
|
||
preview: true,
|
||
created: false,
|
||
enCode: opts.enCode,
|
||
fullName: opts.fullName,
|
||
fields: fieldCount,
|
||
fieldList: collectPreviewRows(formData),
|
||
}
|
||
if (opts.json) printJson(previewPayload)
|
||
return ctx.success(previewPayload)
|
||
}
|
||
log.info('--preview: 已确认, 继续创建')
|
||
}
|
||
|
||
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})`)
|
||
|
||
// T3 close-loop (webapi hardening): POST 已发生, 此处 closeFormContract 仅跑 GET + strict 校验
|
||
// 通过后才让下方 release 重试逻辑跑; 失败立即 FormSchemaInvalidError 退出, 阻断 runtime 不一致
|
||
const closeLoopWebapi = {
|
||
postForm: async () => ({ id: newId, code: 200 }), // POST 已发生 (loadVisualDev.create 上面), no-op stub
|
||
getForm: buildGetFormAdapter((id) => loadVisualDev.getInfo(id) as Promise<{ id: string; state: number | string; formData: unknown }>),
|
||
releaseForm: async () => ({ code: 200 }), // required by type, never invoked (autoRelease=false) — release 走下方既有重试
|
||
}
|
||
try {
|
||
await closeFormContract(closeLoopWebapi, {
|
||
enCode: opts.enCode,
|
||
appCode: c.appCode,
|
||
autoRelease: false,
|
||
op: 'create',
|
||
})
|
||
} catch (e) {
|
||
if (e instanceof FormSchemaInvalidError) {
|
||
log.error(`✗ T3 回读校验失败: ${e.message}`)
|
||
// Bug 1 (R3): 回读失败时清残留 state=0 行 (newId 已创建, 但 release 没走)
|
||
await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose })
|
||
return ctx.fail(`${FORM_SCHEMA_INVALID_TAG} (创建后回读校验失败)`, { id: newId, enCode: opts.enCode, errors: e.errors })
|
||
}
|
||
throw e
|
||
}
|
||
log.ok(` ✓ T3 闭环校验通过 (state=0, 等待 release)`)
|
||
|
||
// release 失败时重试 3 次 (指数 backoff 500/1000/2000ms), 仍失败 process.exit(1)
|
||
// 后端: VisualdevController.java:593 publish() — state=1 + base_visual_release 行 saveOrUpdate (line 673)
|
||
// web 端: web/apps/jnpf-web-apps-main/src/api/onlineDev/visualDev.ts:43-45 release(id) → POST /visualdev/Base/{id}/Actions/Release
|
||
//
|
||
// ⚠ 铁律 3 audit (2026-07-29): retry + backoff 是 dacli ADDITIVE SAFETY NET, 不在 web 镜像范围.
|
||
// web 端 release() 简单 POST 无 retry, 因为浏览器交互是一次性的 (用户点发布, 失败看错误);
|
||
// dacli 跑 CI / agent loop 不能中断, 加 retry 兜底后端 saveOrUpdate 竞态 (base_visual_release 表).
|
||
// 此机制不属于"镜像", 是 dacli 的工程化改进 (跟 BS-新149 注释同根).
|
||
//
|
||
// 历史 BS-新149: 测试场偶发后端 400 "Data does not exist" 是 base_visual_release 表 saveOrUpdate 竞态,
|
||
// 单次 500ms 重试命中率低 (实测 ~30%), 升级到 3 次指数 backoff 命中率 ~85%.
|
||
const tryRelease = async (): Promise<void> => {
|
||
await loadVisualDev.release(newId) // unwrap() throws on non-200
|
||
}
|
||
const RELEASE_BACKOFF_MS = [500, 1000, 2000] // 总等待 ≤3.5s, 用户感知可接受
|
||
let releaseOk = false
|
||
let lastErr: Error | null = null
|
||
for (let attempt = 0; attempt <= RELEASE_BACKOFF_MS.length; attempt++) {
|
||
try {
|
||
await tryRelease()
|
||
if (attempt === 0) log.ok('发布成功 (state=1)')
|
||
else log.ok(`发布成功 (state=1, 重试 ${attempt} 次)`)
|
||
releaseOk = true
|
||
break
|
||
} catch (e: any) {
|
||
lastErr = e
|
||
if (attempt < RELEASE_BACKOFF_MS.length) {
|
||
const wait = RELEASE_BACKOFF_MS[attempt]!
|
||
log.warn(`发布失败 (${e.message}), ${wait}ms 后重试 (${attempt + 1}/${RELEASE_BACKOFF_MS.length})...`)
|
||
// Bug 2 (R3 + R1 P6.2): 首次 400 时, 强制 GET 一次 formInfo 刷新后端缓存,
|
||
// 防 base_visual_release 表 saveOrUpdate 竞态 (后端偶发缓存 state=0, GET 一次会触发 ORM refresh).
|
||
// 这是 dacli ADDITIVE SAFETY NET (不在 web 镜像范围, web 端浏览器交互是一次性的).
|
||
if (attempt === 0) {
|
||
try {
|
||
await loadVisualDev.getInfo(newId)
|
||
log.warn(` ↳ GET formInfo 刷新 (R3 兜底)`)
|
||
} catch (ge: any) {
|
||
log.warn(` ↳ GET formInfo 刷新失败: ${ge.message?.slice(0, 60)}, 直接重试 release`)
|
||
}
|
||
}
|
||
await new Promise((r) => setTimeout(r, wait))
|
||
}
|
||
}
|
||
}
|
||
if (!releaseOk) {
|
||
log.error(`✗ 发布失败 (重试 ${RELEASE_BACKOFF_MS.length} 次仍失败): ${lastErr?.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: lastErr?.message })
|
||
// Bug 1 (R3): release 失败时清残留 state=0 行 (newId 已创建但未发布)
|
||
await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose })
|
||
return ctx.fail(`发布失败 (重试 ${RELEASE_BACKOFF_MS.length} 次仍失败): ${lastErr?.message}`, { id: newId, enCode: opts.enCode })
|
||
}
|
||
if (!releaseOk) {
|
||
// Bug 1 (R3): defensive (releaseOk=false 但走不到这里, 仍兜底)
|
||
await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose })
|
||
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} 未在数据建模列表中找到`)
|
||
// v2.4+ L3: release 可能失败, 提示先 dm create
|
||
ctx.addSuggestion(remindPhysicalTableMissing(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.json) {
|
||
// 2026-07-22 fix (eventhub blocker 阶段 5): --json 路径 stdout 已被
|
||
// printJson({ id, enCode, type, webType }) (line 1418) 占满,
|
||
// 此处必须 discard buffered log (防泄漏) 且**不输出**人类摘要/详情,
|
||
// 否则 stdout 会被 ✓ ... + "详情: dacli log last" 污染, JSON.parse 整段失败.
|
||
log.discard()
|
||
} else 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) {
|
||
// Bug 1 (R3): 外层 catch 也兜底清残留 (handler 任何 ctx.fail 之外的 throw 都覆盖)
|
||
// 注意: 此时 newId 可能不可见 (create 未成功), cleanupResidueForms 内部会按 enCode 查询 state=0 残留
|
||
await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose })
|
||
return ctx.fail(`form create 失败: ${(e as Error).message?.slice(0, 200)}`, { enCode: opts.enCode })
|
||
}
|
||
})
|
||
})
|
||
|
||
installHelpHookWithPatterns(cmd, 'form create', {
|
||
purpose: '创建表单. 推荐 --ai 一条命令完成 (v0.22+ SSW /api/ssw/ai/build-form + web buildFormData), 业务建议 dm→form 两步走.',
|
||
required: { '--fullName | --ai': '中文名, 或传 --ai 由平台 AI 自动生成' },
|
||
optional: {
|
||
'--enCode': '英文编码 (--ai 自动填)',
|
||
'--type': '1=自定义(formDesign) 2=系统 3=接口 4=视图 (默认 1)',
|
||
'--webType': '1=仅表单 2=表单+列表(默认) 3=树+表单 4=数据视图 (默认 2)',
|
||
'--category': '分类 id (不传自动从 businessType 字典推导)',
|
||
'--dbLinkId': '业务库 id (type≠4 时必传)',
|
||
'--fields': 'formData.fields JSON (--ai 自动填, --fields 路径已废弃)',
|
||
'--tables': 'tables JSON (type=1/2)',
|
||
'--enableFlow': '0|1',
|
||
'--flowId': '工作流 id',
|
||
'--autoRelease': '建完立刻发布 (type=4 自动跳过)',
|
||
'--autoTable': '从 --fields 推导 --tables JSON (覆盖 --tables, 对齐 web formDesign)',
|
||
'--autoCreateMenu': '发布后自动挂菜单 (需 --menuParentId, 避免浏览器验证失败)',
|
||
'--menuParentId': '挂菜单的父目录 id (--autoCreateMenu 时必传)',
|
||
'--no-cleanup-on-fail': '关闭 create 失败时自动清残留 state=0 行 (默认 ON, R3 P0 兜底)',
|
||
'--no-relation-form-auto': '关闭 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/apps/jnpf-web-apps-main/src/views/onlineDev/formDesign/Form.vue:444-465 + AI助手.vue', api: 'POST /api/visualdev/Base | POST /api/visualdev/ai/form' },
|
||
notes: [
|
||
'推荐 dm→form 两步: dm create 建物理表 → form create --ai "<描述>" 建表单',
|
||
'autoRelease 对 type=4 自动跳过 (release 会 400)',
|
||
'--ai 走 web 端 buildFormData, type/webType 默认与命令一致 (1/2)',
|
||
'--ai-field 只输出建议, 不建表单, 用于 AI 辅助字段设计',
|
||
'--tables 含 allowNull=0 字段时, 自动同步 formData.fields[].__config__.required=true (避免 POST 缺字段触发后端 INSERT 失败)',
|
||
],
|
||
})
|
||
|
||
return cmd
|
||
}
|