Files
dacli/src/commands/form/export.ts
T
sswandClaude 7bf7762839 refactor(v0.11+): form clone + export 改用 webapi
Phase 1 审计 P0:
- form/clone release 调用 → loadVisualDev.release
- form/export getInfo 调用 → loadVisualDev.getInfo
- 累计 form 7 调用 webapi 化 (validate 1 + fixcolumndata 3 + bindflow 1 + clone 1 + export 1)

剩余 form 22 调用 - 16:
- form/import.ts (8 调用) - 最大
- form/codegen.ts (4 调用)
- form/create.ts (4 调用)

Co-Authored-By: Claude <[email protected]>
2026-06-25 15:12:29 +08:00

129 lines
6.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* commands/form/export.ts — 导出表单 JSON
*
* v0.7: 同时拉物理表 schema 存到 `_physicalSchema`,
* 解 #15 (web Form.vue tables[].fields 是 DB 实时查的, 不在 form JSON 里).
* 配合 import.ts 的 --autoTable 在目标库重建物理表.
*
* v0.8.2 修复盲点 #? (2026-06-19, tdd1 实战发现):
* - URL 拼写错: `Table/{t}/Fields` → 应为 **`Tables/{t}/Fields`** (复数, 跟 web 端 TableList/index.vue:184 一致)
* - 单数 `Table` 返回 404 (Content-Length: 0, JNPF 没这个端点)
* - 复数 `Tables` 返回 `{list: Field[]}` (不是 `{fields:[]}`)
* - 响应解析补 `{list: []}` 形态 (web `dataModel/TableList.vue:184` 真值)
*
* 关键: web 端 createDataModel 是单独走「数据建模」入口, form 设计器只引用表名;
* 迁移时若不带物理 schema 出来, import 后浏览器报 "该表单已删除".
*/
import { writeFileSync } from 'node:fs'
import { Command } from 'commander'
import { JnpfClient } from '../../core/client.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import type { FormDetail } from '../../core/types.ts'
import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
interface PhysicalSchemaEntry {
table: string
tableName?: string
typeId?: string
fields: Record<string, unknown>[]
}
interface ExportedForm extends FormDetail {
_physicalSchema?: PhysicalSchemaEntry[]
_exportedAt?: string
}
export function buildFormExportCommand(): Command {
const cmd = new Command('export')
.description('导出表单完整 schema 到文件 (v0.7 同时带物理表 schema, v0.8.2 修 URL Tables 复数 + 响应 {list} 解析)')
.argument('<id>', '表单 id')
.option('--out <path>', '输出文件路径 (默认 ./<enCode>.json)')
.option('--no-physical', '不带物理表 schema (默认会带, 兼容旧版导出)')
.action(async (id: string, opts: { out?: string; physical?: boolean }) => {
const c = await JnpfClient.fromToken()
// v0.11+ Phase 2: 改用 webapi (loadVisualDev.getInfo 替代 c.get)
await initWebapi(c)
const data = (await loadVisualDev.getInfo(id)) as ExportedForm
// v0.7: 拉物理表 schema (除非 --no-physical)
if (opts.physical !== false) {
try {
// FormDetail.tables 类型偏宽, 后端实际返 JSON string, 强转
const tables = data.tables
? (JSON.parse(typeof data.tables === 'string' ? data.tables : JSON.stringify(data.tables)) as Array<
Record<string, unknown>
>)
: []
const physical: PhysicalSchemaEntry[] = []
for (const t of tables) {
const tableName = String(t.table || '')
if (!tableName) continue
const dbLinkId = String(data.dbLinkId || '0')
try {
// v0.8.2 修复: URL 用 **Tables** (复数); 响应是 `{list: Field[]}` 形态 (web TableList 真值)
const fr = await c.get<
{ list?: Record<string, unknown>[]; fields?: Record<string, unknown>[] } | Record<string, unknown>[]
>(`/system/DataModel/${dbLinkId}/Tables/${tableName}/Fields`)
if (fr.code === 200) {
// 兼容 3 种形态: [{...}] / {list: [...]} / {fields: [...]}
let arr: Record<string, unknown>[] = []
if (Array.isArray(fr.data)) arr = fr.data
else {
const d = fr.data as { list?: unknown[]; fields?: unknown[] }
arr = (d.list || d.fields || []) as Record<string, unknown>[]
}
physical.push({
table: tableName,
tableName: t.tableName as string | undefined,
typeId: t.typeId as string | undefined,
fields: arr,
})
if (arr.length === 0) {
log.warn(` ↳ ${tableName} 字段返回 0 条 (Tables 端点有响应但无字段, 检查表是否真存在)`)
} else {
log.debug(` ↳ 拉 ${tableName} 字段 ×${arr.length}`)
}
} else {
log.warn(` ↳ ${tableName} 字段查失败 code=${fr.code}: ${fr.msg} (跳过)`)
}
} catch (e) {
log.warn(` ↳ ${tableName} 字段查异常: ${(e as Error).message} (跳过)`)
}
}
if (physical.length) {
data._physicalSchema = physical
data._exportedAt = new Date().toISOString()
}
} catch (e) {
log.warn(`物理表 schema 解析失败 (跳过): ${(e as Error).message}`)
}
}
const path = opts.out || `./${data.enCode || id}.json`
writeFileSync(path, JSON.stringify(data, null, 2), 'utf-8')
const sizeKb = (JSON.stringify(data).length / 1024).toFixed(1)
const phyCount = data._physicalSchema?.length ?? 0
const phyFields = data._physicalSchema?.reduce((s, p) => s + (p.fields?.length || 0), 0) ?? 0
log.ok(`已导出 ${data.enCode} → ${path} (${sizeKb} KB, 含 ${phyCount} 张物理表 schema, 共 ${phyFields} 字段)`)
if (!opts.out) printJson({ id, enCode: data.enCode, path, physicalTables: phyCount, physicalFields: phyFields })
})
installAiHelpHook(cmd, {
purpose: '导出表单完整 schema + 物理表 schema 到文件 (v0.7 解 #15). 用于 baseline 复刻 / 备份 / 跨应用迁移',
required: { '<id>': '源表单 id' },
optional: {
'--out': '输出路径, 默认 ./<enCode>.json',
'--no-physical': '不带物理表 schema (兼容旧导出格式)',
},
example: 'dacli form export 12345 --out=/tmp/leave.json',
source: { api: 'GET /api/visualdev/Base/:id + GET /api/system/DataModel/:linkId/Tables/:table/Fields' },
notes: [
'v0.7 默认带物理表 schema (_physicalSchema 字段), 配合 form import --autoTable 重建物理表',
'v0.8.2 修: URL 用 Tables (复数) 跟 web 端 TableList/index.vue 一致; 单数 Table 返回 404 空',
'web/.../formDesign/Form.vue tables[].fields 是 DB 实时查的, 不在 form JSON 里, 所以必须单独拉',
],
})
return cmd
}