471 lines
18 KiB
Python
471 lines
18 KiB
Python
#!/usr/bin/env python3
|
||
"""AIBridge 完整操作示例
|
||
|
||
演示 JNPF 低代码平台的所有主要操作:
|
||
1. 登录获取 token
|
||
2. 创建功能表单(可视化开发)
|
||
3. 发布功能表单(自动建表)
|
||
4. 创建菜单(目录 + 功能菜单)
|
||
5. 创建扩展数据接口(SQL 查询接口)
|
||
6. 创建简单工作流
|
||
7. 代码生成(含命名修复)
|
||
8. 挂载代码生成页面到菜单
|
||
9. 软删除菜单
|
||
10. 软删除功能表单
|
||
11. 清理测试数据
|
||
|
||
运行方式:
|
||
cd $ccWorkDir
|
||
python3 aibridge/examples/quickstart.py
|
||
|
||
注意:运行前确保 JNPF 后端已启动,且 config.py 中的配置正确。
|
||
"""
|
||
|
||
import sys
|
||
import time
|
||
import traceback
|
||
import os
|
||
import re
|
||
import shutil
|
||
|
||
# 统一设置路径
|
||
import os
|
||
sys.path.insert(0, os.environ["ccWorkDir"])
|
||
|
||
from aibridge import JNPFClient, JNPFConfig
|
||
from aibridge.builders.full_config import build_full_config, build_create_payload
|
||
from aibridge.models import FieldDef
|
||
from aibridge.utils.code_generator import CodeGenerator
|
||
|
||
|
||
# ==================== 配置 ====================
|
||
|
||
CONFIG = JNPFConfig()
|
||
|
||
# 测试用唯一标识(避免重复)
|
||
TS = str(int(time.time() * 1000)) # 毫秒级时间戳
|
||
TEST_PREFIX = f"qs_{TS}"
|
||
|
||
# ★★★ 命名规范(核心配置)★★★
|
||
# company_code = ssw, app_code = datar
|
||
# - 数据库表名:纯业务名(snake_case),如 images
|
||
# - Java 类名:纯业务名(PascalCase),如 ImagesEntity
|
||
# - module_name:传递给 CodeGenerator,用于前端路径和类名
|
||
company_code = CONFIG.company_code # ssw
|
||
app_code = CONFIG.app_code # ssms
|
||
BUSINESS_NAME = "Images" # ★ 纯业务名 PascalCase
|
||
BASE_TABLE_NAME = "images" # ★ 基础表名(snake_case)
|
||
MODULE_NAME = BUSINESS_NAME # ★ 传递给 CodeGenerator,生成 ImagesEntity
|
||
|
||
|
||
# ==================== 工具函数 ====================
|
||
|
||
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 cleanup_previous(client, config):
|
||
"""清理之前测试可能残留的数据"""
|
||
# 1. 清理流程模板(可能引用了表单,需先删)
|
||
resp = client.workflow.get_template_list({"keyword": BUSINESS_NAME, "currentPage": 1, "pageSize": 50})
|
||
for item in (resp.data or {}).get("list", []):
|
||
if item.get("fullName", "").find(BUSINESS_NAME) >= 0:
|
||
try:
|
||
client.workflow.delete_template(item["id"])
|
||
except Exception as e:
|
||
print(f" 删除流程模板失败(忽略): {e}")
|
||
# 2. 清理功能表单(使用 soft_delete 避免直接删除被引用的表单)
|
||
resp = client.visual_dev.get_list({"keyword": BUSINESS_NAME, "currentPage": 1, "pageSize": 200})
|
||
for item in (resp.data or {}).get("list", []):
|
||
if item.get("fullName", "").find(BUSINESS_NAME) >= 0:
|
||
try:
|
||
client.visual_dev.soft_delete(item["id"])
|
||
except Exception as e:
|
||
print(f" 软删除表单失败(忽略): {e}")
|
||
# 3. 清理菜单
|
||
resp = client.menu.get_list({"keyword": BUSINESS_NAME, "currentPage": 1, "pageSize": 200})
|
||
for item in (resp.data or {}).get("list", []):
|
||
if item.get("fullName", "").find(BUSINESS_NAME) >= 0:
|
||
try:
|
||
client.menu.delete(item["id"])
|
||
except Exception:
|
||
pass
|
||
# 4. 清理 DI
|
||
resp = client.data_interface.get_list({
|
||
"category": config.interface_category_id,
|
||
"keyword": BUSINESS_NAME,
|
||
"pageSize": 50,
|
||
})
|
||
for item in (resp.data or {}).get("list", []):
|
||
try:
|
||
client.data_interface.delete(item["id"])
|
||
except Exception:
|
||
pass
|
||
time.sleep(2) # 等待后端同步
|
||
|
||
|
||
def main():
|
||
created_ids = [] # 记录创建的资源,用于清理
|
||
|
||
# ============================================================
|
||
# 1. 登录
|
||
# ============================================================
|
||
step("1. 登录获取 token")
|
||
client = JNPFClient.from_config(CONFIG)
|
||
resp = client.login()
|
||
print(f" 登录结果: code={resp.code}, msg={resp.msg}")
|
||
ok(f"token: {client.token[:30]}...")
|
||
if resp.code != 200:
|
||
fail("登录失败,请检查配置")
|
||
return
|
||
|
||
# 清理上次测试残留
|
||
step("0. 清理上次测试残留")
|
||
cleanup_previous(client, CONFIG)
|
||
ok("清理完成")
|
||
|
||
# ============================================================
|
||
# 2. 检查表是否存在,如存在则加唯一后缀避免冲突
|
||
# ============================================================
|
||
step("2. 检查数据库表是否已存在")
|
||
from aibridge.modules.data_model import DataModelAPI
|
||
dm = DataModelAPI(client)
|
||
try:
|
||
table_info = dm.get_table_info(CONFIG.db_link_id, BASE_TABLE_NAME)
|
||
table_exists = table_info.success and table_info.data is not None
|
||
except Exception:
|
||
table_exists = False
|
||
if table_exists:
|
||
TABLE_NAME = f"{BASE_TABLE_NAME}_{TS[-6:]}"
|
||
ok(f"表 {BASE_TABLE_NAME} 已存在,使用唯一表名: {TABLE_NAME}")
|
||
else:
|
||
TABLE_NAME = BASE_TABLE_NAME
|
||
ok(f"表 {TABLE_NAME} 不存在,使用原始表名")
|
||
|
||
# ============================================================
|
||
# 3. 创建功能表单
|
||
# ============================================================
|
||
step("2. 创建功能表单")
|
||
# ★ 关键:表名使用纯业务名(如 images),不要加系统前缀
|
||
# JNPF 内部会处理为 ais_images,但代码生成器会按 module_name 生成正确类名
|
||
form_en_code = f"{TEST_PREFIX}_{TABLE_NAME}"
|
||
form_table = TABLE_NAME # ★ 纯业务名,不加 ais_ 前缀
|
||
form_name = f"{BUSINESS_NAME}_{TS[:6]}"
|
||
|
||
# FieldDef 定义表单字段(字段名用 f_ 前缀 + snake_case)
|
||
fields = [
|
||
FieldDef(field="f_name", field_name="镜像名称", required=True),
|
||
FieldDef(field="f_repository_id", field_name="仓库ID"),
|
||
FieldDef(field="f_image_version", field_name="镜像版本"),
|
||
FieldDef(field="f_full_path", field_name="完整路径"),
|
||
FieldDef(field="f_size", field_name="大小", jnpf_key="inputNumber"),
|
||
FieldDef(field="f_status", field_name="状态", jnpf_key="select", options=[
|
||
{"fullName": "运行中", "id": "1"},
|
||
{"fullName": "已停止", "id": "0"},
|
||
]),
|
||
FieldDef(field="f_describe", field_name="描述"),
|
||
]
|
||
|
||
config = build_full_config(
|
||
full_name=form_name,
|
||
en_code=form_en_code,
|
||
table_name=form_table, # ★ 纯业务表名
|
||
table_label=form_name,
|
||
description="aibridge quickstart 自动创建",
|
||
category="Web",
|
||
fields=[f.to_dict() if hasattr(f, "to_dict") else f for f in fields],
|
||
db_link_id=CONFIG.db_link_id,
|
||
)
|
||
payload = build_create_payload(config, dynamic_table=True)
|
||
|
||
create_resp = client.visual_dev.create(payload)
|
||
func_id = create_resp.id
|
||
if not func_id:
|
||
func_id = client.visual_dev.get_id_by_en_code(form_en_code)
|
||
print(f" 创建功能: code={create_resp.code}, msg={create_resp.msg}")
|
||
ok(f"func_id={func_id}, table={form_table}")
|
||
if not func_id:
|
||
fail("创建功能表单失败,跳过代码生成")
|
||
return
|
||
created_ids.append(("form", func_id))
|
||
|
||
# ============================================================
|
||
# 4. 发布功能表单(Release 时自动建表)
|
||
# ============================================================
|
||
step("4. 发布功能表单")
|
||
release_resp = client.visual_dev.release(func_id)
|
||
ok(f"发布: code={release_resp.code}, msg={release_resp.msg}")
|
||
time.sleep(2) # 等待发布完成
|
||
|
||
# ★ relationForm 后处理:从目标表单提取 columnOptions 并更新字段
|
||
# ============================================================
|
||
# 5. 创建菜单
|
||
# ============================================================
|
||
step("4. 创建菜单(目录 + 功能菜单)")
|
||
|
||
# 4a. 创建目录菜单
|
||
dir_en_code = f"{TEST_PREFIX}_dir"
|
||
dir_name = f"{BUSINESS_NAME}目录_{TS[:6]}"
|
||
dir_resp = client.menu.create_directory_menu(
|
||
full_name=dir_name,
|
||
en_code=dir_en_code,
|
||
icon="icon-ym icon-ym-folder",
|
||
sort_code=9999,
|
||
parent_id="-1",
|
||
)
|
||
dir_id = dir_resp.id
|
||
if not dir_id:
|
||
dir_id = client.menu.get_id_by_en_code(dir_en_code)
|
||
if not dir_id:
|
||
fail("创建目录菜单失败,功能菜单将挂在顶级")
|
||
dir_id = "-1"
|
||
else:
|
||
ok(f"目录菜单: id={dir_id}")
|
||
created_ids.append(("menu", dir_id))
|
||
|
||
# 4b. 创建功能菜单(挂在目录下)
|
||
menu_en_code = f"{TEST_PREFIX}_{TABLE_NAME}"
|
||
menu_name = f"{BUSINESS_NAME}_{TS[:6]}"
|
||
menu_resp = client.menu.create_form_menu(
|
||
full_name=menu_name,
|
||
en_code=menu_en_code,
|
||
visual_dev_id=func_id,
|
||
parent_id=dir_id or "-1",
|
||
sort_code=1,
|
||
)
|
||
menu_id = menu_resp.id
|
||
if not menu_id:
|
||
menu_id = client.menu.get_id_by_en_code(menu_en_code)
|
||
ok(f"功能菜单: id={menu_id}")
|
||
created_ids.append(("menu", menu_id))
|
||
|
||
# ============================================================
|
||
# 6. 创建扩展数据接口
|
||
# ============================================================
|
||
step("5. 创建扩展数据接口(SQL 查询)")
|
||
di_en_code = f"{TEST_PREFIX}_{TABLE_NAME}_query"
|
||
di_name = f"{BUSINESS_NAME}查询_{TS[:6]}"
|
||
di_id = client.data_interface.create_sql_interface(
|
||
full_name=di_name,
|
||
en_code=di_en_code,
|
||
sql=f"""-- 业务说明:查询镜像列表
|
||
-- 业务逻辑:
|
||
-- 1. 筛选指定项目的镜像
|
||
-- 2. 按创建时间倒序
|
||
-- 对应业务类:sSW.ais.service.{BUSINESS_NAME}Service.list()
|
||
SELECT f_id as id, f_name as name, f_image_version as version,
|
||
f_full_path as path, f_size as size, f_status as status
|
||
FROM {TABLE_NAME}
|
||
WHERE f_status = '1'
|
||
ORDER BY f_create_time DESC""",
|
||
parameters=[],
|
||
category=CONFIG.interface_category_id,
|
||
action=3, # 3=查询
|
||
db_link_id=CONFIG.db_link_id,
|
||
)
|
||
ok(f"数据接口: id={di_id}, enCode={di_en_code}")
|
||
created_ids.append(("di", di_id))
|
||
|
||
# 执行接口验证(表可能无数据,不致命错误)
|
||
try:
|
||
exec_result = client.data_interface.execute(di_id, {})
|
||
ok(f"执行接口返回 {len(exec_result)} 条记录")
|
||
except RuntimeError as e:
|
||
ok(f"执行接口暂时失败(表无数据属正常): {e}")
|
||
|
||
# ============================================================
|
||
# 7. 创建简单工作流
|
||
# ============================================================
|
||
step("6. 创建简单工作流")
|
||
flow_en_code = f"{TEST_PREFIX}_{TABLE_NAME}_flow"
|
||
flow_name = f"{BUSINESS_NAME}审批流_{TS[:6]}"
|
||
try:
|
||
flow_result = client.workflow.create_simple_flow(
|
||
full_name=flow_name,
|
||
en_code=flow_en_code,
|
||
form_id=func_id,
|
||
approver_user_ids=[], # 空审批人(创建模板用)
|
||
form_name=form_name,
|
||
description="aibridge quickstart 自动创建",
|
||
release_immediately=True,
|
||
)
|
||
template_id = flow_result["template_id"]
|
||
version_id = flow_result["version_id"]
|
||
ok(f"工作流模板: template_id={template_id}, version_id={version_id}")
|
||
created_ids.append(("flow_template", template_id))
|
||
except RuntimeError as e:
|
||
fail(f"创建工作流失败: {e}")
|
||
template_id = None
|
||
version_id = None
|
||
|
||
# ============================================================
|
||
# 8. 代码生成(含命名修复)
|
||
# ============================================================
|
||
step("7. 代码生成(含命名修复)")
|
||
|
||
# 使用 CodeGenerator 生成代码
|
||
gen = CodeGenerator(client, CONFIG)
|
||
result = gen.generate(
|
||
func_id=func_id,
|
||
module_name=MODULE_NAME, # ★ 传递纯业务名(Images),生成 ImagesEntity
|
||
enable_flow=0,
|
||
tables="0",
|
||
form_type="2", # 2=Detail(表单+列表)
|
||
description=form_name,
|
||
)
|
||
|
||
frontend_path = None
|
||
backend_path = None
|
||
if not result.get('success'):
|
||
fail(f"代码生成失败: {result.get('message')}")
|
||
# 继续执行挂载菜单步骤(使用 func_id 作为 moduleId)
|
||
else:
|
||
ok(result.get('message'))
|
||
backend_path = result.get('backend_path')
|
||
frontend_path = result.get('frontend_path')
|
||
ok(f"后端路径: {backend_path}")
|
||
ok(f"前端路径: {frontend_path}")
|
||
|
||
# ★★★ 命名修复(自动从 formData 计算旧前缀)★★★
|
||
ok(f"修复类名前缀: * → {MODULE_NAME}*")
|
||
fix_result = gen.fix_class_names(backend_path, None, MODULE_NAME, frontend_path)
|
||
for old, new_item in fix_result.get('backend', []):
|
||
ok(f" {old} → {new_item}")
|
||
ok(f"后端 {len(fix_result.get('backend', []))} 个文件,前端 {fix_result.get('frontend', 0)} 个文件")
|
||
|
||
# ============================================================
|
||
# 9. 挂载代码生成页面到菜单
|
||
# ============================================================
|
||
step("8. 挂载代码生成页面到菜单")
|
||
|
||
# 获取页面中的 moduleId(从生成的 index.vue 或配置中读取)
|
||
# 此处演示完整参数,实际使用时需要从生成的代码中获取
|
||
gen_menu_en_code = f"{TEST_PREFIX}_{TABLE_NAME}_gen"
|
||
gen_menu_name = f"{BUSINESS_NAME}代码生成_{TS[:6]}"
|
||
page_folder = MODULE_NAME.lower() # images(前端文件夹名)
|
||
|
||
# 尝试从生成的 index.vue 中提取 moduleId
|
||
# frontend_path 可能为 None(代码生成失败时),使用 config 中的路径
|
||
module_id = None
|
||
index_vue_path = os.path.join(frontend_path, 'index.vue') if frontend_path else \
|
||
os.path.join(CONFIG.frontend_views_path, company_code, app_code, page_folder, 'index.vue')
|
||
if index_vue_path and os.path.exists(index_vue_path):
|
||
with open(index_vue_path, 'r', encoding='utf-8') as f:
|
||
content = f.read()
|
||
m = re.search(r'moduleId:\s*["\']?(\d+)["\']?', content)
|
||
if m:
|
||
module_id = m.group(1)
|
||
|
||
if not module_id:
|
||
# fallback:使用 func_id 作为 moduleId
|
||
module_id = func_id
|
||
|
||
import json
|
||
menu_data = {
|
||
"parentId": dir_id or "-1",
|
||
"fullName": gen_menu_name,
|
||
"enCode": gen_menu_en_code,
|
||
"type": 2, # 页面菜单
|
||
"category": "Web",
|
||
"icon": "icon-ym icon-ym-generator-function",
|
||
"urlAddress": f"model/{gen_menu_en_code}",
|
||
# pageAddress: 代码生成页面实际路径
|
||
"pageAddress": f"{company_code}/{app_code}/{page_folder}",
|
||
"propertyJson": json.dumps({
|
||
"iconBackgroundColor": "",
|
||
"isTree": 0,
|
||
"moduleId": module_id,
|
||
"webType": 2,
|
||
}, ensure_ascii=False),
|
||
"enabledMark": 1,
|
||
"sortCode": 2,
|
||
"isButtonAuthorize": 0,
|
||
"isColumnAuthorize": 0,
|
||
"isDataAuthorize": 0,
|
||
"isFormAuthorize": 0,
|
||
}
|
||
|
||
gen_menu_resp = client.menu.create(menu_data)
|
||
gen_menu_id = getattr(gen_menu_resp, 'id', None) or (gen_menu_resp.data.get("id") if hasattr(gen_menu_resp, 'data') and gen_menu_resp.data else None)
|
||
# JNPF 有时会返回成功但 id=None,需通过 en_code 查询修复
|
||
if not gen_menu_id:
|
||
gen_menu_id = client.menu.get_id_by_en_code(gen_menu_en_code)
|
||
if gen_menu_id:
|
||
ok(f"菜单创建成功: id={gen_menu_id}")
|
||
created_ids.append(("menu", gen_menu_id))
|
||
else:
|
||
fail(f"菜单创建失败: {gen_menu_resp}")
|
||
|
||
# ============================================================
|
||
# 10. 软删除功能菜单(保留目录)
|
||
# ============================================================
|
||
step("9. 软删除功能菜单")
|
||
if menu_id:
|
||
soft_resp = client.menu.soft_delete(menu_id)
|
||
ok(f"软删除功能菜单: code={soft_resp.code}, msg={soft_resp.msg}")
|
||
exists = client.menu.check_en_code_exists(menu_en_code)
|
||
ok(f"原编码 {menu_en_code} 已释放: {not exists}")
|
||
|
||
# ============================================================
|
||
# 11. 软删除功能表单
|
||
# ============================================================
|
||
step("10. 软删除功能表单")
|
||
soft_resp = client.visual_dev.soft_delete(func_id)
|
||
ok(f"软删除功能: code={soft_resp.code}, msg={soft_resp.msg}")
|
||
exists = client.visual_dev.check_en_code_exists(form_en_code)
|
||
ok(f"原编码 {form_en_code} 已释放: {not exists}")
|
||
|
||
# ============================================================
|
||
# 11. 清理测试数据
|
||
# ============================================================
|
||
step("11. 清理测试数据")
|
||
for resource_type, rid in reversed(created_ids):
|
||
if not rid or rid == "-1":
|
||
continue
|
||
try:
|
||
if resource_type == "flow_template":
|
||
client.workflow.delete_template(rid)
|
||
ok(f"删除工作流模板 {rid}")
|
||
elif resource_type == "menu":
|
||
client.menu.delete(rid)
|
||
ok(f"删除菜单 {rid}")
|
||
elif resource_type == "di":
|
||
client.data_interface.delete(rid)
|
||
ok(f"删除数据接口 {rid}")
|
||
elif resource_type == "form":
|
||
client.visual_dev.delete(rid)
|
||
ok(f"删除功能 {rid}")
|
||
except Exception as e:
|
||
fail(f"清理 {resource_type} {rid}: {e}")
|
||
|
||
# ============================================================
|
||
# 完成
|
||
# ============================================================
|
||
print(f"\n{'='*60}")
|
||
print(" 全部操作完成!")
|
||
print(f"{'='*60}")
|
||
print(f"\n命名规范总结:")
|
||
print(f" 数据库表名: {TABLE_NAME} (纯业务名 snake_case)")
|
||
print(f" Java 类名: {MODULE_NAME}Entity (纯业务名 PascalCase)")
|
||
print(f" 前端页面: {frontend_path}")
|
||
print(f" 后端模块: {backend_path}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|