Files
aibridge/docs/development-guide.md
T
2026-05-18 09:28:15 +08:00

26 KiB
Raw Blame History

开发指南

AIBridge 完整开发工作流:从需求分析到上线部署。

开发流程总览

需求规划 → 字段定义 → 配置构建 → 功能创建 → 发布 → 创建菜单 → 数据字典 → 工作流集成 → 测试验证 → 上线

第一步:需求规划

在编码之前,明确以下信息:

1.1 确定模块结构

业务系统(App-Code: wj)
├── 目录:办公用品管理
│   ├── 功能:文具分类(字典维护)
│   ├── 功能:销售商管理
│   ├── 功能:文具产品管理
│   └── 功能:文具订单管理
└── 目录:统计分析
    └── 功能:销售报表

1.2 确定功能类型

web_type 说明 适用场景
1 纯表单 单条数据录入
2 表单加列表 最常用,标准 CRUD
3 表单列表工作流 需要审批的功能
4 数据视图 统计报表

1.3 收集平台参数

# 需要预先获取的参数
app_code = "wj"
SYSTEM_ID = "your_system_id"       # 仅做记录,实际由 app_code 自动解析
CATEGORY_ID = "your_category_id"

第二步:字段定义

2.1 支持的控件类型

AIBridge 支持 25+ 种 JNPF 控件类型:

jnpf_key 控件 适用字段
input 文本输入 名称、编码、描述
textarea 多行文本 长描述、备注
inputNumber / numInput 数字输入 价格、数量、金额
select 下拉选择 状态、类型
radio 单选 性别、是否
checkbox 多选 兴趣标签
date 日期 出生日期、截止日期
datetime 日期时间 创建时间、更新时间
time 时间 营业时间
switch 开关 启用/禁用
cascader 级联选择 省市区
address 地址 联系地址
uploadImg 图片上传 头像、产品图
uploadFile 文件上传 附件
rate 评分 满意度
comSelect 公司选择 所属公司
treeSelect 树形选择 组织架构
popupTable 弹窗表格 关联数据选择
relationForm 关联表单 关联详情
relationFlow 关联流程 关联审批

2.4 关联表单(relationForm)注意事项

relationForm 字段用于在一个表单中关联另一个表单的数据(如"镜像管理"关联"仓库管理")。 由于需要知道目标表单的 visual_dev_id,它必须通过两阶段创建实现:

阶段一:创建被引用的表单(如"仓库管理")
  → build_full_config + create + release → 得到 form_id_A

阶段二:创建引用方表单(如"镜像管理")
  → build_full_config → 修正 relationForm 字段的 modelId 和 columnOptions → create + release

relationForm 字段的关键属性:

属性 含义 示例
modelId 目标表单的 visual_dev ID "807267538537809157"
relationField 目标表单中作为显示文本的字段 "f_repository_name"
propsValue 提交时提交的字段名(默认 "id") "id"
hasPage 弹出窗口是否分页(默认 False) True
columnOptions 弹出窗口的列表列配置 见下方

columnOptions items 必须包含 value 字段:

前端 RelationForm.vue 用 o.value 作为表格列的 dataIndex:

const columns = (props.columnOptions).map((o) => ({
  dataIndex: o.value,   // 必须有值,否则 .includes() 报错
}));

正确的 columnOptions item 结构:

{
    "value": "f_repository_name",   # ← 关键!等于数据库字段名
    "label": "仓库名称",
    "fullName": "仓库名称",
    "fullNameI18nCode": [""],
    "width": "150",
    "align": "left",
    "headerAlign": "left",
    "sortable": True,
    "jnpfKey": "input",
    "sourceType": 2,
    "__vModel__": "f_repository_name",
    "clearable": True,
}

完整的两阶段创建示例参考 aibridge/examples/create_image_management.py。

2.2 字段命名注意事项

F_Version 是系统关键字:字段名不能使用 F_Version,否则会报错:

版本号-F_Version不能使用系统、开发语言及数据库关键字命名

解决方案:使用替代命名,如 F_VerCode。

2.3 支持的数据类型

data_type 说明 示例
varchar 字符串 "200"
int 整数 "9"
decimal 小数 "18,2"
bigint 长整数 "18"
datetime 日期时间 -
text 长文本 -
date 日期 -

