diff --git a/src/commands/form/fix_entity.ts b/src/commands/form/fix_entity.ts new file mode 100644 index 0000000..709975f --- /dev/null +++ b/src/commands/form/fix_entity.ts @@ -0,0 +1,177 @@ +/** + * commands/form/fix-entity.ts — codegen 输出后置修复 (jxcj 2026-06-29 P0) + * + * 背景: jnpf 后端 CodeGenerateFactoryV3 用 mybatis-plus generator 生成 entity + service, + * 默认不加 @TableId type=IdType.ASSIGN_ID (jnpf 雪花 string id 必需). + * 默认 ServletUtil.getHeader("jnpf-origin").equals("pc") 也会 NPE (curl/外调没 header). + * + * 症状: + * - 写表单数据: "Type handler was null on parameter mapping for property 'id'" + * - 浏览器外调: "java.lang.NullPointerException ... cannot invoke String.equals(Object)" + * - 影响 27 form × 2 = 54 个文件. + * + * 用法: + * dacli form fix-entity # 扫 ./boot/ssw-*-entity, 加 @TableId (P0 2) + * dacli form fix-entity --type=biz # 扫 ./boot/ssw-*-biz, 修 Service NPE (P0 3) + * dacli form fix-entity --type=all # 同时修 entity + biz + * dacli form fix-entity --dry-run # 只显示不写 + * dacli form fix-entity --table=team # 只修指定表 + * dacli form fix-entity --dir=/path/... # 自定义目录 + * + * 适用: jnpf 6.2 (codegen 输出) + jnpf 6.5+ (后置补丁) + */ +import { Command } from 'commander' +import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' +import { loadToken } from '../../core/config.ts' + +interface Opts { + table?: string + dir?: string + type?: string + dryRun?: boolean +} + +const TARGET_ANNOTATION = '@TableId(value = "f_id", type = IdType.ASSIGN_ID)' + +/** 找 entity 目录(boot/ssw-{app}-entity/src/main/java/ssw/{app}/entity/) */ +function findAppDirs(): { app: string; entityDir: string; bizDir: string | null }[] { + const cwd = process.cwd() + const out: { app: string; entityDir: string; bizDir: string | null }[] = [] + try { + for (const appDir of readdirSync(join(cwd, 'boot'))) { + if (!appDir.startsWith('ssw-')) continue + const appName = appDir.replace('ssw-', '') + const entityPath = join(cwd, 'boot', appDir, `${appDir}-entity`, 'src', 'main', 'java', 'ssw', appName, 'entity') + const bizPath = join(cwd, 'boot', appDir, `${appDir}-biz`, 'src', 'main', 'java', 'ssw', appName, 'service', 'impl') + if (existsSync(entityPath)) { + out.push({ app: appName, entityDir: entityPath, bizDir: existsSync(bizPath) ? bizPath : null }) + } + } + } catch { + return [] + } + return out +} + +/** 修单个 entity 文件 (P0 2) */ +function fixEntityFile(filePath: string, tableName?: string): { changed: boolean; reason: string } { + if (tableName && !filePath.endsWith(`${tableName}Entity.java`)) { + return { changed: false, reason: 'skip (not target table)' } + } + let content = readFileSync(filePath, 'utf-8') + if (content.includes(TARGET_ANNOTATION)) { + return { changed: false, reason: 'already fixed' } + } + const fIdMatch = content.match(/@JSONField\(name\s*=\s*"f_id"\)\s*\n\s*private\s+String\s+id\s*;/) + if (!fIdMatch) { + return { changed: false, reason: 'no f_id String id field found' } + } + const newContent = content.replace( + fIdMatch[0], + `${TARGET_ANNOTATION}\n ${fIdMatch[0]}`, + ) + writeFileSync(filePath, newContent, 'utf-8') + return { changed: true, reason: 'added @TableId' } +} + +/** 修单个 ServiceImpl 文件 (P0 3) */ +function fixServiceNpe(filePath: string, tableName?: string): { changed: boolean; reason: string } { + if (!filePath.endsWith('ServiceImpl.java')) { + return { changed: false, reason: 'skip (not ServiceImpl)' } + } + if (tableName && !filePath.includes(`/service/impl/${tableName}ServiceImpl.java`)) { + return { changed: false, reason: 'skip (not target table)' } + } + let content = readFileSync(filePath, 'utf-8') + // jnpf 后端生成的代码格式: `ServletUtil.getHeader("jnpf-origin").equals("pc")` + const npePattern = /ServletUtil\.getHeader\("jnpf-origin"\)\.equals\("pc"\)/g + if (!npePattern.test(content)) { + return { changed: false, reason: 'no jnpf-origin NPE pattern' } + } + content = content.replace( + npePattern, + 'ServletUtil.getHeader("jnpf-origin") != null && ServletUtil.getHeader("jnpf-origin").equals("pc")', + ) + writeFileSync(filePath, content, 'utf-8') + return { changed: true, reason: 'added null check on jnpf-origin' } +} + +export function buildFormFixEntityCommand(): Command { + const cmd = new Command('fix-entity') + .alias('fixEntity') + .description('P0 修复: entity 加 @TableId(type=ASSIGN_ID) + Service 加 jnpf-origin null check (jxcj 2026-06-29 实战教训)') + .option('--table ', '只修指定表 (默认修所有)') + .option('--dir ', '自定义目录 (优先级最高, 覆盖自动扫描)') + .option('--type ', '修类型 entity|biz|all (默认 all)', 'all') + .option('--dry-run', '只显示不写文件', false) + .action(async (opts: Opts) => { + if (!loadToken()) { + log.error('未登录, 请先 dacli app login') + process.exit(1) + } + const fixType = opts.type || 'all' + const apps = findAppDirs() + if (apps.length === 0 && !opts.dir) { + log.error('未找到 entity 目录 (在 ./boot/ssw-*-entity/ 找) 或 用 --dir 显式指定') + process.exit(1) + } + let totalFixed = 0 + let totalSkipped = 0 + // 修 entity (P0 2) + if (fixType === 'entity' || fixType === 'all') { + log.info('==== P0 2: 修 entity ====') + for (const a of apps) { + const dir = opts.dir || a.entityDir + log.info(`扫描 entity: ${dir}`) + const files = readdirSync(dir).filter((f) => f.endsWith('Entity.java')) + for (const f of files) { + const full = join(dir, f) + if (opts.dryRun) { + const c = readFileSync(full, 'utf-8') + if (!c.includes(TARGET_ANNOTATION) && c.includes('@JSONField(name = "f_id")')) { + log.ok(`[DRY] ${f}: 需要加 @TableId`) + totalFixed++ + } else { totalSkipped++ } + } else { + const r = fixEntityFile(full, opts.table) + if (r.changed) { log.ok(`✅ ${f}: ${r.reason}`); totalFixed++ } else { totalSkipped++ } + } + } + } + } + // 修 biz Service NPE (P0 3) + if (fixType === 'biz' || fixType === 'all') { + log.info('==== P0 3: 修 Service NPE on jnpf-origin ====') + for (const a of apps) { + if (!a.bizDir) continue + log.info(`扫描 biz: ${a.bizDir}`) + const files = readdirSync(a.bizDir).filter((f) => f.endsWith('ServiceImpl.java')) + for (const f of files) { + const full = join(a.bizDir, f) + if (opts.dryRun) { + const c = readFileSync(full, 'utf-8') + if (c.includes('ServletUtil.getHeader("jnpf-origin").equals("pc")')) { + log.ok(`[DRY] ${f}: 需要加 null check`) + totalFixed++ + } else { totalSkipped++ } + } else { + const r = fixServiceNpe(full, opts.table) + if (r.changed) { log.ok(`✅ ${f}: ${r.reason}`); totalFixed++ } else { totalSkipped++ } + } + } + } + } + log.info(`完成: fixed=${totalFixed} skipped=${totalSkipped}`) + }) + installAiHelpHook(cmd, { + purpose: 'P0 修复: entity 加 @TableId + Service 加 jnpf-origin null check (jnpf 雪花 id 必需, jxcj 2026-06-29 实战教训).', + required: {}, + optional: { '--table': '只修指定表', '--dir': '自定义目录', '--type': 'entity|biz|all', '--dry-run': '只显示不写' }, + example: ['dacli form fix-entity', 'dacli form fix-entity --type=biz', 'dacli form fix-entity --dry-run'], + source: {api: 'scan + sed'}, + }) + return cmd +} \ No newline at end of file