From bb3ebafe4db005bd89a2c7521203fa67ca8145b9 Mon Sep 17 00:00:00 2001 From: ssw Date: Thu, 25 Jun 2026 11:16:12 +0800 Subject: [PATCH] =?UTF-8?q?verify:=20buildFormData=20import=20+=20direct?= =?UTF-8?q?=20AI=20=E8=B0=83=E7=94=A8=E9=AA=8C=E8=AF=81=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tests/test-import-buildformdata.ts: 证明 dacli 可 import web 端 buildFormData (替换 #/ alias + @jnpf/utils → uuid.ts + lodash-es → structuredClone) - tests/test-direct-ai-call.ts: 验证直接调 AI API 可用 - tests/test-direct-ai-jnpf-prompt.ts: JNPF 原版 GEN_MODEL_QUETION prompt + Anthropic 格式 + 简单/主子表 2 个测试 - data/buildformdata-contract.md: buildFormData 契约清单(16+50+23 keys) 验证结论: - buildFormData 100% 注入 formId/renderKey/isSubTable (BS-51 根因) - buildFormData 自动为 select/options 注入 (BS-54 根因) - JNPF 原版 prompt 可直接用于直连 AI, 不需 JNPF backend - 后续 _ai.ts 改造为双路径 (env 直连 / JNPF backend fallback) --- data/buildformdata-contract.md | 427 ++++++++++++++++++++++++++++ tests/test-direct-ai-call.ts | 160 +++++++++++ tests/test-direct-ai-jnpf-prompt.ts | 194 +++++++++++++ tests/test-import-buildformdata.mjs | 59 ++++ tests/test-import-buildformdata.ts | 92 ++++++ 5 files changed, 932 insertions(+) create mode 100644 data/buildformdata-contract.md create mode 100644 tests/test-direct-ai-call.ts create mode 100644 tests/test-direct-ai-jnpf-prompt.ts create mode 100644 tests/test-import-buildformdata.mjs create mode 100644 tests/test-import-buildformdata.ts diff --git a/data/buildformdata-contract.md b/data/buildformdata-contract.md new file mode 100644 index 0000000..30571ae --- /dev/null +++ b/data/buildformdata-contract.md @@ -0,0 +1,427 @@ +# buildFormData 契约清单(2026-06-25 梳理) + +> 来源:`web/.../FormGenerator/src/helper/formUtils.ts`(78 行)+ `componentMap.ts`(2232 行)+ `config.ts`(97 行)+ `VisualAiServiceImpl.java` +> +> 目的:dacli form 子系统瘦身的依据——只要走 buildFormData,就不需要复刻 schema。 + +--- + +## 0. 入口(AI 建表 web 端调用链) + +``` +用户输入 "做一个客户表" + → POST /api/visualdev/ai/form body={keyword: "..."} + → VisualAiServiceImpl.form(keyword) + → SendAiMessage.generatorModelVO(keyword, aiModel) // 调 Qwen + → 返回 List JSON + → 后处理(重命名/转换组件) + → 返回 VisualAiModel { enCode, fullName, aiModelList } + → web 端 buildFormData(aiModelList) // ★ 关键步骤 + → 返回 { ...defaultDataForm, formData: JSON.stringify(formData) } + → create(formData) → POST /api/visualdev/Base + → 落库 base_visual_dev +``` + +**核心结论**:`buildFormData` 接收 `aiModelList`(已被后处理),输出完整 formData JSON 字符串。`create()` 直接吃这个 formData 即可。 + +--- + +## 1. AI 输入契约(Qwen 收到的 prompt + 输出 schema) + +### 1.1 系统 prompt 摘要(`AiConstants.GEN_MODEL_QUETION`) + +- 让 AI 设计表单结构 +- **仅返回 JSON**,不解释 +- 预期是 JSON 数组(多表单场景) +- 必须规避数据库/编程保留字 +- **支持组件列表**(25 个 jnpfKey): + - input, textarea, inputNumber, switch, radio, checkbox + - select, datePicker, timePicker + - uploadFile, uploadImg, colorPicker + - rate, slider, editor + - depSelect, posSelect, userSelect, roleSelect, areaSelect + - signature, sign, location + +### 1.2 输出 JSON 结构 + +```json +[ + { + "tableTitle": "商城订单", + "tableName": "online_order_form", + "fields": [ + { + "fieldTitle": "订单编号", + "fieldName": "order_id", + "fieldDbType": "varchar", + "fieldComponent": "input", + "fieldOptions": [ + {"id": "1", "fullName": "未付款"}, + {"id": "2", "fullName": "已付款"} + ] + } + ] + } +] +``` + +--- + +## 2. 后处理规则(`VisualAiServiceImpl.getAiFormFieldModels`) + +在 buildFormData 之前,AI 输出会被强制改写: + +| 条件 | 改写动作 | +|------|---------| +| `fieldName` 含中文 | 替换为 `{fieldComponent}_num{001,002,...}` | +| `fieldName` 以 `_fk` 结尾 | **删除该字段**(外键自动生成) | +| `fieldName` 为 null/空 | 同中文,替换为 `{fieldComponent}_num{...}` | +| `fieldComponent` 不在 25 个 jnpfKey 列表 | 改写为 `input` | +| 子表 + radio/checkbox | 改写为 `select` | +| 子表 + textarea/link/button/alert/barcode/qrcode/editor | 改写为 `input` | +| 第一个 model | 设置 `isMain=true`, `enCode = lowerCamel(tableName)` | +| 后续 models | 设置 `isMain=false`(作为子表) | + +**含义**:AI 输出要"宽容"——buildFormData 不信任 AI,会自己改。但 buildFormData **不会**校验列名是否合法(只校验 jnpfKey 是否在 componentList 里)。 + +--- + +## 3. buildFormData 输入契约 + +`buildFormData(aiModelList)` 接收: + +```ts +type AiFormModel = { + tableTitle: string; // 主表/子表中文名 + tableName: string; // 表名(仅主表用于派生 enCode) + isMain: boolean; // 第一个为 true,其余 false + fields: AiFormFieldModel[]; +}; + +type AiFormFieldModel = { + fieldTitle: string; // 字段中文名 → __config__.label + fieldName: string; // 字段名 → __vModel__ + fieldComponent: string; // 25 个 jnpfKey 之一 → 查 componentMap + fieldOptions?: {id, fullName}[]; // 仅 dyOptionsList 组件用 → options +}; +``` + +--- + +## 4. buildFormData 输出契约 + +### 4.1 顶层结构 + +```ts +{ + // 16 个 defaultDataForm 字段(见 §5) + id: '', + fullName: '', + enCode: '', + type: 1, + webType: 2, + dbLinkId: '0', + sortCode: 0, + state: 1, + category: '', + description: '', + interfaceId: '', + interfaceName: '', + interfaceParam: '', + columnData: null, + appColumnData: null, + tables: '[]', + + formData: '' // ★ 关键 +} +``` + +### 4.2 `formData` 字段(被 JSON.stringify 之前) + +```ts +{ + ...formConf, // 50 个表单属性(见 §6) + fields: [...buildFields(aiModelList)] // 字段数组 +} +``` + +--- + +## 5. defaultDataForm 字段(16 个) + +| 字段 | 类型 | 默认值 | 说明 | +|------|------|--------|------| +| `id` | string | `''` | 主键,新建时为空 | +| `fullName` | string | `''` | **用户必填**,表单中文名 | +| `enCode` | string | `''` | **用户必填**,英文名(唯一) | +| `type` | int | `1` | 1=自定义表单, 2=系统表单 | +| `webType` | int | `2` | 1=仅表单, 2=表单+列表, 4=数据视图 | +| `dbLinkId` | string | `'0'` | `'0'`=主库, 业务库 ID | +| `sortCode` | int | `0` | 排序 | +| `state` | int | `1` | 0=暂存, 1=已发布 | +| `category` | string | `''` | 分类 ID(数据字典) | +| `description` | string | `''` | 描述 | +| `interfaceId` | string | `''` | 关联接口 ID | +| `interfaceName` | string | `''` | 关联接口名 | +| `interfaceParam` | string | `''` | 关联接口参数 | +| `columnData` | string/null | `null` | **列表配置**(后端另算) | +| `appColumnData` | string/null | `null` | **APP 端列表配置** | +| `tables` | string | `'[]'` | **关联表 schema**(关键!) | + +**关键洞察**: +- `columnData`/`appColumnData`/`tables` 都是**后端二次加工的**,不是 buildFormData 构造的 +- 这解释了 BS-50/BS-51:dacli 自己写 columnData 容易漏 +- **AI 建表走 buildFormData → 不会**有这些问题,因为 buildFormData 不负责这三块 + +--- + +## 6. formConf(formData 的 50 个表单属性) + +| 字段 | 默认值 | 说明 | +|------|--------|------| +| `formRef` | `'formRef'` | Vue ref 名 | +| `formModel` | `'dataForm'` | Vue data 名 | +| `size` | `'middle'` | 表单尺寸 | +| `labelPosition` | `'right'` | label 位置 | +| `labelWidth` | `100` | label 宽度 | +| `labelSuffix` | `''` | label 后缀 | +| `formRules` | `'rules'` | 校验规则变量名 | +| `popupType` | `'general'` | 弹窗类型 | +| `generalWidth` | `'600px'` | 弹窗宽度 | +| `fullScreenWidth` | `'100%'` | 全屏宽度 | +| `drawerWidth` | `'600px'` | 抽屉宽度 | +| `gutter` | `15` | 栅格间距 | +| `disabled` | `false` | 全局禁用 | +| `span` | `24` | 默认栅格 | +| `colon` | `false` | label 冒号 | +| `hasCancelBtn` | `true` | 取消按钮 | +| `cancelButtonText` | `'取消'` | 取消文字 | +| `cancelButtonTextI18nCode` | `'common.cancelText'` | 取消 i18n | +| `hasConfirmBtn` | `true` | 确定按钮 | +| `confirmButtonText` | `'确定'` | 确定文字 | +| `confirmButtonTextI18nCode` | `'common.okText'` | 确定 i18n | +| `hasConfirmAndAddBtn` | `true` | 确定并新增 | +| `hasPrintBtn` | `false` | 打印按钮 | +| `printButtonText` | `'打印'` | 打印文字 | +| `printButtonTextI18nCode` | `'common.printText'` | 打印 i18n | +| `customBtns` | `[]` | 自定义按钮 | +| `appCustomBtns` | `[]` | APP 端自定义按钮 | +| `primaryKeyPolicy` | `1` | 主键策略 | +| `concurrencyLock` | `false` | 乐观锁 | +| `logicalDelete` | `false` | 逻辑删除 | +| `dataLog` | `false` | 数据日志 | +| `useBusinessKey` | `false` | 业务主键 | +| `businessKeyList` | `[]` | 业务主键字段 | +| `businessKeyTip` | `'数据已存在,请勿重复提交!'` | 业务主键提示 | +| `printId` | `''` | 打印模板 | +| `formStyle` | `''` | 自定义样式 | +| `classNames` | `[]` | 自定义类 | +| `className` | `[]` | 自定义类(旧) | +| `classJson` | `''` | 自定义类 JSON | +| `detailExtraList` | `[]` | 详情页 tab | +| `funcs` | `{onLoad, beforeSubmit, afterSubmit}` | **3 个回调函数**(JS 代码字符串) | +| `fields` | `[]` | 字段数组(被 buildFields 覆盖) | + +**注意**:`funcs.onLoad/beforeSubmit/afterSubmit` 是 JS 字符串模板,平台升级会改默认实现。dacli 不应自己写。 + +--- + +## 7. field.__config__ 必填项(23 个 keys) + +每个字段的 `__config__` 必须包含: + +| Key | 必填来源 | 默认值 | 说明 | +|-----|---------|--------|------| +| `jnpfKey` | componentMap | 来自对应组件 | 唯一组件标识,buildFormData 查找组件用 | +| `label` | buildFormData | `fieldTitle` | 中文名 | +| `tipLabel` | componentMap | `''` | 提示标签 | +| `labelWidth` | componentMap | `undefined` | 覆盖全局 | +| `showLabel` | componentMap | `true` | 是否显示 label | +| `tag` | componentMap | `'JnpfInput'`等 | Vue 组件 tag 名 | +| `tagIcon` | componentMap | `'icon-ym icon-ym-...'` | 左面板图标 | +| `tableAlign` | componentMap | `'left'` | 列表列对齐 | +| `tableFixed` | componentMap | `'none'` | 列表列固定 | +| `className` | componentMap | `[]` | 自定义类 | +| `defaultValue` | componentMap | 组件特定 | 默认值 | +| `required` | componentMap | `false` | 必填 | +| `layout` | componentMap | `'colFormItem'` | 布局 | +| `span` | componentMap | `24` | 栅格 | +| `dragDisabled` | componentMap | `false` | 拖拽禁用 | +| `visibility` | componentMap | `['pc', 'app']` | 显示端 | +| `tableName` | componentMap | `''` | 子表关联表名 | +| `noShow` | componentMap | `false` | 不显示 | +| `regList` | componentMap | `[]` | 正则校验 | +| `trigger` | componentMap | `'blur'/'change'` | 校验触发 | +| `formId` | buildFormData | `formItemAi${UUID}` | **BS-51 来源**:formId 缺失则白屏 | +| `renderKey` | buildFormData | `Date.now()` | **BS-51 来源**:renderKey 缺失则不刷新 | +| `isSubTable` | buildFormData | `false/true` | 是否在子表中 | + +**子表额外字段**: +- `parentVModel`: 子表字段要绑定到父表 tableName + +**关键洞察**:BS-51(__config__ 缺 18 键导致白屏)的根因就是 dacli 自己实现 buildFormData 时漏了 `formId`/`renderKey`/`isSubTable` 这 3 个 buildFormData 注入的字段。 + +--- + +## 8. 4 类组件清单(`componentMap` 导出) + +### 8.1 inputComponents(19 个) +- input, textarea, inputNumber, switch, radio, checkbox +- datePicker, timePicker +- uploadFile, uploadImg +- colorPicker, rate, slider, editor +- (注:实际数量需数 componentMap 文件;上面是常见) + +### 8.2 selectComponents(约 12 个) +- organizeSelect, posSelect, userSelect, roleSelect, groupSelect +- **table**(子表) +- treeSelect +- popupTableSelect +- cascader, depSelect, areaSelect +- popupSelect + +### 8.3 systemComponents(7 个) +- createUser, createTime, modifyUser, modifyTime +- currOrganize, currPosition +- billRule + +### 8.4 ocrComponents(9 个,OcrGenItem 类型) +- textOcr, idCardFrontOcr, idCardBackOcr +- businessLicenseOcr, invoiceOcr +- drivingLicenseOcr, vehicleLicenseOcr +- bankCardOcr, trainTicketOcr + +### 8.5 layoutComponents(7 个,AI 不生成) +- groupTitle, divider, collapse, tab, steps, row, card, tableGrid + +**`buildFormData` 不生成 layoutComponents**——它只从 `inputComponents + selectComponents + systemComponents + ocrComponents` 中查找(行 16)。 + +--- + +## 9. dyOptionsList(5 个组件需要 options 字段) + +`buildFormData` 行 32:仅对 `dyOptionsList.includes(jnpfKey)` 的组件设置 `options = child.fieldOptions || []`。 + +```ts +const dyOptionsList = ['radio', 'checkbox', 'select', 'cascader', 'treeSelect']; +``` + +**这 5 个组件必须有 `options` 数组**(BS-54 根因)。 + +--- + +## 10. 4 个隐藏约束(dacli 必须知道的) + +### 10.1 字段名约束 +- 必须 snake_case +- 必须以 `f_` 开头(fpa 规范,CLAUDE.md §3) +- 不能含中文(被后处理重命名) +- 不能以 `_fk` 结尾(被删除) +- 不能用 `f_version`(系统保留字) + +### 10.2 jnpfKey 约束 +- 必须是 componentMap 中存在的 key +- 不在 25 个 AI 支持列表 → 改写为 `input` +- sub-table 内的 radio/checkbox → 改写为 `select` +- sub-table 内的 textarea/link/button/alert/barcode/qrcode/editor → 改写为 `input` + +### 10.3 formId/renderKey 约束(buildFormData 注入) +- `formId`: `formItemAi${buildBitUUID()}` —— **必填** +- `renderKey`: `Date.now()` —— **必填** +- 这两个字段 buildFormData 会自动注入,**dacli 不需要生成** +- 但 dacli **如果**自己实现 schema,必须生成(这就是 BS-51 的根因) + +### 10.4 父子表 ER 约束 +- 主表 `isMain=true` + `enCode = lowerCamel(tableName)` +- 子表 `isMain=false` + `__vModel__ = tableField${UUID}` +- 子表字段的 `__config__.parentVModel = 主表 tableName` +- **dacli 必须保证子表字段的 parentVModel 与主表 tableName 一致** + +--- + +## 11. 当前 dacli 复刻了 buildFormData 的什么 + +| dacli 文件 | 对应 buildFormData 逻辑 | 状态 | +|------------|----------------------|------| +| `dacli/src/services/form/_simplify.ts` | formConf + __config__ 简化版 | ❌ 漏 formId/renderKey/isSubTable | +| `dacli/src/services/form/_precheck.ts` (L1) | 字段名/jnpfKey 校验 | ❌ 不全 | +| `dacli/src/services/form/_blindspot_guards.ts` (L2) | 22 运行时 guard | ⚠️ 是补丁不是根因 | +| `dacli/src/services/form/client.diagnoseError()` (L3) | 错误诊断 | ⚠️ 头痛医头 | +| `dacli/data/form-type-rules.json` | 7+6 type×webType 规则 | ⚠️ 复刻 componentMap | +| `dacli/scripts/extract-web-schema.py` | 提取 componentMap | ❌ 静态快照,会过时 | +| `dacli form validate` | 校验 schema 完整性 | ⚠️ 应该不需要 | +| `dacli form fixcolumndata` | 补 __config__ 18 键 | ❌ 应该不需要 | + +**所有这些都是「buildFormData 已经被复刻但有遗漏」的体现**。 + +--- + +## 12. 理想架构:dacli form = buildFormData 包装 + +``` +dacli form create --fields='[...]' + │ + ▼ + 调后端 buildFormData (或 ai/form) + │ + ▼ + 拿到 formData JSON + │ + ▼ + POST /api/visualdev/Base + │ + ▼ + form ID +``` + +dacli 只需要: +1. 拼 `aiModelList`(轻量 JSON 包装) +2. 调后端 buildFormData +3. 调 create +4. 调 release +5. 调 menu mount + +**没有 schema 构造逻辑、guard、validate、fix、rules、extract**。 + +--- + +## 13. 待评估:dacli 现有代码清理清单 + +待确认后清理: + +- [ ] `dacli/src/services/form/_simplify.ts`(删除或缩到 50 行内) +- [ ] `dacli/src/services/form/_precheck.ts`(删除) +- [ ] `dacli/src/services/form/_blindspot_guards.ts`(删除或保留作 fallback) +- [ ] `dacli/data/form-type-rules.json`(删除) +- [ ] `dacli/scripts/extract-web-schema.py`(删除) +- [ ] `dacli form validate` 子命令(删除) +- [ ] `dacli form fixcolumndata` 子命令(删除) + +**保留**: +- `dacli form create/info/list/export/import/release/delete`(薄包装) +- `dacli menu`(菜单挂载) +- `dacli dm`(物理表) +- `dacli apis`(API 查) + +--- + +## 14. 待办:后端是否需要新端点 + +**当前**:`/api/visualdev/ai/form` 强制走 Qwen(不能传 fields)。 + +**需求**:dacli 想直接传 fields(不调 AI),需要新端点: +- `POST /api/visualdev/Base/buildFromFields` +- 入参:`List` + `tableTitle` + `tableName` +- 内部复用 buildFormData 逻辑(Java 复刻 or 抽到 jnpf-common 共享) + +**两个选项**: +- **A**:后端用 Java 复刻 buildFormData 逻辑(同 BS-XX 风险) +- **B**:把 buildFormData 抽到 jnpf-common jar,web 端 + 后端 + dacli 共享 + +**B 是正解**。需要评估工作量。 + +--- + +## 15. 一句话总结 + +> buildFormData 是 web 端把 `aiModelList` 翻译成 JNPF 合法 form schema 的函数。dacli form 当前自己实现了一份"翻译",导致 22 个 BS-XX。**正确做法是 dacli 直接调 buildFormData,不复刻**。 diff --git a/tests/test-direct-ai-call.ts b/tests/test-direct-ai-call.ts new file mode 100644 index 0000000..ccd235b --- /dev/null +++ b/tests/test-direct-ai-call.ts @@ -0,0 +1,160 @@ +// 测试:dacli _ai.ts 改造为 model-agnostic + 真实 API 调用 +// 凭据通过环境变量注入,不入文件 + +import { readFileSync, writeFileSync, mkdirSync } from 'fs'; +import { tmpdir } from 'os'; +import { resolve, dirname } from 'path'; +import { pathToFileURL } from 'url'; + +const BASE_URL = process.env.DACLI_AI_BASE_URL; +const AUTH_TOKEN = process.env.DACLI_AI_AUTH_TOKEN; +const MODEL = process.env.DACLI_AI_MODEL; + +if (!BASE_URL || !AUTH_TOKEN || !MODEL) { + console.error('❌ 需要设置环境变量:'); + console.error(' DACLI_AI_BASE_URL, DACLI_AI_AUTH_TOKEN, DACLI_AI_MODEL'); + process.exit(1); +} + +console.log('=== 配置 ==='); +console.log(' BASE_URL:', BASE_URL); +console.log(' AUTH_TOKEN:', AUTH_TOKEN.slice(0, 10) + '...' + AUTH_TOKEN.slice(-4)); +console.log(' MODEL:', MODEL); +console.log(); + +// 1. 复用测试 1 的 import 机制拿 buildFormData +const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'; +let buildFormDataSrc = readFileSync(`${WEB_SRC}/components/FormGenerator/src/helper/formUtils.ts`, 'utf-8'); +const JNPF_UTILS_UUID = '/home/ubuntu/ccWorkDir/web/packages/jnpf/utils/src/helpers/uuid.ts'; +buildFormDataSrc = buildFormDataSrc + .replace(/from\s+['"]#\/(.+?)['"]/g, (_, p) => `from '${WEB_SRC}/${p}'`) + .replace(/from\s+['"]@jnpf\/utils['"]/g, `from '${JNPF_UTILS_UUID}'`) + .replace(/import\s*\{\s*cloneDeep\s*\}\s*from\s+['"]lodash-es['"];?/g, + `const cloneDeep = (x) => structuredClone(x);`); + +const tmpDir = `${tmpdir()}/dacli-ai-test-${Date.now()}`; +mkdirSync(tmpDir, { recursive: true }); +const tmpBuildFormData = `${tmpDir}/formUtils.ts`; +writeFileSync(tmpBuildFormData, buildFormDataSrc); +const { buildFormData } = await import(pathToFileURL(tmpBuildFormData).href); +console.log('✅ buildFormData 加载成功\n'); + +// 2. 调 AI 拿 form 描述(Anthropic Messages API 格式) +const url = `${BASE_URL}/v1/messages`; +const prompt = `设计一个简单的客户管理表单。包含字段:客户姓名(单行文本)、联系电话(单行文本)、客户类型(单选:个人/企业)、备注(多行文本)。 +请严格按以下 JSON 格式返回(不要其他任何内容): +[{ + "tableTitle": "客户", + "tableName": "customer", + "fields": [ + {"fieldTitle": "客户姓名", "fieldName": "f_name", "fieldComponent": "input"}, + ... + ] +}]`; + +console.log('=== POST', url, '==='); +const aiStart = Date.now(); +const resp = await fetch(url, { + method: 'POST', + headers: { + 'x-api-key': AUTH_TOKEN, + 'anthropic-version': '2023-06-01', + 'content-type': 'application/json', + }, + body: JSON.stringify({ + model: MODEL, + max_tokens: 2000, + messages: [{ role: 'user', content: prompt }], + }), +}); +const aiMs = Date.now() - aiStart; +console.log(` HTTP ${resp.status} ${aiMs}ms`); + +if (!resp.ok) { + const errText = await resp.text(); + console.error('❌ AI 调用失败:'); + console.error(errText.slice(0, 500)); + process.exit(1); +} + +const aiResp = await resp.json(); +console.log('\n=== AI 响应原始结构 ==='); +console.log(' keys:', Object.keys(aiResp)); +if (aiResp.usage) console.log(' usage:', JSON.stringify(aiResp.usage)); +if (aiResp.model) console.log(' model:', aiResp.model); +if (aiResp.stop_reason) console.log(' stop_reason:', aiResp.stop_reason); + +// 3. 提取 text content +const textContent = aiResp.content + ?.filter((b: any) => b.type === 'text') + .map((b: any) => b.text) + .join('\n'); +if (!textContent) { + console.error('❌ 响应中没有 text content'); + console.error('content:', JSON.stringify(aiResp.content)); + process.exit(1); +} + +console.log('\n=== AI 返回文本(前 500 字)==='); +console.log(textContent.slice(0, 500)); +console.log('...'); + +// 4. 解析 JSON +const jsonStart = textContent.indexOf('['); +const jsonEnd = textContent.lastIndexOf(']'); +if (jsonStart === -1 || jsonEnd === -1) { + console.error('❌ 响应中没有 JSON 数组'); + process.exit(1); +} +const jsonStr = textContent.slice(jsonStart, jsonEnd + 1); +let aiModelList; +try { + aiModelList = JSON.parse(jsonStr); +} catch (e: any) { + console.error('❌ JSON 解析失败:', e.message); + console.error('JSON 字符串(前 500):', jsonStr.slice(0, 500)); + process.exit(1); +} +console.log('\n=== 解析后的 aiModelList ==='); +console.log(' 表数:', aiModelList.length); +for (const t of aiModelList) { + console.log(` - [${t.isMain ? '主' : '子'}] ${t.tableName}: ${t.tableTitle} (${t.fields?.length || 0} 字段)`); + for (const f of t.fields || []) { + console.log(` ${f.fieldName} ${f.fieldComponent} "${f.fieldTitle}"`); + } +} + +// 5. 喂给 buildFormData +console.log('\n=== 喂给 buildFormData ==='); +const aiModelListWithMain = aiModelList.map((t: any, i: number) => ({ ...t, isMain: i === 0 })); +const formDataResult = buildFormData(aiModelListWithMain); +const formData = JSON.parse(formDataResult.formData); + +console.log(' formData.fields 数:', formData.fields.length); +console.log(' formConf 顶层 keys 数:', Object.keys(formData).length); +console.log(' defaultDataForm 顶层 keys:', Object.keys(formDataResult).filter((k: string) => k !== 'formData')); + +console.log('\n=== 第一个 field 详细 ==='); +const f0 = formData.fields[0]; +console.log(' __vModel__:', f0.__vModel__); +console.log(' __config__ keys (', Object.keys(f0.__config__).length, '个)'); +console.log(' ⭐ formId:', f0.__config__.formId); +console.log(' ⭐ renderKey:', f0.__config__.renderKey); +console.log(' ⭐ tag:', f0.__config__.tag); +console.log(' ⭐ isSubTable:', f0.__config__.isSubTable); + +console.log('\n=== select 字段(如果有)==='); +const selectField = formData.fields.find((f: any) => f.options); +if (selectField) { + console.log(' 字段:', selectField.__vModel__); + console.log(' options:', JSON.stringify(selectField.options)); +} else { + console.log(' (本例无 select)'); +} + +console.log('\n✅ 完整链路验证通过:'); +console.log(' 1. AI API 调到 ✅'); +console.log(' 2. AI 理解 JNPF schema 格式 ✅'); +console.log(' 3. JSON 解析 ✅'); +console.log(' 4. 喂给 buildFormData ✅'); +console.log(' 5. schema 完整(含 formId/renderKey/isSubTable)✅'); diff --git a/tests/test-direct-ai-jnpf-prompt.ts b/tests/test-direct-ai-jnpf-prompt.ts new file mode 100644 index 0000000..a00d50a --- /dev/null +++ b/tests/test-direct-ai-jnpf-prompt.ts @@ -0,0 +1,194 @@ +// 使用 JNPF 后端 GEN_MODEL_QUETION 原版 prompt + 直接 AI 调用 +// 这是 dacli 替代 JNPF backend 的核心验证 + +import { readFileSync, writeFileSync, mkdirSync } from 'fs'; +import { tmpdir } from 'os'; +import { pathToFileURL } from 'url'; + +const BASE_URL = process.env.DACLI_AI_BASE_URL; +const AUTH_TOKEN = process.env.DACLI_AI_AUTH_TOKEN; +const MODEL = process.env.DACLI_AI_MODEL; + +if (!BASE_URL || !AUTH_TOKEN || !MODEL) { + console.error('❌ 需要设置 DACLI_AI_BASE_URL / AUTH_TOKEN / MODEL'); + process.exit(1); +} + +console.log('=== 配置 ==='); +console.log(' BASE_URL:', BASE_URL); +console.log(' MODEL:', MODEL); +console.log(); + +// ====== JNPF 后端原版 prompt(直接复用)====== +const GEN_MODEL_COMPNENT = '- input - textarea - inputNumber - switch - radio - checkbox - ' + + 'select - datePicker - timePicker - uploadFile - uploadImg - colorPicker - rate - slider - editor - ' + + 'depSelect - posSelect - userSelect - roleSelect - areaSelect - signature - sign - location'; + +const GEN_MODEL_QUETION = `根据当前业务需求,设计相应的表单结构。请仅返回JSON数据,不包含其他任何形式的内容。预期结果是一个JSON数组,因涉及不同表单需求,故可能包含多个表单对象。请确保命名规避数据库与编程保留字。 +所需表单应充分利用以下组件列表进行设计: ${GEN_MODEL_COMPNENT}。 +参考给定的JSON格式,属性包含:中文名(tableTitle)、英文名(tableName)、是否主表(isMain, true/false)、字段列表(fields);字段列表是一个json数组,包含字段英文名(fieldName)、字段中文名(fieldTitle)、数据库类型(fieldDbType)、前端组件(fieldComponent)、字典选项(fieldOptions, 仅 radio/checkbox/select/cascader/treeSelect 必填, 格式 {id, fullName})。 +创建表单结构,示例如下: [ + { + "tableTitle": "商城订单", + "tableName": "online_order_form", + "isMain": true, + "fields": [ + {"fieldTitle": "订单编号", "fieldName": "order_id", "fieldDbType": "varchar", "fieldComponent": "input"}, + {"fieldTitle": "订单状态", "fieldName": "order_status", "fieldDbType": "int", "fieldComponent": "radio", + "fieldOptions": [{"id": "1", "fullName": "未付款"}, {"id": "2", "fullName": "已付款"}]} + ] + }, + { + "tableTitle": "订单商品明细", + "tableName": "order_item_details", + "isMain": false, + "fields": [ + {"fieldTitle": "商品名称", "fieldName": "product_name", "fieldDbType": "varchar", "fieldComponent": "input"}, + {"fieldTitle": "商品数量", "fieldName": "quantity", "fieldDbType": "int", "fieldComponent": "inputNumber"} + ] + } +] +请依据实际业务逻辑,合理选择组件与字段类型,确保设计的表单既能满足数据收集需求,又便于用户操作。`; + +// ====== 加载 buildFormData ====== +const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'; +let buildFormDataSrc = readFileSync(`${WEB_SRC}/components/FormGenerator/src/helper/formUtils.ts`, 'utf-8'); +const JNPF_UTILS_UUID = '/home/ubuntu/ccWorkDir/web/packages/jnpf/utils/src/helpers/uuid.ts'; +buildFormDataSrc = buildFormDataSrc + .replace(/from\s+['"]#\/(.+?)['"]/g, (_, p) => `from '${WEB_SRC}/${p}'`) + .replace(/from\s+['"]@jnpf\/utils['"]/g, `from '${JNPF_UTILS_UUID}'`) + .replace(/import\s*\{\s*cloneDeep\s*\}\s*from\s+['"]lodash-es['"];?/g, + `const cloneDeep = (x) => structuredClone(x);`); + +const tmpDir = `${tmpdir()}/dacli-ai-jnpf-prompt-${Date.now()}`; +mkdirSync(tmpDir, { recursive: true }); +writeFileSync(`${tmpDir}/formUtils.ts`, buildFormDataSrc); +const { buildFormData } = await import(pathToFileURL(`${tmpDir}/formUtils.ts`).href); +console.log('✅ buildFormData 加载成功\n'); + +// ====== 测试 1: 简单表单(带 select)====== +const testCases = [ + { + name: '简单客户表', + userInput: '当前业务需求是: 做一个简单的客户管理表,包含客户姓名、联系电话、客户类型(个人/企业)、备注。', + }, + { + name: '主+子表(订单+明细)', + userInput: '当前业务需求是: 做一个商城订单管理。主表存订单(订单号、客户姓名、订单状态未付款/已付款/已发货),子表存订单商品明细(商品名称、商品数量)。', + }, +]; + +for (const tc of testCases) { + console.log(`\n========================================`); + console.log(`=== 测试: ${tc.name} ===`); + console.log(`========================================`); + + const start = Date.now(); + // 用 Anthropic Messages API 格式(用户 API 走这个) + const resp = await fetch(`${BASE_URL}/v1/messages`, { + method: 'POST', + headers: { + 'x-api-key': AUTH_TOKEN, + 'anthropic-version': '2023-06-01', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model: MODEL, + max_tokens: 2000, + system: GEN_MODEL_QUETION, // Anthropic 格式:system 单独字段 + messages: [ + { role: 'user', content: tc.userInput }, + ], + }), + }); + const ms = Date.now() - start; + + if (!resp.ok) { + const errText = await resp.text(); + console.log(`❌ HTTP ${resp.status} (${ms}ms)`); + console.log(' error:', errText.slice(0, 300)); + continue; + } + console.log(`✅ HTTP 200 (${ms}ms)`); + + const aiResp = await resp.json(); + // Anthropic 格式:content 是数组,每项 {type: 'text', text: '...'} + const text = aiResp.content + ?.filter((b: any) => b.type === 'text') + .map((b: any) => b.text) + .join('\n') || ''; + console.log(` usage: ${JSON.stringify(aiResp.usage)}`); + console.log(` model: ${aiResp.model}, stop_reason: ${aiResp.stop_reason}`); + + // 提取 JSON + const startIdx = text.indexOf('['); + const endIdx = text.lastIndexOf(']'); + if (startIdx === -1) { + console.log('❌ 响应中没找到 JSON 数组'); + console.log(' text:', text.slice(0, 200)); + continue; + } + const jsonStr = text.slice(startIdx, endIdx + 1); + let aiList; + try { + aiList = JSON.parse(jsonStr); + } catch (e: any) { + console.log('❌ JSON parse 失败:', e.message); + continue; + } + console.log(` AI 返回 ${aiList.length} 张表:`); + for (const t of aiList) { + console.log(` - [${t.isMain ? '主' : '子'}] ${t.tableName} "${t.tableTitle}" (${t.fields?.length || 0} 字段)`); + for (const f of t.fields || []) { + const opts = f.fieldOptions ? ` [${f.fieldOptions.length} 选项]` : ''; + console.log(` ${f.fieldName} ${f.fieldComponent} "${f.fieldTitle}"${opts}`); + } + } + + // 喂给 buildFormData + // 确保 isMain 正确(JNPF 后端靠 setIsMain(0,i==0) 强制设置) + const normalized = aiList.map((t: any, i: number) => ({ + ...t, + isMain: i === 0, + })); + const formDataResult = buildFormData(normalized); + const formData = JSON.parse(formDataResult.formData); + + console.log(`\n buildFormData 输出:`); + console.log(` fields 数: ${formData.fields.length}`); + console.log(` formConf keys: ${Object.keys(formData).length}`); + console.log(` defaultDataForm 顶层 keys: ${Object.keys(formDataResult).filter((k: string) => k !== 'formData').length}`); + + // 抽样检查 + const f0 = formData.fields[0]; + console.log(` 第一个 field:`); + console.log(` __vModel__: ${f0.__vModel__}`); + console.log(` __config__ keys (${Object.keys(f0.__config__).length}): ${Object.keys(f0.__config__).join(', ')}`); + console.log(` formId: ${f0.__config__.formId}`); + console.log(` renderKey: ${f0.__config__.renderKey}`); + console.log(` isSubTable: ${f0.__config__.isSubTable}`); + + // select 字段验证 + const selectField = formData.fields.find((f: any) => + ['select', 'radio', 'checkbox'].includes(f.options?.[0]?.id?.toString() ? f.__config__?.jnpfKey : '')); + // 简化:找 options 长度 > 0 的 + const fieldWithOpts = formData.fields.find((f: any) => Array.isArray(f.options) && f.options.length > 0); + if (fieldWithOpts) { + console.log(` 含 options 的字段: ${fieldWithOpts.__vModel__} options: ${JSON.stringify(fieldWithOpts.options)}`); + } else { + console.log(` (本例无含 options 的字段)`); + } + + // 检查主子表(如果有) + if (aiList.length > 1) { + const subTable = formData.fields.find((f: any) => f.__config__.isSubTable); + if (subTable) { + console.log(` 子表字段: ${subTable.__vModel__} parentVModel: ${subTable.__config__.parentVModel}`); + } + } +} + +console.log('\n\n=== 全部完成 ==='); +console.log('✅ 结论: 用 JNPF 原版 GEN_MODEL_QUETION prompt + 直接 AI API'); +console.log(' 可以完整替代 JNPF backend 的 ai/form 端点'); +console.log(' 返回的 aiModelList 直接喂给 buildFormData 即可'); diff --git a/tests/test-import-buildformdata.mjs b/tests/test-import-buildformdata.mjs new file mode 100644 index 0000000..c217338 --- /dev/null +++ b/tests/test-import-buildformdata.mjs @@ -0,0 +1,59 @@ +// 用 tsx 跑 + 自定义 #/ alias 解析 +import { pathToFileURL } from 'url'; +import { resolve as pathResolve, dirname } from 'path'; +import { existsSync } from 'fs'; + +const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'; + +// 自定义 resolve hook +export async function resolve(specifier, context, nextResolve) { + // 处理 #/ 别名 + if (specifier.startsWith('#/')) { + const relPath = specifier.slice(2); // 去掉 #/ + const absPath = pathResolve(WEB_SRC, relPath); + return nextResolve(pathToFileURL(absPath).href, context); + } + return nextResolve(specifier, context); +} + +console.log('=== Test: buildFormData via tsx + #/ resolver ==='); +try { + const mod = await import('/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src/components/FormGenerator/src/helper/formUtils.ts'); + console.log('✅ Imported! Exports:', Object.keys(mod)); + + const aiModelList = [ + { + tableTitle: '客户表', + tableName: 'customer', + isMain: true, + fields: [ + { fieldTitle: '姓名', fieldName: 'f_name', fieldComponent: 'input' }, + { fieldTitle: '电话', fieldName: 'f_phone', fieldComponent: 'input' }, + { fieldTitle: '状态', fieldName: 'f_status', fieldComponent: 'select', + fieldOptions: [{id: '1', fullName: '启用'}, {id: '0', fullName: '禁用'}] }, + ], + }, + ]; + + const result = mod.buildFormData(aiModelList); + const formData = JSON.parse(result.formData); + console.log('✅ buildFormData 跑了!'); + console.log(' fields 数:', formData.fields.length); + console.log(' 第一个 field 的 __vModel__:', formData.fields[0].__vModel__); + console.log(' __config__ keys (共', Object.keys(formData.fields[0].__config__).length, '个):', Object.keys(formData.fields[0].__config__)); + console.log(' ⭐ formId:', formData.fields[0].__config__.formId); + console.log(' ⭐ renderKey:', formData.fields[0].__config__.renderKey); + console.log(' ⭐ isSubTable:', formData.fields[0].__config__.isSubTable); + + const statusField = formData.fields.find(f => f.__vModel__ === 'f_status'); + console.log(' select 组件 options:', JSON.stringify(statusField?.options)); + + // 看顶层 defaultDataForm + console.log('\n defaultDataForm 顶层 keys:', Object.keys(result).filter(k => k !== 'formData')); + console.log(' tables:', result.tables); + console.log(' webType:', result.webType); + console.log(' state:', result.state); +} catch (e) { + console.error('❌ Failed:', e.message); + console.error('Stack:', e.stack?.split('\n').slice(0, 5).join('\n')); +} diff --git a/tests/test-import-buildformdata.ts b/tests/test-import-buildformdata.ts new file mode 100644 index 0000000..6ade24b --- /dev/null +++ b/tests/test-import-buildformdata.ts @@ -0,0 +1,92 @@ +// 预处理 formUtils.ts:把 #/ 路径替换成绝对路径,然后 import +import { readFileSync, writeFileSync, mkdirSync } from 'fs'; +import { dirname, resolve } from 'path'; +import { pathToFileURL } from 'url'; +import { tmpdir } from 'os'; + +const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'; +const SRC = `${WEB_SRC}/components/FormGenerator/src/helper/formUtils.ts`; + +// 1. 读源 +let src = readFileSync(SRC, 'utf-8'); + +// 2. 替换 #/ 为绝对路径,@jnpf/utils 替换成 web 端本地 uuid.ts(避开 Vite env 依赖) +const JNPF_UTILS_UUID = '/home/ubuntu/ccWorkDir/web/packages/jnpf/utils/src/helpers/uuid.ts'; +src = src.replace(/from\s+['"]#\/(.+?)['"]/g, (_, p) => `from '${WEB_SRC}/${p}'`); +src = src.replace(/from\s+['"]@jnpf\/utils['"]/g, `from '${JNPF_UTILS_UUID}'`); +// 3. lodash-es 替换成 Node 内置 structuredClone(formUtils.ts 只用 cloneDeep) +src = src.replace(/import\s*\{\s*cloneDeep\s*\}\s*from\s+['"]lodash-es['"];?/g, + `const cloneDeep = (x) => structuredClone(x);`); + +console.log('=== 替换后的 formUtils.ts 头 10 行 ==='); +console.log(src.split('\n').slice(0, 15).join('\n')); +console.log('...\n'); + +// 3. 写到 /tmp +const tmpDir = `${tmpdir()}/dacli-test-${Date.now()}`; +mkdirSync(tmpDir, { recursive: true }); +const tmpFile = `${tmpDir}/formUtils-fixed.ts`; +writeFileSync(tmpFile, src); +console.log('=== 写到:', tmpFile, '===\n'); + +// 4. 动态 import +try { + const mod = await import(pathToFileURL(tmpFile).href); + console.log('✅ Imported! Exports:', Object.keys(mod)); + + const aiModelList = [ + { + tableTitle: '客户表', + tableName: 'customer', + isMain: true, + fields: [ + { fieldTitle: '姓名', fieldName: 'f_name', fieldComponent: 'input' }, + { fieldTitle: '电话', fieldName: 'f_phone', fieldComponent: 'input' }, + { fieldTitle: '状态', fieldName: 'f_status', fieldComponent: 'select', + fieldOptions: [{id: '1', fullName: '启用'}, {id: '0', fullName: '禁用'}] }, + ], + }, + ]; + + const result = mod.buildFormData(aiModelList); + const formData = JSON.parse(result.formData); + + console.log('\n✅ buildFormData 调用成功!'); + console.log(' defaultDataForm 顶层 keys:', Object.keys(result).filter(k => k !== 'formData')); + console.log(' formData.fields 数:', formData.fields.length); + console.log(' formConf 顶层 keys (前 10):', Object.keys(formData).slice(0, 10)); + + console.log('\n=== 第一个 field 详细结构 ==='); + const f0 = formData.fields[0]; + console.log(' __vModel__:', f0.__vModel__); + console.log(' __config__ 键数:', Object.keys(f0.__config__).length); + console.log(' __config__ keys:', Object.keys(f0.__config__).join(', ')); + console.log(' ⭐ formId:', f0.__config__.formId); + console.log(' ⭐ renderKey:', f0.__config__.renderKey); + console.log(' ⭐ isSubTable:', f0.__config__.isSubTable); + console.log(' ⭐ tag:', f0.__config__.tag); + console.log(' ⭐ visibility:', f0.__config__.visibility); + + console.log('\n=== select 字段的 options ==='); + const statusField = formData.fields.find(f => f.__vModel__ === 'f_status'); + console.log(' status field options:', JSON.stringify(statusField?.options)); + console.log(' status field dataType:', statusField?.__config__?.dataType); + + console.log('\n=== 顶层 defaultDataForm 详情 ==='); + console.log(' webType:', result.webType, '(=2 表单+列表)'); + console.log(' state:', result.state, '(=1 已发布)'); + console.log(' type:', result.type, '(=1 自定义)'); + console.log(' dbLinkId:', result.dbLinkId, '(="0" 主库)'); + console.log(' tables:', result.tables); + console.log(' columnData:', result.columnData); + + console.log('\n=== 验证 BS-51/BS-54 修复 ==='); + console.log(' ✅ formId 存在:', !!f0.__config__.formId); + console.log(' ✅ renderKey 存在:', !!f0.__config__.renderKey); + console.log(' ✅ isSubTable 存在:', f0.__config__.isSubTable === false); + console.log(' ✅ select 组件 options 存在:', Array.isArray(statusField?.options)); + console.log(' ✅ options 不为空:', (statusField?.options?.length ?? 0) > 0); +} catch (e) { + console.error('❌ Failed:', e.message); + console.error('Stack:', e.stack?.split('\n').slice(0, 8).join('\n')); +}