2.3 字段定义示例

# 产品管理字段
product_fields = [
    {"field": "f_name", "fieldName": "产品名称", "jnpfKey": "input", "required": True, "dataType": "varchar", "dataLength": "100"},
    {"field": "f_code", "fieldName": "产品编码", "jnpfKey": "input", "required": True, "dataType": "varchar", "dataLength": "50"},
    {"field": "f_category", "fieldName": "产品分类", "jnpfKey": "select", "dataType": "varchar", "dataLength": "50"},
    {"field": "f_price", "fieldName": "单价", "jnpfKey": "inputNumber", "dataType": "decimal", "dataLength": "18,2"},
    {"field": "f_stock", "fieldName": "库存", "jnpfKey": "inputNumber", "dataType": "int", "dataLength": "9"},
    {"field": "f_unit", "fieldName": "单位", "jnpfKey": "select", "dataType": "varchar", "dataLength": "20"},
    {"field": "f_image", "fieldName": "产品图片", "jnpfKey": "uploadImg"},
    {"field": "f_description", "fieldName": "产品描述", "jnpfKey": "textarea", "dataType": "varchar", "dataLength": "500"},
    {"field": "f_enabled", "fieldName": "是否上架", "jnpfKey": "switch"},
]

# 订单管理字段(含工作流)
order_fields = [
    {"field": "f_order_no", "fieldName": "订单编号", "jnpfKey": "input", "required": True, "dataType": "varchar", "dataLength": "50"},
    {"field": "f_customer", "fieldName": "客户名称", "jnpfKey": "input", "required": True, "dataType": "varchar", "dataLength": "100"},
    {"field": "f_amount", "fieldName": "订单金额", "jnpfKey": "inputNumber", "required": True, "dataType": "decimal", "dataLength": "18,2"},
    {"field": "f_order_date", "fieldName": "下单日期", "jnpfKey": "datePicker", "required": True},
    {"field": "f_remark", "fieldName": "备注", "jnpfKey": "textarea", "dataType": "varchar", "dataLength": "500"},
]

第三步:创建功能

3.1 建表策略选择

JNPF 创建功能时有两种建表策略:

策略 适用场景 说明
动态建表(推荐) 全新功能,表不需要预先存在 create 传空 tables,Release 时自动建表
预建表 已有物理表(手动建/迁移/外部系统) create 传完整 tables,要求物理表已存在

数据库连接:通过 db_link_id 指定("0" 为主数据库),可在 JNPFConfig 中配置, 或在平台「数据中心→数据连接」中创建业务数据库连接。

系统隔离规则:业务系统的表应建在系统对应的数据连接下,不要使用 db_link_id="0"(主库)。 当前系统配置见 aibridge/config.py。

3.2 使用配置构建器(推荐)

from aibridge.builders.full_config import build_full_config, build_create_payload

# 构建完整配置
config = build_full_config(
    full_name="产品管理",
    en_code="productManage",
    table_name="product",
    table_label="产品表",
    description="产品信息管理",
    category=CATEGORY_ID,
    fields=product_fields,
    db_link_id="0",           # 数据库连接 ID(默认主数据库)
    web_type=2,
    search_field_count=3,      # 前3个字段作为搜索条件
    display_field_count=4,      # 前4个字段显示在列表
)

# 动态建表模式(默认,推荐)
payload = build_create_payload(config)                  # 传空 tables
resp = client.visual_dev.create(payload)
func_id = resp.id
client.visual_dev.release(func_id)                      # Release 自动建表

# 预建表模式(表已存在时)
client.data_model.get_table_info("0", "product")       # 先确认表存在
payload = build_create_payload(config, dynamic_table=False)  # 传完整 tables
resp = client.visual_dev.create(payload)
client.visual_dev.release(func_id)

3.3 DataModel 数据库操作

创建功能后,通过 data_model 模块管理数据库表:

# 查询表列表
resp = client.data_model.get_table_list("0", {"keyword": "product"})
for t in resp.data.get("list", []):
    print(f'{t["table"]} - {t["comment"]} - {t.get("sum", 0)} 条记录')

# 查询表字段
resp = client.data_model.get_table_info("0", "product")
for f in resp.data.get("tableFieldList", []):
    print(f'{f["field"]} {f["dataType"]}({f.get("dataLength", "")}) '
          f'PK={f["primaryKey"]} Required={1 - f["allowNull"]}')

