diff --git a/src/commands/_auto_fix.ts b/src/commands/_auto_fix.ts new file mode 100644 index 0000000..4cb2f6e --- /dev/null +++ b/src/commands/_auto_fix.ts @@ -0,0 +1,442 @@ +/** + * commands/_auto_fix.ts — 自修正流水线 (dacli v2.0+) + * + * 三级修正: + * Silent — 确定性 100%, 静默修, 不通知 + * Assertive — 高置信, 自动修 + 回滚命令 + * Suggest — 不确定, 不修, 给候选 + * + * 设计原则: + * - 所有规则纯函数, 不依赖外部 AI 服务 + * - 修错了可以一行命令回滚 + * - 只防崩溃和体验极差, 不追求"完美配置" + */ + +import type { FixEntry } from '../core/logfile.ts' + +// ============================================================ +// Types +// ============================================================ + +export interface FormField { + field?: string + fieldName?: string + fieldTitle?: string + fieldDbType?: string + fieldComponent?: string + jnpfKey?: string + dataType?: string + dataLength?: string | number + dictType?: string + dictionaryType?: string + required?: boolean + format?: string + modelId?: string + columnOptions?: unknown[] + [key: string]: unknown +} + +export interface FixContext { + /** 已存在的表单列表 (用于 FK 匹配, 查 enCode→formId) */ + existingForms?: Array<{ id: string; enCode: string; fullName?: string }> + /** 已存在的字典列表 (用于 dictType 查重) */ + existingDicts?: Array<{ id: string; enCode: string; fullName?: string }> + /** 目标 formId (用于回滚命令生成) */ + formId?: string +} + +export interface FixResult { + fields: FormField[] + silent: FixEntry[] + assertive: FixEntry[] + suggestions: FixEntry[] +} + +// ============================================================ +// Silent fixes (100% certain, no notification) +// ============================================================ + +function fixJnpfKeyWhitelist(field: FormField): { field: FormField; entry?: FixEntry } { + const jnpfKey = field.jnpfKey || field.fieldComponent + if (!jnpfKey) return { field } + + // From JNPF JnpfKeyConsts + AiConstants.GEN_MODEL_COMPNENT + const WHITELIST = new Set([ + 'input', 'textarea', 'inputNumber', 'switch', 'radio', 'checkbox', + 'select', 'datePicker', 'timePicker', 'uploadFile', 'uploadImg', + 'colorPicker', 'rate', 'slider', 'editor', + 'depSelect', 'posSelect', 'userSelect', 'roleSelect', 'areaSelect', + 'signature', 'sign', 'location', 'relationForm', 'relationFlow', + 'popupSelect', 'popupTableSelect', 'treeSelect', 'cascader', + 'organizeSelect', 'currOrganize', 'currDept', 'currPosition', + 'createUser', 'createTime', 'modifyUser', 'modifyTime', + 'billRule', 'calculate', 'groupTitle', 'divider', 'button', + 'link', 'alert', 'card', 'row', 'tab', 'collapse', 'table', + 'qrcode', 'barcode', 'iframe', + ]) + + if (!WHITELIST.has(jnpfKey)) { + const original = jnpfKey + field.jnpfKey = 'input' + if (field.fieldComponent) field.fieldComponent = 'input' + return { + field, + entry: { + id: 'S4', + level: 'silent', + field: field.fieldName || field.field, + summary: `jnpfKey: ${original} → input (不在白名单, fallback)`, + from: original, + to: 'input', + }, + } + } + return { field } +} + +function fixChildTableComponents(field: FormField, isSubTable: boolean): { field: FormField; entry?: FixEntry } { + if (!isSubTable) return { field } + const jnpfKey = field.jnpfKey || field.fieldComponent + if (!jnpfKey) return { field } + + // JNPF VisualAiServiceImpl: 子表不能有 radio/checkbox → select + const toSelect = new Set(['radio', 'checkbox']) + // 子表不能有 textarea/link/button/alert/barcode/qrcode/editor → input + const toInput = new Set(['textarea', 'link', 'button', 'alert', 'barcode', 'qrcode', 'editor']) + + if (toSelect.has(jnpfKey)) { + const original = jnpfKey + field.jnpfKey = 'select' + if (field.fieldComponent) field.fieldComponent = 'select' + return { + field, + entry: { + id: 'S5', + level: 'silent', + field: field.fieldName || field.field, + summary: `子表 ${original} → select (子表不支持)`, + from: original, + to: 'select', + }, + } + } + + if (toInput.has(jnpfKey)) { + const original = jnpfKey + field.jnpfKey = 'input' + if (field.fieldComponent) field.fieldComponent = 'input' + return { + field, + entry: { + id: 'S5', + level: 'silent', + field: field.fieldName || field.field, + summary: `子表 ${original} → input (子表不支持)`, + from: original, + to: 'input', + }, + } + } + + return { field } +} + +function fixFkSuffix(field: FormField): { field: FormField | null; entry?: FixEntry } { + const name = field.fieldName || field.field || '' + if (name.toLowerCase().endsWith('_fk')) { + return { + field: null, // 丢弃 + entry: { + id: 'S10', + level: 'silent', + field: name, + summary: `${name}: _fk 后缀字段已丢弃 (JNPF 自动管理外键)`, + }, + } + } + return { field } +} + +// ============================================================ +// Assertive fixes (high confidence, auto-fix + rollback) +// ============================================================ + +function fixDatetimeToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } { + const dataType = (field.dataType || field.fieldDbType || '').toLowerCase() + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + + if ((dataType === 'datetime' || dataType === 'timestamp') && jnpfKey !== 'datePicker') { + const original = jnpfKey || 'none' + field.jnpfKey = 'datePicker' + if (field.fieldComponent) field.fieldComponent = 'datePicker' + if (!field.format) field.format = 'yyyy-MM-dd HH:mm:ss' + const fieldName = field.fieldName || field.field || '?' + return { + field, + entry: { + id: 'A2', + level: 'assertive', + field: fieldName, + summary: `${fieldName}: ${original} → datePicker (format=yyyy-MM-dd HH:mm:ss)`, + from: original, + to: 'datePicker', + confidence: 'extremely_high', + rollback: formId + ? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'` + : undefined, + }, + } + } + return { field } +} + +function fixDateToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } { + const dataType = (field.dataType || field.fieldDbType || '').toLowerCase() + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + + if (dataType === 'date' && jnpfKey !== 'datePicker') { + const original = jnpfKey || 'none' + field.jnpfKey = 'datePicker' + if (field.fieldComponent) field.fieldComponent = 'datePicker' + if (!field.format) field.format = 'yyyy-MM-dd' + const fieldName = field.fieldName || field.field || '?' + return { + field, + entry: { + id: 'A3', + level: 'assertive', + field: fieldName, + summary: `${fieldName}: ${original} → datePicker (format=yyyy-MM-dd)`, + from: original, + to: 'datePicker', + confidence: 'extremely_high', + rollback: formId + ? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'` + : undefined, + }, + } + } + return { field } +} + +function fixTimePickerToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } { + const dataType = (field.dataType || field.fieldDbType || '').toLowerCase() + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + + // timePicker on a datetime column → should be datePicker + if ((dataType === 'datetime' || dataType === 'timestamp') && jnpfKey === 'timePicker') { + field.jnpfKey = 'datePicker' + if (field.fieldComponent) field.fieldComponent = 'datePicker' + if (!field.format) field.format = 'yyyy-MM-dd HH:mm:ss' + const fieldName = field.fieldName || field.field || '?' + return { + field, + entry: { + id: 'A5', + level: 'assertive', + field: fieldName, + summary: `${fieldName}: timePicker → datePicker (datetime 字段应配 datePicker)`, + from: 'timePicker', + to: 'datePicker', + confidence: 'extremely_high', + rollback: formId + ? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"timePicker"}]'` + : undefined, + }, + } + } + return { field } +} + +function fixIntWithDictToSelect(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } { + const dataType = (field.dataType || field.fieldDbType || '').toLowerCase() + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + const dictType = field.dictType || field.dictionaryType || '' + + if ((dataType === 'int' || dataType === 'integer' || dataType === 'tinyint' || dataType === 'smallint') && + dictType && jnpfKey !== 'select') { + const original = jnpfKey || 'inputNumber' + field.jnpfKey = 'select' + if (field.fieldComponent) field.fieldComponent = 'select' + const fieldName = field.fieldName || field.field || '?' + return { + field, + entry: { + id: 'A4', + level: 'assertive', + field: fieldName, + summary: `${fieldName}: ${original} → select (int+dictType=${dictType})`, + from: original, + to: 'select', + confidence: 'high', + rollback: formId + ? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'` + : undefined, + }, + } + } + return { field } +} + +function fixFkToRelationForm( + field: FormField, + ctx: FixContext, +): { field: FormField; entry?: FixEntry } { + const fieldName = field.fieldName || field.field || '' + const match = fieldName.match(/^f_(.+)_id$/) + if (!match) return { field } + + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + if (jnpfKey === 'relationForm') return { field } // 已正确 + + const targetTable = match[1] // f_user_id → user + const existing = ctx.existingForms?.find( + f => f.enCode === targetTable || f.enCode?.toLowerCase() === targetTable.toLowerCase(), + ) + + if (!existing) { + // 找不到匹配表单 → suggest 而非 assertive + return { + field, + entry: { + id: 'G1', + level: 'suggest', + field: fieldName, + summary: `${fieldName}: 疑似 FK 字段, 但未找到匹配表单 "${targetTable}", 保持 ${jnpfKey}`, + candidates: ctx.existingForms?.slice(0, 5).map(f => f.enCode), + }, + } + } + + const original = jnpfKey || 'inputNumber' + field.jnpfKey = 'relationForm' + if (field.fieldComponent) field.fieldComponent = 'relationForm' + field.dictType = existing.enCode + field.modelId = existing.id + + return { + field, + entry: { + id: 'A1', + level: 'assertive', + field: fieldName, + summary: `${fieldName}: ${original} → relationForm (关联 ${existing.enCode})`, + from: original, + to: 'relationForm', + confidence: 'high', + rollback: ctx.formId + ? `dacli form update ${ctx.formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'` + : undefined, + }, + } +} + +// ============================================================ +// Suggest level (not sure, give candidates) +// ============================================================ + +function suggestDictTypeForInt(field: FormField, ctx: FixContext): FixEntry | null { + const dataType = (field.dataType || field.fieldDbType || '').toLowerCase() + const jnpfKey = field.jnpfKey || field.fieldComponent || '' + const dictType = field.dictType || field.dictionaryType || '' + + if ((dataType === 'int' || dataType === 'integer') && + (jnpfKey === 'select' || jnpfKey === 'radio') && !dictType) { + const fieldName = field.fieldName || field.field || '?' + const candidates = ctx.existingDicts?.slice(0, 5).map(d => d.enCode) || [] + return { + id: 'G2', + level: 'suggest', + field: fieldName, + summary: `${fieldName}: int + ${jnpfKey} 但未指定 dictType`, + candidates, + } + } + return null +} + +// ============================================================ +// Main pipeline +// ============================================================ + +/** + * 运行 auto-fix pipeline + * @param fields 原始字段列表 + * @param ctx 上下文 (已有表单/字典) + * @param isSubTable 是否为子表字段 + * @returns 修正后的字段 + fix 日志 + */ +export function runAutoFix( + fields: FormField[], + ctx: FixContext = {}, + isSubTable = false, +): FixResult { + const silent: FixEntry[] = [] + const assertive: FixEntry[] = [] + const suggestions: FixEntry[] = [] + + const fixed: FormField[] = [] + + for (const rawField of fields) { + let field = { ...rawField } + + // ---- Silent fixes (run always, modify in place) ---- + // S4: jnpfKey whitelist check + const whitelistResult = fixJnpfKeyWhitelist(field) + field = whitelistResult.field + if (whitelistResult.entry) silent.push(whitelistResult.entry) + + // S5: child table component restrictions + const childResult = fixChildTableComponents(field, isSubTable) + field = childResult.field + if (childResult.entry) silent.push(childResult.entry) + + // S10: _fk suffix removal + const fkResult = fixFkSuffix(field) + if (fkResult.field === null) { + if (fkResult.entry) silent.push(fkResult.entry) + continue // 丢弃该字段 + } + field = fkResult.field + + // ---- Assertive fixes (high confidence, auto-fix + rollback) ---- + // A2: datetime → datePicker + const dtResult = fixDatetimeToDatePicker(field, ctx.formId) + field = dtResult.field + if (dtResult.entry) assertive.push(dtResult.entry) + + // A3: date → datePicker + const dResult = fixDateToDatePicker(field, ctx.formId) + field = dResult.field + if (dResult.entry) assertive.push(dResult.entry) + + // A5: timePicker on datetime → datePicker + const tpResult = fixTimePickerToDatePicker(field, ctx.formId) + field = tpResult.field + if (tpResult.entry) assertive.push(tpResult.entry) + + // A4: int + dictType → select + const intResult = fixIntWithDictToSelect(field, ctx.formId) + field = intResult.field + if (intResult.entry) assertive.push(intResult.entry) + + // A1: FK → relationForm + const fkRelResult = fixFkToRelationForm(field, ctx) + field = fkRelResult.field + if (fkRelResult.entry) { + if (fkRelResult.entry.level === 'suggest') { + suggestions.push(fkRelResult.entry) + } else { + assertive.push(fkRelResult.entry) + } + } + + // ---- Suggest level (don't fix, give candidates) ---- + const dictSuggestion = suggestDictTypeForInt(field, ctx) + if (dictSuggestion) suggestions.push(dictSuggestion) + + fixed.push(field) + } + + return { fields: fixed, silent, assertive, suggestions } +} diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index ae22c20..5cf4c65 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -28,6 +28,8 @@ import { loadAppContext } from '../app/context.ts' import { loadToken } from '../../core/config.ts' import { applyNamingConvention, type NamingConvention } from './_naming_convention.ts' import { autoStripEnCode, autoStripFullName } from '../_encode_validator.ts' +import { runAutoFix, type FixContext } from '../_auto_fix.ts' +import { saveCommandLog, formatOneLineSummary, type CommandLog } from '../../core/logfile.ts' interface CreateOpts { fullName?: string @@ -250,6 +252,10 @@ export function buildFormCreateCommand(): Command { // 不传 = 默认 snake_case 语义名 (dacli --ai 旧行为, baseline 0/60) .option('--column-naming