feat: initial commit

This commit is contained in:
admin committed 2026-05-18 09:28:15 +08:00
commit 539b115e38
232 files changed
+31223

No files matched your search

+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""AIBridge 代码生成与菜单挂载脚本
用法:
python3 run-codegen.py # 交互模式(显示系统菜单树供选择)
python3 run-codegen.py <func_id> <module_name> [menu_title] # 参数模式
示例:
python3 run-codegen.py 808986025610185477 Project 项目管理
python3 run-codegen.py 808986025610185477 Project "项目管理" --parent "AI训练"
"""
import sys
import os
import re
import json
import argparse
from typing import Optional
# 项目根目录(上三层:scripts/ → .claude/ → 项目根)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, PROJECT_DIR)
from aibridge import JNPFClient, JNPFConfig
from aibridge.utils.code_generator import CodeGenerator
def step(title):
print(f"\n{'='*60}")
print(f" {title}")
print(f"{'='*60}")
def ok(msg):
print(f" [OK] {msg}")
def fail(msg):
print(f" [FAIL] {msg}")
def print_menu_tree(menus: list, indent: int = 0) -> None:
"""打印菜单树(友好展示)"""
prefix = " " * indent
for menu in menus:
menu_type = {1: "📁", 2: "📄", 3: "🔗"}.get(menu.get("type"), "📄")
print(f"{prefix}{menu_type} {menu.get('fullName', '')} [{menu.get('enCode', '')}]")
children = menu.get("children") or []
if children:
print_menu_tree(children, indent + 1)
def find_parent_id(client: JNPFClient, parent_name: str) -> Optional[str]:
"""通过菜单名称查找父级菜单 ID(支持模糊匹配)
Args:
parent_name: 父级菜单名称(支持模糊匹配,如 "AI训练" 匹配 "AI训练开发系统")
Returns:
菜单 ID,未找到返回 None
"""
resp = client.menu.get_selector_all()
if resp.code != 200:
return None
items = resp.data.get("list", []) if resp.data else []
# 精确匹配优先,再模糊匹配
for item in items:
if item.get("fullName") == parent_name:
return item.get("id")
for item in items:
if parent_name in item.get("fullName", ""):
return item.get("id")
return None
def get_old_class_prefix(form_data_str: str, app_code: str) -> str:
"""从 formData JSON 中提取表名,计算旧类名前缀
JNPF 生成 {app_code}_{table_name} → Ais_aisproject
table_name 本身含系统前缀,如 ais_aisproject
"""
if not form_data_str:
return app_code.capitalize()
form_data = json.loads(form_data_str)
table_name = form_data.get('tableName', '')
if table_name:
return table_name.capitalize() # ais_aisproject → Ais_aisproject
return app_code.capitalize()
def main():
parser = argparse.ArgumentParser(description='AIBridge 代码生成与菜单挂载')
parser.add_argument('func_id', nargs='?', help='功能ID')
parser.add_argument('module_name', nargs='?', help='模块名称(PascalCase)')
parser.add_argument('menu_title', nargs='?', help='菜单标题')
parser.add_argument('--parent', help='父级菜单名称(模糊匹配,如 "AI训练")')
parser.add_argument('--parent-id', help='父级菜单ID(直接指定)')
args = parser.parse_args()
config = JNPFConfig()
client = JNPFClient.from_config(config)
client.login()
# 参数处理
func_id = args.func_id
module_name = args.module_name
menu_title = args.menu_title
parent_id = args.parent_id
parent_name = args.parent
if not func_id or not module_name:
step("AIBridge 代码生成与菜单挂载")
func_id = input("请输入功能ID(func_id,可从菜单URL复制): ").strip()
module_name = input("请输入模块名称(PascalCase,如 Project/Images): ").strip()
menu_title = input("请输入菜单标题(直接回车使用默认值): ").strip() or f"{module_name}代码生成菜单"
parent_name = input("请输入父级菜单名称(直接回车显示菜单树选择): ").strip()
if not parent_name:
step("系统菜单树")
resp = client.menu.get_selector_all()
if resp.code == 200 and resp.data:
print_menu_tree(resp.data.get("list", []))
print()
parent_name = input("请输入父级菜单名称: ").strip()
else:
menu_title = menu_title or f"{module_name}代码生成菜单"
# 如果没有指定 parent_id,通过名称查找
if not parent_id and parent_name:
parent_id = find_parent_id(client, parent_name)
if parent_id:
ok(f"找到父级菜单: {parent_name} → id={parent_id}")
else:
fail(f"未找到父级菜单: {parent_name}")
# 列出菜单树供用户选择
resp = client.menu.get_selector_all()
if resp.code == 200 and resp.data:
print("\n可用菜单:")
print_menu_tree(resp.data.get("list", []))
return
if not parent_id:
fail("未指定父级菜单")
return
# ========== Step 1: 代码生成 ==========
step("Step 1/4 代码生成")
gen = CodeGenerator(client, config)
result = gen.generate(
func_id=func_id,
module_name=module_name,
enable_flow=0,
tables='0',
form_type='2',
description=menu_title,
)
if not result.get('success'):
fail(f"代码生成失败: {result.get('message')}")
return
backend_path = result.get('backend_path')
frontend_path = result.get('frontend_path')
ok(f"代码生成成功")
ok(f"后端: {backend_path}")
ok(f"前端: {frontend_path}")
# ========== Step 2: 获取表单信息,计算旧类名前缀 ==========
step("Step 2/4 类名修复")
resp = client.request('GET', f'/api/visualdev/Base/{func_id}')
old_prefix = get_old_class_prefix(
resp.data.get('formData', '') if resp.success and resp.data else '',
config.app_code
)
ok(f"修复类名前缀: {old_prefix}* → {module_name}*")
fix_result = gen.fix_class_names(backend_path, old_prefix, module_name, frontend_path)
for old, new in fix_result['backend']:
ok(f" {old} → {new}")
ok(f"后端 {len(fix_result['backend'])} 个文件,前端 {fix_result['frontend']} 个文件")
# ========== Step 3: 获取 moduleId ==========
step("Step 3/4 获取 moduleId")
module_id = func_id
index_vue = os.path.join(frontend_path, 'index.vue')
if os.path.exists(index_vue):
with open(index_vue, 'r', encoding='utf-8') as f:
content = f.read()
m = re.search(r"moduleId:\s*['\"]?(\d+)", content)
if m:
module_id = m.group(1)
ok(f"moduleId: {module_id}")
# ========== Step 4: 挂载菜单 ==========
step("Step 4/4 挂载菜单")
menu_en_code = f"{config.app_code}_{module_name.lower()}_gen"
parts = config.module_package_name.split('.') # [company_code, app_code]
menu_data = {
"parentId": parent_id,
"fullName": menu_title,
"enCode": menu_en_code,
"type": 2,
"category": "Web",
"icon": "icon-ym icon-ym-generator-function",
"urlAddress": f"model/{menu_en_code}",
"pageAddress": f"{parts[0]}/{parts[1]}/{module_name}",
"propertyJson": json.dumps({
"iconBackgroundColor": "",
"isTree": 0,
"moduleId": module_id,
"webType": 2,
}, ensure_ascii=False),
"enabledMark": 1,
"sortCode": 0,
"isButtonAuthorize": 0,
"isColumnAuthorize": 0,
"isDataAuthorize": 0,
"isFormAuthorize": 0,
}
resp = client.menu.create(menu_data)
menu_id = getattr(resp, 'id', None) or (
resp.data.get('id') if hasattr(resp, 'data') and resp.data else None
)
if not menu_id:
menu_id = client.menu.get_id_by_en_code(menu_en_code)
if menu_id:
ok(f"菜单创建成功: id={menu_id}")
else:
fail(f"菜单创建失败: code={resp.code}, msg={resp.msg}")
# ========== 完成 ==========
step("完成")
print(f" 功能ID: {func_id}")
print(f" 模块名: {module_name}")
print(f" 菜单标题: {menu_title}")
print(f" 父级ID: {parent_id}")
print(f" 前端路径: {frontend_path}")
print(f" 后端路径: {backend_path}")
print(f" 菜单ID: {menu_id}")
if __name__ == '__main__':
main()