# 确认表是否存在(用于预建表模式)
resp = client.data_model.get_table_info("0", "product")
if resp.success:
    print("表已存在,可使用预建表模式")

3.2 主表 + 子表(table 控件)

AIBridge builder 原生支持 主表 + 子表 结构(JNPF 的 table 控件)。 通过 child_tables 参数定义子表,builder 会自动生成:

  • tables 中的主表(typeId=1)和子表(typeId=0)条目
  • formData 中的 table 控件及子表字段(isSubTable=true)
  • 子表外键自动创建(默认字段名 f_parent_id)
from aibridge.models import FieldDef
from aibridge.builders.full_config import build_full_config, build_create_payload

# 主表字段
main_fields = [
    FieldDef("f_customer", "客户名称", required=True),
    FieldDef("f_contact", "联系人"),
    FieldDef("f_phone", "联系电话"),
]

# 子表字段
child_fields = [
    FieldDef("f_month", "缴费月份"),
    FieldDef("f_amount", "费用金额", data_type="decimal", data_length="18,2"),
    FieldDef("f_total", "合计", data_type="decimal", data_length="18,2"),
]

config = build_full_config(
    full_name="文具应收费用",
    en_code="stationeryReceivable",
    table_name="wj_receivable",
    table_label="文具应收费用表",
    description="文具业务应收费用管理",
    category="",
    fields=[f.to_dict() for f in main_fields],
    child_tables=[{
        "table_name": "wj_receivable_detail",
        "table_label": "文具应收费用明细表",
        "fields": [f.to_dict() for f in child_fields],
        "label": "添加明细",
        "foreign_key_field": "f_receivable_id",  # 子表外键字段名(默认 f_parent_id)
        "show_summary": 0,                       # 是否显示合计行
        "summary_field": [],                     # 合计字段列表
    }],
)

payload = build_create_payload(config)
resp = client.visual_dev.create(payload)
client.visual_dev.release(resp.id)

子表数据写入(create_model 时子表数据以子表名为 key):

client.visual_dev.create_model(model_id, {
    "f_customer": "ABC公司",
    "f_contact": "张经理",
    "wj_receivable_detail": [
        {"f_month": "2026-01", "f_amount": 1500.00, "f_total": 1500.00},
        {"f_month": "2026-02", "f_amount": 1200.00, "f_total": 1200.00},
    ],
})

完整示例:aibridge/examples/create_stationery_receivable.py

3.3 构建器参数说明

build_full_config 参数:

参数 类型 说明
full_name str 功能中文名
en_code str 功能英文编码(唯一)
table_name str 数据库表名(业务表 snake_case 无前缀,平台表 base_ 前缀不变)
table_label str 表中文名
description str 功能描述
category str 分类 ID
fields list 字段定义列表
child_tables list 子表定义列表(可选,见 3.2)
db_link_id str 数据库连接 ID(业务表用系统连接,不要用 "0")
web_type int 页面类型(1/2/3/4)
search_field_count int 搜索字段数量
display_field_count int 列表显示字段数量

child_tables 子表定义:

字段 类型 说明
table_name str 子表数据库表名
table_label str 子表中文名
fields list 子表字段定义列表
label str 表单中子表标签(默认 "添加明细")
foreign_key_field str 外键字段名(默认 "f_parent_id")
relation_field str 主表关联字段(默认 "F_Id")
show_summary int 是否显示合计行(0/1)
summary_field list 合计字段 vModel 列表

build_create_payload 参数:

参数 类型 说明
config dict build_full_config 返回的配置
dynamic_table bool True=动态建表(默认),False=预建表模式

3.4 关联表单控件(relationForm)

关联表单用于引用其他功能的数据,点击时弹出目标表单的数据列表供选择。

from aibridge.models import FieldDef
from aibridge.builders.full_config import build_full_config, build_create_payload

fields = [
    FieldDef("f_order_no", "订单编号", required=True),
    # 关联表单:关联到「文具应收费用」,显示 f_customer 字段
    FieldDef("f_customer_id", "关联客户", jnpf_key="relationForm"),
    FieldDef("f_total_amount", "订单金额", jnpf_key="inputNumber",
             data_type="decimal", data_length="18,2"),
]

