817 lines
37 KiB
Python
817 lines
37 KiB
Python
"""代码生成模块
|
||
|
||
从 VisualDev 表单生成前后端代码,自动适配项目结构
|
||
"""
|
||
|
||
import os
|
||
import re
|
||
import json
|
||
from typing import Optional
|
||
|
||
from aibridge.client import JNPFClient
|
||
from aibridge.models import APIResponse
|
||
from aibridge.config import JNPFConfig
|
||
|
||
|
||
class CodeGenerator:
|
||
"""代码生成器"""
|
||
|
||
def __init__(self, client: JNPFClient, config: Optional[JNPFConfig] = None):
|
||
self._client = client
|
||
self._config = config or JNPFConfig()
|
||
self._gen_prefix = "/api/visualdev/Generater"
|
||
|
||
@property
|
||
def company(self) -> str:
|
||
return self._config.company_code
|
||
|
||
@property
|
||
def app_code(self) -> str:
|
||
return self._config.app_code
|
||
|
||
@property
|
||
def module_name(self) -> str:
|
||
"""模块名,格式: ssw-datar"""
|
||
return f"{self.company}-{self.app_code}"
|
||
|
||
@property
|
||
def module_package(self) -> str:
|
||
"""包名,格式: ssw.datar"""
|
||
return f"{self.company}.{self.app_code}"
|
||
|
||
@property
|
||
def backend_base(self) -> str:
|
||
"""后端代码根目录"""
|
||
return self._config.backend_code_path
|
||
|
||
@property
|
||
def frontend_base(self) -> str:
|
||
"""前端视图根目录"""
|
||
return self._config.frontend_views_path
|
||
|
||
# ==================== 代码预览接口 ====================
|
||
|
||
def code_preview(self, func_id: str, data: dict = None) -> APIResponse:
|
||
"""代码预览"""
|
||
params = data or {}
|
||
return self._client.request("POST", f"{self._gen_prefix}/{func_id}/Actions/CodePreview", data=params)
|
||
|
||
def get_alias_info(self, func_id: str) -> APIResponse:
|
||
"""获取代码生成命名规范"""
|
||
return self._client.request("GET", f"{self._gen_prefix}/{func_id}/Alias/Info")
|
||
|
||
def save_alias(self, func_id: str, data: dict) -> APIResponse:
|
||
"""更新代码生成命名规范"""
|
||
return self._client.request("POST", f"{self._gen_prefix}/{func_id}/Alias/Save", data=data)
|
||
|
||
# ==================== 代码生成 ====================
|
||
|
||
def generate(
|
||
self,
|
||
func_id: str,
|
||
module_name: str,
|
||
enable_flow: int = 0,
|
||
tables: str = "0",
|
||
form_type: str = "1",
|
||
description: str = None,
|
||
auto_fix_names: bool = False,
|
||
) -> dict:
|
||
"""生成代码并保存
|
||
|
||
目录结构:
|
||
{backend_code_path}/
|
||
└── ssw-aistudio/ # 父模块
|
||
├── pom.xml
|
||
├── ssw-aistudio-entity/ # Entity 模块
|
||
│ ├── pom.xml
|
||
│ └── src/main/java/ssw/aistudio/
|
||
│ ├── entity/
|
||
│ └── model/
|
||
├── ssw-aistudio-biz/ # Biz 模块
|
||
│ ├── pom.xml
|
||
│ └── src/main/java/
|
||
│ ├── ssw/aistudio/service/
|
||
│ └── jnpf/mapper/
|
||
└── ssw-aistudio-controller/ # Controller 模块
|
||
├── pom.xml
|
||
└── src/main/java/ssw/aistudio/controller/
|
||
|
||
Args:
|
||
func_id: 表单ID
|
||
module_name: 功能模块名称,用于类名前缀
|
||
enable_flow: 是否启用流程,0=否,1=是
|
||
tables: 0=当前表,1=主表+明细表
|
||
form_type: 1=Form,2=Detail
|
||
description: 功能描述
|
||
auto_fix_names: 是否自动修复JNPF生成的类名前缀(如 Ais_aisproject → Project)
|
||
|
||
Returns:
|
||
dict: {'success': bool, 'message': str, 'files': {...}}
|
||
"""
|
||
# 获取表单信息
|
||
info_resp = self._client.request("GET", f"/api/visualdev/Base/{func_id}")
|
||
if not info_resp.success:
|
||
return {'success': False, 'message': f'获取表单信息失败: {info_resp.msg}'}
|
||
|
||
form_info = info_resp.data
|
||
form_en_code = form_info.get('enCode', '')
|
||
desc = description or form_en_code
|
||
|
||
# 保存 module_name 供后续 _fix_package 使用
|
||
self._current_module_name = module_name
|
||
self._current_form_info = form_info
|
||
|
||
# 代码预览
|
||
code_data = {
|
||
'module': self._config.system_id,
|
||
'description': desc,
|
||
'modulePackageName': self.module_package,
|
||
'enableFlow': enable_flow
|
||
}
|
||
|
||
preview_resp = self.code_preview(func_id, code_data)
|
||
if not preview_resp.success:
|
||
return {'success': False, 'message': f'代码预览失败: {preview_resp.msg}'}
|
||
|
||
# 解析代码
|
||
files = self._extract_files(preview_resp.data)
|
||
|
||
# 创建模块目录结构
|
||
self._create_module_structure()
|
||
|
||
# 前端路径: {frontend_base}/{company}/{app_code}/{module_name}/
|
||
frontend_path = os.path.join(self.frontend_base, self.company, self.app_code, module_name)
|
||
|
||
# 后端路径: {backend_base}/{module_name}/
|
||
# 注意: module_name 在此处是业务模块名(如 ssw-dr),不是类名前缀
|
||
backend_path = os.path.join(self.backend_base, self.module_name)
|
||
|
||
# 保存前端代码
|
||
frontend_files = self._save_frontend(frontend_path, files)
|
||
|
||
# 保存后端代码
|
||
backend_files = self._save_backend(files)
|
||
|
||
# 自动修复类名前缀(JNPF 生成的类名带有 Dr_ 前缀,需要替换为 PascalCase)
|
||
fix_result = None
|
||
if auto_fix_names:
|
||
# 先从生成的文件中检测旧的类名前缀
|
||
old_prefix = self._detect_old_prefix(backend_path, module_name)
|
||
fix_result = self.fix_class_names(
|
||
backend_path=backend_path,
|
||
old_class_prefix=old_prefix,
|
||
new_class_prefix=module_name,
|
||
frontend_path=frontend_path,
|
||
)
|
||
|
||
return {
|
||
'success': True,
|
||
'message': f'代码生成成功,前端 {len(frontend_files)} 个文件,后端 {len(backend_files)} 个文件',
|
||
'frontend_path': frontend_path,
|
||
'backend_path': backend_path,
|
||
'files': {'frontend': frontend_files, 'backend': backend_files},
|
||
'fix_result': fix_result,
|
||
}
|
||
|
||
def _create_module_structure(self):
|
||
"""创建模块目录结构和 pom.xml
|
||
|
||
使用独立的 ModuleStructureCreator,保持单一职责。
|
||
"""
|
||
from aibridge.utils.modulestructure import ModuleStructureCreator
|
||
|
||
creator = ModuleStructureCreator(
|
||
module_name=self.module_name, # 业务模块名,如 "ssw-dr"
|
||
package=self.module_package, # 包名,如 "ssw.dr"
|
||
backend_base=self.backend_base,
|
||
boot_parent=self._config.boot_parent,
|
||
)
|
||
creator.create()
|
||
|
||
def _extract_files(self, code_data: dict) -> dict:
|
||
"""从代码预览数据中提取文件
|
||
|
||
JNPF 返回结构:
|
||
- 顶层 fileName: 模块名(如"model")
|
||
- 子节点 folderName: xml/java/json/vue/js/ts 文件类型
|
||
"""
|
||
web_main = []
|
||
web_helper = []
|
||
backend_files = []
|
||
helper_files = {'columnList.ts', 'searchList.ts', 'superQueryJson.ts', 'api.ts'}
|
||
|
||
def classify_java_file(file_name: str) -> str:
|
||
"""根据 Java 文件名分类到对应目录"""
|
||
if 'Controller' in file_name:
|
||
return 'controller'
|
||
elif 'Entity' in file_name:
|
||
return 'entity'
|
||
elif 'Service' in file_name and 'Impl' not in file_name:
|
||
return 'service'
|
||
elif 'ServiceImpl' in file_name:
|
||
return 'service'
|
||
elif 'Mapper' in file_name:
|
||
return 'mapper'
|
||
elif 'Excel' in file_name or 'Form' in file_name or 'Pagination' in file_name or 'Constant' in file_name or 'Json' in file_name:
|
||
return 'model'
|
||
else:
|
||
return 'model'
|
||
|
||
def traverse(items, parent_folder=''):
|
||
for item in items:
|
||
children = item.get('children', [])
|
||
if children:
|
||
traverse(children, item.get('fileName', ''))
|
||
else:
|
||
file_name = item.get('fileName', '')
|
||
content = item.get('fileContent', '')
|
||
folder_name = item.get('folderName', '').lower()
|
||
if not content:
|
||
return
|
||
|
||
# 判断是前端还是后端文件
|
||
if folder_name in ('vue', 'js', 'ts'):
|
||
if file_name in helper_files:
|
||
web_helper.append({'name': file_name, 'content': content})
|
||
else:
|
||
web_main.append({'name': file_name, 'content': content})
|
||
elif folder_name == 'xml':
|
||
backend_files.append({'folder': 'mapper', 'name': file_name, 'content': content})
|
||
elif folder_name == 'java':
|
||
backend_folder = classify_java_file(file_name)
|
||
backend_files.append({'folder': backend_folder, 'name': file_name, 'content': content})
|
||
elif folder_name == 'json':
|
||
backend_files.append({'folder': 'model', 'name': file_name, 'content': content})
|
||
|
||
traverse(code_data.get('list', []))
|
||
return {'web': {'main': web_main, 'helper': web_helper}, 'backend': backend_files}
|
||
|
||
def _save_frontend(self, base_path: str, files: dict) -> list:
|
||
"""保存前端代码"""
|
||
saved = []
|
||
helper_path = os.path.join(base_path, 'helper')
|
||
os.makedirs(helper_path, exist_ok=True)
|
||
|
||
# 主文件
|
||
for f in files['web']['main']:
|
||
path = os.path.join(base_path, f['name'])
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
with open(path, 'w', encoding='utf-8') as fp:
|
||
fp.write(f['content'])
|
||
saved.append(path)
|
||
|
||
# 辅助文件
|
||
for f in files['web']['helper']:
|
||
path = os.path.join(helper_path, f['name'])
|
||
with open(path, 'w', encoding='utf-8') as fp:
|
||
fp.write(f['content'])
|
||
saved.append(path)
|
||
|
||
return saved
|
||
|
||
def _save_backend(self, files: dict) -> list:
|
||
"""保存后端代码"""
|
||
saved = []
|
||
base = self.backend_base
|
||
module = self.module_name
|
||
pkg = self.module_package
|
||
|
||
paths = {
|
||
'entity': os.path.join(base, module, f"{module}-entity", "src", "main", "java", *pkg.split('.'), 'entity'),
|
||
'model': os.path.join(base, module, f"{module}-entity", "src", "main", "java", *pkg.split('.'), 'model'),
|
||
'service': os.path.join(base, module, f"{module}-biz", "src", "main", "java", *pkg.split('.'), 'service'),
|
||
'mapper': os.path.join(base, module, f"{module}-biz", "src", "main", "java", "jnpf", "mapper"),
|
||
'controller': os.path.join(base, module, f"{module}-controller", "src", "main", "java", *pkg.split('.'), 'controller'),
|
||
}
|
||
|
||
for f in files['backend']:
|
||
folder = f['folder'].lower()
|
||
if folder not in paths:
|
||
continue
|
||
|
||
target_dir = paths[folder]
|
||
os.makedirs(target_dir, exist_ok=True)
|
||
|
||
content = f['content']
|
||
name = f['name']
|
||
|
||
# 修复包名
|
||
if folder == 'mapper':
|
||
content = self._fix_mapper(content)
|
||
elif folder == 'controller':
|
||
content = self._fix_package(content, folder)
|
||
content = self._fix_controller(content)
|
||
else:
|
||
content = self._fix_package(content, folder)
|
||
# Service 文件也需要修复 jnpf-origin NPE 问题
|
||
if folder == 'service':
|
||
content = self._fix_service(content)
|
||
|
||
path = os.path.join(target_dir, name)
|
||
with open(path, 'w', encoding='utf-8') as fp:
|
||
fp.write(content)
|
||
saved.append(path)
|
||
|
||
return saved
|
||
|
||
def _fix_package(self, content: str, file_type: str) -> str:
|
||
"""修复 Java 文件包名"""
|
||
pkg = self.module_package
|
||
|
||
# 确定包名
|
||
if file_type == 'entity':
|
||
package = f'{pkg}.entity'
|
||
elif file_type == 'model':
|
||
package = f'{pkg}.model'
|
||
elif file_type == 'service':
|
||
package = f'{pkg}.service'
|
||
elif file_type == 'controller':
|
||
package = f'{pkg}.controller'
|
||
else:
|
||
package = pkg
|
||
|
||
# 修复 package 声明
|
||
content = re.sub(r'^package\s+[\w.]+;', f'package {package};', content, flags=re.MULTILINE)
|
||
|
||
# 修复 model 子包的 import
|
||
content = re.sub(
|
||
rf'import\s+{re.escape(self.module_package)}\.model\.[^;]+;',
|
||
f'import {pkg}.model.*;',
|
||
content
|
||
)
|
||
|
||
# 修复 entity/controller 包的 import(但 service 需要单独处理)
|
||
if file_type != 'service':
|
||
content = re.sub(
|
||
rf'import\s+{re.escape(self.module_package)}\.(\w+)\.([^;]+);',
|
||
rf'import {pkg}.\1.\2;',
|
||
content
|
||
)
|
||
|
||
# 修复 mapper import(指向 jnpf.mapper)
|
||
content = re.sub(
|
||
rf'import\s+{re.escape(self.module_package)}\.mapper\.([^;]+);',
|
||
r'import jnpf.mapper.\1;',
|
||
content
|
||
)
|
||
|
||
# 修复 service 文件:移除 service 和 service.impl 的 import(不需要引用自己)
|
||
if file_type == 'service':
|
||
# 移除 {company}.{app}.service.xxx 和 {company}.{app}.service.impl.xxx
|
||
content = re.sub(
|
||
rf'import\s+{re.escape(self.module_package)}\.service(\.impl)?\.[^;]+;\s*',
|
||
'',
|
||
content
|
||
)
|
||
|
||
return content
|
||
|
||
def _fix_mapper(self, content: str) -> str:
|
||
"""修复 Mapper 文件(固定包名为 jnpf.mapper)"""
|
||
pkg = self.module_package
|
||
|
||
# 固定包名为 jnpf.mapper
|
||
content = re.sub(r'^package\s+[\w.]+;', 'package jnpf.mapper;', content, flags=re.MULTILINE)
|
||
|
||
# 修复 Entity import
|
||
content = re.sub(
|
||
rf'import\s+{re.escape(pkg)}\.entity\.([^;]+);',
|
||
rf'import {pkg}.entity.\1;',
|
||
content
|
||
)
|
||
|
||
# 移除 service import
|
||
content = re.sub(rf'import\s+{re.escape(pkg)}\.service\.[^;]+;\s*', '', content)
|
||
|
||
return content
|
||
|
||
def _fix_controller(self, content: str, chinese_name: str = None, api_path: str = None) -> str:
|
||
"""修复 Controller 文件的 API 路径、注解及常见生成问题
|
||
|
||
JNPF 代码生成器的 @Tag/@RequestMapping 使用了系统前缀,
|
||
需要替换为标准路径:
|
||
- @RequestMapping("/api/{company_code}/{app_code}/{modelName}")
|
||
- @Tag(name = "{chinese_name}", description = "{api_path}")
|
||
|
||
同时修复 JNPF 生成的代码常见问题:
|
||
1. entityToMap → entityToMapNull(空值处理)
|
||
2. ccdt-origin → jnpf-origin(header 头)
|
||
3. CreateMethod 方法体缺失(#if isFlow 导致)
|
||
4. UpdateMethod 的 ${name}Service 变量名不一致
|
||
"""
|
||
pkg = self.module_package
|
||
parts = pkg.split('.') # [company_code, app_code]
|
||
module = getattr(self, '_current_module_name', parts[1].capitalize())
|
||
|
||
# 使用传入的值或推断
|
||
chinese_name = chinese_name or module
|
||
api_path = api_path or module.lower()
|
||
service_name = f"{module[0].lower()}{module[1:]}"
|
||
|
||
# 修复重复路径:/api/{company}/{app}/{app} → /api/{company}/{app}/xxx
|
||
def fix_request_mapping(m):
|
||
old_path = m.group(2)
|
||
path = old_path
|
||
path = re.sub(rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/{re.escape(parts[1])}/?$', rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}', path)
|
||
path = re.sub(rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/Dr_(\w+)', rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/\1', path)
|
||
path = re.sub(rf'/api/[^/]+/[^/]+/Dr_\w+', rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/{re.escape(api_path)}', path)
|
||
path = re.sub(rf'/api/\d+/Dr_\w+', rf'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/{re.escape(api_path)}', path)
|
||
if not path.startswith(f'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/'):
|
||
path = f'/api/{re.escape(parts[0])}/{re.escape(parts[1])}/{re.escape(api_path)}'
|
||
return f'@RequestMapping("{path}")'
|
||
|
||
# 修复 @RequestMapping
|
||
content = re.sub(r'(@RequestMapping\s*\(\s*)"/api/([^"]+)"(\s*\))', fix_request_mapping, content)
|
||
|
||
# 修复 @Tag
|
||
content = re.sub(
|
||
r'@Tag\s*\(\s*name\s*=\s*"[^"]+"\s*,\s*description\s*=\s*"[^"]+"(\s*\))',
|
||
f'@Tag(name = "{chinese_name}", description = "{api_path}")',
|
||
content
|
||
)
|
||
|
||
# 1. entityToMap → entityToMapNull
|
||
content = re.sub(r'JsonUtil\.entityToMap\(entity\)', 'JsonUtil.entityToMapNull(entity)', content)
|
||
content = re.sub(r'JsonUtil\.entityToMap\((\$\{?\w+\}?)\)', r'JsonUtil.entityToMapNull(\1)', content)
|
||
|
||
# 2. ccdt-origin → jnpf-origin
|
||
content = content.replace('"ccdt-origin"', '"jnpf-origin"')
|
||
|
||
# 2.1 修复 jnpf-origin null 检查:ServletUtil.getHeader("jnpf-origin").equals("pc") 会 NPE
|
||
# 改为 "pc".equals(ServletUtil.getHeader("jnpf-origin")) 安全写法
|
||
content = re.sub(
|
||
r'"pc"\.equals\s*\(\s*ServletUtil\.getHeader\s*\(\s*"jnpf-origin"\s*\)\s*\)',
|
||
'"pc".equals(ServletUtil.getHeader("jnpf-origin"))',
|
||
content
|
||
)
|
||
content = re.sub(
|
||
r'ServletUtil\.getHeader\s*\(\s*"jnpf-origin"\s*\)\.equals\s*\(\s*"pc"\s*\)',
|
||
'"pc".equals(ServletUtil.getHeader("jnpf-origin"))',
|
||
content
|
||
)
|
||
|
||
# 3. 修复 CreateMethod:确保方法签名完整(模板有时会因 #if isFlow 导致方法体缺失)
|
||
# 如果 create 方法参数为空或异常,修复为标准签名
|
||
create_pattern = r'(@PostMapping\s*\n\s*@Operation\(summary\s*=\s*"创建"\)\s*\n\s*public ActionResult<Object> create\()(\s*@RequestBody\s+@Valid\s+\$\{Name\}Form\s+\$\{name\}Form)?(\s*\))'
|
||
content = re.sub(create_pattern, '@PostMapping\n @Operation(summary = "创建")\n public ActionResult<Object> create(@RequestBody @Valid ${Name}Form ${name}Form)', content)
|
||
|
||
# 4. 修复 UpdateMethod 中 ${name}Service → ${serviceName}
|
||
# UpdateMethod 使用了与注入字段不一致的变量名
|
||
def fix_service_refs(m):
|
||
prefix = m.group(1)
|
||
var_name = m.group(2)
|
||
suffix = m.group(3)
|
||
if var_name == module or var_name == module.lower():
|
||
return f'{prefix}{service_name}{suffix}'
|
||
return m.group(0)
|
||
|
||
# 修复 UpdateMethod 中的 getInfo 和 checkForm 调用
|
||
content = re.sub(
|
||
r'(\$\{)' + module + r'(\}Service\.getInfo)',
|
||
rf'\1{service_name}\2',
|
||
content
|
||
)
|
||
content = re.sub(
|
||
r'(\$\{)' + module + r'(\}Service\.checkForm)',
|
||
rf'\1{service_name}\2',
|
||
content
|
||
)
|
||
content = re.sub(
|
||
r'(\$\{)' + module + r'(\}Service\.saveOrUpdate)',
|
||
rf'\1{service_name}\2',
|
||
content
|
||
)
|
||
|
||
return content
|
||
|
||
def _fix_service(self, content: str) -> str:
|
||
"""修复 Service 文件的常见生成问题
|
||
|
||
修复 JNPF 生成的 service 代码常见问题:
|
||
1. jnpf-origin null 检查:ServletUtil.getHeader("jnpf-origin").equals("pc") 会 NPE
|
||
改为 "pc".equals(ServletUtil.getHeader("jnpf-origin")) 安全写法
|
||
"""
|
||
# 修复 jnpf-origin null 检查
|
||
content = re.sub(
|
||
r'ServletUtil\.getHeader\s*\(\s*"jnpf-origin"\s*\)\s*\.equals\s*\(\s*"pc"\s*\)',
|
||
'"pc".equals(ServletUtil.getHeader("jnpf-origin"))',
|
||
content
|
||
)
|
||
return content
|
||
|
||
def _detect_old_prefix(self, backend_path: str, module_name: str) -> str:
|
||
"""检测 JNPF 生成的旧类名前缀
|
||
|
||
扫描 entity/controller 目录找到实际生成的类名,判断是否需要重命名:
|
||
- 如果类名包含下划线(如 Tdc_connector_configEntity),返回下划线前缀用于重命名
|
||
- 如果类名已是 PascalCase(如 TdcConnectorConfigEntity),返回 None(无需重命名)
|
||
|
||
Returns:
|
||
str or None: 需要重命名的旧前缀,如 'Tdc_connector_config',无需重命名时返回 None
|
||
"""
|
||
def has_underscore(name: str) -> bool:
|
||
"""判断名字是否包含下划线(下划线格式需要转换)"""
|
||
return '_' in name and name[0].isupper()
|
||
|
||
def extract_class_prefix(fname: str) -> str:
|
||
"""从文件名提取类名前缀,去除后缀"""
|
||
for suffix in ['Entity.java', 'Controller.java', 'Service.java', 'ServiceImpl.java',
|
||
'Mapper.java', 'Form.java', 'Pagination.java', 'ExcelVO.java',
|
||
'ExcelErrorVO.java', 'ListVO.java', 'Constant.java', 'Json.json', 'Mapper.xml']:
|
||
if fname.endswith(suffix):
|
||
return fname[:-len(suffix)]
|
||
return None
|
||
|
||
# 扫描 entity 目录
|
||
entity_dir = os.path.join(backend_path, f'{self.module_name}-entity', 'src', 'main', 'java',
|
||
self.module_package.replace('.', '/'), 'entity')
|
||
if os.path.exists(entity_dir):
|
||
for fname in os.listdir(entity_dir):
|
||
prefix = extract_class_prefix(fname)
|
||
if prefix and has_underscore(prefix):
|
||
return prefix
|
||
|
||
# 扫描 controller 目录(兜底)
|
||
controller_dir = os.path.join(backend_path, f'{self.module_name}-controller', 'src', 'main', 'java',
|
||
self.module_package.replace('.', '/'), 'controller')
|
||
if os.path.exists(controller_dir):
|
||
for fname in os.listdir(controller_dir):
|
||
prefix = extract_class_prefix(fname)
|
||
if prefix and has_underscore(prefix):
|
||
return prefix
|
||
|
||
# 扫描 service 目录(兜底)
|
||
service_dir = os.path.join(backend_path, f'{self.module_name}-biz', 'src', 'main', 'java',
|
||
self.module_package.replace('.', '/'), 'service')
|
||
if os.path.exists(service_dir):
|
||
for fname in os.listdir(service_dir):
|
||
prefix = extract_class_prefix(fname)
|
||
if prefix and has_underscore(prefix):
|
||
return prefix
|
||
|
||
# 未发现下划线格式的类名,无需重命名
|
||
return None
|
||
|
||
def fix_class_names(
|
||
self,
|
||
backend_path: str = None,
|
||
old_class_prefix: str = None,
|
||
new_class_prefix: str = None,
|
||
frontend_path: str = None,
|
||
) -> dict:
|
||
"""修复已生成代码的类名前缀(JNPF 代码生成器命名问题修复)
|
||
|
||
JNPF CodeGenerator 使用表名生成类名,如 ais_images → Ais_imagesEntity
|
||
此方法将旧类名前缀替换为新类名前缀,同时修复 Controller 和前端 API 路径。
|
||
|
||
Args:
|
||
backend_path: 后端代码根目录
|
||
old_class_prefix: 旧类名前缀(PascalCase),如 Ais_aisproject。
|
||
如果不传,则从 generate() 时保存的 _current_form_info 自动计算。
|
||
new_class_prefix: 新类名前缀(PascalCase),如 ProjectUser
|
||
frontend_path: 前端代码路径
|
||
|
||
Returns:
|
||
dict: {'backend': [(old, new), ...], 'frontend': 修复文件数}
|
||
"""
|
||
if not backend_path:
|
||
backend_path = os.path.join(self.backend_base, self.module_name)
|
||
if not old_class_prefix:
|
||
# 自动从 formData JSON 中提取表名计算旧类前缀
|
||
form_info = getattr(self, '_current_form_info', None)
|
||
if form_info:
|
||
form_data_str = form_info.get('formData', '')
|
||
if form_data_str:
|
||
import json
|
||
form_data = json.loads(form_data_str)
|
||
table_name = form_data.get('tableName', '')
|
||
if table_name:
|
||
old_class_prefix = table_name.capitalize()
|
||
if not old_class_prefix:
|
||
old_class_prefix = f'{self.app_code.capitalize()}'
|
||
if not new_class_prefix:
|
||
return {'backend': [], 'frontend': 0}
|
||
|
||
# 如果 old_class_prefix 为空,说明已是 PascalCase,无需重命名
|
||
if not old_class_prefix:
|
||
return {'backend': [], 'frontend': 0, 'message': 'Already PascalCase, skipped'}
|
||
|
||
# 确保 old_class_prefix 首字母大写(检测返回的可能是 dr_data_source_config)
|
||
old_prefix_formatted = old_class_prefix[0].upper() + old_class_prefix[1:] if old_class_prefix else old_class_prefix
|
||
|
||
rename_map = {
|
||
f"{old_prefix_formatted}Entity.java": f"{new_class_prefix}Entity.java",
|
||
f"{old_prefix_formatted}Controller.java": f"{new_class_prefix}Controller.java",
|
||
f"{old_prefix_formatted}Service.java": f"{new_class_prefix}Service.java",
|
||
f"{old_prefix_formatted}ServiceImpl.java": f"{new_class_prefix}ServiceImpl.java",
|
||
f"{old_prefix_formatted}Mapper.java": f"{new_class_prefix}Mapper.java",
|
||
f"{old_prefix_formatted}Form.java": f"{new_class_prefix}Form.java",
|
||
f"{old_prefix_formatted}Pagination.java": f"{new_class_prefix}Pagination.java",
|
||
f"{old_prefix_formatted}ExcelVO.java": f"{new_class_prefix}ExcelVO.java",
|
||
f"{old_prefix_formatted}ExcelErrorVO.java": f"{new_class_prefix}ExcelErrorVO.java",
|
||
f"{old_prefix_formatted}ListVO.java": f"{new_class_prefix}ListVO.java",
|
||
f"{old_prefix_formatted}Constant.java": f"{new_class_prefix}Constant.java",
|
||
f"{old_prefix_formatted}Json.json": f"{new_class_prefix}Json.json",
|
||
f"{old_prefix_formatted}Mapper.xml": f"{new_class_prefix}Mapper.xml",
|
||
}
|
||
|
||
def snake_to_camel(snake: str) -> str:
|
||
"""snake_case 转 camelCase (首字母小写)"""
|
||
parts = snake.split('_')
|
||
if len(parts) == 1:
|
||
return snake[0].lower() + snake[1:] if len(snake) > 1 else snake.lower()
|
||
return parts[0].lower() + ''.join(word.capitalize() for word in parts[1:])
|
||
|
||
def replace_content(content: str) -> str:
|
||
# 替换类名:Entity/Controller/Service/Mapper/Form/VO/Constant 等
|
||
# 处理 JNPF 生成的两种格式:
|
||
# 1. Dr_data_source_configEntity (下划线分隔,如 dr_data_source_config 表)
|
||
# 2. Ai_match_recordEntity (下划线分隔,PascalCase 变体)
|
||
content = re.sub(
|
||
rf'\b{old_prefix_formatted}(\w+)\b',
|
||
lambda m: new_class_prefix + m.group(1) if m.group(1) else new_class_prefix,
|
||
content
|
||
)
|
||
# 替换 old_prefix_formatted 本身(当下划线分隔的 PascalCase 直接出现时)
|
||
# 如 "Ai_match_recordEntity" → "AiMatchRecordEntity"
|
||
old_with_underscore = old_prefix_formatted # "Ai_match_record"
|
||
if '_' in old_with_underscore:
|
||
# 转为 PascalCase:Ai_match_record → AiMatchRecord
|
||
parts = old_with_underscore.split('_')
|
||
old_pascal = ''.join(p.capitalize() for p in parts) # AiMatchRecord
|
||
# 替换文件名和内容中的 Ai_match_recordEntity → AiMatchRecordEntity 等
|
||
for suffix in ['Entity', 'Controller', 'Service', 'ServiceImpl', 'Mapper',
|
||
'Form', 'Pagination', 'ExcelVO', 'ExcelErrorVO', 'ListVO',
|
||
'Constant', 'Json.json', 'Mapper.xml']:
|
||
content = content.replace(old_pascal + suffix, new_class_prefix + suffix)
|
||
# 替换 camelCase 变量名:aiMatchRecordService → dataSourceConfigService
|
||
old_var_camel = parts[0].lower() + ''.join(p.capitalize() for p in parts[1:])
|
||
new_var_camel = snake_to_camel(new_class_prefix)
|
||
content = content.replace(old_var_camel, new_var_camel)
|
||
# 替换变量名:snake_case → camelCase
|
||
old_var_snake = old_prefix_formatted.lower() # "tdc_connector_config"
|
||
new_var_camel = snake_to_camel(new_class_prefix) # "tdcConnectorConfig"
|
||
|
||
# 修复 @TableName 中的表名
|
||
# @TableName 的值应该是数据库表名(snake_case),不是 PascalCase 类名
|
||
# 例如:@TableName("tdcConnectorConfig") → @TableName("tdc_connector_config")
|
||
def fix_table_name(content):
|
||
def convert_to_snake(m):
|
||
before, value, after = m.group(1), m.group(2), m.group(3)
|
||
# 如果值是 PascalCase 格式(如 tdcConnectorConfig),转换为 snake_case
|
||
# PascalCase 检测:包含大写字母但没有下划线,且不全是大写
|
||
# 例如:tdcConnectorConfig (True), TdcConnectorConfig (True), tdc_connector_config (False)
|
||
if not value.isupper() and not '_' in value and any(c.isupper() for c in value):
|
||
# 转换 PascalCase 为 snake_case
|
||
# tdcConnectorConfig -> tdc_connector_config
|
||
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value)
|
||
snake = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
||
return before + snake + after
|
||
# 如果已经是 snake_case 且与 old_var_snake 不同,恢复为正确表名
|
||
if '_' in value and value != old_var_snake and value.lower() == old_var_snake.lower():
|
||
return before + old_var_snake + after
|
||
return m.group(0)
|
||
return re.sub(r'(@TableName\s*\(\s*")([^"]+)(")', convert_to_snake, content)
|
||
|
||
# 先做变量替换,再修复 @TableName(顺序很重要!)
|
||
content = content.replace(old_var_snake, new_var_camel)
|
||
content = fix_table_name(content)
|
||
return content
|
||
|
||
renamed = []
|
||
|
||
# 从 new_class_prefix 推断 chinese_name 和 api_path
|
||
chinese_name = re.sub(r'(Entity|Service|Controller|Config|Management)$', '', new_class_prefix)
|
||
# 简单的中文名映射
|
||
chinese_map = {
|
||
'AssetApply': '资产申请', 'AssetCatalog': '资产目录',
|
||
'CheckReport': '核查报告', 'CheckRule': '核查规则',
|
||
'DbTable': '数据库表', 'DbColumn': '数据库字段',
|
||
'MasterdataModel': '主数据模型', 'MasterdataMember': '主数据成员',
|
||
'RuleLevel': '规则级别', 'RuleType': '规则类型',
|
||
'ScheduleJob': '定时任务', 'StandardContrast': '标准对比',
|
||
'StandardDict': '标准字典', 'StandardType': '标准类型',
|
||
'DataSourceConfig': '数据源配置',
|
||
}
|
||
chinese_name = chinese_map.get(new_class_prefix, chinese_name)
|
||
# api_path: PascalCase to camelCase
|
||
api_path = re.sub(r'([A-Z])', lambda m: m.group(1).lower(), new_class_prefix)
|
||
|
||
for root, dirs, files in os.walk(backend_path):
|
||
for fname in files:
|
||
if fname not in rename_map:
|
||
continue
|
||
old_path = os.path.join(root, fname)
|
||
new_fname = rename_map[fname]
|
||
new_path = os.path.join(root, new_fname)
|
||
|
||
with open(old_path, 'r', encoding='utf-8') as f:
|
||
content = f.read()
|
||
new_content = replace_content(content)
|
||
|
||
# Controller 文件额外修复 API 路径
|
||
if fname.endswith('Controller.java'):
|
||
new_content = self._fix_controller(new_content, chinese_name, api_path)
|
||
|
||
with open(new_path, 'w', encoding='utf-8') as f:
|
||
f.write(new_content)
|
||
os.remove(old_path)
|
||
renamed.append((fname, new_fname))
|
||
|
||
# 修复前端 API 路径
|
||
frontend_fixed = self._fix_frontend(frontend_path, old_class_prefix, new_class_prefix)
|
||
|
||
return {'backend': renamed, 'frontend': frontend_fixed}
|
||
|
||
def _fix_frontend(self, frontend_path: str = None, old_class_prefix: str = None, new_class_prefix: str = None) -> int:
|
||
"""修复前端代码中的旧 API 路径
|
||
|
||
JNPF 生成的旧路径格式:/api/{systemId}/{oldClassName}
|
||
例如:/api/808341719178283333/Dr_data_source_config/getList
|
||
需要替换为标准路径:/api/{company_code}/{app_code}/{moduleName}
|
||
例如:/api/ssw/dr/datasourceconfig/getList
|
||
|
||
Args:
|
||
frontend_path: 前端代码路径
|
||
old_class_prefix: 旧的类名前缀(PascalCase),如 Dr_data_source_config
|
||
new_class_prefix: 新的类名前缀(PascalCase),如 DataSourceConfig
|
||
|
||
Returns:
|
||
int: 修复的文件数
|
||
"""
|
||
if not frontend_path:
|
||
return 0
|
||
if not os.path.exists(frontend_path):
|
||
return 0
|
||
|
||
pkg = self.module_package
|
||
parts = pkg.split('.') # [company_code, app_code]
|
||
|
||
# new_class_prefix = "DataSourceConfig" → lowercase = "datasourceconfig"
|
||
if new_class_prefix:
|
||
# PascalCase → all lowercase without underscores
|
||
# DataSourceConfig → dataSourceConfig → datasourceconfig
|
||
import re
|
||
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', new_class_prefix)
|
||
s2 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1)
|
||
module_camel = s2.replace('_', '').lower()
|
||
else:
|
||
module_camel = getattr(self, '_current_module_name', parts[1]).lower()
|
||
|
||
new_api_prefix = f'/api/{parts[0]}/{parts[1]}/{module_camel}'
|
||
|
||
# JNPF 生成的旧 API 路径有两种格式:
|
||
# 1. /api/{systemId}/{oldClassName} (如 /api/808341719178283333/Ais_aisproject)
|
||
# 2. /api/{company}_{app_code}{module} (如 /api/ssw_aisproject)
|
||
# 需要同时匹配两种
|
||
old_company_app_pattern = f'{parts[0]}_{parts[1]}' # e.g. ssw_dr or ssw_ais
|
||
|
||
fixed = 0
|
||
for root, dirs, files in os.walk(frontend_path):
|
||
for fname in files:
|
||
if not fname.endswith(('.ts', '.js', '.vue')):
|
||
continue
|
||
fpath = os.path.join(root, fname)
|
||
try:
|
||
with open(fpath, 'r', encoding='utf-8') as f:
|
||
content = f.read()
|
||
orig = content
|
||
|
||
# 检测实际的前端 API 路径格式
|
||
# 优先使用 old_class_prefix 匹配,否则从文件内容中检测实际路径
|
||
if old_class_prefix:
|
||
# 明确的前缀:替换 /api/{systemId}/{oldClassName} → /api/ssw/dr/datasourceconfig
|
||
content = re.sub(
|
||
rf'/api/\d+/{re.escape(old_class_prefix)}',
|
||
new_api_prefix,
|
||
content,
|
||
flags=re.IGNORECASE
|
||
)
|
||
# 兼容旧格式 /api/{company}_{app}{module}
|
||
content = re.sub(
|
||
rf'/api/{re.escape(old_company_app_pattern)}{re.escape(module_camel)}',
|
||
new_api_prefix,
|
||
content
|
||
)
|
||
else:
|
||
# old_class_prefix 为空,从文件内容检测实际的 API 路径模式
|
||
# 匹配 /api/{systemId}/{something} 或 /api/{company}_{app}{something}
|
||
detected = re.findall(r'/api/[^/]+/([A-Za-z_][A-Za-z0-9_]*)', content)
|
||
for old_path_class in set(detected):
|
||
# 如果检测到的路径包含下划线(说明是旧格式),则替换
|
||
if '_' in old_path_class:
|
||
old_api_pattern = rf'/api/\d+/{re.escape(old_path_class)}'
|
||
content = re.sub(old_api_pattern, new_api_prefix, content, flags=re.IGNORECASE)
|
||
old_api_pattern2 = rf'/api/{re.escape(old_company_app_pattern)}{re.escape(old_path_class.replace("_", "").lower())}'
|
||
content = re.sub(old_api_pattern2, new_api_prefix, content)
|
||
except Exception:
|
||
pass
|
||
if content != orig:
|
||
try:
|
||
with open(fpath, 'w', encoding='utf-8') as f:
|
||
f.write(content)
|
||
fixed += 1
|
||
except Exception:
|
||
pass
|
||
return fixed
|