diff --git a/src/commands/dict/datacreate.ts b/src/commands/dict/datacreate.ts new file mode 100644 index 0000000..853b373 --- /dev/null +++ b/src/commands/dict/datacreate.ts @@ -0,0 +1,93 @@ +/** + * commands/dict/datacreate.ts — 往已存在字典类型追加字典项 + * + * API: POST /api/system/DictionaryData + * + * 用法: + * dacli dict data-create --typeId=443409825091648261 --enCode=new_item --fullName="新项" + * dacli dict data-create --typeId=X --items='[{"enCode":"x1","fullName":"X1"}]' + * + * 补充 type-create 用法, 单条/批量追加字典项. + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface Opts { + typeId: string + enCode?: string + fullName?: string + parentId?: string + sortCode?: string + items?: string + json?: boolean +} + +export function buildDictDataCreateCommand(): Command { + const cmd = new Command('dataCreate') + .alias('data-create') + .description('往已存在字典类型追加字典项 (单条/批量)') + .requiredOption('--typeId ', '字典类型 id') + .option('--enCode ', '字典项编码 (单条模式必填)') + .option('--fullName ', '字典项名 (单条模式必填)') + .option('--parentId

', '父字典项 id (默认 0)', '0') + .option('--sortCode ', '排序 (默认 0)', '0') + .option('--items ', '批量 JSON 数组 [{enCode, fullName, sortCode?}, ...] (与 --enCode/--fullName 互斥)') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: Opts) => { + if (!opts.typeId) { + log.error('--typeId 必填') + process.exit(2) + } + if (!opts.items && (!opts.enCode || !opts.fullName)) { + log.error('单条模式必填 --enCode 和 --fullName; 或传 --items 批量') + process.exit(2) + } + + const c = await JnpfClient.fromToken() + let items: Array<{ enCode: string; fullName: string; sortCode?: number; parentId?: string }> + + if (opts.items) { + try { items = JSON.parse(opts.items) } + catch (e) { log.error(`--items JSON 解析失败: ${(e as Error).message}`); process.exit(2) } + if (!Array.isArray(items) || items.length === 0) { log.error('--items 必是非空数组'); process.exit(2) } + } else { + items = [{ enCode: opts.enCode!, fullName: opts.fullName!, sortCode: Number(opts.sortCode || '0'), parentId: opts.parentId || '0' }] + } + + log.info(`POST /system/DictionaryData typeId=${opts.typeId} count=${items.length}`) + let ok = 0, fail = 0 + const ids: string[] = [] + for (const it of items) { + const body = { + dictionaryTypeId: opts.typeId, + enCode: it.enCode, + fullName: it.fullName, + parentId: it.parentId || '0', + sortCode: it.sortCode ?? 0, + } + const r = await c.postJson<{ id: string }>('/system/DictionaryData', body) + if (r.code === 200) { ok++; ids.push(r.data?.id || ''); log.ok(` ✓ ${it.enCode} → ${it.fullName} id=${r.data?.id || ''}`) } + else { fail++; log.warn(` ✗ ${it.enCode} (code=${r.code}): ${r.msg}`) } + } + log.info(`完成: 成功 ${ok}, 失败 ${fail}`) + if (opts.json) printJson({ typeId: opts.typeId, success: ok, failed: fail, ids }) + }) + + installAiHelpHook(cmd, { + purpose: '往已存在字典类型追加字典项 (单条/批量).', + required: { '--typeId': '字典类型 id' }, + optional: { + '--enCode': '单条模式: 字典项编码', + '--fullName': '单条模式: 字典项名', + '--items': '批量模式: JSON 数组 [{enCode, fullName, sortCode?}]', + '--parentId': '父字典项 id (默认 0)', + '--sortCode': '排序 (默认 0)', + }, + example: 'dacli dict dataCreate --typeId=443409825091648261 --enCode=new --fullName="新项"', + source: { api: 'POST /api/system/DictionaryData' }, + notes: ['解决盲点 41: 往已有字典类型追加字典项'], + }) + return cmd +} diff --git a/src/commands/dict/index.ts b/src/commands/dict/index.ts index 9e1d3ce..11b9083 100644 --- a/src/commands/dict/index.ts +++ b/src/commands/dict/index.ts @@ -4,10 +4,14 @@ import { Command } from 'commander' import { buildDictTypeListCommand } from './typelist.ts' import { buildDictDataListCommand } from './datalist.ts' +import { buildDictTypeCreateCommand } from './typecreate.ts' +import { buildDictDataCreateCommand } from './datacreate.ts' export function buildDictCommand(): Command { const cmd = new Command('dict').description('字典管理 (类型 + 数据)') cmd.addCommand(buildDictTypeListCommand()) cmd.addCommand(buildDictDataListCommand()) + cmd.addCommand(buildDictTypeCreateCommand()) + cmd.addCommand(buildDictDataCreateCommand()) return cmd } diff --git a/src/commands/dict/typecreate.ts b/src/commands/dict/typecreate.ts new file mode 100644 index 0000000..46c1375 --- /dev/null +++ b/src/commands/dict/typecreate.ts @@ -0,0 +1,116 @@ +/** + * commands/dict/typecreate.ts — 创建字典类型 (含 items) + * + * API: POST /api/system/DictionaryType + * POST /api/system/DictionaryData (per item) + * + * 用法: + * dacli dict type-create --enCode=tds_space_status --fullName="空间状态" --items='[{"enCode":"draft","fullName":"草稿"},{"enCode":"running","fullName":"运行中"}]' + * + * 解决盲点 41 (TS 版 dict 只读). 端到端: 1 条命令建类型 + N 条字典项. + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log, printJson } from '../../core/log.ts' + +interface Opts { + enCode: string + fullName: string + parentId?: string + category?: string + isTree?: string + sortCode?: string + items?: string + json?: boolean +} + +export function buildDictTypeCreateCommand(): Command { + const cmd = new Command('typeCreate') + .alias('type-create') + .description('创建字典类型 (含 items 一并建; 解决盲点 41: TS 版 dict 只读)') + .requiredOption('--enCode ', '字典编码 (英文, 唯一)') + .requiredOption('--fullName ', '字典名 (中文)') + .option('--parentId

', '父字典 id, 不传则建顶级 (默认 "0")', '0') + .option('--category ', '分类: 0=业务 1=系统 (默认 0)', '0') + .option('--isTree <0|1>', '是否树形 (默认 0)', '0') + .option('--sortCode ', '排序, 数字越大越靠后 (默认 0)', '0') + .option('--items ', '字典项 JSON 数组 [{enCode, fullName, sortCode?}, ...] (可选)') + .option('--json', '原始 JSON 输出', false) + .action(async (opts: Opts) => { + if (!opts.enCode || !opts.fullName) { + log.error('--enCode 和 --fullName 必填') + process.exit(2) + } + const c = await JnpfClient.fromToken() + + // 1. 建字典类型 + const typeBody: Record = { + fullName: opts.fullName, + enCode: opts.enCode, + parentId: opts.parentId || '0', + category: opts.category || '0', + isTree: Number(opts.isTree || '0'), + sortCode: Number(opts.sortCode || '0'), + } + log.info(`POST /system/DictionaryType enCode=${opts.enCode}`) + const tr = await c.postJson<{ id: string }>('/system/DictionaryType', typeBody) + if (tr.code !== 200) { + log.error(`建字典类型失败 (code=${tr.code}): ${tr.msg}`) + process.exit(1) + } + const typeId = tr.data?.id || '(unknown)' + log.ok(`✓ 字典类型创建: id=${typeId} enCode=${opts.enCode}`) + + // 2. 批量建字典项 (--items) + if (opts.items) { + let parsed: Array<{ enCode: string; fullName: string; sortCode?: number; parentId?: string }> + try { + parsed = JSON.parse(opts.items) + } catch (e) { + log.error(`--items JSON 解析失败: ${(e as Error).message}`) + process.exit(2) + } + if (!Array.isArray(parsed) || parsed.length === 0) { + log.warn('--items 是空数组, 跳过') + } else { + log.info(`建 ${parsed.length} 个字典项...`) + let ok = 0, fail = 0 + for (const item of parsed) { + const body = { + dictionaryTypeId: typeId, + enCode: item.enCode, + fullName: item.fullName, + parentId: item.parentId || '0', + sortCode: item.sortCode ?? 0, + } + const r = await c.postJson<{ id: string }>('/system/DictionaryData', body) + if (r.code === 200) { ok++; log.ok(` ✓ ${item.enCode} → ${item.fullName}`) } + else { fail++; log.warn(` ✗ ${item.enCode} (code=${r.code}): ${r.msg}`) } + } + log.info(`字典项: 成功 ${ok}, 失败 ${fail}`) + } + } + + if (opts.json) printJson({ typeId, enCode: opts.enCode, fullName: opts.fullName }) + }) + + installAiHelpHook(cmd, { + purpose: '创建字典类型 (含可选 items 批量建). 端到端 1 条命令替代 web UI 手敲.', + required: { + '--enCode': '字典编码 (英文唯一)', + '--fullName': '字典名 (中文)', + }, + optional: { + '--items': '字典项 JSON 数组 [{enCode, fullName, sortCode?}, ...]', + '--parentId': '父字典 id (默认 0 = 顶级)', + '--category': '0=业务 1=系统 (默认 0)', + '--isTree': '是否树形 (默认 0)', + '--sortCode': '排序 (默认 0)', + }, + example: 'dacli dict typeCreate --enCode=tds_space_status --fullName="空间状态" --items=\'[{"enCode":"draft","fullName":"草稿"},{"enCode":"running","fullName":"运行中"}]\'', + source: { api: 'POST /api/system/DictionaryType + POST /api/system/DictionaryData' }, + notes: ['解决盲点 41 (TS 版 dict 只读): 端到端建类型+字典项 1 条命令'], + }) + return cmd +} diff --git a/src/commands/dm/create.ts b/src/commands/dm/create.ts index 763726f..129068e 100644 --- a/src/commands/dm/create.ts +++ b/src/commands/dm/create.ts @@ -32,6 +32,16 @@ export function buildDmCreateCommand(): Command { const dbLinkId = opts.dbLinkId || c.dbLinkId || '0' const userFields = JSON.parse(opts.fields) as Record[] + + // D-5 (盲点 38 防御): 用户字段含 f_description 会被系统自动加的 text 列冲突 + // 系统会自动注入 f_description (text) 作为"描述"列, 用户不应自己再传 + const userFieldNames = userFields.map((f) => String(f.field || '')) + if (userFieldNames.includes('f_description')) { + log.warn('⚠️ D-5 检测: 用户字段含 f_description, 这与系统自动注入的 "描述(text)" 列冲突!') + log.warn(' 建议: 把 f_description 改名 (如 f_desc), 或移除 (系统已含默认 text 描述列)') + log.warn(' 继续执行会报 "Duplicate column name \'f_description\'" (盲点 38)') + } + // 强制补全 schema 必填项 (autoIncrement/identity/columnName/index/primaryKey) const fields = userFields.map((f) => ({ autoIncrement: 0, @@ -71,7 +81,17 @@ export function buildDmCreateCommand(): Command { 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) if (r.code !== 200) { - log.error(`建表失败 (code=${r.code}): ${r.msg}`) + // D-5 (盲点 38 防御): 友好提示 f_description 冲突 + const errMsg = r.msg || '' + if (errMsg.includes("Duplicate column name 'f_description'")) { + log.error(`建表失败 (code=${r.code}): ${r.msg}`) + log.error('') + log.error(' 💡 这是盲点 38 已知问题: f_description 已被系统自动注入为 "描述(text)" 列') + log.error(' 解决方法: 移除 --fields 里的 f_description, 或改名为 f_desc') + log.error(' 详见 docs/tds/summary.html §3 盲点 38') + } else { + log.error(`建表失败 (code=${r.code}): ${r.msg}`) + } if (opts.json) printJson(r) process.exit(1) } diff --git a/src/commands/form/_simplify.ts b/src/commands/form/_simplify.ts new file mode 100644 index 0000000..97b33f7 --- /dev/null +++ b/src/commands/form/_simplify.ts @@ -0,0 +1,178 @@ +/** + * commands/form/_simplify.ts — 简化字段格式自动包 __config__ (D-3 盲点 42 防御) + * + * 用户友好的简化格式: + * [ + * {"vmodel":"f_name","label":"名称","jnpfKey":"input","required":true, + * "dataType":"varchar","dataLength":"100"}, + * {"vmodel":"f_status","label":"状态","jnpfKey":"select","required":true, + * "options":[{"fullName":"草稿","id":"draft"}]}, + * {"vmodel":"f_owner","label":"负责人","jnpfKey":"relationForm","required":true, + * "relationTable":"base_user","columnOptions":[{"label":"姓名","value":"realName"}]} + * ] + * + * 自动转 JNPF web 标准的完整 schema: + * [ + * { + * "__config__": {formId, visibility, jnpfKey, label, required, tableName, layout, tag, ...}, + * "__vModel__": "f_name", + * "field": "f_name", + * "clearable": true, + * "style": {"width": "100%"}, + * "placeholder": "请输入名称", + * "id": "f_name", + * "fullName": "名称", + * "fullNameI18nCode": [""], + * "options": [...], // select 选项透传 + * "relationTable": "...", // relationForm 透传 + * "columnOptions": [...], // relationForm 透传 + * } + * ] + * + * 检测: 字段不含 `__config__` 视为简化格式, 自动包. + */ + +export interface SimpleField { + vmodel: string + label: string + jnpfKey: string + required?: boolean + dataType?: string + dataLength?: string + options?: unknown[] + relationTable?: string + columnOptions?: unknown[] + /** relationForm 用: 取数字段, 缺省 vmodel */ + relationField?: string + /** select 用: 字典类型 id (替代 options) */ + dictionaryType?: string + /** 透传其他字段, 如 span/regList 等 */ + [key: string]: unknown +} + +export interface FullField { + __config__: Record + __vModel__: string + [key: string]: unknown +} + +/** + * 把用户给的简化 fields 数组转成 JNPF web 标准的 __config__ schema. + * 若 fields[0] 已含 __config__ 则原样透传 (完整格式). + */ +export function wrapSimplifiedFields( + fields: unknown[], + tableName: string, +): { wrapped: FullField[]; converted: number; total: number } { + if (!Array.isArray(fields) || fields.length === 0) { + return { wrapped: [], converted: 0, total: 0 } + } + // 检测是否简化格式: 第一项无 __config__ 即视作简化 + const firstItem = fields[0] as Record | undefined + const isSimplified = !firstItem?.__config__ + + if (!isSimplified) { + return { wrapped: fields as FullField[], converted: 0, total: fields.length } + } + + const wrapped: FullField[] = fields.map((raw, i) => { + const f = raw as SimpleField + if (!f.vmodel) throw new Error(`fields[${i}] 缺少 vmodel 字段`) + if (!f.jnpfKey) throw new Error(`fields[${i}] 缺少 jnpfKey 字段`) + if (!f.label) throw new Error(`fields[${i}] 缺少 label 字段 (BS-31)`) + + const jnpfKey = f.jnpfKey + const config: Record = { + formId: 101 + i, + visibility: ['pc', 'app'], + jnpfKey, + noShow: false, + tipLabel: '', + dragDisabled: false, + className: [], + label: f.label, + showLabel: true, + required: f.required === true, + tableName, + renderKey: 1780900000000 + i, + layout: 'colFormItem', + tagIcon: `icon-ym icon-ym-generator-${jnpfKey.toLowerCase()}`, + tag: + jnpfKey === 'input' || jnpfKey === 'textarea' + ? 'JnpfInput' + : 'Jnpf' + jnpfKey[0].toUpperCase() + jnpfKey.slice(1), + regList: [], + span: 24, + dictionaryType: f.dictionaryType || '', + trigger: jnpfKey === 'input' ? 'blur' : '', + } + + const placeholder = + jnpfKey === 'input' || jnpfKey === 'textarea' || jnpfKey === 'inputNumber' + ? `请输入${f.label}` + : `请选择${f.label}` + + const result: FullField = { + __config__: config, + __vModel__: f.vmodel, + field: f.vmodel, + clearable: true, + style: { width: '100%' }, + placeholder, + id: f.vmodel, + fullName: f.label, + fullNameI18nCode: [''], + } + + // 透传 select 字典项 + if (f.options) result.options = f.options + // 透传 relationForm 配置 + if (f.relationTable) result.relationTable = f.relationTable + if (f.columnOptions) result.columnOptions = f.columnOptions + if (f.relationField) result.relationField = f.relationField + // 透传其他字段 (span/regList 等) + for (const k of Object.keys(f)) { + if ( + !['vmodel', 'label', 'jnpfKey', 'required', 'dataType', 'dataLength', 'options', 'relationTable', 'columnOptions', 'relationField', 'dictionaryType'].includes(k) + ) { + result[k] = f[k] + } + } + return result + }) + + return { wrapped, converted: wrapped.length, total: fields.length } +} + +/** 从 fields 推导 tables 默认值 (D-2 自动推断) */ +export function buildTablesFromFields( + enCode: string, + name: string, + fields: SimpleField[], +): unknown[] { + // 排除系统列 (9 列) — 业务字段 + const SYSTEM = 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']) + const businessFields = fields + .filter((f) => !SYSTEM.has(f.vmodel)) + .map((f) => ({ + dataType: f.dataType || 'varchar', + field: f.vmodel, + fieldName: f.label, + primaryKey: 0, + dataLength: f.dataLength || (f.dataType === 'text' ? '0' : '200'), + allowNull: f.required ? 0 : 1, + })) + return [ + { + table: enCode, + tableName: name, + typeId: '1', + comment: '主表', + fields: [ + { dataType: 'varchar', field: 'f_id', fieldName: '主键', primaryKey: 1 }, + { dataType: 'varchar', field: 'f_tenant_id', fieldName: '租户id', primaryKey: 1 }, + ...businessFields, + ], + }, + ] +} diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index 382549d..2a96b7d 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -12,6 +12,7 @@ import { JnpfClient } from '../../core/client.ts' import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { callAiForm, printAiFormResult } from './_ai.ts' +import { wrapSimplifiedFields, buildTablesFromFields, type SimpleField } from './_simplify.ts' interface CreateOpts { fullName?: string @@ -94,10 +95,21 @@ export function buildFormCreateCommand(): Command { const webType = Number(opts.webType) const dbLinkId = opts.dbLinkId || c.dbLinkId || '0' + // D-3: --fields 简化格式自动包 __config__ (盲点 42 防御) + let rawFields: unknown[] = [] + if (opts.fields) { + try { rawFields = JSON.parse(opts.fields) } + catch (e) { log.error(`--fields JSON 解析失败: ${(e as Error).message}`); process.exit(2) } + } + const { wrapped: fieldsArr, converted, total } = wrapSimplifiedFields(rawFields, opts.enCode) + if (converted > 0) { + log.info(`D-3: 自动包 ${converted}/${total} 字段为 __config__ schema (解决盲点 42)`) + } + const formData = { formRef: 'formRef', formModel: 'dataForm', - fields: opts.fields ? JSON.parse(opts.fields) : [], + fields: fieldsArr, tableName: opts.enCode, } // v0.7.1 fix (盲点 23): 必须显式 4 个 use*Permission 字段, 否则后端 VisualUtil.setPcPermission @@ -118,17 +130,20 @@ export function buildFormCreateCommand(): Command { ? JSON.parse(opts.tables) : type === 4 ? [] - : [ - { - table: opts.enCode, - typeId: '1', - comment: '主表', - fields: [ - { dataType: 'varchar', field: 'f_id', fieldName: '主键', primaryKey: 1 }, - { dataType: 'varchar', field: 'f_tenant_id', fieldName: '租户id', primaryKey: 1 }, - ], - }, - ] + : converted > 0 + // D-2: --fields 给了简化格式, 自动从 fields 推导 tables 默认值 (避免盲点 39) + ? buildTablesFromFields(opts.enCode, opts.fullName, rawFields as SimpleField[]) + : [ + { + table: opts.enCode, + typeId: '1', + comment: '主表', + fields: [ + { dataType: 'varchar', field: 'f_id', fieldName: '主键', primaryKey: 1 }, + { dataType: 'varchar', field: 'f_tenant_id', fieldName: '租户id', primaryKey: 1 }, + ], + }, + ] const body: Record = { fullName: opts.fullName, diff --git a/src/commands/menu/create.ts b/src/commands/menu/create.ts index f6287ec..5f224f0 100644 --- a/src/commands/menu/create.ts +++ b/src/commands/menu/create.ts @@ -61,6 +61,56 @@ export function buildMenuCreateCommand(): Command { // 模式 A: 挂表单菜单 — 走 web 真路径 if (opts.formId) { + // D-4 (盲点 40 防御): form webType=4 (视图) 走 Actions/Module 会 400, 自动 fallback 低级 API + let formWebType = 0 + let formEnCode = '' + try { + const formR = await c.get<{ data?: { webType?: string | number; enCode?: string } }>(`/visualdev/Base/${opts.formId}`) + const fData = (formR.data as { webType?: string | number; enCode?: string } | undefined) || {} + formWebType = Number(fData.webType || 0) + formEnCode = fData.enCode || '' + if (formWebType === 4) { + log.warn(`D-4: form webType=4 (视图), Actions/Module 走不通, 自动 fallback 低级 API`) + // 走低级 API, 把菜单挂上 + const lowBody: Record = { + fullName: opts.fullName, + enCode: opts.enCode || formEnCode, + parentId: opts.parentId && opts.parentId !== '-1' ? opts.parentId : '836286140288869573', // 没传父, 用第一个 Web 根 + type: 3, // VisualDev + enabledMark: 1, + sortCode: 0, + category: 'Web', + linkTarget: '_self', + isButtonAuthorize: 1, + isColumnAuthorize: 1, + isDataAuthorize: 1, + isFormAuthorize: 1, + icon: opts.icon || 'icon-ym icon-ym-generator', + propertyJson: `{"moduleId":"${opts.formId}","iconBackgroundColor":"","isTree":0,"webType":4}`, + urlAddress: `model/${formEnCode || opts.enCode}`, + pageAddress: `model/${formEnCode || opts.enCode}`, + } + // 自动从 SelectorFilter 找 pc 父菜单 + if (lowBody.parentId === '836286140288869573') { + const sel = await c.get<{ list?: { id: string; type: number }[] }>('/system/Menu/SelectorFilter/0', { category: 'Web' }) + const root = sel.data?.list?.find((m) => m.type === 0) + if (root) lowBody.parentId = root.id + } + log.info(`POST /system/Menu (D-4 fallback) ${lowBody.enCode} type=3 webType=4`) + const r = await c.postJson<{ id?: string }>('/system/Menu', lowBody) + if (r.code !== 200) { + log.error(`D-4 fallback menu create 失败 code=${r.code}: ${r.msg}`) + if (opts.json) printJson(r) + process.exit(1) + } + log.ok(`✓ 视图菜单创建成功 (formId=${opts.formId}, webType=4): id=${r.data?.id || '(unknown)'}`) + if (opts.json) printJson(r.data || r) + return + } + } catch (e) { + log.warn(`D-4: GET form webType 失败 (${(e as Error).message?.slice(0, 80)}), 继续走 Actions/Module`) + } + const pc = opts.pc === false ? 0 : 1 const app = opts.app ? 1 : 0 if (!pc && !app) {