config = build_full_config(
    full_name="文具销售订单",
    en_code="wjStationeryOrder",
    table_name="wj_order",
    table_label="文具销售订单表",
    description="文具销售订单",
    category="",
    fields=[f.to_dict() for f in fields],
)

# relationForm 需要设置 modelId(目标表单 ID)和 relationField(显示字段)
import json
form_data = json.loads(config["formData"])
for f in form_data["fields"]:
    if f["__config__"]["jnpfKey"] == "relationForm":
        f["modelId"] = "807225892043490565"  # 目标功能的 visual_dev ID
        f["relationField"] = "f_customer"     # 目标表单中显示的字段 vModel
config["formData"] = json.dumps(form_data, ensure_ascii=False)

payload = build_create_payload(config)
resp = client.visual_dev.create(payload)
client.visual_dev.release(resp.id)

数据写入:关联表单存储的是目标记录的主键 ID。

client.visual_dev.create_model(model_id, {
    "f_order_no": "ORD-2026-001",
    "f_customer_id": "807225892999791877",  # 应收费用记录的主键
    "f_total_amount": 2800.00,
})

relationForm 字段属性:

属性 说明
modelId 目标表单的 visual_dev ID(功能 ID)
relationField 目标表单中用于显示的字段 vModel
popupType 弹窗类型("dialog"/"drawer")
popupWidth 弹窗宽度
hasPage 是否分页

完整示例:aibridge/examples/create_stationery_order.py

3.5 手动构建(高级用法)

如果需要更细粒度的控制,可以单独使用各构建器:

from aibridge.builders.table_config import build_tables
from aibridge.builders.form_config import build_form_data
from aibridge.builders.column_config import build_column_data
import json

# 单独构建表结构
tables = build_tables("product", "产品表", product_fields)

# 单独构建表单配置
form_data = build_form_data(product_fields, "product")

# 单独构建列表配置
column_data = build_column_data(product_fields, "product", search_field_count=3, display_field_count=4)

# 组装 payload
payload = {
    "fullName": "产品管理",
    "enCode": "productManage",
    "type": 1,
    "webType": 2,
    "state": 0,
    "sortCode": 1000,
    "category": CATEGORY_ID,
    "dbLinkId": "0",
    "tables": json.dumps(tables, ensure_ascii=False),
    "formData": json.dumps(form_data, ensure_ascii=False),
    "columnData": json.dumps(column_data, ensure_ascii=False),
}

第四步:发布

4.1 标准发布流程

# 发布(systemId 在创建时已由 App-Code 自动设置,无需手动修正)
release_resp = visual_dev.release(func_id)
print(f"发布: {release_resp.msg}")

4.2 验证发布结果

# 检查发布状态
info = visual_dev.get_info(func_id)
print(f"状态: {info.data.get('state')}")  # 1=已发布

# 检查菜单可见性
menu_list = menu_api.get_list()
for item in menu_list.data:
    print(f"菜单: {item.get('fullName')} (id={item.get('id')})")

第五步:创建菜单结构

5.1 代码生成页面挂载到菜单

对于通过 JNPF 代码生成功能生成的页面(位于 views/{company}/{app_code}/{page}),需要通过 type=2 页面菜单 挂载到系统菜单中。

文件路径约定:

前端: web/apps/jnpf-web-apps-main/src/views/{company_code}/{app_code}/{页面名}
后端: boot/{company_code}-{app_code}/

示例: 将 views/{company_code}/{app_code}/aaa 页面挂载到菜单

import json

# 创建代码生成页面菜单(type=2 页面菜单)
data = {
    "parentId": "-1",                           # 父菜单ID,-1表示顶级
    "fullName": "测试功能表gen",                 # 菜单显示名称(加 gen 后缀区别)
    "enCode": "testFuncTableGen",               # 菜单编码(唯一)
    "type": 2,                                  # 2=页面菜单(链接到自定义页面)
    "category": "Web",
    "icon": "icon-ym icon-ym-generator-function",
    "urlAddress": "model/testFuncTableGen",     # 前端路由路径
    "pageAddress": "{company_code}/{app_code}/aaa",  # 代码生成页面实际路径
    "propertyJson": json.dumps({
        "iconBackgroundColor": "",
        "isTree": 0,
        "moduleId": "807529252202218757",       # 与页面中的 moduleId 一致
        "webType": 2,                           # 2=表单加列表
    }, ensure_ascii=False),
    "enabledMark": 1,
    "sortCode": 0,
    "isButtonAuthorize": 0,
    "isColumnAuthorize": 0,
    "isDataAuthorize": 0,
    "isFormAuthorize": 0,
}

