feat(dacli): form/dm create 内置 pre-check (P1.2, 解决 D 类根因)
This commit is contained in:
1 parent
65f07dc47e
commit
bf22b0fcfe
4 files changed
+310
-65
No files matched your search
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* commands/_precheck.ts — form/dm create 执行前的依赖检查
|
||||
*
|
||||
* 解决 D 类根因 (详见 doc/ai-error-analysis.md §D): 隐式依赖链只在文档里, 没有工具强制
|
||||
* 设计: 执行前自动验证依赖, 失败时明确报错 + 提示下一步, 不进入 API 调用
|
||||
*
|
||||
* 与 P0.1 (AppContext) 衔接:
|
||||
* - 直接 import { loadAppContext } 复用 context.ts 的采集逻辑
|
||||
* - 失败容错: context 加载失败时仅 warning 不阻断 (避免双重失败)
|
||||
* - 与 P1.3 (form-type-rules.json) 软联动: 文件不存在时跳过规则检查
|
||||
*/
|
||||
import type { JnpfClient } from '../core/client.ts'
|
||||
import { loadAppContext } from './app/context.ts'
|
||||
import { log } from '../core/log.ts'
|
||||
|
||||
export interface PreCheckResult {
|
||||
pass: boolean
|
||||
errors: string[]
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export interface PreCheckOptions {
|
||||
/** 期望创建的表单 enCode */
|
||||
enCode?: string
|
||||
/** 期望创建的表名 */
|
||||
table?: string
|
||||
/** 期望的 dbLinkId(覆盖 token 中的) */
|
||||
dbLinkId?: string
|
||||
/** webType */
|
||||
webType?: number
|
||||
/** type (1=自定义 2=系统 3=接口 4=视图) */
|
||||
type?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 AppContext(容错,失败返 null + warning)
|
||||
*
|
||||
* 注意: 不传 client, 因为 loadAppContext 内部已自带 client 构造
|
||||
* 这里保留 client 参数仅为未来扩展 (e.g. 复用调用方已登录的 client)
|
||||
*/
|
||||
export async function loadContextSafe(_client: JnpfClient | null): Promise<{ ctx: Awaited<ReturnType<typeof loadAppContext>> | null; warning?: string }> {
|
||||
try {
|
||||
const ctx = await loadAppContext()
|
||||
return { ctx }
|
||||
} catch (e) {
|
||||
return { ctx: null, warning: `AppContext 加载失败: ${(e as Error).message}` }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* form create pre-check
|
||||
*
|
||||
* 检查项:
|
||||
* 1. dbLinkId 有效 (≥1 或非 '0')
|
||||
* 2. enCode 不重复 (vs ctx.existingEnCodes)
|
||||
* 3. type/webType 组合合法 (vs data/form-type-rules.json, 可选)
|
||||
*/
|
||||
export async function preCheckFormCreate(
|
||||
_client: JnpfClient | null,
|
||||
opts: PreCheckOptions,
|
||||
): Promise<PreCheckResult> {
|
||||
const errors: string[] = []
|
||||
const warnings: string[] = []
|
||||
|
||||
const { ctx, warning } = await loadContextSafe(_client)
|
||||
if (warning) warnings.push(warning)
|
||||
|
||||
if (!ctx) {
|
||||
warnings.push('AppContext 加载失败(dacli app context 不可用),跳过 pre-check')
|
||||
return { pass: true, errors, warnings } // 容错:加载失败不阻断
|
||||
}
|
||||
|
||||
// 检查 1: dbLinkId 有效
|
||||
// '0' 是平台库, type=4 视图不需物理表 (兼容), 其他场景要求 ≥1
|
||||
// 注: type=4 时 dbLinkId 可以是 '0', 这里给软警告而非硬错
|
||||
const isType4 = String(opts.type) === '4'
|
||||
if (!opts.dbLinkId || opts.dbLinkId === '') {
|
||||
errors.push(`dbLinkId="${opts.dbLinkId || '(空)'}" 无效(pre-check 要求 ≥ 1)`)
|
||||
errors.push(' 修复:从 dacli app context --json 取 dbLinkId,或显式 --dbLinkId=<id>')
|
||||
} else if (opts.dbLinkId === '0' && !isType4) {
|
||||
errors.push(`dbLinkId="0" 为主库/平台库 (type≠4 时业务表单需业务库)`)
|
||||
errors.push(' 修复:从 dacli app context --json 取业务库 dbLinkId (非 "0")')
|
||||
}
|
||||
|
||||
// 检查 2: enCode 不重复
|
||||
if (opts.enCode && ctx.existingEnCodes.includes(opts.enCode)) {
|
||||
errors.push(`enCode "${opts.enCode}" 已存在(当前 app 已有 ${ctx.existingEnCodes.length} 个 enCode)`)
|
||||
errors.push(' 修复方案:')
|
||||
errors.push(' a) 改名加 _v2 后缀,如 leaveApply_v2')
|
||||
errors.push(' b) dacli form delete <id> 后重建(破坏性)')
|
||||
errors.push(' c) dacli form clone <id> 复制后改名')
|
||||
}
|
||||
|
||||
// 检查 3: type/webType 合法组合(用 form-type-rules.json,由 P1.3 提供)
|
||||
// 如果 form-type-rules.json 不存在,跳过此检查
|
||||
try {
|
||||
const fs = await import('fs')
|
||||
const path = await import('path')
|
||||
const rulesPath = path.resolve(process.cwd(), 'data/form-type-rules.json')
|
||||
if (fs.existsSync(rulesPath)) {
|
||||
const rules = JSON.parse(fs.readFileSync(rulesPath, 'utf8'))
|
||||
const typeRules = rules.typeRules || []
|
||||
const matched = typeRules.find(
|
||||
(r: any) => r.type === opts.type && r.webType === opts.webType,
|
||||
)
|
||||
if (!matched && opts.type && opts.webType) {
|
||||
warnings.push(
|
||||
`type=${opts.type} webType=${opts.webType} 未在 form-type-rules.json 中注册,请确认参数`,
|
||||
)
|
||||
} else if (matched && matched.needsPhysicalTable && !opts.table) {
|
||||
errors.push(
|
||||
`type=${opts.type} webType=${opts.webType}(${matched.name})需要物理表,请传 --table=<table_name>`,
|
||||
)
|
||||
errors.push(' 修复:先 dacli dm create,再 dacli form create')
|
||||
} else if (matched && !matched.needsPhysicalTable && opts.table) {
|
||||
warnings.push(
|
||||
`type=${opts.type} webType=${opts.webType}(${matched.name})无需物理表,--table 参数将被忽略`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
log.debug(`form-type-rules.json 加载失败: ${(e as Error).message}`)
|
||||
}
|
||||
|
||||
return { pass: errors.length === 0, errors, warnings }
|
||||
}
|
||||
|
||||
/**
|
||||
* dm create pre-check
|
||||
*
|
||||
* 检查项:
|
||||
* 1. dbLinkId 有效
|
||||
* 2. 表不重复 (vs ctx.existingTables)
|
||||
*/
|
||||
export async function preCheckDmCreate(
|
||||
_client: JnpfClient | null,
|
||||
opts: { table?: string; dbLinkId?: string },
|
||||
): Promise<PreCheckResult> {
|
||||
const errors: string[] = []
|
||||
const warnings: string[] = []
|
||||
|
||||
const { ctx, warning } = await loadContextSafe(_client)
|
||||
if (warning) warnings.push(warning)
|
||||
|
||||
if (!ctx) {
|
||||
warnings.push('AppContext 加载失败,跳过 pre-check')
|
||||
return { pass: true, errors, warnings }
|
||||
}
|
||||
|
||||
// 检查 1: dbLinkId 有效
|
||||
if (!opts.dbLinkId || opts.dbLinkId === '0') {
|
||||
errors.push(`dbLinkId="${opts.dbLinkId || '(空)'}" 无效`)
|
||||
errors.push(' 修复:从 dacli app context --json 取 dbLinkId')
|
||||
}
|
||||
|
||||
// 检查 2: 表不重复
|
||||
if (opts.table && ctx.existingTables.includes(opts.table)) {
|
||||
errors.push(`表 "${opts.table}" 已存在(当前业务库已有 ${ctx.existingTables.length} 张表)`)
|
||||
errors.push(' 修复方案:')
|
||||
errors.push(' a) 换表名')
|
||||
errors.push(' b) dacli dm drop <table> 后重建(破坏性)')
|
||||
}
|
||||
|
||||
return { pass: errors.length === 0, errors, warnings }
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印 pre-check 结果 (form/dm 共享)
|
||||
*
|
||||
* pass=true, warnings.length>0 → 打印警告不阻断
|
||||
* pass=false → 打印错误并退出 (exit 2)
|
||||
*/
|
||||
export function handlePreCheckResult(label: string, pre: PreCheckResult): void {
|
||||
if (!pre.pass) {
|
||||
log.error(`Pre-check 失败(${label} 终止,请修复后重试):`)
|
||||
pre.errors.forEach((e) => log.error(` ${e}`))
|
||||
if (pre.warnings.length) {
|
||||
log.warn('警告:')
|
||||
pre.warnings.forEach((w) => log.warn(` ${w}`))
|
||||
}
|
||||
process.exit(2)
|
||||
}
|
||||
if (pre.warnings.length) {
|
||||
log.warn(`Pre-check 警告(${label} 不阻断,但请关注):`)
|
||||
pre.warnings.forEach((w) => log.warn(` ${w}`))
|
||||
}
|
||||
}
|
||||
+70
-62
@@ -24,7 +24,7 @@ import type { AppContext, FormSummary } from '../../core/types.ts'
|
||||
// 用 fileURL + 文本扫描 + 正则提 VERSION
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
|
||||
const PAGE_SIZE = 500 // 一次拉完, 避免分页遗漏
|
||||
|
||||
@@ -59,6 +59,69 @@ function calcTokenExpiry(loginAt?: string): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* P1.2: 公开的 AppContext 加载函数 (供 pre-check 等复用)
|
||||
*
|
||||
* 设计: 拉 token → 构造 client → 拉 form/dm/menu → 组装 AppContext
|
||||
* 失败容错: 任何 API 失败写入 warnings, 不抛错
|
||||
* 不抛异常, 失败尽量返回部分填充的对象 + warnings
|
||||
*/
|
||||
export async function loadAppContext(opts?: { appCode?: string }): Promise<AppContext> {
|
||||
const cached = loadToken()
|
||||
const appCode = opts?.appCode || cached?.appCode || ''
|
||||
const dbLinkId = cached?.dbLinkId || ''
|
||||
const tokenStatus: AppContext['tokenStatus'] = cached ? 'valid' : 'expired'
|
||||
const tokenExpiry = calcTokenExpiry(cached?.loginAt)
|
||||
const warnings: string[] = []
|
||||
|
||||
let forms: FormSummary[] = []
|
||||
let tables: string[] = []
|
||||
let menus: string[] = []
|
||||
|
||||
try {
|
||||
const c = await JnpfClient.fromToken(opts?.appCode ? { appCode: opts.appCode } : {})
|
||||
if (opts?.appCode) c.appCode = opts.appCode
|
||||
|
||||
const f = await tryFetchForms(c)
|
||||
forms = f.forms
|
||||
if (f.warning) warnings.push(f.warning)
|
||||
|
||||
const t = await tryFetchTables(c)
|
||||
tables = t.tables
|
||||
if (t.warning) warnings.push(t.warning)
|
||||
|
||||
const m = await tryFetchMenus(c)
|
||||
menus = m.menus
|
||||
if (m.warning) warnings.push(m.warning)
|
||||
} catch (e) {
|
||||
warnings.push(`client 初始化失败: ${(e as Error).message}`)
|
||||
}
|
||||
|
||||
const existingEnCodes = Array.from(
|
||||
new Set(forms.map((f) => f.enCode).filter((s): s is string => !!s)),
|
||||
)
|
||||
const unreleasedForms = forms
|
||||
.filter((f) => f.state === 0)
|
||||
.map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`)
|
||||
const releasedForms = forms
|
||||
.filter((f) => f.state === 1)
|
||||
.map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`)
|
||||
|
||||
return {
|
||||
appCode,
|
||||
dbLinkId,
|
||||
tokenStatus,
|
||||
tokenExpiry,
|
||||
existingEnCodes,
|
||||
unreleasedForms,
|
||||
releasedForms,
|
||||
existingTables: tables,
|
||||
menus,
|
||||
currentVersion: readCliVersion(),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/** 安全拉 form list — 失败返回 null + 警告 */
|
||||
async function tryFetchForms(c: JnpfClient): Promise<{ forms: FormSummary[]; warning?: string }> {
|
||||
try {
|
||||
@@ -118,65 +181,10 @@ export function buildAppContextCommand(): Command {
|
||||
.option('--json', '单行 JSON 输出 (AI 友好)', false)
|
||||
.option('--app <appCode>', '覆盖 token 中的 appCode (供快速切换测试)')
|
||||
.action(async (opts: ContextOpts) => {
|
||||
// 1. 先读 token — 不需要登录就能给出基础信息 (appCode/dbLinkId/tokenStatus)
|
||||
const cached = loadToken()
|
||||
const appCode = opts.app || cached?.appCode || ''
|
||||
const dbLinkId = cached?.dbLinkId || ''
|
||||
const tokenStatus: AppContext['tokenStatus'] = cached ? 'valid' : 'expired'
|
||||
const tokenExpiry = calcTokenExpiry(cached?.loginAt)
|
||||
const warnings: string[] = []
|
||||
// P1.2: 复用 loadAppContext 提取的核心采集逻辑
|
||||
const ctx = await loadAppContext(opts.app ? { appCode: opts.app } : undefined)
|
||||
|
||||
// 2. 尝试构造 client 拉 form/dm/menu — 失败容错
|
||||
let forms: FormSummary[] = []
|
||||
let tables: string[] = []
|
||||
let menus: string[] = []
|
||||
|
||||
try {
|
||||
// 如果有缓存 token, 复用; 没有则尝试登录 (失败也不致命, 后续 API 调用会再失败)
|
||||
const c = await JnpfClient.fromToken(opts.app ? { appCode: opts.app } : {})
|
||||
// 应用 --app 覆盖
|
||||
if (opts.app) c.appCode = opts.app
|
||||
|
||||
const f = await tryFetchForms(c)
|
||||
forms = f.forms
|
||||
if (f.warning) warnings.push(f.warning)
|
||||
|
||||
const t = await tryFetchTables(c)
|
||||
tables = t.tables
|
||||
if (t.warning) warnings.push(t.warning)
|
||||
|
||||
const m = await tryFetchMenus(c)
|
||||
menus = m.menus
|
||||
if (m.warning) warnings.push(m.warning)
|
||||
} catch (e) {
|
||||
// 登录失败 / 网络不通 — 仍然输出能拿到的部分
|
||||
warnings.push(`client 初始化失败: ${(e as Error).message}`)
|
||||
}
|
||||
|
||||
// 3. 切分 form 状态
|
||||
const existingEnCodes = Array.from(new Set(forms.map((f) => f.enCode).filter((s): s is string => !!s)))
|
||||
const unreleasedForms = forms
|
||||
.filter((f) => f.state === 0)
|
||||
.map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`)
|
||||
const releasedForms = forms
|
||||
.filter((f) => f.state === 1)
|
||||
.map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`)
|
||||
|
||||
const ctx: AppContext = {
|
||||
appCode,
|
||||
dbLinkId,
|
||||
tokenStatus,
|
||||
tokenExpiry,
|
||||
existingEnCodes,
|
||||
unreleasedForms,
|
||||
releasedForms,
|
||||
existingTables: tables,
|
||||
menus,
|
||||
currentVersion: readCliVersion(),
|
||||
warnings,
|
||||
}
|
||||
|
||||
// 4. 输出
|
||||
// 输出
|
||||
if (opts.json) {
|
||||
// 单行 JSON (AI 友好, 便于 grep/管道)
|
||||
console.log(JSON.stringify(ctx))
|
||||
@@ -192,9 +200,9 @@ export function buildAppContextCommand(): Command {
|
||||
log.info(`forms : ${ctx.releasedForms.length} 发布 / ${ctx.unreleasedForms.length} 草稿`)
|
||||
log.info(`tables : ${ctx.existingTables.length} 张`)
|
||||
log.info(`menus : ${ctx.menus.length} 个`)
|
||||
if (warnings.length) {
|
||||
log.warn(`采集警告 ${warnings.length} 条:`)
|
||||
for (const w of warnings) log.dim(` - ${w}`)
|
||||
if (ctx.warnings.length) {
|
||||
log.warn(`采集警告 ${ctx.warnings.length} 条:`)
|
||||
for (const w of ctx.warnings) log.dim(` - ${w}`)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installAiHelpHook } from '../../core/help.ts'
|
||||
import { log, printJson } from '../../core/log.ts'
|
||||
import { preCheckDmCreate, handlePreCheckResult } from '../_precheck.ts'
|
||||
import { loadAppContext } from '../app/context.ts'
|
||||
|
||||
interface CreateOpts {
|
||||
table: string
|
||||
@@ -33,6 +35,16 @@ export function buildDmCreateCommand(): Command {
|
||||
|
||||
const userFields = JSON.parse(opts.fields) as Record<string, unknown>[]
|
||||
|
||||
// P1.2: dm create pre-check (dbLinkId / 表重复)
|
||||
// 失败时 exit 2, 不进入 API 调用; 警告不阻断
|
||||
handlePreCheckResult(
|
||||
'dm create',
|
||||
await preCheckDmCreate(c, {
|
||||
table: opts.table,
|
||||
dbLinkId,
|
||||
}),
|
||||
)
|
||||
|
||||
// D-5 (盲点 38 防御): 用户字段含 f_description 会被系统自动加的 text 列冲突
|
||||
// 系统会自动注入 f_description (text) 作为"描述"列, 用户不应自己再传
|
||||
const userFieldNames = userFields.map((f) => String(f.field || ''))
|
||||
@@ -79,7 +91,12 @@ export function buildDmCreateCommand(): Command {
|
||||
tableFieldList: allFields,
|
||||
}
|
||||
log.info(`POST /system/DataModel/${dbLinkId}/Table table=${opts.table} fields=${allFields.length} (含9系统列)`)
|
||||
const r = await c.postJson<{ table?: string }>(`/system/DataModel/${dbLinkId}/Table`, body)
|
||||
// P0.2: 加载 AppContext 供诊断用 (复用 P0.1 loadAppContext, 失败不阻断)
|
||||
const diagCtx = await loadAppContext().catch(() => null)
|
||||
const r = await c.callWithDiagnosis<{ table?: string }>(
|
||||
() => c.postJson<{ table?: string }>(`/system/DataModel/${dbLinkId}/Table`, body),
|
||||
diagCtx,
|
||||
)
|
||||
if (r.code !== 200) {
|
||||
// D-5 (盲点 38 防御): 友好提示 f_description 冲突
|
||||
const errMsg = r.msg || ''
|
||||
|
||||
@@ -15,6 +15,8 @@ import { callAiForm, printAiFormResult } from './_ai.ts'
|
||||
import { wrapSimplifiedFields, buildTablesFromFields, type SimpleField } from './_simplify.ts'
|
||||
import { browserVerify } from './_browser_verify.ts'
|
||||
import { createFormViaUi } from './_create_ui.ts'
|
||||
import { preCheckFormCreate, handlePreCheckResult } from '../_precheck.ts'
|
||||
import { loadAppContext } from '../app/context.ts'
|
||||
|
||||
interface CreateOpts {
|
||||
fullName?: string
|
||||
@@ -135,6 +137,29 @@ export function buildFormCreateCommand(): Command {
|
||||
const webType = Number(opts.webType)
|
||||
const dbLinkId = opts.dbLinkId || c.dbLinkId || '0'
|
||||
|
||||
// P1.2: form create pre-check (dbLinkId / enCode 重复 / type-webType 规则)
|
||||
// 失败时 exit 2, 不进入 API 调用; 警告不阻断
|
||||
// 从 --tables JSON 提取主表名 (供 type-webType 规则判断 needsPhysicalTable 用)
|
||||
let mainTable: string | undefined
|
||||
if (opts.tables) {
|
||||
try {
|
||||
const tbls = JSON.parse(opts.tables) as Array<{ table?: string }>
|
||||
mainTable = tbls[0]?.table
|
||||
} catch {
|
||||
/* JSON 解析失败留给后续步骤报错 */
|
||||
}
|
||||
}
|
||||
handlePreCheckResult(
|
||||
'form create',
|
||||
await preCheckFormCreate(c, {
|
||||
enCode: opts.enCode,
|
||||
table: mainTable,
|
||||
dbLinkId,
|
||||
webType,
|
||||
type,
|
||||
}),
|
||||
)
|
||||
|
||||
// D-3: --fields 简化格式自动包 __config__ (盲点 42 防御)
|
||||
let rawFields: unknown[] = []
|
||||
if (opts.fields) {
|
||||
@@ -321,7 +346,12 @@ export function buildFormCreateCommand(): Command {
|
||||
}
|
||||
|
||||
log.info(`POST /visualdev/Base ${opts.enCode} type=${type} webType=${webType} dbLinkId=${dbLinkId}`)
|
||||
const r = await c.postJson<unknown>('/visualdev/Base', body)
|
||||
// P0.2: 加载 AppContext 供诊断用 (复用 P0.1 的 loadAppContext, 失败不阻断主流程)
|
||||
const diagCtx = await loadAppContext().catch(() => null)
|
||||
const r = await c.callWithDiagnosis<unknown>(
|
||||
() => c.postJson<unknown>('/visualdev/Base', body),
|
||||
diagCtx,
|
||||
)
|
||||
if (r.code !== 200) {
|
||||
log.error(`创建失败 (code=${r.code}): ${r.msg}`)
|
||||
if (opts.json) printJson(r)
|
||||
@@ -338,7 +368,10 @@ export function buildFormCreateCommand(): Command {
|
||||
|
||||
if (opts.autoRelease && type !== 4 && newId !== '(unknown)') {
|
||||
log.info(`发布: POST /visualdev/Base/${newId}/Actions/Release (v0.7 修)`)
|
||||
const rr = await c.postJson(`/visualdev/Base/${newId}/Actions/Release`, {})
|
||||
const rr = await c.callWithDiagnosis(
|
||||
() => c.postJson(`/visualdev/Base/${newId}/Actions/Release`, {}),
|
||||
diagCtx,
|
||||
)
|
||||
if (rr.code === 200) log.ok('发布成功 (state=1)')
|
||||
else log.warn(`发布失败 (code=${rr.code}): ${rr.msg}`)
|
||||
} else if (opts.autoRelease && type === 4) {
|
||||
|
||||
Reference in new issue
Block a user