resp = client.menu.create(data)
menu_id = resp.id

关键点:

参数 说明
type=2 页面菜单类型,用于链接到外部或自定义页面
urlAddress 使用 model/{enCode} 格式,JNPF 前端会自动映射
pageAddress 关键! 代码生成页面的实际路径,格式为 {company_code}/{app_code}/{页面文件夹}
propertyJson.moduleId 必须与代码生成页面中的 moduleId 一致(从页面的 defaultSearchInfo.moduleId 获取)
enCode 建议加 gen 后缀与 VisualDev 功能区分

完整脚本参考: aibridge/examples/mount_codegen_page.py

5.2 标准菜单层级

所有 create_* 方法已内置 id=null 自动修复,直接使用即可。

# 一级目录
dir1 = menu_api.create_directory_menu("办公用品", "office_dir", sort_code=100)
dir1_id = dir1.id

# 二级功能菜单
menu_api.create_form_menu("产品管理", "productList", func_id, dir1_id, web_type=2)
menu_api.create_form_menu("销售商管理", "vendorList", vendor_func_id, dir1_id, web_type=2)
menu_api.create_form_menu("订单管理", "orderList", order_func_id, dir1_id, web_type=2)

5.3 多级目录

# 一级目录
top_dir = menu_api.create_directory_menu("业务管理", "biz_dir", sort_code=100)
top_dir_id = top_dir.id

# 二级目录
sub_dir = menu_api.create_directory_menu(
    full_name="办公用品",
    en_code="office_dir",
    sort_code=100,
    parent_id=top_dir_id,
)
sub_dir_id = sub_dir.id

# 三级功能
menu_api.create_form_menu(
    full_name="产品列表",
    en_code="productList",
    visual_dev_id=func_id,
    parent_id=sub_dir_id,
    web_type=2,
)

第六步:数据字典

6.1 创建字典分类和数据

from aibridge.modules.dictionary import DictionaryAPI

dict_api = DictionaryAPI(client)

# 创建分类
type_resp = dict_api.create_type({
    "fullName": "产品分类",
    "enCode": "productCategory",
})
type_id = type_resp.id

# 创建字典数据
dict_api.create_data({
    "typeId": type_id,
    "fullName": "办公用品",
    "enCode": "office",
    "sortCode": 1,
    "enabledMark": 1,
})
dict_api.create_data({
    "typeId": type_id,
    "fullName": "电子设备",
    "enCode": "electronics",
    "sortCode": 2,
    "enabledMark": 1,
})

6.2 在表单中使用字典

字典创建后,可以在表单字段的 options 中引用:

# 获取功能配置
info = visual_dev.get_info(func_id)
form_data = json.loads(info.data["formData"])

# 找到需要关联字典的字段
for field in form_data["fields"]:
    if field["__vModel__"] == "f_category":
        field["options"] = [
            {"fullName": "办公用品", "id": "office"},
            {"fullName": "电子设备", "id": "electronics"},
        ]
        break

# 更新功能配置
update_data = {
    "id": func_id,
    "fullName": info.data["fullName"],
    "formData": json.dumps(form_data, ensure_ascii=False),
}
visual_dev.update(update_data)

第七步:工作流集成

7.1 创建带工作流的功能

# web_type=3 表示表单列表工作流
order_config = build_full_config(
    full_name="采购申请",
    en_code="purchaseRequest",
    table_name="purchase_request",
    table_label="采购申请表",
    description="采购审批流程",
    category=CATEGORY_ID,
    fields=order_fields,
    web_type=3,  # 带工作流
)

7.2 工作流详细指南

请参阅 工作流指南。

7.3 工作流创建最佳实践

使用 create_simple_flow() 便捷方法一步完成模板创建和发布:

# 一步创建流程模板(内部自动处理 create_template + get_version_list + save_flow)
flow_result = client.workflow.create_simple_flow(
    full_name="采购审批",
    en_code="purchaseApproval",
    form_id=func_id,
    approver_user_ids=["approver_user_id"],
    form_name="采购申请",
    flow_type=1,  # 1=简单流程(推荐新手)
)

# 发起流程(formData 自动序列化为 JSON 字符串)
task_resp = client.workflow.launch_task(flow_result["version_id"], {
    "f_order_no": "PO-2026-001",
    "f_customer": "测试公司",
    "f_amount": 5000.00,
})

# 审批(自动带 status=1)
pending = client.workflow.get_pending_tasks()
if pending:
    client.workflow.approve(pending[0]["taskOperatorId"], "同意")

注意事项:

  • webType=3(表单列表工作流)才能绑定流程模板
  • create_template 必须包含 flowXml/flowNodes/flowConfig(create_simple_flow 已内置处理)
  • 审批接口需要 status 字段(approve/reject 便捷方法已内置处理)
  • launch_task 的 formData 直接传 dict,不要 json.dumps(后端 Map<String, Object> 类型)
  • 发起人和审批人不能是同一用户
  • 删除资源顺序:流程模板 → 表单 → 功能菜单 → 目录菜单(先解除引用再删除)

第八步:代码生成与导出

8.1 代码预览

# 预览生成的代码
preview_resp = visual_dev.code_preview(func_id, {"type": 1})
print(f"生成的代码: {preview_resp.data}")

8.2 下载代码

# 下载完整代码包
download_resp = visual_dev.download_code(func_id, {"type": 1})

扩展点

自定义 API 接口

通过数据接口(DataInterface)实现自定义查询:

from aibridge.modules.data_interface import DataInterfaceAPI
import json

di_api = DataInterfaceAPI(client)

# 创建自定义查询接口
di_api.create({
    "fullName": "产品库存查询",
    "enCode": "productStockQuery",
    "requestMethod": 1,
    "dataConfigJson": json.dumps({
        "staticData": "",
        "sqlData": {
            "dbLinkId": "0",
            "sql": "SELECT p.f_name, p.f_stock, p.f_price FROM product p WHERE p.f_enabled = 1"
        },
        "apiData": {"method": 1, "url": "", "header": [], "query": [], "body": "", "bodyType": 0},
    }),
})

# 执行查询
result = di_api.preview(di_id, {"keyword": "文具"})

前端脚本扩展

在表单配置中使用 funcs 钩子:

form_data["funcs"] = {
    "beforeSubmit": "({ data, onlineUtils }) => { data.f_order_no = 'ORD-' + Date.now(); }",
    "onLoad": "({ data, onlineUtils }) => { console.log('表单加载', data); }",
    "afterSubmit": "({ data, onlineUtils }) => { onlineUtils.$message.success('提交成功'); }",
}

最佳实践

1. 配置集中管理

PROJECT_CONFIG = {
    "base_url": "http://localhost:30000",
    "app_code": "wj",
    "system_id": "your_system_id",
    "category_id": "your_category_id",
}

2. 字段定义复用

COMMON_FIELDS = [
    {"field": "f_description", "fieldName": "描述", "jnpfKey": "textarea", "dataType": "varchar", "dataLength": "500"},
    {"field": "f_sort_code", "fieldName": "排序", "jnpfKey": "inputNumber", "dataType": "int", "dataLength": "9"},
    {"field": "f_enabled", "fieldName": "是否启用", "jnpfKey": "switch"},
]

all_fields = [
    {"field": "f_name", "fieldName": "名称", "jnpfKey": "input", "required": True},
    *COMMON_FIELDS,
]

3. 错误处理

from aibridge import APIError, AuthError, JNPFError

try:
    resp = client.login(account="admin", password=pwd)
except AuthError as e:
    print(f"认证错误: {e.msg}")
except JNPFError as e:
    print(f"平台错误: {e.msg}")

4. 批量操作

for module_def in module_definitions:
    config = build_full_config(**module_def)
    payload = build_create_payload(config)
    resp = visual_dev.create(payload)
    func_id = resp.id
    visual_dev.release(func_id)
    print(f"  {module_def['full_name']}: {func_id}")

5. 日志记录

import logging
logging.basicConfig(level=logging.INFO)
# AIBridge 自动记录: 登录成功/失败、API 错误、DI 代理 SQL 执行、system_id 自动设置