commit 539b115e3886145884cc9b6e52f886b1e5a0d394 Author: admin Date: Mon May 18 09:28:15 2026 +0800 feat: initial commit diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..f3d6dd9 Binary files /dev/null and b/.DS_Store differ diff --git a/.omc/.DS_Store b/.omc/.DS_Store new file mode 100644 index 0000000..fc353cc Binary files /dev/null and b/.omc/.DS_Store differ diff --git a/.omc/state/idle-notif-cooldown.json b/.omc/state/idle-notif-cooldown.json new file mode 100644 index 0000000..d11afd6 --- /dev/null +++ b/.omc/state/idle-notif-cooldown.json @@ -0,0 +1,3 @@ +{ + "lastSentAt": "2026-04-06T11:40:43.992Z" +} \ No newline at end of file diff --git a/.omc/state/last-tool-error.json b/.omc/state/last-tool-error.json new file mode 100644 index 0000000..6bf0c3b --- /dev/null +++ b/.omc/state/last-tool-error.json @@ -0,0 +1,7 @@ +{ + "tool_name": "Bash", + "tool_input_preview": "{\"command\":\"cd /Users/xs/Desktop/6.2 && python3 << 'EOF'\\nfrom aibridge import setup_path\\nsetup_path()\\nfrom aibridge.client import JNPFClient\\nfrom aibridge.config import JNPFConfig\\n\\nconfig = JNPF...", + "error": "Exit code 1\nLogin OK\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.13/site-packages/requests/models.py\", line 971, in json\n return complexjson.loads(self.text, **kwargs)\n ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/Cellar/python@3.13/3.13.3_1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/json/__init__.py\", line 346, in loads\n return _default_decoder.decode(s)\n ~~~~~~~~~~~~~~~~~~~~~~~^^^\n File \"/usr/local/Cellar/python@3.13/3...", + "timestamp": "2026-04-06T10:42:00.191Z", + "retry_count": 2 +} \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..a189d31 --- /dev/null +++ b/__init__.py @@ -0,0 +1,86 @@ +"""AIBridge - JNPF 低代码平台 Python 接口包 + +通过 AI 对话快速完成产品设计、应用开发和验证。 + +使用方法: + # 方式一:在项目根目录运行 + cd /path/to/project + python3 -m aibridge.examples.example_name + + # 方式二:在 examples 目录运行 + cd /path/to/project/aibridge/examples + python3 example_name.py + + # 方式三:使用统一入口(自动设置路径) + import sys + from aibridge import setup_path + setup_path() # 自动添加项目根目录到 sys.path + + from aibridge import JNPFClient, JNPFConfig + # ... +""" + +__version__ = "1.0.0" +__author__ = "AIBridge" + +import os +import sys + + +def setup_path() -> None: + """统一设置 sys.path,确保能正确导入 aibridge 模块。 + + 调用此函数会自动将项目根目录添加到 sys.path。 + 项目根目录 = aibridge 包所在目录的父目录。 + + 推荐在所有示例脚本开头调用此函数: + + from aibridge import setup_path + setup_path() + + from aibridge import JNPFClient, JNPFConfig + # ... + """ + # 获取 aibridge 包所在目录 + aibridge_dir = os.path.dirname(os.path.abspath(__file__)) + # 项目根目录 = aibridge 的父目录 + project_root = os.path.dirname(aibridge_dir) + + # 如果项目根目录还不在 sys.path 中,则添加 + if project_root not in sys.path: + sys.path.insert(0, project_root) + + +def check_python_version() -> bool: + """检查 Python 版本,确保是 python3。 + + Returns: + True 如果是 python3,False 否则 + """ + version = sys.version_info + if version.major < 3: + print(f"错误:需要 Python 3.x,当前版本是 {version.major}.{version.minor}") + print("请使用 python3 命令运行此脚本") + return False + return True + + +# 导出公共接口 +from aibridge.client import JNPFClient +from aibridge.config import JNPFConfig +from aibridge.exceptions import JNPFError, AuthError, APIError +from aibridge.models import APIResponse + +__all__ = [ + # 核心 + "JNPFClient", + "JNPFConfig", + "APIResponse", + # 异常 + "JNPFError", + "AuthError", + "APIError", + # 工具函数 + "setup_path", + "check_python_version", +] diff --git a/__pycache__/__init__.cpython-312.pyc b/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..4601c69 Binary files /dev/null and b/__pycache__/__init__.cpython-312.pyc differ diff --git a/__pycache__/__init__.cpython-313.pyc b/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..65cdfb4 Binary files /dev/null and b/__pycache__/__init__.cpython-313.pyc differ diff --git a/__pycache__/client.cpython-312.pyc b/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000..ff24eaa Binary files /dev/null and b/__pycache__/client.cpython-312.pyc differ diff --git a/__pycache__/client.cpython-313.pyc b/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000..949be75 Binary files /dev/null and b/__pycache__/client.cpython-313.pyc differ diff --git a/__pycache__/config.cpython-312.pyc b/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000..219ad01 Binary files /dev/null and b/__pycache__/config.cpython-312.pyc differ diff --git a/__pycache__/config.cpython-313.pyc b/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000..fef9e5f Binary files /dev/null and b/__pycache__/config.cpython-313.pyc differ diff --git a/__pycache__/exceptions.cpython-312.pyc b/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000..d702810 Binary files /dev/null and b/__pycache__/exceptions.cpython-312.pyc differ diff --git a/__pycache__/exceptions.cpython-313.pyc b/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000..4fe88b3 Binary files /dev/null and b/__pycache__/exceptions.cpython-313.pyc differ diff --git a/__pycache__/models.cpython-312.pyc b/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000..cc15815 Binary files /dev/null and b/__pycache__/models.cpython-312.pyc differ diff --git a/__pycache__/models.cpython-313.pyc b/__pycache__/models.cpython-313.pyc new file mode 100644 index 0000000..0b3dd70 Binary files /dev/null and b/__pycache__/models.cpython-313.pyc differ diff --git a/appconfig/.DS_Store b/appconfig/.DS_Store new file mode 100644 index 0000000..7b24677 Binary files /dev/null and b/appconfig/.DS_Store differ diff --git a/appconfig/__init__.py b/appconfig/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/appconfig/__pycache__/__init__.cpython-312.pyc b/appconfig/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..75876eb Binary files /dev/null and b/appconfig/__pycache__/__init__.cpython-312.pyc differ diff --git a/appconfig/__pycache__/__init__.cpython-313.pyc b/appconfig/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..bfe5701 Binary files /dev/null and b/appconfig/__pycache__/__init__.cpython-313.pyc differ diff --git a/appconfig/__pycache__/config_dd.cpython-312.pyc b/appconfig/__pycache__/config_dd.cpython-312.pyc new file mode 100644 index 0000000..7a8ac43 Binary files /dev/null and b/appconfig/__pycache__/config_dd.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_dr.cpython-312.pyc b/appconfig/__pycache__/config_dr.cpython-312.pyc new file mode 100644 index 0000000..f95ff76 Binary files /dev/null and b/appconfig/__pycache__/config_dr.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_dr.cpython-313.pyc b/appconfig/__pycache__/config_dr.cpython-313.pyc new file mode 100644 index 0000000..31d0cab Binary files /dev/null and b/appconfig/__pycache__/config_dr.cpython-313.pyc differ diff --git a/appconfig/__pycache__/config_jxcj.cpython-312.pyc b/appconfig/__pycache__/config_jxcj.cpython-312.pyc new file mode 100644 index 0000000..352cd18 Binary files /dev/null and b/appconfig/__pycache__/config_jxcj.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_jyzs.cpython-312.pyc b/appconfig/__pycache__/config_jyzs.cpython-312.pyc new file mode 100644 index 0000000..ae48e31 Binary files /dev/null and b/appconfig/__pycache__/config_jyzs.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_newapp.cpython-312.pyc b/appconfig/__pycache__/config_newapp.cpython-312.pyc new file mode 100644 index 0000000..ca7348d Binary files /dev/null and b/appconfig/__pycache__/config_newapp.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_ssms.cpython-312.pyc b/appconfig/__pycache__/config_ssms.cpython-312.pyc new file mode 100644 index 0000000..cceed60 Binary files /dev/null and b/appconfig/__pycache__/config_ssms.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_sswportal.cpython-312.pyc b/appconfig/__pycache__/config_sswportal.cpython-312.pyc new file mode 100644 index 0000000..7ea0011 Binary files /dev/null and b/appconfig/__pycache__/config_sswportal.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_tdc.cpython-312.pyc b/appconfig/__pycache__/config_tdc.cpython-312.pyc new file mode 100644 index 0000000..70b0db8 Binary files /dev/null and b/appconfig/__pycache__/config_tdc.cpython-312.pyc differ diff --git a/appconfig/__pycache__/config_tds.cpython-312.pyc b/appconfig/__pycache__/config_tds.cpython-312.pyc new file mode 100644 index 0000000..c66edf0 Binary files /dev/null and b/appconfig/__pycache__/config_tds.cpython-312.pyc differ diff --git a/appconfig/config_dd.py b/appconfig/config_dd.py new file mode 100644 index 0000000..c8cda78 --- /dev/null +++ b/appconfig/config_dd.py @@ -0,0 +1,8 @@ +"""App 配置 - 测试 (dd)""" + +app_code: str = "dd" +system_title: str = "测试" +system_id: str = "824295337236629189" +db_link_id: str = "2054490688536317952" +interface_category_id: str = "824295339530913477" +business_category_id: str = "824295339908400837" diff --git a/appconfig/config_dr.py b/appconfig/config_dr.py new file mode 100644 index 0000000..fbd8871 --- /dev/null +++ b/appconfig/config_dr.py @@ -0,0 +1,8 @@ +"""App 配置 - 数据资产管理平台 (dr)""" + +app_code: str = "dr" +system_title: str = "数据资产管理平台" +system_id: str = "821711157730476101" +db_link_id: str = "2051905879476453376" +interface_category_id: str = "812979854893908293" +business_category_id: str = "812979855015543109" diff --git a/appconfig/config_jxcj.py b/appconfig/config_jxcj.py new file mode 100644 index 0000000..069ea97 --- /dev/null +++ b/appconfig/config_jxcj.py @@ -0,0 +1,8 @@ +"""App 配置 - 江财数智大赛 (jxcj)""" + +app_code: str = "jxcj" +system_title: str = "江财数智大赛" +system_id: str = "813341589253390341" +db_link_id: str = "2043536939842416640" +interface_category_id: str = "813341590457155589" +business_category_id: str = "813341590650093573" diff --git a/appconfig/config_jyzs.py b/appconfig/config_jyzs.py new file mode 100644 index 0000000..9e77ff3 --- /dev/null +++ b/appconfig/config_jyzs.py @@ -0,0 +1,8 @@ +"""App 配置 - 交易助手 (jyzs)""" + +app_code: str = "jyzs" +system_title: str = "交易助手" +system_id: str = "811938353527135109" +db_link_id: str = "2042386207729803264" +interface_category_id: str = "811938354168863621" +business_category_id: str = "811938354340830085" diff --git a/appconfig/config_newapp.py b/appconfig/config_newapp.py new file mode 100644 index 0000000..eaecfbb --- /dev/null +++ b/appconfig/config_newapp.py @@ -0,0 +1,9 @@ +"""App 配置 - New Application (newapp)""" + +app_code: str = "newapp" +system_title: str = "New Application" +system_id: str = "728867800898255737" +db_link_name: str = "newdb" +db_link_id: str = "" +interface_category_id: str = "" +business_category_id: str = "" diff --git a/appconfig/config_ssms.py b/appconfig/config_ssms.py new file mode 100644 index 0000000..4ad7da5 --- /dev/null +++ b/appconfig/config_ssms.py @@ -0,0 +1,8 @@ +"""App 配置 - 尚数密算 (ssms)""" + +app_code: str = "ssms" +system_title: str = "尚数密算" +system_id: str = "811616853779552901" +db_link_id: str = "2041812204325728256" +interface_category_id: str = "811616854844906117" +business_category_id: str = "811616854987512453" diff --git a/appconfig/config_sswportal.py b/appconfig/config_sswportal.py new file mode 100644 index 0000000..27b0b03 --- /dev/null +++ b/appconfig/config_sswportal.py @@ -0,0 +1,8 @@ +"""App 配置 - 尚数网官网 (sswportal)""" + +app_code: str = "sswportal" +system_title: str = "尚数网官网" +system_id: str = "815243258971030853" +db_link_id: str = "2045438609439354880" +interface_category_id: str = "815243259755365701" +business_category_id: str = "815243259994441029" diff --git a/appconfig/config_tdc.py b/appconfig/config_tdc.py new file mode 100644 index 0000000..7b13a99 --- /dev/null +++ b/appconfig/config_tdc.py @@ -0,0 +1,17 @@ +"""App 配置 - 接入连接器 (tdc)""" + +app_code: str = "tdc" +system_title: str = "接入连接器" +system_id: str = "816537010347966981" +db_link_id: str = "2046732360698667008" +interface_category_id: str = "816537011182633477" +business_category_id: str = "816537011342017029" + +# TDS 平台 API 地址(供 TDC 调用) +tds_api_base: str = "http://127.0.0.1:30000/api" +tds_app_code: str = "tds" + +# TDS 平台 OAuth 认证(供 TDC 调用) +tds_oauth_id: str = "None" +tds_oauth_app_id: str = "tdc_connector" +tds_oauth_app_secret: str = "tdc_tds_connector_secret_2024" diff --git a/appconfig/config_tds.py b/appconfig/config_tds.py new file mode 100644 index 0000000..3941360 --- /dev/null +++ b/appconfig/config_tds.py @@ -0,0 +1,8 @@ +"""App 配置 - 可信数据空间 (tds)""" + +app_code: str = "tds" +system_title: str = "可信数据空间" +system_id: str = "816331189550842245" +db_link_id: str = "2046526540199313408" +interface_category_id: str = "816331190771384709" +business_category_id: str = "816331190968516997" diff --git a/builders/.DS_Store b/builders/.DS_Store new file mode 100644 index 0000000..a8f7d6f Binary files /dev/null and b/builders/.DS_Store differ diff --git a/builders/__init__.py b/builders/__init__.py new file mode 100644 index 0000000..022ed10 --- /dev/null +++ b/builders/__init__.py @@ -0,0 +1,27 @@ +"""AIBridge 构建器模块""" + +from aibridge.builders.field_model import build_field_model, build_table_field_model +from aibridge.builders.form_config import build_form_data +from aibridge.builders.column_config import build_column_data +from aibridge.builders.table_config import ( + build_tables, + build_main_table_entry, + build_child_table_entry, + build_tables_with_child, +) +from aibridge.builders.full_config import build_full_config +from aibridge.builders.mobile_field_model import build_mobile_field, build_mobile_column_data + +__all__ = [ + "build_field_model", + "build_table_field_model", + "build_form_data", + "build_column_data", + "build_tables", + "build_main_table_entry", + "build_child_table_entry", + "build_tables_with_child", + "build_full_config", + "build_mobile_field", + "build_mobile_column_data", +] diff --git a/builders/__pycache__/__init__.cpython-312.pyc b/builders/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..43a5ed0 Binary files /dev/null and b/builders/__pycache__/__init__.cpython-312.pyc differ diff --git a/builders/__pycache__/column_config.cpython-312.pyc b/builders/__pycache__/column_config.cpython-312.pyc new file mode 100644 index 0000000..8b4385b Binary files /dev/null and b/builders/__pycache__/column_config.cpython-312.pyc differ diff --git a/builders/__pycache__/field_model.cpython-312.pyc b/builders/__pycache__/field_model.cpython-312.pyc new file mode 100644 index 0000000..3afe9ff Binary files /dev/null and b/builders/__pycache__/field_model.cpython-312.pyc differ diff --git a/builders/__pycache__/form_config.cpython-312.pyc b/builders/__pycache__/form_config.cpython-312.pyc new file mode 100644 index 0000000..b50f891 Binary files /dev/null and b/builders/__pycache__/form_config.cpython-312.pyc differ diff --git a/builders/__pycache__/full_config.cpython-312.pyc b/builders/__pycache__/full_config.cpython-312.pyc new file mode 100644 index 0000000..77bacdf Binary files /dev/null and b/builders/__pycache__/full_config.cpython-312.pyc differ diff --git a/builders/__pycache__/mobile_field_model.cpython-312.pyc b/builders/__pycache__/mobile_field_model.cpython-312.pyc new file mode 100644 index 0000000..8bae880 Binary files /dev/null and b/builders/__pycache__/mobile_field_model.cpython-312.pyc differ diff --git a/builders/__pycache__/table_config.cpython-312.pyc b/builders/__pycache__/table_config.cpython-312.pyc new file mode 100644 index 0000000..98a17bf Binary files /dev/null and b/builders/__pycache__/table_config.cpython-312.pyc differ diff --git a/builders/column_config.py b/builders/column_config.py new file mode 100644 index 0000000..bef93b1 --- /dev/null +++ b/builders/column_config.py @@ -0,0 +1,209 @@ +"""列表配置构建器 + +参考前端 ColumnDesign/src/helper/config.ts 中 defaultColumnData 的 columnData 部分。 +生成完整的 columnData JSON 配置,包含搜索条件、列显示、按钮配置等。 +""" + +from typing import Any, Dict, List + +from aibridge.builders.field_model import build_field_model + + +def build_column_data( + fields: List[Dict[str, Any]], + table_name: str = "base_table", + base_render_key: int = 0, + search_field_count: int = 3, + display_field_count: int = 3, +) -> Dict[str, Any]: + """构建列表配置 columnData JSON + + Args: + fields: 字段定义列表 + table_name: 表名 + base_render_key: 基础渲染键 + search_field_count: 搜索条件字段数量(默认前 3 个字段) + display_field_count: 列表显示字段数量(默认前 3 个字段) + + Returns: + columnData 字典(需 JSON 序列化后传入 API) + """ + all_field_models = [] + for i, f in enumerate(fields): + all_field_models.append(build_field_model( + field_name=f.get("fieldName", ""), + field_vmodel=f.get("field", ""), + jnpf_key=f.get("jnpfKey", "input"), + required=f.get("required", False), + table_name=table_name, + render_key=base_render_key + i, + options=f.get("options"), + dictionary_type=f.get("dictionaryType", ""), + )) + + # searchList - 前 N 个字段作为搜索条件 + search_list = [] + for fm in all_field_models[:search_field_count]: + search_list.append({ + "label": fm["fullName"], + "labelI18nCode": "", + "prop": fm["id"], + "jnpfKey": fm["__config__"]["jnpfKey"], + "sourceType": 2, + "searchType": 2, + "searchMultiple": False, + "isKeyword": False, + "id": fm["id"], + "fullName": fm["fullName"], + "fullNameI18nCode": [""], + **fm, + }) + + # columnList - 前 N 个字段显示在列表 + column_list = [] + for fm in all_field_models[:display_field_count]: + column_list.append({ + "label": fm["fullName"], + "labelI18nCode": "", + "prop": fm["id"], + "fixed": "none", + "headerAlign": "left", + "align": "left", + "jnpfKey": fm["__config__"]["jnpfKey"], + "sortable": False, + "width": None, + "id": fm["id"], + "fullName": fm["fullName"], + "fullNameI18nCode": [""], + **fm, + }) + + # columnOptions - 所有可选字段 + column_options = [] + for fm in all_field_models: + column_options.append({ + "id": fm["id"], + "fullName": fm["fullName"], + "fullNameI18nCode": [""], + **fm, + }) + + # defaultColumnList - 所有字段,前 N 个 checked=true + default_column_list = [] + for idx, fm in enumerate(all_field_models): + default_column_list.append({ + "label": fm["fullName"], + "labelI18nCode": "", + "prop": fm["id"], + "fixed": "none", + "headerAlign": "left", + "align": "left", + "jnpfKey": fm["__config__"]["jnpfKey"], + "sortable": False, + "width": None, + "id": fm["id"], + "fullName": fm["fullName"], + "fullNameI18nCode": [""], + "checked": idx < display_field_count, + **fm, + }) + + return { + "searchList": search_list, + "columnList": column_list, + "columnOptions": column_options, + "defaultColumnList": default_column_list, + + # 过滤规则 - SuperJsonModel 类型,必须是对象 + "ruleList": {"matchLogic": "and", "conditionList": []}, + + # 标签面板 - TabConfigModel 类型,不能为 null + "tabConfig": {"on": False, "relationField": "", "hasAllTab": True}, + + # 卡片布局配置 + "cardListConfig": { + "cardLayout": "horizontal", + "titleField": "", + "subTitleField": "", + "displayFields": "", + "columnCount": 1, + "enableImage": False, + "imageSource": "", + "displayPosition": "left", + "fillMode": "contain", + }, + + "customBtnsList": [], + + # 顶部按钮列表 + "btnsList": [ + {"show": True, "value": "add", "icon": "icon-ym icon-ym-btn-add", + "label": "新增", "labelI18nCode": "common.add2Text"}, + {"show": False, "value": "download", "icon": "icon-ym icon-ym-btn-download", + "label": "导出", "labelI18nCode": "common.exportText"}, + {"show": False, "value": "upload", "icon": "icon-ym icon-ym-btn-upload", + "label": "导入", "labelI18nCode": "common.importText"}, + {"show": False, "value": "batchRemove", "icon": "icon-ym icon-ym-btn-clearn", + "label": "批量删除", "labelI18nCode": "common.batchDelText"}, + {"show": False, "value": "batchPrint", "icon": "icon-ym icon-ym-report-icon-preview-printPreview", + "label": "批量打印", "labelI18nCode": "common.batchPrintText"}, + ], + + # 行操作按钮 + "columnBtnsList": [ + {"show": True, "value": "edit", "icon": "icon-ym icon-ym-btn-edit", + "label": "编辑", "labelI18nCode": "common.editText", + "event": {"enableFunc": "({ row, rowIndex, onlineUtils }) => { return true }"}}, + {"show": True, "value": "remove", "icon": "icon-ym icon-ym-btn-clearn", + "label": "删除", "labelI18nCode": "common.delText", + "event": {"enableFunc": "({ row, rowIndex, onlineUtils }) => { return true }"}}, + {"show": True, "value": "detail", "icon": "icon-ym icon-ym-generator-menu", + "label": "详情", "labelI18nCode": "common.detailText", + "event": {"enableFunc": "({ row, rowIndex, onlineUtils }) => { return true }"}}, + ], + + # 其他配置 + "resizable": True, + "hasSuperQuery": True, + "showOverflow": True, + "childTableStyle": 1, + "showSummary": False, + "summaryField": [], + "type": 1, + "defaultSortConfig": [], + "viewKey": "", + "hasPage": True, + "pageSize": 20, + "hasTreeQuery": False, + "treeTitle": "左侧标题", + "treeTitleI18nCode": "", + "treeDataSource": "dictionary", + "treeDictionary": "", + "treeRelation": "", + "treeRelationFieldSelectType": "all", + "treeRelationFieldAbleIds": [], + "treeSyncType": 0, + "treeSyncInterfaceId": "", + "treeSyncInterfaceName": "", + "treeSyncTemplateJson": [], + "treePropsUrl": "", + "treePropsName": "", + "treeTemplateJson": [], + "treePropsValue": "id", + "treePropsChildren": "children", + "treePropsLabel": "fullName", + "groupField": "", + "parentField": "", + "printIds": [], + "useColumnPermission": False, + "useFormPermission": False, + "useBtnPermission": False, + "useDataPermission": False, + "funcs": { + "afterOnload": "({ data, tableRef, onlineUtils }) => {}", + "rowStyle": "({ row, rowIndex }) => {}", + "cellStyle": "({ row, column, rowIndex, columnIndex }) => {}", + }, + "uploaderTemplateJson": {}, + "complexHeaderList": [], + } diff --git a/builders/field_model.py b/builders/field_model.py new file mode 100644 index 0000000..2801688 --- /dev/null +++ b/builders/field_model.py @@ -0,0 +1,294 @@ +"""字段模型构建器 + +参考前端 FieLdsModel 和 ConfigModel 结构。 +将简洁的字段定义转换为完整的 JNPF 字段模型。 +""" + +import time +from typing import Any, Dict, List, Optional + +# jnpfKey → (tagIcon, tag, placeholder 模板) +_JNPF_KEY_MAP = { + "input": ("icon-ym icon-ym-generator-input", "JnpfInput", "请输入{label}"), + "inputNumber": ("icon-ym icon-ym-generator-number", "JnpfInputNumber", "请输入{label}"), + "textarea": ("icon-ym icon-ym-generator-input", "JnpfInput", "请输入{label}"), + "select": ("icon-ym icon-ym-generator-select", "JnpfSelect", "请选择{label}"), + "datePicker": ("icon-ym icon-ym-generator-date", "JnpfDatePicker", "请选择{label}"), + "switch": ("icon-ym icon-ym-generator-switch", "JnpfSwitch", ""), + "checkbox": ("icon-ym icon-ym-generator-checkbox", "JnpfCheckbox", ""), + "radio": ("icon-ym icon-ym-generator-radio", "JnpfRadio", "请选择{label}"), + "numInput": ("icon-ym icon-ym-generator-number", "JnpfInputNumber", "请输入{label}"), + "comSelect": ("icon-ym icon-ym-generator-select", "JnpfComSelect", "请选择{label}"), + "cascader": ("icon-ym icon-ym-generator-cascader", "JnpfCascader", "请选择{label}"), + "treeSelect": ("icon-ym icon-ym-generator-tree", "JnpfTreeSelect", "请选择{label}"), + "address": ("icon-ym icon-ym-generator-address", "JnpfAddress", "请选择{label}"), + "uploadImg": ("icon-ym icon-ym-generator-upload", "JnpfUploadImg", ""), + "uploadFile": ("icon-ym icon-ym-generator-upload", "JnpfUploadFile", ""), + "rate": ("icon-ym icon-ym-generator-rate", "JnpfRate", ""), + "colorPicker": ("icon-ym icon-ym-generator-color", "JnpfColorPicker", ""), + "popupTable": ("icon-ym icon-ym-generator-popup", "JnpfPopupTable", ""), + "popupAttr": ("icon-ym icon-ym-generator-popup", "JnpfPopupAttr", ""), + "relationForm": ("icon-ym icon-ym-generator-relation", "JnpfRelationForm", ""), + "relationFlow": ("icon-ym icon-ym-generator-relation", "JnpfRelationFlow", ""), + "sign": ("icon-ym icon-ym-sign", "JnpfSign", ""), + "timePicker": ("icon-ym icon-ym-generator-date", "JnpfTime", "请选择{label}"), +} + + +def build_field_model( + field_name: str, + field_vmodel: str, + jnpf_key: str = "input", + required: bool = False, + table_name: str = "base_table", + render_key: int = 0, + is_sub_table: bool = False, + relation_table: str = "", + parent_vmodel: str = "", + options: List[Dict[str, Any]] = None, + dictionary_type: str = "", +) -> Dict[str, Any]: + """构建单个字段的 FieLdsModel + + Args: + field_name: 字段中文名,如 "销售商名称" + field_vmodel: 数据库字段名,如 "f_full_name" + jnpf_key: 控件类型,支持 25+ 种类型,"table" 表示子表控件 + required: 是否必填 + table_name: 所属表名 + render_key: 渲染键(自动生成) + is_sub_table: 是否为子表字段(table 控件的 children) + relation_table: 子表所属表名(子表字段必填) + parent_vmodel: 子表控件的 vModel(子表字段必填) + options: 下拉选项列表,仅 select/radio/comSelect 支持。 + 格式必须为 [{fullName: "显示文本", id: "值"}, ...], + 不是 [{label: "显示文本", value: "值"}, ...]。 + + Returns: + 完整的 FieLdsModel 字典 + """ + # JNPF 系统保留字段验证(只验证 f_version,大小写敏感) + if field_vmodel.lower() == "f_version": + raise ValueError(f"字段名 '{field_vmodel}' 是 JNPF 系统保留字段,禁止使用。") + # 提示字段命名规范(f_xx_xx 格式) + import re + if not re.match(r'^f_[a-z][a-z0-9]*(_[a-z0-9]+)*$', field_vmodel): + print(f"⚠️ 提示:字段名建议使用 f_xx_xx 格式(如 f_user_name),当前:{field_vmodel}") + + tag_icon, tag, placeholder_tpl = _JNPF_KEY_MAP.get(jnpf_key, _JNPF_KEY_MAP["input"]) + + model: Dict[str, Any] = { + "clearable": True, + "suffixIcon": "", + "addonAfter": "", + "__config__": { + "formId": 101, + "visibility": ["pc", "app"], + "jnpfKey": jnpf_key, + "noShow": False, + "tipLabel": "", + "dragDisabled": False, + "className": [], + "label": field_name, + "trigger": "blur", + "showLabel": True, + "required": required, + "tableName": table_name, + "renderKey": render_key, + "layout": "colFormItem", + "tagIcon": tag_icon, + "tag": tag, + "regList": [], + "dictionaryType": dictionary_type, # 数据字典类型ID + }, + "readonly": False, + "__vModel__": field_vmodel, + "showPassword": False, + "style": {"width": "100%"}, + "disabled": False, + "placeholder": placeholder_tpl.format(label=field_name) if placeholder_tpl else "", + "prefixIcon": "", + "addonBefore": "", + "on": {"change": "", "blur": ""}, + # columnOptions 额外字段 + "id": field_vmodel, + "fullName": field_name, + "fullNameI18nCode": [""], + } + + # 子表字段特有属性 + if is_sub_table: + model["__config__"]["isSubTable"] = True + model["__config__"]["relationTable"] = relation_table + model["__config__"]["parentVModel"] = parent_vmodel + model["__config__"]["span"] = 24 + + # 控件类型特有属性 + if jnpf_key == "switch": + model["activeValue"] = 1 + model["inactiveValue"] = 0 + elif jnpf_key == "inputNumber" or jnpf_key == "numInput": + model["step"] = 1 + model["controls"] = True + model["min"] = None + model["max"] = None + elif jnpf_key == "rate": + model["max"] = 5 + model["allowHalf"] = False + model["showText"] = False + elif jnpf_key == "textarea": + model["rows"] = 4 + model["maxlength"] = None + elif jnpf_key == "datePicker": + model["format"] = "yyyy-MM-dd" + model["valueFormat"] = "yyyy-MM-dd" + elif jnpf_key == "timePicker": + model["format"] = "HH:mm:ss" + model["valueFormat"] = "HH:mm:ss" + elif jnpf_key in ("select", "radio", "checkbox", "comSelect"): + model["multiple"] = False + # 使用字段定义中传入的 options + # 注意:options 必须使用 {fullName, id} 格式,不是 {label, value} + # 前端通过 props.label="fullName" 和 props.value="id" 读取选项 + model["options"] = options if options else [] + model["props"] = {"label": "fullName", "value": "id", "disabled": "disabled", "children": ""} + # 如果有数据字典类型,设置关联 + if dictionary_type: + model["__config__"]["dictionaryType"] = dictionary_type + elif jnpf_key == "relationForm": + model.update({ + "modelId": "", + "relationField": "", + "hasPage": False, + "pageSize": 20, + "queryType": 0, + "propsValue": None, + "extraOptions": [], + "columnOptions": [], + "clearable": True, + "popupType": "dialog", + "popupTitle": "选择数据", + "popupWidth": "800px", + "filterable": False, + "field": field_vmodel, + }) + + return model + + +def build_table_field_model( + label: str, + vmodel: str, + child_table_name: str, + children: List[Dict[str, Any]], + render_key: int = 0, + main_table_name: str = "", + show_summary: int = 0, + summary_field: Optional[List[str]] = None, +) -> Dict[str, Any]: + """构建 table 控件(子表)的 FieLdsModel + + Args: + label: 子表标签,如 "添加明细" + vmodel: 子表控件 vModel,如 "tableField107" + child_table_name: 子表数据库表名,如 "base_order_item" + children: 子表字段模型列表(通过 build_field_model 生成,需设 is_sub_table=True) + render_key: 渲染键 + main_table_name: 主表表名(用于 children 的 tableName) + show_summary: 是否显示合计行 (0=否, 1=是) + summary_field: 合计字段列表(vModel 列表) + + Returns: + 完整的 table 控件 FieLdsModel 字典 + """ + return { + "showSummary": show_summary, + "actionText": "添加", + "tableConf": {}, + "defaultValue": [], + "footerBtnsList": [ + {"btnIcon": "icon-ym icon-ym-btn-add", "show": True, + "label": "添加", "btnType": "primary", "value": "add"}, + {"btnIcon": "icon-ym icon-ym-btn-clearn", "showConfirm": True, + "show": True, "label": "批量删除", "btnType": "danger", "value": "batchRemove"}, + ], + "addTableConf": { + "popupType": "dialog", + "hasPage": True, + "popupTitle": "选择数据", + "pageSize": 20, + "columnOptions": [], + "interfaceId": "", + "interfaceName": "", + "relationOptions": [], + "templateJson": [], + "popupWidth": "800px", + }, + "columnBtnsList": [ + {"btnIcon": "icon-ym icon-ym-btn-edit", "show": True, + "label": "复制", "btnType": "primary", "value": "copy"}, + {"btnIcon": "icon-ym icon-ym-btn-clearn", "showConfirm": True, + "show": True, "label": "删除", "btnType": "danger", "value": "remove"}, + ], + "summaryField": summary_field or [], + "showDeleteBtn": True, + "addType": 0, + "__config__": { + "formId": 107, + "visibility": ["pc", "app"], + "jnpfKey": "table", + "defaultValue": [], + "noShow": False, + "tipLabel": "", + "dragDisabled": False, + "className": [], + "label": label, + "type": "table", + "showLabel": False, + "tableName": child_table_name, + "renderKey": render_key, + "layout": "rowFormItem", + "tagIcon": "icon-ym icon-ym-generator-table", + "children": children, + "showTitle": True, + "complexHeaderList": [], + "tag": "JnpfInputTable", + "componentName": f"table{render_key}", + "span": 24, + }, + "showAddBtn": True, + "__vModel__": vmodel, + "disabled": False, + "layoutType": "table", + } + + +def build_field_models( + fields: List[Dict[str, Any]], + table_name: str = "base_table", + base_render_key: int = 0, +) -> List[Dict[str, Any]]: + """批量构建字段模型 + + Args: + fields: 字段定义列表,每个元素参考 FieldDef.to_dict() 格式 + table_name: 表名 + base_render_key: 基础渲染键 + + Returns: + 字段模型列表 + """ + models = [] + for i, f in enumerate(fields): + model = build_field_model( + field_name=f.get("fieldName", ""), + field_vmodel=f.get("field", ""), + jnpf_key=f.get("jnpfKey", "input"), + required=f.get("required", False), + table_name=table_name, + render_key=base_render_key + i, + options=f.get("options"), + dictionary_type=f.get("dictionaryType", ""), + ) + models.append(model) + return models diff --git a/builders/form_config.py b/builders/form_config.py new file mode 100644 index 0000000..30477b9 --- /dev/null +++ b/builders/form_config.py @@ -0,0 +1,142 @@ +"""表单配置构建器 + +参考前端 ColumnDesign/src/helper/config.ts 中 defaultColumnData 的 formData 部分。 +生成完整的 formData JSON 配置,支持主表字段 + 子表(table 控件)。 +""" + +from typing import Any, Dict, List + +from aibridge.builders.field_model import build_field_model, build_table_field_model + + +def build_form_data( + fields: List[Dict[str, Any]], + table_name: str = "base_table", + base_render_key: int = 0, + child_tables: List[Dict[str, Any]] = None, +) -> Dict[str, Any]: + """构建表单配置 formData JSON + + Args: + fields: 主表字段定义列表 + table_name: 主表表名 + base_render_key: 基础渲染键 + child_tables: 子表定义列表,每个子表包含: + - label: 子表标签(如 "添加明细") + - child_table_name: 子表表名(如 "base_order_item") + - fields: 子表字段定义列表 + - show_summary: 是否显示合计行(默认 0) + - summary_field: 合计字段列表(默认空) + + Returns: + formData 字典(需 JSON 序列化后传入 API) + """ + form_fields = [] + render_counter = base_render_key + + # 主表字段 + for i, f in enumerate(fields): + form_fields.append(build_field_model( + field_name=f.get("fieldName", ""), + field_vmodel=f.get("field", ""), + jnpf_key=f.get("jnpfKey", "input"), + required=f.get("required", False), + table_name=table_name, + render_key=render_counter, + options=f.get("options"), + dictionary_type=f.get("dictionaryType", ""), + )) + render_counter += 1 + + # 子表控件 + if child_tables: + for ct in child_tables: + child_table_name = ct["child_table_name"] + child_fields = ct["fields"] + render_counter += 1 # table 控件自身占一个 render_key + table_render_key = render_counter + + # 构建子表 vModel: tableField{renderKey} + table_vmodel = f"tableField{table_render_key}" + + # 构建子表字段模型 + child_field_models = [] + for cf in child_fields: + child_field_models.append(build_field_model( + field_name=cf.get("fieldName", ""), + field_vmodel=cf.get("field", ""), + jnpf_key=cf.get("jnpfKey", "input"), + required=cf.get("required", False), + table_name=table_name, # 子表字段的 tableName 是主表名 + render_key=render_counter, + is_sub_table=True, + relation_table=child_table_name, + parent_vmodel=table_vmodel, + options=cf.get("options"), + dictionary_type=cf.get("dictionaryType", ""), + )) + render_counter += 1 + + # 构建 table 控件 + table_field = build_table_field_model( + label=ct.get("label", "添加明细"), + vmodel=table_vmodel, + child_table_name=child_table_name, + children=child_field_models, + render_key=table_render_key, + main_table_name=table_name, + show_summary=ct.get("show_summary", 0), + summary_field=ct.get("summary_field", []), + ) + form_fields.append(table_field) + + return { + "formRef": "formRef", + "formModel": "dataForm", + "size": "default", + "labelPosition": "right", + "labelWidth": 100, + "labelSuffix": "", + "formRules": "rules", + "popupType": "general", + "generalWidth": "600px", + "fullScreenWidth": "100%", + "drawerWidth": "600px", + "gutter": 15, + "disabled": False, + "span": 24, + "colon": False, + "hasCancelBtn": True, + "cancelButtonText": "取消", + "cancelButtonTextI18nCode": "common.cancelText", + "hasConfirmBtn": True, + "confirmButtonText": "确定", + "confirmButtonTextI18nCode": "common.okText", + "hasConfirmAndAddBtn": True, + "hasPrintBtn": False, + "printButtonText": "打印", + "printButtonTextI18nCode": "common.printText", + "customBtns": [], + "appCustomBtns": [], + "primaryKeyPolicy": 1, + "concurrencyLock": False, + "logicalDelete": False, + "dataLog": False, + "useBusinessKey": False, + "businessKeyList": [], + "businessKeyTip": "", + "printId": "", + "formStyle": "", + "classNames": [], + "className": [], + "classJson": "", + "detailExtraList": [], + "formBtns": False, + "tableName": table_name, + "fields": form_fields, + "funcs": { + "beforeSubmit": "", + "onLoad": "", + "afterSubmit": "", + }, + } diff --git a/builders/full_config.py b/builders/full_config.py new file mode 100644 index 0000000..cfef5b5 --- /dev/null +++ b/builders/full_config.py @@ -0,0 +1,203 @@ +"""完整配置构建器 + +一站式组合 table_config + form_config + column_config, +从简洁的字段描述生成完整的 VisualDev 创建 payload。 +支持主表 + 子表(table 控件)结构。 +""" + +import json +import time +from typing import Any, Dict, List, Optional + +from aibridge.builders.column_config import build_column_data +from aibridge.builders.form_config import build_form_data +from aibridge.builders.table_config import build_tables, build_tables_with_child + + +def build_full_config( + full_name: str, + en_code: str, + table_name: str, + table_label: str, + description: str, + category: str, + fields: List[Dict[str, Any]], + system_id: str = "", + db_link_id: str = None, # ★ 禁止使用 "0"(主库),必须显式传入业务库 ID + web_type: int = 2, + sort_code: int = 1000, + search_field_count: int = 3, + display_field_count: int = 3, + child_tables: Optional[List[Dict[str, Any]]] = None, +) -> Dict[str, Any]: + """构建完整的可视化开发功能配置 + + Args: + full_name: 功能名称,如 "文具销售商管理" + en_code: 功能编码,如 "salesVendorManage" + table_name: 数据库表名,如 "base_sales_vendor" + table_label: 表中文名,如 "文具销售商表" + description: 功能描述 + category: 分类 ID + fields: 字段定义列表,每个元素参考 FieldDef.to_dict() 格式 + system_id: 系统 ID(创建 API 不接受,仅用于发布后修正) + db_link_id: ★ 必须传入业务数据库连接 ID(禁止 "0" 主库)。从 config.db_link_id 获取 + web_type: 页面类型 (1=纯表单 2=表单加列表 3=表单列表工作流 4=数据视图) + sort_code: 排序码 + search_field_count: 搜索条件字段数量 + display_field_count: 列表显示字段数量 + child_tables: 子表定义列表,每个子表包含: + - table_name: 子表数据库表名(如 "base_order_item") + - table_label: 子表中文名(如 "订单明细表") + - fields: 子表字段定义列表 + - label: 表单中子表标签(如 "添加明细",默认 "添加明细") + - foreign_key_field: 外键字段名(默认 "F_ParentId") + - relation_field: 主表关联字段(默认 "F_Id") + - show_summary: 是否显示合计行(默认 0) + - summary_field: 合计字段列表(默认空) + + Returns: + 包含 tables/formData/columnData 和功能元数据的配置字典。 + tables, formData, columnData 为 JSON 字符串(API 要求)。 + """ + # ★ 强制校验:禁止 db_link_id 为 "0"(主库),业务表必须使用业务数据库 + if not db_link_id or db_link_id == "0": + raise ValueError( + 'db_link_id 不能为空或 "0"(主库)。' + '业务表必须创建在业务数据库中。请传入正确的 db_link_id(如 config.db_link_id)。' + ) + + render_key = int(time.time() * 1000) + + # 补全字段默认值 + for f in fields: + f.setdefault("jnpfKey", "input") + f.setdefault("required", False) + f.setdefault("dataType", "varchar") + f.setdefault("dataLength", "200") + + # 补全子表字段默认值 + if child_tables: + for ct in child_tables: + for cf in ct["fields"]: + cf.setdefault("jnpfKey", "input") + cf.setdefault("required", False) + cf.setdefault("dataType", "varchar") + cf.setdefault("dataLength", "200") + + # 构建 tables + if child_tables: + tables = build_tables_with_child(table_name, table_label, fields, child_tables) + else: + tables = build_tables(table_name, table_label, fields) + + # 构建 child_tables 参数给 form_config + form_child_tables = None + if child_tables: + form_child_tables = [] + for ct in child_tables: + form_child_tables.append({ + "child_table_name": ct["table_name"], + "fields": ct["fields"], + "label": ct.get("label", "添加明细"), + "show_summary": ct.get("show_summary", 0), + "summary_field": ct.get("summary_field", []), + }) + + form_data = build_form_data(fields, table_name, render_key, form_child_tables) + column_data = build_column_data( + fields, table_name, render_key, + search_field_count, display_field_count, + ) + + return { + "tables": json.dumps(tables, ensure_ascii=False), + "formData": json.dumps(form_data, ensure_ascii=False), + "columnData": json.dumps(column_data, ensure_ascii=False), + "appColumnData": json.dumps(column_data, ensure_ascii=False), # APP端列表配置,与PC端相同 + "full_name": full_name, + "en_code": en_code, + "description": description, + "category": category, + "system_id": system_id, + "db_link_id": db_link_id, + "web_type": web_type, + "sort_code": sort_code, + } + + +def build_create_payload(config: Dict[str, Any], dynamic_table: bool = True) -> Dict[str, Any]: + """从 build_full_config 的输出构建 API 创建 payload + + JNPF create 接口要求物理表已存在(会校验主键策略),有两种策略: + + **动态建表模式 (dynamic_table=True,默认)**: + create 时传空 tables,跳过物理表校验;Release 时自动建表。 + 适用于全新功能,表不需要预先存在。 + + **预建表模式 (dynamic_table=False)**: + create 时传完整 tables,要求物理表必须已存在。 + 适用于已有物理表的场景(如手动建表、从其他系统迁移)。 + 使用前先通过 `client.data_model.get_table_info(link_id, table)` 确认表存在。 + + Args: + config: build_full_config 返回的配置字典 + dynamic_table: 是否动态建表(默认 True) + + Returns: + 可直接传入 VisualDevAPI.create() 的 data 字典 + """ + return { + "fullName": config["full_name"], + "enCode": config["en_code"], + "type": 1, + "description": config["description"], + "webType": config["web_type"], + "state": 0, + "sortCode": config["sort_code"], + "category": config["category"], + "dbLinkId": config.get("db_link_id", "0"), + "tables": "[]" if dynamic_table else config["tables"], + "formData": config["formData"], + "columnData": config["columnData"], + "appColumnData": config.get("appColumnData", config["columnData"]), # APP端列表配置 + } + + +def build_update_payload(config: Dict[str, Any], form_id: str) -> Dict[str, Any]: + """从 build_full_config 的输出构建 API 更新 payload + + .. warning:: + update API 的后端实现 (ConcurrencyUtils.checkAutoIncrement) + 通过 JDBC 查询**物理数据库表**的主键信息,而非读取 JSON 配置。 + 因此调用 update 时,物理表必须已存在,否则报 "表[xxx]无主键!"。 + + **推荐做法**:使用动态建表模式 (build_create_payload(dynamic_table=True)) + 直接 Create → Release,无需中间 Update 步骤。 + Release 时后端会从 formData 的 tableName 字段自动创建物理表。 + + 仅在物理表已存在时(如从其他系统迁移、手动建表)才使用本函数。 + + Args: + config: build_full_config 返回的配置字典 + form_id: 已创建功能的 ID + + Returns: + 可直接传入 VisualDevAPI.update() 的 data 字典 + """ + return { + "id": form_id, + "fullName": config["full_name"], + "enCode": config["en_code"], + "type": 1, + "description": config["description"], + "webType": config["web_type"], + "state": 0, + "sortCode": config["sort_code"], + "category": config["category"], + "dbLinkId": config.get("db_link_id", "0"), + "tables": config["tables"], + "formData": config["formData"], + "columnData": config["columnData"], + "appColumnData": config.get("appColumnData", config["columnData"]), # APP端列表配置 + } diff --git a/builders/mobile_field_model.py b/builders/mobile_field_model.py new file mode 100644 index 0000000..0565b07 --- /dev/null +++ b/builders/mobile_field_model.py @@ -0,0 +1,201 @@ +"""移动端字段模型构建器 + +将 PC 端 jnpfKey 转换为移动端 f_app_column_data 的 columnData 配置。 +参考: aibridge/docs/control/13-mobile-controls.md + +PC jnpfKey → 移动端 component 的映射规则。 +移动端组件通过 props 对象传递配置,与 PC 端的 __config__ 机制不同。 +""" + +from typing import Any, Dict, List, Optional + +# PC jnpfKey → 移动端 component 映射 +_JNPF_KEY_TO_MOBILE_COMPONENT = { + "input": "Input", + "textarea": "Textarea", + "inputNumber": "InputNumber", + "numInput": "InputNumber", + "select": "Select", + "radio": "Radio", + "checkbox": "Checkbox", + "datePicker": "DatePicker", + "timePicker": "TimePicker", + "switch": "Switch", + "uploadImg": "UploadImg", + "uploadFile": "UploadFile", + "treeSelect": "TreeSelect", + "cascader": "Cascader", + "organizeSelect": "OrganizeSelect", + "userSelect": "UserSelect", + "rate": "Rate", + "colorPicker": "ColorPicker", + "sign": "Sign", +} + +# 移动端组件默认 props 模板 +_DEFAULT_PROPS_TEMPLATE = { + "Input": {"placeholder": "请输入{label}"}, + "Textarea": {"placeholder": "请输入{label}", "rows": 3}, + "InputNumber": {"placeholder": "请输入{label}", "step": 1}, + "Select": {"placeholder": "请选择{label}", "options": []}, + "Radio": {"options": []}, + "Checkbox": {"options": []}, + "DatePicker": {"format": "YYYY-MM-DD"}, + "TimePicker": {"format": "HH:mm:ss"}, + "Switch": {"checkedValue": 1, "unCheckedValue": 0}, + "UploadImg": {}, + "UploadFile": {}, + "TreeSelect": {"options": []}, + "Cascader": {"options": []}, + "OrganizeSelect": {"placeholder": "请选择组织"}, + "UserSelect": {"placeholder": "请选择用户"}, + "Rate": {"max": 5}, + "ColorPicker": {}, + "Sign": {}, +} + + +def build_mobile_field( + field_name: str, + field_vmodel: str, + jnpf_key: str = "input", + required: bool = False, + options: Optional[List[Dict[str, Any]]] = None, + placeholder: Optional[str] = None, + extra_props: Optional[Dict[str, Any]] = None, +) -> Dict[str, Any]: + """构建移动端单个字段的 columnData 配置 + + Args: + field_name: 字段中文名,如 "客户名称" + field_vmodel: 数据库字段名,如 "f_customer_name" + jnpf_key: PC 端控件类型,对应移动端 component + required: 是否必填(移动端通过 rules.required 校验) + options: 下拉选项列表,格式为 [{label: "显示文本", value: "值"}] + 注意:移动端使用 label/value 格式,与 PC 端 fullName/id 不同 + placeholder: 自定义 placeholder,默认从模板生成 + extra_props: 额外 props,会合并到默认 props 中 + + Returns: + 移动端 columnData 中的单个字段配置字典 + + Example: + >>> build_mobile_field("状态", "F_Status", "select", options=[{"label": "启用", "value": "1"}]) + { + "column": "F_Status", + "component": "Select", + "props": { + "placeholder": "请选择状态", + "options": [{"label": "启用", "value": "1"}] + }, + "rules": [{"required": True, "message": "请选择状态"}] + } + """ + component = _JNPF_KEY_TO_MOBILE_COMPONENT.get(jnpf_key, "Input") + + # 获取默认 props 模板 + props_template = _DEFAULT_PROPS_TEMPLATE.get(component, {}).copy() + + # 处理 placeholder + if placeholder: + props_template["placeholder"] = placeholder + elif "placeholder" in props_template: + props_template["placeholder"] = props_template["placeholder"].format(label=field_name) + + # 处理 options(PC 端 fullName/id → 移动端 label/value) + if options and component in ("Select", "Radio", "Checkbox", "TreeSelect", "Cascader"): + if component in ("Select", "Radio", "Checkbox"): + # 移动端使用 label/value 格式 + props_template["options"] = [ + {"label": opt.get("fullName", opt.get("label", "")), "value": opt.get("id", opt.get("value", ""))} + for opt in options + ] + elif component in ("TreeSelect", "Cascader"): + # 树形/级联组件保留完整结构,仅转换顶层字段名 + props_template["options"] = _convert_tree_options(options) + + # 合并额外 props + if extra_props: + props_template.update(extra_props) + + # 构建字段配置 + field_config: Dict[str, Any] = { + "column": field_vmodel, + "component": component, + "props": props_template, + } + + # 添加必填校验规则 + if required: + field_config["rules"] = [{"required": True, "message": f"请输入{field_name}"}] + + # 根据组件类型调整 rules.message + if required: + if component in ("Select", "Radio", "Checkbox", "TreeSelect", "Cascader", "OrganizeSelect", "UserSelect"): + field_config["rules"] = [{"required": True, "message": f"请选择{field_name}"}] + elif component in ("DatePicker", "TimePicker"): + field_config["rules"] = [{"required": True, "message": f"请选择{field_name}"}] + + return field_config + + +def _convert_tree_options(options: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """转换树形选项结构(PC fullName/id → 移动端 label/value,保留 children) + + Args: + options: PC 端格式的选项列表 [{fullName, id, children: [...]}] + + Returns: + 移动端格式的选项列表 [{label, value, children: [...]}] + """ + result = [] + for opt in options: + item = { + "label": opt.get("fullName", opt.get("label", "")), + "value": opt.get("id", opt.get("value", "")), + } + if "children" in opt and opt["children"]: + item["children"] = _convert_tree_options(opt["children"]) + if "disabled" in opt: + item["disabled"] = opt["disabled"] + result.append(item) + return result + + +def build_mobile_column_data( + fields: List[Dict[str, Any]], +) -> List[Dict[str, Any]]: + """批量构建移动端 columnData 配置 + + Args: + fields: 字段定义列表,每个元素参考以下格式: + { + "fieldName": "客户名称", # 字段中文名 + "field": "f_customer_name", # 数据库字段名 + "jnpfKey": "input", # PC 端控件类型 + "required": False, # 是否必填 + "options": [...], # 选项列表(可选) + } + + Returns: + 移动端 columnData 配置列表(JSON 字符串格式) + + Example: + >>> fields = [ + ... {"fieldName": "客户名称", "field": "f_customer_name", "jnpfKey": "input"}, + ... {"fieldName": "状态", "field": "f_status", "jnpfKey": "select", + ... "options": [{"fullName": "启用", "id": "1"}]}, + ... ] + >>> column_data = build_mobile_column_data(fields) + >>> print(column_data) # 可以直接赋值给 f_app_column_data + """ + return [ + build_mobile_field( + field_name=f.get("fieldName", ""), + field_vmodel=f.get("field", ""), + jnpf_key=f.get("jnpfKey", "input"), + required=f.get("required", False), + options=f.get("options"), + ) + for f in fields + ] diff --git a/builders/table_config.py b/builders/table_config.py new file mode 100644 index 0000000..6bef7b7 --- /dev/null +++ b/builders/table_config.py @@ -0,0 +1,200 @@ +"""表结构构建器 + +参考后端源码 TableFeildsEnum.java / TableFieldsNameConst.java。 +生成包含系统字段和用户字段的完整表结构 JSON。 +支持主表 + 子表(table 控件)结构。 +""" + +from typing import Any, Dict, List, Optional + +# 主表系统字段 - FlowFormDataUtil.generalInsert 会自动写入 +_MAIN_SYSTEM_FIELDS = [ + {"field": "F_Id", "fieldName": "主键", "dataType": "varchar", "dataLength": "50", + "primaryKey": 1, "allowNull": 0, "identity": 0}, + {"field": "f_flow_task_id", "fieldName": "流程任务id", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "f_flow_id", "fieldName": "流程id", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "f_flow_state", "fieldName": "流程任务状态", "dataType": "int", "dataLength": "9", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "f_tenant_id", "fieldName": "租户id", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 0, "identity": 0}, + {"field": "F_Sort_Code", "fieldName": "排序码", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "F_Create_User", "fieldName": "创建者", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "F_Create_Time", "fieldName": "创建时间", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "F_Modify_User", "fieldName": "修改者", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, + {"field": "F_Modify_Time", "fieldName": "修改时间", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 1, "identity": 0}, +] + +# 子表系统字段 +_CHILD_SYSTEM_FIELDS = [ + {"field": "F_Id", "fieldName": "主键", "dataType": "varchar", "dataLength": "50", + "primaryKey": 1, "allowNull": 0, "identity": 0}, + {"field": "f_tenant_id", "fieldName": "租户id", "dataType": "varchar", "dataLength": "50", + "primaryKey": 0, "allowNull": 0, "identity": 0}, +] + + +def _build_user_fields(fields: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """从字段定义列表构建表字段列表 + + 兼容两种字段名格式: + - field_model 返回格式:__vModel__ 存储字段名 + - 直接传入格式:field 存储字段名 + """ + user_fields = [] + for f in fields: + # 优先使用 field,否则使用 __vModel__(兼容 field_model 构建器) + field_name = f.get("field") or f.get("__vModel__") or f.get("id", "") + field_def = { + "field": field_name, + "fieldName": f.get("fieldName") or f.get("fullName") or f.get("__config__", {}).get("label", field_name), + "dataType": f.get("dataType", "varchar"), + "primaryKey": 0, + "allowNull": 0 if f.get("required", False) else 1, + "autoIncrement": 0, + "identity": 0, + "columnName": None, + } + data_length = f.get("dataLength", "200") + if data_length: # 跳过空值(datetime 等类型不需要长度) + field_def["dataLength"] = data_length + user_fields.append(field_def) + return user_fields + + +def build_tables( + table_name: str, + table_label: str, + fields: List[Dict[str, Any]], + relation_table: str = "", +) -> List[Dict[str, Any]]: + """构建表结构 JSON(仅主表,向后兼容) + + Args: + table_name: 数据库表名,如 "base_sales_vendor" + table_label: 表中文名,如 "文具销售商表" + fields: 用户自定义字段列表,每个元素含 field/fieldName/dataType/dataLength/required + relation_table: 关联表名(默认无关联) + + Returns: + tables 列表(需 JSON 序列化后传入 API) + """ + return [build_main_table_entry(table_name, table_label, fields, relation_table)] + + +def build_main_table_entry( + table_name: str, + table_label: str, + fields: List[Dict[str, Any]], + relation_table: str = "", +) -> Dict[str, Any]: + """构建主表表结构条目 + + Args: + table_name: 数据库表名 + table_label: 表中文名 + fields: 用户自定义字段列表 + relation_table: 关联表名 + + Returns: + 主表结构字典 + """ + return { + "table": table_name, + "tableName": table_label, + "relationTable": relation_table, + "tableField": "", + "fields": _MAIN_SYSTEM_FIELDS + _build_user_fields(fields), + "relationField": "", + "typeId": "1", + } + + +def build_child_table_entry( + child_table_name: str, + child_table_label: str, + main_table_name: str, + child_fields: List[Dict[str, Any]], + relation_field: str = "F_Id", + foreign_key_field: str = "F_ParentId", +) -> Dict[str, Any]: + """构建子表表结构条目 + + 子表通过外键关联主表:child_table.foreign_key_field → main_table.relation_field + + Args: + child_table_name: 子表数据库表名,如 "base_order_item" + child_table_label: 子表中文名,如 "订单明细表" + main_table_name: 主表数据库表名,如 "base_order" + child_fields: 子表用户字段列表(不含外键,外键自动添加) + relation_field: 主表关联字段(默认 F_Id,即主表主键) + foreign_key_field: 子表外键字段名(默认 F_ParentId) + + Returns: + 子表结构字典 + """ + # 外键字段定义 + fk_field = { + "field": foreign_key_field, + "fieldName": "主表主键", + "dataType": "varchar", + "dataLength": "50", + "primaryKey": 0, + "allowNull": 1, + "autoIncrement": 0, + "identity": 0, + "columnName": None, + } + + return { + "table": child_table_name, + "tableName": child_table_label, + "relationTable": main_table_name, + "tableField": foreign_key_field, + "typeId": "0", + "fields": _CHILD_SYSTEM_FIELDS + [fk_field] + _build_user_fields(child_fields), + "relationField": relation_field, + } + + +def build_tables_with_child( + table_name: str, + table_label: str, + fields: List[Dict[str, Any]], + child_tables: List[Dict[str, Any]], +) -> List[Dict[str, Any]]: + """构建包含子表的完整 tables 结构 + + Args: + table_name: 主表数据库表名 + table_label: 主表中文名 + fields: 主表用户字段列表 + child_tables: 子表定义列表,每个子表包含: + - table_name: 子表名 + - table_label: 子表中文名 + - fields: 子表字段列表 + - foreign_key_field: 外键字段名(默认 "F_ParentId") + - relation_field: 主表关联字段(默认 "F_Id") + + Returns: + tables 列表:[主表, 子表1, 子表2, ...] + """ + tables = [build_main_table_entry(table_name, table_label, fields)] + + for ct in child_tables: + tables.append(build_child_table_entry( + child_table_name=ct["table_name"], + child_table_label=ct["table_label"], + main_table_name=table_name, + child_fields=ct["fields"], + relation_field=ct.get("relation_field", "F_Id"), + foreign_key_field=ct.get("foreign_key_field", "F_ParentId"), + )) + + return tables diff --git a/client.py b/client.py new file mode 100644 index 0000000..804ecce --- /dev/null +++ b/client.py @@ -0,0 +1,408 @@ +"""AIBridge 核心客户端 + +JNPFClient 基于 requests.Session 实现,自动管理认证头和双 HTTP 客户端。 + +请求头约定(与前端 request.ts 对齐): + Authorization: {token} # token 已含 "bearer " 前缀(小写) + App-Code: {app_code} # 多应用系统识别码 + Jnpf-Origin: pc # 来源标识 + Vue-Version: 3 # Vue 版本标识 + Content-Type: application/json # 默认 +""" + +import hashlib +import json +import logging +import subprocess +from typing import Any, Dict, Optional, Union +from urllib.parse import urljoin + +import requests + +from aibridge.config import JNPFConfig +from aibridge.exceptions import APIError, AuthError, JNPFError +from aibridge.models import APIResponse + +logger = logging.getLogger("aibridge") + + +def encrypt_password_aes(password: str, cipher_key: str = "EY8WePvjM5GGwQzn") -> str: + """加密密码(与前端登录加密逻辑一致) + + 流程: MD5(明文密码) → AES-128-ECB 加密 → hex + 等同于前端: encryptByMd5(password) → aesEncryption.encryptByAES() + + Args: + password: 明文密码 + cipher_key: AES密钥(默认前端 VITE_CIPHER_KEY) + + Returns: + AES加密后的hex字符串(96字符) + + 注意: 如果加密结果与前端不兼容,请从浏览器开发者工具复制登录请求的 password 值。 + """ + # MD5(明文密码) + md5_pwd = hashlib.md5(password.encode('utf-8')).hexdigest() + + # AES-128-ECB 加密(通过 Node.js 实现,Python 缺少 pycryptodome) + key = hashlib.md5(cipher_key.encode('utf-8')).hexdigest() + node_script = f""" +const crypto = require('crypto'); +const key = Buffer.from('{key}', 'hex'); +const cipher = crypto.createCipheriv('aes-128-ecb', key, null); +cipher.setAutoPadding(true); +let encrypted = cipher.update('{md5_pwd}', 'utf8', 'hex'); +encrypted += cipher.final('hex'); +console.log(encrypted); +""" + result = subprocess.run(['node', '-e', node_script], capture_output=True, text=True) + return result.stdout.strip() + + +def generate_encrypted_password(password: str, cipher_key: str = "EY8WePvjM5GGwQzn") -> str: + """生成可用于 config.py 的加密密码 + + 注意: 如果生成的密码无法登录,说明前端使用的 CIPHER_KEY 与默认值不同。 + 请从浏览器开发者工具复制登录请求中的 password 值。 + + 获取正确密码的方法: + 1. 打开浏览器开发者工具 (F12),切换到 Network 标签 + 2. 登录页面输入账号密码,点击登录 + 3. 找到 /api/oauth/Login 请求 + 4. 复制 Form Data 中的 password 值(96字符的hex字符串) + + Args: + password: 明文密码 + cipher_key: 前端 VITE_CIPHER_KEY(默认 EY8WePvjM5GGwQzn) + + 用法: + from aibridge.client import generate_encrypted_password + encrypted = generate_encrypted_password("your_password") + print(f"加密后的密码: {encrypted}") + """ + return encrypt_password_aes(password, cipher_key) + + +# 默认 AES 密钥(与前端 VITE_CIPHER_KEY 一致) +DEFAULT_CIPHER_KEY = "EY8WePvjM5GGwQzn" + + +class JNPFClient: + """JNPF 低代码平台客户端 + + 用法:: + + # 推荐方式:使用默认配置(当前系统,如 myapp) + from aibridge import JNPFClient, JNPFConfig + CONFIG = JNPFConfig() + client = JNPFClient.from_config(CONFIG) + client.login() # 自动使用 CONFIG 中的账号密码 + + # 或直接构造(需手动传入账号密码) + client = JNPFClient(base_url="http://localhost:30000", app_code="{YOUR_APP_CODE}") + client.login(account="admin", password="xxx") + resp = client.request("GET", "/api/system/Menu/ModuleBySystem") + """ + + def __init__( + self, + base_url: str = "http://localhost:30000", + app_code: str = "", + report_base_url: str = "", + timeout: int = 30, + verify_ssl: bool = False, + ): + self.base_url = base_url.rstrip("/") + self.report_base_url = (report_base_url or base_url).rstrip("/") + self.app_code = app_code + self.timeout = timeout + self.verify_ssl = verify_ssl + + if not app_code: + import warnings + warnings.warn( + "[AIBridge] JNPFClient() 创建时 app_code 为空!\n" + " 这会导致所有 API 请求使用平台系统身份(systemId=309228585019769285),\n" + " 创建的菜单和功能不会出现在你的业务系统中。\n" + " 请使用 JNPFClient.from_config(config) 或传入 app_code 参数。\n" + " 示例: client = JNPFClient(app_code='ais')", + UserWarning, + stacklevel=2 + ) + + self.token: str = "" + self.user_info: Dict[str, Any] = {} + + # 主 HTTP 客户端 + self._session = self._create_session(self.base_url) + # 报表独立客户端 + self._report_session = self._create_session(self.report_base_url) + + # 挂载 API 模块 + from aibridge.modules import ( + AuthAPI, MenuAPI, UserAPI, OrganizeAPI, RoleAPI, PositionAPI, + DictionaryAPI, VisualDevAPI, OnlineDevAPI, WorkflowAPI, + DataInterfaceAPI, InterfaceOauthAPI, PortalAPI, MessageAPI, DataSourceAPI, + DataModelAPI, + PrintDevAPI, ReportAPI, SysConfigAPI, FileAPI, + ) + self.auth = AuthAPI(self) + self.menu = MenuAPI(self) + self.user = UserAPI(self) + self.organize = OrganizeAPI(self) + self.role = RoleAPI(self) + self.position = PositionAPI(self) + self.dictionary = DictionaryAPI(self) + self.visual_dev = VisualDevAPI(self) + self.online_dev = OnlineDevAPI(self) + self.workflow = WorkflowAPI(self) + self.data_interface = DataInterfaceAPI(self) + self.interface_oauth = InterfaceOauthAPI(self) + self.portal = PortalAPI(self) + self.message = MessageAPI(self) + self.data_source = DataSourceAPI(self) + self.data_model = DataModelAPI(self) + self.print_dev = PrintDevAPI(self) + self.report = ReportAPI(self) + self.sys_config = SysConfigAPI(self) + self.file = FileAPI(self) + + @classmethod + def from_config(cls, config: JNPFConfig) -> "JNPFClient": + """从 JNPFConfig 创建客户端,自动保存账号密码供 login() 无参数调用""" + client = cls( + base_url=config.api_base, + app_code=config.app_code, + report_base_url=config.report_api_base, + timeout=config.timeout, + verify_ssl=config.verify_ssl, + ) + client._account = config.account + client._password = config.backend_aes96_password + return client + + def _create_session(self, base_url: str) -> requests.Session: + session = requests.Session() + session.headers.update({ + "Jnpf-Origin": "pc", + "Vue-Version": "3", + "Accept": "application/json, text/plain, */*", + }) + session.verify = self.verify_ssl + return session + + def _update_auth_headers(self): + """更新认证相关请求头""" + headers = {} + if self.token: + auth = self.token if self.token.startswith("bearer ") else f"bearer {self.token}" + headers["Authorization"] = auth + if self.app_code: + headers["App-Code"] = self.app_code + self._session.headers.update(headers) + self._report_session.headers.update(headers) + + # ==================== 认证方法 ==================== + + def login(self, account: str = None, password: str = None) -> APIResponse: + """登录获取 Token + + Args: + account: 账号(默认使用 from_config 保存的值) + password: 密码(默认使用 from_config 保存的值) + - 96字符: 视为已加密的AES密文,直接使用 + - 其他长度: 明文密码(不推荐,Python无法生成正确的AES密文) + ★ 推荐:使用 .claude/scripts/extract_encrypted_password.js 从浏览器提取96字符AES密文 + """ + # 默认使用 from_config 保存的账号密码 + if account is None: + account = getattr(self, '_account', '') + if password is None: + password = getattr(self, '_password', '') + + url = f"{self.base_url}/api/oauth/Login" + + # 96字符视为已加密的AES密文 + if len(password) == 96: + encrypted_pwd = password + origin = "hash" + else: + encrypted_pwd = password + origin = "password" + + data = { + "account": account, + "password": encrypted_pwd, + "origin": origin, + "timestamp": 0, + "grant_type": "password", + } + resp = requests.post( + url, + data=data, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + timeout=self.timeout, + verify=self.verify_ssl, + ) + result = resp.json() + + if result.get("code") != 200: + raise AuthError( + msg=result.get("msg", "登录失败"), + code=result.get("code", 0), + raw=result, + ) + + self.token = result["data"]["token"] + self._update_auth_headers() + logger.info("登录成功: %s", account) + return APIResponse( + code=result["code"], + data=result["data"], + msg=result.get("msg", ""), + raw=result, + ) + + def login_by_token(self, token: str): + """直接设置已有 Token(跳过登录)""" + self.token = token + self._update_auth_headers() + logger.info("Token 已设置") + + def logout(self) -> APIResponse: + """退出登录""" + resp = self._request("POST", "/api/oauth/Logout", with_credentials=True) + self.token = "" + self.user_info = {} + self._update_auth_headers() + logger.info("已退出登录") + return resp + + def get_user_info(self, system_code: str = "", is_backend: int = 0) -> APIResponse: + """获取当前用户信息 + + Args: + system_code: 系统编码,默认使用 app_code + is_backend: 是否后台 0=否 1=是 + """ + params = { + "systemCode": system_code or self.app_code, + "isBackend": is_backend, + } + resp = self._request("GET", "/api/oauth/CurrentUser", params=params) + if resp.success and isinstance(resp.data, dict): + self.user_info = resp.data + return resp + + def get_login_config(self) -> APIResponse: + """获取登录配置""" + return self._request("GET", "/api/oauth/getLoginConfig") + + # ==================== 核心请求方法 ==================== + + def request( + self, + method: str, + path: str, + *, + params: dict = None, + data: dict = None, + json_data: dict = None, + use_report_client: bool = False, + **kwargs, + ) -> APIResponse: + """发送 API 请求 + + Args: + method: HTTP 方法 (GET/POST/PUT/DELETE) + path: API 路径,如 "/api/system/Menu" + params: URL 查询参数 + data: 请求体数据(自动 JSON 序列化) + json_data: 请求体 JSON 数据(优先于 data) + use_report_client: 是否使用报表客户端 + **kwargs: 传递给 requests 的额外参数 + """ + return self._request( + method, path, + params=params, + data=data, + json_data=json_data, + use_report_client=use_report_client, + **kwargs, + ) + + def _request( + self, + method: str, + path: str, + *, + params: dict = None, + data: dict = None, + json_data: dict = None, + use_report_client: bool = False, + with_credentials: bool = False, + **kwargs, + ) -> APIResponse: + """内部请求方法""" + session = self._report_session if use_report_client else self._session + + url = f"{self.base_url}{path}" if not use_report_client else f"{self.report_base_url}{path}" + + req_kwargs = { + "method": method.upper(), + "url": url, + "params": params, + "timeout": kwargs.pop("timeout", self.timeout), + } + + if json_data is not None: + req_kwargs["json"] = json_data + elif data is not None: + req_kwargs["json"] = data + + if with_credentials: + session = requests.Session() + session.headers.update(self._session.headers) + session.verify = self.verify_ssl + req_kwargs["cookies"] = {"Cookie": ""} + + try: + response = session.request(**req_kwargs) + result = response.json() + except requests.exceptions.Timeout: + raise JNPFError(msg=f"请求超时: {path}") + except requests.exceptions.ConnectionError: + raise JNPFError(msg=f"连接失败: {self.base_url}") + except json.JSONDecodeError: + raise JNPFError(msg=f"响应非 JSON: {path} status={response.status_code}") + + code = result.get("code", 0) + msg = result.get("msg", "") + resp_data = result.get("data") + + api_resp = APIResponse( + code=code, + data=resp_data, + msg=msg, + raw=result, + ) + + if code != 200: + logger.warning("API 错误 [%s] %s: %s", code, path, msg) + + return api_resp + + def require_success(self, resp: APIResponse) -> APIResponse: + """要求响应成功,否则抛出异常""" + if not resp.success: + raise APIError( + msg=resp.msg or "操作失败", + code=resp.code, + raw=resp.raw, + ) + return resp + + def check_login(self): + """检查是否已登录,未登录则抛出异常""" + if not self.token: + raise AuthError(msg="未登录,请先调用 login() 或 login_by_token()") diff --git a/config.py b/config.py new file mode 100644 index 0000000..e3b6ed3 --- /dev/null +++ b/config.py @@ -0,0 +1,152 @@ +"""AIBridge 配置管理 + +配置结构: +- config.py: 基础配置(API地址、账号、路径等) +- appconfig/config_*.py: 各 app_code 的业务配置 + +使用方式: + from aibridge import JNPFClient, JNPFConfig + config = JNPFConfig() # 使用默认 app_code="dr" + config = JNPFConfig(app_code="jxcj") # 指定 app_code +""" + +import os +import importlib +from dataclasses import dataclass, field + + +@dataclass +class JNPFConfig: + """JNPF 平台连接配置 + + Attributes: + app_code: 业务系统 App-Code,如 "dr"。为空时不传 App-Code 头。 + base_url: 后端 API 地址,如 "http://localhost:30000" + account: 后端 API 登录账号 + backend_aes96_password: 后端 API 登录密码(96字符AES密文) + frontend_url: 前端页面地址 + frontend_account: 前端登录账号(真实密码) + frontend_password: 前端登录密码(真实密码) + timeout: 请求超时秒数 + verify_ssl: 是否验证 SSL 证书 + company_code: 企业代码,用于代码生成的包名和目录 + project_path: 项目路径 + """ + # 基础配置 + app_code: str = "dd" + base_url: str = "http://localhost:30000" + account: str = "admin" + backend_aes96_password: str = "d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b" + apr_doc_url: str = "" + + # 前端登录配置(真实密码,用于 Playwright 浏览器测试) + frontend_url: str = "" + frontend_account: str = "admin" + frontend_password: str = "123456" + + # 其他配置 + report_base_url: str = "" + timeout: int = 30 + verify_ssl: bool = False + + # 代码开发配置 + company_code: str = "ssw" + project_path: str = "" # 运行时从环境变量 ccWorkDir 读取 + frontend_views_path: str = "" + backend_code_path: str = "" + backend_package_base: str = "com.jnpf" + boot_parent: str = "ssw-boot" + + # 以下为业务配置,自动从 appconfig/config_{app_code}.py 加载 + system_title: str = "" + system_id: str = "" + db_link_name: str = "" + db_link_id: str = "" + interface_category_id: str = "" + business_category_id: str = "" + + def __post_init__(self): + if not self.project_path: + self.project_path = os.environ.get('ccWorkDir', '') + self._load_app_config() + + def _load_app_config(self): + """从 appconfig/config_{app_code}.py 加载业务配置""" + if not self.app_code: + return + + # 设置前端URL + if not self.frontend_url: + self.frontend_url = f"http://127.0.0.1:3000/jnpf_app_{self.app_code}" + + # 设置路径 + if not self.frontend_views_path: + self.frontend_views_path = f"{self.project_path}/web/apps/jnpf-web-apps-main/src/views/" + if not self.backend_code_path: + self.backend_code_path = f"{self.project_path}/boot" + if not self.apr_doc_url: + self.apr_doc_url = f"{self.base_url}/doc.html" + + # 加载 app 配置 + try: + app_config = importlib.import_module(f"aibridge.appconfig.config_{self.app_code}") + for key in ["system_title", "system_id", "db_link_name", "db_link_id", + "interface_category_id", "business_category_id"]: + if hasattr(app_config, key): + value = getattr(app_config, key) + if key == "db_link_name": + self.db_link_name = value + elif key == "db_link_id": + self.db_link_id = value + elif key == "system_title": + self.system_title = value + elif key == "system_id": + self.system_id = value + elif key == "interface_category_id": + self.interface_category_id = value + elif key == "business_category_id": + self.business_category_id = value + except ImportError: + pass + + @property + def api_base(self) -> str: + return self.base_url.rstrip("/") + + @property + def report_api_base(self) -> str: + return (self.report_base_url or self.base_url).rstrip("/") + + @property + def module_package_name(self) -> str: + """代码生成的 modulePackageName,格式: {company_code}.{app_code}""" + return f"{self.company_code}.{self.app_code}" + + @property + def frontend_module_path(self) -> str: + """前端模块路径,格式: {company_code}/{app_code}/{module_name}""" + return f"{self.company_code}/{self.app_code}" + + @property + def backend_module_name(self) -> str: + """后端模块名称,格式: {company_code}-{app_code}""" + return f"{self.company_code}-{self.app_code}" + + def get_frontend_view_path(self, module_name: str) -> str: + """获取前端视图目录完整路径""" + return os.path.join(self.frontend_views_path, self.company_code, self.app_code, module_name) + + def get_backend_module_path(self) -> str: + """获取后端模块目录完整路径""" + return os.path.join(self.backend_code_path, self.backend_module_name) + + def verify_paths(self) -> dict: + """验证关键路径是否存在""" + results = {} + paths = [ + ("frontend_views_path", self.frontend_views_path), + ("backend_code_path", self.backend_code_path) + ] + for name, path in paths: + results[name] = os.path.exists(path) + return results diff --git a/config.py.bak b/config.py.bak new file mode 100644 index 0000000..955a47a --- /dev/null +++ b/config.py.bak @@ -0,0 +1,152 @@ +"""AIBridge 配置管理 + +配置结构: +- config.py: 基础配置(API地址、账号、路径等) +- appconfig/config_*.py: 各 app_code 的业务配置 + +使用方式: + from aibridge import JNPFClient, JNPFConfig + config = JNPFConfig() # 使用默认 app_code="dr" + config = JNPFConfig(app_code="jxcj") # 指定 app_code +""" + +import os +import importlib +from dataclasses import dataclass, field + + +@dataclass +class JNPFConfig: + """JNPF 平台连接配置 + + Attributes: + app_code: 业务系统 App-Code,如 "dr"。为空时不传 App-Code 头。 + base_url: 后端 API 地址,如 "http://localhost:30000" + account: 后端 API 登录账号 + backend_aes96_password: 后端 API 登录密码(96字符AES密文) + frontend_url: 前端页面地址 + frontend_account: 前端登录账号(真实密码) + frontend_password: 前端登录密码(真实密码) + timeout: 请求超时秒数 + verify_ssl: 是否验证 SSL 证书 + company_code: 企业代码,用于代码生成的包名和目录 + project_path: 项目路径 + """ + # 基础配置 + app_code: str = "newapp" + base_url: str = "http://localhost:30000" + account: str = "admin" + backend_aes96_password: str = "d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b" + apr_doc_url: str = "" + + # 前端登录配置(真实密码,用于 Playwright 浏览器测试) + frontend_url: str = "" + frontend_account: str = "admin" + frontend_password: str = "123456" + + # 其他配置 + report_base_url: str = "" + timeout: int = 30 + verify_ssl: bool = False + + # 代码开发配置 + company_code: str = "ssw" + project_path: str = "" # 运行时从环境变量 ccWorkDir 读取 + frontend_views_path: str = "" + backend_code_path: str = "" + backend_package_base: str = "com.jnpf" + boot_parent: str = "ssw-boot" + + # 以下为业务配置,自动从 appconfig/config_{app_code}.py 加载 + system_title: str = "" + system_id: str = "" + db_link_name: str = "" + db_link_id: str = "" + interface_category_id: str = "" + business_category_id: str = "" + + def __post_init__(self): + if not self.project_path: + self.project_path = os.environ.get('ccWorkDir', '') + self._load_app_config() + + def _load_app_config(self): + """从 appconfig/config_{app_code}.py 加载业务配置""" + if not self.app_code: + return + + # 设置前端URL + if not self.frontend_url: + self.frontend_url = f"http://127.0.0.1:3000/jnpf_app_{self.app_code}" + + # 设置路径 + if not self.frontend_views_path: + self.frontend_views_path = f"{self.project_path}/web/apps/jnpf-web-apps-main/src/views/" + if not self.backend_code_path: + self.backend_code_path = f"{self.project_path}/boot" + if not self.apr_doc_url: + self.apr_doc_url = f"{self.base_url}/doc.html" + + # 加载 app 配置 + try: + app_config = importlib.import_module(f"aibridge.appconfig.config_{self.app_code}") + for key in ["system_title", "system_id", "db_link_name", "db_link_id", + "interface_category_id", "business_category_id"]: + if hasattr(app_config, key): + value = getattr(app_config, key) + if key == "db_link_name": + self.db_link_name = value + elif key == "db_link_id": + self.db_link_id = value + elif key == "system_title": + self.system_title = value + elif key == "system_id": + self.system_id = value + elif key == "interface_category_id": + self.interface_category_id = value + elif key == "business_category_id": + self.business_category_id = value + except ImportError: + pass + + @property + def api_base(self) -> str: + return self.base_url.rstrip("/") + + @property + def report_api_base(self) -> str: + return (self.report_base_url or self.base_url).rstrip("/") + + @property + def module_package_name(self) -> str: + """代码生成的 modulePackageName,格式: {company_code}.{app_code}""" + return f"{self.company_code}.{self.app_code}" + + @property + def frontend_module_path(self) -> str: + """前端模块路径,格式: {company_code}/{app_code}/{module_name}""" + return f"{self.company_code}/{self.app_code}" + + @property + def backend_module_name(self) -> str: + """后端模块名称,格式: {company_code}-{app_code}""" + return f"{self.company_code}-{self.app_code}" + + def get_frontend_view_path(self, module_name: str) -> str: + """获取前端视图目录完整路径""" + return os.path.join(self.frontend_views_path, self.company_code, self.app_code, module_name) + + def get_backend_module_path(self) -> str: + """获取后端模块目录完整路径""" + return os.path.join(self.backend_code_path, self.backend_module_name) + + def verify_paths(self) -> dict: + """验证关键路径是否存在""" + results = {} + paths = [ + ("frontend_views_path", self.frontend_views_path), + ("backend_code_path", self.backend_code_path) + ] + for name, path in paths: + results[name] = os.path.exists(path) + return results diff --git a/config.py.bak2 b/config.py.bak2 new file mode 100644 index 0000000..a9bc37a --- /dev/null +++ b/config.py.bak2 @@ -0,0 +1,152 @@ +"""AIBridge 配置管理 + +配置结构: +- config.py: 基础配置(API地址、账号、路径等) +- appconfig/config_*.py: 各 app_code 的业务配置 + +使用方式: + from aibridge import JNPFClient, JNPFConfig + config = JNPFConfig() # 使用默认 app_code="dr" + config = JNPFConfig(app_code="jxcj") # 指定 app_code +""" + +import os +import importlib +from dataclasses import dataclass, field + + +@dataclass +class JNPFConfig: + """JNPF 平台连接配置 + + Attributes: + app_code: 业务系统 App-Code,如 "dr"。为空时不传 App-Code 头。 + base_url: 后端 API 地址,如 "http://localhost:30000" + account: 后端 API 登录账号 + backend_aes96_password: 后端 API 登录密码(96字符AES密文) + frontend_url: 前端页面地址 + frontend_account: 前端登录账号(真实密码) + frontend_password: 前端登录密码(真实密码) + timeout: 请求超时秒数 + verify_ssl: 是否验证 SSL 证书 + company_code: 企业代码,用于代码生成的包名和目录 + project_path: 项目路径 + """ + # 基础配置 + app_code: str = "dr" + base_url: str = "http://localhost:30000" + account: str = "admin" + backend_aes96_password: str = "d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b" + apr_doc_url: str = "" + + # 前端登录配置(真实密码,用于 Playwright 浏览器测试) + frontend_url: str = "" + frontend_account: str = "admin" + frontend_password: str = "123456" + + # 其他配置 + report_base_url: str = "" + timeout: int = 30 + verify_ssl: bool = False + + # 代码开发配置 + company_code: str = "ssw" + project_path: str = "" # 运行时从环境变量 ccWorkDir 读取 + frontend_views_path: str = "" + backend_code_path: str = "" + backend_package_base: str = "com.jnpf" + boot_parent: str = "ssw-boot" + + # 以下为业务配置,自动从 appconfig/config_{app_code}.py 加载 + system_title: str = "" + system_id: str = "" + db_link_name: str = "" + db_link_id: str = "" + interface_category_id: str = "" + business_category_id: str = "" + + def __post_init__(self): + if not self.project_path: + self.project_path = os.environ.get('ccWorkDir', '') + self._load_app_config() + + def _load_app_config(self): + """从 appconfig/config_{app_code}.py 加载业务配置""" + if not self.app_code: + return + + # 设置前端URL + if not self.frontend_url: + self.frontend_url = f"http://127.0.0.1:3000/jnpf_app_{self.app_code}" + + # 设置路径 + if not self.frontend_views_path: + self.frontend_views_path = f"{self.project_path}/web/apps/jnpf-web-apps-main/src/views/" + if not self.backend_code_path: + self.backend_code_path = f"{self.project_path}/boot" + if not self.apr_doc_url: + self.apr_doc_url = f"{self.base_url}/doc.html" + + # 加载 app 配置 + try: + app_config = importlib.import_module(f"aibridge.appconfig.config_{self.app_code}") + for key in ["system_title", "system_id", "db_link_name", "db_link_id", + "interface_category_id", "business_category_id"]: + if hasattr(app_config, key): + value = getattr(app_config, key) + if key == "db_link_name": + self.db_link_name = value + elif key == "db_link_id": + self.db_link_id = value + elif key == "system_title": + self.system_title = value + elif key == "system_id": + self.system_id = value + elif key == "interface_category_id": + self.interface_category_id = value + elif key == "business_category_id": + self.business_category_id = value + except ImportError: + pass + + @property + def api_base(self) -> str: + return self.base_url.rstrip("/") + + @property + def report_api_base(self) -> str: + return (self.report_base_url or self.base_url).rstrip("/") + + @property + def module_package_name(self) -> str: + """代码生成的 modulePackageName,格式: {company_code}.{app_code}""" + return f"{self.company_code}.{self.app_code}" + + @property + def frontend_module_path(self) -> str: + """前端模块路径,格式: {company_code}/{app_code}/{module_name}""" + return f"{self.company_code}/{self.app_code}" + + @property + def backend_module_name(self) -> str: + """后端模块名称,格式: {company_code}-{app_code}""" + return f"{self.company_code}-{self.app_code}" + + def get_frontend_view_path(self, module_name: str) -> str: + """获取前端视图目录完整路径""" + return os.path.join(self.frontend_views_path, self.company_code, self.app_code, module_name) + + def get_backend_module_path(self) -> str: + """获取后端模块目录完整路径""" + return os.path.join(self.backend_code_path, self.backend_module_name) + + def verify_paths(self) -> dict: + """验证关键路径是否存在""" + results = {} + paths = [ + ("frontend_views_path", self.frontend_views_path), + ("backend_code_path", self.backend_code_path) + ] + for name, path in paths: + results[name] = os.path.exists(path) + return results diff --git a/connectors/__init__.py b/connectors/__init__.py new file mode 100644 index 0000000..26c5613 --- /dev/null +++ b/connectors/__init__.py @@ -0,0 +1,402 @@ +""" +ABU 要素管理 - JNPF 后端连接器 +通过 AIBridge 与 JNPF 平台交互,实现要素的创建、验证、执行 +""" + +import json +import sqlite3 +from datetime import datetime +from pathlib import Path +from typing import Any, Optional + +# 导入 aibridge 客户端 +import sys +sys.path.insert(0, str(Path(__file__).parent.parent)) +from aibridge import JNPFClient, JNPFConfig + + +class ABUConnector: + """ABU Connector - JNPF 平台操作执行器""" + + def __init__(self, data_dir: str = ".od/projects"): + self.data_dir = Path(data_dir) + self._clients = {} # 缓存各 app_code 的客户端 + + def get_client(self, app_code: str) -> JNPFClient: + """获取 JNPF 客户端(带缓存)""" + if app_code not in self._clients: + config = JNPFConfig(app_code=app_code) + client = JNPFClient.from_config(config) + # 预登录 + password = config.backend_aes96_password + client.auth.login(config.login_account, password) + self._clients[app_code] = client + return self._clients[app_code] + + def get_db_path(self, app_code: str) -> Path: + """获取项目的 SQLite 数据库路径""" + db_dir = self.data_dir / app_code / "db" + db_dir.mkdir(parents=True, exist_ok=True) + return db_dir / "abu.sqlite" + + def init_db(self, app_code: str) -> None: + """初始化数据库表""" + db_path = self.get_db_path(app_code) + conn = sqlite3.connect(str(db_path)) + cursor = conn.cursor() + + # 要素主表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS ab_element ( + f_id TEXT PRIMARY KEY, + f_type TEXT NOT NULL CHECK (f_type IN ('form', 'workflow', 'table', 'api', 'service', 'testcase', 'doc', 'issue')), + f_app_code TEXT NOT NULL, + f_name TEXT NOT NULL, + f_en_code TEXT, + f_func_id TEXT, + f_status TEXT DEFAULT 'pending' CHECK (f_status IN ('pending', 'active', 'verified', 'blocked')), + f_executor TEXT DEFAULT 'ai' CHECK (f_executor IN ('human', 'ai', 'hybrid')), + f_meta TEXT, + f_created_at TEXT DEFAULT (datetime('now')), + f_updated_at TEXT + ) + """) + + # 关联表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS ab_relation ( + f_id TEXT PRIMARY KEY, + f_from_id TEXT NOT NULL, + f_to_id TEXT NOT NULL, + f_rel_type TEXT NOT NULL CHECK (f_rel_type IN ('depends_on', 'links_to', 'blocks', 'verifies')), + f_created_at TEXT DEFAULT (datetime('now')) + ) + """) + + # 历史表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS ab_history ( + f_id TEXT PRIMARY KEY, + f_element_id TEXT NOT NULL, + f_action TEXT NOT NULL, + f_actor TEXT NOT NULL CHECK (f_actor IN ('human', 'ai')), + f_detail TEXT, + f_created_at TEXT DEFAULT (datetime('now')) + ) + """) + + # 验证表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS ab_verification ( + f_id TEXT PRIMARY KEY, + f_element_id TEXT NOT NULL, + f_verify_type TEXT NOT NULL CHECK (f_verify_type IN ('e2e', 'api', 'log', 'db')), + f_result TEXT NOT NULL CHECK (f_result IN ('pass', 'fail', 'pending')), + f_output TEXT, + f_verifier TEXT NOT NULL, + f_created_at TEXT DEFAULT (datetime('now')) + ) + """) + + conn.commit() + conn.close() + + def generate_id(self) -> str: + """生成雪花ID""" + import time + import random + timestamp = int(time.time() * 1000) + random_part = random.randint(0, 1024) + return f"{timestamp}-{1}-{random_part}" + + # ============================================================ + # 要素操作 + # ============================================================ + + def create_element( + self, + app_code: str, + element_type: str, + name: str, + en_code: Optional[str] = None, + func_id: Optional[str] = None, + meta: Optional[dict] = None, + executor: str = "ai" + ) -> dict: + """创建要素""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + conn = sqlite3.connect(str(db_path)) + cursor = conn.cursor() + + element_id = self.generate_id() + now = datetime.now().isoformat() + + cursor.execute(""" + INSERT INTO ab_element (f_id, f_type, f_app_code, f_name, f_en_code, f_func_id, f_status, f_executor, f_meta, f_created_at, f_updated_at) + VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?) + """, (element_id, element_type, app_code, name, en_code, func_id, executor, json.dumps(meta or {}), now, now)) + + # 记录历史 + history_id = self.generate_id() + cursor.execute(""" + INSERT INTO ab_history (f_id, f_element_id, f_action, f_actor, f_detail, f_created_at) + VALUES (?, ?, 'created', ?, ?, ?) + """, (history_id, element_id, executor, json.dumps({"element_type": element_type, "name": name}), now)) + + conn.commit() + conn.close() + + return {"element_id": element_id, "f_id": element_id} + + def query_elements( + self, + app_code: str, + element_type: Optional[str] = None, + status: Optional[str] = None + ) -> list: + """查询要素列表""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + + if not db_path.exists(): + return [] + + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + query = "SELECT * FROM ab_element WHERE f_app_code = ?" + params = [app_code] + + if element_type: + query += " AND f_type = ?" + params.append(element_type) + if status: + query += " AND f_status = ?" + params.append(status) + + cursor.execute(query, params) + rows = cursor.fetchall() + conn.close() + + return [dict(row) for row in rows] + + def get_element(self, app_code: str, element_id: str) -> Optional[dict]: + """获取单个要素""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + + if not db_path.exists(): + return None + + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + cursor.execute("SELECT * FROM ab_element WHERE f_id = ?", (element_id,)) + row = cursor.fetchone() + conn.close() + + return dict(row) if row else None + + def update_element_status(self, app_code: str, element_id: str, status: str, actor: str = "ai") -> bool: + """更新要素状态""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + conn = sqlite3.connect(str(db_path)) + cursor = conn.cursor() + + now = datetime.now().isoformat() + cursor.execute("UPDATE ab_element SET f_status = ?, f_updated_at = ? WHERE f_id = ?", (status, now, element_id)) + + # 记录历史 + history_id = self.generate_id() + cursor.execute(""" + INSERT INTO ab_history (f_id, f_element_id, f_action, f_actor, f_detail, f_created_at) + VALUES (?, ?, ?, ?, ?, ?) + """, (history_id, element_id, f"status_change:{status}", actor, json.dumps({"new_status": status}), now)) + + conn.commit() + conn.close() + return True + + # ============================================================ + # 关联操作 + # ============================================================ + + def link_elements(self, app_code: str, from_id: str, to_id: str, rel_type: str) -> dict: + """关联两要素""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + conn = sqlite3.connect(str(db_path)) + cursor = conn.cursor() + + relation_id = self.generate_id() + now = datetime.now().isoformat() + + cursor.execute(""" + INSERT INTO ab_relation (f_id, f_from_id, f_to_id, f_rel_type, f_created_at) + VALUES (?, ?, ?, ?, ?) + """, (relation_id, from_id, to_id, rel_type, now)) + + conn.commit() + conn.close() + + return {"relation_id": relation_id} + + def get_relations(self, app_code: str, element_id: str, direction: str = "both") -> dict: + """获取要素关联""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + + if not db_path.exists(): + return {"upstream": [], "downstream": []} + + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + upstream = [] + downstream = [] + + if direction in ("upstream", "both"): + cursor.execute("SELECT * FROM ab_relation WHERE f_to_id = ?", (element_id,)) + upstream = [dict(row) for row in cursor.fetchall()] + + if direction in ("downstream", "both"): + cursor.execute("SELECT * FROM ab_relation WHERE f_from_id = ?", (element_id,)) + downstream = [dict(row) for row in cursor.fetchall()] + + conn.close() + return {"upstream": upstream, "downstream": downstream} + + # ============================================================ + # 历史操作 + # ============================================================ + + def get_history(self, app_code: str, element_id: str) -> list: + """获取要素变更历史""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + + if not db_path.exists(): + return [] + + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + cursor.execute("SELECT * FROM ab_history WHERE f_element_id = ? ORDER BY f_created_at DESC", (element_id,)) + rows = cursor.fetchall() + conn.close() + + return [dict(row) for row in rows] + + # ============================================================ + # 验证操作 + # ============================================================ + + def verify_element( + self, + app_code: str, + element_id: str, + verify_type: str = "api", + result: str = "pass", + output: Optional[dict] = None, + verifier: str = "ai" + ) -> dict: + """验证要素""" + self.init_db(app_code) + db_path = self.get_db_path(app_code) + conn = sqlite3.connect(str(db_path)) + cursor = conn.cursor() + + verification_id = self.generate_id() + now = datetime.now().isoformat() + + cursor.execute(""" + INSERT INTO ab_verification (f_id, f_element_id, f_verify_type, f_result, f_output, f_verifier, f_created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, (verification_id, element_id, verify_type, result, json.dumps(output or {}), verifier, now)) + + conn.commit() + conn.close() + + # 如果验证通过,更新要素状态为 verified + if result == "pass": + self.update_element_status(app_code, element_id, "verified", verifier) + + return {"verification_id": verification_id} + + # ============================================================ + # JNPF 集成操作 + # ============================================================ + + def jnpf_create_form(self, app_code: str, form_data: dict) -> dict: + """通过 JNPF API 创建表单""" + client = self.get_client(app_code) + + # 调用 VisualDev API 创建表单 + result = client.visual_dev.create(form_data) + + # 在 ABU 中记录要素 + element = self.create_element( + app_code=app_code, + element_type="form", + name=form_data.get("fullName", "未命名表单"), + en_code=form_data.get("enCode"), + func_id=result.get("func_id"), + meta={"jnpf_response": result}, + executor="ai" + ) + + return element + + def jnpf_query_forms(self, app_code: str) -> list: + """查询 JNPF 表单列表""" + client = self.get_client(app_code) + forms = client.visual_dev.list() + return forms + + def jnpf_execute_workflow(self, app_code: str, workflow_id: str, data: dict) -> dict: + """触发 JNPF 工作流""" + client = self.get_client(app_code) + result = client.workflow.execute(workflow_id, data) + return result + + +# 单例模式 +_abu_connector: Optional[ABUConnector] = None + + +def get_abu_connector(data_dir: str = ".od/projects") -> ABUConnector: + """获取 ABU Connector 单例""" + global _abu_connector + if _abu_connector is None: + _abu_connector = ABUConnector(data_dir) + return _abu_connector + + +if __name__ == "__main__": + # 测试代码 + import sys + if len(sys.argv) > 1: + app_code = sys.argv[1] + connector = get_abu_connector() + + # 测试初始化 + connector.init_db(app_code) + print(f"数据库初始化完成: {app_code}") + + # 测试创建要素 + element = connector.create_element( + app_code=app_code, + element_type="form", + name="测试表单", + en_code="test_form", + meta={"test": True} + ) + print(f"创建要素: {element}") + else: + print("用法: python -m aibridge.connectors.abu ") \ No newline at end of file diff --git a/connectors/__pycache__/__init__.cpython-312.pyc b/connectors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..b6b8b32 Binary files /dev/null and b/connectors/__pycache__/__init__.cpython-312.pyc differ diff --git a/docs/.DS_Store b/docs/.DS_Store new file mode 100644 index 0000000..49b5d7c Binary files /dev/null and b/docs/.DS_Store differ diff --git a/docs/JNPF-AIBridge培训文档.md b/docs/JNPF-AIBridge培训文档.md new file mode 100644 index 0000000..da24692 --- /dev/null +++ b/docs/JNPF-AIBridge培训文档.md @@ -0,0 +1,866 @@ +# JNPF 低代码平台 + AIBridge 框架培训文档 + +> 本文档系统介绍 JNPF 低代码平台的核心机制、AIBridge 框架的支撑架构,以及基于 Claude Code 的开发流程。 + +--- + +## 目录 + +1. [整体架构概述](#1-整体架构概述) +2. [JNPF 平台核心机制](#2-jnpf-平台核心机制) +3. [AIBridge 框架详解](#3-aibridge-框架详解) +4. [Claude Code 支撑机制](#4-claude-code-支撑机制) +5. [/ssw-dev-flow 7阶段开发流程](#5-ssw-dev-flow-7阶段开发流程) +6. [注意事项与常见问题](#6-注意事项与常见问题) +7. [参考文档索引](#7-参考文档索引) + +--- + +## 1. 整体架构概述 + +### 1.0 平台全景架构图 + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 开发人员 (Human) │ +│ 通过 Claude Code 对话式开发 │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ 自然语言指令 + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ Claude Code (AI Agent Runtime) │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │ Hooks │ │ Skills │ │ Commands │ │ Settings.json │ │ +│ │pre-tool-use │ │ platform- │ │ /ssw-dev-flow│ │ • 权限控制 │ │ +│ │skill-match │ │ mechanism │ │ /ssw-start │ │ • allow/deny 路径 │ │ +│ │ stop.js │ │ form-dev │ │ /ssw-check │ │ • softLinks │ │ +│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ Python SDK 调用 + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ AIBridge (Python SDK) │ +│ │ +│ ┌─────────────────────────────────────────────────────────────────────────┐ │ +│ │ JNPFClient │ │ +│ │ • 自动管理 Token (bearer eyJ...) │ │ +│ │ • 自动携带 App-Code 请求头 │ │ +│ │ • 双 Session (主接口 + 报表) │ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ ┌────────────────────┐ ┌────────────────────┐ ┌──────────────────────┐ │ +│ │ Modules │ │ Builders │ │ Utils │ │ +│ │ ┌──────────────┐ │ │ build_full_config │ │ JNPFConfig │ │ +│ │ │ AuthAPI │ │ │ build_field_model │ │ FieldDef │ │ +│ │ │ MenuAPI │ │ │ build_table_field │ │ APIResponse │ │ +│ │ │ VisualDevAPI │ │ └────────────────────┘ └──────────────────────┘ │ +│ │ │ DataModelAPI │ │ │ +│ │ │ WorkflowAPI │ │ ★ 一行代码生成完整配置 │ +│ │ │ DataInterf.. │ │ config = build_full_config(...) │ +│ │ └──────────────┘ │ payload = build_create_payload(config) │ +│ └────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + │ HTTP REST API + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ JNPF 低代码平台 (Java 后端) │ +│ │ +│ ┌──────────────────────────────────────────────────────────────────────┐ │ +│ │ Controller Layer │ │ +│ │ VisualdevController MenuController WorkflowController DataInter.. │ │ +│ └──────────────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌──────────────────────────────────────────────────────────────────────┐ │ +│ │ Service Layer │ │ +│ │ VisualDevService MenuService WorkflowService DataInterfaceService │ │ +│ │ ────────────────────────────────────────────────────────────────── │ │ +│ │ ★ App-Code 自动解析 → systemId 自动写入 (无需手动指定) │ │ +│ └──────────────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌──────────────────────────────────────────────────────────────────────┐ │ +│ │ Database (MySQL) │ │ +│ │ │ │ +│ │ 主库 (db_link_id="0") │ 业务库 (db_link_id="xxx") │ │ +│ │ ───────────────────── │ ────────────────────── │ │ +│ │ base_system │ 租户业务表 │ │ +│ │ base_user │ • 客户表 customer │ │ +│ │ base_module (菜单) │ • 订单表 orders │ │ +│ │ base_visual_dev (表单配置) │ • 产品表 product │ │ +│ │ base_visual_release (已发布) │ ... │ │ +│ │ base_data_interface │ │ │ +│ └───────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + ▲ + │ App-Code 隔离 +┌─────────────────────────────────────────────────────────────────────────────┐ +│ 多业务系统 (Multi-Tenant) │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ App-Code: │ │ App-Code: │ │ App-Code: │ │ +│ │ "wj" │ │ "aistudio" │ │ "erp" │ │ +│ │ ─────────── │ │ ─────────── │ │ ─────────── │ │ +│ │ 自己的菜单 │ │ 自己的菜单 │ │ 自己的菜单 │ │ +│ │ 自己的表单 │ │ 自己的表单 │ │ 自己的表单 │ │ +│ │ 自己的流程 │ │ 自己的流程 │ │ 自己的流程 │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ +│ ════════════════════════════════════════════════════════════════════════ │ +│ ★ 每个业务系统通过 App-Code 隔离数据,systemId 自动关联 │ +│ ════════════════════════════════════════════════════════════════════════ │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +### 1.1 各层职责说明 + +| 层级 | 组件 | 职责 | 操作对象 | +|------|------|------|----------| +| **人员层** | 开发人员 | 通过自然语言描述需求 | Claude Code | +| **Agent层** | Claude Code | 解析指令、执行任务、安全管控 | Hooks/Skills/Commands | +| **SDK层** | AIBridge | 封装API、提供构建器、简化调用 | JNPFClient/Builders | +| **平台层** | JNPF Java | 业务逻辑、数据处理、权限管理 | Controller/Service | +| **数据层** | MySQL | 数据持久化 | 主库+业务库 | + +### 1.2 数据流向 + +``` +开发人员说"创建一个客户管理表单" + │ + ▼ +┌─────────────────────────────────┐ +│ Claude Code │ +│ 1. skill-matcher 检测到表单开发 │ +│ 2. 调用 AIBridge Python SDK │ +│ 3. Hooks 验证操作安全 │ +└─────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────┐ +│ AIBridge │ +│ build_full_config() │ +│ client.visual_dev.create() │ +│ client.visual_dev.release() │ +│ client.menu.create_*_menu() │ +└─────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────┐ +│ JNPF 平台 │ +│ • App-Code → systemId │ +│ • 表单配置写入 base_visual_dev │ +│ • 发布到 base_visual_release │ +│ • 菜单写入 base_module │ +└─────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────┐ +│ 数据库 │ +│ • 主库:系统表、菜单、表单配置 │ +│ • 业务库:业务数据(客户表) │ +└─────────────────────────────────┘ +``` + +### 1.3 技术栈 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Claude Code (AI 对话层) │ +│ hooks / skills / commands / agents │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ AIBridge (Python SDK) │ +│ JNPFClient + 18个API模块 + 6个配置构建器 │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ JNPF 低代码平台 (后端 Java) │ +│ VisualDev / Menu / Workflow / DataInterface │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ MySQL 数据库 │ +│ 主库(系统表) + 业务库(租户表) │ +└─────────────────────────────────────────────────────────────┘ +``` + +### 1.4 项目结构 + +``` +6.2/ +├── aibridge/ # ★ Python API 包(可修改) +│ ├── modules/ # 18 个 API 模块 +│ ├── builders/ # 6 个配置构建器 +│ ├── docs/ # 完整文档(40+ 篇) +│ ├── examples/ # 标准示例代码 +│ └── config.py # ★ 统一配置文件 +│ +├── boot/ # ★ 后端代码(可修改) +│ ├── jnpf-admin/ # 主模块 +│ ├── ssw-common/ # ssw 公共模块 +│ └── ssw-{app_code}/ # 业务模块(如 ssw-ais) +│ ├── ssw-{app_code}-entity/ +│ ├── ssw-{app_code}-biz/ +│ └── ssw-{app_code}-controller/ +│ +├── web/ # ★ PC 前端(基于 jnpf/前端/ 复制) +│ └── apps/jnpf-web-apps-main/src/views/ssw/ +│ +├── uniapp/ # ★ 移动端前端(基于 jnpf/移动端/ 复制) +│ +├── jnpf/ # JNPF 平台源码(不可修改) +│ ├── 前端/ # Vue 3 前端 +│ ├── 后端/ # Java 后端 +│ ├── 移动端/ # 移动端 +│ └── 数据库/ # 数据库脚本 +│ +├── .claude/ # ★ Claude Code 配置(可修改) +│ ├── settings.json # 权限、hooks、MCP 配置 +│ ├── hooks/ # 钩子脚本 +│ ├── skills/ # 11 个技能定义 +│ ├── commands/ # SSW 命令指南 +│ └── templates/ # 文档模板 +│ +├── docs/ # 项目文档目录(按 app_code 组织) +│ └── {app_code}/ # 特定应用的文档 +│ ├── plan.md # 开发计划 +│ ├── 详细设计方案.md +│ ├── 测试用例.md +│ ├── debug.md # 调试记录 +│ └── scripts/ # 临时脚本 +│ +├── test/ # 测试环境目录 +└── log/ # 后端日志 +``` + +### 1.5 核心设计原则 + +> **简单需求用表单+流程实现,复杂逻辑通过后端开发技能实现(导出模型代码 + 业务系统 Helper),DI 仅作为临时查询手段。** + +### 1.6 五条铁律(开发人员必须遵守) + +> **务必遵守,违反将导致项目配置错乱、代码质量下降** + +| # | 铁律 | 触发场景 | 后果 | +|---|------|---------|------| +| 1 | **DI 限制多 → 立即触发 `backend-dev` 技能** | 提到 DI/SQL/数据接口 | 用临时方案而非后端永久方案 | +| 2 | **登录分清前端(真密码)与后端(hash)** | 提到登录/密码/token | API 认证失败或混用配置 | +| 3 | **数据库操作必须通过 AIBridge API** | 提到数据库查询/SQL/表结构 | 绕过平台隔离,破坏多租户安全 | +| 4 | **业务库建表:表名 snake_case 无前缀,字段名 f_ 前缀 + snake_case** | 提到建表/字段命名/表名 | 平台规范混乱,代码生成失败 | +| 5 | **配置统一从 `config.py` 读取** | 任何硬编码 app_code/system_id | 多系统配置错乱,难以切换 | + +#### 铁律 1:后端开发原则 + +DI SQL 有较多限制(占位符格式、`{}` 字面量陷阱、dbLinkId 隔离问题)。**当需要扩展功能时,立即触发 `backend-dev` 技能**,在 `ssw-{app_code}` 业务模块中创建后端代码。 + +**后端开发原则**:优先导出模型代码 → 基于模型代码组合 → 业务逻辑写在业务系统 Helper(Util/Service)中,**不直接在导出模型相关代码上写业务**。 + +``` +业务系统 Helper 示例: +ssw.ais.util.AisDataUtil # 数据处理工具类 +ssw.ais.service.AisBizService # 业务服务类 +``` + +#### 铁律 2:前端/后端登录配置 + +| 环境 | 地址 | 密码格式 | 说明 | +|------|------|---------|------| +| **前端页面** | http://127.0.0.1:3000/jnpf_app_{app_code} | 真实密码(如 `admin/123456`) | 浏览器登录 | +| **后端 API** | http://127.0.0.1:30000 | 96字符AES密文 | Python AIBridge 调用 | + +AIBridge 使用 `JNPFClient.from_config(config)` 自动处理,**不要混用**。 + +#### 铁律 3:数据库操作必须通过 AIBridge API + +严禁直接执行 SQL。数据库相关操作全部通过 `aibridge` API: +- 查询表结构:`data_model.get_table_info(link_id, table_name)` +- 查询数据:`data_model.get_table_list(link_id, data)` 或 `data_interface.execute(di_id, params)` +- link_id `"0"` = 主库,非 `"0"` = 业务库(当前系统 `db_link_id` 在 `config.py` 中) + +#### 铁律 4:建表命名规范(业务数据库) + +**表名 snake_case 无前缀,字段名 f_ 前缀 + snake_case**: + +``` +表名:metadata_source(snake_case,无前缀) +字段:f_image_name(f_ 前缀 + snake_case) +``` + +- ❌ `t_metadata_source` / `img_metadata_source` / `base_metadata_source`(带前缀) +- ❌ `F_ImageName`(大写F + PascalCase) +- ❌ `F_Image_Name`(大写F + 带下划线) +- ✅ `metadata_source` 表名 / `f_image_name` 字段 + +#### 铁律 5:配置统一从 config.py 读取 + +所有项目参数(app_code / system_id / db_link_id / category_id)**必须从 `aibridge/config.py` 获取**,禁止在代码中硬编码项目参数。 + +```python +# ✅ 正确 +from aibridge import JNPFClient, JNPFConfig +client = JNPFClient.from_config(JNPFConfig()) + +# ❌ 错误:硬编码参数 +client = JNPFClient(base_url="http://127.0.0.1:30000", app_code="ais", ...) +``` + +--- + +## 2. JNPF 平台核心机制 + +### 2.1 App-Code 多应用机制 + +JNPF 支持在同一平台实例中运行多个业务系统,通过 **App-Code** 进行识别和隔离。 + +#### 请求链路 + +``` +用户访问 /wj/ 前缀 + ↓ +前端 request.ts 设置请求头 App-Code: "wj" + ↓ +后端 RequestContext.getAppCode() = "wj" + ↓ +systemService.getInfoByEnCode("wj") + ↓ +SELECT * FROM base_system WHERE F_EN_CODE = 'wj' → systemId + ↓ +按 systemId 过滤菜单、表单、流程等数据 +``` + +#### AIBridge 使用方式 + +```python +from aibridge import JNPFClient, JNPFConfig + +# 推荐方式:从 config.py 加载配置 +client = JNPFClient.from_config(JNPFConfig()) +client.login() + +# 登录后所有请求自动携带 App-Code 请求头 +# 创建的菜单/功能自动归属到对应业务系统 +``` + +#### 不设置 App-Code 的后果 + +| 问题 | 影响 | +|------|------| +| 功能/菜单归属 | 归属到系统平台(systemId=309228585019769285) | +| 业务系统可见性 | 业务系统中看不到 | +| 获取菜单 | 返回系统平台菜单,不是业务系统菜单 | + +### 2.2 systemId 自动设置 + +JNPF 后端在以下 API 中**自动通过 App-Code 解析并写入 systemId**,无需手动指定: + +| API | 后端行为 | +|-----|----------| +| `POST /api/visualdev/Base`(创建表单) | `entity.setSystemId(getInfoByEnCode(getAppCode()).getId())` | +| `POST /api/visualdev/Base/{id}/Release`(发布) | 继承原 systemId | +| `POST /api/system/Menu`(创建菜单) | `moduleCrForm.setSystemId(info.getId())` | + +**验证方法**: + +```python +func_info = client.visual_dev.get_info(func_id) +print(f"systemId: {func_info.data.get('systemId')}") +``` + +### 2.3 VisualDev 发布流程 + +``` +┌──────────────────────────────────────────────────────────────┐ +│ VisualDev 生命周期 │ +├──────────────────────────────────────────────────────────────┤ +│ │ +│ 创建 (state=0,设计态) │ +│ ↓ │ +│ 发布 (state=0 → 1,复制到 base_visual_release) │ +│ ↓ │ +│ 运行 (state=1,前端可用) │ +│ ↓ │ +│ 修改 (state=1 → 0,重新进入设计态) │ +│ ↓ │ +│ 再次发布 │ +│ │ +└──────────────────────────────────────────────────────────────┘ +``` + +**关键点**: +- 未发布(state=0)的表单前端**不可用** +- 发布操作是**全量覆盖**,不是增量 +- 修改已发布表单后需要**重新发布** + +### 2.4 数据库连接(db_link_id) + +| db_link_id | 说明 | 用途 | +|------------|------|------| +| `"0"` | 主数据库 | 系统平台级表(用户、角色、菜单等) | +| 业务库ID | 业务数据库 | 业务表(客户、订单等) | + +### 2.5 菜单类型 + +| type | 说明 | URL 地址 | 典型用途 | +|------|------|----------|----------| +| 1 | 目录菜单 | 空 | 分组导航 | +| 2 | 页面菜单 | 外部URL | 链接外部系统 | +| 3 | 功能表单菜单 | `model/{enCode}` | 绑定 VisualDev 功能 | + +**parentId 规则**: +- `"-1"` 表示顶级菜单 +- 或已存在的目录菜单(type=1)的 ID +- **禁止使用 systemId**! + +--- + +## 3. AIBridge 框架详解 + +### 3.1 核心模块架构 + +``` +JNPFClient (认证/HTTP/会话管理) +├── AuthAPI 认证(登录/登出/用户信息) +├── MenuAPI 菜单管理(CRUD/目录/表单菜单) +├── VisualDevAPI ★可视化开发核心(功能/发布/代码生成) +├── OnlineDevAPI OnlineDev 数据操作便捷接口 +├── DataModelAPI ★数据模型 CRUD(推荐使用) +├── WorkflowAPI 工作流(任务/审批/模板/委托) +├── DataInterfaceAPI 数据接口(SQL 执行/预览) +└── ... 其他 10+ 模块 +``` + +### 3.2 配置构建器(build_full_config) + +**推荐使用**,一站式生成完整配置: + +```python +from aibridge.builders import build_full_config, build_create_payload + +config = build_full_config( + full_name="产品管理", + en_code="productManage", + table_name="product", + table_label="产品表", + description="产品信息管理", + category=CONFIG.business_category_id, + fields=[f.to_dict() for f in fields], + web_type=2, +) + +payload = build_create_payload(config, dynamic_table=True) +resp = client.visual_dev.create(payload) +func_id = resp.id +client.visual_dev.release(func_id) # 必须发布! +``` + +### 3.3 AIBridge 模块速查 + +| 模块 | 文件 | 核心功能 | +|------|------|----------| +| AuthAPI | auth.py | 登录/登出/用户信息 | +| MenuAPI | menu.py | 菜单 CRUD、soft_delete | +| VisualDevAPI | visual_dev.py | 表单创建/发布/代码生成/soft_delete | +| OnlineDevAPI | online_dev.py | 数据 CRUD 便捷封装 | +| DataModelAPI | data_model.py | ★ 数据模型 CRUD(推荐) | +| WorkflowAPI | workflow.py | 工作流任务/审批/模板 | +| DataInterfaceAPI | data_interface.py | DI 创建/执行/预览 | +| DictionaryAPI | dictionary.py | 数据字典 | +| UserAPI | user.py | 用户管理 | +| OrganizeAPI | organize.py | 组织架构 | +| PortalAPI | portal.py | 门户管理 | +| **CodeGenerator** | **visual_code.py** | **★ 代码生成与类名修复** | + +--- + +## 4. Claude Code 支撑机制 + +### 4.1 目录结构 + +``` +.claude/ +├── settings.json # 主配置(权限、hooks、MCP) +├── hooks/ # 钩子脚本 +│ ├── pre-tool-use.js # 工具使用前触发(安全检查) +│ ├── skill-matcher.js # SSW 命令匹配 +│ └── stop.js # 会话停止时清理 +├── skills/ # 11 个技能定义 +│ ├── platform-mechanism/ # App-Code、systemId、发布流程 +│ ├── form-development/ # 可视化表单开发 +│ ├── workflow-development/ # Flowable 工作流 +│ ├── backend-dev/ # 后端业务开发 +│ └── ... # 其他技能 +├── commands/ # SSW 命令 +│ ├── ssw-dev-flow.md # ★ 7阶段开发流程 +│ ├── ssw-start.md # 开始新功能开发 +│ ├── ssw-check.md # 检查当前状态 +│ ├── ssw-next.md # 下一步建议 +│ ├── ssw-debug.md # 调试问题 +│ ├── ssw-flow.md # 构建工作流 +│ ├── ssw-code-gen.md # 代码生成 +│ ├── ssw-onlinedev.md # 在线功能表单 +│ ├── ssw-test.md # E2E 测试 +│ ├── ssw-init-app.md # 初始化应用 +│ ├── ssw-init-workdir.md # 初始化工作目录 +│ └── ssw-pack-init.md # 业务包创建 +└── templates/ # 文档模板 +``` + +### 4.2 Hooks 机制 + +#### PreToolUse Hook(pre-tool-use.js) +- **触发时机**:工具使用前 +- **功能**:阻止危险命令、禁止写入限制目录、警告敏感操作 + +#### Skill Matcher Hook(skill-matcher.js) +- **触发时机**:用户提交 Prompt 时 +- **功能**:检测 SSW 命令并路由到对应技能文件 + +### 4.3 Skills 技能系统 + +| 技能 | 触发词 | 用途 | +|------|--------|------| +| platform-mechanism | App-Code、systemId、发布、release | 平台核心机制 | +| form-development | 表单、可视化、build_full_config | 表单开发 | +| workflow-development | 工作流、workflow、审批 | 工作流开发 | +| data-interface | 数据接口、sql、DataInterface | 数据接口 | +| data-management | 数据、CRUD、create_model | 数据管理 | +| backend-dev | 后端、业务类、controller、service | 后端业务开发 | +| code-generator | codegen、生成代码、导出代码 | 代码生成 | +| menu-configuration | 菜单配置、挂载 | 菜单管理 | +| troubleshooting | 排查问题、报错解决 | 故障排查 | +| basic-standards | 编码规范、命名 | 开发规范 | + +### 4.4 AI 辅助开发命令 + +| 命令 | 说明 | +|------|------| +| `/ssw-dev-flow` | ★ 7阶段通用软件开发流 | +| `/ssw-start` | 开始新功能开发 | +| `/ssw-check` | 检查当前状态 | +| `/ssw-next` | 下一步建议 | +| `/ssw-debug` | 调试问题 | +| `/ssw-flow` | 构建工作流 | +| `/ssw-code-gen` | 代码生成 | +| `/ssw-onlinedev` | 创建在线功能表单 | +| `/ssw-test` | E2E 测试 | +| `/ssw-init-app` | 初始化应用环境 | +| `/ssw-init-workdir` | 初始化工作目录 | +| `/ssw-pack-init` | 业务包创建 | + +--- + +## 5. /ssw-dev-flow 7阶段开发流程 + +### 5.1 概览 + +`/ssw-dev-flow` 是基于 JNPF + AIBridge 的通用软件开发流程,覆盖从需求到迭代的完整生命周期。 + +**输入参数**: + +| 参数 | 说明 | 必填 | +|------|------|------| +| `app_code` | 应用编码(英文唯一标识) | 是 | +| `app_name` | 应用名称 | 是 | +| `system_title` | 系统中文名 | 是 | +| `source_path` | 源码/文档路径(可空) | 否 | +| `db_name` | 数据库名(默认同 app_code) | 否 | + +### 5.2 阶段详解 + +``` +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段1:初始化环境 (Init) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 调用 /ssw-init-app 初始化应用: │ +│ • 创建数据库连接 │ +│ • 创建系统 │ +│ • 创建数据源 │ +│ • 创建字典分类 │ +│ │ +│ 参数: │ +│ - app_code: 应用编码 │ +│ - app_name: 应用名称 │ +│ - system_title: 系统中文名 │ +│ - db_name: 数据库名(默认同 app_code) │ +│ - frontend_password: 前端密码(默认 123456) │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段2:设计 (Design) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 输入:源码/文档/数据库(如有) │ +│ │ +│ 输出文档到 docs/{app_code}/: │ +│ • 详细设计方案.md │ +│ • 测试用例.md │ +│ │ +│ 设计内容: │ +│ • 基本框架:JNPF 用户、权限、菜单、角色 │ +│ • 模型设计:表单控件、关联字段(优先关联表单控件) │ +│ • 流程设计:使用 Flowable 工作流 │ +│ • 功能表单:优先用表单实现,复杂逻辑用扩展代码 │ +│ • UI 设计:基于 JNPF 组件 │ +│ │ +│ 关键约束: │ +│ • 功能表单无法实现的业务,尽量不用 DI,优先用代码生成器 │ +│ • 代码生成后扩展,放在 ssw-{app_code} 业务包下 │ +│ • 配置统一从 aibridge/config.py 读取 │ +│ │ +│ 命名规范: │ +│ • 包名: ssw.{app_code}.*(不是 com.ssw.{app_code}.*) │ +│ • 类名/属性名: PascalCase(例:ProductEntity) │ +│ • 字段名: f_snake_case(例:f_product_name) │ +│ │ +│ PC端路由: ssw/{app_code}/** → views/ssw/{app_code}/** │ +│ 移动端路由: ssw/{app_code}/** → pages/ssw/{app_code}/** │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段3:评审 (Review) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 多角色虚拟评审: │ +│ • 系统架构 │ +│ • 项目管理 │ +│ • UI │ +│ • 程序设计 │ +│ • 质量 │ +│ • 测试 │ +│ │ +│ 评审内容: │ +│ • 源码、文档、数据库 │ +│ • JNPF 开发模式适配性 │ +│ • 功能覆盖完整性 │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段4:执行 (Execute) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 4.1 创建功能表单 │ +│ 使用 /ssw-onlinedev 创建功能表单 │ +│ │ +│ 4.2 扩展开发(功能表单无法满足时) │ +│ • 优先使用 JNPF 代码生成器 /ssw-code-gen │ +│ • 导出后端代码后扩展,放在 boot/ssw-{app_code}/ │ +│ • 业务包不存在时用 /ssw-pack-init 创建 │ +│ │ +│ 4.3 统一配置 │ +│ • 配置统一从 aibridge/config.py 读取 │ +│ • 调用 AIBridge API 迁移数据 │ +│ │ +│ 4.4 调试记录 │ +│ • 遇到错误写入 docs/{app_code}/debug.md │ +│ • 包括:问题、处理措施、建议、提示词优化 │ +│ │ +│ 4.5 菜单配置 │ +│ 使用 menu-configuration 技能 │ +│ │ +│ 4.6 临时脚本 │ +│ 放在 docs/{app_code}/scripts │ +│ │ +│ 4.7 Maven 编译 │ +│ • mvn 找不到时尝试 ~/maven/bin │ +│ • 编译:mvn clean compile -DskipTests │ +│ • 打包:mvn clean package -DskipTests │ +│ │ +│ 注意:功能表单id、菜单id以数据库实际为准 │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段5:测试 (Test) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 5.1 调用 /ssw-test 进行 E2E 测试 │ +│ │ +│ 5.2 根据测试用例逐项验证 │ +│ │ +│ 5.3 测试框架: │ +│ • API 集成测试:python3 aibridge/utils/api_test.py(无需启动前端) │ +│ • E2E 测试:cd test && ./node_modules/.bin/playwright test lib/e2e.spec.ts │ +│ │ +│ 5.4 发现问题直接修复并验证 │ +│ • 平台/AIBridge 相关问题写入 docs/{app_code}/debug.md │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段6:总结 (Summary) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 输出 docs/{app_code}/总结.md: │ +│ • 遇到的问题及处理措施 │ +│ • 设计方案修改建议 │ +│ • 测试用例修改建议 │ +│ • JNPF 平台建议 │ +│ • AIBridge 建议 │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 阶段7:迭代 (Iteration) │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ 根据总结文档、详细设计、测试用例,从阶段2开始迭代 │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ +``` + +### 5.3 开发检查清单 + +``` +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ 开发自检清单 │ +├─────────────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ □ 代码权限检查 │ +│ ├─ ✅ 使用 JNPFClient.from_config() 设置了正确的 app_code │ +│ ├─ ✅ 登录账号有足够的权限创建功能/菜单 │ +│ └─ ✅ 没有写入限制目录(前端/后端/数据库/移动端) │ +│ │ +│ □ 表单开发检查 │ +│ ├─ ✅ 字段命名符合规范(f_ 前缀 + snake_case) │ +│ ├─ ✅ required=True 的字段已设置 │ +│ ├─ ✅ 下拉选项使用 {fullName, id} 格式 │ +│ ├─ ✅ relationForm 已执行两阶段创建和后处理 │ +│ ├─ ✅ 子表字段配置了正确的 is_sub_table=true │ +│ ├─ ✅ create 后执行了 release() │ +│ └─ ✅ 菜单的 parentId 使用正确(非 systemId) │ +│ │ +│ □ 流程开发检查 │ +│ ├─ ✅ webType=2 或 3(纯表单无法绑定流程) │ +│ ├─ ✅ 审批人是两个不同用户(发起人不能同时审批) │ +│ ├─ ✅ 流程模板已激活 │ +│ └─ ✅ 发起流程的表单已发布 │ +│ │ +│ □ 数据操作检查 │ +│ ├─ ✅ 使用 data_model 而非 raw SQL(避免 db_link_id 问题) │ +│ ├─ ✅ DI Preview 只查主库(租户库用 MyBatis-Plus API) │ +│ └─ ✅ Token 格式正确(bearer eyJ...) │ +│ │ +│ □ 删除操作检查 │ +│ ├─ ✅ 使用 soft_delete() 而非 delete()(避免重建冲突) │ +│ └─ ✅ 删除前确认没有其他功能依赖 │ +│ │ +│ □ 命名规范检查 │ +│ ├─ ✅ 表名 snake_case 无前缀(例:product) │ +│ ├─ ✅ 字段名 f_ 前缀 + snake_case(例:f_product_name) │ +│ ├─ ✅ Java 类名 PascalCase(例:ProductEntity) │ +│ └─ ✅ 包名 ssw.{app_code}.*(不是 com.ssw.{app_code}.*) │ +│ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 6. 注意事项与常见问题 + +### 6.1 触发铁律提醒的场景 + +| 用户提到关键词 | 触发铁律 | AI 应立即提醒 | +|---------------|---------|--------------| +| DI/SQL/数据接口/执行SQL | 铁律 1 | ⚠️ DI 有限制,建议触发 backend-dev 技能走 后端开发 | +| 登录/密码/token | 铁律 2 | ⚠️ 前端用真实密码,后端 API 用 hash 密码 | +| 直接 SQL/数据库查询 | 铁律 3 | ⚠️ 必须通过 aibridge API 操作数据库 | +| 建表/表名/字段命名 | 铁律 4 | ⚠️ 表名 snake_case 无前缀,字段 f_ 前缀 + snake_case | +| 硬编码 app_code/项目参数 | 铁律 5 | ⚠️ 必须从 config.py 读取配置 | + +### 6.2 常见问题 + +| 问题 | 原因 | 解决方案 | +|------|------|----------| +| 菜单不显示 | app_code 未设置 或 未发布 | 检查配置,调用 release() | +| 编码冲突 | 已存在同名功能 | 使用 `soft_delete()` | +| "map is null" | formData 类型错误 | 使用 `data_model.create_model()` | +| DI 查不到数据 | db_link_id=0 连主库 | 租户库表需用 MyBatis-Plus API | +| relationForm 无法弹出 | modelId 未设置 | 需要两阶段创建 | +| mvn 找不到 | Maven 未安装或路径不对 | 尝试 `~/maven/bin` | + +### 6.3 下拉选项格式 + +```python +# ★ 必须是 {fullName, id} 格式 +options=[ + {"fullName": "启用", "id": "1"}, + {"fullName": "禁用", "id": "0"}, +] +``` + +### 6.4 后端开发关键约束 + +1. **包名规则**:`ssw.{app_code}.*`(不是 `com.ssw.{app_code}.*`) +2. **代码路径**:`boot/ssw-{app_code}/` +3. **业务包不存在**:先用 `/ssw-pack-init` 创建标准三层结构 +4. **编译后重启**:修改业务模块后必须 `mvn clean install` 重新安装 + +--- + +## 7. 参考文档索引 + +| 文档 | 说明 | +|------|------| +| `aibridge/docs/quickstart.md` | 5 分钟快速入门 | +| `aibridge/docs/platform-guide.md` | App-Code/systemId/发布流程 | +| `aibridge/docs/troubleshooting.md` | 常见问题 | +| `aibridge/docs/api-reference.md` | 全部 API 方法索引 | +| `aibridge/docs/control/01-quick-ref.md` | 控件速查 | +| `aibridge/docs/codedev/` | 扩展开发指南 | +| `aibridge/docs/datainterface/07-examples.md` | 数据接口示例 | +| `aibridge/docs/workflow/` | 工作流指南 | +| `aibridge/examples/quickstart.py` | 端到端可运行示例 | +| `.claude/commands/ssw-dev-flow.md` | 7阶段开发流程 | +| `.claude/skills/backend-dev/SKILL.md` | 后端业务开发技能 | +| `CLAUDE.md` | 项目概述和核心约束 | + +--- + +## 附录:命名规范速查 + +### 数据库命名 + +| 类型 | 规则 | 示例 | +|------|------|------| +| 表名 | snake_case,无前缀 | `product`, `order_detail` | +| 主键 | `f_id`(varchar(50),雪花ID) | | +| 字段 | f_ 前缀 + snake_case | `f_name`, `f_customer_id` | +| 系统字段 | f_id, f_flow_task_id, f_flow_id, f_flow_state, f_tenant_id, f_sort_code, f_create_user, f_create_time, f_modify_user, f_modify_time, f_delete_user, f_delete_time | | + +### Java 类命名 + +| 类型 | 规则 | 示例 | +|------|------|------| +| Entity | `{BusinessName}Entity`(PascalCase) | `ProductEntity` | +| Controller | `{BusinessName}Controller` | `ProductController` | +| Service | `{BusinessName}Service` | `ProductService` | +| ServiceImpl | `{BusinessName}ServiceImpl` | `ProductServiceImpl` | +| Mapper | `{BusinessName}Mapper` | `ProductMapper` | + +### 包名规则 + +| 类型 | 包名规则 | 说明 | +|------|----------|------| +| Entity | `ssw.{app_code}.entity` | 数据库实体 | +| Model | `ssw.{app_code}.model` | BO/VO 对象 | +| Mapper | `jnpf.mapper` | 固定包名 | +| Service | `ssw.{app_code}.service` | 业务接口 | +| Controller | `ssw.{app_code}.controller` | REST 接口 | + +--- + +*文档版本:2026-04-13* diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..d19957d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,169 @@ +# AIBridge - JNPF 低代码平台 Python 接口包 + +通过 AI 对话快速完成产品设计、应用开发和验证。 + +## 功能特性 + +- **API 全覆盖**:封装 JNPF 平台 9 大模块 200+ 端点 +- **配置构建器**:从简洁字段描述自动生成完整 JSON 配置 +- **端到端开发**:登录 → 创建功能 → 发布 → 创建菜单 → 数据操作 +- **DI 代理 SQL**:通过 DataInterface 间接执行 SQL +- **双 HTTP 客户端**:主接口 + 报表独立接口 + +## 架构 + +``` +JNPFClient (认证/HTTP) +├── AuthAPI 认证(登录/登出/用户信息) +├── MenuAPI 菜单管理(CRUD/目录/表单菜单) +├── UserAPI 用户管理(CRUD/岗位/导入导出) +├── OrganizeAPI 组织管理(公司/部门) +├── RoleAPI 角色管理 +├── PositionAPI 岗位管理 +├── DictionaryAPI 数据字典(分类+数据) +├── VisualDevAPI ★可视化开发核心(功能/发布/OnlineDev/代码生成) +├── OnlineDevAPI OnlineDev 数据操作便捷接口 +├── WorkflowAPI 工作流(任务/审批/模板/委托/监控/Webhook) +├── DataInterfaceAPI 数据接口(CRUD/预览/字段/日志) +├── InterfaceOauthAPI 接口认证(外部系统访问控制) +├── PortalAPI 门户管理 +├── MessageAPI 消息公告(公告/消息中心/IM) +├── DataSourceAPI 数据源(连接/测试/同步) +├── PrintDevAPI 打印模板(CRUD/版本) +├── ReportAPI Univer 报表 +├── SysConfigAPI 系统配置 +├── FileAPI 文件管理(上传/下载/知识库) +└── Builders 配置构建器(字段/表单/列表/表结构/完整配置/移动端字段) +``` + +## 快速上手 + +```python +from aibridge import JNPFClient, JNPFConfig +from aibridge.builders import build_full_config, build_create_payload + +# 1. 创建客户端并登录(App-Code 自动设置 systemId) +client = JNPFClient.from_config(JNPFConfig()) +client.login() # 自动使用配置中的账号密码 + +# 2. 构建表单配置 +config = build_full_config( + full_name="文具销售商管理", + en_code="salesVendorManage", + table_name="base_sales_vendor", + table_label="文具销售商表", + description="文具销售商管理系统", + category="e43a773b8a024d109dfb176e99f08a35", + fields=[ + {"field": "f_full_name", "fieldName": "销售商名称", "required": True}, + {"field": "f_en_code", "fieldName": "销售商编码", "required": True}, + {"field": "f_contact", "fieldName": "联系人"}, + {"field": "f_phone", "fieldName": "联系电话"}, + ], +) + +# 3. 创建功能 +payload = build_create_payload(config) +resp = client.visual_dev.create(payload) +func_id = resp.id + +# 4. 发布(systemId 继承自创建步骤) +client.visual_dev.release(func_id) + +# 5. 创建菜单(App-Code 自动设置 systemId) +menu_resp = client.menu.create_form_menu( + full_name="文具销售商管理", + en_code="salesVendorManage", + visual_dev_id=func_id, + parent_id="parent_dir_menu_id", +) +``` + +## 模块访问 + +```python +# 所有 API 模块通过 client 属性访问 +client.auth.login(...) # 或 client.login(...) +client.menu.get_list(...) +client.visual_dev.create(...) +client.workflow.audit(...) + +# 或单独实例化 +from aibridge.modules import VisualDevAPI +api = VisualDevAPI(client) +``` + +## 响应处理 + +```python +resp = client.menu.get_list() +if resp.success: + print(resp.data) # 直接获取 data + print(resp.id) # 快捷获取 id +else: + print(resp.code, resp.msg) # 错误码和消息 + +# 要求成功,否则抛异常 +client.require_success(resp) +``` + +## 目录结构 + +``` +aibridge/ +├── __init__.py # 包入口 +├── client.py # JNPFClient 核心客户端 +├── models.py # 数据模型 +├── exceptions.py # 异常体系 +├── config.py # 配置管理 +├── modules/ # 16 个 API 模块 +├── builders/ # 6 个配置构建器(字段/表单/列表/表结构/完整配置/移动端字段) +├── utils/ # 工具模块 +├── tests/ # 测试 +├── examples/ # ★ 标准示例 +│ └── quickstart.py # 完整操作示例(登录/表单/菜单/DI/工作流/软删除) +└── docs/ # 文档 + ├── portal/ # 门户开发指南(21种组件+27个API) + ├── workflow/ # 工作流开发指南(示例+指南+故障排查) + ├── control/ # 控件开发指南 + ├── datainterface/ # 数据接口开发指南 + └── codedev/ # ★ 扩展开发指南(前后端代码模式) + ├── README.md # 速查索引 + ├── 01-backend-pattern.md # 后端开发模式 + ├── 02-frontend-pattern.md # 前端开发模式 + ├── 03-examples-index.md # 示例目录 + ├── 04-import-export.md # 导入导出详解 + ├── 05-table-operation.md # 表格操作 + ├── 06-chart-examples.md # 图表示例 + ├── 07-form-examples.md # 表单控件 + ├── 08-special-features.md # 特殊功能 + └── 09-quick-start.md # 快速开发模板 +``` + +## 测试 + +### 移动端 H5 测试 + +**项目位置**:`uniapp/`(基于 jnpf/移动端/jnpf-app-vue3 复制) + +**运行步骤**: +1. 用 **HBuilderX** 导入项目(菜单:文件 → 导入 → 从本地项目导入) +2. 菜单:运行 → 运行到浏览器 → Chrome + +**命令行运行**(项目需先用 HBuilderX 导入): +```bash +/Applications/HBuilderX.app/Contents/MacOS/cli launch web --project $ccWorkDir/uniapp +``` + +**Playwright 移动端测试**: +```bash +cd $ccWorkDir/test +npx playwright test mobile --reporter=line +``` + +### PC 端测试 + +```bash +cd $ccWorkDir/test +npx playwright test --reporter=line +``` diff --git a/docs/api-reference.md b/docs/api-reference.md new file mode 100644 index 0000000..c04f66f --- /dev/null +++ b/docs/api-reference.md @@ -0,0 +1,714 @@ +# API 参考 + +> AIBridge 全部接口方法索引,按模块分组。 + +## 认证模块 - AuthAPI + +**类名:** `AuthAPI` +**模块文件:** `aibridge.modules.auth` +**依赖:** 也可通过 `JNPFClient` 直接调用(`client.login()` 等) + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `login(account, password)` | POST | `/api/oauth/Login` | 登录获取 Token | +| `logout()` | POST | `/api/oauth/Logout` | 退出登录 | +| `get_user_info(system_code, is_backend)` | GET | `/api/oauth/CurrentUser` | 获取当前用户信息 | +| `get_login_config()` | GET | `/api/oauth/getLoginConfig` | 获取登录配置 | +| `get_config(account)` | GET | `/api/oauth/getConfig/{account}` | 获取系统默认配置 | +| `get_ticket()` | GET | `/api/oauth/getTicket` | 获取登录票据 | +| `get_ticket_status(ticket)` | GET | `/api/oauth/getTicketStatus/{ticket}` | 获取票据登录状态 | +| `unlock(data)` | POST | `/api/oauth/LockScreen` | 锁屏解锁 | +| `socials_login(params)` | POST | `/api/oauth/Login/socials` | 第三方登录回调 | +| `get_code_certificate()` | GET | `/api/oauth/codeCertificate` | 扫码登录获取凭证 | +| `get_code_certificate_status(ticket)` | GET | `/api/oauth/codeCertificateStatus/{ticket}` | 凭证状态 | +| `update_password_message()` | POST | `/api/oauth/updatePasswordMessage` | 修改密码信息发送 | + +## 菜单管理 - MenuAPI + +**类名:** `MenuAPI` +**URL 前缀:** `/api/system/Menu` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/system/Menu/ModuleBySystem` | 获取菜单列表 | +| `get_selector(data, id)` | GET | `/api/system/Menu/Selector/{id}` | 上级菜单下拉框 | +| `get_selector_all(data)` | GET | `/api/system/Menu/Selector/All` | 菜单列表(下拉框,仅 system 子节点) | +| `get_all_menus()` | - | `data_model.query(base_module)` | ★ 获取所有菜单(按 system_id 过滤,扁平列表) | +| `get_user_menu_tree()` | - | `/api/oauth/CurrentUser` | ★ 获取用户可见菜单树(多级嵌套结构) | +| `get_children(parent_id)` | - | - | 获取指定菜单的子菜单(递归查找) | +| `get_selector_filter(data, id)` | GET | `/api/system/Menu/SelectorFilter/{id}` | 上级菜单下拉框(发布过滤) | +| `get_selector_form(data)` | GET | `/api/system/Menu/Selector/Form` | 菜单表单选择器 | +| `get_system_menu()` | GET | `/api/system/Menu/getSystemMenu` | 菜单表单树 | +| `get_menu_list_form_type(data)` | GET | `/api/system/Menu/Selector/Page` | 特定类型菜单(带分页) | +| `create(data)` | POST | `/api/system/Menu` | 新建菜单 | +| `update(data)` | PUT | `/api/system/Menu/{id}` | 修改菜单 | +| `get_info(menu_id)` | GET | `/api/system/Menu/{menu_id}` | 菜单详情 | +| `delete(menu_id)` | DELETE | `/api/system/Menu/{menu_id}` | 删除菜单(不推荐) | +| `soft_delete(menu_id)` | PUT | `/api/system/Menu/{menu_id}` | 软删除:parentId=-100、停用、改名改编码(避免冲突) | +| `move_to_deleted(menu_ids)` | PUT | - | 批量软删除 | +| `export(menu_id)` | GET | `/api/system/Menu/{menu_id}/Actions/Export` | 导出菜单数据 | +| `get_permission_group(data)` | GET | `/api/system/Menu/getPermissionGroup/{id}` | 查看权限组 | +| `get_permission_info(data)` | GET | `/api/system/Menu/getPermission/{id}/{permissionId}` | 获取权限 | +| `create_directory_menu(...)` | POST | `/api/system/Menu` | 创建目录菜单(type=1)✅ | +| `create_form_menu(...)` | POST | `/api/system/Menu` | 创建功能菜单(type=3)✅ 自动修复 | +| `create_page_menu(...)` | POST | `/api/system/Menu` | 创建Vue页面菜单(type=2)✅ | +| `create_app_directory_menu(...)` | POST | `/api/system/Menu` | 创建移动端目录菜单(category=App) | +| `create_app_form_menu(...)` | POST | `/api/system/Menu` | 创建移动端功能菜单(category=App) | +| `create_app_form_menu_with_parent(...)` | POST | `/api/system/Menu` | 创建移动端菜单,自动创建父目录 | +| `update_parent(menu_id, new_parent_id)` | PUT | `/api/system/Menu/{menu_id}` | 修改菜单父级 | +| `batch_update_parent(menu_ids, new_parent_id)` | PUT | - | 批量修改菜单父级 | +| `get_id_by_en_code(en_code)` | GET | - | 通过enCode查询菜单ID | +| `get_id_by_name(full_name)` | GET | - | 通过名称查询菜单ID | + +## 用户管理 - UserAPI + +**类名:** `UserAPI` +**URL 前缀:** `/api/permission/Users` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(params)` | GET | `/api/permission/Users` | 用户列表(分页) | +| `get_selector(data)` | GET | `/api/permission/Users/Selector` | 用户下拉框 | +| `create(data)` | POST | `/api/permission/Users` | 新建用户 | +| `update(data)` | PUT | `/api/permission/Users/{id}` | 修改用户 | +| `get_info(user_id)` | GET | `/api/permission/Users/{user_id}` | 用户信息 | +| `delete(user_id)` | DELETE | `/api/permission/Users/{user_id}` | 删除用户 | +| `batch_delete(data)` | POST | `/api/permission/Users/BatchDelete` | 批量删除 | +| `reset_password(user_id, data)` | POST | `/api/permission/Users/{id}/Actions/ResetPassword` | 重置密码 | +| `batch_update_state(data)` | POST | `/api/permission/Users/BatchUpdateState` | 批量更新状态 | +| `unlock(user_id)` | PUT | `/api/permission/Users/{id}/Actions/unlock` | 解除锁定 | +| `get_user_info_list(ids)` | POST | `/api/permission/Users/getUserList` | 批量获取用户信息 | +| `export_excel(data)` | GET | `/api/permission/Users/ExportData` | 导出 Excel | +| `template_download()` | GET | `/api/permission/Users/TemplateDownload` | 导入模板下载 | +| `import_data(data)` | POST | `/api/permission/Users/ImportData` | 导入用户 | +| `import_preview(data)` | GET | `/api/permission/Users/ImportPreview` | 导入预览 | +| `export_exception_data(data)` | POST | `/api/permission/Users/ExportExceptionData` | 导出错误数据 | +| `get_selected_list(ids)` | POST | `/api/permission/Users/getSelectedList` | 获取选中用户信息 | +| `get_work_by_user(data)` | GET | `/api/permission/Users/getWorkByUser` | 离职交接数据 | +| `work_handover(data)` | POST | `/api/permission/Users/workHandover` | 工作交接 | +| `get_receive_user_list(data)` | GET | `/api/permission/Users/ReceiveUserList` | 同部门/岗位/公司用户 | +| `get_same_pos_user(data)` | GET | `/api/permission/Users/{id}/SelectorByUserPosId` | 相同岗位用户 | +| `get_user_position(user_id)` | GET | `/api/permission/Users/{user_id}/GetPosition` | 获取用户岗位 | +| `set_user_position(data)` | POST | `/api/permission/Users/{id}/SetPosition` | 设置用户岗位 | +| `batch_set_user_position(data)` | POST | `/api/permission/Users/SetPositionBatch` | 批量设置岗位 | +| `get_auth_group(data)` | GET | `/api/permission/Users/getAllPermission` | 权限分组 | +| `get_auth_list(data)` | GET | `/api/permission/Users/Authorize` | 用户查看权限 | + +## 组织管理 - OrganizeAPI + +**类名:** `OrganizeAPI` +**URL 前缀:** `/api/permission/Organize` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_async_list(data)` | GET | `/api/permission/Organize/AsyncList/{parentId}` | 组织列表(异步加载) | +| `get_list(data)` | GET | `/api/permission/Organize` | 组织列表 | +| `create(data)` | POST | `/api/permission/Organize` | 新建组织 | +| `update(data)` | PUT | `/api/permission/Organize/{id}` | 修改组织 | +| `get_info(org_id)` | GET | `/api/permission/Organize/{org_id}` | 组织信息 | +| `delete(org_id)` | DELETE | `/api/permission/Organize/{org_id}` | 删除组织 | +| `get_selector(data)` | GET | `/api/permission/Organize/Selector` | 组织下拉框 | +| `get_selected_list(ids)` | POST | `/api/permission/Organize/SelectedList` | 选中组织信息 | +| `get_organize_condition(ids)` | POST | `/api/permission/Organize/OrganizeCondition` | 通过ID获取组织列表 | +| `get_org_and_pos_selector(data)` | GET | `/api/permission/Organize/AsyncPosList` | 组织和岗位下拉框 | +| `export_excel(data)` | GET | `/api/permission/Organize/ExportData` | 导出 Excel | +| `template_download()` | GET | `/api/permission/Organize/TemplateDownload` | 导入模板 | +| `import_data(data)` | POST | `/api/permission/Organize/ImportData` | 导入 | +| `import_preview(data)` | GET | `/api/permission/Organize/ImportPreview` | 导入预览 | +| `export_exception_data(data)` | POST | `/api/permission/Organize/ExportExceptionData` | 导出错误数据 | + +## 角色管理 - RoleAPI + +**类名:** `RoleAPI` +**URL 前缀:** `/api/permission/Role` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/permission/Role` | 角色列表 | +| `get_selector(type_, is_system)` | GET | `/api/permission/Role/Selector` | 角色下拉框 | +| `create(data)` | POST | `/api/permission/Role` | 新建角色 | +| `update(data)` | PUT | `/api/permission/Role/{id}` | 修改角色 | +| `get_info(role_id)` | GET | `/api/permission/Role/{role_id}` | 角色信息 | +| `delete(role_id)` | DELETE | `/api/permission/Role/{role_id}` | 删除角色 | +| `get_role_by_condition(data)` | POST | `/api/permission/Role/RoleCondition` | 选中角色信息 | +| `create_role_relation(data)` | POST | `/api/permission/RoleRelation` | 创建角色关联 | +| `delete_role_relation(relation_id)` | DELETE | `/api/permission/RoleRelation/{id}` | 删除角色关联 | +| `get_role_relation_list(data)` | GET | `/api/permission/RoleRelation` | 角色关联列表 | + +## 岗位管理 - PositionAPI + +**类名:** `PositionAPI` +**URL 前缀:** `/api/permission/Position` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/permission/Position` | 岗位列表 | +| `get_selector(data)` | GET | `/api/permission/Position/Selector` | 岗位下拉框 | +| `create(data)` | POST | `/api/permission/Position` | 新建岗位 | +| `update(data)` | PUT | `/api/permission/Position/{id}` | 修改岗位 | +| `get_info(pos_id)` | GET | `/api/permission/Position/{pos_id}` | 岗位信息 | +| `delete(pos_id)` | DELETE | `/api/permission/Position/{pos_id}` | 删除岗位 | + +## 数据字典 - DictionaryAPI + +**类名:** `DictionaryAPI` +**分类前缀:** `/api/system/DictionaryType` +**数据前缀:** `/api/system/DictionaryData` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| **分类管理** | | | | +| `get_type_list()` | GET | `/api/system/DictionaryType` | 字典分类列表 | +| `get_type_selector(id)` | GET | `/api/system/DictionaryType/Selector/{id}` | 分类下拉框 | +| `create_type(data)` | POST | `/api/system/DictionaryType` | 添加分类 | +| `update_type(data)` | PUT | `/api/system/DictionaryType/{id}` | 修改分类 | +| `get_type_info(type_id)` | GET | `/api/system/DictionaryType/{type_id}` | 分类信息 | +| `delete_type(type_id)` | DELETE | `/api/system/DictionaryType/{type_id}` | 删除分类 | +| **字典数据** | | | | +| `get_data_list(type_id, params)` | GET | `/api/system/DictionaryData/{type_id}` | 数据列表 | +| `get_all()` | GET | `/api/system/DictionaryData/All` | 全部字典数据 | +| `get_data_type_selector(type_id, is_tree, id)` | GET | `/api/system/DictionaryData/{type_id}/Selector/{id}` | 分类下拉框 | +| `get_data_selector(type_id)` | GET | `/api/system/DictionaryData/{type_id}/Data/Selector` | 数据下拉框 | +| `create_data(data)` | POST | `/api/system/DictionaryData` | 添加字典数据 | +| `update_data(data)` | PUT | `/api/system/DictionaryData/{id}` | 修改字典数据 | +| `get_data_info(data_id)` | GET | `/api/system/DictionaryData/{data_id}/Info` | 字典数据信息 | +| `delete_data(data_id)` | DELETE | `/api/system/DictionaryData/{data_id}` | 删除字典数据 | +| `export_data(type_id)` | GET | `/api/system/DictionaryData/{type_id}/Actions/Export` | 导出数据 | + +## 可视化开发 - VisualDevAPI + +**类名:** `VisualDevAPI` +**核心前缀:** `/api/visualdev/Base` +**数据操作前缀:** `/api/visualdev/OnlineDev` +**代码生成前缀:** `/api/visualdev/Generater` + +### 功能 CRUD + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/visualdev/Base` | 功能列表 | +| `get_form_list(data)` | GET | `/api/visualdev/Base/list` | 功能列表(集成助手) | +| `create(data)` | POST | `/api/visualdev/Base` | 新建功能 | +| `update(data)` | PUT | `/api/visualdev/Base/{id}` | 修改功能 | +| `get_info(func_id)` | GET | `/api/visualdev/Base/{func_id}` | 功能详情 | +| `delete(func_id)` | DELETE | `/api/visualdev/Base/{func_id}` | 删除功能 | +| `soft_delete(func_id)` | PUT | `/api/visualdev/Base/{func_id}` | 软删除:改名改编码、sortCode沉底(避免冲突) | +| `copy(func_id)` | POST | `/api/visualdev/Base/{id}/Actions/Copy` | 复制功能 | +| `release(func_id)` | POST | `/api/visualdev/Base/{id}/Actions/Release` | **发布功能** | +| `get_release_menu(func_id)` | GET | `/api/visualdev/Base/{id}/getReleaseMenu` | 已发布菜单 | +| `create_menu(func_id, data)` | POST | `/api/visualdev/Base/{id}/Actions/Module` | 生成菜单 | +| `get_form_data_fields(func_id, filter_type)` | GET | `/api/visualdev/Base/{id}/FormDataFields` | 表单主表属性列表 | +| `get_field_data_select(data)` | GET | `/api/visualdev/Base/{modelId}/FieldDataSelect` | 表单数据下拉框 | +| `get_selector(data)` | GET | `/api/visualdev/Base/Selector` | 功能下拉框 | +| `get_column_list(data)` | GET | `/api/visualdev/Base/getColumnList` | 列表字段 | +| `get_list_by_system(data)` | GET | `/api/visualdev/Base/getListBySystem` | 跨应用菜单 | +| `get_id_by_en_code(en_code)` | GET | `/api/visualdev/Base/Id/{enCode}` | 通过enCode查询功能ID | + +### OnlineDev 数据操作 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_config(model_id, data)` | GET | `/api/visualdev/OnlineDev/{id}/Config` | 列表配置 JSON | +| `get_config_by_menu_id(data)` | GET | `/api/visualdev/OnlineDev/Config` | 通过菜单获取配置 | +| `get_form_data(model_id)` | GET | `/api/visualdev/OnlineDev/{id}/FormData` | 表单配置 JSON | +| `get_model_list(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/List` | 数据列表 | +| `create_model(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}` | 新建数据 | +| `update_model(model_id, data)` | PUT | `/api/visualdev/OnlineDev/{id}/{recordId}` | 修改数据 | +| `get_model_info(model_id, record_id, menu_id)` | GET | `/api/visualdev/OnlineDev/{id}/{recordId}` | 数据详情 | +| `delete_model(model_id, record_id)` | DELETE | `/api/visualdev/OnlineDev/{id}/{recordId}` | 删除数据 | +| `batch_delete_model(model_id, data)` | POST | `/api/visualdev/OnlineDev/batchDelete/{id}` | 批量删除 | +| `get_data_change(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/DataChange` | 数据变更对比 | +| `export_model_data(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/Actions/ExportData` | 导出数据 | +| `get_template(model_id)` | GET | `/api/visualdev/OnlineDev/{id}/Template` | 下载导入模板 | +| `export_data(model_id)` | POST | `/api/visualdev/OnlineDev/{id}/Actions/Export` | 导出模板 | +| `launch_flow(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/actionLaunchFlow` | 发起流程 | +| `get_relation_query(data)` | POST | `/api/visualdev/OnlineDev/RelationQuery` | 关联查询 | + +### 个人视图 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_view_list(data)` | GET | `/api/visualdev/personal` | 视图列表 | +| `create_view(data)` | POST | `/api/visualdev/personal` | 新建视图 | +| `update_view(data)` | PUT | `/api/visualdev/personal/{id}` | 修改视图 | +| `delete_view(view_id, menu_id)` | DELETE | `/api/visualdev/personal/{id}?menuId=xxx` | 删除视图 | +| `set_default_view(view_id, menu_id)` | PUT | `/api/visualdev/personal/{id}/setDefault?menuId=xxx` | 设置默认视图 | + +### 代码生成 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `download_code(func_id, data)` | POST | `/api/visualdev/Generater/{id}/Actions/DownloadCode` | 下载代码 | +| `code_preview(func_id, data)` | POST | `/api/visualdev/Generater/{id}/Actions/CodePreview` | 代码预览 | +| `get_alias_info(func_id)` | GET | `/api/visualdev/Generater/{id}/Alias/Info` | 命名规范 | +| `save_alias(func_id, data)` | POST | `/api/visualdev/Generater/{id}/Alias/Save` | 更新命名规范 | + +### AI / OCR / 跨应用 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_ai_info(data)` | POST | `/api/visualdev/ai/form` | AI 表单生成 | +| `get_ocr_data(data)` | POST | `/api/visualdev/ocr` | OCR 识别 | +| `get_share_list()` | GET | `/api/visualdev/share` | 跨应用表单列表 | +| `get_share_info(ids)` | POST | `/api/visualdev/share/SelectedList` | 跨应用表单详情 | +| `save_share(data)` | POST | `/api/visualdev/share/save` | 保存跨应用回显 | +| `get_share_selector()` | GET | `/api/visualdev/share/Selector` | 功能下拉框(含跨应用) | + +## 代码生成器 - CodeGenerator + +**类名:** `CodeGenerator` +**模块文件:** `aibridge.utils.code_generator` +**说明:** JNPF VisualDev 代码生成与命名修复封装,自动处理 JNPF 类名前缀 bug。 + +### 生成与修复 + +| 方法 | 说明 | +|------|------| +| `generate(func_id, module_name, **kwargs)` | 生成前后端代码,返回 `{success, frontend_path, backend_path}` | +| `fix_class_names(backend_path, old_class_prefix, new_class_prefix, frontend_path)` | 修复类名前缀,返回 `{backend: [(old, new), ...], frontend: int}` | + +> `fix_class_names()` 的 `old_class_prefix` 可不传,会自动从 `formData.tableName` 计算(如 `ais_aisproject` → `Ais_aisproject`)。 + +### 使用示例 + +```python +from aibridge import JNPFClient, JNPFConfig +from aibridge.utils.code_generator import CodeGenerator + +config = JNPFConfig() +client = JNPFClient.from_config(config) +client.login() + +gen = CodeGenerator(client, config) + +# 1. 生成代码 +result = gen.generate( + func_id="808986025610185477", + module_name="Project", # 纯业务名 PascalCase + enable_flow=0, + tables='0', + form_type='2', +) +frontend_path = result['frontend_path'] +backend_path = result['backend_path'] + +# 2. 自动修复类名前缀(old_prefix 可省略) +fix_result = gen.fix_class_names(backend_path, None, "Project", frontend_path) +# fix_result = {'backend': [('Ais_aisprojectEntity', 'ProjectEntity'), ...], 'frontend': 1} +``` + +### 运行脚本 + +推荐使用 `aibridge/utils/run-codegen.py`,一键完成代码生成 + 类名修复 + 菜单挂载: + +```bash +python3 aibridge/utils/run-codegen.py [menu_title] +# 示例: +python3 aibridge/utils/run-codegen.py 808986025610185477 Project 项目管理 +``` + +## OnlineDev 便捷模块 - OnlineDevAPI + +**类名:** `OnlineDevAPI` +**URL 前缀:** `/api/visualdev/OnlineDev` +**说明:** 面向数据 CRUD 的便捷封装,参数更简洁。 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_config(model_id, **kwargs)` | GET | `/api/visualdev/OnlineDev/{id}/Config` | 列表配置 | +| `get_form_data(model_id)` | GET | `/api/visualdev/OnlineDev/{id}/FormData` | 表单配置 | +| `list(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/List` | 数据列表 | +| `create(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}` | 新建记录 | +| `update(model_id, record_id, data)` | PUT | `/api/visualdev/OnlineDev/{id}/{recordId}` | 更新记录 | +| `get(model_id, record_id, menu_id)` | GET | `/api/visualdev/OnlineDev/{id}/{recordId}` | 记录详情 | +| `delete(model_id, record_id)` | DELETE | `/api/visualdev/OnlineDev/{id}/{recordId}` | 删除记录 | +| `batch_delete(model_id, ids)` | POST | `/api/visualdev/OnlineDev/batchDelete/{id}` | 批量删除 | +| `export_data(model_id, data)` | POST | `/api/visualdev/OnlineDev/{id}/Actions/ExportData` | 导出数据 | +| `import_template(model_id)` | GET | `/api/visualdev/OnlineDev/{id}/Template` | 导入模板 | + +## 工作流 - WorkflowAPI + +**类名:** `WorkflowAPI` +**详细文档:** [工作流指南](workflow/README.md) + +### 流程任务 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_launch_list(data)` | GET | `/api/workflow/task` | 发起列表 | +| `get_task_info(task_id, data)` | GET | `/api/workflow/task/{id}` | 审批详情 | +| `create(data)` | POST | `/api/workflow/task` | 新建发起 | +| `update(data)` | PUT | `/api/workflow/task/{id}` | 更新发起 | +| `delete(task_id)` | DELETE | `/api/workflow/task/{id}` | 删除发起 | +| `launch_recall(task_id, data)` | PUT | `/api/workflow/task/Recall/{id}` | 撤回 | +| `revoke(task_id, data)` | PUT | `/api/workflow/task/Revoke/{id}` | 撤销 | +| `press(task_id)` | POST | `/api/workflow/task/Press/{id}` | 催办 | +| `get_event_log(task_id)` | GET | `/api/workflow/task/{id}/EventLog` | 事件日志 | +| `get_task_user_list(data)` | GET | `/api/workflow/task/TaskUserList/{taskId}` | 相关人员 | +| `get_sub_flow_info(node_code, flow_id)` | GET | `/api/workflow/task/SubFlowInfo` | 子流程 | +| `get_start_form_info(task_id)` | GET | `/api/workflow/task/ViewStartForm/{id}` | 发起表单 | +| `retry_outside(node_id)` | GET | `/api/workflow/task/Hooks/Retry/{id}` | 外部节点重试 | + +### 审批操作 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_before_list(category, data)` | GET | `/api/workflow/operator/List/{category}` | 待审核列表 | +| `audit(operator_id, data)` | POST | `/api/workflow/operator/Audit/{id}` | 审核(同意/拒绝) | +| `sign(operator_id)` | POST | `/api/workflow/operator/Sign` | 签收 | +| `cancel_sign(operator_id)` | POST | `/api/workflow/operator/Sign` | 退签 | +| `batch_sign(data)` | POST | `/api/workflow/operator/Sign` | 批量签收/退签 | +| `handle(operator_id)` | POST | `/api/workflow/operator/Transact` | 开始办理 | +| `batch_handle(data)` | POST | `/api/workflow/operator/Transact` | 批量办理 | +| `save_audit(operator_id, data)` | POST | `/api/workflow/operator/SaveAudit/{id}` | 暂存审批 | +| `assist(operator_id, data)` | POST | `/api/workflow/operator/Assist/{id}` | 协办 | +| `audit_recall(operator_id, data)` | POST | `/api/workflow/operator/Recall/{id}` | 撤回审核 | +| `transfer(operator_id, data)` | POST | `/api/workflow/operator/Transfer/{id}` | 转审 | +| `back(operator_id, data)` | POST | `/api/workflow/operator/SendBack/{id}` | 退回审核 | +| `get_back_node_list(operator_id)` | GET | `/api/workflow/operator/SendBackNodeList/{id}` | 退回节点列表 | +| `free_approver(operator_id, data)` | POST | `/api/workflow/operator/AddSign/{id}` | 加签 | +| `reduce_approver(operator_id, data)` | POST | `/api/workflow/operator/ReduceApprover/{id}` | 减签 | +| `get_candidate_user(data)` | POST | `/api/workflow/operator/CandidateUser/{id}` | 候选人列表 | +| `get_candidates(operator_id, data)` | POST | `/api/workflow/operator/CandidateNode/{id}` | 是否有候选人 | +| `batch_operation(data)` | POST | `/api/workflow/operator/BatchOperation` | 批量审批 | +| `get_record_list(task_id, node_id)` | GET | `/api/workflow/operator/RecordList` | 经办列表 | +| `get_circulate_list(task_id, node_id)` | GET | `/api/workflow/operator/CirculateList` | 抄送人员 | + +### 流程模板 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_template_list(data)` | GET | `/api/workflow/template` | 模板列表 | +| `get_flow_list(form_id)` | GET | `/api/workflow/template/{form_id}/FlowList` | 表单流程列表 | +| `create_template(data)` | POST | `/api/workflow/template` | 新建模板 | +| `update_template(data)` | PUT | `/api/workflow/template/{id}` | 修改模板 | +| `get_template_info(template_id)` | GET | `/api/workflow/template/{id}` | 模板信息 | +| `delete_template(template_id)` | DELETE | `/api/workflow/template/{id}` | 删除模板 | +| `copy_template(template_id)` | POST | `/api/workflow/template/{id}/Actions/Copy` | 复制模板 | +| `export_template(template_id)` | GET | `/api/workflow/template/{id}/Actions/Export` | 导出模板 | +| `save_flow(data)` | POST | `/api/workflow/template/Save` | 保存流程设计 | +| `get_flow_info(template_id)` | GET | `/api/workflow/template/Info/{id}` | 流程设计详情 | +| `get_version_list(template_id)` | GET | `/api/workflow/template/Version/{id}` | 版本列表 | +| `copy_version(version_id)` | POST | `/api/workflow/template/Version/{id}/Actions/Copy` | 复制版本 | +| `get_flow_form_info(template_id)` | GET | `/api/workflow/template/{id}/FormInfo` | 流程表单(小ID) | +| `get_flow_start_form_info(template_id)` | GET | `/api/workflow/template/StartForm/{id}` | 流程表单(大ID) | +| `get_tree_list(form_type)` | GET | `/api/workflow/template/TreeList` | 流程列表(树形) | + +### Webhook + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_webhook_url(data)` | GET | `/api/workflow/Hooks/getUrl` | 获取 Webhook URL | +| `get_webhook_params(random_str)` | GET | `/api/workflow/Hooks/getParams/{str}` | 获取 Webhook 字段 | +| `webhook_start(flow_id, random_str)` | GET | `/api/workflow/Hooks/{flowId}/start/{str}` | 开启 Webhook | + +### 委托与监控 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_delegate_list(data)` | GET | `/api/workflow/FlowDelegate` | 委托列表 | +| `get_monitor_list(data)` | GET | `/api/workflow/FlowMonitor` | 监控列表 | + +### 便捷方法 + +| 方法 | 说明 | 返回 | +|------|------|------| +| `create_simple_flow(full_name, en_code, form_id, approver_user_ids, ...)` | 一键创建流程模板并发布 | `{"template_id": ..., "version_id": ...}` | +| `launch_task(flow_version_id, form_data, urgent, draft)` | 快捷发起流程(formData 直接传 dict) | `APIResponse` | +| `approve(operator_id, opinion)` | 快捷审批通过(自动带 status=1) | `APIResponse` | +| `reject(operator_id, opinion)` | 快捷审批拒绝(自动带 status=2) | `APIResponse` | +| `get_pending_tasks(page, page_size)` | 获取待审批列表 | `list[dict]` | +| `build_simple_flow_xml()` | 获取简单流程默认 BPMN XML(URL 编码) | `str` | +| `build_simple_flow_nodes(form_id, ...)` | 构建简单流程 flowNodes 配置 | `dict` | + +> **注意**:`create_template()` 必须包含 `flowXml/flowNodes/flowConfig`,否则后端 NPE 导致 templateJson 未创建。`create_simple_flow()` 已内置处理。 + +## 数据库表管理 - DataModelAPI + +**类名:** `DataModelAPI` +**模块文件:** `aibridge.modules.data_model` +**URL 前缀:** `/api/system/DataModel` +**前端参考:** `api/systemData/dataModel.ts` +**说明:** 数据库表和字段的 CRUD 操作,支持通过 DataSource 管理数据库连接。优先使用此模块操作数据库,而非直接执行 SQL。 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_table_list(link_id, data)` | GET | `/api/system/DataModel/{link_id}/Tables` | 获取数据库表列表 | +| `get_table_list_all(link_id, data)` | GET | `/api/system/DataModel/{link_id}/TableAll` | 获取表列表(含视图) | +| `preview_table(link_id, table, data)` | GET | `/api/system/DataModel/{link_id}/Table/{table}/Preview` | 预览表数据 | +| `get_table_info(link_id, table)` | GET | `/api/system/DataModel/{link_id}/Table/{table}` | 获取表详情(含字段列表) | +| `create_table(link_id, data)` | POST | `/api/system/DataModel/{link_id}/Table` | 新建数据库表 | +| `update_table(link_id, data)` | PUT | `/api/system/DataModel/{link_id}/Table` | 修改数据库表 | +| `delete_table(link_id, table)` | DELETE | `/api/system/DataModel/{link_id}/Table/{table}` | 删除数据库表 | +| `get_field_list(link_id, table, field_type)` | GET | `/api/system/DataModel/{link_id}/Tables/{table}/Fields` | 获取表字段列表 | +| `add_fields(link_id, data)` | PUT | `/api/system/DataModel/{link_id}/addFields` | 新增字段 | +| `export_table(link_id, table)` | GET | `/api/system/DataModel/{link_id}/Table/{table}/Actions/Export` | 导出表结构 | + +> **注意**:`link_id="0"` 表示主数据库,非 0 值表示业务数据源(通过 db_link_id 指定)。 + +## 数据接口 - DataInterfaceAPI + +**类名:** `DataInterfaceAPI` +**模块文件:** `aibridge.modules.data_interface` +**URL 前缀:** `/api/system/DataInterface` +**前端参考:** `api/systemData/dataInterface.ts` +**后端实现:** `DataInterfaceServiceImpl.java` +**Swagger:** http://127.0.0.1:30000/doc.html#/home(仅本地可用) + +### 基础 CRUD + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/system/DataInterface` | 接口列表(**必须传 category**) | +| `get_selector()` | GET | `/api/system/DataInterface/Selector` | 接口下拉框 | +| `create(data)` | POST | `/api/system/DataInterface` | 新建接口 | +| `update(data)` | PUT | `/api/system/DataInterface/{id}` | 修改接口 | +| `get_info(di_id)` | GET | `/api/system/DataInterface/{di_id}` | 接口信息 | +| `delete(di_id)` | DELETE | `/api/system/DataInterface/{di_id}` | 删除接口 | +| `copy(di_id)` | POST | `/api/system/DataInterface/{di_id}/Actions/Copy` | 复制接口 | + +### 执行与预览 + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `preview(di_id, data)` | POST | `/api/system/DataInterface/{id}/Actions/Preview` | **预览/执行** | +| `execute(di_id, params)` | - | 调用 preview | **简化执行**(dict 自动转 paramList) | +| `get_param(di_id)` | GET | `/api/system/DataInterface/GetParam/{id}` | 接口参数 | +| `export_data(di_id)` | GET | `/api/system/DataInterface/{id}/Actions/Export` | 导出数据 | +| `get_log(di_id, data)` | GET | `/api/system/DataInterfaceLog/{id}` | 调用日志 | +| `get_data_select(data)` | POST | `/api/system/DataInterface/{id}/Actions/List` | 接口数据列表 | +| `get_data_info_by_ids(di_id, data)` | POST | `/api/system/DataInterface/{id}/Actions/InfoByIds` | 批量详情 | +| `get_fields(di_id, data)` | POST | `/api/system/DataInterface/{id}/Actions/GetFields` | 接口字段 | +| `get_selector_list(data)` | GET | `/api/system/DataInterface/getList` | 接口列表(工作流用) | + +### Payload 构建器(静态方法,无需 client) + +| 方法 | 说明 | +|------|------| +| `build_payload(...)` | 构建标准 SQL 接口 payload(含 isPostPosition=0) | +| `build_select_payload(...)` | 构建 SELECT payload(支持 hasPage 分页) | +| `build_insert_payload(...)` | 构建 INSERT payload(自动生成 SQL) | +| `build_update_payload(...)` | 构建 UPDATE payload(自动生成 SQL) | +| `build_delete_payload(...)` | 构建 DELETE payload(自动生成 SQL) | + +### 一键创建接口(封装 create + ID 查找) + +| 方法 | 说明 | +|------|------| +| `create_sql_interface(...)` | 创建 SQL 接口并返回 ID | +| `create_select_interface(...)` | 创建 SELECT 接口(支持分页) | +| `create_insert_interface(...)` | 创建 INSERT 接口 | +| `create_update_interface(...)` | 创建 UPDATE 接口 | +| `create_delete_interface(...)` | 创建 DELETE 接口 | + +### 三种接口类型 + +| type | 名称 | 说明 | +|------|------|------| +| 1 | SQL操作 | 执行 SQL(增删改查) | +| 2 | 静态数据 | 返回固定 JSON(图表、选项) | +| 3 | API操作 | 调用 HTTP 接口,独有异常验证 | + +**dataExceptionJson**(仅 type=3):JS 脚本返回 true 继续、false 重试(最多3次)。错误码 SYS121/122/123。 +**dataJsJson**(所有类型):最终返回前的 JS 数据处理脚本。 + +### 使用示例 + +```python +from aibridge.modules.data_interface import DataInterfaceAPI + +di = DataInterfaceAPI(client) + +# 创建查询接口(一步到位,返回 ID) +query_id = di.create_sql_interface( + full_name="按编码查询", + en_code="query_by_code", + sql="SELECT f_id, f_full_name FROM base_visual_dev WHERE f_en_code = {code} AND f_delete_mark = 0", + parameters=[{"field": "code", "fieldName": "编码", "dataType": "varchar", "required": 1, "sourceType": 1}], + category="806502782600217349", + action=3, +) + +# 执行查询(简化参数传递) +rows = di.execute(query_id, {"code": "ABC001"}) +for row in rows: + print(row["f_id"], row["f_full_name"]) + +# 创建新增接口(使用系统变量 @snowFlakeID) +insert_id = di.create_sql_interface( + full_name="新增记录", + en_code="insert_record", + sql="INSERT INTO base_visual_dev (f_id, f_full_name, f_en_code, f_type, f_enabled_mark, f_tenant_id, f_delete_mark) VALUES (@snowFlakeID, {name}, {code}, {type}, 1, '0', 0)", + parameters=[ + {"field": "name", "fieldName": "名称", "dataType": "varchar", "required": 1, "sourceType": 1}, + {"field": "code", "fieldName": "编码", "dataType": "varchar", "required": 1, "sourceType": 1}, + {"field": "type", "fieldName": "类型", "dataType": "varchar", "required": 0, "sourceType": 1}, + ], + category="806502782600217349", + action=1, +) +di.execute(insert_id, {"name": "测试", "code": "TEST001", "type": "1"}) + +# 清理 +di.safe_delete(query_id) +di.safe_delete(insert_id) +``` + +### 注意事项 + +- `get_list()` **必须传 category 参数**,否则返回空列表 +- 创建 payload 中 **isPostPosition 必须为 0**(否则 Preview NPE) +- SQL 中的 `{参数名}` 会被替换为 `?`,**不能包含 `{}` 空字面量** +- action=1(增删改)返回 data=[],这是正常行为 +- 多租户环境下 `dbLinkId=0` 连接主库,部分表可能不在主库中(参见 troubleshooting.md) + +## 门户管理 - PortalAPI + +**类名:** `PortalAPI` +**核心前缀:** `/api/visualdev/Portal` +**管理前缀:** `/api/system/PortalManage` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/visualdev/Portal` | 门户列表 | +| `get_info(portal_id)` | GET | `/api/visualdev/Portal/{id}` | 门户信息 | +| `create(data)` | POST | `/api/visualdev/Portal` | 新建门户 | +| `update(data)` | PUT | `/api/visualdev/Portal/{id}` | 修改门户 | +| `delete(portal_id)` | DELETE | `/api/visualdev/Portal/{id}` | 删除门户 | +| `copy(portal_id)` | POST | `/api/visualdev/Portal/{id}/Actions/Copy` | 复制门户 | +| `export_portal(portal_id)` | POST | `/api/visualdev/Portal/{id}/Actions/Export` | 导出门户 | +| `get_selector(type_, system_id)` | GET | `/api/visualdev/Portal/Selector` | 门户下拉框 | +| `release(portal_id, data)` | PUT | `/api/visualdev/Portal/Actions/release/{id}` | 发布门户 | +| `get_manage_list(data)` | GET | `/api/system/PortalManage/list/{systemId}` | 门户管理列表 | +| `get_manage_info(manage_id)` | GET | `/api/system/PortalManage/{id}` | 门户管理详情 | + +## 消息公告 - MessageAPI + +**类名:** `MessageAPI` +**公告前缀:** `/api/message/Notice` +**消息前缀:** `/api/message` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_notice_list(data)` | POST | `/api/message/Notice/List` | 公告列表 | +| `create_notice(data)` | POST | `/api/message/Notice` | 新建公告 | +| `update_notice(data)` | PUT | `/api/message/Notice/{id}` | 修改公告 | +| `get_notice_info(notice_id)` | GET | `/api/message/Notice/{id}` | 公告详情 | +| `delete_notice(notice_id)` | DELETE | `/api/message/Notice/{id}` | 删除公告 | +| `release_notice(notice_id)` | PUT | `/api/message/Notice/{id}/Actions/Release` | 发布公告 | +| `get_message_list(data)` | GET | `/api/message` | 消息列表 | +| `read_all(data)` | POST | `/api/message/Actions/ReadAll` | 全部已读 | +| `read_info(msg_id)` | GET | `/api/message/ReadInfo/{id}` | 查看消息 | +| `delete_message(data)` | DELETE | `/api/message/Record` | 删除消息 | + +## 数据源 - DataSourceAPI + +**类名:** `DataSourceAPI` +**连接前缀:** `/api/system/DataSource` +**同步前缀:** `/api/system/DataSync` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/system/DataSource` | 连接列表 | +| `get_selector(type_)` | GET | `/api/system/DataSource/Selector` | 连接下拉框 | +| `create(data)` | POST | `/api/system/DataSource` | 新建连接 | +| `update(data)` | PUT | `/api/system/DataSource/{id}` | 修改连接 | +| `get_info(ds_id)` | GET | `/api/system/DataSource/{id}` | 连接信息 | +| `delete(ds_id)` | DELETE | `/api/system/DataSource/{id}` | 删除连接 | +| `test_connection(data)` | POST | `/api/system/DataSource/Actions/Test` | 测试连接 | +| `data_sync(data)` | POST | `/api/system/DataSync` | 同步校验 | +| `execute(data)` | POST | `/api/system/DataSync/Actions/Execute` | 同步数据 | +| `batch_execute(data)` | POST | `/api/system/DataSync/Actions/batchExecute` | 批量同步 | +| `check_db_link(data)` | POST | `/api/system/DataSync/Actions/checkDbLink` | 校验连接 | + +### 扩展方法(ssw-common) + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `create_db_link(full_name, service_name, db_type="MySQL", description="")` | POST | `/api/common/dblinkExt/create` | 创建数据源(使用系统默认配置) | +| `get_db_link_id(en_code)` | GET | `/api/common/dblinkExt/id/{en_code}` | 获取数据源ID | +| `test_connection_ext(db_type, host, port, user_name, password, service_name)` | POST | `/api/common/dblinkExt/test` | 测试数据库连接 | +| `create_database(db_name, db_type="MySQL")` | POST | `/api/common/dblinkExt/createDatabase` | 创建数据库(使用系统默认配置) | + +## 打印模板 - PrintDevAPI + +**类名:** `PrintDevAPI` +**URL 前缀:** `/api/system/printDev` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/system/printDev` | 模板列表 | +| `get_selector()` | GET | `/api/system/printDev/Selector` | 模板下拉框 | +| `create(data)` | POST | `/api/system/printDev` | 新建模板 | +| `update(data)` | PUT | `/api/system/printDev/{id}` | 修改模板 | +| `get_info(pd_id)` | GET | `/api/system/printDev/{id}` | 模板信息 | +| `delete(pd_id)` | DELETE | `/api/system/printDev/{id}` | 删除模板 | +| `copy(pd_id)` | POST | `/api/system/printDev/{id}/Actions/Copy` | 复制模板 | +| `get_preview(pd_id)` | GET | `/api/system/printDev/{id}/Actions/Preview` | 打印预览 | +| `save_version(data)` | POST | `/api/system/printDev/Save` | 修改设计 | +| `get_version_info(version_id)` | GET | `/api/system/printDev/Info/{id}` | 设计详情 | +| `get_version_list(pd_id)` | GET | `/api/system/printDev/Version/{id}` | 版本列表 | + +## Univer 报表 - ReportAPI + +**类名:** `ReportAPI` +**URL 前缀:** `/api/Report` +**注意:** 使用 `use_report_client=True`(报表独立服务) + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_list(data)` | GET | `/api/Report` | 报表列表 | +| `create(data)` | POST | `/api/Report` | 新建报表 | +| `update(data)` | PUT | `/api/Report/{id}` | 修改报表 | +| `get_info(report_id)` | GET | `/api/Report/{id}` | 报表信息 | +| `delete(report_id)` | DELETE | `/api/Report/{id}` | 删除报表 | +| `copy(report_id)` | POST | `/api/Report/{id}/Actions/Copy` | 复制报表 | +| `get_data(data)` | POST | `/api/Report/Data` | 获取数据 | +| `save_version(data)` | POST | `/api/Report/Save` | 修改设计 | +| `get_version_list(report_id)` | GET | `/api/Report/Version/{id}` | 版本列表 | +| `get_selector()` | GET | `/api/Report/Selector` | 报表下拉框 | +| `get_preview_design(report_id, data)` | POST | `/api/Report/data/{id}/preview` | 预览设计 | + +## 系统配置 - SysConfigAPI + +**类名:** `SysConfigAPI` +**URL 前缀:** `/api/system/SysConfig` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_config()` | GET | `/api/system/SysConfig` | 获取配置 | +| `update(data)` | PUT | `/api/system/SysConfig` | 更新配置 | +| `test_qy(data, type_)` | POST | `/api/system/SysConfig/{type}/testQyWebChatConnect` | 测试企微 | +| `test_ding(data)` | POST | `/api/system/SysConfig/testDingTalkConnect` | 测试钉钉 | +| `get_admin_list()` | GET | `/api/system/SysConfig/getAdminList` | 系统管理员 | +| `set_admin_list(data)` | PUT | `/api/system/SysConfig/setAdminList` | 设置管理员 | +| `get_socials_config()` | GET | `/api/system/SysConfig/socials` | 第三方配置 | +| `syn_organize_to_ding(type_, dept_id)` | GET | `/api/system/SynThirdInfo/synAllOrganizeSysToDing` | 同步组织到钉钉 | +| `syn_user_to_ding(type_, dept_id)` | GET | `/api/system/SynThirdInfo/synAllUserSysToDing` | 同步用户到钉钉 | +| `syn_organize_to_qy(type_, dept_id)` | GET | `/api/system/SynThirdInfo/synAllOrganizeSysToQy` | 同步组织到企微 | +| `syn_user_to_qy(type_, dept_id)` | GET | `/api/system/SynThirdInfo/synAllUserSysToQy` | 同步用户到企微 | + +## 文件管理 - FileAPI + +**类名:** `FileAPI` +**文档前缀:** `/api/file/Document` + +| 方法 | HTTP | URL | 说明 | +|------|------|-----|------| +| `get_download_url(file_type, file_name)` | GET | `/api/file/Download/{type}/{name}` | 下载链接 | +| `get_pack_download_url(file_type, data)` | POST | `/api/file/PackDownload/{type}` | 打包下载 | +| `preview(data)` | GET | `/api/file/Uploader/Preview` | 预览文件 | +| `chunk_merge(data)` | POST | `/api/file/merge` | 分片组装 | +| `get_all_list(data)` | GET | `/api/file/Document` | 文档列表 | +| `create_folder(data)` | POST | `/api/file/Document` | 添加文件夹 | +| `update(data)` | PUT | `/api/file/Document/{id}` | 修改文件名 | +| `batch_delete(ids)` | POST | `/api/file/Document/BatchDelete` | 批量删除 | +| `get_folder_tree(ids)` | POST | `/api/file/Document/FolderTree` | 文件夹树 | +| `get_info(doc_id)` | GET | `/api/file/Document/{id}` | 文件信息 | +| `move_to(to_id, ids)` | PUT | `/api/file/Document/Actions/MoveTo/{id}` | 批量移动 | +| `create_share(ids, user_ids)` | POST | `/api/file/Document/Actions/Share` | 批量分享 | +| `get_share_out_list(data)` | GET | `/api/file/Document/Share` | 我的共享 | +| `get_share_tome_list(data)` | GET | `/api/file/Document/ShareTome` | 共享给我 | +| `get_trash_list(data)` | GET | `/api/file/Document/Trash` | 回收站 | +| `trash_recovery(ids)` | POST | `/api/file/Document/Trash/Actions/Recovery` | 还原 | +| `pack_download(ids)` | POST | `/api/file/Document/PackDownload` | 批量下载 | diff --git a/docs/code-rule.md b/docs/code-rule.md new file mode 100644 index 0000000..63da34c --- /dev/null +++ b/docs/code-rule.md @@ -0,0 +1,228 @@ +尚数网企业代码结构 +### 2. 代码结构 + +**后端**(Java Spring Boot): + +``` +{backend_code_path}/ +└── {company_code}-{app_code}/ # 父模块 + ├── pom.xml + ├── {company_code}-{app_code}-entity/ # Entity 模块 + │ └── src/main/java/{company_code}/{app_code}/ + │ ├── entity/ + │ │ └── {ModelName}Entity.java + │ └── model/ + │ ├── {ModelName}Form.java + │ ├── {ModelName}Pagination.java + │ └── {ModelName}ExcelVO.java + ├── {company_code}-{app_code}-biz/ # Biz 模块 + │ └── src/main/java/ + │ ├── {company_code}/{app_code}/ + │ │ ├── service/ + │ │ │ ├── I{ModelName}Service.java + │ │ │ └── impl/{ModelName}ServiceImpl.java + │ └── jnpf/mapper/ # 固定包名 + │ └── {ModelName}Mapper.java + └── {company_code}-{app_code}-controller/ # Controller 模块 + └── src/main/java/{company_code}/{app_code}/ + └── controller/ + └── {ModelName}Controller.java +``` + +> **示例**:当 `company_code=ssw`, `app_code=ais` 时,模块为 `ssw-ais`,包名为 `ssw.ais.*` + +**前端**(Vue 3): + +``` +{frontend_views_path}/{app_code}/{model_name}/ +├── index.vue # 列表页 +├── Form.vue # 表单页 +├── Detail.vue # 详情页 +└── helper/ + ├── api.ts # API 调用 + ├── columnList.ts # 列配置 + └── searchList.ts # 搜索配置 +``` + +## 命名规范 + +### 数据库命名 +| 类型 | 规则 | 示例 | +|------|------|------| +| 业务表名 | `{business_name}`(snake_case,无前缀) | `images` | +| 平台表名 | `{base_name}`(base_ 前缀不变) | `base_user` | + +> **注意**:业务库已按系统名隔离,业务表用 snake_case,不加前缀,不用字符分割。 +> 平台表(base_*)保持原样不变。 + +### Java 类命名 +| 类型 | 规则 | 示例 | +|------|------|------| +| Entity | `{BusinessName}Entity`(PascalCase) | `ImagesEntity` | +| Controller | `{BusinessName}Controller` | `ImagesController` | +| Service | `{BusinessName}Service` | `ImagesService` | +| ServiceImpl | `{BusinessName}ServiceImpl` | `ImagesServiceImpl` | +| Mapper | `{BusinessName}Mapper` | `ImagesMapper` | +| Form | `{BusinessName}Form` | `ImagesForm` | +| VO | `{BusinessName}VO` / `{BusinessName}ListVO` | `ImagesVO` | + +> **注意**:类名只使用业务名(PascalCase),不加 app_code 前缀,避免重复 + +### Java 属性命名(字段) +| 类型 | 规则 | 示例 | +|------|------|------| +| 业务字段 | `{FieldName}`(PascalCase) | `private String name;` | +| 主键 | `Id`(PascalCase) | `private String id;` | +| 创建相关 | `CreateUser` / `CreateTime` 等 | `private String createUser;` | + +> **说明**:Java 类属性名使用 PascalCase(与数据库 f_snake_case 字段名通过 MyBatis-Plus 自动映射) + +### 包名规则 + +| 类型 | 包名规则 | 说明 | +|------|----------|------| +| Entity | `{company_code}.{app_code}.entity` | 数据库实体 | +| Model | `{company_code}.{app_code}.model` | BO/VO 对象 | +| Mapper | `jnpf.mapper` | 固定包名 | +| Service | `{company_code}.{app_code}.service` | 业务接口 | +| Controller | `{company_code}.{app_code}.controller` | REST 接口 | + +**变量对应关系**: +| 变量 | 值 | 示例 | +|------|-----|------| +| `company_code` | 企业代码 | `ssw` | +| `app_code` | 系统英文名 | `ais` | +| `businessName` | 业务名(PascalCase) | `Images` | +| `business_name` | 业务名(snake_case) | `images` | + +**示例**: +- `company_code=ssw`, `app_code=ais`, `businessName=Images` +- 数据库表:`images` +- Java 类:`ImagesEntity`, `ImagesController`, `ImagesService` +- Java 属性(Entity 字段):`name`, `fullName`, `createUser` +- 包名:`ssw.ais.entity.ImagesEntity` +- API 路径:`/api/ssw/ais/images` + +## API 路径规则 + +| 类型 | 路径规则 | 示例 | +|------|----------|------| +| 后端 Controller | `/api/{company_code}/{app_code}/{BusinessName}` | `/api/ssw/ais/Images` | +| 前端 API | `/api/{app_code}/{enCode}` | `/api/ais/images` | + +**说明**: +- 后端 Controller 使用完整路径 `{company_code}/{app_code}/{BusinessName}` +- 前端调用后端 API 时使用 `{app_code}/{enCode}`(App-Code 自动追加) + +## POM 依赖规则 + +**父模块** (`{company_code}-{app_code}/pom.xml`): +```xml + + com.jnpf + boot + 6.2.0-RELEASE + +{company_code}-{app_code} +pom + + {company_code}-{app_code}-entity + {company_code}-{app_code}-biz + {company_code}-{app_code}-controller + +``` + +**Entity 模块** (`{company_code}-{app_code}-entity/pom.xml`): +```xml + + {company_code}-{app_code} + com.jnpf + 6.2.0-RELEASE + +{company_code}-{app_code}-entity + + + + com.jnpf + jnpf-common-all + + + com.jnpf + jnpf-generater-base + + +``` + +**Biz 模块** (`{company_code}-{app_code}-biz/pom.xml`): +```xml + + {company_code}-{app_code} + com.jnpf + 6.2.0-RELEASE + +{company_code}-{app_code}-biz + + + + com.jnpf + {company_code}-{app_code}-entity + + + com.alibaba + fastjson + + + org.apache.commons + commons-lang3 + 3.12.0 + + + com.jnpf + jnpf-common-all + + +``` + +**Controller 模块** (`{company_code}-{app_code}-controller/pom.xml`): +```xml + + {company_code}-{app_code} + com.jnpf + 6.2.0-RELEASE + +{company_code}-{app_code}-controller + + + + com.jnpf + {company_code}-{app_code}-biz + + + com.jnpf + jnpf-common-all + + +``` + +### 依赖层级图 + +``` +Controller ({company_code}-{app_code}-controller) + └── Biz ({company_code}-{app_code}-biz) + ├── Entity ({company_code}-{app_code}-entity) + │ ├── jnpf-common-all + │ └── jnpf-generater-base + ├── fastjson + ├── commons-lang3 (3.12.0) + └── jnpf-common-all + └── jnpf-common-all +``` + +### 关键依赖说明 + +| Artifact ID | 说明 | +|-------------|------| +| `jnpf-common-all` | JNPF 公共模块,所有层级都需要 | +| `jnpf-generater-base` | 代码生成基础模块,仅 Entity 层需要 | +| `fastjson` | JSON 处理,仅 Biz 层需要 | +| `commons-lang3` | 工具类库,仅 Biz 层需要 | diff --git a/docs/codedev/01-backend-pattern.md b/docs/codedev/01-backend-pattern.md new file mode 100644 index 0000000..2c2ad81 --- /dev/null +++ b/docs/codedev/01-backend-pattern.md @@ -0,0 +1,461 @@ +# 后端扩展开发模式 + +> 基于 jnpf-extend 模块的 Controller → Service → Mapper → Entity 分层架构 +> 源码分析时间:2026-04-01 + +--- + +## 一、目录结构 + +``` +jnpf-extend/ +├── jnpf-extend-controller/ # 控制层 +│ └── src/main/java/jnpf/controller/{Xxx}Controller.java +├── jnpf-extend-biz/ # 业务层 +│ ├── src/main/java/jnpf/service/{Xxx}Service.java # 接口 +│ ├── src/main/java/jnpf/service/impl/{Xxx}ServiceImpl.java +│ └── src/main/java/jnpf/mapper/{Xxx}Mapper.java +└── jnpf-extend-entity/ # 实体层 + ├── src/main/java/jnpf/entity/{Xxx}Entity.java + └── src/main/java/jnpf/model/{module}/*{VO,Form}.java +``` + +--- + +## 二、Entity 层 + +### 2.1 实体类模板 + +```java +package jnpf.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import jnpf.base.entity.SuperExtendEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import java.math.BigDecimal; +import java.util.Date; + +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("Xxx") // 表名:PascalCase 无前缀 +public class XxxEntity extends SuperExtendEntity { + + @TableField("f_fieldName") + private String fieldName; + + @TableField("f_amount") + private BigDecimal amount; // 金额用 BigDecimal + + @TableField("f_createTime") + private Date createTime; +} +``` + +### 2.2 命名规范 + +| 类型 | 规范 | 示例 | +|------|------|------| +| 表名 | PascalCase 无前缀 | `TableExample` | +| 字段 | `f_` 前缀 + PascalCase | `f_projectName` | +| Java字段 | 驼峰命名 | `projectName` | + +### 2.3 主键策略 + +- 主键类型:`String` (UUID) +- 主键生成:`RandomUtil.uuId()` +- 排序码:`RandomUtil.parses()` + +### 2.4 审计字段 + +继承 `SuperExtendEntity` 自动获得: +- `creatorTime` / `creatorUserId` - 创建人 +- `lastModifyTime` / `lastModifyUserId` - 修改人 +- `sortCode` - 排序码 +- `deleteMark` - 删除标记 + +--- + +## 三、Mapper 层 + +### 3.1 Mapper 接口模板 + +```java +package jnpf.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import jnpf.base.mapper.SuperMapper; +import jnpf.entity.XxxEntity; +import jnpf.model.PaginationXxx; +import jnpf.util.RandomUtil; +import jnpf.util.UserProvider; +import org.apache.ibatis.annotations.Mapper; +import java.util.Date; + +@Mapper +public interface XxxMapper extends SuperMapper { + + // ========== CRUD ========== + + default XxxEntity getInfo(String id) { + return this.selectById(id); + } + + default void create(XxxEntity entity) { + entity.setId(RandomUtil.uuId()); + entity.setSortCode(RandomUtil.parses()); + entity.setCreatorTime(new Date()); + entity.setCreatorUserId(UserProvider.getUser().getUserId()); + this.insert(entity); + } + + default boolean update(String id, XxxEntity entity) { + entity.setId(id); + entity.setLastModifyTime(new Date()); + entity.setLastModifyUserId(UserProvider.getUser().getUserId()); + return this.updateById(entity) > 0; + } + + default void delete(XxxEntity entity) { + this.deleteById(entity.getId()); + } + + // ========== 分页查询 ========== + + default Page getList(PaginationXxx pagination) { + QueryWrapper wrapper = new QueryWrapper<>(); + + // 关键字查询 + if (!StringUtils.isEmpty(pagination.getKeyword())) { + wrapper.lambda() + .like(XxxEntity::getFieldName, pagination.getKeyword()); + } + + // 排序 + wrapper.lambda().orderByDesc(XxxEntity::getCreatorTime); + + Page page = new Page<>( + pagination.getCurrentPage(), + pagination.getPageSize() + ); + return this.selectPage(page, wrapper); + } +} +``` + +### 3.2 QueryWrapper 常用模式 + +```java +// 关键字模糊查询 +wrapper.lambda() + .like(Entity::getField, keyword) + .or() + .like(Entity::getField2, keyword); + +// 精确查询 +wrapper.lambda().eq(Entity::getField, value); + +// 范围查询 +wrapper.lambda().between(Entity::getTime, start, end); + +// IN 查询 +wrapper.lambda().in(Entity::getId, list); + +// 分页 +Page page = new Page<>(current, pageSize); +IPage result = this.selectPage(page, wrapper); +``` + +--- + +## 四、Service 层 + +### 4.1 Service 接口 + +```java +package jnpf.service; + +import jnpf.entity.XxxEntity; +import jnpf.model.PaginationXxx; +import java.util.List; + +public interface XxxService { + List getList(); + List getList(PaginationXxx pagination); + XxxEntity getInfo(String id); + void create(XxxEntity entity); + boolean update(String id, XxxEntity entity); + void delete(XxxEntity entity); +} +``` + +### 4.2 Service 实现 + +```java +package jnpf.service.impl; + +@Service +public class XxxServiceImpl extends SuperServiceImpl + implements XxxService { + + @Override + public List getList() { + return this.baseMapper.getList(); + } + + @Override + public List getList(PaginationXxx pagination) { + return this.baseMapper.getList(pagination); + } + + @Override + public XxxEntity getInfo(String id) { + return this.baseMapper.getInfo(id); + } + + @Override + public void create(XxxEntity entity) { + this.baseMapper.create(entity); + } + + @Override + public boolean update(String id, XxxEntity entity) { + return this.baseMapper.update(id, entity); + } + + @Override + public void delete(XxxEntity entity) { + this.baseMapper.delete(entity); + } +} +``` + +--- + +## 五、Controller 层 + +### 5.1 Controller 模板 + +```java +package jnpf.controller; + +@Tag(name = "功能名称", description = "Xxx") +@RestController +@RequestMapping("/api/extend/Xxx") +@RequiredArgsConstructor +public class XxxController extends SuperController { + + private final XxxService xxxService; + + // ========== CRUD ========== + + @Operation(summary = "获取列表") + @GetMapping + @SaCheckPermission("extend.xxx.list") + public ActionResult> list(PaginationXxx pagination) { + List data = xxxService.getList(pagination); + List list = JsonUtil.getJsonToList(data, XxxListVO.class); + return ActionResult.page(list, JsonUtil.getJsonToBean(pagination, PaginationVO.class)); + } + + @Operation(summary = "获取信息") + @GetMapping("/{id}") + @SaCheckPermission("extend.xxx.list") + public ActionResult info(@PathVariable("id") String id) { + XxxEntity entity = xxxService.getInfo(id); + return ActionResult.success(JsonUtil.getJsonToBean(entity, XxxInfoVO.class)); + } + + @Operation(summary = "新建") + @PostMapping + @SaCheckPermission("extend.xxx.list") + public ActionResult create(@RequestBody @Valid XxxCrForm form) { + XxxEntity entity = JsonUtil.getJsonToBean(form, XxxEntity.class); + xxxService.create(entity); + return ActionResult.success(MsgCode.SU001.get()); + } + + @Operation(summary = "更新") + @PutMapping("/{id}") + @SaCheckPermission("extend.xxx.list") + public ActionResult update(@PathVariable("id") String id, + @RequestBody @Valid XxxUpForm form) { + XxxEntity entity = JsonUtil.getJsonToBean(form, XxxEntity.class); + boolean flag = xxxService.update(id, entity); + return flag ? ActionResult.success(MsgCode.SU004.get()) + : ActionResult.fail(MsgCode.FA002.get()); + } + + @Operation(summary = "删除") + @DeleteMapping("/{id}") + @SaCheckPermission("extend.xxx.list") + public ActionResult delete(@PathVariable("id") String id) { + XxxEntity entity = xxxService.getInfo(id); + if (entity != null) { + xxxService.delete(entity); + return ActionResult.success(MsgCode.SU003.get()); + } + return ActionResult.fail(MsgCode.FA003.get()); + } +} +``` + +### 5.2 接口定义模式 + +| 操作 | 注解 | 路径 | 权限 | +|------|------|------|------| +| 列表 | `@GetMapping` | `/api/extend/Xxx` | `@SaCheckPermission` | +| 详情 | `@GetMapping("/{id}")` | `/{id}` | `@SaCheckPermission` | +| 创建 | `@PostMapping` | `/api/extend/Xxx` | `@SaCheckPermission` | +| 更新 | `@PutMapping("/{id}")` | `/{id}` | `@SaCheckPermission` | +| 删除 | `@DeleteMapping("/{id}")` | `/{id}` | `@SaCheckPermission` | + +### 5.3 参数获取方式 + +```java +@PathVariable("id") // URL 路径参数 +@RequestBody @Valid // 请求体 + JSR-303 校验 +@RequestParam("name") // 查询参数 +``` + +### 5.4 统一返回值 + +```java +ActionResult.success(vo) // 成功 +ActionResult.fail(MsgCode.XX.get()) // 失败 +ActionResult.page(list, paginationVO) // 分页 +``` + +--- + +## 六、Model 类 + +### 6.1 分页模型 + +```java +package jnpf.model; + +@Data +public class PaginationXxx extends Page { + private String keyword; // 关键字 + private String field; // 字段过滤 + // ... 业务特定字段 +} +``` + +### 6.2 VO 模型 + +```java +package jnpf.model; + +// 列表 VO +@Data +public class XxxListVO { + private String id; + private String fieldName; + // 仅包含需要返回的字段 +} + +// 详情 VO +@Data +public class XxxInfoVO { + private String id; + private String fieldName; + private BigDecimal amount; + // 包含所有字段 +} +``` + +### 6.3 Form 模型 + +```java +package jnpf.model; + +// 创建表单 +@Data +public class XxxCrForm { + @NotBlank(message = "字段不能为空") + private String fieldName; +} + +// 更新表单 +@Data +public class XxxUpForm { + private String fieldName; +} +``` + +--- + +## 七、导入导出模式(参考 EmployeeController) + +### 7.1 导出 Excel + +```java +@GetMapping("/ExportData") +public ActionResult exportData(PaginationXxx pagination) { + List list = xxxService.getList(pagination); + List voList = JsonUtil.getJsonToList(list, XxxExportVO.class); + + // 构建导出列 + List entitys = new ArrayList<>(); + entitys.add(new ExcelExportEntity("列名", "field")); + + ExportParams params = new ExportParams(null, "标题"); + Workbook workbook = ExcelExportUtil.exportExcel(params, entitys, voList); + + // 上传并返回 + String fileName = "导出_" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xlsx"; + // ... 上传逻辑 + return ActionResult.success(vo); +} +``` + +### 7.2 导入预览 + +```java +@GetMapping("/ImportPreview") +public ActionResult importPreview(@RequestParam("fileName") String fileName) { + // 下载文件并解析 + List list = ExcelUtil.importExcelByInputStream(inputStream, 0, 1, XxxModel.class); + return ActionResult.success(xxxService.importPreview(list)); +} +``` + +### 7.3 导入数据 + +```java +@PostMapping("/ImportData") +public ActionResult importData(@RequestBody XxxModel data) { + List list = JsonUtil.getJsonToList(data.getList(), XxxEntity.class); + // ... 处理并插入 + return ActionResult.success(result); +} +``` + +--- + +## 八、关键配置项 + +| 配置项 | 值 | +|--------|-----| +| 表名 | PascalCase 无前缀 | +| 字段前缀 | `f_` | +| 主键类型 | String (UUID) | +| 主键生成 | `RandomUtil.uuId()` | +| 审计字段 | 自动从 `SuperExtendEntity` 继承 | +| API 路径 | `/api/extend/Xxx` | +| 权限格式 | `extend.xxx.yyy` | + +--- + +## 九、参考示例 + +| 示例 | 路径 | 说明 | +|------|------|------| +| TableExample | `jnpf-extend/.../TableExample*` | 完整 CRUD + 特殊操作 | +| Employee | `jnpf-extend/.../Employee*` | 导入导出完整流程 | +| Order | `jnpf-extend/.../Order*` | 主子表结构 | +| ProjectGantt | `jnpf-extend/.../ProjectGantt*` | 树形+复杂结构 | diff --git a/docs/codedev/02-frontend-pattern.md b/docs/codedev/02-frontend-pattern.md new file mode 100644 index 0000000..471b8a7 --- /dev/null +++ b/docs/codedev/02-frontend-pattern.md @@ -0,0 +1,395 @@ +# 前端扩展开发模式 + +> 基于 views/extend 示例的 Vue 3 + TypeScript 前端开发指南 +> 源码分析时间:2026-04-01 + +--- + +## 一、前端目录结构 + +``` +web/apps/jnpf-web-apps-main/src/ +├── views/extend/ # 扩展示例 +│ ├── barCode/ # 条形码 +│ ├── importAndExport/ # 导入导出 ★ +│ ├── tableDemo/ # 表格示例 ★ +│ └── ... +└── api/extend/ # API 接口定义 + ├── employee.ts + ├── table.ts + └── ... +``` + +--- + +## 二、API 接口定义 + +### 2.1 API 文件模板 + +```typescript +// #/api/extend/xxx.ts +import { defHttp } from '#/api/request'; + +enum Api { + Prefix = '/api/extend/Xxx', // 后端接口路径 +} + +// 获取列表 +export function getXxxList(data) { + return defHttp.get({ url: Api.Prefix, data }); +} + +// 获取详情 +export function getInfo(id) { + return defHttp.get({ url: `${Api.Prefix}/${id}` }); +} + +// 创建 +export function createXxx(data) { + return defHttp.post({ url: Api.Prefix, data }); +} + +// 更新 +export function updateXxx(data: { id }) { + return defHttp.put({ url: `${Api.Prefix}/${data.id}`, data }); +} + +// 删除 +export function delXxx(id) { + return defHttp.delete({ url: `${Api.Prefix}/${id}` }); +} + +// 导出Excel +export function exportExcel(data) { + return defHttp.get({ url: `${Api.Prefix}/ExportData`, data }); +} + +// 导入预览 +export function importPreview(data) { + return defHttp.get({ url: `${Api.Prefix}/ImportPreview`, data }); +} + +// 导入数据 +export function importData(data) { + return defHttp.post({ url: `${Api.Prefix}/ImportData`, data }); +} +``` + +### 2.2 HTTP 方法对应 + +| 操作 | 前端方法 | 后端注解 | +|------|----------|----------| +| 获取列表 | `defHttp.get({ url: Prefix, data })` | `@GetMapping` | +| 获取详情 | `defHttp.get({ url: `${Prefix}/${id}` })` | `@GetMapping("/{id}")` | +| 创建 | `defHttp.post({ url: Prefix, data })` | `@PostMapping` | +| 更新 | `defHttp.put({ url: `${Prefix}/${id}`, data })` | `@PutMapping("/{id}")` | +| 删除 | `defHttp.delete({ url: `${Prefix}/${id}` })` | `@DeleteMapping("/{id}")` | + +--- + +## 三、Vue 组件模式 + +### 3.1 基础列表页面(使用 useVxeTable) + +```vue + + + +``` + +### 3.2 搜索表单配置 + +```javascript +function getFormConfig(): Partial { + return { + schemas: [ + { + field: 'field1', + label: '字段1', + component: 'Input', + componentProps: { placeholder: '请输入' } + }, + { + field: 'field2', + label: '字段2', + component: 'Select', + componentProps: { + placeholder: '请选择', + options: [ + { id: 1, fullName: '选项1' }, + { id: 2, fullName: '选项2' } + ] + } + } + ] + }; +} +``` + +### 3.3 列配置 + +```typescript +const columns: BasicColumn[] = [ + { title: '序号', dataIndex: 'index', width: 60, customRender: ({ index }) => index + 1 }, + { title: '编码', dataIndex: 'code', width: 150, fixed: 'left' }, + { title: '名称', dataIndex: 'name', minWidth: 150 }, + { title: '金额', dataIndex: 'amount', width: 120, format: 'money' }, + { title: '日期', dataIndex: 'date', width: 120, format: 'date|YYYY-MM-DD' }, + { title: '状态', dataIndex: 'status', width: 80, slots: { default: 'status' } }, + { title: '操作', dataIndex: 'action', width: 150, fixed: 'right' }, +]; +``` + +### 3.4 弹窗表单 + +```vue + + + +``` + +--- + +## 四、useVxeTable 钩子 + +### 4.1 核心方法 + +```typescript +const [registerTable, { + reload, // 刷新数据 + setColumns, // 设置列 + getSelectRows, // 获取选中行 + clearSelectedRowKeys, // 清空选择 + getFetchParams, // 获取查询参数 +}] = useVxeTable(options); +``` + +### 4.2 常用配置 + +```typescript +const options = { + api: getList, // 数据接口(必填) + columns, // 列定义(必填) + useSearchForm: true, // 是否显示搜索表单 + formConfig, // 搜索表单配置 + rowSelection: { type: 'checkbox' }, // 行选择 + pagination: { pageSize: 20 }, // 分页配置 + afterFetch: (data) => { // 数据处理钩子 + return data.map(item => ({ + ...item, + // 处理数据 + })); + }, +}; +``` + +--- + +## 五、主子表模式(参考 saleOrder) + +```vue + + + +``` + +--- + +## 六、导入导出模式(参考 importAndExport) + +### 6.1 导出组件 + +```vue + +``` + +### 6.2 导入组件 + +```vue + +``` + +--- + +## 七、常用组件 + +| 组件 | 引入 | 用途 | +|------|------|------| +| `BasicVxeTable` | `@jnpf/ui/vxeTable` | 高级表格 | +| `useVxeTable` | `@jnpf/ui/vxeTable` | 表格状态管理 | +| `TableAction` | `@jnpf/ui/vxeTable` | 表格操作按钮 | +| `BasicModal` | `@jnpf/ui/modal` | 弹窗 | +| `useModal` | `@jnpf/ui/modal` | 弹窗状态管理 | +| `useMessage` | `@jnpf/hooks` | 消息提示 | +| `usePopup` | `@jnpf/ui/popup` | 弹出页面 | +| `downloadByUrl` | `@jnpf/utils` | 文件下载 | + +--- + +## 八、关键配置 + +| 配置 | 说明 | +|------|------| +| API 路径前缀 | `/api/extend/Xxx` | +| 组件 name | `ExtendXxxDemo` | +| 表格列配置 | `BasicColumn[]` | +| 搜索表单 | `formConfig.schemas` | +| 操作按钮 | `getTableActions()` | diff --git a/docs/codedev/03-examples-index.md b/docs/codedev/03-examples-index.md new file mode 100644 index 0000000..c825c73 --- /dev/null +++ b/docs/codedev/03-examples-index.md @@ -0,0 +1,190 @@ +# 示例目录与功能对照表 + +> 基于 `views/extend` 和 `jnpf-extend` 模块的完整示例索引 +> 整理时间:2026-04-01 + +--- + +## 一、前端扩展示例 + +### 1.1 表格示例 (tableDemo) + +| 示例 | 路径 | 功能说明 | +|------|------|----------| +| 普通表格 | `tableDemo/commonTable` | 基础 CRUD 操作 | +| 树形表格 | `tableDemo/treeTable` | 树形数据展示 | +| 复杂表头 | `tableDemo/complexHeader` | 多层表头合并 | +| 合并单元格 | `tableDemo/mergeTable` | 行列合并 | +| 分组表格 | `tableDemo/groupingTable` | 数据分组 | +| 锁定表格 | `tableDemo/lockTable` | 列冻结 | +| 编辑表格 | `tableDemo/redactTable` | 行内编辑 | +| 签字表格 | `tableDemo/signTable` | 手写签字 | +| 批注表格 | `tableDemo/postilTable` | 单元格批注 | +| 扩展表格 | `tableDemo/extension` | 行政区划联动 | +| 统计表格 | `tableDemo/statisticsTable` | 数据统计 | + +**后端对应**:`TableExampleController` (`/api/extend/TableExample`) + +### 1.2 图表示例 (graphDemo) + +| 示例 | 路径 | 图表类型 | +|------|------|----------| +| 柱状图 | `graphDemo/echartsBar` | Bar | +| 折线图 | `graphDemo/echartsLine` | Line | +| 饼图 | `graphDemo/echartsPie` | Pie | +| 仪表盘 | `graphDemo/echartsGauge` | Gauge | +| 散点图 | `graphDemo/echartsScatter` | Scatter | +| 树图 | `graphDemo/echartsTree` | Tree | +| 漏斗图 | `graphDemo/echartsFunnel` | Funnel | +| K线图 | `graphDemo/echartsCandlestick` | Candlestick | +| 柱状折线混合 | `graphDemo/echartsLineBar` | Line+Bar | +| 面积图 | `graphDemo/echartsLineArea` | Line Area | + +### 1.3 表单示例 (formDemo) + +| 示例 | 路径 | 控件类型 | +|------|------|----------| +| fieldForm1 | `formDemo/fieldForm1` | 文本、数值、日期 | +| fieldForm2 | `formDemo/fieldForm2` | 下拉、树形 | +| fieldForm3 | `formDemo/fieldForm3` | 弹窗选择 | +| fieldForm4 | `formDemo/fieldForm4` | 文件上传 | +| fieldForm5 | `formDemo/fieldForm5` | 开关、复选框 | +| fieldForm6 | `formDemo/fieldForm6` | 定位、地图 | +| verifyForm | `formDemo/verifyForm` | 表单验证 | + +### 1.4 其他示例 + +| 示例 | 路径 | 功能说明 | +|------|------|----------| +| 导入导出 | `importAndExport` | Excel 导入导出 ★ | +| 订单管理 | `order` | 主从表结构 | +| 销售订单 | `saleOrder` | 复杂业务表单 ★ | +| 项目甘特图 | `projectGantt` | 甘特图组件 ★ | +| 邮件 | `email` | 邮件发送接收 ★ | +| 条形码 | `barCode` | 条形码生成 | +| 印章 | `signet` | 电子印章 | +| 手写签名 | `signature` | 手写签名 | +| 文档预览 | `documentPreview` | 多格式文档预览 | +| 地图 | `map` | 百度/高德地图 | +| 大数据 | `bigData` | 大数据量表格 | + +--- + +## 二、后端模块对照 + +### 2.1 Controller 层 + +| Controller | 路径 | 功能说明 | +|------------|------|----------| +| `TableExampleController` | `/api/extend/TableExample` | 表格 CRUD + 特殊操作 | +| `EmployeeController` | `/api/extend/Employee` | 职员管理 + 导入导出 ★ | +| `SalesOrderController` | `/api/extend/saleOrder` | 销售订单 ★ | +| `OrderController` | `/api/extend/Order` | 订单管理 | +| `ProjectGanttController` | `/api/extend/ProjectGantt` | 项目甘特图 | +| `EmailController` | `/api/extend/Email` | 邮件收发 | +| `BigDataController` | `/api/extend/BigData` | 大数据表格 | +| `BarCodeController` | `/api/extend/BarCode` | 条形码生成 | +| `DocumentPreviewController` | `/api/extend/DocumentPreview` | 文档预览 | +| `CustomerController` | `/api/extend/Customer` | 客户管理 | +| `ProductController` | `/api/extend/Product` | 产品管理 | +| `WorkLogController` | `/api/extend/WorkLog` | 工作日志 | +| `LeaveApplyController` | `/api/extend/LeaveApply` | 请假申请 | + +### 2.2 Entity 层 + +| Entity | 表名 | 说明 | +|--------|------|------| +| `TableExampleEntity` | `table_example` | 表格示例 | +| `EmployeeEntity` | `employee` | 职员信息 | +| `SalesOrderEntity` | `sales_order` | 销售订单 | +| `OrderEntity` | `order` | 订单 | +| `ProjectGanttEntity` | `project_gantt` | 项目甘特图 | +| `EmailSendEntity` | `email_send` | 邮件发送 | +| `BigDataEntity` | `big_data` | 大数据 | +| `CustomerEntity` | `customer` | 客户 | +| `ProductEntity` | `product` | 产品 | +| `WorkLogEntity` | `work_log` | 工作日志 | + +### 2.3 Service 层 + +| Service | 说明 | +|---------|------| +| `TableExampleService` | 表格 CRUD | +| `EmployeeService` | 职员 + 导入导出 | +| `SalesOrderService` | 销售订单 | +| `OrderService` | 订单 | +| `ProjectGanttService` | 甘特图 | +| `EmailSendService` | 邮件发送 | +| `BigDataService` | 大数据 | + +--- + +## 三、示例功能分类 + +### 3.1 完整流程示例 ★★★ + +| 示例 | 说明 | 关键代码位置 | +|------|------|--------------| +| **Employee** | 导入导出完整流程 | `EmployeeController` 完整导入导出 | +| **TableExample** | CRUD + 特殊操作 | `TableExampleController` 批注/行编辑 | +| **saleOrder** | 主子表 | `saleOrder/index.vue` + `SalesOrderController` | + +### 3.2 特殊功能示例 + +| 示例 | 功能 | 说明 | +|------|------|------| +| `projectGantt` | 甘特图 | 任务树 + 时间轴 | +| `email` | 邮件 | 发送/接收/配置 | +| `importAndExport` | 导入导出 | Excel/Word/PDF | +| `barCode` | 条形码 | 生成打印 | +| `documentPreview` | 文档预览 | Office/PDF/图片 | + +--- + +## 四、源码位置速查 + +### 前端 +``` +web/apps/jnpf-web-apps-main/src/ +├── views/extend/ +│ ├── importAndExport/ # 导入导出 ★ +│ │ ├── index.vue # 主页面 +│ │ ├── ImportModal.vue # 导入弹窗 +│ │ └── ExportModal.vue # 导出弹窗 +│ ├── saleOrder/ # 销售订单 ★ +│ │ ├── index.vue # 主页面 +│ │ └── Form.vue # 表单弹窗 +│ ├── tableDemo/ # 表格示例 +│ ├── projectGantt/ # 甘特图 +│ └── ... +└── api/extend/ + ├── employee.ts # 职员 API + ├── saleOrder.ts # 销售订单 API + ├── table.ts # 表格 API + └── ... +``` + +### 后端 +``` +jnpf/后端/jnpf-java-boot/jnpf-extend/ +├── jnpf-extend-controller/src/main/java/jnpf/controller/ +│ ├── EmployeeController.java # 导入导出 ★ +│ ├── TableExampleController.java # CRUD ★ +│ ├── SalesOrderController.java # 销售订单 ★ +│ └── ... +├── jnpf-extend-biz/src/main/java/jnpf/ +│ ├── service/impl/ # Service 实现 +│ └── mapper/ # Mapper +└── jnpf-extend-entity/src/main/java/jnpf/ + ├── entity/ # Entity + └── model/ # VO/Form +``` + +--- + +## 五、推荐学习路径 + +1. **入门**:TableExample → CRUD 最基础 +2. **进阶**:Employee → 导入导出完整流程 +3. **复杂**:saleOrder → 主子表操作 +4. **扩展**:projectGantt → 甘特图组件 diff --git a/docs/codedev/04-import-export.md b/docs/codedev/04-import-export.md new file mode 100644 index 0000000..4d49bb5 --- /dev/null +++ b/docs/codedev/04-import-export.md @@ -0,0 +1,431 @@ +# 导入导出实现详解 + +> 基于 EmployeeController 和 importAndExport 示例的完整导入导出流程 +> 源码分析时间:2026-04-01 + +--- + +## 一、功能概述 + +职员管理示例是最完整的导入导出参考,包含: +- Excel 导出(可选字段) +- Excel 导入(预览 + 确认) +- Word 导出 +- PDF 导出 + +--- + +## 二、前端实现 + +### 2.1 API 定义(employee.ts) + +```typescript +import { defHttp } from '#/api/request'; + +enum Api { + Prefix = '/api/extend/Employee', +} + +// 获取列表 +export function getEmployeeList(data) { + return defHttp.get({ url: Api.Prefix, data }); +} + +// 删除 +export function delEmployee(id) { + return defHttp.delete({ url: `${Api.Prefix}/${id}` }); +} + +// 导出Excel(可选字段) +export function exportExcel(data) { + return defHttp.get({ url: `${Api.Prefix}/ExportData`, data }); +} + +// 模板下载 +export function templateDownload() { + return defHttp.get({ url: `${Api.Prefix}/TemplateDownload` }); +} + +// 导入 +export function importData(data) { + return defHttp.post({ url: `${Api.Prefix}/ImportData`, data }); +} + +// 导入预览 +export function importPreview(data) { + return defHttp.get({ url: `${Api.Prefix}/ImportPreview`, data }); +} +``` + +### 2.2 导出弹窗(ExportModal.vue) + +```vue + + + +``` + +### 2.3 导入弹窗(ImportModal.vue) + +```vue + + + +``` + +### 2.4 主页面(index.vue) + +```vue + + + +``` + +--- + +## 三、后端实现 + +### 3.1 导出 Excel(可选字段) + +```java +@GetMapping("/ExportData") +public ActionResult exportExcelData(PaginationEmployee paginationEmployee) { + String dataType = paginationEmployee.getDataType(); + String selectKey = paginationEmployee.getSelectKey(); + + // 根据类型获取数据 + List entityList = "0".equals(dataType) + ? employeeService.getList(paginationEmployee) + : employeeService.getList(); + + // 构建导出数据 + List modeList = new ArrayList<>(); + for (EmployeeEntity entity : entityList) { + EmployeeModel mode = new EmployeeModel(); + mode.setEnCode(entity.getEnCode()); + mode.setFullName(entity.getFullName()); + // ... 映射字段 + modeList.add(mode); + } + + // 根据选中的字段构建导出列 + List entitys = new ArrayList<>(); + String[] splitData = selectKey.split(","); + for (String key : splitData) { + if ("enCode".equals(key)) { + entitys.add(new ExcelExportEntity("工号", "enCode")); + } + if ("fullName".equals(key)) { + entitys.add(new ExcelExportEntity("姓名", "fullName")); + } + // ... 其他字段 + } + + // 导出 + ExportParams exportParams = new ExportParams(null, "职员信息"); + exportParams.setType(ExcelType.XSSF); + Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entitys, modeList); + + // 上传文件 + String fileName = "职员信息_" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xlsx"; + MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName); + FileInfo fileInfo = FileUploadUtils.uploadFile( + new FileParameter(FileTypeConstant.TEMPORARY, fileName), multipartFile); + + // 返回 + DownloadVO vo = new DownloadVO(); + vo.setName(fileName); + vo.setUrl(UploaderUtil.uploaderFile(fileName + "#" + FileTypeConstant.TEMPORARY)); + return ActionResult.success(vo); +} +``` + +### 3.2 导入预览 + +```java +@GetMapping("/ImportPreview") +public ActionResult importPreview(@RequestParam("fileName") String fileName) { + AtomicReference> map = new AtomicReference<>(); + FileUploadUtils.downloadFile(new FileParameter(FileTypeConstant.TEMPORARY, fileName), + inputStream -> { + // 解析 Excel + List personList = ExcelUtil.importExcelByInputStream( + inputStream, 0, 1, EmployeeModel.class); + // 返回预览数据 + map.set(employeeService.importPreview(personList)); + }); + return ActionResult.success(map.get()); +} +``` + +### 3.3 导入数据 + +```java +@PostMapping("/ImportData") +public ActionResult importData(@RequestBody EmployeeModel data) { + List dataList; + if (data.isType()) { + // 跳过预览,直接导入 + ActionResult result = importPreview(data.getFileName()); + Map dataMap = (Map) result.getData(); + dataList = JsonUtil.getJsonToList(dataMap.get("dataRow"), EmployeeModel.class); + } else { + dataList = data.getList(); + } + + // 执行导入 + EmployeeImportVO result = employeeService.importData(dataList); + return ActionResult.success(result); +} +``` + +### 3.4 Service 导入逻辑 + +```java +@Override +public EmployeeImportVO importData(List dt) { + // 日期格式处理 + for (EmployeeModel model : dt) { + model.setAttendWorkTime(DateUtil.cstFormat(model.getAttendWorkTime())); + model.setBirthday(DateUtil.cstFormat(model.getBirthday())); + model.setGraduationTime(DateUtil.cstFormat(model.getGraduationTime())); + } + + List entitys = JsonUtil.getJsonToList(dt, EmployeeEntity.class); + + int sum = 0; // 成功数 + int num = 0; // 失败数 + List errList = new ArrayList<>(); + + for (EmployeeEntity entity : entitys) { + entity.setId(RandomUtil.uuId()); + entity.setCreatorUserId(UserProvider.getLoginUserId()); + entity.setCreatorTime(new Date()); + try { + this.baseMapper.insert(entity); + sum++; + } catch (Exception e) { + errList.add(entity); + num++; + } + } + + // 返回结果 + EmployeeImportVO vo = new EmployeeImportVO(); + vo.setSnum(sum); + vo.setFnum(num); + vo.setResultType(num > 0 ? 1 : 0); + if (num > 0) { + vo.setFailResult(JsonUtil.getJsonToList(errList, EmployeeModel.class)); + } + return vo; +} +``` + +--- + +## 四、关键工具类 + +| 工具类 | 用途 | +|--------|------| +| `ExcelExportUtil` | EasyPOI 导出 | +| `ExcelUtil.importExcelByInputStream` | Excel 解析 | +| `UploaderUtil.uploaderFile` | 文件上传 | +| `FileUploadUtils.uploadFile` | 文件存储 | +| `DateUtil.cstFormat` | 日期格式转换 | + +--- + +## 五、文件上传接口 + +```java +@PostMapping("/Uploader") +public ActionResult uploader() { + List list = UpUtil.getFileAll(); + MultipartFile file = list.get(0); + if (!file.isEmpty()) { + String fileName = RandomUtil.uuId() + "." + UpUtil.getFileType(file); + FileInfo fileInfo = FileUploadUtils.uploadFile( + new FileParameter(FileTypeConstant.TEMPORARY, fileName), file); + DownloadVO vo = new DownloadVO(); + vo.setName(fileInfo.getFilename()); + return ActionResult.success(vo); + } + return ActionResult.fail(MsgCode.ETD110.get()); +} +``` + +--- + +## 六、导入导出结果模型 + +```java +@Data +public class EmployeeImportVO { + private Integer snum; // 成功数量 + private Integer fnum; // 失败数量 + private Integer resultType; // 结果类型 0=全部成功, 1=部分失败 + private List failResult; // 失败数据 +} +``` + +--- + +## 七、完整流程图 + +``` +导出: +用户点击导出 → 打开导出弹窗 → 选择范围和字段 → 调用 ExportData + → Service 查询数据 → 构建 Excel → 上传文件 → 返回下载地址 + +导入: +用户点击导入 → 打开导入弹窗 → 上传文件 → 调用 Uploader + → 文件上传到临时目录 → 调用 ImportPreview → 预览数据 + → 用户确认 → 调用 ImportData → Service 批量插入 → 返回结果 +``` diff --git a/docs/codedev/05-table-operation.md b/docs/codedev/05-table-operation.md new file mode 100644 index 0000000..877cb30 --- /dev/null +++ b/docs/codedev/05-table-operation.md @@ -0,0 +1,169 @@ +# 表格操作示例 + +> 基于 TableExampleController 和 tableDemo 的 CRUD + 特殊操作 +> 源码分析时间:2026-04-01 + +--- + +## 一、功能概述 + +TableExample 是最完整的 CRUD 参考,包含: +- 基础 CRUD +- 树形表格 +- 批注功能 +- 行编辑 +- 标记功能 + +--- + +## 二、后端实现 + +### 2.1 列表查询 + +```java +@GetMapping +@SaCheckPermission("extend.tableDemo.commonTable") +public ActionResult> list(PaginationTableExample pagination) { + List data = tableExampleService.getList(pagination); + List list = JsonUtil.getJsonToList(data, TableExampleListVO.class); + + // 处理用户信息 + List userIds = list.stream().map(TableExampleListVO::getRegistrant).collect(Collectors.toList()); + List userList = userService.getUserName(userIds); + for (TableExampleListVO vo : list) { + UserEntity user = userList.stream() + .filter(t -> t.getId().equals(vo.getRegistrant())) + .findFirst().orElse(null); + vo.setRegistrant(user != null ? user.getRealName() + "/" + user.getAccount() : ""); + } + + return ActionResult.page(list, JsonUtil.getJsonToBean(pagination, PaginationVO.class)); +} +``` + +### 2.2 创建 + +```java +@PostMapping +@SaCheckPermission("extend.tableDemo.commonTable") +public ActionResult create(@RequestBody @Valid TableExampleCrForm form) { + TableExampleEntity entity = JsonUtil.getJsonToBean(form, TableExampleEntity.class); + + // 默认值处理 + entity.setCostAmount(entity.getCostAmount() == null ? new BigDecimal("0") : entity.getCostAmount()); + entity.setSign("0000000"); // 标记初始化 + + tableExampleService.create(entity); + return ActionResult.success(MsgCode.SU001.get()); +} +``` + +### 2.3 批注功能 + +```java +// 发送批注 +@PostMapping("/{id}/Postil") +public ActionResult sendPostil(@PathVariable("id") String id, @RequestBody PostilSendForm form) { + TableExampleEntity entity = tableExampleService.getInfo(id); + + // 构建批注 + PostilModel model = new PostilModel(); + model.setCreatorTime(DateUtil.getNow("+8")); + model.setText(form.getText()); + model.setUserId(UserProvider.getUser().getUserName() + "/" + UserProvider.getUser().getUserAccount()); + + List list = new ArrayList<>(); + list.add(model); + + // 合并已有批注 + if (!StringUtil.isEmpty(entity.getPostilJson())) { + list.addAll(JsonUtil.getJsonToList(entity.getPostilJson(), PostilModel.class)); + } + + entity.setPostilJson(JsonUtil.getObjectToString(list)); + entity.setPostilCount(list.size()); + tableExampleService.update(id, entity); + + return ActionResult.success(MsgCode.SU012.get()); +} + +// 获取批注 +@GetMapping("/{id}/Actions/Postil") +public ActionResult getPostil(@PathVariable("id") String id) { + TableExampleEntity entity = tableExampleService.getInfo(id); + PostilInfoVO vo = new PostilInfoVO(); + vo.setPostilJson(entity.getPostilJson()); + return ActionResult.success(vo); +} +``` + +### 2.4 行编辑 + +```java +@PutMapping("/{id}/Actions/RowsEdit") +public ActionResult rowEditing(@PathVariable("id") String id, @RequestBody @Valid TableExampleRowUpForm form) { + TableExampleEntity entity = JsonUtil.getJsonToBean(form, TableExampleEntity.class); + + // 默认值处理 + entity.setCostAmount(entity.getCostAmount() == null ? new BigDecimal("0") : entity.getCostAmount()); + entity.setId(id); + + boolean flag = tableExampleService.rowEditing(entity); + return flag ? ActionResult.success(MsgCode.SU004.get()) : ActionResult.fail(MsgCode.FA002.get()); +} +``` + +--- + +## 三、Mapper 查询模式 + +```java +// 关键字模糊查询 +default List getList(String keyword) { + QueryWrapper wrapper = new QueryWrapper<>(); + if (!StringUtils.isEmpty(keyword)) { + wrapper.lambda() + .and(t -> t.like(Entity::getCustomerName, keyword) + .or().like(Entity::getProjectName, keyword)); + } + wrapper.lambda().orderByDesc(Entity::getRegisterDate); + return this.selectList(wrapper); +} + +// 标签查询 +default List getList(Pagination pagination) { + QueryWrapper wrapper = new QueryWrapper<>(); + String sign = pagination.getFSign(); + if (!StringUtils.isEmpty(sign)) { + String[] arraySign = sign.split(","); + for (int i = 0; i < arraySign.length; i++) { + String item = arraySign[i]; + if (i == 0) { + wrapper.lambda().like(Entity::getProjectCode, item); + } else { + wrapper.lambda().or(t -> t.like(Entity::getProjectCode, item)); + } + } + } + // 排序 + if (StringUtils.isEmpty(pagination.getSidx())) { + wrapper.lambda().orderByDesc(Entity::getRegisterDate); + } else { + wrapper.lambda().orderByDesc(pagination.getSidx()); + } + return this.selectList(wrapper); +} +``` + +--- + +## 四、参考文件 + +| 文件 | 说明 | +|------|------| +| `TableExampleController.java` | 完整 CRUD + 批注/行编辑 | +| `TableExampleMapper.java` | QueryWrapper 查询模式 | +| `TableExampleServiceImpl.java` | 业务逻辑 | +| `tableDemo/commonTable` | 基础列表 | +| `tableDemo/postilTable` | 批注表格 | +| `tableDemo/redactTable` | 行编辑表格 | diff --git a/docs/codedev/06-chart-examples.md b/docs/codedev/06-chart-examples.md new file mode 100644 index 0000000..8d074e2 --- /dev/null +++ b/docs/codedev/06-chart-examples.md @@ -0,0 +1,203 @@ +# 图表示例 + +> 基于 graphDemo 的 ECharts 图表实现 +> 源码分析时间:2026-04-01 + +--- + +## 一、图表类型 + +| 类型 | 路径 | ECharts 类型 | +|------|------|-------------| +| 柱状图 | `graphDemo/echartsBar` | Bar | +| 折线图 | `graphDemo/echartsLine` | Line | +| 饼图 | `graphDemo/echartsPie` | Pie | +| 仪表盘 | `graphDemo/echartsGauge` | Gauge | +| 散点图 | `graphDemo/echartsScatter` | Scatter | +| 树图 | `graphDemo/echartsTree` | Tree | +| 漏斗图 | `graphDemo/echartsFunnel` | Funnel | +| K线图 | `graphDemo/echartsCandlestick` | Candlestick | +| 柱状折线混合 | `graphDemo/echartsLineBar` | Line + Bar | +| 面积图 | `graphDemo/echartsLineArea` | Line Area | + +--- + +## 二、柱状图示例 + +```vue + + + +``` + +--- + +## 三、饼图示例 + +```vue + +``` + +--- + +## 四、仪表盘示例 + +```vue + +``` + +--- + +## 五、通用配置 + +### 5.1 响应式处理 + +```vue + +``` + +### 5.2 常用主题 + +```javascript +// 暗色主题 +import { use } from 'echarts/core'; +import { DARK_THEME } from 'echarts/themes/dark'; + +use(DARK_THEME); +``` + +--- + +## 六、源码位置 + +| 文件 | 说明 | +|------|------| +| `graphDemo/echartsBar/index.vue` | 柱状图 | +| `graphDemo/echartsPie/index.vue` | 饼图 | +| `graphDemo/echartsGauge/index.vue` | 仪表盘 | +| `graphDemo/echartsLine/index.vue` | 折线图 | diff --git a/docs/codedev/07-form-examples.md b/docs/codedev/07-form-examples.md new file mode 100644 index 0000000..3731aea --- /dev/null +++ b/docs/codedev/07-form-examples.md @@ -0,0 +1,189 @@ +# 表单控件示例 + +> 基于 formDemo 的 Vue 3 表单控件使用指南 +> 源码分析时间:2026-04-01 + +--- + +## 一、表单控件类型 + +| 示例 | 路径 | 控件类型 | +|------|------|----------| +| fieldForm1 | `formDemo/fieldForm1` | 文本、数值、日期 | +| fieldForm2 | `formDemo/fieldForm2` | 下拉、树形 | +| fieldForm3 | `formDemo/fieldForm3` | 弹窗选择 | +| fieldForm4 | `formDemo/fieldForm4` | 文件上传 | +| fieldForm5 | `formDemo/fieldForm5` | 开关、复选框 | +| fieldForm6 | `formDemo/fieldForm6` | 定位、地图 | +| verifyForm | `formDemo/verifyForm` | 表单验证 | + +--- + +## 二、文本输入 + +```vue + + + + + + + +``` + +--- + +## 三、数值输入 + +```vue + + + + + + + + + + +``` + +--- + +## 四、日期选择 + +```vue + + + + + + + + + + + +``` + +--- + +## 五、下拉选择 + +```vue + + 选项1 + 选项2 + + + + + 选项1 + +``` + +--- + +## 六、文件上传 + +```vue + + + 点击上传 + + + + +``` + +--- + +## 七、开关和复选框 + +```vue + + + + +同意协议 + + + + 读书 + 运动 + 旅游 + +``` + +--- + +## 八、表单验证 + +```vue + + + + + + + +``` + +--- + +## 九、表单布局 + +```vue + + 分组标题 + + + + + + + +``` + +--- + +## 十、参考文件 + +| 文件 | 说明 | +|------|------| +| `formDemo/fieldForm1` | 文本、数值、日期 | +| `formDemo/fieldForm2` | 下拉、树形 | +| `formDemo/verifyForm` | 表单验证 | diff --git a/docs/codedev/08-special-features.md b/docs/codedev/08-special-features.md new file mode 100644 index 0000000..4beabf8 --- /dev/null +++ b/docs/codedev/08-special-features.md @@ -0,0 +1,289 @@ +# 特殊功能示例 + +> 甘特图、订单、邮件等复杂业务功能 +> 源码分析时间:2026-04-01 + +--- + +## 一、销售订单(saleOrder) + +### 1.1 功能特点 + +- 主子表结构(订单 + 明细) +- 右侧产品选择弹窗 +- 订单状态管理 + +### 1.2 前端实现 + +```vue + + + +``` + +### 1.3 后端 API + +```typescript +// saleOrder.ts +export function getOrderList(data) { + return defHttp.get({ url: '/api/extend/saleOrder/Product', data }); +} +export function getProductEntry(id) { + return defHttp.get({ url: `/api/extend/saleOrder/Product/ProductEntry/${id}` }); +} +``` + +--- + +## 二、项目甘特图(projectGantt) + +### 2.1 功能特点 + +- 树形任务结构 +- 甘特图时间轴 +- 任务依赖关系 + +### 2.2 前端组件 + +``` +projectGantt/ +├── index.vue # 主页面 +├── Task.vue # 任务组件 +├── TaskForm.vue # 任务表单 +└── Form.vue # 甘特图配置 +``` + +### 2.3 后端 Controller + +```java +// ProjectGanttController +@GetMapping +public ActionResult> list() { } + +@GetMapping("/{id}") +public ActionResult info(@PathVariable("id") String id) { } + +@PostMapping +public ActionResult create(@RequestBody @Valid ProjectGanttCrForm form) { } + +@PutMapping("/{id}") +public ActionResult update(@PathVariable("id") String id, @RequestBody ProjectGanttUpForm form) { } +``` + +--- + +## 三、邮件功能(email) + +### 3.1 功能模块 + +- 邮件发送(EmailSend) +- 邮件接收(EmailReceive) +- 邮件配置(EmailConfig) + +### 3.2 前端结构 + +``` +email/ +├── index.vue # 邮件列表 +├── Form.vue # 发送表单 +├── Detail.vue # 邮件详情 +├── Config.vue # 配置页面 +├── DetailPage.vue # 详情页面 +└── DetailMain.vue # 详情主体 +``` + +### 3.3 后端 Controller + +```java +// EmailController +@GetMapping +public ActionResult list() { } + +@PostMapping +public ActionResult create(@RequestBody EmailSendEntity entity) { } + +@GetMapping("/{id}") +public ActionResult info(@PathVariable("id") String id) { } +``` + +--- + +## 四、大数据表格(bigData) + +### 4.1 特点 + +- 虚拟滚动 +- 分页加载 +- 大量数据处理 + +### 4.2 实现参考 + +```vue + +``` + +--- + +## 五、条形码(barCode) + +### 5.1 前端实现 + +```vue + + + +``` + +### 5.2 后端 Controller + +```java +@GetMapping("/{content}") +public ActionResult generate(@PathVariable("content") String content) { + // 返回条形码图片 +} +``` + +--- + +## 六、文档预览(documentPreview) + +### 6.1 支持格式 + +- PDF +- Office 文档(Word、Excel、PPT) +- 图片 +- 文本文件 + +### 6.2 实现方式 + +```vue + +``` + +--- + +## 七、源码位置 + +| 功能 | 前端路径 | 后端 Controller | +|------|----------|-----------------| +| 销售订单 | `saleOrder/` | `SalesOrderController` | +| 项目甘特图 | `projectGantt/` | `ProjectGanttController` | +| 邮件 | `email/` | `EmailController` | +| 大数据 | `bigData/` | `BigDataController` | +| 条形码 | `barCode/` | `BarCodeController` | +| 文档预览 | `documentPreview/` | `DocumentPreviewController` | + +--- + +## 八、主子表开发模板 + +### 8.1 前端主子表 + +```vue + + + +``` + +### 8.2 后端主子表 + +```java +// 主表查询 +@GetMapping +public ActionResult list(Pagination pagination) { + List list = mainService.getList(pagination); + return ActionResult.page(list, pagination); +} + +// 子表查询 +@GetMapping("/{id}/Entries") +public ActionResult> getEntries(@PathVariable("id") String id) { + List list = subService.getListByMainId(id); + return ActionResult.success(list); +} +``` diff --git a/docs/codedev/09-quick-start.md b/docs/codedev/09-quick-start.md new file mode 100644 index 0000000..2a56ce9 --- /dev/null +++ b/docs/codedev/09-quick-start.md @@ -0,0 +1,250 @@ +# 快速开发模板 + +> 基于 JNPF 扩展开发的完整代码模板 +> 整理时间:2026-04-01 + +--- + +## 一、后端快速模板 + +### 1.1 Entity + +```java +package jnpf.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import jnpf.base.entity.SuperExtendEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import java.math.BigDecimal; + +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("Xxx") +public class XxxEntity extends SuperExtendEntity { + + @TableField("f_name") + private String name; + + @TableField("f_amount") + private BigDecimal amount; +} +``` + +### 1.2 Mapper + +```java +package jnpf.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import jnpf.base.mapper.SuperMapper; +import jnpf.entity.XxxEntity; +import jnpf.util.RandomUtil; +import jnpf.util.UserProvider; +import org.apache.ibatis.annotations.Mapper; +import java.util.Date; + +@Mapper +public interface XxxMapper extends SuperMapper { + + default XxxEntity getInfo(String id) { + return this.selectById(id); + } + + default void create(XxxEntity entity) { + entity.setId(RandomUtil.uuId()); + entity.setSortCode(RandomUtil.parses()); + entity.setCreatorTime(new Date()); + entity.setCreatorUserId(UserProvider.getUser().getUserId()); + this.insert(entity); + } + + default boolean update(String id, XxxEntity entity) { + entity.setId(id); + entity.setLastModifyTime(new Date()); + entity.setLastModifyUserId(UserProvider.getUser().getUserId()); + return this.updateById(entity) > 0; + } + + default void delete(XxxEntity entity) { + this.deleteById(entity.getId()); + } +} +``` + +### 1.3 Service + +```java +// 接口 +package jnpf.service; +public interface XxxService {} +// 实现 +package jnpf.service.impl; +@Service +public class XxxServiceImpl extends SuperServiceImpl implements XxxService {} +``` + +### 1.4 Controller + +```java +package jnpf.controller; + +@Tag(name = "功能名称", description = "Xxx") +@RestController +@RequestMapping("/api/extend/Xxx") +@RequiredArgsConstructor +public class XxxController extends SuperController { + + private final XxxService xxxService; + + @Operation(summary = "列表") + @GetMapping + @SaCheckPermission("extend.xxx.list") + public ActionResult> list(PaginationXxx pagination) { + List data = xxxService.getList(pagination); + return ActionResult.page(JsonUtil.getJsonToList(data, XxxListVO.class), + JsonUtil.getJsonToBean(pagination, PaginationVO.class)); + } + + @Operation(summary = "详情") + @GetMapping("/{id}") + public ActionResult info(@PathVariable("id") String id) { + return ActionResult.success(JsonUtil.getJsonToBean(xxxService.getInfo(id), XxxInfoVO.class)); + } + + @Operation(summary = "新建") + @PostMapping + public ActionResult create(@RequestBody @Valid XxxCrForm form) { + xxxService.create(JsonUtil.getJsonToBean(form, XxxEntity.class)); + return ActionResult.success(MsgCode.SU001.get()); + } + + @Operation(summary = "更新") + @PutMapping("/{id}") + public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid XxxUpForm form) { + boolean flag = xxxService.update(id, JsonUtil.getJsonToBean(form, XxxEntity.class)); + return flag ? ActionResult.success(MsgCode.SU004.get()) : ActionResult.fail(MsgCode.FA002.get()); + } + + @Operation(summary = "删除") + @DeleteMapping("/{id}") + public ActionResult delete(@PathVariable("id") String id) { + XxxEntity entity = xxxService.getInfo(id); + if (entity != null) { + xxxService.delete(entity); + return ActionResult.success(MsgCode.SU003.get()); + } + return ActionResult.fail(MsgCode.FA003.get()); + } +} +``` + +--- + +## 二、前端快速模板 + +### 2.1 API + +```typescript +// #/api/extend/xxx.ts +import { defHttp } from '#/api/request'; + +enum Api { Prefix = '/api/extend/Xxx' } + +export const getXxxList = (data) => defHttp.get({ url: Api.Prefix, data }); +export const getInfo = (id) => defHttp.get({ url: `${Api.Prefix}/${id}` }); +export const createXxx = (data) => defHttp.post({ url: Api.Prefix, data }); +export const updateXxx = (data) => defHttp.put({ url: `${Api.Prefix}/${data.id}`, data }); +export const delXxx = (id) => defHttp.delete({ url: `${Api.Prefix}/${id}` }); +``` + +### 2.2 列表页面 + +```vue + + + +``` + +--- + +## 三、数据库表结构 + +```sql +CREATE TABLE Xxx ( + f_id VARCHAR(50) PRIMARY KEY, + f_name VARCHAR(100) COMMENT '名称', + f_amount DECIMAL(18,2) COMMENT '金额', + f_sortCode INT COMMENT '排序码', + f_creatorTime DATETIME COMMENT '创建时间', + f_creatorUser VARCHAR(50) COMMENT '创建人', + f_modifyTime DATETIME COMMENT '修改时间', + f_modifyUser VARCHAR(50) COMMENT '修改人', + f_deleteMark INT DEFAULT 0 COMMENT '删除标记' +); +``` + +--- + +## 四、关键配置清单 + +| 项目 | 配置 | +|------|------| +| 表名 | `Xxx` | +| 字段前缀 | `f_` | +| 主键 | `f_id` VARCHAR(50) | +| Controller 路径 | `/api/extend/Xxx` | +| 权限标识 | `extend.xxx.list` | +| 主键生成 | `RandomUtil.uuId()` | +| 审计字段 | 自动继承 | + +--- + +## 五、参考示例 + +| 示例 | 路径 | 用途 | +|------|------|------| +| Employee | `EmployeeController` | 导入导出 | +| TableExample | `TableExampleController` | CRUD | +| saleOrder | `saleOrder/` | 主子表 | +| projectGantt | `projectGantt/` | 甘特图 | diff --git a/docs/codedev/README.md b/docs/codedev/README.md new file mode 100644 index 0000000..3640a8c --- /dev/null +++ b/docs/codedev/README.md @@ -0,0 +1,180 @@ +# JNPF 扩展开发文档 (codedev) + +> 基于 JNPF 平台扩展模块(jnpf-extend)的系统性开发指南 +> 整理时间:2026-04-01 + +--- + +## 文档结构 + +| 文档 | 说明 | +|------|------| +| **[README.md](README.md)** | 本文档,速查与索引 | +| **[01-backend-pattern.md](01-backend-pattern.md)** | 后端扩展开发模式(Controller/Service/Mapper/Entity) | +| **[02-frontend-pattern.md](02-frontend-pattern.md)** | 前端扩展开发模式(Vue 组件/API 调用) | +| **[03-examples-index.md](03-examples-index.md)** | 示例目录与功能对照表 | +| **[04-import-export.md](04-import-export.md)** | 导入导出实现(Employee 示例) | +| **[05-table-operation.md](05-table-operation.md)** | 表格操作示例(TableExample 示例) | +| **[06-chart-examples.md](06-chart-examples.md)** | 图表示例(ECharts) | +| **[07-form-examples.md](07-form-examples.md)** | 表单控件示例 | +| **[08-special-features.md](08-special-features.md)** | 特殊功能(甘特图、订单、邮件等) | +| **[09-quick-start.md](09-quick-start.md)** | 快速开发模板 | + +--- + +## VisualDev vs codedev 适用场景 + +**优先使用 VisualDev(低代码表单)**:通用 CRUD、表单+列表、简单审批流程、数据管理 + +**必须使用 codedev(扩展开发)**: +- 复杂业务逻辑(多个外部 API 调用、数据转换) +- 自定义算法(统计、分析、调度) +- 非标准交互(特殊控件、复杂验证规则) +- 性能敏感操作(批量处理、大数据量操作) +- 需要直接操作数据库的场景 +- 需要调用第三方服务的场景 + +**典型选择**: +| 场景 | 推荐方式 | +|------|----------| +| 通用表单+列表 | VisualDev | +| 简单审批流程 | VisualDev + workflow | +| 复杂表单(多步骤、联动计算) | codedev | +| 图表分析页面 | codedev | +| 导入导出(复杂格式) | codedev | +| 定时任务/批处理 | codedev | + +--- + +## 核心规则速查 + +### 后端命名规范 + +| 类型 | 规范 | 示例 | +|------|------|------| +| 表名 | PascalCase 无前缀 | `TableExample` | +| 字段 | `f_` 前缀 + PascalCase | `f_projectName` | +| Java字段 | 驼峰命名 | `projectName` | +| Controller路径 | `/api/extend/Xxx` | `/api/extend/Employee` | +| 权限标识 | `extend.xxx.yyy` | `extend.tableDemo.commonTable` | +| 主键 | String (UUID) | `RandomUtil.uuId()` | + +### 前端命名规范 + +| 类型 | 规范 | 示例 | +|------|------|------| +| API文件 | `#/api/extend/xxx` | `#/api/extend/employee` | +| 组件路径 | `views/extend/xxx` | `views/extend/importAndExport` | +| 组件name | `ExtendXxx` | `ExtendImportAndExport` | + +### 关键 API 路径 + +| 功能 | 路径 | 方法 | +|------|------|------| +| 列表 | `/api/extend/Xxx` | GET | +| 详情 | `/api/extend/Xxx/{id}` | GET | +| 创建 | `/api/extend/Xxx` | POST | +| 更新 | `/api/extend/Xxx/{id}` | PUT | +| 删除 | `/api/extend/Xxx/{id}` | DELETE | +| 导出 | `/api/extend/Xxx/ExportData` | GET | +| 导入预览 | `/api/extend/Xxx/ImportPreview` | GET | +| 导入数据 | `/api/extend/Xxx/ImportData` | POST | + +--- + +## 源码位置索引 + +### 前端示例 +``` +web/apps/jnpf-web-apps-main/src/views/extend/ +├── barCode/ # 条形码 +├── bigData/ # 大数据表格 +├── documentPreview/ # 文档预览 +├── email/ # 邮件发送 +├── formDemo/ # 表单控件(6种) +├── graphDemo/ # 图表(10种ECharts) +├── importAndExport/ # 导入导出 ★ +├── map/ # 地图 +├── order/ # 订单管理 +├── projectGantt/ # 项目甘特图 +├── saleOrder/ # 销售订单 +├── signature/ # 手写签名 +├── signet/ # 印章 +└── tableDemo/ # 表格控件(10种) ★ +``` + +### 前端 API +``` +前端/.../src/api/extend/ +├── employee.ts # 职员管理(含导入导出) +├── table.ts # 表格示例 +├── saleOrder.ts # 销售订单 +├── order.ts # 订单 +├── email.ts # 邮件 +├── bigData.ts # 大数据 +├── documentPreview.ts # 文档预览 +└── projectGantt.ts # 项目甘特图 +``` + +### 后端模块 +``` +jnpf/后端/jnpf-java-boot/jnpf-extend/ +├── jnpf-extend-controller/ # Controller 层 +│ └── jnpf/controller/*.java +├── jnpf-extend-biz/ # Service + Mapper 层 +│ ├── jnpf/service/impl/*.java +│ └── jnpf/mapper/*.java +└── jnpf-extend-entity/ # Entity + Model 层 + ├── jnpf/entity/*.java + └── jnpf/model/**/*.java +``` + +--- + +## 示例功能对照表 + +| 示例 | 前端入口 | 后端Controller | 关键功能 | +|------|----------|----------------|----------| +| 职员管理 | importAndExport | EmployeeController | 导入导出Excel/Word/PDF | +| 表格示例 | tableDemo/* | TableExampleController | CRUD、树形、批注、行编辑 | +| 销售订单 | saleOrder | SalesOrderController | 主子表、明细表 | +| 项目甘特图 | projectGantt | ProjectGanttController | 甘特图、任务管理 | +| 邮件 | email | EmailController | 发送、接收、配置 | +| 大数据 | bigData | BigDataController | 分页、大数据量 | +| 条形码 | barCode | BarCodeController | 条形码生成 | +| 文档预览 | documentPreview | DocumentPreviewController | 多格式文档预览 | + +--- + +## 开发流程 + +### 1. 后端开发 +``` +1. 创建 Entity (jnpf-extend-entity) +2. 创建 Mapper (jnpf-extend-biz) +3. 创建 Service 接口 + 实现 +4. 创建 Controller +5. 添加权限配置 +``` + +### 2. 前端开发 +``` +1. 创建 API 文件 (#/api/extend/xxx) +2. 创建 Vue 组件 (views/extend/xxx) +3. 使用 useVxeTable 或 BasicVxeTable +4. 注册到菜单系统 +``` + +### 3. 完整示例参考 +- 职员管理(importAndExport):导入导出完整流程 +- 表格示例(tableDemo):CRUD + 特殊操作 +- 销售订单(saleOrder):主子表操作 + +--- + +## 相关文档 + +- [AIBridge API 参考](../../api-reference.md) +- [表单开发指南](../form-development/) +- [工作流开发指南](../workflow/) +- [平台机制](../platform-guide.md) diff --git a/docs/control/01-quick-ref.md b/docs/control/01-quick-ref.md new file mode 100644 index 0000000..2100c93 --- /dev/null +++ b/docs/control/01-quick-ref.md @@ -0,0 +1,218 @@ +# JNPF 控件快速使用速查 + +## 目录结构 + +本文档集包含以下内容: + +| 文档 | 说明 | +|------|------| +| 01-quick-ref.md | 本文档,控件快速使用速查 | +| 02-input-controls.md | 输入类控件 | +| 03-select-controls.md | 选择类控件 | +| 04-date-controls.md | 日期时间控件 | +| 05-upload-controls.md | 上传控件 | +| 06-popup-controls.md | 弹窗控件 | +| 07-table-controls.md | 子表格控件 | +| 08-special-controls.md | 特殊控件 | +| 09-chart-controls.md | 图表控件 | +| 10-table-patterns.md | 表格高级模式 | +| 11-form-patterns.md | 表单高级模式 | +| 13-mobile-controls.md | 移动端控件 | +| 12-examples/workSystem-examples.md | workSystem 示例索引 | +| 12-examples/extend-examples.md | extend 代码示例索引 | + +--- + +## 控件速查表 + +### 输入类控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 单行文本 | `input` | placeholder, showPassword | **字符串直接存储** | `build_field_model(..., jnpf_key="input")` | +| 多行文本 | `textarea` | rows, maxlength | **字符串直接存储**(含换行) | `build_field_model(..., jnpf_key="textarea")` | +| 数字输入 | `inputNumber` | step, controls, min, max | **数值或字符串存储**(取决于 precision 配置) | `build_field_model(..., jnpf_key="inputNumber")` | + +### 选择类控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 下拉选择 | `select` | multiple, options (格式: {fullName, id}) | **选项id字符串存储**(单选如"2",多选格式为JSON数组) | `build_field_model(..., jnpf_key="select", options=[...])` | +| 单选组 | `radio` | options | **选项id字符串存储**(如"1") | `build_field_model(..., jnpf_key="radio", options=[...])` | +| 多选组 | `checkbox` | options | **选项id数组JSON序列化存储**(如`["1","3"]`) | `build_field_model(..., jnpf_key="checkbox", options=[...])` | +| 级联选择 | `cascader` | options | **节点id数组JSON序列化存储**(如`["44","4403","440305"]`) | `build_field_model(..., jnpf_key="cascader", options=[...])` | +| 树形选择 | `treeSelect` | options | **节点id字符串存储**(如"1-1") | `build_field_model(..., jnpf_key="treeSelect", options=[...])` | +| 组织选择 | `organizeSelect` | - | **组织id字符串存储** | AIBridge 无封装,需手动配置 | +| 用户选择 | `userSelect` | - | **用户名字符串存储**(如"admin"),非用户ID | AIBridge 无封装,需手动配置 | + +### 日期时间控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 日期选择 | `datePicker` | format: "yyyy-MM-dd" | **日期字符串存储**(如"2026-04-07")或时间戳 | `build_field_model(..., jnpf_key="datePicker")` | +| 时间选择 | `timePicker` | format: "HH:mm:ss" | **时间字符串存储**(如"14:30:00") | `build_field_model(..., jnpf_key="timePicker")` | + +### 上传控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 图片上传 | `uploadImg` | multiple, maxCount | **文件路径字符串存储**:`"/upload/20260407/test.jpg"` | `build_field_model(..., jnpf_key="uploadImg")` | +| 文件上传 | `uploadFile` | multiple, maxCount | **文件路径字符串存储**:`"/upload/20260407/test.pdf"` | `build_field_model(..., jnpf_key="uploadFile")` | + +### 弹窗控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 弹窗表格 | `popupTable` | modelId, relationField | **关联记录id字符串存储** | 需两阶段创建 | +| 弹窗选择 | `popupSelect` | - | **选中记录id** | workSystem #33 | +| 弹窗属性 | `popupAttr` | - | **JSON对象存储** | workSystem #33 | +| 关联表单 | `relationForm` | modelId, relationField | **关联记录id字符串存储** | 需两阶段创建 | +| 关联流程 | `relationFlow` | - | **流程实例id** | - | + +### 特殊控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | AIBridge builder | +|------|---------|----------|-------------|------------------| +| 开关 | `switch` | activeValue, inactiveValue | **字符串存储**(activeValue/inactiveValue 转字符串存储,如"1"/"0",数据库 varchar(255)) | `build_field_model(..., jnpf_key="switch")` | +| 评分 | `rate` | max, allowHalf | **decimal(38,1) 存储**(如 4.0 表示4星) | `build_field_model(..., jnpf_key="rate")` | +| 滑块 | `slider` | min, max, step | **decimal(38,15) 高精度存储** | `build_field_model(..., jnpf_key="slider")` | +| 颜色选择 | `colorPicker` | - | **颜色值字符串存储**(如"#1890ff") | `build_field_model(..., jnpf_key="colorPicker")` | +| 签章 | `sign` | - | **签章图片路径** | - | + +### 布局控件 + +| 控件 | jnpfKey | 关键配置 | 数据存储规律 | +|------|---------|----------|-------------| +| 分隔线 | `divider` | - | 不存储数据 | +| 分组标题 | `groupTitle` | - | 不存储数据 | +| 轮播 | `carousel` | - | 不存储数据 | +| 页签 | `tab` | - | 不存储数据 | +| 二维码 | `qrcode` | - | **字符串存储**(二维码内容) | +| 条形码 | `barcode` | - | **字符串存储**(条形码内容) | +| 单据规则 | `billRule` | - | **字符串存储**(自动生成的编号) | +| 计算 | `calculate` | - | **数值存储**(计算结果) | +| 地址选择 | `address` | - | **纯文本字符串存储**(如"广东省东莞市万江区家达能大厦74B"),非 JSON 对象 | + +### 系统控件 + +| 控件 | jnpfKey | 说明 | 数据存储规律 | +|------|---------|------|-------------| +| 创建用户 | `createUser` | 自动填充当前用户 | **用户id字符串** | +| 创建时间 | `createTime` | 自动填充创建时间 | **时间戳或日期字符串** | +| 修改时间 | `modifyTime` | 自动填充修改时间 | **时间戳或日期字符串** | +| 当前组织 | `currOrganize` | 自动填充当前组织 | **组织id字符串** | +| 区域选择 | `areaSelect` | 省市区选择 | **省市区JSON数组** | + +--- + +## AIBridge 快速使用 + +### 基础文本输入 +```python +from aibridge.builders.field_model import build_field_model + +field = build_field_model( + field_name="客户名称", + field_vmodel="f_customer_name", + jnpf_key="input", + required=True +) +``` + +### 下拉选择 (注意 options 格式) +```python +field = build_field_model( + field_name="客户状态", + field_vmodel="f_customer_status", + jnpf_key="select", + required=True, + options=[ + {"fullName": "潜在客户", "id": "1"}, + {"fullName": "正式客户", "id": "2"}, + {"fullName": "流失客户", "id": "3"}, + ] +) +``` + +### 日期选择 +```python +field = build_field_model( + field_name="下单日期", + field_vmodel="f_order_date", + jnpf_key="datePicker", + required=True +) +``` + +### 子表格 +```python +from aibridge.builders.field_model import build_table_field_model + +table = build_table_field_model( + label="订单明细", + vmodel="f_order_detail_list", + child_table_name="ord_order_detail", + children=[ + build_field_model("商品名称", "f_product_name", "input"), + build_field_model("数量", "f_quantity", "inputNumber"), + build_field_model("单价", "f_unit_price", "inputNumber"), + ], + render_key=0, + show_summary=True, + summary_field="f_amount" +) +``` + +### 移动端表单配置 +```python +from aibridge.builders.mobile_field_model import build_mobile_field, build_mobile_column_data +import json + +# 构建单个移动端字段 +mobile_field = build_mobile_field( + field_name="客户名称", + field_vmodel="f_customer_name", + jnpf_key="input", + required=True +) + +# 批量构建移动端 columnData(可赋值给 f_app_column_data) +fields = [ + {"fieldName": "客户名称", "field": "f_customer_name", "jnpfKey": "input", "required": True}, + {"fieldName": "状态", "field": "f_status", "jnpfKey": "select", "options": [{"fullName": "启用", "id": "1"}]}, +] +column_data = build_mobile_column_data(fields) +# 输出 JSON 字符串供 f_app_column_data 使用 +print(json.dumps(column_data)) +``` + +--- + +## 常见错误 + +| 错误 | 原因 | 解决 | +|------|------|------| +| 下拉选择不显示选项 | options 格式错误 | 必须使用 `{fullName, id}` 格式,不是 `{label, value}` | +| 日期选择无值 | valueFormat 与 format 不匹配 | valueFormat 应等于 format(如 `"yyyy-MM-dd"`),非 `"timestamp"` | +| 开关状态不生效 | activeValue/inactiveValue 类型错误 | 应为数值 `1/0`,非布尔 `True/False` | +| relationForm 无法弹出 | modelId 未设置 | 需要两阶段创建,先创建表单获取 ID,再填充 modelId | +| 子表格提交失败 | isSubTable 属性缺失 | 子表格字段必须设置 `is_sub_table=True` | + +--- + +## workSystem 示例索引 + +| 表单名称 | 表单ID | 包含的控件 | +|----------|--------|----------| +| 信贷信息 | 797473600809468485 | input, inputNumber | +| 油耗计算 | 797460178185224773 | input, inputNumber, select | +| 二维码条形码联动 | 797444600007492165 | input, inputNumber, qrcode | +| 跨应用访问 | 797436740041179717 | relationForm | +| 员工培训 | 624164673918337925 | datePicker, input, organizeSelect, select, textarea, userSelect | +| 入职申请 | 624163990351643525 | datePicker, divider, input, organizeSelect, textarea, userSelect | +| 数据接口字段示例 | 469500336084679173 | autoComplete, cascader, checkbox, popupAttr, popupSelect, popupTableSelect, radio, select, treeSelect | +| 复杂表头主子表 | 469496902811974149 | table, tableGrid | +| 订单示例 | 469133201755925637 | billRule, createUser, datePicker, input, inputNumber, select, tab, textarea, uploadFile, userSelect | +| 产品管理 | 469039386000943493 | billRule, createTime, createUser, groupTitle, input, inputNumber, modifyTime, select, textarea, uploadImg | + +详细示例见: [workSystem-examples.md](12-examples/workSystem-examples.md) diff --git a/docs/control/02-input-controls.md b/docs/control/02-input-controls.md new file mode 100644 index 0000000..45a46e2 --- /dev/null +++ b/docs/control/02-input-controls.md @@ -0,0 +1,296 @@ +# 输入类控件 + +## 目录 + +- [单行文本 (input)](#单行文本-input) +- [多行文本 (textarea)](#多行文本-textarea) +- [数字输入 (inputNumber)](#数字输入-inputnumber) + +--- + +## 单行文本 (input) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `input` | +| AIBridge builder | `build_field_model(..., jnpf_key="input")` | +| 源码示例 | `extend/formDemo/fieldForm1/index.vue` | +| workSystem 示例 | 几乎所有表单 | + +### 基本规则 + +1. **必填配置**: + - `field_name`: 字段中文名称 (显示在表单标签) + - `field_vmodel`: 字段 vModel 值 (对应数据库字段) + - `jnpf_key`: 必须为 `"input"` + +2. **常用配置**: + - `required`: 是否必填 (默认 False) + - `placeholder`: 占位提示文本 + - `showPassword`: 是否显示密码格式 (默认 False) + - `prefixIcon`: 输入框前缀图标 + - `suffixIcon`: 输入框后缀图标 + +### AIBridge 使用 + +```python +from aibridge.builders.field_model import build_field_model + +# 基础文本输入 +field = build_field_model( + field_name="客户名称", + field_vmodel="f_customer_name", + jnpf_key="input", + required=True +) + +# 密码输入 +password_field = build_field_model( + field_name="登录密码", + field_vmodel="f_password", + jnpf_key="input", + showPassword=True +) + +# 带前缀图标 +field_with_icon = build_field_model( + field_name="手机号码", + field_vmodel="f_mobile", + jnpf_key="input", + prefixIcon="mobile" +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 用途说明 | +|----------|--------|----------| +| 信贷信息 | 797473600809468485 | 基本信息输入 | +| 员工培训 | 624164673918337925 | 多字段表单 | +| 产品管理 | 469039386000943493 | 产品名称、编码输入 | + +### 常见错误 + +| 错误现象 | 原因 | 解决 | +|----------|------|------| +| 输入内容不保存 | vModel 与数据库字段不匹配 | 确保 `field_vmodel` 与表字段名一致 (大写 F_ 前缀) | +| 必填校验不生效 | required 未设置为 True | `build_field_model(..., required=True)` | +| placeholder 不显示 | 平台自动生成 | 如需自定义,可通过 `__config__.placeholder` 设置 | + +--- + +## 多行文本 (textarea) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `textarea` | +| AIBridge builder | `build_field_model(..., jnpf_key="textarea")` | +| 源码示例 | `extend/formDemo/fieldForm1/index.vue` | +| workSystem 示例 | 员工培训、离职申请、采购申请 等 | + +### 基本规则 + +1. **必填配置**:同 input +2. **特有配置**: + - `rows`: 显示行数 (默认 4) + - `maxlength`: 最大输入字符数 (默认无限制) + +### AIBridge 使用 + +```python +# 基础多行文本 +field = build_field_model( + field_name="备注说明", + field_vmodel="f_remark", + jnpf_key="textarea", + required=False +) + +# 指定行数和最大长度 +field = build_field_model( + field_name="详细描述", + field_vmodel="f_description", + jnpf_key="textarea", + rows=6, + maxlength=500 +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置 | +|----------|--------|------| +| 员工培训 | 624164673918337925 | textarea, required | +| 离职申请 | 623163301152424133 | textarea | +| 离职交接表 | 623417538411233285 | textarea, 较长内容 | +| 产品管理 | 469039386000943493 | 产品描述 | + +--- + +## 数字输入 (inputNumber) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `inputNumber` / `numInput` | +| AIBridge builder | `build_field_model(..., jnpf_key="inputNumber")` | +| 源码示例 | `extend/formDemo/fieldForm1/index.vue` | +| workSystem 示例 | 信贷信息、油耗计算、订单明细 等 | + +### 基本规则 + +1. **必填配置**:同 input +2. **特有配置**: + - `step`: 步进值 (默认 1) + - `controls`: 是否显示增减按钮 (默认 True) + - `min`: 最小值 (默认无限制) + - `max`: 最大值 (默认无限制) + +### AIBridge 使用 + +```python +# 基础数字输入 +field = build_field_model( + field_name="年龄", + field_vmodel="f_age", + jnpf_key="inputNumber", + required=True +) + +# 带步进和范围 +field = build_field_model( + field_name="折扣比例", + field_vmodel="f_discount_rate", + jnpf_key="inputNumber", + min=0, + max=100, + step=5 +) + +# 不显示增减按钮 +field = build_field_model( + field_name="精确数量", + field_vmodel="f_quantity", + jnpf_key="inputNumber", + controls=False +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置 | +|----------|--------|------| +| 信贷信息 | 797473600809468485 | 贷款金额 | +| 油耗计算 | 797460178185224773 | 油耗数量计算 | +| 报价信息 | 585107422926864709 | 价格输入 | +| 订单示例 | 469133201755925637 | 订单数量、单价 | + +### 金额输入特殊处理 + +金额类字段通常需要: +1. 设置 `step=0.01` 或 `step=1` +2. 设置适当的 `min` (通常为 0) +3. 可配合 `addonAfter` 显示单位 (如 "元") + +```python +# 金额输入示例 (addonAfter 需要额外配置 __config__) +field = build_field_model( + field_name="订单金额", + field_vmodel="f_order_amount", + jnpf_key="inputNumber", + min=0, + step=0.01 +) +``` + +--- + +## 输入类控件通用配置 + +### AIBridge build_field_model 完整参数 + +| 参数 | 类型 | 默认值 | 说明 | +|------|------|--------|------| +| field_name | str | 必填 | 字段中文名称 | +| field_vmodel | str | 必填 | 字段 vModel (对应数据库) | +| jnpf_key | str | "input" | 控件类型 | +| required | bool | False | 是否必填 | +| table_name | str | "base_table" | 表名 | +| render_key | int | 0 | 渲染 key | +| options | list | None | 下拉选项 (select/radio/checkbox 用) | +| dictionary_type | str | "" | 数据字典类型 | + +### 输出结构 + +```json +{ + "__config__": { + "jnpfKey": "input", + "label": "客户名称", + "showLabel": true, + "required": true, + "tableName": "ord_customer", + "renderKey": 0, + "tag": "JnpfInput", + "tagIcon": "icon-ym icon-ym-generator-input", + "layout": "colFormItem" + }, + "placeholder": "请输入客户名称", + "readonly": false, + "disabled": false, + "clearable": true, + "showPassword": false, + "style": { "width": "100%" } +} +``` + +--- + +## 数据存储规律 + +### 输入类控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 示例 | +|------|---------|---------|------| +| 单行文本 | `input` | **字符串** | `"测试文本ABC123"` | +| 多行文本 | `textarea` | **字符串**(含换行符) | `"第一行\n第二行\n第三行"` | +| 数字输入 | `inputNumber` | **数值或字符串**(取决于 precision 配置) | `12345.67` 或 `"12345.67"` | + +### 实际测试结果 + +通过 AIBridge API 实际测试结果: + +```python +# 单行文本 +test_value = "测试文本ABC123" +stored_value = "测试文本ABC123" # str = str + +# 多行文本 +test_value = "第一行\n第二行\n第三行" +stored_value = "第一行\n第二行\n第三行" # str = str(含换行) + +# 数字输入 +test_value = 12345.67 +stored_value = "12345.67" # float -> str +``` + +### 数据库字段要求 + +| 控件 | 建议字段类型 | +|------|------------| +| input | `varchar(500)` 或 `text` | +| textarea | `text` | +| inputNumber | `decimal(18,2)` 或 `varchar(50)` | + +--- + +## 下一步 + +- [选择类控件](03-select-controls.md) +- [日期时间控件](04-date-controls.md) +- [上传控件](05-upload-controls.md) diff --git a/docs/control/03-select-controls.md b/docs/control/03-select-controls.md new file mode 100644 index 0000000..8a3043d --- /dev/null +++ b/docs/control/03-select-controls.md @@ -0,0 +1,445 @@ +# 选择类控件 + +## 目录 + +- [下拉选择 (select)](#下拉选择-select) +- [单选组 (radio)](#单选组-radio) +- [多选组 (checkbox)](#多选组-checkbox) +- [级联选择 (cascader)](#级联选择-cascader) +- [树形选择 (treeSelect)](#树形选择-treeselect) +- [组织选择 (organizeSelect)](#组织选择-organizeselect) +- [用户选择 (userSelect)](#用户选择-userselect) + +--- + +## 下拉选择 (select) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `select` / `comSelect` | +| AIBridge builder | `build_field_model(..., jnpf_key="select", options=[...])` | +| 源码示例 | `extend/formDemo/fieldForm2/index.vue` | +| workSystem 示例 | 几乎所有业务表单 | + +### 基本规则 + +**关键:options 格式必须为 `{fullName, id}`,不是 `{label, value}`** + +1. **必填配置**: + - `field_name`: 字段中文名称 + - `field_vmodel`: 字段 vModel + - `jnpf_key`: `"select"` + - `options`: 选项列表 + +2. **特有配置**: + - `multiple`: 是否多选 (默认 False) + - `options`: 固定选项列表 + - `dictionary_type`: 数据字典类型 (平台数据字典) + +### AIBridge 使用 + +```python +# 固定选项 +field = build_field_model( + field_name="客户状态", + field_vmodel="f_customer_status", + jnpf_key="select", + required=True, + options=[ + {"fullName": "潜在客户", "id": "1"}, + {"fullName": "正式客户", "id": "2"}, + {"fullName": "流失客户", "id": "3"}, + ] +) + +# 多选模式 +multi_field = build_field_model( + field_name="擅长领域", + field_vmodel="f_skill_areas", + jnpf_key="select", + multiple=True, + options=[ + {"fullName": "前端开发", "id": "frontend"}, + {"fullName": "后端开发", "id": "backend"}, + {"fullName": "数据库", "id": "db"}, + ] +) + +# 使用数据字典 +dict_field = build_field_model( + field_name="所属部门", + field_vmodel="f_department", + jnpf_key="select", + dictionary_type="DepartmentType" # 平台数据字典编码 +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置 | +|----------|--------|------| +| 油耗计算 | 797460178185224773 | 计算类型选择 | +| 列表标签面板 | 585825534638818437 | 标签类型 | +| 采购申请 | 585441013829468933 | 采购类型 | +| 行政区划联动 | 469139004097359749 | 行政区划 | + +### 常见错误 + +| 错误现象 | 原因 | 解决 | +|----------|------|------| +| 下拉选项不显示 | options 格式错误 | 必须使用 `{fullName, id}`,不是 `{label, value}` | +| 多选保存失败 | multiple 未设置 | `multiple=True` | +| 数据字典选项为空 | dictionary_type 不存在 | 检查数据字典编码是否正确 | + +--- + +## 单选组 (radio) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `radio` | +| AIBridge builder | `build_field_model(..., jnpf_key="radio", options=[...])` | +| 源码示例 | `extend/formDemo/fieldForm2/index.vue` | +| workSystem 示例 | 离职申请、物资申请、隔离管控 等 | + +### 基本规则 + +1. **必填配置**:同 select +2. **特有配置**:无 multiple,其他同 select + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="性别", + field_vmodel="f_gender", + jnpf_key="radio", + required=True, + options=[ + {"fullName": "男", "id": "1"}, + {"fullName": "女", "id": "2"}, + ] +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 选项内容 | +|----------|--------|----------| +| 离职申请 | 623163301152424133 | 离职类型 | +| 物资申请 | 585436888639210245 | 物资类型 | +| 隔离管控 | 469050754464803205 | 管控类型 | +| 人才管理 | 469047177461688709 | 人才类型 | + +--- + +## 多选组 (checkbox) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `checkbox` | +| AIBridge builder | `build_field_model(..., jnpf_key="checkbox", options=[...])` | +| workSystem 示例 | 数据接口调用字段示例 (#33) | + +### 基本规则 + +同 select,但允许多选。 + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="权限范围", + field_vmodel="f_permission_scope", + jnpf_key="checkbox", + options=[ + {"fullName": "读取", "id": "read"}, + {"fullName": "写入", "id": "write"}, + {"fullName": "删除", "id": "delete"}, + {"fullName": "导出", "id": "export"}, + ] +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 数据接口字段示例 | 469500336084679173 | checkbox 多选 | + +--- + +## 级联选择 (cascader) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `cascader` | +| AIBridge builder | `build_field_model(..., jnpf_key="cascader", options=[...])` | +| workSystem 示例 | 数据接口调用字段示例 (#33) | + +### 基本规则 + +1. **options 结构**:必须包含 `children` 字段形成层级 +2. **数据格式**: +```json +[ + { + "fullName": "浙江省", + "id": "330000", + "children": [ + {"fullName": "杭州市", "id": "330100", "children": [...]} + ] + } +] +``` + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="所在区域", + field_vmodel="f_region", + jnpf_key="cascader", + options=[ + {"fullName": "浙江省", "id": "330000", "children": [ + {"fullName": "杭州市", "id": "330100"}, + {"fullName": "宁波市", "id": "330200"} + ]}, + {"fullName": "江苏省", "id": "320000", "children": [ + {"fullName": "南京市", "id": "320100"} + ]} + ] +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 数据接口调用字段示例 | 469500336084679173 | cascader 级联选择 | + +--- + +## 树形选择 (treeSelect) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `treeSelect` | +| AIBridge builder | `build_field_model(..., jnpf_key="treeSelect", options=[...])` | +| workSystem 示例 | 数据接口调用字段示例、列表树形表格 等 | + +### 基本规则 + +同 cascader,但显示为树形下拉样式。 + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="组织架构", + field_vmodel="f_organization", + jnpf_key="treeSelect", + options=[ + {"fullName": "总公司", "id": "1", "children": [ + {"fullName": "研发部", "id": "1-1"}, + {"fullName": "销售部", "id": "1-2"} + ]} + ] +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 数据接口调用字段示例 | 469500336084679173 | treeSelect | +| 列表树形表格 | 469136286624574597 | 分类树形选择 | + +--- + +## 组织选择 (organizeSelect) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `organizeSelect` | +| AIBridge builder | 无封装,需手动配置 | +| workSystem 示例 | 几乎所有人员管理表单 | + +### 基本规则 + +组织选择控件用于选择部门/组织,**AIBridge 无封装**,需要手动配置。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 员工培训 | 624164673918337925 | 培训机构选择 | +| 入职申请 | 624163990351643525 | 部门选择 | +| 离职交接表 | 623417538411233285 | 归属部门 | +| 列表行内编辑 | 585824111083652229 | 组织选择 | +| 采购申请 | 585441013829468933 | 采购部门 | +| 列表左侧树 | 585806182086608005 | 组织树 | +| 预算管理 | 469100392253286789 | 预算部门 | +| 大客户信息 | 468842471892247429 | 所属组织 | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "organizeSelect", + "label": "所属部门", + "tag": "JnpfOrganizeSelect" + }, + "placeholder": "请选择部门", + "multiple": false, + "clearable": true +} +``` + +--- + +## 用户选择 (userSelect) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `userSelect` | +| AIBridge builder | 无封装,需手动配置 | +| workSystem 示例 | 几乎所有审批/人员表单 | + +### 基本规则 + +用户选择控件用于选择系统用户,**AIBridge 无封装**。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 员工培训 | 624164673918337925 | 培训人选择 | +| 入职申请 | 624163990351643525 | 申请人 | +| 离职交接表 | 623417538411233285 | 离职人 | +| 离职员工表 | 623183958128984261 | 员工选择 | +| 员工信息 | 623163913990570181 | 信息录入 | +| 离职申请 | 623163301152424133 | 申请人 | +| 列表行内编辑 | 585824111083652229 | 负责人 | +| 采购申请 | 585441013829468933 | 申请人 | +| 物资申请 | 585436888639210245 | 申请人 | +| 付款申请 | 585398402720727621 | 付款人 | +| 订单示例 | 469133201755925637 | 创建人 | +| 采购管理 | 469106304141552773 | 采购人 | +| 出差管理 | 469066996185622917 | 出差人 | +| 设备巡检管理 | 469062048563652997 | 巡检人 | +| OKR管理 | 469059874144184709 | 负责人 | +| 用车管理 | 469040281883306373 | 用车人 | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "userSelect", + "label": "申请人", + "tag": "JnpfUserSelect" + }, + "placeholder": "请选择申请人", + "multiple": false, + "clearable": true +} +``` + +--- + +## 选择类控件对比 + +| 控件 | 多选 | 层级支持 | AIBridge | 典型用途 | +|------|------|---------|----------|----------| +| select | 支持 | 否 | 支持 | 简单下拉 | +| radio | 否 | 否 | 支持 | 二选一/有限选项 | +| checkbox | 自动多选 | 否 | 支持 | 多选权限/类别 | +| cascader | 否 | 是 | 支持 | 省市县/分类层级 | +| treeSelect | 支持 | 是 | 支持 | 组织架构/分类树 | +| organizeSelect | 支持 | 是 | 无封装 | 部门选择 | +| userSelect | 支持 | 否 | 无封装 | 用户选择 | + +--- + +--- + +## 数据存储规律 + +### 选择类控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | +|------|---------|---------|------------| +| 下拉选择(单选) | `select` | **字符串** | `"2"` | +| 下拉选择(多选) | `select` (multiple=true) | **JSON数组字符串** | `["1","3","5"]` | +| 单选组 | `radio` | **字符串** | `"1"` | +| 多选组 | `checkbox` | **JSON数组字符串** | `["1","3"]` | +| 级联选择 | `cascader` | **JSON数组字符串** | `["44","4403","440305"]` | +| 树形选择 | `treeSelect` | **字符串** | `"1-1"` 或 `"1-1-2"` | +| 组织选择 | `organizeSelect` | **字符串** | `"组织id"` | +| 用户选择 | `userSelect` | **字符串** | `"用户id"` 或 `"admin"` | + +### 重要:选项格式 + +**AIBridge 必须使用 `{fullName, id}` 格式,不是 `{label, value}`** + +```python +# 正确格式 +options = [ + {"fullName": "潜在客户", "id": "1"}, + {"fullName": "正式客户", "id": "2"}, +] + +# 错误格式(会导致选项不显示) +options = [ + {"label": "潜在客户", "value": "1"}, # 错! + {"label": "正式客户", "value": "2"}, # 错! +] +``` + +### 存储验证示例 + +```python +# 通过 AIBridge 查询数据库结果: + +# 单选 - 存储的是 id +f_gender: "1" # 存储选项的 id 值 + +# 多选 - 存储的是 JSON 数组 +f_hobbies: '["1","3"]' # 存储选项 id 的 JSON 数组 + +# 级联 - 存储的是完整路径数组 +f_region: '["44","4403","440305"]' # 省-市-区的 id 数组 +``` + +### 数据库字段要求 + +| 控件 | 建议字段类型 | +|------|------------| +| select/radio | `varchar(50)` | +| checkbox/cascader | `varchar(500)` 或 `text` | +| treeSelect | `varchar(100)` | +| userSelect/organizeSelect | `varchar(50)` | + +--- + +## 下一步 + +- [日期时间控件](04-date-controls.md) +- [上传控件](05-upload-controls.md) +- [弹窗控件](06-popup-controls.md) diff --git a/docs/control/04-date-controls.md b/docs/control/04-date-controls.md new file mode 100644 index 0000000..de81ed3 --- /dev/null +++ b/docs/control/04-date-controls.md @@ -0,0 +1,246 @@ +# 日期时间控件 + +## 目录 + +- [日期选择 (datePicker)](#日期选择-datepicker) +- [时间选择 (timePicker)](#时间选择-timepicker) + +--- + +## 日期选择 (datePicker) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `datePicker` | +| AIBridge builder | `build_field_model(..., jnpf_key="datePicker")` | +| 源码示例 | `extend/formDemo/fieldForm1/index.vue` | +| workSystem 示例 | 几乎所有业务表单 | + +### 基本规则 + +1. **必填配置**: + - `field_name`: 字段中文名称 + - `field_vmodel`: 字段 vModel + - `jnpf_key`: `"datePicker"` + +2. **特有配置**: + - `format`: 显示格式 (默认 `"yyyy-MM-dd"`) + - `valueFormat`: 值格式 (默认 `"yyyy-MM-dd"`) + +### AIBridge 使用 + +```python +# 基础日期选择 +field = build_field_model( + field_name="出生日期", + field_vmodel="f_birth_date", + jnpf_key="datePicker", + required=True +) + +# 自定义格式 (如需显示年月日) +field = build_field_model( + field_name="入职日期", + field_vmodel="f_entry_date", + jnpf_key="datePicker", + format="yyyy-MM-dd", + valueFormat="yyyy-MM-dd" +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 用途 | +|----------|--------|------| +| 员工培训 | 624164673918337925 | 培训日期 | +| 入职申请 | 624163990351643525 | 入职日期 | +| 劳动合同续签 | 623425065425305605 | 合同日期 | +| 离职交接表 | 623417538411233285 | 离职日期 | +| 离职员工表 | 623183958128984261 | 离职日期 | +| 离职申请 | 623163301152424133 | 申请日期 | +| 列表行内编辑 | 585824111083652229 | 日期编辑 | +| 多语言采购申请 | 585448937427567365 | 采购日期 | +| 采购申请 | 585441013829468933 | 申请日期 | +| 物资申请 | 585436888639210245 | 申请日期 | +| 代码对比 | 585436444760212229 | 日期字段 | +| 付款申请 | 585398402720727621 | 付款日期 | +| 套打示例 | 585384793399624261 | 制单日期 | +| 水电费用 | 585110234985398597 | 费用日期 | +| 报价信息 | 585107422926864709 | 报价日期 | +| 个人信息 | 585101489710563653 | 生日 | +| 采购合同 | 585077579715707205 | 签订日期 | +| 订单示例 | 469133201755925637 | 订单日期 | +| 预算管理 | 469100392253286789 | 预算期间 | +| 出差管理 | 469066996185622917 | 出差日期 | +| 事件管理 | 469065268790880645 | 发生日期 | +| 设备巡检管理 | 469062048563652997 | 巡检日期 | +| 核酸检测 | 469038006062344581 | 检测日期 | +| 药房管理 | 468849844170057541 | 日期字段 | +| 报名管理外链 | 468848215723140933 | 报名日期 | +| 大客户信息 | 468842471892247429 | 签约日期 | + +### 常见问题 + +| 问题 | 原因 | 解决 | +|------|------|------| +| 保存后显示时间戳 | valueFormat 不对 | 确认 `valueFormat: "yyyy-MM-dd"` | +| 日期显示 NaN | format 不匹配 | 确认 `format: "yyyy-MM-dd"` | + +--- + +## 时间选择 (timePicker) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `timePicker` | +| AIBridge builder | `build_field_model(..., jnpf_key="timePicker")` | + +### 基本规则 + +1. **特有配置**: + - `format`: 显示格式 (默认 `"HH:mm:ss"`) + - `valueFormat`: 值格式 (默认 `"HH:mm:ss"`) + +### AIBridge 使用 + +```python +# 时间选择 +field = build_field_model( + field_name="上班时间", + field_vmodel="f_work_start_time", + jnpf_key="timePicker" +) + +# 范围时间 (需两个字段) +start_time = build_field_model( + field_name="开始时间", + field_vmodel="f_start_time", + jnpf_key="timePicker" +) +end_time = build_field_model( + field_name="结束时间", + field_vmodel="f_end_time", + jnpf_key="timePicker" +) +``` + +--- + +## 日期相关高级控件 + +### 移动端特有 + +| 控件 | jnpfKey | 说明 | +|------|---------|------| +| DateRange | dateRange | 日期范围选择 | +| TimeRange | timeRange | 时间范围选择 | +| NumberRange | numberRange | 数字范围 | + +### 计算类 + +| 控件 | jnpfKey | 说明 | workSystem 示例 | +|------|---------|------|-----------------| +| DateCalculate | dateCalculate | 日期计算 | - | +| Calculate | calculate | 通用计算 | 水电费用 (#25), 采购合同 (#28) | + +--- + +## 通用配置说明 + +### format 和 valueFormat + +```python +# 常见格式组合 + +# 1. 标准日期 (最常用) +field = build_field_model( + field_name="日期", + field_vmodel="f_date", + jnpf_key="datePicker", + format="yyyy-MM-dd", + valueFormat="yyyy-MM-dd" +) + +# 2. 仅时间 +field = build_field_model( + field_name="时间", + field_vmodel="f_time", + jnpf_key="timePicker", + format="HH:mm:ss", + valueFormat="HH:mm:ss" +) +``` + +### format 格式字符串 + +| 格式 | 说明 | 示例 | +|------|------|------| +| yyyy | 4位年份 | 2024 | +| MM | 2位月份 | 01-12 | +| dd | 2位日期 | 01-31 | +| HH | 24小时 | 00-23 | +| mm | 分钟 | 00-59 | +| ss | 秒 | 00-59 | + +### valueFormat 选项 + +| 值 | 说明 | +|-----|------| +| `yyyy-MM-dd` | 日期字符串 (默认) | +| `yyyy-MM-dd HH:mm:ss` | 完整时间字符串 | +| `timestamp` | 毫秒时间戳 | + +--- + +## 数据存储规律 + +### 日期时间控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | 说明 | +|------|---------|---------|------------|------| +| 日期选择 | `datePicker` | **字符串** | `"2026-04-07"` | 取决于 valueFormat 配置 | +| 时间选择 | `timePicker` | **字符串** | `"14:30:00"` | 固定字符串格式 | + +### valueFormat 配置说明 + +| valueFormat | 存储示例 | 说明 | +|-------------|---------|------| +| `yyyy-MM-dd` | `"2026-04-07"` | 日期字符串 (默认) | +| `yyyy-MM-dd HH:mm:ss` | `"2026-04-07 14:30:00"` | 完整时间字符串 | +| `timestamp` | `1744051200000` | 毫秒时间戳(13位) | + +### format vs valueFormat + +- **format**: 控制前端显示格式(用户看到的) +- **valueFormat**: 控制数据存储格式(提交到数据库的) + +```python +# 显示日期,存储日期字符串 +field = build_field_model( + field_name="日期", + field_vmodel="f_date", + jnpf_key="datePicker", + format="yyyy-MM-dd", + valueFormat="yyyy-MM-dd" +) +``` + +### 数据库字段要求 + +| 控件 | 建议字段类型 | 说明 | +|------|------------|------| +| datePicker | `varchar(20)` | 如 "2026-04-07" | +| datePicker (时间戳) | `bigint` | 毫秒时间戳 | +| timePicker | `varchar(10)` | 如 "14:30:00" | + +--- + +## 下一步 + +- [上传控件](05-upload-controls.md) +- [弹窗控件](06-popup-controls.md) +- [子表格控件](07-table-controls.md) diff --git a/docs/control/05-upload-controls.md b/docs/control/05-upload-controls.md new file mode 100644 index 0000000..9692404 --- /dev/null +++ b/docs/control/05-upload-controls.md @@ -0,0 +1,265 @@ +# 上传控件 + +## 目录 + +- [图片上传 (uploadImg)](#图片上传-uploadimg) +- [文件上传 (uploadFile)](#文件上传-uploadfile) +- [移动端特有上传控件](#移动端特有上传控件) + +--- + +## 图片上传 (uploadImg) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `uploadImg` | +| AIBridge builder | `build_field_model(..., jnpf_key="uploadImg")` | +| workSystem 示例 | 纵向卡片表格、横向卡片表格、产品管理、设备巡检 等 | + +### 基本规则 + +1. **必填配置**: + - `field_name`: 字段中文名称 + - `field_vmodel`: 字段 vModel + - `jnpf_key`: `"uploadImg"` + +2. **特有配置**: + - `multiple`: 是否多选 (默认 False) + - `maxCount`: 最大上传数量 (默认无限制) + - `maxSize`: 单个文件最大大小 (MB) + +### AIBridge 使用 + +```python +# 基础图片上传 +field = build_field_model( + field_name="证件照片", + field_vmodel="f_id_card_photo", + jnpf_key="uploadImg", + required=True +) + +# 多图片上传 +multi_field = build_field_model( + field_name="产品图片", + field_vmodel="f_product_images", + jnpf_key="uploadImg", + multiple=True, + maxCount=9 +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置 | +|----------|--------|------| +| 纵向卡片表格 | 797382749911515717 | uploadImg | +| 横向卡片表格 | 797381799859716677 | uploadImg | +| 产品管理 | 469039386000943493 | 产品图片 | +| 设备巡检管理 | 469062048563652997 | 巡检照片 | + +### 返回数据格式 + +图片上传后,数据库存储的是**文件路径字符串**,格式如: +``` +/upload/20260407/test.jpg +``` + +> ⚠️ **注意**:文档早期描述的 JSON 数组格式 `[{"fileId":"xxx","name":"a.jpg","url":"/files/xxx.jpg"}]` 与实际存储不符,实际存储为纯文件路径字符串。 + +--- + +## 文件上传 (uploadFile) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `uploadFile` | +| AIBridge builder | `build_field_model(..., jnpf_key="uploadFile")` | +| workSystem 示例 | 劳动合同续签、离职交接表、采购合同、订单示例 等 | + +### 基本规则 + +同 uploadImg,但上传任意文件类型。 + +### AIBridge 使用 + +```python +# 基础文件上传 +field = build_field_model( + field_name="合同附件", + field_vmodel="f_contract_attachment", + jnpf_key="uploadFile", + required=True +) + +# 多文件上传 +multi_field = build_field_model( + field_name="证明材料", + field_vmodel="f_certificates", + jnpf_key="uploadFile", + multiple=True, + maxCount=5 +) +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 用途 | +|----------|--------|------| +| 劳动合同续签 | 623425065425305605 | 合同扫描件 | +| 离职交接表 | 623417538411233285 | 交接文档 | +| 代码对比 | 585436444760212229 | 代码文件 | +| 付款申请 | 585398402720727621 | 付款凭证 | +| 套打示例 | 585384793399624261 | 附件 | +| 采购合同 | 585077579715707205 | 合同文件 | +| 订单示例 | 469133201755925637 | 附件 | +| 采购管理 | 469106304141552773 | 采购文件 | +| 事件管理 | 469065268790880645 | 事件附件 | +| 人才管理 | 469047177461688709 | 简历附件 | +| 核酸检测 | 469038006062344581 | 检测报告 | + +--- + +## 移动端特有上传控件 + +### 上传控件对比 + +| 控件 | jnpfKey | 平台 | 说明 | +|------|---------|------|------| +| uploadImg | uploadImg | PC+移动 | 图片上传 | +| uploadFile | uploadFile | PC+移动 | 文件上传 | +| UploadFileH | uploadFileH | 移动端 | H5文件上传 (跨平台) | +| UploadFileComment | uploadFileComment | 移动端 | 评论文件上传 | + +### 移动端配置 + +移动端文件上传需要额外配置 `appColumnData`,用于移动端动态表单配置。 + +```python +# 移动端图片上传配置 +field = build_field_model( + field_name="现场照片", + field_vmodel="f_scene_photos", + jnpf_key="uploadImg", + multiple=True +) +# 移动端配置需在 appColumnData 中单独设置 +``` + +--- + +## 上传控件通用配置 + +### 重要配置项 + +| 配置 | 类型 | 默认值 | 说明 | +|------|------|--------|------| +| multiple | bool | False | 是否多选 | +| maxCount | int | 无限制 | 最大文件数 | +| maxSize | int | 无限制 | 单文件最大大小(MB) | +| accept | string | 无限制 | 接受的文件类型 | +| showTip | bool | True | 是否显示提示 | +| showView | bool | True | 是否显示预览 | +| showDownload | bool | True | 是否显示下载 | + +### 文件类型限制 + +```python +# 仅允许图片 +field = build_field_model( + field_name="证件照", + field_vmodel="f_id_photo", + jnpf_key="uploadImg", + accept="image/*" +) + +# 仅允许 PDF 和 Word +field = build_field_model( + field_name="文档", + field_vmodel="f_document", + jnpf_key="uploadFile", + accept=".pdf,.doc,.docx" +) + +# 全部允许 (默认) +field = build_field_model( + field_name="附件", + field_vmodel="f_attachments", + jnpf_key="uploadFile" +) +``` + +--- + +## 常见问题 + +| 问题 | 原因 | 解决 | +|------|------|------| +| 上传后不显示 | vModel 字段类型不对 | 数据库字段类型应为 varchar(500+) | +| 多文件只保存一个 | multiple 未设置 | `multiple=True` | +| 移动端上传失败 | appColumnData 未配置 | 需在移动端单独配置 | +| 文件下载404 | 路径问题 | 检查文件服务器配置 | + +--- + +## 数据存储规律 + +### 上传控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | +|------|---------|---------|------------| +| 图片上传 | `uploadImg` | **文件路径字符串** | `"/upload/20260407/test.jpg"` | +| 文件上传 | `uploadFile` | **文件路径字符串** | `"/upload/20260407/test.pdf"` | + +### 返回数据结构 + +上传成功后,控件返回的 JSON 数组格式: + +```json +[ + { + "fileId": "文件ID", + "name": "文件名.jpg", + "url": "/files/实际路径/文件名.jpg", + "size": 12345, + "type": "image/jpeg" + } +] +``` + +### 实际测试结果 + +```python +# 未上传时,数据库存储空字符串 +f_uploadImg: '' + +# 上传后,数据库存储文件路径字符串 +f_uploadImg: '/upload/20260407/test.jpg' +``` + +> **交叉验证**:在 `datahub_banner.f_image`、`datahub_app.f_icon`、`comp_test_1775565106.f_uploadImg` 等多个表中均确认存储为文件路径字符串。 + +### 数据库字段要求 + +| 控件 | 建议字段类型 | +|------|------------| +| uploadImg | `varchar(2000)` 或 `text` | +| uploadFile | `varchar(2000)` 或 `text` | + +### 重要提示 + +1. **文件存储位置**:文件实际存储在服务器 `/files/` 目录下,数据库只存储路径信息 +2. **fileId 作用**:用于文件下载/预览时查找文件 +3. **多文件上传**:multiple=true 时,JSON 数组会包含多个文件对象 + +--- + +## 下一步 + +- [弹窗控件](06-popup-controls.md) +- [子表格控件](07-table-controls.md) +- [特殊控件](08-special-controls.md) diff --git a/docs/control/06-popup-controls.md b/docs/control/06-popup-controls.md new file mode 100644 index 0000000..b13fd3d --- /dev/null +++ b/docs/control/06-popup-controls.md @@ -0,0 +1,314 @@ +# 弹窗控件 + +## 目录 + +- [弹窗表格 (popupTable)](#弹窗表格-popuptable) +- [弹窗选择 (popupSelect)](#弹窗选择-popupselect) +- [弹窗属性 (popupAttr)](#弹窗属性-popupattr) +- [关联表单 (relationForm)](#关联表单-relationform) +- [关联流程 (relationFlow)](#关联流程-relationflow) + +--- + +## 弹窗表格 (popupTable) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `popupTable` | +| AIBridge builder | 无完整封装,需两阶段创建 | +| workSystem 示例 | 数据接口调用字段示例 (#33) | +| 复杂度 | 高 - 需要目标表单ID | + +### 基本规则 + +1. **核心概念**:弹窗表格通过弹出另一个表单的列表来选择数据 +2. **必需配置**: + - `modelId`: 目标表单的 visual_dev ID + - `relationField`: 关联字段名 +3. **其他配置**: + - `popupType`: 弹窗类型 (`"dialog"` / `"drawer"`) + - `popupTitle`: 弹窗标题 + - `popupWidth`: 弹窗宽度 + - `hasPage`: 是否分页 + - `pageSize`: 每页条数 + +### AIBridge 两阶段创建 + +**第一阶段**:创建字段(不包含 modelId) +```python +# 注意:popupTable 的 modelId 需要等目标表单创建后才能填入 +# 先创建占位字段 +field = build_field_model( + field_name="选择客户", + field_vmodel="f_customer_id", + jnpf_key="popupTable", + # modelId 暂时不填,创建目标表单后再更新 +) +``` + +**第二阶段**:更新 modelId +```python +# 假设目标客户表单 ID 为 123456789 +target_form_id = "123456789" + +# 更新字段配置,填入 modelId +field["__config__"]["modelId"] = target_form_id +field["relationField"] = "f_customer_id" # 目标表单的关联字段 +``` + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 数据接口调用字段示例 | 469500336084679173 | popupTableSelect | + +--- + +## 弹窗选择 (popupSelect) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `popupSelect` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 数据接口调用字段示例 (#33) | + +### 基本规则 + +同 popupTable,但显示为单选/多选样式。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置字段 | +|----------|--------|----------| +| 数据接口调用字段示例 | 469500336084679173 | popupSelect, popupTableSelect | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "popupSelect", + "label": "选择供应商", + "tag": "JnpfPopupSelect" + }, + "modelId": "目标表单ID", + "relationField": "f_supplier_id", + "popupType": "dialog", + "popupTitle": "选择供应商", + "popupWidth": "800px", + "multiple": false, + "hasPage": true, + "pageSize": 20 +} +``` + +--- + +## 弹窗属性 (popupAttr) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `popupAttr` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 数据接口调用字段示例 (#33) | + +### 基本规则 + +弹窗属性用于显示关联数据的详细属性,**不需要选择**。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 配置字段 | +|----------|--------|----------| +| 数据接口调用字段示例 | 469500336084679173 | popupAttr | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "popupAttr", + "label": "供应商信息", + "tag": "JnpfPopupAttr" + }, + "modelId": "目标表单ID", + "relationField": "f_supplier_id", + "popupType": "dialog", + "popupTitle": "供应商详情" +} +``` + +--- + +## 关联表单 (relationForm) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `relationForm` | +| AIBridge builder | 无完整封装 | +| workSystem 示例 | 跨应用访问 (#4) | + +### 基本规则 + +关联表单用于在当前表单中嵌入另一个表单的视图,**实现跨应用数据访问**。 + +### 关键配置 + +| 属性 | 说明 | +|------|------| +| `modelId` | 目标表单的 visual_dev ID | +| `relationField` | 显示文本字段(如 `f_name`),弹窗列表和选中后显示的文字 | +| `propsValue` | 实际主键字段(小写 `f_id`,提交时保存的值) | +| `columnOptions` | 弹窗列表的列配置,格式 `[{value, label}]`,从目标表单 `columnData` 中提取 | + +> **常见错误**: +> - 把 `relationField` 设成 ID 字段(如 `f_id`),导致弹窗只显示序号而非名称 +> - `propsValue` 误用大写字段名(如 `f_id`),实际主键应为小写 `f_id`(DataChange API 返回的数据主键字段是小写) +> - 缺少 `columnOptions`,导致弹窗列表只有序号列 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 跨应用访问 | 797436740041179717 | relationForm, 跨应用数据展示 | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "relationForm", + "label": "关联客户信息", + "tag": "JnpfRelationForm" + }, + "modelId": "目标表单ID", + "relationField": "f_name", + "propsValue": "f_id", + "columnOptions": [ + {"value": "f_name", "label": "名称"}, + {"value": "f_code", "label": "编号"} + ], + "hasPage": true, + "pageSize": 20, + "popupType": "dialog", + "popupTitle": "选择客户", + "popupWidth": "800px" +} +``` + +--- + +## 关联流程 (relationFlow) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `relationFlow` | +| AIBridge builder | 无封装 | + +### 基本规则 + +关联流程用于在表单中嵌入流程相关信息。 + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "relationFlow", + "label": "关联流程", + "tag": "JnpfRelationFlow" + }, + "flowId": "流程模板ID" +} +``` + +--- + +## 弹窗控件对比 + +| 控件 | 选择方式 | 编辑支持 | 适用场景 | AIBridge | +|------|---------|---------|----------|----------| +| popupTable | 弹窗列表选择 | 否 | 简单选择 | 需两阶段 | +| popupSelect | 弹窗下拉选择 | 否 | 单选/多选 | 无封装 | +| popupAttr | 无选择 | 是 | 仅展示详情 | 无封装 | +| relationForm | 嵌入表单 | 是 | 跨应用数据 | 无封装 | +| relationFlow | 嵌入流程 | - | 流程关联 | 无封装 | + +--- + +## 常见问题 + +| 问题 | 原因 | 解决 | +|------|------|------| +| 弹窗不弹出 | modelId 不正确 | 检查目标表单 ID | +| 数据不显示 | relationField 不匹配 | 确保字段名一致 | +| 跨应用失败 | 权限问题 | 检查目标表单权限配置 | +| 选择后不回填 | popupType 配置 | 确认 popupType 是否正确 | + +--- + +## 数据存储规律 + +### 弹窗控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | 说明 | +|------|---------|---------|------------|------| +| 弹窗表格 | `popupTable` | **字符串** | `"123456789"` | 选中记录的主键ID | +| 弹窗选择 | `popupSelect` | **字符串或JSON数组** | `"123"` 或 `["123","456"]` | 单选为ID字符串,多选为ID数组 | +| 弹窗属性 | `popupAttr` | **JSON对象字符串** | `{"id":"123","name":"供应商A",...}` | 关联记录的完整属性 | +| 关联表单 | `relationForm` | **字符串** | `"123456789"` | 选中记录的主键ID | +| 关联流程 | `relationFlow` | **字符串** | `"flow_123"` | 流程实例ID | + +### 存储详解 + +**popupTable / relationForm**: +存储的是选中记录的主键ID(f_id),用于关联查询 + +```json +// 存储值示例 +"f_customer_id": "811298790165190697" +``` + +**popupSelect 多选**: +存储的是选中记录的ID数组(JSON序列化) + +```json +// 存储值示例 +"f_product_ids": '["811298790165190697","811298790165190698"]' +``` + +**popupAttr**: +存储的是关联记录的完整JSON对象 + +```json +// 存储值示例 +"f_supplier_info": '{"id":"123","name":"供应商A","code":"SUP001","contact":"张三"}' +``` + +### 数据库字段要求 + +| 控件 | 建议字段类型 | +|------|------------| +| popupTable/relationForm | `varchar(50)` | +| popupSelect (单选) | `varchar(50)` | +| popupSelect (多选) | `varchar(500)` 或 `text` | +| popupAttr | `text` | +| relationFlow | `varchar(50)` | + +--- + +## 下一步 + +- [子表格控件](07-table-controls.md) +- [特殊控件](08-special-controls.md) +- [图表控件](09-chart-controls.md) diff --git a/docs/control/07-table-controls.md b/docs/control/07-table-controls.md new file mode 100644 index 0000000..da6b707 --- /dev/null +++ b/docs/control/07-table-controls.md @@ -0,0 +1,254 @@ +# 子表格控件 + +## 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `table` | +| AIBridge builder | `build_table_field_model()` | +| 源码示例 | `extend/tableDemo/` 多种模式 | +| workSystem 示例 | 水电费用、报价信息、个人信息、采购合同 等 | + +## 基本规则 + +### 核心概念 + +子表格是一种**嵌套表格**,用于在主表单中管理多条明细数据。 + +### 关键配置 + +| 配置 | 说明 | 必填 | +|------|------|------| +| child_table_name | 子表物理表名 | 是 | +| children | 子表字段列表 | 是 | +| show_summary | 是否显示汇总 | 否 | +| summary_field | 汇总字段 | 否 | +| addTableConf | 新增弹窗配置 | 否 | +| footerBtnsList | 底部按钮 | 否 | +| columnBtnsList | 列按钮 | 否 | + +### AIBridge 使用 + +```python +from aibridge.builders.field_model import build_table_field_model, build_field_model + +# 创建子表格 +table = build_table_field_model( + label="订单明细", + vmodel="f_order_detail_list", + child_table_name="ord_order_detail", + children=[ + build_field_model("商品名称", "f_product_name", "input"), + build_field_model("规格型号", "f_spec", "input"), + build_field_model("单位", "f_unit", "select", options=[ + {"fullName": "个", "id": "个"}, + {"fullName": "件", "id": "件"}, + {"fullName": "台", "id": "台"}, + ]), + build_field_model("数量", "f_quantity", "inputNumber"), + build_field_model("单价", "f_unit_price", "inputNumber"), + build_field_model("金额", "f_amount", "inputNumber"), # 可能用于汇总 + ], + render_key=0, + show_summary=True, # 显示汇总行 + summary_field="f_amount" # 汇总字段 +) +``` + +### 子表格字段配置 + +子表格内的字段需要额外配置: + +```python +# 子表字段会自动设置 isSubTable 属性 +# 但需要注意 parentVModel 和 relationTable +child_fields = [ + build_field_model("商品名称", "f_product_name", "input"), + build_field_model("数量", "f_quantity", "inputNumber"), +] +``` + +--- + +## workSystem 示例 + +| 表单名称 | 表单ID | 子表配置 | +|----------|--------|----------| +| 水电费用 | 585110234985398597 | calculate + table, 自动计算 | +| 报价信息 | 585107422926864709 | table, 商品明细 | +| 个人信息 | 585101489710563653 | table, 教育经历等 | +| 采购合同 | 585077579715707205 | table + calculate, 合同明细+金额计算 | +| 高级控件和默认查询 | 469499301635095045 | table, 默认查询条件 | +| 订单示例 | 469133201755925637 | table, 订单明细 | +| 采购管理 | 469106304141552773 | table + uploadFile, 采购明细+附件 | +| 客户管理 | 469102214628043141 | table, 客户联系人 | +| OKR管理 | 469059874144184709 | table, KR明细 | +| 报名管理外链 | 468848215723140933 | table, 报名信息 | +| 应收费用 | 468826463014018501 | table, 费用明细 | +| 产品管理 | 469039386000943493 | table + modifyTime, 产品明细 | + +--- + +## 高级配置 + +### 表格网格 (tableGrid) + +一种特殊的子表格布局,支持主子表头。 + +```json +{ + "__config__": { + "jnpfKey": "tableGrid", + "label": "费用明细", + "tag": "JnpfTableGrid" + }, + "children": [ + { + "title": "项目", + "children": [ + {"title": "名称", "dataIndex": "f_item_name"}, + {"title": "编码", "dataIndex": "f_item_code"} + ] + }, + { + "title": "金额", + "children": [ + {"title": "预算", "dataIndex": "f_budget"}, + {"title": "实际", "dataIndex": "f_actual"} + ] + } + ] +} +``` + +workSystem 示例: 复杂表头(主子表)示例 (469496902811974149) + +### 汇总行配置 + +```python +# 汇总配置 +table = build_table_field_model( + label="订单明细", + vmodel="f_order_detail_list", + child_table_name="ord_order_detail", + children=[...], + show_summary=True, + summary_field="f_amount" +) +``` + +### 新增弹窗配置 (addTableConf) + +```python +# 暂不支持,需手动配置 +add_config = { + "popupTitle": "新增明细", + "popupWidth": "60%", + "columnCount": 2 # 弹窗内字段排版 +} +``` + +--- + +## 表格类型对比 + +| 类型 | jnpfKey | 说明 | workSystem | +|------|---------|------|------------| +| 子表格 | table | 嵌套表格 | #25, #26, #27 | +| 表格网格 | tableGrid | 复杂表头主子表 | #35 | + +--- + +## 常见问题 + +| 问题 | 原因 | 解决 | +|------|------|------| +| 子表数据保存失败 | isSubTable 未设置 | 子表字段必须使用 build_table_field_model | +| 汇总不显示 | show_summary 未设 | `show_summary=True` | +| 汇总字段不对 | summary_field 错误 | 确认汇总字段名 | +| 弹窗新增失败 | addTableConf 缺失 | 需要配置弹窗属性 | + +--- + +## 数据存储规律 + +### 子表格存储规律 + +子表格(table)的数据存储在**独立的物理表**中,而非主表。 + +### 存储机制 + +1. **主表字段**:存储子表的外键关联(主键ID) +2. **子表字段**:存储在独立的物理表中,通过 `f_flow_task_id` 或 `f_id` 关联 + +### 子表数据结构 + +```json +// 主表存储 +{ + "f_id": "主表记录ID", + "f_order_no": "SO20260407001", + "f_order_detail_list": "811298790165190697" // 子表关联ID +} + +// 子表(ord_order_detail)存储 +{ + "f_id": "子表记录ID", + "f_flow_task_id": "811298790165190697", // 关联主表 + "f_product_name": "产品A", + "f_quantity": 10, + "f_unit_price": 99.00 +} +``` + +### 子表字段存储 + +子表内字段的存储与其他控件相同: + +| 子表字段 | 存储类型 | 示例 | +|---------|---------|------| +| input | 字符串 | `"产品名称"` | +| textarea | 字符串 | `"备注信息"` | +| inputNumber | 数值/字符串 | `99.00` 或 `"99.00"` | +| select/radio | 字符串 | `"1"` | +| checkbox | JSON数组 | `["1","3"]` | + +### 数据库表结构要求 + +子表需要创建独立的物理表,表结构示例: + +```sql +CREATE TABLE ord_order_detail ( + f_id VARCHAR(50) PRIMARY KEY, -- 主键(雪花ID) + f_flow_task_id VARCHAR(50), -- 关联主表的flow_task_id + f_product_name VARCHAR(200), -- 商品名称 + f_spec VARCHAR(100), -- 规格型号 + f_unit VARCHAR(20), -- 单位 + f_quantity DECIMAL(18,2), -- 数量 + f_unit_price DECIMAL(18,2), -- 单价 + f_amount DECIMAL(18,2), -- 金额 + -- 系统字段 + f_create_user VARCHAR(50), + f_create_time DATETIME, + f_modify_user VARCHAR(50), + f_modify_time DATETIME +); +``` + +### 重要配置 + +| 配置 | 说明 | 必填 | +|------|------|------| +| child_table_name | 子表物理表名(snake_case) | 是 | +| children | 子表字段列表 | 是 | +| is_sub_table | 标记为子表字段 | 自动设置 | +| show_summary | 是否显示汇总行 | 否 | +| summary_field | 汇总字段名 | 否 | + +--- + +## 下一步 + +- [特殊控件](08-special-controls.md) +- [图表控件](09-chart-controls.md) +- [表格高级模式](10-table-patterns.md) diff --git a/docs/control/08-special-controls.md b/docs/control/08-special-controls.md new file mode 100644 index 0000000..04f7fe3 --- /dev/null +++ b/docs/control/08-special-controls.md @@ -0,0 +1,449 @@ +# 特殊控件 + +## 目录 + +- [开关 (switch)](#开关-switch) +- [评分 (rate)](#评分-rate) +- [颜色选择 (colorPicker)](#颜色选择-colorpicker) +- [签章 (sign)](#签章-sign) +- [二维码 (qrcode)](#二维码-qrcode) +- [分隔线 (divider)](#分隔线-divider) +- [分组标题 (groupTitle)](#分组标题-grouptitle) +- [页签 (tab)](#页签-tab) +- [轮播 (carousel)](#轮播-carousel) +- [单据规则 (billRule)](#单据规则-billrule) +- [计算 (calculate)](#计算-calculate) +- [自动完成 (autoComplete)](#自动完成-autocomplete) + +--- + +## 开关 (switch) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `switch` | +| AIBridge builder | `build_field_model(..., jnpf_key="switch")` | + +### 基本规则 + +| 配置 | 类型 | 默认值 | 说明 | +|------|------|--------|------| +| activeValue | any | true | 开启时的值 | +| inactiveValue | any | false | 关闭时的值 | + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="是否启用", + field_vmodel="f_enabled", + jnpf_key="switch" +) + +# 自定义值 +field = build_field_model( + field_name="接收通知", + field_vmodel="f_receive_notification", + jnpf_key="switch", + activeValue="1", + inactiveValue="0" +) +``` + +--- + +## 评分 (rate) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `rate` | +| AIBridge builder | `build_field_model(..., jnpf_key="rate")` | + +### 基本规则 + +| 配置 | 类型 | 默认值 | 说明 | +|------|------|--------|------| +| max | int | 5 | 最大分值 | +| allowHalf | bool | false | 是否允许半星 | +| showText | bool | false | 是否显示文字 | + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="满意度评分", + field_vmodel="f_satisfaction", + jnpf_key="rate", + max=5, + allowHalf=True +) + +# 显示文字 +field = build_field_model( + field_name="等级评定", + field_vmodel="f_level", + jnpf_key="rate", + max=3, + showText=True +) +``` + +--- + +## 颜色选择 (colorPicker) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `colorPicker` | +| AIBridge builder | `build_field_model(..., jnpf_key="colorPicker")` | + +### AIBridge 使用 + +```python +field = build_field_model( + field_name="主题颜色", + field_vmodel="f_theme_color", + jnpf_key="colorPicker" +) +``` + +--- + +## 签章 (sign) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `sign` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 套打示例 (#24) | + +### 基本规则 + +签章控件用于电子签章/盖章,**通常需配合流程使用**。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 套打示例 | 585384793399624261 | billRule + sign, 单据签章 | + +--- + +## 二维码 (qrcode) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `qrcode` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 二维码、条形码多组件值联动展示 (#3) | + +### 基本规则 + +二维码控件用于生成和扫描二维码。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 二维码、条形码多组件值联动展示 | 797444600007492165 | qrcode + inputNumber 联动 | + +### 源码位置 + +``` +jnpf/移动端/jnpf-app-vue3/components/Jnpf/Qrcode/index.vue +jnpf/移动端/jnpf-app-vue3/components/Jnpf/Barcode/index.vue +``` + +--- + +## 分隔线 (divider) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `divider` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 入职申请、物资申请、套打示例 等 | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 入职申请 | 624163990351643525 | 表单分区 | +| 物资申请 | 585436888639210245 | 类型分隔 | +| 套打示例 | 585384793399624261 | 区域分隔 | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "divider", + "label": "基本信息" + }, + "orientation": "left", + "contentPosition": "left" +} +``` + +--- + +## 分组标题 (groupTitle) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `groupTitle` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 离职交接表、预算管理、出差管理、事件管理 等 | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 离职交接表 | 623417538411233285 | 分组显示 | +| 预算管理 | 469100392253286789 | 预算信息分组 | +| 出差管理 | 469066996185622917 | 出差信息分组 | +| 事件管理 | 469065268790880645 | 事件信息分组 | +| 设备巡检管理 | 469062048563652997 | 巡检信息分组 | +| 产品管理 | 469039386000943493 | 产品信息分组 | +| 核酸检测 | 469038006062344581 | 检测信息分组 | +| 药房管理 | 468849844170057541 | 药房信息分组 | +| 报名管理外链 | 468848215723140933 | 报名信息分组 | +| 用车管理 | 469040281883306373 | 用车信息分组 | +| 人才管理 | 469047177461688709 | 人才信息分组 | + +### 手动配置示例 + +```json +{ + "__config__": { + "jnpfKey": "groupTitle", + "label": "基本信息" + }, + "showBorder": true +} +``` + +--- + +## 页签 (tab) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `tab` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 高级控件和默认查询 (#34)、订单示例 (#43) | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 高级控件和默认查询 | 469499301635095045 | tab + table | +| 订单示例 | 469133201755925637 | tab 切换明细 | + +--- + +## 轮播 (carousel) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `carousel` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 表单规则 (#7) | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 表单规则 | 797378890455581253 | carousel + input + inputNumber + select | + +--- + +## 单据规则 (billRule) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `billRule` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 套打示例、采购合同、订单示例、产品管理 等 | + +### 基本规则 + +单据规则用于自动生成单据编号,通常是只读字段。 + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 套打示例 | 585384793399624261 | 单据编号 | +| 采购合同 | 585077579715707205 | 合同编号 | +| 订单示例 | 469133201755925637 | 订单编号 | +| 采购管理 | 469106304141552773 | 采购单号 | +| 客户管理 | 469102214628043141 | 客户编号 | +| 产品管理 | 469039386000943493 | 产品编码 | +| 核酸检测 | 469038006062344581 | 检测编号 | +| 药房管理 | 468849844170057541 | 药方编号 | +| 应收费用 | 468826463014018501 | 应收单号 | +| 用车管理 | 469040281883306373 | 用车单号 | + +--- + +## 计算 (calculate) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `calculate` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 水电费用 (#25)、采购合同 (#28) | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 水电费用 | 585110234985398597 | calculate + table, 自动计算费用 | +| 采购合同 | 585077579715707205 | calculate, 金额汇总计算 | + +--- + +## 自动完成 (autoComplete) + +### 基本信息 + +| 属性 | 值 | +|------|-----| +| jnpfKey | `autoComplete` | +| AIBridge builder | 无封装 | +| workSystem 示例 | 数据接口调用字段示例 (#33) | + +### workSystem 示例 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 数据接口调用字段示例 | 469500336084679173 | autoComplete + select + cascader + popupSelect | + +--- + +## 系统自动填充控件 + +| 控件 | jnpfKey | 说明 | workSystem 示例 | +|------|---------|------|-----------------| +| 创建用户 | createUser | 自动填充当前用户 | #43, #46, #47, #49 | +| 创建时间 | createTime | 自动填充创建时间 | #46, #47, #49, #55 | +| 修改时间 | modifyTime | 自动填充修改时间 | #49, #55 | +| 当前组织 | currOrganize | 自动填充当前组织 | #47, #51 | +| 区域选择 | areaSelect | 省市区选择 | #52, #59 | + +--- + +## 数据存储规律 + +### 特殊控件存储规律 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | 说明 | +|------|---------|---------|------------|------| +| 开关 | `switch` | **字符串** | `"1"` / `"0"` | activeValue/inactiveValue 转字符串存储,数据库类型 varchar(255) | +| 评分 | `rate` | **decimal(38,1)** | `4.0` | 存储为 decimal(38,1),如 4.0 表示4星 | +| 滑块 | `slider` | **decimal(38,15)** | `50.000000000000000` | 高精度 decimal 存储,非整数 | +| 颜色选择 | `colorPicker` | **字符串** | `"#1890ff"` | 十六进制颜色值 | +| 签章 | `sign` | **字符串** | `"/files/sign/xxx.png"` | 签章图片路径 | +| 二维码 | `qrcode` | **字符串** | `"http://xxx"` | 二维码内容 | +| 条形码 | `barcode` | **字符串** | `"123456789"` | 条形码内容 | +| 单据规则 | `billRule` | **字符串** | `"BJ20260407001"` | 自动生成的编号 | +| 计算 | `calculate` | **数值** | `1234.56` | 计算结果值 | + +### 开关控件详解 + +开关的存储值由 `activeValue` 和 `inactiveValue` 决定: + +| 配置 | activeValue | inactiveValue | 开启存储 | 关闭存储 | +|------|------------|---------------|---------|---------| +| 默认 | `true` | `false` | `1` | `0` | +| 数值型 | `"1"` | `"0"` | `"1"` | `"0"` | +| 布尔型 | `"true"` | `"false"` | `"true"` | `"false"` | + +### AIBridge 配置示例 + +```python +# 默认开关(存储 1/0) +field = build_field_model( + field_name="是否启用", + field_vmodel="f_enabled", + jnpf_key="switch" +) + +# 自定义值 +field = build_field_model( + field_name="接收通知", + field_vmodel="f_receive_notification", + jnpf_key="switch", + activeValue="1", + inactiveValue="0" +) +``` + +### 地址选择控件 + +| 控件 | jnpfKey | 存储类型 | 存储格式示例 | +|------|---------|---------|------------| +| 地址选择 | `address` | **纯文本字符串** | `"广东省东莞市万江区家达能大厦74B"` | 实际存储为纯地址文本,非 JSON 对象 | + +### 存储验证示例 + +```python +# 开关(实际存储为字符串) +f_enabled: "1" # 开启,varchar(255) 存储 + +# 评分(实际存储为 decimal(38,1)) +f_rating: Decimal('4.0') # 4星 + +# 滑块(实际存储为高精度 decimal(38,15)) +f_opacity: Decimal('50.000000000000000') # 50% + +# 颜色 +f_color: "#1890ff" + +# 地址(实际存储为纯文本,非 JSON 对象) +f_address: '广东省东莞市万江区家达能大厦74B' +``` + +### 数据库字段要求 + +| 控件 | 建议字段类型 | +|------|------------| +| switch | `varchar(255)` | +| rate | `decimal(38,1)` | +| slider | `decimal(38,15)` | +| colorPicker | `varchar(255)` | +| sign/qrcode/barcode | `varchar(500)` 或 `text` | +| billRule | `varchar(50)` | +| calculate | `decimal(18,2)` | +| address | `varchar(255)` | + +--- + +## 下一步 + +- [图表控件](09-chart-controls.md) +- [表格高级模式](10-table-patterns.md) +- [表单高级模式](11-form-patterns.md) diff --git a/docs/control/09-chart-controls.md b/docs/control/09-chart-controls.md new file mode 100644 index 0000000..c106878 --- /dev/null +++ b/docs/control/09-chart-controls.md @@ -0,0 +1,421 @@ +# 图表控件 + +## 目录 + +- [概述](#概述) +- [柱状图 (Bar)](#柱状图-bar) +- [横向柱状图 (BarAcross)](#横向柱状图-baracross) +- [折线面积图 (LineArea)](#折线面积图-linearea) +- [折线柱状图 (LineBar)](#折线柱状图-linebar) +- [饼图 (Pie)](#饼图-pie) +- [散点图 (Scatter)](#散点图-scatter) +- [K线图 (Candlestick)](#k线图-candlestick) +- [漏斗图 (Funnel)](#漏斗图-funnel) +- [仪表盘 (Gauge)](#仪表盘-gauge) +- [树图 (Tree)](#树图-tree) + +--- + +## 概述 + +### 基本信息 + +JNPF 使用 **ECharts** 作为图表引擎,封装在 `@vben/plugins/echarts` 包中。 + +### 源码位置 + +``` +$ccWorkDir/web/apps/jnpf-web-apps-main/src/views/extend/graphDemo/ +``` + +### 通用引入 + +```typescript +import type { EchartsUIType } from '@vben/plugins/echarts'; +import { EchartsUI, useEcharts } from '@vben/plugins/echarts'; + +const chartRef = ref(); +const { renderEcharts } = useEcharts(chartRef); + +onMounted(() => { + renderEcharts(options); +}); + +// 模板 + +``` + +### 图表类型清单 (12 种) + +| 类型 | 目录 | 说明 | +|------|------|------| +| 柱状图 | echartsBar | 堆叠柱状图,支持标记线 | +| 横向柱状图 | echartsBarAcross | 水平柱状图 | +| 折线面积图 | echartsLineArea | 堆叠面积图 | +| 折线柱状图 | echartsLineBar | 组合图 | +| 饼图 | echartsPie | 环形饼图 | +| 散点图 | echartsScatter | 散点分布 | +| K线图 | echartsCandlestick | 股票K线 | +| 漏斗图 | echartsFunnel | 流程漏斗 | +| 仪表盘 | echartsGauge | 多仪表盘 | +| 树图 | echartsTree | 层级树图 | + +--- + +## 柱状图 (Bar) + +### 源码位置 + +``` +extend/graphDemo/echartsBar/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'axis' }, + legend: { data: ['销量', '利润'] }, + xAxis: { type: 'category', data: ['衬衫', '毛衣', '裤子', '袜子'] }, + yAxis: { type: 'value' }, + series: [ + { + name: '销量', + type: 'bar', + data: [5, 20, 36, 10], + markPoint: { data: [{ type: 'max', name: '最大值' }] }, + markLine: { data: [{ type: 'average', name: '平均值' }] } + } + ] +}; +``` + +### 特性 + +- 支持 `magicType`: 切换柱状/折线 +- 支持 `markPoint`: 标记点 (最大/最小值) +- 支持 `markLine`: 标记线 (平均值) + +--- + +## 横向柱状图 (BarAcross) + +### 源码位置 + +``` +extend/graphDemo/echartsBarAcross/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'axis' }, + legend: { data: ['销量'] }, + xAxis: { type: 'value' }, + yAxis: { type: 'category', data: ['衬衫', '毛衣', '裤子', '袜子'] }, + series: [{ + name: '销量', + type: 'bar', + data: [5, 20, 36, 10] + }] +}; +``` + +--- + +## 折线面积图 (LineArea) + +### 源码位置 + +``` +extend/graphDemo/echartsLineArea/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'axis' }, + legend: { data: ['蒸发量', '降水量'] }, + xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月'], boundaryGap: false }, + yAxis: { type: 'value' }, + series: [ + { + name: '蒸发量', + type: 'line', + data: [2.0, 4.9, 7.0, 23.2], + areaStyle: {}, // 填充面积 + stack: '总量', // 堆叠 + emphasis: { focus: 'series' } + } + ] +}; +``` + +### 特性 + +- `areaStyle`: 开启面积填充 +- `stack: '总量'`: 堆叠模式 +- `boundaryGap: false`: 折线连接 + +--- + +## 折线柱状图 (LineBar) + +### 源码位置 + +``` +extend/graphDemo/echartsLineBar/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'axis' }, + legend: { data: ['蒸发量', '降水量', '平均温度'] }, + xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月'] }, + yAxis: [ + { type: 'value', name: '水量' }, + { type: 'value', name: '温度', min: 0, max: 30 } + ], + series: [ + { name: '蒸发量', type: 'bar', data: [2.0, 4.9, 7.0, 23.2] }, + { name: '降水量', type: 'bar', data: [2.6, 5.9, 9.0, 26.4] }, + { name: '平均温度', type: 'line', yAxisIndex: 1, data: [2.0, 2.2, 3.3, 4.5] } + ] +}; +``` + +--- + +## 饼图 (Pie) + +### 源码位置 + +``` +extend/graphDemo/echartsPie/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' }, + legend: { orient: 'vertical', left: 'left', data: ['直接访问', '邮件营销'] }, + series: [{ + name: '访问来源', + type: 'pie', + radius: ['40%', '70%'], // 环形 + center: ['50%', '50%'], + avoidLabelOverlap: false, + label: { formatter: '{b}: {d}%' }, + data: [ + { value: 335, name: '直接访问' }, + { value: 234, name: '邮件营销' } + ] + }] +}; +``` + +### 特性 + +- 环形: `radius: ['40%', '70%']` +- 南丁格尔: `roseType: 'area'` + +--- + +## 散点图 (Scatter) + +### 源码位置 + +``` +extend/graphDemo/echartsScatter/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'item' }, + xAxis: { type: 'value', scale: true }, + yAxis: { type: 'value', scale: true }, + series: [{ + type: 'scatter', + symbolSize: 20, + data: [ + [10.0, 8.04], [8.0, 6.95], [13.0, 7.58], [9.0, 8.81] + ] + }] +}; +``` + +--- + +## K线图 (Candlestick) + +### 源码位置 + +``` +extend/graphDemo/echartsCandlestick/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'axis' }, + legend: { data: ['DowJS', 'Gold'] }, + xAxis: { type: 'category', data: ['2012-12-14', '2012-12-15'] }, + yAxis: { type: 'value' }, + series: [{ + name: 'DowJS', + type: 'candlestick', + data: [ + [open, close, low, high], // [开盘, 收盘, 最低, 最高] + [20, 30, 10, 35] + ] + }] +}; +``` + +--- + +## 漏斗图 (Funnel) + +### 源码位置 + +``` +extend/graphDemo/echartsFunnel/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'item' }, + legend: { data: ['展现', '点击', '访问', '咨询', '成交'] }, + series: [{ + name: '漏斗图', + type: 'funnel', + left: '10%', + top: 60, + bottom: 60, + width: '80%', + data: [ + { value: 100, name: '展现' }, + { value: 80, name: '点击' }, + { value: 60, name: '访问' }, + { value: 40, name: '咨询' }, + { value: 20, name: '成交' } + ] + }] +}; +``` + +--- + +## 仪表盘 (Gauge) + +### 源码位置 + +``` +extend/graphDemo/echartsGauge/index.vue +``` + +### 关键配置 + +```typescript +const options = { + series: [ + { + type: 'gauge', + startAngle: 180, + endAngle: 0, + center: ['50%', '70%'], + radius: '90%', + progress: { show: true, width: 18 }, + axisLine: { lineStyle: { width: 18 } }, + axisTick: { show: false }, + splitLine: { show: false }, + axisLabel: { show: false }, + pointer: { show: false }, + title: { show: true, offsetCenter: [0, '10%'], fontSize: 16 }, + detail: { valueAnimation: true, fontSize: 48, offsetCenter: [0, '-10%'] }, + data: [{ value: 75, name: '完成率' }] + } + ] +}; + +// 动态更新 +timer.value = setInterval(() => { + options.series[0].data[0].value = (Math.random() * 100).toFixed(2) - 0; + renderEcharts(options, false); // false = 仅更新数据 +}, 2000); +``` + +--- + +## 树图 (Tree) + +### 源码位置 + +``` +extend/graphDemo/echartsTree/index.vue +``` + +### 关键配置 + +```typescript +const options = { + tooltip: { trigger: 'item' }, + series: [{ + type: 'tree', + data: [{ + name: '根节点', + children: [ + { name: '节点1', children: [{ name: '叶子1' }, { name: '叶子2' }] }, + { name: '节点2' } + ] + }], + symbol: 'emptyCircle', + symbolSize: 8, + orient: 'horizontal', // 水平/vertical + expandAndCollapse: true, + label: { position: 'bottom', formatter: '{b}' } + }] +}; +``` + +--- + +## 图表开发建议 + +### 动态图表 + +```typescript +// 使用 ref 和 setInterval 实现动态更新 +const timer = ref(); + +onUnmounted(() => { + if (timer.value) clearInterval(timer.value); +}); +``` + +### 自适应尺寸 + +```typescript +// 窗口 resize 时自动适应 +window.addEventListener('resize', () => { + chartRef.value?.resize(); +}); +``` + +--- + +## 下一步 + +- [表格高级模式](10-table-patterns.md) +- [表单高级模式](11-form-patterns.md) +- [示例参考](12-examples/extend-examples.md) diff --git a/docs/control/10-table-patterns.md b/docs/control/10-table-patterns.md new file mode 100644 index 0000000..f58cba9 --- /dev/null +++ b/docs/control/10-table-patterns.md @@ -0,0 +1,513 @@ +# 表格高级模式 + +## 目录 + +- [通用表格 (commonTable)](#通用表格-commontable) +- [树形表格 (treeTable)](#树形表格-treetable) +- [分组表格 (groupingTable)](#分组表格-groupingtable) +- [合并单元格 (mergeTable)](#合并单元格-mergetable) +- [锁定列 (lockTable)](#锁定列-locktable) +- [批注表格 (postilTable)](#批注表格-postiltable) +- [行内编辑 (redactTable)](#行内编辑-redacttable) +- [标记表格 (signTable)](#标记表格-signtable) +- [打印表格 (printTable)](#打印表格-printtable) +- [统计表格 (statisticsTable)](#统计表格-statisticstable) +- [扩展表格 (extension)](#扩展表格-extension) +- [复杂表头 (complexHeader)](#复杂表头-complexheader) +- [表格树 (tableTree)](#表格树-tabletree) + +--- + +## 源码位置 + +``` +$ccWorkDir/web/apps/jnpf-web-apps-main/src/views/extend/tableDemo/ +``` + +--- + +## 通用表格 (commonTable) + +### 源码 + +``` +tableDemo/commonTable/index.vue +``` + +### 核心模式 + +```typescript +const [registerTable, { reload }] = useVxeTable({ + api: getTableList, // 数据接口 + columns, // 列定义 + useSearchForm: true, // 启用搜索表单 + formConfig: { // 搜索表单配置 + schemas: searchSchemas + }, + actionColumn: { // 操作列 + width: 100, + title: '操作', + dataIndex: 'action' + } +}); +``` + +### 列定义 + +```typescript +const columns: BasicColumn[] = [ + { title: '名称', dataIndex: 'name', width: 150 }, + { title: '编码', dataIndex: 'code', width: 120 }, + { title: '状态', dataIndex: 'status', slots: { default: 'status' } }, + { title: '创建时间', dataIndex: 'createTime', width: 180, format: 'date|YYYY-MM-DD' }, + { title: '操作', dataIndex: 'action', width: 120, fixed: 'right' } +]; +``` + +--- + +## 树形表格 (treeTable) + +### 源码 + +``` +tableDemo/treeTable/index.vue +``` + +### 核心模式 + +```typescript +// 左侧树 + 右侧表格 + + +// 表格搜索参数 +const searchInfo = reactive({ typeId: '' }); + +const [registerTable, { reload }] = useVxeTable({ + api: getTableListByType, + searchInfo, // 传入树选择的参数 + immediate: false // 延迟加载 +}); +``` + +### 关键点 + +- `BasicLeftTree`: 左侧树组件 +- `searchInfo`: 响应式对象,接收树选择的值 +- `immediate: false`: 延迟加载,等树选择后再加载 + +--- + +## 分组表格 (groupingTable) + +### 源码 + +``` +tableDemo/groupingTable/index.vue +``` + +### 核心模式 + +```typescript +const [registerTable, { reload }] = useVxeTable({ + api: getTableListAll, + isTreeTable: true, // 开启树形模式 + pagination: false, // 禁用分页 + afterFetch: (data) => { + // 将扁平数据转换为树结构 + let list = cloneDeep(industryTypeList); + for (const e of list) { + e.isParent = true; + e.children = []; + for (const datum of data) { + if (e.id == datum.projectType) e.children.push(datum); + } + } + return list; + } +}); +``` + +### 关键点 + +- `isTreeTable: true`: 启用分组 +- `pagination: false`: 分组模式下通常禁用分页 +- `afterFetch`: 数据转换,构造父子关系 + +--- + +## 合并单元格 (mergeTable) + +### 源码 + +``` +tableDemo/mergeTable/index.vue +``` + +### 核心模式 + +```typescript +const [registerTable, { reload }] = useVxeTable({ + spanMethod: ({ row, column, rowIndex, columnIndex }) => { + // 合并相同值的单元格 + if (columnIndex === 4 || columnIndex === 6) { + if (rowIndex > 0 && row[column.property] === tableData[rowIndex - 1][column.property]) { + return { rowspan: 0, colspan: 0 }; + } + let rspan = 1; + for (let i = rowIndex + 1; i < tableData.length; i++) { + if (tableData[i][column.property] === row[column.property]) { + rspan++; + } else break; + } + return { rowspan: rspan, colspan: 1 }; + } + } +}); +``` + +### 关键点 + +- `spanMethod`: 合并算法,返回 `{rowspan, colspan}` +- 返回 `{rowspan: 0, colspan: 0}` 表示被合并 + +--- + +## 锁定列 (lockTable) + +### 源码 + +``` +tableDemo/lockTable/index.vue +``` + +### 核心模式 + +```typescript +const columns: BasicColumn[] = [ + { title: '项目名称', dataIndex: 'projectName', minWidth: 200, fixed: 'left' }, + { title: '项目编码', dataIndex: 'projectCode', width: 160, fixed: 'left' }, + // ... 中间列不固定 ... + { title: '操作', dataIndex: 'action', width: 100, fixed: 'right' } +]; +``` + +### 关键点 + +- `fixed: 'left'`: 左侧锁定 +- `fixed: 'right'`: 右侧锁定 +- `minWidth`: 防止列宽过小 + +--- + +## 批注表格 (postilTable) + +### 源码 + +``` +tableDemo/postilTable/index.vue +``` + +### 核心模式 + +```typescript +// 列定义 +{ title: '批注', dataIndex: 'postilCount', slots: { default: 'postilCount' } } + +// 模板 + + +// 打开批注弹窗 +function addOrUpdateHandle(id) { + openPostilModal(true, { id }); +} +``` + +### 关键点 + +- 批注数量字段 `postilCount` +- 点击打开批注详情弹窗 + +--- + +## 行内编辑 (redactTable) + +### 源码 + +``` +tableDemo/redactTable/index.vue +``` + +### 核心模式 + +```typescript +// 点击切换编辑模式 + + +// 点击行开启编辑 +function handleRowClick({ record }) { + state.tabClickId = record.id; +} + +// 保存编辑 +async function handleSave(row) { + await updateRowData(row); + state.tabClickId = null; +} +``` + +### 关键点 + +- `tabClickId`: 记录当前编辑行 +- 动态组件切换编辑控件 +- 支持多种控件类型 + +--- + +## 标记表格 (signTable) + +### 源码 + +``` +tableDemo/signTable/index.vue +``` + +### 核心模式 + +```typescript +// 颜色标记下拉 + + + 项目标记 + + + +``` + +### 关键点 + +- 颜色选项列表 `options` +- `handleSign`: 更新行的标记颜色 + +--- + +## 打印表格 (printTable) + +### 源码 + +``` +tableDemo/printTable/index.vue +``` + +### 核心模式 + +```typescript +import printJS from 'print-js'; + +function handlePrint() { + printJS({ + printable: state.list, // 数据 + properties: columnsList.map((o) => ({ + field: o.dataIndex, + displayName: o.title + })), + type: 'json', + gridStyle: 'border: 1px solid lightgray;' + }); +} +``` + +### 关键点 + +- 使用 `printJS` 库 +- `properties`: 字段映射 + +--- + +## 统计表格 (statisticsTable) + +### 源码 + +``` +tableDemo/statisticsTable/index.vue +``` + +### 核心模式 + +```typescript +const [registerTable, { reload }] = useVxeTable({ + showFooter: true, + footerMethod: ({ columns, data }) => { + return [columns.map((column, columnIndex) => { + if (![9, 10, 11].includes(columnIndex)) return ''; // 非统计列 + let sumVal = data.reduce((sum, d) => { + return sum + Number.parseFloat(d[column.property] || 0); + }, 0); + return Number.isNaN(sumVal) ? '' : sumVal.toFixed(2); + })]; + } +}); +``` + +### 关键点 + +- `showFooter: true`: 显示汇总行 +- `footerMethod`: 返回汇总数据 + +--- + +## 扩展表格 (extension) + +### 源码 + +``` +tableDemo/extension/index.vue +``` + +### 核心模式 + +```typescript +// 展开行显示嵌套表格 +expandConfig: { + lazy: true, + loadMethod({ row }) { + return new Promise((resolve) => { + getCityList(row.id).then((res) => { + row.list = res.data.list; + resolve(row); + }); + }); + } +} + +// 嵌套 VxeGrid + +``` + +### 关键点 + +- `expandConfig.lazy`: 懒加载展开数据 +- `loadMethod`: 返回 Promise +- 嵌套 `VxeGrid` 显示子数据 + +--- + +## 复杂表头 (complexHeader) + +### 源码 + +``` +tableDemo/complexHeader/index.vue +``` + +### 核心模式 + +```typescript +const columns: BasicColumn[] = [ + { + title: '相关费用', + width: 240, + align: 'center', + children: [ + { title: '费用金额', dataIndex: 'costAmount', width: 100 }, + { title: '已用金额', dataIndex: 'tunesAmount', width: 100 }, + { title: '预计收入', dataIndex: 'projectedIncome', width: 100 } + ] + } +]; +``` + +### 关键点 + +- `children`: 定义子列 +- 多层表头嵌套 + +--- + +## 表格树 (tableTree) + +### 源码 + +``` +tableDemo/tableTree/index.vue +``` + +### 核心模式 + +```typescript +const [registerTable, { expandAll }] = useVxeTable({ + isTreeTable: true, + immediate: false +}); + +// 字典数据作为树 +state.industryTypeList = await baseStore.getDictionaryData('IndustryType'); +``` + +### 关键点 + +- `isTreeTable: true`: 纯树形表格 +- 树形数据来自数据字典 + +--- + +## 通用 API 模式 + +### 列表查询 + +```typescript +import { getTableList, createRecord, updateRecord, deleteRecord } from '@/api/xxx'; + +const [registerTable, { reload, deleteTableDataRecord }] = useVxeTable({ + api: getTableList, + columns, + actionColumn: { width: 120, title: '操作', dataIndex: 'action' } +}); + +// 新增 +function handleAdd() { + openModal(true, {}); +} + +// 编辑 +function handleEdit(record) { + openModal(true, record); +} + +// 删除 +async function handleDelete(record) { + await deleteRecord(record.id); + deleteTableDataRecord(record.id); + reload(); +} +``` + +--- + +## 下一步 + +- [表单高级模式](11-form-patterns.md) +- [示例参考](12-examples/workSystem-examples.md) +- [示例参考](12-examples/extend-examples.md) diff --git a/docs/control/11-form-patterns.md b/docs/control/11-form-patterns.md new file mode 100644 index 0000000..899bd23 --- /dev/null +++ b/docs/control/11-form-patterns.md @@ -0,0 +1,318 @@ +# 表单高级模式 + +## 目录 + +- [验证规则 (verifyForm)](#验证规则-verifyform) +- [字段联动](#字段联动) +- [自定义按钮](#自定义按钮) +- [打印模板](#打印模板) + +--- + +## 源码位置 + +``` +$ccWorkDir/web/apps/jnpf-web-apps-main/src/views/extend/formDemo/ +``` + +--- + +## 验证规则 (verifyForm) + +### 源码 + +``` +formDemo/verifyForm/index.vue +formDemo/verifyForm1/index.vue +``` + +### 核心模式 + +```typescript +const state = reactive({ + dataForm: { + account: '', + password: '', + email: '', + url: '', + creditcard: '', + tel: '', + mobile: '', + phone: '', + age: '', + zipCode: '', + cardId: '', + RGB: '', + wechat: '', + licensePlate: '', + qq: '', + ip: '', + english: '', + chinese: '', + date: '', + floatLtZero: '', + intGtZero: '', + intNEqZero: '' + }, + dataRule: { + // 必填 + account: [ + { required: true, message: '用户账号不能为空', trigger: 'blur' }, + { min: 6, max: 20, message: '长度在6-20之间', trigger: 'blur' } + ], + // 自定义正则 + password: [ + { required: true, message: '用户密码不能为空', trigger: 'blur' }, + { pattern: /^[\w-]{6,20}$/, message: '密码格式错误', trigger: 'blur' } + ], + // 邮箱验证 + email: [ + { pattern: /^[a-z0-9]+([._\\-]*[a-z-9])*@([a-z0-9][-a-z0-9]*[a-z0-9].){1,63}[a-z0-9]+$/, message: '请输入正确格式的电子邮件', trigger: 'blur' } + ], + // URL 验证 + url: [ + { pattern: /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)?@)?/, message: '请输入正确格式的URL', trigger: 'blur' } + ], + // 信用卡验证 + creditcard: [ + { pattern: /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$/, message: '请输入正确的信用卡号', trigger: 'blur' } + ], + // 电话号码 + tel: [ + { pattern: /^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' } + ], + // 手机号码 + mobile: [ + { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' } + ], + // 座机 + phone: [ + { pattern: /^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的座机号', trigger: 'blur' } + ], + // 年龄 + age: [ + { pattern: /^(?:[1-9][0-9]?|1[01][0-9]|120)$/, message: '请输入正确的年龄', trigger: 'blur' } + ], + // 邮编 + zipCode: [ + { pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮编', trigger: 'blur' } + ], + // 身份证 + cardId: [ + { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' } + ], + // RGB颜色 + RGB: [ + { pattern: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/, message: '请输入正确的RGB颜色值', trigger: 'blur' } + ], + // 微信 + wechat: [ + { pattern: /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/, message: '请输入正确的微信号', trigger: 'blur' } + ], + // 车牌号 + licensePlate: [ + { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号', trigger: 'blur' } + ], + // QQ号 + qq: [ + { pattern: /^[1-9][0-9]{4,10}$/, message: '请输入正确的QQ号', trigger: 'blur' } + ], + // IP地址 + ip: [ + { pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入正确的IP地址', trigger: 'blur' } + ], + // 英文 + english: [ + { pattern: /^[A-Za-z]+$/, message: '请输入英文字母', trigger: 'blur' } + ], + // 中文 + chinese: [ + { pattern: /^[\u4e00-\u9fa5]+$/, message: '请输入中文字符', trigger: 'blur' } + ], + // 日期 + date: [ + { pattern: /^\d{4}-\d{2}-\d{2}$/, message: '请输入正确格式的日期', trigger: 'blur' } + ], + // 负数 + floatLtZero: [ + { pattern: /^-\d+(\.\d+)?$/, message: '请输入负数', trigger: 'blur' } + ], + // 正整数 + intGtZero: [ + { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' } + ], + // 非零整数 + intNEqZero: [ + { pattern: /^-?[1-9]\d*$/, message: '请输入非零整数', trigger: 'blur' } + ] + } +}); +``` + +### 常用验证规则 + +| 规则 | 正则表达式 | 说明 | +|------|-----------|------| +| 必填 | `{ required: true }` | 不能为空 | +| 长度 | `{ min: 6, max: 20 }` | 字符长度限制 | +| 邮箱 | `/^[a-z0-9]+([._\\-]*[a-z-9])*@.../` | 邮箱格式 | +| 手机 | `/^1[3-9]\d{9}$/` | 手机号(1开头) | +| 电话 | `/^0\d{2,3}-?\d{7,8}$/` | 座机号码 | +| 身份证 | `/(^\d{15}$)\|(^\d{18}$).../` | 15/18位身份证 | +| URL | `/^(https?|ftp):\/\/.../` | 网址 | +| 邮编 | `/^[1-9]\d{5}$/` | 国内邮编 | +| 银行卡 | `/^(?:4[0-9]{12}...` | 信用卡/借记卡 | +| IP地址 | `/^(?:(?:25[0-5]...` | IPv4 | +| 中文 | `/^[\u4e00-\u9fa5]+$/` | 纯中文 | +| 英文 | `/^[A-Za-z]+$/` | 纯英文 | +| 正整数 | `/^[1-9]\d*$/` | 大于0的整数 | + +### 自定义验证器 + +```typescript +// 密码确认验证 +const validatePass = (_rule, value) => { + return value === state.dataForm.password + ? Promise.resolve() + : Promise.reject(new Error('两次密码输入不一致')); +}; + +// 使用 +{ validator: validatePass, trigger: 'blur' } +``` + +--- + +## 字段联动 + +### 源码 + +``` +formDemo/fieldForm4/index.vue +formDemo/fieldForm5/index.vue +formDemo/fieldForm6/index.vue +``` + +### 核心模式 + +```typescript +// 根据一个字段的值控制另一个字段的显示/选项 +watch(() => state.dataForm.selectType, (val) => { + if (val === '1') { + state.dataForm.inputValue = '类型1的默认值'; + } else if (val === '2') { + state.options = [ + { label: '选项A', value: 'a' }, + { label: '选项B', value: 'b' } + ]; + } +}); + +// 计算字段 +const computedValue = computed(() => { + return state.dataForm.price * state.dataForm.quantity; +}); +``` + +### 联动场景 + +1. **选项联动**: 选择A时,B的选项跟着变 +2. **值联动**: 选择A时,B自动填充默认值 +3. **显示联动**: 选择A时,显示/隐藏某些字段 +4. **计算联动**: 多个字段计算得出结果 + +--- + +## 自定义按钮 + +### workSystem 示例 + +``` +表单自定义按钮及多打印模板示例 (469136940843723909) +``` + +### 核心模式 + +```typescript +// 按钮定义 +const buttonList = [ + { title: '提交', icon: 'icon-ym icon-ym-generator-add', type: 'primary', click: 'handleSubmit' }, + { title: '保存草稿', icon: 'icon-ym icon-ym-generator-baocun', click: 'handleDraft' }, + { title: '取消', icon: 'icon-ym icon-ym-generator-guanbi', click: 'handleCancel' } +]; + +// 按钮点击处理 +function handleSubmit() { + // 提交逻辑 +} + +function handleDraft() { + // 保存草稿 +} +``` + +--- + +## 打印模板 + +### workSystem 示例 + +``` +套打示例 (585384793399624261) +表单自定义按钮及多打印模板示例 (469136940843723909) +``` + +### 核心模式 + +```typescript +// 打印配置 +const printConfig = { + printTemplate: 'default', // 模板名称 + printFields: ['field1', 'field2'], // 打印字段 + printType: '套打/普通打印' +}; + +// 打印处理 +function handlePrint() { + // 调用打印组件 + openPrintModal(true, { data: state.dataForm }); +} +``` + +--- + +## 工作流表单 + +### 基本信息 + +工作流表单与普通表单不同: +- `enableFlow: 1`: 启用流程 +- `webType: 2`: 表单列表类型 +- `formData`: 流程字段列表 + +### 字段结构 + +```typescript +// 工作流表单字段 (不同于普通表单) +const flowFields = [ + { filedName: "流程标题", filedId: "flowTitle", required: true, tableName: "wform_xxx" }, + { filedName: "紧急情况", filedId: "flowUrgent", required: true, tableName: "wform_xxx" }, + { filedName: "申请人员", filedId: "applicant", required: true, tableName: "wform_xxx" } +]; +``` + +### workSystem 中的工作流表单 + +| 表单名称 | 表单ID | 说明 | +|----------|--------|------| +| 请假申请 | 1589964488616407041 | 流程标题/紧急情况/申请人 | +| 销售订单 | 1589960344887267330 | 销售流程 | +| 订单示例 | 359757745991204532 | CRM订单流程 | + +--- + +## 下一步 + +- [workSystem 示例索引](12-examples/workSystem-examples.md) +- [extend 示例索引](12-examples/extend-examples.md) +- [控件速查](01-quick-ref.md) diff --git a/docs/control/12-examples/extend-examples.md b/docs/control/12-examples/extend-examples.md new file mode 100644 index 0000000..962de3c --- /dev/null +++ b/docs/control/12-examples/extend-examples.md @@ -0,0 +1,217 @@ +# extend 代码示例索引 + +## 源码位置 + +``` +$ccWorkDir/web/apps/jnpf-web-apps-main/src/views/extend/ +``` + +--- + +## 表格模式 (tableDemo) + +| 目录 | 说明 | 关键特性 | +|------|------|----------| +| commonTable | 通用表格 | useVxeTable, formConfig, actionColumn | +| treeTable | 树形表格 | BasicLeftTree, searchInfo, immediate | +| groupingTable | 分组表格 | isTreeTable, afterFetch, 父子结构 | +| mergeTable | 合并单元格 | spanMethod, rowspan/colspan | +| lockTable | 锁定列 | fixed: 'left'/'right', minWidth | +| postilTable | 批注表格 | postilCount, 批注弹窗 | +| redactTable | 行内编辑 | tabClickId, 动态组件 | +| signTable | 标记表格 | 颜色标记, a-dropdown | +| printTable | 打印表格 | printJS, printable | +| statisticsTable | 统计表格 | showFooter, footerMethod | +| extension | 扩展表格 | expandConfig, lazy, VxeGrid | +| complexHeader | 复杂表头 | children, 多层表头 | +| tableTree | 表格树 | isTreeTable, 字典数据 | + +--- + +## 表单模式 (formDemo) + +| 目录 | 说明 | 关键特性 | +|------|------|----------| +| fieldForm1 | 文本数字 | a-input, a-input-number, jnpf-date-picker | +| fieldForm2 | 选择树 | radio, checkbox, jnpf-select, jnpf-tree-select, cascader | +| fieldForm3 | 上传 | jnpf-upload-file, jnpf-upload-img | +| fieldForm4 | 字段联动 | watch, computed | +| fieldForm5 | 字段联动 | 联动场景 | +| fieldForm6 | 字段联动 | 联动场景 | +| verifyForm | 验证规则 | dataRule, pattern, validator | +| verifyForm1 | 验证规则 | 更多验证示例 | + +--- + +## 图表模式 (graphDemo) + +| 目录 | 说明 | 关键特性 | +|------|------|----------| +| echartsBar | 柱状图 | markPoint, markLine, magicType | +| echartsBarAcross | 横向柱状图 | horizontal bar | +| echartsLineArea | 折线面积图 | areaStyle, stack | +| echartsLineBar | 折线柱状图 | yAxis[], 多系列 | +| echartsPie | 饼图 | radius, center, label | +| echartsScatter | 散点图 | symbolSize, scale | +| echartsCandlestick | K线图 | candlestick data | +| echartsFunnel | 漏斗图 | funnel series | +| echartsGauge | 仪表盘 | gauge, progress, timer | +| echartsTree | 树图 | tree data, orient | + +--- + +## 功能扩展 + +| 目录 | 说明 | 关键特性 | +|------|------|----------| +| barCode | 条码/二维码 | JsBarcode, qrcode, canvas | +| bigData | 大数据表格 | 10000+数据, VxeTable | +| documentPreview | 文档预览 | 本地/在线预览切换 | +| email | 邮件系统 | useVxeTable, useModal, usePopup | +| importAndExport | 导入导出 | openExportModal, openImportModal | +| map | 地图 | AMapLoader, AMap | +| order | 订单管理 | FlowParser, expandConfig, lazy | +| projectGantt | 项目甘特图 | 进度展示, avatar | +| saleOrder | 销售订单 | 主从表, rowClick | +| signature | 电子签章 | ESign, generate | +| signet | 可拖拽印章 | Vue3DraggableResizable | + +--- + +## 关键组件索引 + +### 表格组件 + +| 组件 | 用途 | +|------|------| +| BasicVxeTable | 增强表格 | +| BasicLeftTree | 左侧树 | +| TableAction | 表格操作按钮 | +| VxeGrid | 嵌套表格 | + +### 表单组件 + +| 组件 | 用途 | +|------|------| +| BasicForm | 增强表单 | +| useForm | 表单 Hook | + +### 弹窗组件 + +| 组件 | 用途 | +|------|------| +| useModal | 模态框 | +| usePopup | 弹出框 | + +### 图表组件 + +| 组件 | 用途 | +|------|------| +| EchartsUI | ECharts 封装 | +| useEcharts | ECharts Hook | + +### 特殊组件 + +| 组件 | 用途 | +|------|------| +| ESign | 电子签章 | +| Vue3DraggableResizable | 可拖拽容器 | +| ScrollContainer | 滚动容器 | + +--- + +## 常用 API 模式 + +### HTTP 请求 + +```typescript +import { defHttp } from '@/api/request'; + +enum Api { + Prefix = '/api/extend/ResourceName' +} + +export function getList(data) { + return defHttp.get({ url: Api.Prefix, data }); +} + +export function create(data) { + return defHttp.post({ url: Api.Prefix, data }); +} + +export function update(data) { + return defHttp.put({ url: `${Api.Prefix}/${data.id}`, data }); +} + +export function del(id) { + return defHttp.delete({ url: `${Api.Prefix}/${id}` }); +} +``` + +### 数据字典 + +```typescript +import { useBaseStore } from '@/store'; + +const baseStore = useBaseStore(); +const options = (await baseStore.getDictionaryData('DictionaryCode')) as any[]; +``` + +--- + +## 通用类型定义 + +### 表格列 + +```typescript +interface BasicColumn { + title: string; // 列标题 + dataIndex: string; // 数据字段 + width?: number; // 固定宽度 + minWidth?: number; // 最小宽度 + fixed?: 'left' | 'right'; // 锁定列 + align?: 'center' | 'left' | 'right'; + type?: 'seq' | 'checkbox' | 'radio'; + format?: string; // 格式化 + slots?: { default?: string }; // 插槽 + children?: BasicColumn[]; // 复杂表头 +} +``` + +--- + +## 快速参考 + +### 创建通用表格 + +```typescript +const [registerTable, { reload, deleteTableDataRecord }] = useVxeTable({ + api: getList, + columns, + useSearchForm: true, + formConfig: { schemas: searchSchemas }, + actionColumn: { width: 100, title: '操作', dataIndex: 'action' } +}); +``` + +### 创建图表 + +```typescript +const chartRef = ref(); +const { renderEcharts } = useEcharts(chartRef); + +onMounted(() => { + renderEcharts(options); +}); +``` + +### 创建验证规则 + +```typescript +const dataRule = { + field: [ + { required: true, message: '不能为空', trigger: 'blur' }, + { pattern: /正则/, message: '格式错误', trigger: 'blur' } + ] +}; +``` diff --git a/docs/control/12-examples/workSystem-examples.md b/docs/control/12-examples/workSystem-examples.md new file mode 100644 index 0000000..3e13ede --- /dev/null +++ b/docs/control/12-examples/workSystem-examples.md @@ -0,0 +1,152 @@ +# workSystem 示例索引 + +## 系统信息 + +| 属性 | 值 | +|------|-----| +| App-Code | workSystem | +| System-ID | 664077319056394182 | +| 表单数量 | 60 | +| 平台地址 | http://localhost:30000 | + +## 完整表单清单 + +| # | 表单ID | 名称 | 英文编码 | 状态 | 主要控件 | +|---|--------|------|---------|------|----------| +| 1 | 797473600809468485 | 信贷信息 | xdxx | 已发布 | input, inputNumber | +| 2 | 797460178185224773 | 油耗计算 | yhjs | 已发布 | input, inputNumber, select | +| 3 | 797444600007492165 | 二维码、条形码多组件值联动展示 | ewm | 已发布 | input, inputNumber, qrcode | +| 4 | 797436740041179717 | 跨应用访问 | kyyfw | 已发布 | relationForm | +| 5 | 797382749911515717 | 纵向卡片表格 | zxkpbg | 已发布 | datePicker, input, inputNumber, select, textarea, uploadImg | +| 6 | 797381799859716677 | 横向卡片表格 | kpbg | 已发布 | datePicker, input, inputNumber, select, textarea, uploadImg | +| 7 | 797378890455581253 | 表单规则 | bdgz | 已发布 | carousel, input, inputNumber, select | +| 8 | 797103633685545477 | 页签管理 | yqgl | 已发布 | input | +| 9 | 624164673918337925 | 员工培训 | yuangongpx | 已发布 | datePicker, input, organizeSelect, select, textarea, userSelect | +| 10 | 624163990351643525 | 入职申请 | ruzhishenq | 已发布 | datePicker, divider, input, organizeSelect, textarea, userSelect | +| 11 | 623425065425305605 | 劳动合同续签 | renewal | 已发布 | datePicker, input, organizeSelect, uploadFile, userSelect | +| 12 | 623417538411233285 | 离职交接表 | leaveoffice | 已发布 | datePicker, groupTitle, input, organizeSelect, textarea, uploadFile, userSelect | +| 13 | 623183958128984261 | 离职员工表 | lzyuang | 已发布 | datePicker, input, organizeSelect, textarea, userSelect | +| 14 | 623163913990570181 | 员工信息 | staffinform | 已发布 | datePicker, input, organizeSelect, textarea, userSelect | +| 15 | 623163301152424133 | 离职申请 | lizhishenq | 已发布 | datePicker, input, organizeSelect, radio, textarea, userSelect | +| 16 | 585825534638818437 | 列表标签面板 | lbbq | 已发布 | input, inputNumber, select, textarea | +| 17 | 585824111083652229 | 列表行内编辑 | hnbj | 已发布 | datePicker, input, inputNumber, organizeSelect, userSelect | +| 18 | 585806182086608005 | 列表左侧树 | zcs | 已发布 | input, organizeSelect | +| 19 | 585448937427567365 | 多语言采购申请 | dyy | 已发布 | datePicker, input, inputNumber, organizeSelect, userSelect | +| 20 | 585441013829468933 | 采购申请 | ProcurementReq | 已发布 | datePicker, input, inputNumber, organizeSelect, userSelect | +| 21 | 585436888639210245 | 物资申请 | materiaapply | 已发布 | datePicker, divider, input, inputNumber, organizeSelect, radio, textarea, userSelect | +| 22 | 585436444760212229 | 代码对比 | dmdb | 已发布 | datePicker, input, inputNumber, organizeSelect, textarea, userSelect | +| 23 | 585398402720727621 | 付款申请 | paymentapply | 已发布 | datePicker, input, inputNumber, organizeSelect, textarea, userSelect | +| 24 | 585384793399624261 | 套打示例 | tdsl | 已发布 | billRule, datePicker, divider, input, inputNumber, select, sign | +| 25 | 585110234985398597 | 水电费用 | shuidain | 已发布 | calculate, input, table | +| 26 | 585107422926864709 | 报价信息 | baojiainfo | 已发布 | input, table | +| 27 | 585101489710563653 | 个人信息 | gerenxinxi | 已发布 | datePicker, input, radio, select, table | +| 28 | 585077579715707205 | 采购合同 | caigouhetong | 已发布 | billRule, calculate, datePicker, input, select, table, userSelect | +| 29 | 515140323182118341 | 视图查询 | stcx | 已发布 | 纯列表视图,无表单控件 | +| 30 | 470940954832929285 | 官网jnpf案例信息 | cc | 已发布 | 纯列表视图,无表单控件 | +| 31 | 470929822571299333 | 客户管理记录表(集成助手) | khgljlb | 已发布 | input | +| 32 | 470913011435962821 | 集成助手写入数据表 | zc | 已发布 | input | +| 33 | 469500336084679173 | 数据接口调用字段示例 | 2432 | 已发布 | autoComplete, cascader, checkbox, input, popupAttr, popupSelect, popupTableSelect, radio, select, treeSelect | +| 34 | 469499301635095045 | 高级控件和默认查询 | 0809 | 已发布 | tab, table | +| 35 | 469496902811974149 | 复杂表头(主子表)示例 | 095656 | 已发布 | table, tableGrid | +| 36 | 359757745991204532 | 订单示例 | crmOrder | 已发布 | 工作流表单 | +| 37 | 1589964488616407041 | 请假申请 | leaveApply | 已发布 | 工作流表单 | +| 38 | 1589960344887267330 | 销售订单 | salesOrder | 已发布 | 工作流表单 | +| 39 | 469139004097359749 | 行政区划联动 | xzqhld | 已发布 | select | +| 40 | 469136940843723909 | 表单自定义按钮及多打印模板示例 | zdydy | 已发布 | input, textarea | +| 41 | 469136286624574597 | 列表树形表格 | lbsx | 已发布 | input, treeSelect | +| 42 | 469135870243433605 | 视图示例 | stsl | 已发布 | 纯列表视图,无表单控件 | +| 43 | 469133201755925637 | 订单示例 | crmOrderceshi | 已发布 | billRule, createUser, datePicker, input, inputNumber, select, tab, textarea, uploadFile, userSelect | +| 44 | 469106304141552773 | 采购管理 | caigouguanli | 已发布 | billRule, groupTitle, input, organizeSelect, select, table, uploadFile, userSelect | +| 45 | 469102214628043141 | 客户管理 | kehuguanli | 已发布 | billRule, input, table, textarea | +| 46 | 469100392253286789 | 预算管理 | yusuanguanli | 已发布 | createTime, createUser, datePicker, groupTitle, inputNumber, organizeSelect, textarea | +| 47 | 469066996185622917 | 出差管理 | chuchaiguanli | 已发布 | createTime, createUser, currOrganize, datePicker, groupTitle, table, userSelect | +| 48 | 469065268790880645 | 事件管理 | shijianguanli | 已发布 | datePicker, groupTitle, input, select, textarea, uploadFile, userSelect | +| 49 | 469062048563652997 | 设备巡检管理 | shebeiguanli | 已发布 | createTime, createUser, input, modifyTime, table, uploadImg, userSelect | +| 50 | 469059874144184709 | OKR管理 | pcokrguanli | 已发布 | input, organizeSelect, select, table, userSelect | +| 51 | 469052057282734469 | 工资条管理 | gongzitiaoguanli | 已发布 | currOrganize, input, inputNumber, textarea | +| 52 | 469050754464803205 | 隔离管控 | geliguankong | 已发布 | areaSelect, datePicker, input, radio, select, textarea | +| 53 | 469047177461688709 | 人才管理 | rencaiguanli | 已发布 | groupTitle, input, inputNumber, radio, select, table, textarea, uploadFile | +| 54 | 469040281883306373 | 用车管理 | nianjiaguanli | 已发布 | billRule, datePicker, groupTitle, textarea, userSelect | +| 55 | 469039386000943493 | 产品管理 | chanpinguanli | 已发布 | billRule, createTime, createUser, groupTitle, input, inputNumber, modifyTime, select, textarea, uploadImg | +| 56 | 469038006062344581 | 核酸检测 | hesuanjiancedengji | 已发布 | billRule, datePicker, groupTitle, input, select, uploadFile | +| 57 | 468849844170057541 | 药房管理 | yaofangguanli | 已发布 | billRule, datePicker, groupTitle, input, radio | +| 58 | 468848215723140933 | 报名管理外链 | baomingguanli | 已发布 | datePicker, groupTitle, input, select, table | +| 59 | 468842471892247429 | 大客户信息 | testcustomer | 已发布 | areaSelect, input, organizeSelect, select | +| 60 | 468826463014018501 | 应收费用 | testreceivable | 已发布 | billRule, input, table | + +--- + +## 控件与示例对照 + +### 输入类控件 + +| 控件 | 示例表单 | +|------|----------| +| input | 几乎所有表单 | +| textarea | #9, #10, #12, #13, #14, #15, #16, #21, #22, #23 | +| inputNumber | #1, #2, #3, #5, #6, #7, #16, #17, #19, #20, #21, #22, #23, #24 | + +### 选择类控件 + +| 控件 | 示例表单 | +|------|----------| +| select | #2, #5, #6, #7, #9, #16, #21, #24, #27, #33, #39, #43, #44, #45, #50, #52, #53, #56, #57, #58, #59 | +| radio | #15, #21, #33, #52, #53, #57 | +| checkbox | #33 | +| cascader | #33 | +| treeSelect | #33, #41 | +| organizeSelect | #9, #10, #11, #12, #13, #14, #15, #17, #18, #19, #20, #21, #22, #23, #44, #46, #50, #59 | +| userSelect | #9, #10, #11, #12, #13, #14, #15, #17, #19, #20, #21, #22, #23, #28, #43, #44, #47, #48, #49, #50, #54 | + +### 日期时间控件 + +| 控件 | 示例表单 | +|------|----------| +| datePicker | #5, #6, #9, #10, #11, #12, #13, #14, #15, #17, #19, #20, #21, #22, #23, #24, #25, #27, #28, #43, #46, #47, #48, #49, #52, #54, #55, #56, #57, #58, #59 | + +### 上传控件 + +| 控件 | 示例表单 | +|------|----------| +| uploadImg | #5, #6, #49, #55 | +| uploadFile | #11, #12, #21, #23, #28, #43, #44, #48, #53, #56 | + +### 布局控件 + +| 控件 | 示例表单 | +|------|----------| +| divider | #10, #21, #24 | +| groupTitle | #12, #44, #46, #47, #48, #49, #53, #54, #55, #56, #57, #58 | +| tab | #34, #43 | +| carousel | #7 | +| billRule | #24, #28, #43, #44, #45, #54, #55, #56, #57, #60 | +| calculate | #25, #28 | + +### 弹窗控件 + +| 控件 | 示例表单 | +|------|----------| +| popupTable | #33 | +| popupSelect | #33 | +| popupAttr | #33 | +| relationForm | #4 | + +### 系统控件 + +| 控件 | 示例表单 | +|------|----------| +| createUser | #43, #46, #47, #49, #55 | +| createTime | #46, #47, #49, #55 | +| modifyTime | #49, #55 | +| currOrganize | #47, #51 | +| areaSelect | #52, #59 | + +### 特殊控件 + +| 控件 | 示例表单 | +|------|----------| +| qrcode | #3 | +| sign | #24 | +| autoComplete | #33 | +| table | #25, #26, #27, #28, #34, #35, #43, #44, #45, #47, #49, #50, #58, #60 | +| tableGrid | #35 | diff --git a/docs/control/13-mobile-controls.md b/docs/control/13-mobile-controls.md new file mode 100644 index 0000000..4605fc3 --- /dev/null +++ b/docs/control/13-mobile-controls.md @@ -0,0 +1,298 @@ +# 移动端控件 + +## 目录 + +- [概述](#概述) +- [移动端组件清单](#移动端组件清单) +- [f_app_column_data 解析](#f_app_column_data-解析) +- [PC端与移动端差异](#pc端与移动端差异) + +--- + +## 概述 + +### 源码位置 + +``` +$ccWorkDir/jnpf/移动端/jnpf-app-vue3/components/Jnpf/ +``` + +### 组件数量 + +共 **55 个** Jnpf 组件,涵盖输入、选择、日期、上传、特殊功能等类别。 + +--- + +## 移动端组件清单 + +### 输入类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| Input | Input/ | 单行文本输入 | +| InputNumber | InputNumber/ | 数字输入 | +| Textarea | Textarea/ | 多行文本输入 | + +### 选择类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| Select | Select/ | 下拉选择 | +| Radio | Radio/ | 单选 | +| Checkbox | Checkbox/ | 多选 | +| TreeSelect | TreeSelect/ | 树形选择 | +| Cascader | Cascader/ | 级联选择 | +| OrganizeSelect | OrganizeSelect/ | 组织选择 | +| UserSelect | UserSelect/ | 用户选择 | +| UsersSelect | UsersSelect/ | 多用户选择 | +| RoleSelect | RoleSelect/ | 角色选择 | +| GroupSelect | GroupSelect/ | 分组选择 | +| AreaSelect | AreaSelect/ | 区域选择 | +| PosSelect | PosSelect/ | 职位选择 | +| MultSelect | MultSelect/ | 多选 | + +### 日期时间类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| DatePicker | DatePicker/ | 日期选择 | +| TimePicker | TimePicker/ | 时间选择 | +| DateRange | DateRange/ | 日期范围 | +| TimeRange | TimeRange/ | 时间范围 | +| NumberRange | NumberRange/ | 数字范围 | + +### 上传类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| UploadImg | UploadImg/ | 图片上传 | +| UploadFile | UploadFile/ | 文件上传 | +| UploadFileH | UploadFileH/ | H5文件上传 | +| UploadFileComment | UploadFileComment/ | 评论文件上传 | + +### 特殊功能类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| Switch | Switch/ | 开关 | +| Slider | Slider/ | 滑块 | +| Rate | Rate/ | 评分 | +| ColorPicker | ColorPicker/ | 颜色选择 | +| Steps | Steps/ | 步骤 | +| Signature | Signature/ | 电子签名 | +| Sign | Sign/ | 签章 | +| Barcode | Barcode/ | 条形码 | +| Qrcode | Qrcode/ | 二维码 | +| Ocr | Ocr/ | OCR识别 | +| Location | Location/ | 定位 | +| Link | Link/ | 链接 | +| Alert | Alert/ | 警告提示 | +| Text | Text/ | 文本显示 | +| Button | Button/ | 按钮 | +| Empty | Empty/ | 空状态 | +| Divider | Divider/ | 分隔线 | +| GroupTitle | GroupTitle/ | 分组标题 | +| Carousel | Carousel/ | 轮播 | +| Editor | Editor/ | 富文本编辑器 | + +### 弹窗类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| PopupSelect | PopupSelect/ | 弹窗选择 | +| PopupAttr | PopupAttr/ | 弹窗属性 | +| RelationForm | RelationForm/ | 关联表单 | +| RelationFormAttr | RelationFormAttr/ | 关联表单属性 | +| Parser | Parser/ | 解析器 | +| ChildTable | Parser/childTable.vue | 子表格 | + +### 计算类 + +| 组件 | 目录 | 说明 | +|------|------|------| +| Calculate | Calculate/ | 计算 | +| DateCalculate | DateCalculate/ | 日期计算 | + +--- + +## f_app_column_data 解析 + +### 基本概念 + +`f_app_column_data` 是 JNPF 移动端动态表单配置的 JSON 字段,用于定义移动端表单的渲染规则。 + +### 数据库字段 + +| 字段 | 说明 | +|------|------| +| f_app_column_data | 移动端表单列配置 (JSON) | +| f_app_form_data | 移动端表单数据配置 (JSON) | + +### 配置结构 + +```json +{ + "columnData": [ + { + "column": "f_customer_name", + "component": "Input", + "props": { + "placeholder": "请输入客户名称", + "disabled": false + } + }, + { + "column": "f_status", + "component": "Select", + "props": { + "placeholder": "请选择状态", + "options": [ + {"label": "启用", "value": "1"}, + {"label": "禁用", "value": "0"} + ] + } + } + ] +} +``` + +### 组件映射 + +| PC 控件 | 移动端组件 | 说明 | +|---------|------------|------| +| input | Input | 单行文本 | +| textarea | Textarea | 多行文本 | +| inputNumber | InputNumber | 数字输入 | +| select | Select | 下拉选择 | +| radio | Radio | 单选 | +| checkbox | Checkbox | 多选 | +| date | DatePicker | 日期选择 | +| datetime | DatePicker | 日期时间 | +| time | TimePicker | 时间选择 | +| switch | Switch | 开关 | +| uploadImg | UploadImg | 图片上传 | +| uploadFile | UploadFile | 文件上传 | +| treeSelect | TreeSelect | 树形选择 | +| cascader | Cascader | 级联选择 | +| organizeSelect | OrganizeSelect | 组织选择 | +| userSelect | UserSelect | 用户选择 | + +### Props 传递 + +移动端组件通过 `props` 对象传递配置: + +```json +{ + "column": "f_field_name", + "component": "ComponentName", + "props": { + "placeholder": "提示文本", + "disabled": false, + "clearable": true, + "multiple": false + } +} +``` + +--- + +## PC端与移动端差异 + +### 组件命名差异 + +| PC jnpfKey | 移动端组件 | +|------------|-----------| +| input | Input | +| textarea | Textarea | +| inputNumber | InputNumber | +| select | Select | +| datePicker | DatePicker | +| time | TimePicker | +| uploadImg | UploadImg | +| uploadFile | UploadFile | + +### 特有移动端控件 + +以下控件**仅移动端**可用: + +| 组件 | 说明 | +|------|------| +| Location | GPS定位 | +| Ocr | OCR文字识别 | +| Steps | 步骤指示器 | +| NumberRange | 数字范围选择 | +| DateRange | 日期范围选择 | +| TimeRange | 时间范围选择 | +| UploadFileH | H5文件上传 (跨平台) | +| UploadFileComment | 评论文件上传 | + +### 表单配置差异 + +| 特性 | PC端 | 移动端 | +|------|------|--------| +| 配置字段 | formData | f_app_column_data | +| 列表配置 | columnData | f_app_column_data | +| 默认值 | __config__.defaultValue | props.defaultValue | +| 必填校验 | __config__.required | rules.required | +| 禁用状态 | disabled | props.disabled | + +--- + +## 使用示例 + +### 移动端表单配置 + +```json +{ + "f_app_column_data": "{\"columnData\":[{\"column\":\"f_customer_name\",\"component\":\"Input\",\"props\":{\"placeholder\":\"请输入客户名称\"}},{\"column\":\"f_order_date\",\"component\":\"DatePicker\",\"props\":{\"format\":\"YYYY-MM-DD\"}},{\"column\":\"f_status\",\"component\":\"Select\",\"props\":{\"placeholder\":\"请选择状态\",\"options\":[{\"label\":\"启用\",\"value\":\"1\"},{\"label\":\"禁用\",\"value\":\"0\"}]}}]}" +} +``` + +### 移动端组件使用 + +```vue + + + +``` + +--- + +## 下一步 + +- [PC端控件速查](01-quick-ref.md) +- [workSystem 示例](12-examples/workSystem-examples.md) +- [extend 代码示例](12-examples/extend-examples.md) diff --git a/docs/control/README.md b/docs/control/README.md new file mode 100644 index 0000000..50d2fab --- /dev/null +++ b/docs/control/README.md @@ -0,0 +1,190 @@ +# JNPF 控件使用文档 + +## 文档概述 + +本目录收录 JNPF 低代码平台全部控件的使用文档,包含快速查询、详细配置说明、示例参考等内容。 + +## 文档索引 + +### 入门 + +| 文档 | 说明 | +|------|------| +| [01-quick-ref.md](01-quick-ref.md) | **控件快速使用速查** - 表格形式速查所有控件 | +| [控件完整清单](#控件完整清单) | 按类别整理的控件速查表 | + +### 控件详细文档 + +| 文档 | 说明 | 包含控件 | +|------|------|----------| +| [02-input-controls.md](02-input-controls.md) | 输入类控件 | input, textarea, inputNumber | +| [03-select-controls.md](03-select-controls.md) | 选择类控件 | select, radio, checkbox, cascader, treeSelect, organizeSelect, userSelect | +| [04-date-controls.md](04-date-controls.md) | 日期时间控件 | date, datetime, time | +| [05-upload-controls.md](05-upload-controls.md) | 上传控件 | uploadImg, uploadFile | +| [06-popup-controls.md](06-popup-controls.md) | 弹窗控件 | popupTable, popupSelect, popupAttr, relationForm | +| [07-table-controls.md](07-table-controls.md) | 子表格控件 | table, tableGrid | +| [08-special-controls.md](08-special-controls.md) | 特殊控件 | switch, rate, colorPicker, sign, qrcode, divider, groupTitle, tab, carousel, billRule, calculate, autoComplete | +| [09-chart-controls.md](09-chart-controls.md) | 图表控件 | 10种 ECharts 图表 | +| [13-mobile-controls.md](13-mobile-controls.md) | 移动端控件 | 55个移动端组件, f_app_column_data | + +### 高级模式 + +| 文档 | 说明 | +|------|------| +| [10-table-patterns.md](10-table-patterns.md) | **表格高级模式** - 13种表格模式详解 | +| [11-form-patterns.md](11-form-patterns.md) | **表单高级模式** - 验证规则、字段联动、打印模板 | + +### 示例参考 + +| 文档 | 说明 | +|------|------| +| [12-examples/workSystem-examples.md](12-examples/workSystem-examples.md) | **workSystem 示例** - 60个表单完整索引 | +| [12-examples/extend-examples.md](12-examples/extend-examples.md) | **extend 示例** - 代码示例完整索引 | + +--- + +## 控件完整清单 + +### 输入类 (3) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 单行文本 | `input` | [02-input-controls.md](02-input-controls.md) | +| 多行文本 | `textarea` | [02-input-controls.md](02-input-controls.md) | +| 数字输入 | `inputNumber` | [02-input-controls.md](02-input-controls.md) | + +### 选择类 (7) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 下拉选择 | `select` | [03-select-controls.md](03-select-controls.md) | +| 单选组 | `radio` | [03-select-controls.md](03-select-controls.md) | +| 多选组 | `checkbox` | [03-select-controls.md](03-select-controls.md) | +| 级联选择 | `cascader` | [03-select-controls.md](03-select-controls.md) | +| 树形选择 | `treeSelect` | [03-select-controls.md](03-select-controls.md) | +| 组织选择 | `organizeSelect` | [03-select-controls.md](03-select-controls.md) | +| 用户选择 | `userSelect` | [03-select-controls.md](03-select-controls.md) | + +### 日期时间类 (3) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 日期选择 | `date` | [04-date-controls.md](04-date-controls.md) | +| 日期时间 | `datetime` | [04-date-controls.md](04-date-controls.md) | +| 时间选择 | `time` | [04-date-controls.md](04-date-controls.md) | + +### 上传类 (2) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 图片上传 | `uploadImg` | [05-upload-controls.md](05-upload-controls.md) | +| 文件上传 | `uploadFile` | [05-upload-controls.md](05-upload-controls.md) | + +### 弹窗类 (4) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 弹窗表格 | `popupTable` | [06-popup-controls.md](06-popup-controls.md) | +| 弹窗选择 | `popupSelect` | [06-popup-controls.md](06-popup-controls.md) | +| 弹窗属性 | `popupAttr` | [06-popup-controls.md](06-popup-controls.md) | +| 关联表单 | `relationForm` | [06-popup-controls.md](06-popup-controls.md) | + +### 布局类 (6) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 分隔线 | `divider` | [08-special-controls.md](08-special-controls.md) | +| 分组标题 | `groupTitle` | [08-special-controls.md](08-special-controls.md) | +| 页签 | `tab` | [08-special-controls.md](08-special-controls.md) | +| 轮播 | `carousel` | [08-special-controls.md](08-special-controls.md) | +| 子表格 | `table` | [07-table-controls.md](07-table-controls.md) | +| 表格网格 | `tableGrid` | [07-table-controls.md](07-table-controls.md) | + +### 特殊功能类 (12) + +| 控件 | jnpfKey | 文档 | +|------|---------|------| +| 开关 | `switch` | [08-special-controls.md](08-special-controls.md) | +| 评分 | `rate` | [08-special-controls.md](08-special-controls.md) | +| 颜色选择 | `colorPicker` | [08-special-controls.md](08-special-controls.md) | +| 二维码 | `qrcode` | [08-special-controls.md](08-special-controls.md) | +| 签章 | `sign` | [08-special-controls.md](08-special-controls.md) | +| 单据规则 | `billRule` | [08-special-controls.md](08-special-controls.md) | +| 计算 | `calculate` | [08-special-controls.md](08-special-controls.md) | +| 自动完成 | `autoComplete` | [08-special-controls.md](08-special-controls.md) | +| 创建用户 | `createUser` | [08-special-controls.md](08-special-controls.md) | +| 创建时间 | `createTime` | [08-special-controls.md](08-special-controls.md) | +| 修改时间 | `modifyTime` | [08-special-controls.md](08-special-controls.md) | +| 区域选择 | `areaSelect` | [08-special-controls.md](08-special-controls.md) | + +### 图表类 (10) + +| 图表 | 类型 | 文档 | +|------|------|------| +| 柱状图 | Bar | [09-chart-controls.md](09-chart-controls.md) | +| 横向柱状图 | BarAcross | [09-chart-controls.md](09-chart-controls.md) | +| 折线面积图 | LineArea | [09-chart-controls.md](09-chart-controls.md) | +| 折线柱状图 | LineBar | [09-chart-controls.md](09-chart-controls.md) | +| 饼图 | Pie | [09-chart-controls.md](09-chart-controls.md) | +| 散点图 | Scatter | [09-chart-controls.md](09-chart-controls.md) | +| K线图 | Candlestick | [09-chart-controls.md](09-chart-controls.md) | +| 漏斗图 | Funnel | [09-chart-controls.md](09-chart-controls.md) | +| 仪表盘 | Gauge | [09-chart-controls.md](09-chart-controls.md) | +| 树图 | Tree | [09-chart-controls.md](09-chart-controls.md) | + +--- + +## AIBridge 支持 + +AIBridge 提供 `build_field_model()` 和 `build_table_field_model()` 方法快速构建控件配置: + +```python +from aibridge.builders.field_model import build_field_model + +# 文本输入 +field = build_field_model( + field_name="客户名称", + field_vmodel="f_customer_name", + jnpf_key="input", + required=True +) + +# 下拉选择 (注意 options 格式) +field = build_field_model( + field_name="状态", + field_vmodel="f_status", + jnpf_key="select", + options=[ + {"fullName": "启用", "id": "1"}, + {"fullName": "禁用", "id": "0"}, + ] +) +``` + +详见 [AIBridge 文档](../README.md) 和 [快速入门](../docs/quickstart.md)。 + +--- + +## 示例系统 + +### workSystem (示例系统) + +| 属性 | 值 | +|------|-----| +| App-Code | workSystem | +| System-ID | 664077319056394182 | +| 表单数量 | 60 | +| 特点 | 包含几乎所有控件类型的完整示例 | + +详见 [workSystem-examples.md](12-examples/workSystem-examples.md) + +### extend (代码示例) + +| 目录 | 说明 | +|------|------| +| tableDemo/ | 13种表格模式 | +| formDemo/ | 8种表单模式 | +| graphDemo/ | 10种图表示例 | +| 其他 | barCode, bigData, email, map 等 | + +详见 [extend-examples.md](12-examples/extend-examples.md) diff --git a/docs/control/component_storage_results.json b/docs/control/component_storage_results.json new file mode 100644 index 0000000..c16632e --- /dev/null +++ b/docs/control/component_storage_results.json @@ -0,0 +1,199 @@ +[ + { + "component": "单行文本", + "jnpfKey": "input", + "fieldName": "f_input", + "testValue": "测试文本ABC123", + "testValueType": "str", + "storedValue": "测试文本ABC123", + "storedType": "str", + "pattern": "字符串直接存储" + }, + { + "component": "多行文本", + "jnpfKey": "textarea", + "fieldName": "f_textarea", + "testValue": "第一行\n第二行\n第三行", + "testValueType": "str", + "storedValue": "第一行\n第二行\n第三行", + "storedType": "str", + "pattern": "字符串直接存储" + }, + { + "component": "数字输入", + "jnpfKey": "inputNumber", + "fieldName": "f_inputNumber", + "testValue": 12345.67, + "testValueType": "float", + "storedValue": "12345.67", + "storedType": "str", + "pattern": "数值或字符串存储(取决于precision)" + }, + { + "component": "下拉选择", + "jnpfKey": "select", + "fieldName": "f_select", + "testValue": "2", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "选项id字符串存储(如\"2\")" + }, + { + "component": "单选组", + "jnpfKey": "radio", + "fieldName": "f_radio", + "testValue": "1", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "选项id字符串存储(如\"1\")" + }, + { + "component": "多选组", + "jnpfKey": "checkbox", + "fieldName": "f_checkbox", + "testValue": [ + "1", + "3" + ], + "testValueType": "list", + "storedValue": null, + "storedType": "NoneType", + "pattern": "选项id数组JSON序列化存储(如[\"1\",\"3\"])" + }, + { + "component": "日期选择", + "jnpfKey": "datePicker", + "fieldName": "f_date", + "testValue": "2026-04-07", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "日期字符串存储(如\"2026-04-07\")" + }, + { + "component": "时间选择", + "jnpfKey": "timePicker", + "fieldName": "f_time", + "testValue": "14:30:00", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "时间字符串存储(如\"14:30:00\")" + }, + { + "component": "日期时间", + "jnpfKey": "datePicker", + "fieldName": "f_datetime", + "testValue": "2026-04-07 14:30:00", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "日期时间字符串存储(如\"2026-04-07 14:30:00\")" + }, + { + "component": "开关", + "jnpfKey": "switch", + "fieldName": "f_switch", + "testValue": 1, + "testValueType": "int", + "storedValue": null, + "storedType": "NoneType", + "pattern": "整数存储(1/0),activeValue/inactiveValue决定" + }, + { + "component": "评分", + "jnpfKey": "rate", + "fieldName": "f_rate", + "testValue": 4, + "testValueType": "int", + "storedValue": null, + "storedType": "NoneType", + "pattern": "整数存储(如4)" + }, + { + "component": "滑块", + "jnpfKey": "slider", + "fieldName": "f_slider", + "testValue": 50, + "testValueType": "int", + "storedValue": null, + "storedType": "NoneType", + "pattern": "整数或字符串存储" + }, + { + "component": "颜色选择", + "jnpfKey": "colorPicker", + "fieldName": "f_colorPicker", + "testValue": "#1890ff", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "颜色值字符串存储(如\"#1890ff\")" + }, + { + "component": "图片上传", + "jnpfKey": "uploadImg", + "fieldName": "f_uploadImg", + "testValue": "/upload/20260407/test.jpg", + "testValueType": "str", + "storedValue": [], + "storedType": "list", + "pattern": "文件路径字符串存储" + }, + { + "component": "文件上传", + "jnpfKey": "uploadFile", + "fieldName": "f_uploadFile", + "testValue": "/upload/20260407/test.pdf", + "testValueType": "str", + "storedValue": [], + "storedType": "list", + "pattern": "文件路径字符串存储" + }, + { + "component": "树形选择", + "jnpfKey": "treeSelect", + "fieldName": "f_treeSelect", + "testValue": "1-1", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "节点id字符串存储(如\"1-1\")" + }, + { + "component": "级联选择", + "jnpfKey": "cascader", + "fieldName": "f_cascader", + "testValue": [ + "44", + "4403", + "440305" + ], + "testValueType": "list", + "storedValue": null, + "storedType": "NoneType", + "pattern": "节点id数组JSON序列化存储(如[\"44\",\"4403\",\"440305\"])" + }, + { + "component": "用户选择", + "jnpfKey": "userSelect", + "fieldName": "f_userSelect", + "testValue": "admin", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "用户id或用户名字符串存储" + }, + { + "component": "部门选择", + "jnpfKey": "organizeSelect", + "fieldName": "f_organizeSelect", + "testValue": "1", + "testValueType": "str", + "storedValue": null, + "storedType": "NoneType", + "pattern": "组织id字符串存储" + } +] \ No newline at end of file diff --git a/docs/datainterface/01-basic-rules.md b/docs/datainterface/01-basic-rules.md new file mode 100644 index 0000000..9e7c694 --- /dev/null +++ b/docs/datainterface/01-basic-rules.md @@ -0,0 +1,328 @@ +# 数据接口基础规则 + +## 核心机制 + +### 接口类型 (type) + +| type | 名称 | 说明 | 示例 | +|------|------|------|------| +| 1 | SQL操作 | 执行SQL语句 | SELECT/INSERT/UPDATE/DELETE | +| 2 | 静态数据 | 返回固定JSON | 图表配置、选项列表 | +| 3 | API操作 | 调用HTTP接口 | 第三方API、内部接口 | + +### 动作 (action) + +| action | 名称 | 说明 | +|--------|------|------| +| 1 | 增加 | INSERT | +| 2 | 修改 | UPDATE | +| 3 | 查询 | SELECT | +| 4 | 删除 | DELETE | + +> **注意**: action仅对SQL操作(type=1)有意义。静态数据action=0,API操作action由接口决定。 + +### 分页 (hasPage) + +| 值 | 说明 | +|----|------| +| 0 | 禁用分页,返回全部数据 | +| 1 | 启用分页,需配置分页SQL | + +### 鉴权 (isPostPosition) + +| 值 | 说明 | +|----|------| +| 0 | 普通接口 | +| 1 | 鉴权接口(后置),作为权限验证 | + +> **重要**: isPostPosition必须为0,否则Preview时后端会NPE + +--- + +## 数据配置结构 (dataConfigJson) + +### SQL操作配置 + +```json +{ + "staticData": "", + "sqlData": { + "dbLinkId": "0", + "sql": "SELECT * FROM base_user WHERE f_real_name = {name}" + }, + "apiData": { + "method": 1, + "url": "", + "header": [], + "query": [], + "body": "", + "bodyType": 0 + } +} +``` + +### 静态数据配置 + +```json +{ + "staticData": "[{\"id\":\"1\",\"name\":\"选项1\"},{\"id\":\"2\",\"name\":\"选项2\"}]", + "sqlData": {"dbLinkId": "", "sql": ""}, + "apiData": {"method": 1, "url": "", "header": [], "query": [], "body": "", "bodyType": 0} +} +``` + +### API操作配置 + +```json +{ + "staticData": "", + "sqlData": {"dbLinkId": "", "sql": ""}, + "apiData": { + "method": 1, + "url": "/api/extend/CrmOrder/Goods", + "header": [{"field": "Authorization", "defaultValue": "token", "source": "1"}], + "query": [{"field": "keyword", "defaultValue": "", "source": "1"}], + "body": "", + "bodyType": 0 + } +} +``` + +--- + +## 参数配置 (parameterJson) + +### 参数结构 + +```json +[ + { + "field": "参数名", + "fieldName": "中文名", + "dataType": "varchar|int|datetime|decimal", + "required": 0, + "sourceType": 1, + "defaultValue": "默认值" + } +] +``` + +### sourceType 类型 + +| 值 | 说明 | 行为 | +|----|------|------| +| 1 | 字段 | 使用defaultValue作为参数值 | +| 2 | 自定义 | 使用relationField作为参数值 | +| 3 | 空值 | **推荐使用**:参数值直接替换,最可靠 | +| 4 | 系统参数 | 使用系统变量值 | + +> **重要区别**: +> - `sourceType=1`:受 DI 中配置的 `defaultValue` 影响 +> - `sourceType=3`:**直接使用传入的参数值**,忽略 `defaultValue` +> - AIBridge `execute()` 内部使用 `sourceType=3` + +--- + +## SQL占位符规则 + +### 自定义参数占位符 + +```sql +SELECT * FROM table WHERE field = {参数名} +``` +- `{参数名}` → 替换为 `?` 占位符 +- 通过PreparedStatement安全赋值 + +### 系统变量占位符 + +```sql +SELECT * FROM base_user WHERE f_user_id = {@userId} +``` + +| 系统变量 | 说明 | +|----------|------| +| `{@userId}` | 当前用户ID | +| `{@organizeId}` | 当前组织ID | +| `{@positionId}` | 当前岗位ID | +| `{@snowFlakeID}` | 雪花ID(新增时) | +| `{@lotSnowID}` | 批量雪花ID | +| `{@keyword}` | 关键词搜索 | +| `{@pageSize}` | 每页条数 | +| `{@offsetSize}` | 开始条数 | +| `{@currentPage}` | 当前页码 | + +### 禁止事项 + +⚠️ **SQL中不能有`{}`空字面量**,会被当作参数占位符解析 + +```sql +-- 错误示例 +SELECT * FROM table WHERE json = '{}' + +-- 正确示例 +SELECT * FROM table WHERE json = '''{}''' +``` + +--- + +## 数据库连接 (dbLinkId) + +| 值 | 说明 | +|----|------| +| "0" | 主数据库 | +| 其他ID | 业务数据库连接 | + +> **注意**: 多租户环境下,dbLinkId=0连接主库,部分业务表仅在租户库中 +> +> ⚠️ **dbLinkId 位置**:不是 `dataConfigJson.dbLinkId`,而是 `dataConfigJson.sqlData.dbLinkId` + +```json +{ + "dataConfigJson": { + "sqlData": { + "dbLinkId": "0", // ← 实际位置在 sqlData 子对象中 + "sql": "SELECT ..." + } + } +} +``` + +### 业务表字段命名规律 + +| 表类型 | 字段命名 | 示例 | +|--------|----------|------| +| JNPF系统表 | snake_case | f_id, f_full_name | +| 业务表(VisualDev) | PascalCase | F_Id, F_Company_Name | + +> ⚠️ **重要**: 业务表(如 opportunity_mgmt, mirror_demand 等 VisualDev 创建的表)字段名是大写的 PascalCase,如 `F_Company_Name`,而非 `f_company_name` + +可通过 `SELECT * FROM table LIMIT 1` 查看实际字段名。 + +--- + +## 数据处理 (dataJsJson) + +```javascript +(data) => { + // 处理数据逻辑 + // 返回所需的数据 + return data +} +``` + +--- + +## 异常验证 (dataExceptionJson) + +```javascript +(data) => { + // 返回true表示接口验证成功 + // 返回false表示接口验证失败 + return true +} +``` + +--- + +## 执行流程 + +``` +1. 参数处理 + ├── replaceDefaultVale: 填充默认值(sourceType=1 时) + ├── checkRequestParams: 验证必填和类型 + └── paramSourceTypeReplaceValue: 替换参数值(sourceType=3 时直接用传入值) + +2. 数据获取 + ├── type=1: executeSql → JdbcUtil + ├── type=2: callStaticData → JSON.parse + └── type=3: callHTTP → HttpUtil + +3. 数据处理 + ├── handlePostVariate: 后置变量处理 + └── JScriptUtil.callJs: 执行JS处理脚本 + +4. 返回结果 + └── ActionResult.success(data) +``` + +## execute() vs preview() + +| 特性 | execute() | preview() | +|------|-----------|-----------| +| 参数格式 | `{"key": "value"}` | `{"paramList": [...]}` | +| sourceType | 固定为 3 | 可手动指定 | +| defaultValue | 被忽略 | sourceType=1 时生效 | +| 适用场景 | 需要覆盖默认行为 | 需要使用 DI 默认值 | + +--- + +## AIBridge build_payload + +```python +DataInterfaceAPI.build_payload( + full_name="接口名称", + en_code="接口编码", + sql="SELECT * FROM table WHERE field = {param}", + parameters=[{"field": "param", "fieldName": "参数", "dataType": "varchar", "required": 1, "sourceType": 1}], + category="分类ID", + action=3, + db_link_id="0" +) +``` + +> **关键**: isPostPosition强制设为0,避免后端NPE + +## AIBridge 扩展的增删改方法 + +AIBridge 提供了简化创建增删改 DI 的方法: + +```python +di = DataInterfaceAPI(client) + +# INSERT +insert_payload = di.build_insert_payload( + full_name="新增接口", + en_code="insert_demo", + table_name="base_user", + fields=["f_real_name", "f_account"], + parameters=[ + {"field": "real_name", "fieldName": "姓名", "dataType": "varchar", "required": 1, "sourceType": 1}, + {"field": "account", "fieldName": "账号", "dataType": "varchar", "required": 1, "sourceType": 1}, + ], + category="分类ID" +) +# SQL: INSERT INTO base_user (f_real_name, f_account) VALUES ({real_name}, {account}) + +# UPDATE +update_payload = di.build_update_payload( + full_name="修改接口", + en_code="update_demo", + table_name="base_user", + set_fields=["f_real_name"], + where_field="f_id", + parameters=[...], + category="分类ID" +) +# SQL: UPDATE base_user SET f_real_name = {real_name} WHERE f_id = {id} + +# DELETE +delete_payload = di.build_delete_payload( + full_name="删除接口", + en_code="delete_demo", + table_name="base_user", + where_field="f_id", + parameters=[...], + category="分类ID" +) +# SQL: DELETE FROM base_user WHERE f_id = {id} + +# SELECT (支持分页) +select_payload = di.build_select_payload( + full_name="查询接口", + en_code="select_demo", + sql="SELECT * FROM base_user LIMIT {offset}, {size}", + parameters=[...], + category="分类ID", + has_page=1 +) +``` diff --git a/docs/datainterface/02-sql-operation.md b/docs/datainterface/02-sql-operation.md new file mode 100644 index 0000000..6700ec6 --- /dev/null +++ b/docs/datainterface/02-sql-operation.md @@ -0,0 +1,150 @@ +# SQL操作接口 + +## 基本配置 + +| 字段 | 值 | 说明 | +|------|-----|------| +| type | 1 | SQL操作 | +| action | 3 | 查询(SELECT) | +| hasPage | 0/1 | 是否分页 | +| dbLinkId | "0" | 主库,可指定业务库 | + +## 示例:基础查询 + +```python +# 创建按ID查询用户的接口 +payload = DataInterfaceAPI.build_payload( + full_name="按ID查询用户", + en_code="query_user_by_id", + sql="SELECT * FROM base_user WHERE f_id = {userId}", + parameters=[{ + "field": "userId", + "fieldName": "用户ID", + "dataType": "varchar", + "required": 1, + "sourceType": 1 + }], + category="分类ID", + action=3 +) + +di.create(payload) +result = di.execute(di_id, {"userId": "xxx"}) +``` + +## 示例:带系统变量 + +```sql +-- 查询当前用户信息 +SELECT * FROM base_user WHERE f_id = {@userId} + +-- 查询当前组织及子组织 +SELECT * FROM base_organize WHERE f_id IN ({@organizeId}) +``` + +## 示例:模糊查询 + +```sql +-- 关键词搜索 +SELECT * FROM base_user WHERE f_real_name LIKE CONCAT('%', {@keyword}, '%') + +-- 多字段搜索 +SELECT * FROM base_user +WHERE f_real_name LIKE CONCAT('%', {@keyword}, '%') + OR f_account LIKE CONCAT('%', {@keyword}, '%') +``` + +## 执行增删改 (action=1/2/4) + +```python +# action=1 增加, action=2 修改, action=4 删除 +# 增删改不返回数据,只返回成功/失败 +``` + +> **注意**:action 值不可信!部分 DI 配置为 action=1 但实际执行的是 SELECT 查询。判断 DI 类型应以 SQL 首关键词(SELECT/INSERT/UPDATE/DELETE)为准。 + +payload = DataInterfaceAPI.build_payload( + full_name="删除用户", + en_code="delete_user", + sql="DELETE FROM base_user WHERE f_id = {userId}", + parameters=[...], + category="分类ID", + action=4 # 删除 +) +``` + +## 参考示例 + +| ID | 名称 | SQL特征 | +|-----|------|---------| +| 83ae1f5e5c26447b8c4849ead352b048 | 当前用户 | `WHERE f_id = {@userId}` | +| a0c3186292df4fe2842f66dee0ea7729 | 查询当前组织 | 多表JOIN | +| ebcc44be142e43b795c0d769abd6d25a | 用户列表 | 多表JOIN+条件 | +| 420587863533428357 | 行政区划 | `WHERE f_parent_id = {parentId}` | +| 469125798494792965 | SQL真分页 | `LIMIT` 分页 | + +## AIBridge 快速构建增删改查 + +```python +di = DataInterfaceAPI(client) + +# INSERT 新增 +di_id = di.create_insert_interface( + full_name="新增用户", + en_code="insert_user", + table_name="base_user", + fields=["f_real_name", "f_account"], + parameters=[ + {"field": "real_name", "fieldName": "姓名", "dataType": "varchar", "required": 1, "sourceType": 1}, + {"field": "account", "fieldName": "账号", "dataType": "varchar", "required": 1, "sourceType": 1}, + ], + category="分类ID" +) + +# UPDATE 修改 +di_id = di.create_update_interface( + full_name="修改用户", + en_code="update_user", + table_name="base_user", + set_fields=["f_real_name"], + where_field="f_id", + parameters=[...], + category="分类ID" +) + +# DELETE 删除 +di_id = di.create_delete_interface( + full_name="删除用户", + en_code="delete_user", + table_name="base_user", + where_field="f_id", + parameters=[...], + category="分类ID" +) + +# SELECT 查询(支持分页) +di_id = di.create_select_interface( + full_name="查询用户", + en_code="select_user", + sql="SELECT * FROM base_user LIMIT {offset}, {size}", + parameters=[...], + category="分类ID", + has_page=1 +) +``` + +### 示例1:当前用户查询 +```sql +SELECT f_real_name, f_organize_id +FROM base_user +WHERE f_id = {@userId} +``` + +### 示例2:行政区划(树形) +```sql +SELECT f_id, f_full_name +FROM base_province +WHERE f_parent_id = {parentId} +``` +- 参数: parentId (varchar) +- 用于:省市区三级联动 diff --git a/docs/datainterface/03-static-data.md b/docs/datainterface/03-static-data.md new file mode 100644 index 0000000..c10fa9e --- /dev/null +++ b/docs/datainterface/03-static-data.md @@ -0,0 +1,124 @@ +# 静态数据接口 + +## 基本配置 + +| 字段 | 值 | 说明 | +|------|-----|------| +| type | 2 | 静态数据 | +| action | 0 | 无 | +| staticData | JSON字符串 | 固定数据 | + +## 数据格式 + +### 数组格式 + +```json +[ + {"id": "1", "name": "选项1"}, + {"id": "2", "name": "选项2"} +] +``` + +### 对象格式 + +```json +{ + "categories": ["类别1", "类别2"], + "series": [{"name": "系列1", "data": [120, 200]}] +} +``` + +## 图表静态数据示例 + +### 柱状图 + +```json +{ + "categories": ["苹果品牌", "三星品牌", "小米品牌"], + "series": [ + {"name": "2024年", "data": [335, 310, 234]}, + {"name": "2023年", "data": [502, 534, 763]} + ] +} +``` + +### 折线图 + +```json +{ + "categories": ["苹果", "三星", "小米", "oppo", "vivo"], + "series": [ + {"name": "销量", "data": [235, 189, 156, 208, 133]} + ] +} +``` + +### 饼图 + +```json +{ + "title": {"text": "天气情况统计", "subtext": "虚构数据"}, + "series": [ + {"name": "访问来源", "data": [{"value": 335, "name": "直接访问"}]} + ] +} +``` + +### 雷达图 + +```json +{ + "indicator": [ + {"name": "销售", "max": 6500}, + {"name": "管理", "max": 16000} + ], + "series": [{"data": [{"value": [4300, 10000, 2800, 3500, 5000], "name": "预算分配"}]}] +} +``` + +## 级联选择静态数据 + +```json +[ + { + "id": "d7f26bf6ad224054a6d3276b62eeeb43", + "hasChildren": true, + "fullName": "广东省", + "children": [ + {"id": "child1", "fullName": "广州市", "hasChildren": false} + ] + } +] +``` + +## 参考示例 + +| ID | 名称 | 用途 | +|-----|------|------| +| cd6fe911f90048f0bba7ef9f38251d96 | 柱状图 | 图表配置 | +| be312b18a1664d8787e0dfcd2412969f | 折线图 | 图表配置 | +| 79e5455c2f0d4d8ba2b444249bae0490 | 饼图 | 图表配置 | +| 8ce8ccf7a3bf48a79a0c2bff20b46726 | 象形图 | 图表配置 | +| 78814d0a32fa41ae8427b708bfadb808 | 雷达图 | 图表配置 | +| 04d910fb47f4469e907a5c85949329cb | 散点图 | 图表配置 | +| 3044325436d347af9b59a617f10e3ab6 | 漏斗图 | 图表配置 | +| 469493919109937797 | 测试级联_字段列表 | 级联选择 | + +## AIBridge创建 + +```python +# 静态数据直接存储在dataConfigJson.staticData中 +payload = { + "fullName": "下拉选项", + "enCode": "dropdown_options", + "type": 2, + "action": 0, + "dataConfigJson": json.dumps({ + "staticData": '[{"id":"1","name":"选项1"},{"id":"2","name":"选项2"}]', + "sqlData": {"dbLinkId": "", "sql": ""}, + "apiData": {} + }) +} + +di.create(payload) +``` diff --git a/docs/datainterface/04-api-operation.md b/docs/datainterface/04-api-operation.md new file mode 100644 index 0000000..e8e258b --- /dev/null +++ b/docs/datainterface/04-api-operation.md @@ -0,0 +1,268 @@ +# API操作接口 + +## 基本配置 + +| 字段 | 值 | 说明 | +|------|-----|------| +| type | 3 | API操作 | +| method | 1=GET, 2=POST | 请求方法 | +| url | API路径 | 完整或相对路径 | +| hasPage | 0/1 | 是否分页 | +| isPostPosition | 0/1 | 是否鉴权 | + +## 请求配置 (apiData) + +```json +{ + "method": 1, + "url": "/api/extend/CrmOrder/Goods", + "header": [ + {"field": "Authorization", "defaultValue": "", "source": "1"} + ], + "query": [ + {"field": "keyword", "defaultValue": "", "source": "1"} + ], + "body": "", + "bodyType": 0 +} +``` + +## header/query source类型 + +| source | 说明 | +|--------|------| +| 1 | 字段:使用defaultValue | +| 2 | 自定义:从变量获取 | +| 3 | 空值:固定空字符串 | + +## bodyType 类型 + +| 值 | 说明 | +|----|------| +| 0 | none | +| 1 | form-data | +| 2 | x-www-form-urlencoded | +| 3 | json | +| 4 | xml | + +## 分页API配置 + +hasPage=1时,需要配置: +1. **数据配置**:获取分页数据 +2. **数量统计**:返回总数 + +### API分页结构 + +```json +{ + "dataConfigJson": { + "apiData": { + "url": "/api/list?page={currentPage}&size={pageSize}", + "method": 1 + } + } +} +``` + +## 参考示例 + +| ID | 名称 | 特征 | +|-----|------|------| +| 360711881444294853 | 获取订单商品接口 | GET, 1个参数 | +| 395538362724780101 | 访问jnpf接口认证示例 | 内部API调用 | +| 398826053293854213 | 系统菜单接口(示例) | 多参数 | +| 469125039078305029 | API真分页 | hasPage=1 | +| 469471490920740869 | 添加公告接口 | POST | + +### 示例1:获取订单商品 + +```json +{ + "apiData": { + "method": 1, + "url": "/api/extend/CrmOrder/Goods", + "header": [], + "query": [{"field": "keyword", "defaultValue": "", "source": "1"}], + "body": "", + "bodyType": 0 + } +} +``` + +### 示例2:POST添加公告 + +```json +{ + "apiData": { + "method": 2, + "url": "/api/message/Notice", + "header": [], + "query": [], + "body": "{\"text\": \"{text}\", \"body\": \"{body}\", \"excerpt\": \"{excerpt}\"}", + "bodyType": 3 + } +} +``` +- bodyType=3 表示JSON格式 +- body中使用`{参数名}`占位符 + +### AIBridge 调用 POST 接口 + +```python +# POST 接口调用(必填参数需要有 defaultValue 或使用 sourceType=3) +result = di.preview('469471490920740869', { + 'paramList': [ + {'field': 'text', 'defaultValue': '标题', 'dataType': 'varchar', 'sourceType': 3}, + {'field': 'body', 'defaultValue': '内容', 'dataType': 'varchar', 'sourceType': 3}, + {'field': 'excerpt', 'defaultValue': '', 'dataType': 'varchar', 'sourceType': 3}, + ] +}) +``` + +> **注意**:如果 DI 中参数配置了 `required=1` 但 `defaultValue=null`,调用时会失败。建议在创建 DI 时给必填参数设置 `defaultValue`。 + +### 示例3:API真分页 + +```json +{ + "apiData": { + "method": 1, + "url": "/api/system/DataInterface?sort=desc", + "query": [] + } +} +``` + +## 内部API调用 + +当URL以`/`开头且不以`http`开头时,自动添加apiDomain前缀 + +```java +// 后端处理逻辑 +if (StringUtil.isNotEmpty(path.toString()) && path.toString().startsWith("/")) { + path.insert(0, configValueUtil.getApiDomain()); + // 自动附加token + token = UserProvider.getUser().getToken(); +} +``` + +## 外部API调用 + +完整URL以`http`开头,直接调用 + +```json +{ + "apiData": { + "url": "https://api.example.com/data", + "method": 1 + } +} +``` + +## 异常验证(dataExceptionJson) + +仅 `type=3`(API操作)接口支持异常验证脚本。 + +| 字段 | 说明 | +|------|------| +| dataExceptionJson | JS脚本,返回 `true` 继续处理,`false` 重新调用API(重试机制) | + +### 错误码 + +| 错误码 | 含义 | +|--------|------| +| SYS121 | HTTP调用失败(连接超时、响应错误等) | +| SYS122 | API返回结果为空 | +| SYS123 | JS脚本执行异常 | + +### 执行时机 + +``` +HTTP调用完成 → dataExceptionJson验证 → dataJsJson处理 → 返回结果 +``` + +当JS返回 `false` 时,后端会重新调用HTTP接口,**最多重试3次**。 + +### 示例:检查响应状态码 + +```javascript +var result = responseObj; +if (result && result.code === 200) { + return true; // 状态正常,继续 +} +return false; // 状态异常,重试 +``` + +### 示例:检查业务错误码 + +```javascript +var result = responseObj; +if (result && result.data && result.data.success === true) { + return true; +} +return false; // 业务处理失败,重试 +``` + +## 数据处理(dataJsJson) + +所有类型接口(SQL/静态/API)都支持数据处理脚本,在最终返回前执行。 + +| 字段 | 说明 | +|------|------| +| dataJsJson | JS脚本,对结果进行二次处理后返回 | + +### 示例:添加计算字段 + +```javascript +var list = data; +for (var i = 0; i < list.length; i++) { + list[i].fullName = list[i].f_real_name + ' (' + list[i].f_account + ')'; +} +return list; +``` + +### 示例:过滤空数据 + +```javascript +var list = data; +var filtered = []; +for (var i = 0; i < list.length; i++) { + if (list[i].f_real_name && list[i].f_real_name.length > 0) { + filtered.push(list[i]); + } +} +return filtered; +``` + +## AIBridge创建 + +```python +# API操作 +payload = { + "fullName": "获取订单", + "enCode": "get_order", + "type": 3, + "dataConfigJson": json.dumps({ + "staticData": "", + "sqlData": {"dbLinkId": "", "sql": ""}, + "apiData": { + "method": 1, + "url": "/api/extend/CrmOrder/Goods", + "header": [], + "query": [{"field": "keyword", "defaultValue": "", "source": "1"}], + "body": "", + "bodyType": 0 + } + }), + "parameterJson": json.dumps([{ + "field": "keyword", + "fieldName": "关键词", + "dataType": "varchar", + "required": 0, + "sourceType": 1, + "defaultValue": "" + }]) +} + +di.create(payload) +``` diff --git a/docs/datainterface/05-pagination.md b/docs/datainterface/05-pagination.md new file mode 100644 index 0000000..6717bbc --- /dev/null +++ b/docs/datainterface/05-pagination.md @@ -0,0 +1,155 @@ +# 分页配置 + +## 启用分页 + +| 字段 | 值 | 说明 | +|------|-----|------| +| hasPage | 1 | 启用分页 | + +## SQL分页配置 + +启用分页后,需要配置两个SQL: +1. **数据配置**:查询分页数据 +2. **数量统计**:查询总条数 + +### 配置结构 + +```json +{ + "dataConfigJson": { + "sqlData": { + "sql": "SELECT * FROM base_user LIMIT {@offsetSize}, {@pageSize}" + } + }, + "dataCountJson": { + "sqlData": { + "sql": "SELECT COUNT(*) FROM base_user WHERE ..." + } + } +} +``` + +### 分页变量 + +| 变量 | 说明 | +|------|------| +| `{@pageSize}` | 每页条数(系统变量,自动从 pageSize 参数填充) | +| `{@offsetSize}` | 开始条数 = (当前页-1) × 每页条数(系统计算) | +| `{@currentPage}` | 当前页码(前端传递,非系统变量) | +| `{@keyword}` | 关键词搜索(前端传递) | + +> **注意**:hasPage=1 时,@pageSize/@offsetSize 是系统变量,后端自动计算。但 `currentPage` 和 `keyword` 是用户参数,需前端传递。 + +## SQL分页示例 + +```sql +-- 数据SQL +SELECT * FROM base_user +WHERE f_real_name LIKE CONCAT('%', @keyword, '%') +LIMIT @offsetSize, @pageSize + +-- 数量SQL +SELECT COUNT(*) FROM base_user +WHERE f_real_name LIKE CONCAT('%', @keyword, '%') +``` + +### 参考接口 + +| ID | 名称 | 说明 | +|-----|------|------| +| 469125798494792965 | SQL真分页 | 使用LIMIT分页 | + +**SQL真分页配置**: +```sql +-- 数据SQL +select * from base_user +where f_real_name like concat('%', @keyword, '%') +limit @offsetSize, @pageSize + +-- 数量SQL (需要在数量统计配置中设置) +select count(*) from base_user +where f_real_name like concat('%', @keyword, '%') +``` + +## API分页配置 + +### API分页URL参数 + +```json +{ + "apiData": { + "url": "/api/list?currentPage={currentPage}&pageSize={pageSize}&keyword={keyword}" + } +} +``` + +### 参考接口 + +| ID | 名称 | 说明 | +|-----|------|------| +| 469125039078305029 | API真分页 | URL参数分页 | + +**API真分页配置**: +```json +{ + "apiData": { + "method": 1, + "url": "/api/system/DataInterface?sort=desc&hasPage=0", + "header": [], + "query": [], + "body": "", + "bodyType": 0 + } +} +``` + +## 分页返回格式 + +```json +{ + "code": 200, + "msg": "success", + "data": { + "list": [...], + "pagination": { + "currentPage": 1, + "pageSize": 20, + "total": 100 + } + } +} +``` + +## 分页参数 + +| 参数 | 说明 | +|------|------| +| currentPage | 当前页码 | +| pageSize | 每页条数 | +| keyword | 关键词(可选) | + +## 执行预览 + +```python +# execute() 方式(使用 sourceType=3,参数值直接生效) +result = di.execute(di_id, { + "currentPage": "1", + "pageSize": "20", + "keyword": "张三" +}) + +# preview() 方式(可选择 sourceType) +result = di.preview(di_id, { + "paramList": [ + {"field": "currentPage", "defaultValue": "1", "dataType": "int", "sourceType": 3}, + {"field": "pageSize", "defaultValue": "20", "dataType": "int", "sourceType": 3}, + {"field": "keyword", "defaultValue": "张三", "dataType": "varchar", "sourceType": 3} + ] +}) +``` + +## 注意事项 + +1. hasPage=1时,isPostPosition自动设为0 +2. 分页SQL需要同时配置数据SQL和数量SQL +3. 使用@offsetSize而非@pageSize计算分页起点 diff --git a/docs/datainterface/06-parameters.md b/docs/datainterface/06-parameters.md new file mode 100644 index 0000000..763689b --- /dev/null +++ b/docs/datainterface/06-parameters.md @@ -0,0 +1,216 @@ +# 参数配置 + +## 参数定义 (parameterJson) + +### 参数结构 + +```json +[ + { + "field": "参数名", + "fieldName": "中文名", + "dataType": "varchar", + "required": 0, + "sourceType": 1, + "defaultValue": "默认值" + } +] +``` + +### 字段说明 + +| 字段 | 类型 | 说明 | +|------|------|------| +| field | string | 参数名称,用于SQL占位符{field} | +| fieldName | string | 参数中文名 | +| dataType | string | 数据类型: varchar/int/datetime/decimal | +| required | int | 是否必填: 0=否, 1=是 | +| sourceType | int | 来源类型 | +| defaultValue | string | 默认值 | + +## sourceType 类型 + +| 值 | 名称 | 说明 | 行为 | +|----|------|------|------| +| 1 | 字段 | 使用defaultValue | 直接使用 DI 中配置的默认值 | +| 2 | 自定义 | 使用relationField | 从其他接口获取 | +| 3 | 空值 | **推荐使用**:参数值直接替换,最可靠 | 直接使用传入的值,忽略默认值 | +| 4 | 系统参数 | 使用系统变量 | 从系统获取 | + +> **重要区别**: +> - `sourceType=1`:受 DI 中配置的 `defaultValue` 影响,如果 DI 没配默认值则可能不生效 +> - `sourceType=3`:**直接使用传入的参数值**,不受 `defaultValue` 影响 +> - AIBridge `execute()` 内部使用 `sourceType=3`,适合需要覆盖默认行为的场景 + +## dataType 类型 + +| 值 | 说明 | 验证规则 | +|----|------|----------| +| varchar | 字符串 | 无 | +| int | 整数 | 必须为整数 | +| datetime | 日期时间 | yyyy-MM-dd HH:mm:ss | +| decimal | 浮点数 | 必须为数字 | + +## 参数验证 + +后端自动验证: +1. **必填检查**:required=1时,参数值不能为空 +2. **类型检查**:根据dataType验证格式 + +## SQL中使用参数 + +```sql +-- 简单参数(自定义参数) +SELECT * FROM table WHERE field = {paramName} + +-- IN查询 +SELECT * FROM table WHERE field IN ({paramName}) +-- 参数值应为逗号分隔: "1,2,3" + +-- 模糊查询 +SELECT * FROM table WHERE name LIKE CONCAT('%', {name}, '%') +``` + +## SQL占位符格式说明 + +⚠️ **重要发现**:官方DI中存在两种参数格式: + +```sql +-- 格式1: 自定义参数 {paramName} +-- 用于前端传递的参数 + +-- 格式2: 系统变量 {@userId}, {@organizeId} +-- 用于自动获取当前用户/组织信息 + +-- 格式3: 分页变量 {@pageSize}, {@offsetSize}, {@currentPage} +SELECT * FROM table LIMIT {@offsetSize}, {@pageSize} +``` + +## 系统变量参数 + +```sql +-- 用户ID +SELECT * FROM base_user WHERE f_id = {@userId} + +-- 组织ID +SELECT * FROM base_organize WHERE f_id = {@organizeId} + +-- 雪花ID +INSERT INTO table (f_id) VALUES ({@snowFlakeID}) + +-- 批量雪花ID (用于批量插入) +INSERT INTO table (f_id, f_name) VALUES ({@lotSnowID}, 'name1') +``` + +## 参数传递示例 + +### AIBridge execute方法 + +```python +# 执行带参数的接口(内部使用 sourceType=3) +result = di.execute(di_id, { + "userId": "123", + "name": "张三" +}) +``` + +### Preview直接传递 + +```python +# sourceType=1: 使用 DI 中配置的 defaultValue +result = di.preview(di_id, { + "paramList": [ + { + "field": "userId", + "defaultValue": "123", + "dataType": "varchar", + "sourceType": 1 # 受 defaultValue 影响 + } + ] +}) + +# sourceType=3: 直接使用传入的值,忽略 defaultValue +result = di.preview(di_id, { + "paramList": [ + { + "field": "userId", + "defaultValue": "123", # 会被忽略 + "dataType": "varchar", + "sourceType": 3 # 直接用传入的值 + } + ] +}) +``` + +### execute() vs preview() 区别 + +| 特性 | execute() | preview() | +|------|-----------|-----------| +| 参数格式 | `{"key": "value"}` | `{"paramList": [...]}` | +| sourceType | 固定为 3 | 可手动指定 | +| defaultValue | 被忽略 | sourceType=1 时生效 | +| 适用场景 | 需要覆盖默认行为 | 需要使用 DI 默认值 | + +## 参考示例 + +| ID | 名称 | 参数 | +|-----|------|------| +| 420587863533428357 | 行政区划 | parentId | +| 469493539378625157 | 下拉多参_字段列表 | name, gender | +| 469493805800815237 | 区域下拉补全_字段列表 | name | + +### 行政区划参数示例 + +```json +[ + { + "field": "parentId", + "fieldName": "上级", + "dataType": "varchar", + "required": 0, + "sourceType": 1, + "defaultValue": "0" + } +] +``` + +### 下拉多参示例 + +```json +[ + { + "field": "name", + "fieldName": "姓名", + "dataType": "varchar", + "required": 0, + "sourceType": 1, + "defaultValue": "" + }, + { + "field": "gender", + "fieldName": "性别", + "dataType": "int", + "required": 0, + "sourceType": 1, + "defaultValue": "" + } +] +``` + +## 特殊参数 + +### searchSqlStr - 高级搜索 + +```sql +-- 使用searchSqlStr进行动态条件拼接 +SELECT * FROM base_user WHERE 1=1 {searchSqlStr} +-- searchSqlStr 格式: "f_name='张三' AND f_status=1" +-- values格式: ["张三"] +``` + +### showKey/showValue - 回显参数 + +用于表单详情回显: +```sql +SELECT * FROM table WHERE f_id = {showValue} +``` diff --git a/docs/datainterface/07-examples.md b/docs/datainterface/07-examples.md new file mode 100644 index 0000000..3cf3871 --- /dev/null +++ b/docs/datainterface/07-examples.md @@ -0,0 +1,228 @@ +# 28个示例接口详细说明 + +## SQL操作类 (15条) + +### 1. 当前用户 +- **ID**: `83ae1f5e5c26447b8c4849ead352b048` +- **类型**: SQL查询 +- **SQL**: +```sql +SELECT f_real_name, f_organize_id +FROM base_user +WHERE f_id = {@userId} +``` +- **用途**: 获取当前登录用户的基本信息 + +### 2. 查询当前组织 +- **ID**: `a0c3186292df4fe2842f66dee0ea7729` +- **类型**: SQL查询 +- **SQL**: 多表JOIN查询用户及其组织信息 +- **用途**: 获取用户所属组织详情 + +### 3. 查询当前组织以及子组织 +- **ID**: `fdfd02c7628a4ea4a0b125463e7933e0` +- **类型**: SQL查询 +- **用途**: 获取当前组织及所有子组织 + +### 4. 用户列表 +- **ID**: `ebcc44be142e43b795c0d769abd6d25a` +- **类型**: SQL查询 +- **SQL**: 多表JOIN查询用户、岗位、组织信息 +- **用途**: 用户管理下拉列表 + +### 5. 查询当前用户以及下属 +- **ID**: `bd993fb8dc914076a3848b0c121b17ca` +- **类型**: SQL查询 +- **用途**: 获取当前用户及所有下属用户 + +### 6. 视图表数据 +- **ID**: `395176542063304069` +- **类型**: SQL查询 +- **SQL**: 视图查询,包含多字段 +- **用途**: 从视图获取数据 + +### 7. 列表树形表格 +- **ID**: `395178064327220613` +- **类型**: SQL查询 +- **SQL**: `SELECT F_Id, pid as F_PId, nametest as F_FullName` +- **用途**: 树形表格数据 + +### 8. 菜单 +- **ID**: `398809921702874629` +- **类型**: SQL查询 +- **SQL**: `SELECT * FROM base_module` +- **用途**: 系统菜单查询 + +### 9. 测试 +- **ID**: `400305221865071237` +- **类型**: SQL查询 +- **参数**: organize +- **SQL**: 多表JOIN带参数 +- **用途**: 测试用接口 + +### 10. 行政区划 +- **ID**: `420587863533428357` +- **类型**: SQL查询 +- **参数**: parentId +- **SQL**: `SELECT f_id, f_full_name FROM base_province WHERE f_parent_id = {parentId}` +- **用途**: 省市区三级联动 + +### 11. SQL真分页 +- **ID**: `469125798494792965` +- **类型**: SQL查询 +- **分页**: hasPage=1 +- **SQL**: +```sql +SELECT * FROM base_user +WHERE f_real_name LIKE CONCAT('%', @keyword, '%') +LIMIT @offsetSize, @pageSize +``` +- **用途**: 带分页的用户查询 + +### 12. 树形sql_字段列表 +- **ID**: `469492643924081285` +- **类型**: SQL查询 +- **SQL**: `SELECT F_Id, F_Full_Name, F_Parent_Id as F_PId FROM base_dictionary_type` +- **用途**: 字典类型树形数据 + +### 13. 下拉多参_字段列表 +- **ID**: `469493539378625157` +- **类型**: SQL查询 +- **参数**: name, gender +- **SQL**: 多条件模糊查询 +- **用途**: 下拉选择器数据 + +### 14. 区域下拉补全_字段列表 +- **ID**: `469493805800815237` +- **类型**: SQL查询 +- **参数**: name +- **SQL**: `SELECT f_id, f_full_name FROM base_province_atlas` +- **用途**: 区域联想输入 + +### 15. 当前组织_字段列表 +- **ID**: `469500704067746437` +- **类型**: SQL查询 +- **SQL**: 多表JOIN查询组织信息 +- **用途**: 组织选择器数据 + +--- + +## 静态数据类 (8条) + +### 16. 柱状图 +- **ID**: `cd6fe911f90048f0bba7ef9f38251d96` +- **类型**: 静态数据 +- **用途**: ECharts柱状图配置 + +### 17. 折线图 +- **ID**: `be312b18a1664d8787e0dfcd2412969f` +- **类型**: 静态数据 +- **用途**: ECharts折线图配置 + +### 18. 饼图 +- **ID**: `79e5455c2f0d4d8ba2b444249bae0490` +- **类型**: 静态数据 +- **用途**: ECharts饼图配置 + +### 19. 象形图 +- **ID**: `8ce8ccf7a3bf48a79a0c2bff20b46726` +- **类型**: 静态数据 +- **用途**: ECharts象形图配置 + +### 20. 雷达图 +- **ID**: `78814d0a32fa41ae8427b708bfadb808` +- **类型**: 静态数据 +- **用途**: ECharts雷达图配置 + +### 21. 散点图 +- **ID**: `04d910fb47f4469e907a5c85949329cb` +- **类型**: 静态数据 +- **用途**: ECharts散点图配置 + +### 22. 漏斗图 +- **ID**: `3044325436d347af9b59a617f10e3ab6` +- **类型**: 静态数据 +- **用途**: ECharts漏斗图配置 + +### 23. 测试级联_字段列表 +- **ID**: `469493919109937797` +- **类型**: 静态数据 +- **数据**: 级联选择JSON结构 +- **用途**: 级联选择器数据 + +--- + +## API操作类 (5条) + +### 24. 获取订单商品接口 +- **ID**: `360711881444294853` +- **类型**: API +- **Method**: GET +- **URL**: `/api/extend/CrmOrder/Goods` +- **参数**: keyword +- **用途**: 调用外部订单商品API + +### 25. 访问jnpf接口认证示例 +- **ID**: `395538362724780101` +- **类型**: API +- **Method**: GET +- **URL**: `/api/system/DataInterface/.../Actions/Response` +- **用途**: 内部API调用示例 + +### 26. 系统菜单接口(示例) +- **ID**: `398826053293854213` +- **类型**: API +- **Method**: GET +- **URL**: `/api/system/System` +- **参数**: 8个(id, fullName, enCode等) +- **用途**: 系统菜单API + +### 27. API真分页 +- **ID**: `469125039078305029` +- **类型**: API +- **分页**: hasPage=1 +- **URL**: `/api/system/DataInterface?sort=desc` +- **用途**: API分页查询 + +### 28. 添加公告接口 +- **ID**: `469471490920740869` +- **类型**: API +- **Method**: POST +- **URL**: `/api/message/Notice` +- **参数**: text, body, excerpt +- **用途**: POST提交数据 + +--- + +## 快速参考表 + +| # | ID | 名称 | 类型 | 关键特征 | +|---|-----|------|------|----------| +| 1 | 83ae1f5e5c26447b8c4849ead352b048 | 当前用户 | SQL | {@userId} | +| 2 | a0c3186292df4fe2842f66dee0ea7729 | 查询当前组织 | SQL | 多表JOIN | +| 3 | fdfd02c7628a4ea4a0b125463e7933e0 | 查询当前组织以及子组织 | SQL | 组织树 | +| 4 | ebcc44be142e43b795c0d769abd6d25a | 用户列表 | SQL | 多表JOIN | +| 5 | cd6fe911f90048f0bba7ef9f38251d96 | 柱状图 | 静态 | 图表 | +| 6 | be312b18a1664d8787e0dfcd2412969f | 折线图 | 静态 | 图表 | +| 7 | 79e5455c2f0d4d8ba2b444249bae0490 | 饼图 | 静态 | 图表 | +| 8 | 8ce8ccf7a3bf48a79a0c2bff20b46726 | 象形图 | 静态 | 图表 | +| 9 | 78814d0a32fa41ae8427b708bfadb808 | 雷达图 | 静态 | 图表 | +| 10 | 04d910fb47f4469e907a5c85949329cb | 散点图 | 静态 | 图表 | +| 11 | 3044325436d347af9b59a617f10e3ab6 | 漏斗图 | 静态 | 图表 | +| 12 | bd993fb8dc914076a3848b0c121b17ca | 查询当前用户以及下属 | SQL | {@userId} | +| 13 | 360711881444294853 | 获取订单商品接口 | API | GET | +| 14 | 395176542063304069 | 视图表数据 | SQL | 视图 | +| 15 | 395178064327220613 | 列表树形表格 | SQL | 树形 | +| 16 | 395538362724780101 | 访问jnpf接口认证示例 | API | 鉴权 | +| 17 | 398809921702874629 | 菜单 | SQL | base_module | +| 18 | 398826053293854213 | 系统菜单接口(示例) | API | 多参数 | +| 19 | 400305221865071237 | 测试 | SQL | 带参数 | +| 20 | 420587863533428357 | 行政区划 | SQL | {parentId} | +| 21 | 469125039078305029 | API真分页 | API | hasPage=1 | +| 22 | 469125798494792965 | SQL真分页 | SQL | hasPage=1 | +| 23 | 469471490920740869 | 添加公告接口 | API | POST | +| 24 | 469492643924081285 | 树形sql_字段列表 | SQL | 树形 | +| 25 | 469493539378625157 | 下拉多参_字段列表 | SQL | 多参数 | +| 26 | 469493805800815237 | 区域下拉补全_字段列表 | SQL | 联想 | +| 27 | 469493919109937797 | 测试级联_字段列表 | 静态 | 级联 | +| 28 | 469500704067746437 | 当前组织_字段列表 | SQL | {@organizeId} | diff --git a/docs/datainterface/08-troubleshooting.md b/docs/datainterface/08-troubleshooting.md new file mode 100644 index 0000000..1456334 --- /dev/null +++ b/docs/datainterface/08-troubleshooting.md @@ -0,0 +1,353 @@ +# 常见问题与解决方案 + +## 错误:map is null + +### 原因 +数据操作API期望格式 `{"data": ""}`,但传入格式不正确。 + +### 解决方案 +AIBridge的`execute`方法已内置处理: +```python +result = di.execute(di_id, {"param": "value"}) +``` + +## 预览时NPE (NullPointerException) + +### 原因 +`isPostPosition` 设置为 1,导致 `handlePostVariate` 方法中拆箱异常。 + +### 解决方案 +创建接口时确保 `isPostPosition = 0` + +```python +payload = DataInterfaceAPI.build_payload( + ... + # 不要设置 isPostPosition +) +# AIBridge 已强制设为 0 +``` + +## execute() 返回空列表 + +### 原因 +`execute()` 方法内部使用 `sourceType=1`,如果 DI 配置了 `defaultValue`,会使用默认值而非传入值。 + +### 解决方案 +AIBridge 已修复此问题,`execute()` 现在内部使用 `sourceType=3`,参数值直接传递: + +```python +# 现在正常返回数据 +result = di.execute(di_id, {"parentId": "0"}) +``` + +## SQL中{}被解析为占位符 + +### 原因 +SQL字面量中包含 `{}` 会被当作参数占位符解析。 + +### 错误示例 +```sql +SELECT * FROM table WHERE json = '{}' +``` + +### 正确示例 +```sql +SELECT * FROM table WHERE json = '''{}''' +-- 或 +SELECT * FROM table WHERE json = '"{}"' +``` + +## 预览返回空数据 + +### 可能原因 +1. 参数值不正确 +2. SQL条件无匹配数据 +3. 多租户环境下dbLinkId配置错误 +4. **sourceType=1 使用了 DI 中的 defaultValue**,导致实际参数与预期不符 + +### 排查步骤 +```python +# 1. 使用 sourceType=3 直接传递参数值 +result = di.preview(di_id, { + "paramList": [ + {"field": "paramName", "defaultValue": "test", "dataType": "varchar", "sourceType": 3} + ] +}) + +# 2. 使用 execute() 方法(内部自动用 sourceType=3) +result = di.execute(di_id, {"paramName": "test"}) + +# 3. 检查dbLinkId +# 主库: "0" +# 业务库: 查看数据连接ID +``` + +### sourceType=1 vs sourceType=3 + +| sourceType | 行为 | 受 defaultValue 影响 | +|------------|------|---------------------| +| 1 | 使用 DI 中配置的 defaultValue | ✅ 是 | +| 3 | 直接使用传入的参数值 | ❌ 否 | + +```python +# 示例:DI 配置 defaultValue="-1" +# sourceType=1: 使用 -1(忽略传入的值) +# sourceType=3: 使用传入的值 +``` + +## 敏感词校验失败 + +### 原因 +接口名或SQL包含敏感词。 + +### 错误信息 +``` +MsgCode.SYS006.get(containsSensitive) +``` + +### 解决方案 +修改接口名称或SQL,避免敏感词。 + +## 增删改不返回数据 + +### 正常行为 +action=1(增)/2(改)/4(删) 执行后返回空列表,不返回数据。 + +### 验证方式 +```python +result = di.preview(di_id, {}) +print(result.code) # 200 表示成功 +``` + +## 分页不生效 + +### 可能原因 +1. hasPage 未设为 1 +2. 数量统计SQL未配置 +3. 分页变量使用错误 + +### 正确配置 +```json +{ + "dataConfigJson": { + "sqlData": {"sql": "SELECT * FROM table LIMIT @offsetSize, @pageSize"} + }, + "dataCountJson": { + "sqlData": {"sql": "SELECT COUNT(*) FROM table"} + } +} +``` + +## 接口未找到 + +### 可能原因 +1. 接口ID错误 +2. 接口已被删除 +3. 多租户数据隔离 + +### 解决方案 +```python +# 重新获取接口列表 +resp = di.get_selector() +for item in resp.data: + print(item.get('id'), item.get('fullName')) +``` + +## 参数类型验证失败 + +### 原因 +传入的参数值与定义的dataType不匹配。 + +### 错误示例 +```python +# 定义为int,传入了字符串 +{"field": "age", "dataType": "int", "defaultValue": "abc"} +``` + +### 正确示例 +```python +{"field": "age", "dataType": "int", "defaultValue": "25"} +``` + +## DI预览无法访问业务表 + +### 原因 +多租户环境下,`dbLinkId=0` 连接主库,部分业务表仅在租户库中。 + +### 解决方案 +使用业务数据库连接ID而非"0"。 + +## 执行时间过长 + +### 可能原因 +1. 查询数据量过大 +2. 缺少索引 +3. 网络延迟 + +### 优化建议 +1. 添加分页限制 +2. 添加查询条件减少数据量 +3. 使用explain分析SQL性能 + +## 接口验证失败(dataExceptionJson返回false) + +### 原因 +API接口的异常验证脚本返回了 `false`,触发重试机制(最多3次)。 + +### 错误码说明 +| 错误码 | 含义 | +|--------|------| +| SYS121 | HTTP调用失败(连接超时、响应错误等) | +| SYS122 | API返回结果为空 | +| SYS123 | JS脚本执行异常 | + +### 排查步骤 +1. 检查API是否可正常访问 +2. 检查dataExceptionJson脚本逻辑是否正确 +3. 查看后端日志中的错误码信息 +4. 确认API返回的数据格式是否符合脚本预期 + +### 示例排查 + +```javascript +// dataExceptionJson 脚本示例 +var result = responseObj; +if (result && result.code === 200 && result.data) { + return true; +} +return false; // 失败重试 +``` + +如果持续失败,检查: +- API服务是否正常运行 +- 网络连接是否稳定 +- 返回数据格式是否与脚本预期一致 + +## JS脚本异常(SYS123) + +### 原因 +dataExceptionJson或dataJsJson脚本执行出错。 + +### 常见错误 +1. 变量名与返回结果不匹配 +2. 数组越界访问 +3. 语法错误 +4. 使用了不支持的JS语法 + +### 排查步骤 +1. 检查JS语法是否正确 +2. 确认脚本中的变量名与返回结果字段匹配 +3. 使用try-catch包装可能出错的代码 + +### 安全写法示例 + +```javascript +try { + var list = data; + if (!list || !Array.isArray(list)) { + return data; + } + for (var i = 0; i < list.length; i++) { + if (list[i].f_real_name) { + list[i].fullName = list[i].f_real_name; + } + } + return list; +} catch (e) { + return data; // 出错时返回原始数据 +} +``` + +## POST 接口必填参数校验失败 + +### 原因 +API 接口的必填参数(`required=1`)在 DI 中没有配置 `defaultValue`,且传入的 `defaultValue` 为 `null` 时校验失败。 + +### 错误信息 +``` +text不能为空 +``` + +### 解决方案 + +1. **创建 DI 时设置 defaultValue**: +```json +{ + "field": "text", + "dataType": "varchar", + "required": 1, + "defaultValue": "默认值" +} +``` + +2. **调用时使用 sourceType=3**: +```python +result = di.preview(di_id, { + 'paramList': [ + {'field': 'text', 'defaultValue': '标题', 'dataType': 'varchar', 'sourceType': 3}, + {'field': 'body', 'defaultValue': '内容', 'dataType': 'varchar', 'sourceType': 3}, + ] +}) +``` + +## DI执行失败 "Interface request failed" + +### 原因 +SQL查询的表字段名与实际数据库不符。 + +### 错误日志 +``` +Unknown column 'f_enterprise_name' in 'field list' +``` + +### 排查方法 +1. 查看后端日志 `log/jnpf-java-boot/log_error.log` +2. 使用 `SELECT * FROM table LIMIT 1` 获取实际字段名 +3. 注意JNPF业务表字段可能是大写(如 `F_Company_Name`)而非小写(`f_company_name`) + +### 解决方案 +确认实际字段名后更新DI的SQL配置: +```python +# 错误:使用小写下划线 +sql = "SELECT f_enterprise_name FROM opportunity_mgmt" + +# 正确:使用实际字段名(大写) +sql = "SELECT F_Company_Name FROM opportunity_mgmt" +``` + +### 常见JNPF表字段命名规律 +| 表类型 | 字段命名 | 示例 | +|--------|----------|------| +| JNPF系统表 | snake_case | f_id, f_full_name | +| 业务表(VisualDev) | PascalCase | F_Id, F_Company_Name | + +可通过 `SELECT * FROM table LIMIT 1` 查看实际命名。 + +## dbLinkId 配置错误导致查询失败 + +### 原因 +业务库的表不在主库(0)中,配置错误导致找不到表。 + +### 解决方案 +配置正确的业务库 db_link_id: +```python +# 获取业务库的 db_link_id(不是 "0") +db_link_id = config.db_link_id # 如 "2042386207729803264" + +update_data = { + "id": di_id, + "dbLinkId": db_link_id, # 不是 "0" + "dataConfigJson": json.dumps({ + "sqlData": { + "dbLinkId": db_link_id, # 放在 sqlData 中 + "sql": "SELECT * FROM business_table" + } + }) +} +``` + +### dbLinkId 层级关系 +``` +顶层 dbLinkId: 用于接口列表查询筛选 +└── dataConfigJson.sqlData.dbLinkId: 用于实际SQL执行(必须正确) +``` diff --git a/docs/datainterface/README.md b/docs/datainterface/README.md new file mode 100644 index 0000000..f3e5bd7 --- /dev/null +++ b/docs/datainterface/README.md @@ -0,0 +1,158 @@ +# JNPF 数据接口 (DataInterface) 开发指南 + +## 文档索引 + +| 文档 | 说明 | +|------|------| +| **README.md** | 本文档,基本用法速查 | +| [基础规则](01-basic-rules.md) | 核心机制、类型、参数、SQL占位符 | +| [SQL操作](02-sql-operation.md) | SQL查询接口的创建与使用 | +| [静态数据](03-static-data.md) | 静态数据接口的配置 | +| [API操作](04-api-operation.md) | API接口调用的配置 | +| [分页配置](05-pagination.md) | 分页查询的配置与实现 | +| [参数配置](06-parameters.md) | 参数定义与传递 | +| [示例参考](07-examples.md) | 28个示例接口详细说明 | +| [常见问题](08-troubleshooting.md) | 常见错误与解决方案 | + +--- + +## 快速开始 + +### 1. 核心概念 + +| 概念 | 说明 | +|------|------| +| **type** | 类型: 1=SQL操作, 2=静态数据, 3=API操作 | +| **action** | 动作: 1=增删改, 2=修改, 3=查询, 4=删除 | +| **hasPage** | 分页: 0=禁用, 1=启用 | +| **isPostPosition** | 鉴权: 0=否, 1=是(后置接口) | +| **dbLinkId** | 数据库连接ID,"0"=主库 | + +### 2. 三种接口类型 + +``` +type=1: SQL操作 → 执行SQL查询/增删改 +type=2: 静态数据 → 返回固定JSON数据 +type=3: API操作 → 调用HTTP接口 +``` + +### 3. AIBridge 快速使用 + +```python +from aibridge import JNPFClient, JNPFConfig +from aibridge.modules.data_interface import DataInterfaceAPI + +client = JNPFClient.from_config(JNPFConfig()) +client.login() + +di = DataInterfaceAPI(client) + +# 执行查询 +result = di.execute("接口ID", {"参数名": "值"}) +for row in result: + print(row) +``` + +### 4. 创建SQL查询接口 + +```python +# 构建payload +payload = DataInterfaceAPI.build_payload( + full_name="按名称查询", + en_code="query_by_name", + sql="SELECT * FROM base_user WHERE f_real_name = {name}", + parameters=[{ + "field": "name", + "fieldName": "姓名", + "dataType": "varchar", + "required": 1, + "sourceType": 1 + }], + category="分类ID", + action=3, + db_link_id="0" +) + +# 创建并执行 +di.create(payload) +result = di.execute(di_id, {"name": "张三"}) +``` + +--- + +## 关键配置速查 + +### SQL占位符 +```sql +SELECT * FROM table WHERE field = {参数名} +``` +- `{参数名}` → PreparedStatement `?` +- `{@系统变量}` → 如 `{@userId}`, `{@organizeId}` + +### 参数sourceType +| 值 | 说明 | +|----|------| +| 1 | 字段(defaultValue) | +| 2 | 自定义(relationField) | +| 3 | 空值 | +| 4 | 系统参数 | + +### 系统变量 +| 变量 | 说明 | +|------|------| +| `@userId` | 当前用户ID | +| `@organizeId` | 当前组织ID | +| `@snowFlakeID` | 雪花ID | +| `@lotSnowID` | 批量生成雪花ID | +| `@keyword` | 关键词搜索 | +| `@pageSize` | 每页条数 | +| `@offsetSize` | 开始条数 | + +--- + +## 源码位置 + +| 资源 | 路径 | +|------|------| +| 前端入口 | `前端/.../views/dataCenter/dataInterface/` | +| 前端API | `前端/.../api/systemData/dataInterface.ts` | +| 后端Controller | `后端/.../base/controller/DataInterfaceController.java` | +| 后端Service | `后端/.../base/service/impl/DataInterfaceServiceImpl.java` | +| 实体类 | `后端/.../base/entity/DataInterfaceEntity.java` | +| AIBridge模块 | `aibridge/modules/data_interface.py` | + +--- + +## 28个示例接口参考 + +| # | 名称 | ID | 类型 | 说明 | +|---|------|-----|------|------| +| 1 | 当前用户 | 83ae1f5e5c26447b8c4849ead352b048 | SQL | 查询当前登录用户信息 | +| 2 | 查询当前组织 | a0c3186292df4fe2842f66dee0ea7729 | SQL | 查询用户所属组织 | +| 3 | 查询当前组织以及子组织 | fdfd02c7628a4ea4a0b125463e7933e0 | SQL | 组织及子组织查询 | +| 4 | 用户列表 | ebcc44be142e43b795c0d769abd6d25a | SQL | 用户列表查询 | +| 5-11 | 柱状图/折线图/饼图... | - | 静态 | 图表静态数据 | +| 12 | 查询当前用户以及下属 | bd993fb8dc914076a3848b0c121b17ca | SQL | 用户及下属查询 | +| 13 | 获取订单商品接口 | 360711881444294853 | API | 外部API调用示例 | +| 14-15 | 视图/树形表格 | - | SQL | 特殊SQL查询 | +| 16 | 访问jnpf接口认证示例 | 395538362724780101 | API | 内部API鉴权示例 | +| 17 | 菜单 | 398809921702874629 | SQL | 系统菜单查询 | +| 18 | 系统菜单接口 | 398826053293854213 | API | 多参数API调用 | +| 19-20 | 测试/行政区划 | - | SQL | 带参数的SQL查询 | +| 21 | API真分页 | 469125039078305029 | API | API分页实现 | +| 22 | SQL真分页 | 469125798494792965 | SQL | SQL分页查询 | +| 23 | 添加公告接口 | 469471490920740869 | API | POST API示例 | +| 24-28 | 字段列表系列 | - | SQL | 下拉/树形选择数据 | + +详细示例见 [示例参考](07-examples.md) + +--- + +## 接口验证机制区分 + +| 机制 | 说明 | 适用场景 | +|------|------|---------| +| **dataExceptionJson** | JS脚本验证,API接口内部验证逻辑 | 验证API返回状态、业务错误码 | +| **InterfaceOauth** | 外部系统API密钥认证授权 | 第三方应用访问控制 | + +详见 [接口认证文档](../interface-oauth/README.md)。 diff --git a/docs/development-guide.md b/docs/development-guide.md new file mode 100644 index 0000000..c936c69 --- /dev/null +++ b/docs/development-guide.md @@ -0,0 +1,806 @@ +# 开发指南 + +> AIBridge 完整开发工作流:从需求分析到上线部署。 + +## 开发流程总览 + +``` +需求规划 → 字段定义 → 配置构建 → 功能创建 → 发布 → 创建菜单 → 数据字典 → 工作流集成 → 测试验证 → 上线 +``` + +## 第一步:需求规划 + +在编码之前,明确以下信息: + +### 1.1 确定模块结构 + +``` +业务系统(App-Code: wj) +├── 目录:办公用品管理 +│ ├── 功能:文具分类(字典维护) +│ ├── 功能:销售商管理 +│ ├── 功能:文具产品管理 +│ └── 功能:文具订单管理 +└── 目录:统计分析 + └── 功能:销售报表 +``` + +### 1.2 确定功能类型 + +| web_type | 说明 | 适用场景 | +|----------|------|---------| +| 1 | 纯表单 | 单条数据录入 | +| 2 | 表单加列表 | **最常用**,标准 CRUD | +| 3 | 表单列表工作流 | 需要审批的功能 | +| 4 | 数据视图 | 统计报表 | + +### 1.3 收集平台参数 + +```python +# 需要预先获取的参数 +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`: +```js +const columns = (props.columnOptions).map((o) => ({ + dataIndex: o.value, // 必须有值,否则 .includes() 报错 +})); +``` + +正确的 columnOptions item 结构: +```python +{ + "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 字段定义示例 + +```python +# 产品管理字段 +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 使用配置构建器(推荐) + +```python +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` 模块管理数据库表: + +```python +# 查询表列表 +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`) + +```python +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): + +```python +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) + +关联表单用于引用其他功能的数据,点击时弹出目标表单的数据列表供选择。 + +```python +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。 + +```python +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 手动构建(高级用法) + +如果需要更细粒度的控制,可以单独使用各构建器: + +```python +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 标准发布流程 + +```python +# 发布(systemId 在创建时已由 App-Code 自动设置,无需手动修正) +release_resp = visual_dev.release(func_id) +print(f"发布: {release_resp.msg}") +``` + +### 4.2 验证发布结果 + +```python +# 检查发布状态 +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` 页面挂载到菜单 + +```python +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 自动修复,直接使用即可。 + +```python +# 一级目录 +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 多级目录 + +```python +# 一级目录 +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 创建字典分类和数据 + +```python +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` 中引用: + +```python +# 获取功能配置 +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 创建带工作流的功能 + +```python +# 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 工作流详细指南 + +请参阅 [工作流指南](workflow/README.md)。 + +### 7.3 工作流创建最佳实践 + +使用 `create_simple_flow()` 便捷方法一步完成模板创建和发布: + +```python +# 一步创建流程模板(内部自动处理 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 类型) +- 发起人和审批人不能是同一用户 +- 删除资源顺序:流程模板 → 表单 → 功能菜单 → 目录菜单(先解除引用再删除) + +## 第八步:代码生成与导出 + +### 8.1 代码预览 + +```python +# 预览生成的代码 +preview_resp = visual_dev.code_preview(func_id, {"type": 1}) +print(f"生成的代码: {preview_resp.data}") +``` + +### 8.2 下载代码 + +```python +# 下载完整代码包 +download_resp = visual_dev.download_code(func_id, {"type": 1}) +``` + +## 扩展点 + +### 自定义 API 接口 + +通过数据接口(DataInterface)实现自定义查询: + +```python +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` 钩子: + +```python +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. 配置集中管理 + +```python +PROJECT_CONFIG = { + "base_url": "http://localhost:30000", + "app_code": "wj", + "system_id": "your_system_id", + "category_id": "your_category_id", +} +``` + +### 2. 字段定义复用 + +```python +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. 错误处理 + +```python +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. 批量操作 + +```python +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. 日志记录 + +```python +import logging +logging.basicConfig(level=logging.INFO) +# AIBridge 自动记录: 登录成功/失败、API 错误、DI 代理 SQL 执行、system_id 自动设置 +``` diff --git a/docs/interface-oauth/01-auth-mechanism.md b/docs/interface-oauth/01-auth-mechanism.md new file mode 100644 index 0000000..70d16d4 --- /dev/null +++ b/docs/interface-oauth/01-auth-mechanism.md @@ -0,0 +1,148 @@ +# 认证机制详解 + +## 认证流程 + +外部系统调用数据接口时,经过以下认证流程: + +``` +1. 解析请求头 Authorization → {appId}::{signature/secret} + ↓ +2. 验证 appId 有效性 + - appId 存在 + - 接口在授权列表中 + - enabledMark = 1(已启用) + ↓ +3. 签名验证(verifySignature=1 时) + - 验证时间戳(1分钟内有效) + - 验证 HMAC-SHA256 签名 + ↓ + (verifySignature=0 时) + - 仅验证 appSecret 匹配 + ↓ +4. 验证使用期限 + - usefulLife 为空 或 未过期 + ↓ +5. 获取用户 token + - 通过 UserKey 获取 + ↓ +6. IP 白名单验证 + - whiteList 为空 或 当前IP在白名单中 + ↓ +7. 调用实际数据接口 +``` + +## 签名算法 + +### verifySignature=1(启用签名) + +```java +// 签名源字符串格式 +String source = method + '\n' + url + '\n' + timestamp + '\n' + host + '\n'; + +// 示例 +method = "GET" +url = "/api/system/DataInterface/xxx/Actions/Response" +timestamp = "1743600000000" +host = "localhost:30000" + +source = "GET\n/api/system/DataInterface/xxx/Actions/Response\n1743600000000\nlocalhost:30000\n" + +// HMAC-SHA256 签名 +Mac mac = Mac.getInstance("HmacSHA256"); +SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(appSecret), "HmacSHA256"); +mac.init(secretKeySpec); +String signature = Hex.encodeHexString(mac.doFinal(source.getBytes("UTF-8"))); +``` + +### verifySignature=0(不启用签名) + +直接使用 `appSecret` 作为签名: + +``` +Authorization: {appId}::{appSecret} +``` + +## 请求头说明 + +| 请求头 | 说明 | 必需 | +|--------|------|------| +| Authorization | 认证信息,格式:`{appId}::{signature}` 或 `{appId}::{appSecret}` | 是 | +| YmDate | 时间戳(毫秒),verifySignature=1 时必需 | 条件必需 | +| UserKey | 用户标识,用于获取调用方用户身份 | 是 | +| Host | 请求主机(参与签名计算) | 条件必需 | + +## 错误码详解 + +### SYS124 - 请求已过期 + +``` +原因:YmDate 时间戳超过1分钟 +解决:确保请求前生成新的时间戳,确保客户端与服务端时间同步 +``` + +### SYS125 - 签名验证失败 + +``` +原因:HMAC-SHA256 签名不匹配 +解决: +1. 确认 appSecret 正确 +2. 确认签名源字符串格式正确(注意换行符 \n) +3. 确认 appSecret 是 Base64 编码后的字符串 +``` + +### SYS126 - 使用期限已过 + +``` +原因:usefulLife 设置了日期且已过期 +解决:修改接口认证的 usefulLife 或清空(永久有效) +``` + +### SYS127 - AppId 不存在 + +``` +原因:提供的 appId 在 base_data_interface_oauth 表中不存在 +解决:确认 appId 正确,检查接口认证是否已删除 +``` + +### FA021 - 接口未授权 + +``` +原因:appId 未授权访问该数据接口 +解决:在 JNPF 平台中将该接口ID添加到授权列表 +``` + +## 数据表结构 + +### base_data_interface_oauth + +| 字段 | 类型 | 说明 | +|------|------|------| +| F_Id | varchar(50) | 主键 | +| F_App_Id | varchar(100) | 应用ID(唯一) | +| F_App_Name | varchar(100) | 应用名称 | +| F_App_Secret | varchar(500) | 应用秘钥 | +| F_Verify_Signature | int | 是否验签:0=否, 1=是 | +| F_Useful_Life | datetime | 使用期限 | +| F_White_List | text | IP白名单 | +| F_Black_List | text | IP黑名单 | +| F_Data_Interface_Ids | text | 授权接口ID列表(逗号分隔) | +| F_Enabled_Mark | int | 启用状态:0=禁用, 1=启用 | + +### base_data_interface_user + +| 字段 | 类型 | 说明 | +|------|------|------| +| F_Id | varchar(50) | 主键 | +| F_Interface_Oauth_Id | varchar(50) | 关联的认证ID | +| F_User_Id | varchar(50) | 用户ID | +| F_User_Key | varchar(100) | 用户标识 | + +## 调用日志 + +每次接口调用会记录日志,包含: +- 调用时间 +- 调用方 IP +- 使用的 UserKey +- 调用的接口 +- 请求参数 +- 响应状态 diff --git a/docs/interface-oauth/02-usage-guide.md b/docs/interface-oauth/02-usage-guide.md new file mode 100644 index 0000000..9c1a35a --- /dev/null +++ b/docs/interface-oauth/02-usage-guide.md @@ -0,0 +1,176 @@ +# 使用指南 + +## 完整示例 + +### 场景:创建第三方应用访问权限 + +假设你需要为第三方合作方创建一个只能访问"当前用户"和"行政区划"两个接口的应用。 + +### 1. 准备工作 + +```python +from aibridge import JNPFClient, JNPFConfig + +client = JNPFClient.from_config(JNPFConfig()) +client.login() + +oauth = client.interface_oauth +di = client.data_interface + +# 先验证要授权的接口存在 +di_id_1 = "83ae1f5e5c26447b8c4849ead352b048" # 当前用户 +di_id_2 = "420587863533428357" # 行政区划 +``` + +### 2. 创建认证 + +```python +# 获取新秘钥 +secret_resp = oauth.get_app_secret() +app_secret = secret_resp.data +print(f"生成的秘钥: {app_secret}") + +# 创建认证 +resp = oauth.create({ + "appId": "partner_app", # 唯一应用ID + "appName": "合作伙伴应用", # 应用名称 + "appSecret": app_secret, # 秘钥 + "verifySignature": 0, # 不启用签名验证 + "enabledMark": 1, # 启用 + "whiteList": "192.168.1.1,10.0.0.0/8", # IP白名单 +}) +print(f"创建结果: {resp.msg}") +``` + +### 3. 绑定授权接口 + +```python +# 绑定授权接口 +resp = oauth.bind_interfaces(resp.data, [di_id_1, di_id_2]) +print(f"绑定结果: {resp.msg}") + +# 查看详情确认 +info = oauth.get_info(resp.data) +print(f"授权接口数: {len(info.data.get('list', []))}") +``` + +### 4. 授权用户(可选) + +如果需要记录调用方用户: + +```python +# 获取用户信息 +user_resp = oauth.save_user_list(resp.data, [ + {"userId": "user_id_123", "userKey": "partner_user_1"}, +]) +``` + +### 5. 外部系统调用 + +```python +import requests + +app_id = "partner_app" +app_secret = "之前生成的秘钥" +di_id = di_id_1 # 当前用户接口 + +# 调用 GET 接口 +response = requests.get( + f"http://localhost:30000/api/system/DataInterface/{di_id}/Actions/Response", + headers={ + "Authorization": f"{app_id}::{app_secret}", + "UserKey": "partner_user_1", + } +) +print(response.json()) +``` + +## 高级配置 + +### 启用签名验证 + +```python +# 创建时启用签名 +resp = oauth.create({ + "appId": "secure_app", + "appName": "安全应用", + "appSecret": app_secret, + "verifySignature": 1, # 启用签名验证 + "enabledMark": 1, +}) +``` + +### 设置使用期限 + +```python +from datetime import datetime, timedelta + +# 设置30天后过期 +expire_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d") + +resp = oauth.create({ + "appId": "temp_app", + "appName": "临时应用", + "appSecret": app_secret, + "usefulLife": expire_date, + "enabledMark": 1, +}) +``` + +### 管理授权接口 + +```python +# 查看当前授权 +info = oauth.get_info(oauth_id) +current_ids = [item['id'] for item in info.data.get('list', [])] + +# 添加一个新接口 +new_ids = current_ids + ["new_di_id"] +oauth.bind_interfaces(oauth_id, new_ids) + +# 移除一个接口 +oauth.bind_interfaces(oauth_id, [di_id_1]) # 只保留一个 +``` + +## 常见问题 + +### Q: 如何限制第三方只能访问特定接口? + +```python +# 绑定时只指定允许的接口 +oauth.bind_interfaces(oauth_id, ["di_id_1", "di_id_2"]) +``` + +### Q: 如何吊销一个应用的访问权限? + +```python +# 方式1:禁用 +oauth.update({"id": oauth_id, "enabledMark": 0}) + +# 方式2:删除 +oauth.delete(oauth_id) +``` + +### Q: 如何查看接口调用情况? + +```python +# 获取调用日志 +logs = oauth.get_log(oauth_id, {"currentPage": 1, "pageSize": 20}) +for log in logs.data.get('list', []): + print(f"时间: {log.get('creatorTime')}, IP: {log.get('ipAddress')}, 接口: {log.get('fullName')}") +``` + +### Q: 签名验证失败怎么办? + +1. 确认 `verifySignature` 设置正确(0 或 1) +2. 如果启用签名,确认时间戳在1分钟内 +3. 确认 appSecret 正确(注意是否有前后空格) +4. 参考 `01-auth-mechanism.md` 检查签名算法 + +## 安全建议 + +1. **启用签名验证**:生产环境建议 `verifySignature=1` +2. **设置 IP 白名单**:限制只有已知 IP 可以访问 +3. **设置使用期限**:临时应用设置过期时间 +4. **最小授权**:只授权必要的接口 +5. **定期轮换秘钥**:定期调用 `get_app_secret` 更新秘钥 diff --git a/docs/interface-oauth/README.md b/docs/interface-oauth/README.md new file mode 100644 index 0000000..1919c4e --- /dev/null +++ b/docs/interface-oauth/README.md @@ -0,0 +1,190 @@ +# JNPF 接口认证 (InterfaceOauth) 开发指南 + +## 概述 + +InterfaceOauth 是 JNPF 平台的**外部系统接口认证机制**,用于: +- 为第三方应用分配 `appId` + `appSecret` 访问凭证 +- 控制哪些数据接口可以被外部调用 +- 可选启用 HMAC-SHA256 签名验证增强安全性 +- 记录接口调用日志 + +**注意**:这与 `dataExceptionJson`(JS脚本验证)是完全独立的两个机制: +- `dataExceptionJson`:接口内部的 JS 脚本验证(API类型接口专用) +- `InterfaceOauth`:外部系统访问的 API Key 认证 + +--- + +## 文档索引 + +| 文档 | 说明 | +|------|------| +| **README.md** | 本文档,概述与快速开始 | +| [认证机制](01-auth-mechanism.md) | 认证流程、签名算法、错误码 | +| [使用指南](02-usage-guide.md) | 创建认证、绑定接口、调用示例 | + +--- + +## 快速开始 + +### 1. 创建接口认证 + +```python +from aibridge import JNPFClient, JNPFConfig + +client = JNPFClient.from_config(JNPFConfig()) +client.login() + +oauth = client.interface_oauth + +# 获取新秘钥 +secret_resp = oauth.get_app_secret() +app_secret = secret_resp.data + +# 创建认证 +resp = oauth.create({ + "appId": "my_app", + "appName": "我的应用", + "appSecret": app_secret, + "verifySignature": 0, # 0=不验签, 1=验签 + "enabledMark": 1, +}) +oauth_id = resp.data # 假设返回ID +``` + +### 2. 绑定授权接口 + +```python +# 绑定允许访问的数据接口 +oauth.bind_interfaces(oauth_id, [ + "83ae1f5e5c26447b8c4849ead352b048", # 当前用户 + "420587863533428357", # 行政区划 +]) +``` + +### 3. 外部系统调用 + +#### 不启用签名验证(verifySignature=0) + +```python +import requests + +app_id = "my_app" +app_secret = "生成的秘钥" +di_id = "83ae1f5e5c26447b8c4849ead352b048" + +response = requests.get( + f"http://localhost:30000/api/system/DataInterface/{di_id}/Actions/Response", + headers={ + "Authorization": f"{app_id}::{app_secret}", + "UserKey": "user_key_123", + } +) +``` + +#### 启用签名验证(verifySignature=1) + +```python +import base64 +import hmac +import hashlib +import time + +app_id = "my_app" +app_secret = "生成的秘钥" +di_id = "83ae1f5e5c26447b8c4849ead352b048" +method = "GET" +url_path = f"/api/system/DataInterface/{di_id}/Actions/Response" +timestamp = int(time.time() * 1000) + +# 签名源字符串 +source = f"{method}\n{url_path}\n{timestamp}\n\n" +signature = hmac.new( + base64.b64decode(app_secret), + source.encode('utf-8'), + hashlib.sha256 +).hexdigest() + +response = requests.get( + f"http://localhost:30000{url_path}", + headers={ + "Authorization": f"{app_id}::{signature}", + "YmDate": str(timestamp), + "UserKey": "user_key_123", + } +) +``` + +--- + +## 核心概念 + +### 认证字段 + +| 字段 | 说明 | +|------|------| +| appId | 应用ID(唯一标识) | +| appSecret | 应用秘钥(自动生成或手动输入) | +| verifySignature | 是否启用签名验证:0=否, 1=是 | +| usefulLife | 使用期限(为空表示永久有效) | +| whiteList | IP白名单(多个用英文逗号分隔) | +| dataInterfaceIds | 授权访问的数据接口ID列表 | + +### 签名算法 + +当 `verifySignature=1` 时,使用 HMAC-SHA256 签名: + +``` +签名源 = method + '\n' + url + '\n' + timestamp + '\n' + host + '\n' +签名 = HMAC-SHA256(appSecret Base64解码, 签名源).hex() +``` + +### 错误码 + +| 错误码 | 含义 | +|--------|------| +| SYS124 | 请求已过期(时间戳超过1分钟) | +| SYS125 | 签名验证失败 | +| SYS126 | 已超过使用期限 | +| SYS127 | AppId 不存在 | +| FA021 | 接口未授权访问 | + +--- + +## AIBridge API + +```python +oauth = client.interface_oauth + +# CRUD +oauth.get_list(data) # 获取认证列表 +oauth.create(data) # 创建认证 +oauth.update(data) # 修改认证 +oauth.get_info(oauth_id) # 获取详情(含授权接口和用户) +oauth.delete(oauth_id) # 删除认证 + +# 秘钥 +oauth.get_app_secret() # 获取新秘钥 + +# 授权 +oauth.get_interface_list(oauth_id) # 获取已授权接口 +oauth.bind_interfaces(oauth_id, interface_ids) # 绑定接口 +oauth.get_user_list(oauth_id) # 获取授权用户 +oauth.save_user_list(oauth_id, users) # 保存授权用户 + +# 日志 +oauth.get_log(oauth_id, data) # 获取调用日志 +``` + +--- + +## 源码位置 + +| 资源 | 路径 | +|------|------| +| 前端入口 | `前端/.../views/dataCenter/interfaceOauth/` | +| 前端API | `前端/.../api/systemData/interfaceOauth.ts` | +| 后端Controller | `后端/.../base/controller/InterfaceOauthController.java` | +| 后端Service | `后端/.../base/service/impl/InterfaceOauthServiceImpl.java` | +| 签名工具 | `后端/.../base/util/interfaceutil/InterfaceUtil.java` | +| 实体类 | `后端/.../base/entity/InterfaceOauthEntity.java` | +| AIBridge模块 | `aibridge/modules/interface_oauth.py` | diff --git a/docs/platform-guide.md b/docs/platform-guide.md new file mode 100644 index 0000000..0e431b8 --- /dev/null +++ b/docs/platform-guide.md @@ -0,0 +1,313 @@ +# 平台机制指南 + +> 深入理解 JNPF 低代码平台的核心运行机制,避免开发中的常见陷阱。 + +## App-Code 多应用机制 + +JNPF 支持多业务系统(多应用)部署在同一平台实例中。每个业务系统通过 **App-Code** 进行识别。 + +### 请求链路 + +``` +用户访问 URL 前缀(如 /wj/) + → 前端设置 App-Code 请求头("wj") + → 后端根据 App-Code 查找 base_system 表 + → 获取 systemId + → 按此 systemId 过滤菜单、功能等数据 +``` + +### 配置方式 + +```python +# 创建客户端时指定 app_code +client = JNPFClient(base_url="http://localhost:30000", app_code="wj") + +# 登录后所有请求自动携带 App-Code 请求头 +client.login(account="admin", password="xxx") +``` + +### App-Code 不设置的影响 + +如果不设置 `app_code`,请求不会携带 `App-Code` 头,后端默认使用系统平台(`systemId = 309228585019769285`)。这意味着: +- 创建的功能/菜单会归属到系统平台,业务系统中看不到 +- 获取菜单列表时返回的是系统平台菜单,不是业务系统菜单 + +### base_system 表结构 + +通过数据接口或 SQL 可以查看: + +| 字段 | 说明 | +|------|------| +| F_Id | 系统ID(即 systemId) | +| F_EnCode | 系统编码(对应 App-Code) | +| F_FullName | 系统名称 | +| F_DeleteMark | 删除标记(0=正常) | + +## system_id 自动设置 + +### 机制说明 + +JNPF 后端在以下 API 中**自动通过 App-Code 请求头解析并写入 systemId**,**无需手动修正**: + +| API | 后端代码位置 | 行为 | +|-----|------------|------| +| `POST /api/visualdev/Base`(创建表单) | `VisualdevController.java:563` | `entity.setSystemId(getInfoByEnCode(getAppCode()).getId())` | +| `POST /api/visualdev/Base/{id}/Actions/Release`(发布) | `VisualdevController.java:669` | `BeanUtil.copyProperties(visualdevEntity, clone)` 继承 | +| `POST /api/system/Menu`(创建菜单) | `ModuleController.java:173` | `moduleCrForm.setSystemId(info.getId())` | + +流程: +``` +HTTP 请求头 App-Code: wj + → RequestContext.getAppCode() = "wj" + → systemService.getInfoByEnCode("wj") + → SELECT * FROM base_system WHERE F_EnCode = 'wj' + → 返回 SystemEntity.id → 作为 systemId 写入 +``` + +### 验证方法 + +使用 `aibridge/examples/verify_app_code_systemid.py` 脚本可快速验证 App-Code 是否正确写入 systemId。 + +### App-Code 常见错误 + +| 错误现象 | 原因 | 解决方案 | +|---------|------|----------| +| 表单/菜单创建到系统平台而非业务系统 | `app_code` 为空或 `JNPFClient.from_config(config)` 未使用 | 确保 config.py 中 `app_code` 正确,使用 `from_config()` 创建客户端 | +| config.py 中 app_code 为空字符串 `""` | 配置文件未正确设置 | 检查 config.py 中 `app_code: str = "wj"` | +| base_url 缺少端口导致连接失败 | 本地开发用 30000 端口 | 确保 `base_url="http://127.0.0.1:30000"` | +| 不同环境使用不同 app_code | dev/test/prod 环境混淆 | 使用环境变量或 separate config.py | +| systemId 为 `309228585019769285`(系统平台) | App-Code 未生效 | 检查请求头是否正确设置,参见 verify 脚本 | + +## 菜单类型 + +JNPF 菜单有三种类型,通过 `type` 字段区分: + +| type | 说明 | URL 地址 | 典型用途 | +|------|------|----------|----------| +| 1 | 目录菜单 | 空 | 分组导航,类似文件夹 | +| 2 | 页面菜单 | 外部或自定义页面URL | 链接到外部系统 | +| 3 | 功能表单菜单 | `model/{enCode}` | 绑定 VisualDev 功能 | + +### 创建示例 + +```python +from aibridge.modules.menu import MenuAPI + +menu_api = MenuAPI(client) + +# 目录菜单(type=1) +menu_api.create_directory_menu( + full_name="办公用品", + en_code="office_dir", + icon="icon-ym icon-ym-folder", + sort_code=100, + parent_id="-1", +) + +# 功能表单菜单(type=3) +menu_api.create_form_menu( + full_name="文具订单", + en_code="stationeryOrder", + visual_dev_id="func_id", + parent_id="parent_dir_id", + web_type=2, # 2=表单加列表 +) +``` + +### propertyJson 说明 + +功能菜单的 `propertyJson` 包含关键绑定信息: + +```json +{ + "iconBackgroundColor": "", + "isTree": 0, + "moduleId": "功能ID(base_visual_dev 的 F_Id)", + "webType": 2 +} +``` + +## VisualDev 发布流程 + +``` +设计功能(base_visual_dev, state=0) + │ + ▼ 调用 Release API +发布功能(复制到 base_visual_release, state=1) + │ + ▼ 生成菜单(base_module) + │ + ▼ 前端可见(App-Code 自动设置 systemId) +``` + +**关键点:** +- 未发布的功能(`state=0`)无法在前端使用 +- 发布操作会将 `base_visual_dev` 的数据复制到 `base_visual_release`,并将 `state` 设为 1 +- 每次发布都是全量覆盖,不是增量 +- systemId 由 App-Code 请求头自动设置,创建表单/菜单时无需手动指定 + +## 数据接口 SQL 执行 + +通过 `DataInterfaceAPI.execute()` 直接调用数据接口的 Preview 端点执行 SQL。 + +详见 [数据接口文档](../datainterface/README.md)。 + +## 数据模型约定 + +### 系统字段 + +每个业务表自动包含以下系统字段,由后端 `FlowFormDataUtil.generalInsert` 自动管理: + +| 字段名 | 说明 | 数据类型 | +|--------|------|----------| +| `F_Id` | 主键 | varchar(50) | +| `f_flow_task_id` | 流程任务ID | varchar(50) | +| `f_flow_id` | 流程ID | varchar(50) | +| `f_flow_state` | 流程状态 | int(9) | +| `f_tenant_id` | 租户ID | varchar(50) | +| `F_Sort_Code` | 排序码 | varchar(50) | +| `F_Create_User` | 创建者 | varchar(50) | +| `F_Create_Time` | 创建时间 | varchar(50) | +| `F_Modify_User` | 修改者 | varchar(50) | +| `F_Modify_Time` | 修改时间 | varchar(50) | + +### 命名规范 + +- 主键:`F_Id`(大写 F 前缀) +- 业务字段:`f_field_name`(小写 f 前缀 + snake_case) +- 流程字段:`f_flow_*`(小写 f 前缀 + 下划线) +- 审计字段:`F_Create_*`、`F_Modify_*`(大写 F 前缀 + PascalCase) + +### 关键约束 + +- `f_delete_mark` 字段不能为 NULL,应为 0(正常)或 1(已删除) +- `f_tenant_id` 在多租户模式下自动填充,单租户可以为空 +- `F_Id` 由后端自动生成(通常为雪花ID),无需手动指定 + +## 分类 ID(Category) + +VisualDev 功能和扩展接口都需要指定 `category`(分类ID)。分类在平台中预先创建。 + +### 使用 config.py 中的默认分类ID + +推荐使用 `config.py` 中预定义的分类ID: + +```python +from aibridge import JNPFConfig + +config = JNPFConfig() + +# 功能表单分类(用于 VisualDev 功能) +business_category_id = config.business_category_id # 功能表单分类ID +print(f"功能表单分类: {business_category_id}") + +# 扩展接口分类(用于 DataInterface) +interface_category_id = config.interface_category_id # 扩展接口分类ID +print(f"扩展接口分类: {interface_category_id}") +``` + +### 获取分类ID的方式 + +1. **从 config.py 直接使用**(推荐):配置文件中已预设业务系统的分类ID +2. **从平台界面查看**:数据中心 → 字典管理 → 查看分类编码 +3. **通过 API 查询**: + +```python +# 获取功能列表并查看分类 +resp = visual_dev.get_list() +for item in resp.data.get("list", []): + print(f"分类ID: {item.get('category')}") + +# 获取数据接口列表并查看分类 +resp = di.get_list({"category": "扩展接口分类ID"}) +``` + +### 常见分类 + +常见分类由各业务系统自行定义,没有统一的全局分类。AIBridge 配置文件中的分类ID对应各业务系统的特定分类(示例中的 `aistudio` 仅供参考)。 + +## 多租户与数据库隔离 + +### 核心概念 + +JNPF 支持多租户部署。启用多租户后,数据库访问存在两条路径: + +| 访问方式 | 数据库连接 | 租户过滤 | 典型场景 | +|---------|----------|---------|---------| +| MyBatis-Plus API(标准 CRUD) | 租户库 | 自动(框架拦截器) | `visual_dev.create()`、`menu.get_list()` 等 | +| DI Preview(SQL 直连) | `dbLinkId` 指定的库 | 无 | `DataInterfaceAPI.execute()` | + +### DI Preview 的数据库连接 + +DI Preview 通过 `dbLinkId` 确定连接哪个数据库: + +```python +# dbLinkId=0 连接主库(默认) +payload = DataInterfaceAPI.build_payload(..., db_link_id="0") +``` + +**关键差异**: +- `base_data_interface`(数据接口配置表)等系统表的数据在**租户库**中, + 通过 MyBatis-Plus API 可以正常 CRUD,但 DI Preview 的 SQL 查不到。 +- `base_visual_dev`(可视化开发表)等业务表在**主库**中, + DI Preview 可以直接查询。 + +### 影响范围 + +当通过 DI Preview 执行 SQL 时,只能访问主库中的表。如果需要操作租户库数据,应使用标准 API 而非 DI SQL。 + +### 如何确认表在哪个库 + +```python +# 创建临时 DI 执行 COUNT 查询 +di = DataInterfaceAPI(client) +test_id = di.create_sql_interface( + "检查", "check", "SELECT COUNT(*) as cnt FROM 目标表", + [], category="xxx", action=3, +) +result = di.execute(test_id, {}) +cnt = result[0]["cnt"] if result else 0 +di.safe_delete(test_id) +# cnt > 0 表示表在主库中可访问 +``` + +## Token 认证机制 + +### 登录 + +```python +# POST /api/oauth/Login(form-urlencoded 格式) +# ★ 密码必须是 96 字符 AES 密文(从浏览器提取,Python 无法生成正确密文) +resp = client.login(account="admin", password="d4958348...") # 96字符AES密文 +# 返回 token: "bearer eyJhbGciOiJIUzI1NiJ9..." +``` + +### Token 格式 + +Token 格式为 `bearer {jwt}`,**注意 `bearer` 是小写**。AIBridge 会自动处理前缀: + +```python +# 如果 token 已有 "bearer " 前缀,直接使用 +client.login_by_token("bearer eyJ...") + +# 如果没有前缀,自动添加 +client.login_by_token("eyJ...") # 会自动变为 "bearer eyJ..." +``` + +### Token 生命周期 + +- Token 存储在 `client.token` 属性中 +- 每次请求自动携带 `Authorization` 请求头 +- Token 过期后需要重新登录 + +### 请求头约定 + +AIBridge 发出的请求头(与前端 `request.ts` 对齐): + +| 头 | 值 | 说明 | +|-----|----|------| +| `Authorization` | `bearer eyJ...` | 认证令牌(小写 bearer) | +| `App-Code` | `wj` | 多应用识别码 | +| `Jnpf-Origin` | `pc` | 来源标识 | +| `Vue-Version` | `3` | Vue 版本标识 | +| `Content-Type` | `application/json` | 默认 | diff --git a/docs/portal/01-overview.md b/docs/portal/01-overview.md new file mode 100644 index 0000000..f0ff95b --- /dev/null +++ b/docs/portal/01-overview.md @@ -0,0 +1,173 @@ +# 门户概述与核心概念 + +## 核心实体 + +### PortalEntity (base_portal) + +门户主表,存储门户的基本信息和配置。 + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | string | 门户ID(雪花算法) | +| fullName | string | 门户名称 | +| enCode | string | 门户编码(唯一) | +| category | string | 分类(数据字典维护) | +| type | int | 类型: 0=页面设计, 1=自定义路径 | +| customUrl | string | 静态页面路径(type=1时) | +| linkType | int | 链接类型: 0=页面, 1=外链 | +| state | int | 状态: 0=禁用, 1=启用 | +| enabledLock | int | 移动锁定: 0=未锁定, 1=锁定 | +| platformRelease | string | 发布平台配置 JSON: `{"pc":1,"app":1}` | +| systemId | string | 所属系统ID | +| formData | string | 门户配置JSON(base_portal_data) | + +### PortalDataEntity (base_portal_data) + +门户数据表,存储门户的组件配置。 + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | string | 数据ID | +| portalId | string | 所属门户ID | +| platform | string | 平台: Web=网页端, App=手机端 | +| formData | string | 表单配置JSON(组件布局) | +| systemId | string | 系统ID | +| type | string | 类型: mod=模型, custom=自定义, release=发布 | + +--- + +## 三种数据模式 + +### 1. model (模板模式) +- **用途**: 门户设计的草稿状态 +- **创建**: `client.portal.create({"type": "model", ...})` +- **更新**: `client.portal.update(data)` +- **特点**: 完整的组件配置,可反复修改 + +### 2. custom (自定义模式) +- **用途**: 用户个性化定制 +- **触发**: 用户拖拽调整门户布局后自动保存 +- **更新**: `client.portal.update_custom_portal(portal_id, data)` +- **特点**: 仅保存用户自定义部分,与 model 合并渲染 + +### 3. release (发布模式) +- **用途**: 正式发布的生产版本 +- **触发**: 调用 `client.portal.release(portal_id)` +- **特点**: 只读,供最终用户访问 + +--- + +## 组件通用属性 + +每个组件都包含以下基础结构: + +```json +{ + "i": 1, + "x": 0, + "y": 0, + "jnpfKey": "组件标识", + "title": "组件标题", + "visibility": ["pc", "app"], + "card": { + "titleFontSize": 14, + "titleFontWeight": false, + "titleFontColor": "#303133", + "titleLeft": "left", + "titleBgColor": "", + "cardIcon": "icon-ym icon-ym-xxx", + "cardIconColor": "#606266", + "linkType": "", + "moduleId": "", + "urlAddress": "", + "linkTarget": "_self" + }, + "w": 6, + "h": 4, + "minW": 1, + "minH": 3, + "maxW": 12, + "maxH": 20, + "dataType": "static", + "propsApi": "", + "option": {}, + "refresh": { + "autoRefresh": false, + "autoRefreshTime": 5 + } +} +``` + +### 通用属性说明 + +| 属性 | 类型 | 说明 | +|------|------|------| +| jnpfKey | string | 组件唯一标识 | +| title | string | 组件显示标题 | +| visibility | array | 显示平台: `["pc"]`, `["app"]`, `["pc", "app"]` | +| card | object | 卡片配置(标题、图标、链接等) | +| w | int | 宽度(1-12 栅格) | +| h | int | 高度 | +| minW/minH | int | 最小宽/高度 | +| maxW/maxH | int | 最大宽/高度 | +| dataType | string | 数据类型: `static`(静态), `dynamic`(动态接口) | +| propsApi | string | 数据接口ID(dynamic模式) | +| option | object | 组件特定配置 | +| refresh | object | 自动刷新配置 | + +--- + +## 布局配置 + +门户的完整配置结构: + +```json +{ + "layoutId": 100, + "layout": [ + { + "i": 1, + "x": 0, + "y": 0, + "w": 6, + "h": 4, + "jnpfKey": "dataBoard", + "title": "关键指标" + } + ], + "refresh": { + "autoRefresh": false, + "autoRefreshTime": "5" + } +} +``` + +--- + +## 链接配置 + +组件的卡片支持链接跳转: + +```json +{ + "linkType": "", + "type": "", + "moduleId": "", + "urlAddress": "", + "linkTarget": "_self", + "appLinkType": "", + "appType": "", + "appModuleId": "", + "appUrlAddress": "" +} +``` + +| 属性 | 说明 | +|------|------| +| linkType | PC端链接类型: 空=无, 1=菜单, 2=外链 | +| moduleId | 菜单ID(linkType=1时) | +| urlAddress | 跳转地址 | +| linkTarget | 打开方式: `_self`(本页), `_blank`(新页) | +| appLinkType | APP端链接类型 | +| appModuleId | APP端菜单ID | +| appUrlAddress | APP端跳转地址 | diff --git a/docs/portal/02-component-types.md b/docs/portal/02-component-types.md new file mode 100644 index 0000000..11efebe --- /dev/null +++ b/docs/portal/02-component-types.md @@ -0,0 +1,590 @@ +# 21种组件类型详解 + +## 组件分类总览 + +| 类别 | jnpfKey | 数量 | 说明 | +|------|---------|------|------| +| 布局控件 | card, tab | 2 | 容器组件 | +| 基础控件 | text, image, carousel, video, iframe | 5 | 基础内容展示 | +| 系统控件 | todo, todoList, notice | 4 | 系统功能集成 | +| 图表控件 | dataBoard, tableList, barChart, pieChart, lineChart, radarChart, timeAxis, rankList, mapChart, customEcharts | 10 | 数据可视化 | +| 筛选控件 | filter | 1 | 数据筛选 | + +--- + +## 1. 布局控件 (Layout) + +### 1.1 卡片面板 (card) + +容器组件,可包含子组件。 + +```json +{ + "jnpfKey": "card", + "title": "卡片面板", + "visibility": ["pc", "app"], + "w": 6, "h": 6, + "minW": 1, "minH": 4, + "maxW": 12, "maxH": 12, + "card": { + "titleFontSize": 14, + "titleFontWeight": false, + "titleFontColor": "#303133", + "titleLeft": "left", + "titleBgColor": "", + "cardIcon": "icon-ym icon-ym-portal-card", + "cardIconColor": "#606266" + }, + "children": [] +} +``` + +### 1.2 标签面板 (tab) + +多标签页容器。 + +```json +{ + "jnpfKey": "tab", + "title": "标签面板", + "visibility": ["pc", "app"], + "tabPosition": "top", + "active": "1", + "children": [ + { "title": "Tab 1", "name": "1", "icon": "", "children": [] }, + { "title": "Tab 2", "name": "2", "icon": "", "children": [] } + ], + "card": { "titleFontSize": 14 } +} +``` + +--- + +## 2. 基础控件 (Basic) + +### 2.1 文本 (text) + +```json +{ + "jnpfKey": "text", + "title": "文本", + "visibility": ["pc", "app"], + "dataType": "static", + "propsApi": "", + "w": 4, "h": 3, + "option": { + "styleType": 1, + "defaultValue": "静态文本内容", + "textFontSize": 14, + "textFontColor": "#303133", + "textFontWeight": false, + "textLeft": "left", + "textBgColor": "", + "textAutoplay": false, + "textAutoplayMode": "left", + "textAutoplaySpeed": 60 + } +} +``` + +### 2.2 图片 (image) + +```json +{ + "jnpfKey": "image", + "title": "图片", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 6, + "option": { + "styleType": 2, + "defaultValue": "", + "textDefaultValue": "JNPF快速开发平台", + "imageFillStyle": "cover" + } +} +``` + +### 2.3 轮播图 (carousel) + +```json +{ + "jnpfKey": "carousel", + "title": "轮播图", + "visibility": ["pc", "app"], + "w": 6, "h": 6, + "option": { + "defaultValue": [ + { + "imageUrl": "https://app.cdn.jnpfsoft.com/image/3.2/banner1.png", + "dataType": 2, + "linkType": "", + "urlAddress": "", + "linkTarget": "_self" + } + ], + "carouselAutoplay": true, + "carouselDirection": "horizontal", + "carouselInterval": 3000, + "carouselIndicatorPosition": "bottomRight", + "carouselArrow": "never", + "carouselLoop": true, + "imageFillStyle": "cover" + } +} +``` + +### 2.4 视频 (video) + +```json +{ + "jnpfKey": "video", + "title": "视频", + "visibility": ["pc", "app"], + "w": 6, "h": 6, + "option": { + "styleType": 2, + "defaultValue": "", + "videoAutoplay": true, + "playNumber": 2, + "mutePlay": false + } +} +``` + +### 2.5 Iframe (iframe) + +仅PC端支持。 + +```json +{ + "jnpfKey": "iframe", + "title": "Iframe", + "visibility": ["pc"], + "w": 12, "h": 8, + "option": { + "defaultValue": "https://www.jnpfsoft.com/" + } +} +``` + +--- + +## 3. 系统控件 (System) + +### 3.1 我的待办 (todo) + +流程待办事项聚合组件。 + +```json +{ + "jnpfKey": "todo", + "title": "我的待办", + "visibility": ["pc", "app"], + "w": 12, "h": 4, + "option": { + "styleType": 1, + "defaultValue": [ + { "fullName": "流程待签", "id": "flowToSign", "noShow": false, "num": 0, + "urlAddress": "/workFlow/flowToSign", "icon": "icon-ym icon-ym-flowToSign", "iconBgColor": "#1997f4" }, + { "fullName": "流程待办", "id": "flowTodo", "noShow": false, "num": 0, + "urlAddress": "/workFlow/flowTodo", "icon": "icon-ym icon-ym-flowTodo", "iconBgColor": "#f29700" }, + { "fullName": "流程在办", "id": "flowDoing", "noShow": false, "num": 0, + "urlAddress": "/workFlow/flowDoing", "icon": "icon-ym icon-ym-flowDoing", "iconBgColor": "#495dfd" }, + { "fullName": "流程已办", "id": "flowDone", "noShow": false, "num": 0, + "urlAddress": "/workFlow/flowDone", "icon": "icon-ym icon-ym-flowDone", "iconBgColor": "#7b1ae1" }, + { "fullName": "流程抄送", "id": "flowCirculate", "noShow": false, "num": 0, + "urlAddress": "/workFlow/flowCirculate", "icon": "icon-ym icon-ym-flowCirculate", "iconBgColor": "#33b932" } + ], + "rowNumber": 5, + "showBorder": false, + "labelFontSize": 14, + "valueFontSize": 24, + "valueFontWeight": true + } +} +``` + +### 3.2 待签事项 (todoList, type=0) + +```json +{ + "jnpfKey": "todoList", + "title": "待签事项", + "type": 0, + "visibility": ["pc", "app"], + "w": 6, "h": 7 +} +``` + +### 3.3 待办事项 (todoList, type=1) + +```json +{ + "jnpfKey": "todoList", + "title": "待办事项", + "type": 1, + "visibility": ["pc", "app"], + "w": 6, "h": 7 +} +``` + +### 3.4 在办事项 (todoList, type=2) + +```json +{ + "jnpfKey": "todoList", + "title": "在办事项", + "type": 2, + "visibility": ["pc", "app"], + "w": 6, "h": 7 +} +``` + +### 3.5 公告通知 (notice) + +```json +{ + "jnpfKey": "notice", + "title": "公告通知", + "visibility": ["pc", "app"], + "w": 12, "h": 7, + "option": { + "border": true, + "showOverflow": true, + "showHeader": true, + "styleType": 1, + "showImage": true, + "headerFontSize": 14, + "headerBgColor": "#F3F6F9", + "tableIndex": true, + "noticeCount": 5, + "tableFontSize": 14, + "describe": false, + "showText": true, + "columnData": [ + { "fullName": "类型", "fieldName": "classify", "show": true }, + { "fullName": "标题", "fieldName": "fullName", "show": true }, + { "fullName": "创建人", "fieldName": "creatorUser", "show": true }, + { "fullName": "创建时间", "fieldName": "creatorTime", "show": true } + ] + } +} +``` + +--- + +## 4. 图表控件 (Chart) + +### 4.1 数据面板 (dataBoard) + +数字统计卡片。 + +```json +{ + "jnpfKey": "dataBoard", + "title": "数据面板", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 12, "h": 4, + "option": { + "styleType": 1, + "defaultValue": [ + { "fullName": "新增客户", "unit": "个", "num": 262, + "icon": "icon-ym icon-ym-wf-contractApproval", "iconColor": "rgb(123, 26, 225)" }, + { "fullName": "新增商机", "unit": "个", "num": 199, + "icon": "icon-ym icon-ym-wf-outgoingApply", "iconColor": "rgb(74, 184, 255)" }, + { "fullName": "合同金额", "unit": "元", "num": 126263.5, + "icon": "icon-ym icon-ym-wf-payDistribution", "iconColor": "rgb(255, 139, 88)" }, + { "fullName": "回款金额", "unit": "元", "num": 6223.2, + "icon": "icon-ym icon-ym-wf-incomeRecognition", "iconColor": "rgb(252, 91, 135)" } + ], + "rowNumber": 4, + "showBorder": false, + "labelFontSize": 14, + "valueFontSize": 24, + "valueFontWeight": true + } +} +``` + +### 4.2 表格列表 (tableList) + +```json +{ + "jnpfKey": "tableList", + "title": "表格列表", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "option": { + "border": true, + "showOverflow": true, + "showHeader": true, + "tableIndex": true, + "tableCount": 5, + "columnData": [ + { "fullName": "排名", "fieldName": "inputField101", "width": 0 }, + { "fullName": "姓名", "fieldName": "inputField102", "width": 0 }, + { "fullName": "销售额", "fieldName": "inputField103", "width": 0 }, + { "fullName": "完成情况", "fieldName": "inputField104", "width": 0 } + ], + "target": "_self", + "urlAddress": "" + } +} +``` + +### 4.3 柱状图 (barChart) + +```json +{ + "jnpfKey": "barChart", + "title": "柱状图", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "系列", "value": "" }, + { "field": "维度", "value": "" }, + { "field": "数值", "value": "" } + ], + "option": { + "styleType": 1, + "seriesBarWidth": 30, + "xAxisShow": true, + "yAxisShow": true, + "seriesLabelShow": true, + "tooltipShow": true, + "legendShow": true, + "gridLeft": 20, + "gridTop": 50, + "gridRight": 20, + "gridBottom": 20 + } +} +``` + +### 4.4 饼图 (pieChart) + +```json +{ + "jnpfKey": "pieChart", + "title": "饼图", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "系列", "value": "" }, + { "field": "维度", "value": "" }, + { "field": "数值", "value": "" } + ], + "option": { + "roseType": false, + "seriesLabelShow": true, + "seriesLabelPosition": "outside", + "seriesCenterLeft": 50, + "seriesCenterTop": 50 + } +} +``` + +### 4.5 折线图 (lineChart) + +```json +{ + "jnpfKey": "lineChart", + "title": "折线图", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "系列", "value": "" }, + { "field": "维度", "value": "" }, + { "field": "数值", "value": "" } + ], + "option": { + "areaStyle": false, + "seriesLineStyleWidth": 2, + "seriesSymbolRotate": 4 + } +} +``` + +### 4.6 雷达图 (radarChart) + +```json +{ + "jnpfKey": "radarChart", + "title": "雷达图", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "系列", "value": "" }, + { "field": "维度", "value": "" }, + { "field": "数值", "value": "" }, + { "field": "最大值", "value": "" } + ], + "option": { + "radarAxisNameFontSize": 14, + "seriesAreaStyleOpacity": 0.3, + "radarCenterLeft": 50, + "radarCenterTop": 50 + } +} +``` + +### 4.7 时间轴 (timeAxis) + +```json +{ + "jnpfKey": "timeAxis", + "title": "时间轴", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "内容", "value": "" }, + { "field": "时间戳", "value": "" } + ], + "option": { + "styleType": 1, + "layout": 1, + "sortable": 1 + } +} +``` + +### 4.8 排行榜 (rankList) + +```json +{ + "jnpfKey": "rankList", + "title": "排行榜", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "option": { + "styleType": 1, + "columnOptions": [ + { "label": "部门", "value": "label" }, + { "label": "金额", "value": "value" } + ] + } +} +``` + +### 4.9 地图 (mapChart) + +仅PC端支持。 + +```json +{ + "jnpfKey": "mapChart", + "title": "地图", + "visibility": ["pc"], + "dataType": "static", + "w": 6, "h": 8, + "mappingConfig": [ + { "field": "维度", "value": "" }, + { "field": "数值", "value": "" }, + { "field": "经度", "value": "" }, + { "field": "纬度", "value": "" } + ], + "option": { + "mapType": ["100000"], + "geoAreaColor": "#eee", + "geoBorderColor": "#606266", + "geoRoam": true, + "drillDown": true, + "visualMapMin": 0, + "visualMapMax": 200, + "seriesType": "effectScatter" + } +} +``` + +### 4.10 自定义echart (customEcharts) + +```json +{ + "jnpfKey": "customEcharts", + "title": "自定义echart", + "visibility": ["pc", "app"], + "dataType": "static", + "w": 6, "h": 8, + "option": "", + "appOption": "" +} +``` + +--- + +## 5. 筛选控件 (Filter) + +### 5.1 筛选器 (filter) + +```json +{ + "jnpfKey": "filter", + "title": "筛选器", + "visibility": ["pc", "app"], + "w": 6, "h": 3, + "option": { + "showActionButtonGroup": true, + "colCount": 12, + "filterList": [ + { + "id": "keyWord", + "fullName": "关键词", + "filterInfo": [], + "sourceType": 2, + "defaultValue": "" + } + ] + } +} +``` + +--- + +## 动态数据配置 + +图表组件支持动态数据接口: + +```json +{ + "dataType": "dynamic", + "propsApi": "数据接口ID", + "mappingConfig": [ + { "field": "维度", "value": "接口返回字段名" }, + { "field": "数值", "value": "接口返回字段名" } + ] +} +``` + +| dataType | 说明 | +|----------|------| +| static | 使用 option.defaultValue 中的静态数据 | +| dynamic | 调用 propsApi 指定的数据接口获取数据 | + +--- + +## 刷新配置 + +所有组件支持自动刷新: + +```json +{ + "refresh": { + "autoRefresh": true, + "autoRefreshTime": 5 + } +} +``` + +| 属性 | 类型 | 说明 | +|------|------|------| +| autoRefresh | boolean | 是否自动刷新 | +| autoRefreshTime | int | 刷新间隔(秒) | diff --git a/docs/portal/03-api-reference.md b/docs/portal/03-api-reference.md new file mode 100644 index 0000000..ede5620 --- /dev/null +++ b/docs/portal/03-api-reference.md @@ -0,0 +1,319 @@ +# API 完整参考 + +## PortalAPI 方法清单 + +### 门户 CRUD + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `get_list(data)` | GET | `/api/visualdev/Portal` | 获取门户列表 | +| `get_info(portal_id)` | GET | `/api/visualdev/Portal/{id}` | 获取门户详情 | +| `create(data)` | POST | `/api/visualdev/Portal` | 创建门户 | +| `update(data)` | PUT | `/api/visualdev/Portal/{id}` | 更新门户 | +| `delete(portal_id)` | DELETE | `/api/visualdev/Portal/{id}` | 删除门户 | + +### 门户操作 + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `copy(portal_id)` | POST | `/api/visualdev/Portal/{id}/Actions/Copy` | 复制门户 | +| `export_portal(portal_id)` | POST | `/api/visualdev/Portal/{id}/Actions/Export` | 导出门户 | +| `release(portal_id, data)` | PUT | `/api/visualdev/Portal/Actions/release/{id}` | 发布门户 | +| `set_default(portal_id)` | PUT | `/api/visualdev/Portal/{id}/Actions/SetDefault` | 设置默认门户 | +| `get_auth_portal(portal_id, data)` | GET | `/api/visualdev/Portal/{id}/auth` | 获取权限数据 | +| `update_custom_portal(portal_id, data)` | PUT | `/api/visualdev/Portal/Custom/Save/{id}` | 更新自定义布局 | + +### 选择器 + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `get_selector(type_, system_id)` | GET | `/api/visualdev/Portal/Selector` | 获取下拉列表 | +| `get_home_portal_list()` | GET | `/api/visualdev/Portal/Selector/Menu` | 获取首页门户 | +| `get_system_filter(data, id_)` | GET | `/api/visualdev/Portal/systemFilter/{id}` | 获取系统过滤列表 | + +### 仪表盘 + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `get_notice_list(data)` | POST | `/api/visualdev/Dashboard/Notice` | 获取通知公告 | +| `get_email_list()` | GET | `/api/visualdev/Dashboard/Email` | 获取未读邮件 | + +### 门户管理 + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `get_manage_list(data)` | GET | `/api/system/PortalManage/list/{systemId}` | 获取管理列表 | +| `get_manage_selector(data)` | GET | `/api/visualdev/Portal/manage/Selector/{systemId}` | 获取名称列表 | +| `get_manage_info(manage_id)` | GET | `/api/system/PortalManage/{id}` | 获取管理详情 | +| `create_manage(data)` | POST | `/api/system/PortalManage` | 创建管理 | +| `update_manage(data)` | PUT | `/api/system/PortalManage/{id}` | 更新管理 | +| `delete_manage(manage_id)` | DELETE | `/api/system/PortalManage/{id}` | 删除管理 | + +### 地图 + +| AIBridge 方法 | HTTP | 路径 | 说明 | +|---------------|------|------|------| +| `get_atlas()` | GET | `/api/system/atlas` | 获取全国省市区 | +| `get_map_data(data)` | GET | `/api/system/atlas/geojson` | 获取地图JSON | + +--- + +## 方法签名与示例 + +### get_list(data: dict = None) + +```python +# 获取门户列表(分页) +resp = client.portal.get_list({ + "currentPage": 1, + "pageSize": 20, + "keyword": "", + "type": "model", + "systemId": "system_xxx" +}) +# GET /api/visualdev/Portal?currentPage=1&pageSize=20&keyword=&type=model&systemId=system_xxx +``` + +### get_info(portal_id: str) + +```python +# 获取门户详情 +resp = client.portal.get_info("584307160905678853") +# GET /api/visualdev/Portal/584307160905678853 +``` + +### create(data: dict) + +```python +# 创建门户 +resp = client.portal.create({ + "fullName": "销售看板", + "enCode": "sales_dashboard", + "type": 0, + "systemId": "system_xxx", + "state": 1, + "category": "", + "enabledLock": 0 +}) +# POST /api/visualdev/Portal +``` + +### update(data: dict) + +```python +# 更新门户 +resp = client.portal.update({ + "id": "portal_xxx", + "fullName": "销售看板(更新)", + "formData": '{"layoutId":100,"layout":[]}' +}) +# PUT /api/visualdev/Portal/portal_xxx +``` + +### delete(portal_id: str) + +```python +# 删除门户 +resp = client.portal.delete("portal_xxx") +# DELETE /api/visualdev/Portal/portal_xxx +``` + +### copy(portal_id: str) + +```python +# 复制门户 +resp = client.portal.copy("584307160905678853") +# POST /api/visualdev/Portal/584307160905678853/Actions/Copy +``` + +### export_portal(portal_id: str) + +```python +# 导出门户 +resp = client.portal.export_portal("584307160905678853") +# POST /api/visualdev/Portal/584307160905678853/Actions/Export +``` + +### release(portal_id: str, data: dict = None) + +```python +# 发布门户 +resp = client.portal.release("portal_xxx", { + "systemId": "system_xxx" +}) +# PUT /api/visualdev/Portal/Actions/release/portal_xxx +``` + +### set_default(portal_id: str) + +```python +# 设置默认门户 +resp = client.portal.set_default("portal_xxx") +# PUT /api/visualdev/Portal/portal_xxx/Actions/SetDefault?platform=Web +``` + +### get_auth_portal(portal_id: str, data: dict = None) + +```python +# 获取权限数据 +resp = client.portal.get_auth_portal("portal_xxx", { + "platform": "Web" +}) +# GET /api/visualdev/Portal/portal_xxx/auth?platform=Web +``` + +### update_custom_portal(portal_id: str, data: dict) + +```python +# 用户自定义保存 +resp = client.portal.update_custom_portal("portal_xxx", { + "formData": '{"layoutId":100,"layout":[]}' +}) +# PUT /api/visualdev/Portal/Custom/Save/portal_xxx +``` + +### get_selector(type_: str = None, system_id: str = None) + +```python +# 获取门户下拉选项 +resp = client.portal.get_selector(type_="model", system_id="system_xxx") +# GET /api/visualdev/Portal/Selector?platform=Web&type=model&systemId=system_xxx +``` + +### get_home_portal_list() + +```python +# 获取应用首页门户列表 +resp = client.portal.get_home_portal_list() +# GET /api/visualdev/Portal/Selector/Menu +``` + +### get_system_filter(data: dict, id_: str) + +```python +# 获取应用列表(发布过滤) +resp = client.portal.get_system_filter({"systemId": "system_xxx"}, "portal_xxx") +# GET /api/visualdev/Portal/systemFilter/portal_xxx?systemId=system_xxx +``` + +### get_notice_list(data: dict) + +```python +# 获取通知公告 +resp = client.portal.get_notice_list({ + "size": 5 +}) +# POST /api/visualdev/Dashboard/Notice +``` + +### get_email_list() + +```python +# 获取未读邮件 +resp = client.portal.get_email_list() +# GET /api/visualdev/Dashboard/Email +``` + +### get_manage_list(data: dict) + +```python +# 获取门户管理列表 +resp = client.portal.get_manage_list({ + "systemId": "system_xxx" +}) +# GET /api/system/PortalManage/list/system_xxx +``` + +### get_manage_info(manage_id: str) + +```python +# 获取门户管理详情 +resp = client.portal.get_manage_info("manage_xxx") +# GET /api/system/PortalManage/manage_xxx +``` + +### create_manage(data: dict) + +```python +# 创建门户管理 +resp = client.portal.create_manage({ + "portalId": "portal_xxx", + "systemId": "system_xxx", + "homeShow": 1, + "defaultPortal": 0, + "sort": 1, + "enabled": 1 +}) +# POST /api/system/PortalManage +``` + +### update_manage(data: dict) + +```python +# 更新门户管理 +resp = client.portal.update_manage({ + "id": "manage_xxx", + "portalId": "portal_xxx", + "systemId": "system_xxx", + "homeShow": 1, + "defaultPortal": 1 +}) +# PUT /api/system/PortalManage/manage_xxx +``` + +### delete_manage(manage_id: str) + +```python +# 删除门户管理 +resp = client.portal.delete_manage("manage_xxx") +# DELETE /api/system/PortalManage/manage_xxx +``` + +### get_atlas() + +```python +# 获取全国省市区 +resp = client.portal.get_atlas() +# GET /api/system/atlas +``` + +### get_map_data(data: dict) + +```python +# 获取地图JSON +resp = client.portal.get_map_data({ + "code": "100000" +}) +# GET /api/system/atlas/geojson?code=100000 +``` + +--- + +## 响应格式 + +所有方法返回 `APIResponse` 对象: + +```python +resp = client.portal.get_list() +print(resp.code) # 200 +print(resp.msg) # "操作成功" +print(resp.data) # 实际数据 +print(resp.success) # True +``` + +分页数据: + +```python +{ + "code": 200, + "data": { + "list": [...], + "pagination": { + "currentPage": 1, + "pageSize": 20, + "total": 100 + } + }, + "msg": "操作成功" +} +``` diff --git a/docs/portal/04-portal-management.md b/docs/portal/04-portal-management.md new file mode 100644 index 0000000..eeb97ad --- /dev/null +++ b/docs/portal/04-portal-management.md @@ -0,0 +1,152 @@ +# 门户管理机制 + +## PortalManage 与 Portal 的关系 + +PortalManage 是门户的「管理配置」层,定义门户与具体应用(system)的绑定关系。 + +### PortalManageEntity + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | string | 管理配置ID | +| portalId | string | 关联门户ID | +| systemId | string | 应用系统ID | +| homeShow | int | 首页展示: 0=否, 1=是 | +| defaultPortal | int | 默认门户: 0=否, 1=是 | +| sort | int | 排序 | +| enabled | int | 状态: 0=禁用, 1=启用 | + +--- + +## 管理 API + +### get_manage_list(data: dict) + +获取应用下的门户管理列表。 + +```python +resp = client.portal.get_manage_list({"systemId": "system_xxx"}) +# GET /api/system/PortalManage/list/system_xxx +``` + +### get_manage_selector(data: dict) + +获取门户名称下拉列表。 + +```python +resp = client.portal.get_manage_selector({"systemId": "system_xxx"}) +# GET /api/visualdev/Portal/manage/Selector/system_xxx +``` + +### get_manage_info(manage_id: str) + +获取门户管理详情。 + +```python +resp = client.portal.get_manage_info("manage_xxx") +# GET /api/system/PortalManage/manage_xxx +``` + +### create_manage(data: dict) + +创建门户管理配置。 + +```python +resp = client.portal.create_manage({ + "portalId": "portal_xxx", + "systemId": "system_xxx", + "homeShow": 1, + "defaultPortal": 0, + "sort": 1, + "enabled": 1 +}) +# POST /api/system/PortalManage +``` + +### update_manage(data: dict) + +更新门户管理配置。 + +```python +resp = client.portal.update_manage({ + "id": "manage_xxx", + "portalId": "portal_xxx", + "systemId": "system_xxx", + "homeShow": 1, + "defaultPortal": 1 +}) +# PUT /api/system/PortalManage/manage_xxx +``` + +### delete_manage(manage_id: str) + +删除门户管理配置。 + +```python +resp = client.portal.delete_manage("manage_xxx") +# DELETE /api/system/PortalManage/manage_xxx +``` + +--- + +## 使用场景 + +### 场景1: 多系统复用同一门户 + +一个门户可以发布到多个应用系统: + +```python +# 创建管理配置 - 系统A +client.portal.create_manage({ + "portalId": "portal_xxx", + "systemId": "system_a", + "homeShow": 1, + "defaultPortal": 1 +}) + +# 创建管理配置 - 系统B +client.portal.create_manage({ + "portalId": "portal_xxx", + "systemId": "system_b", + "homeShow": 1, + "defaultPortal": 0 +}) +``` + +### 场景2: 设置默认门户 + +用户登录后显示的默认门户: + +```python +# 方式1: 通过门户管理设置 +client.portal.update_manage({ + "id": "manage_xxx", + "defaultPortal": 1 +}) + +# 方式2: 直接设置 +client.portal.set_default("portal_xxx") +``` + +### 场景3: 获取用户可用的门户 + +```python +# 获取首页门户列表 +resp = client.portal.get_home_portal_list() +# GET /api/visualdev/Portal/Selector/Menu +``` + +--- + +## 示例数据 + +base_portal_manage 表数据: + +| ID | 门户ID | 系统ID | 平台 | +|----|--------|--------|------| +| 1815698993213968386 | 585481192002814853 | 423160212987973 | Web | +| 1815698993335603201 | 585481192002814853 | 423160212987973 | App | +| 1815699049069514753 | 584307823228223493 | 423160212987973 | Web | +| 1815699049161789442 | 584307823228223493 | 423160212987973 | App | +| 1815699093642383362 | 584307160905678853 | 423160212987973 | Web | +| 1815699093797572609 | 584307160905678853 | 423160212987973 | App | diff --git a/docs/portal/05-data-modes.md b/docs/portal/05-data-modes.md new file mode 100644 index 0000000..57b0a0d --- /dev/null +++ b/docs/portal/05-data-modes.md @@ -0,0 +1,213 @@ +# 三种数据模式 + +## 模式总览 + +| 模式 | type值 | 数据表字段 | 说明 | +|------|--------|-----------|------| +| **model** | mod | formData | 模板模式,门户设计态 | +| **custom** | custom | formData | 自定义模式,用户个性化定制 | +| **release** | release | formData | 发布模式,正式版本 | + +--- + +## 1. model (模板模式) + +### 用途 +门户设计的草稿状态,包含完整的组件配置。 + +### 创建 +```python +resp = client.portal.create({ + "fullName": "销售看板", + "enCode": "sales_dashboard", + "type": 0, # 0=页面设计 + "systemId": "system_xxx" +}) +portal_id = resp.data.id +``` + +### 更新 +```python +client.portal.update({ + "id": portal_id, + "fullName": "销售看板(更新)", + "formData": json.dumps({ + "layoutId": 100, + "layout": [ + { + "jnpfKey": "dataBoard", + "title": "关键指标", + "w": 12, "h": 4, + "option": { + "styleType": 1, + "defaultValue": [ + {"fullName": "今日销售额", "num": 125000, "unit": "元"} + ] + } + } + ] + }) +}) +``` + +### 特点 +- 可反复修改 +- 保存完整组件配置 +- 发布前必须先设计完成 + +--- + +## 2. custom (自定义模式) + +### 用途 +用户个性化定制,允许用户拖拽调整自己的门户布局。 + +### 更新 +```python +client.portal.update_custom_portal(portal_id, { + "formData": json.dumps({ + "layoutId": 100, + "layout": [ + # 用户自定义的布局 + ] + }) +}) +``` + +### 获取用户定制 +```python +resp = client.portal.get_auth_portal(portal_id, {"platform": "Web"}) +# 返回: custom版本(如有) > release版本 +``` + +### 特点 +- 每个用户独立一份 +- 仅保存用户修改的部分 +- 与 model 合并后渲染 + +--- + +## 3. release (发布模式) + +### 用途 +正式发布的生产版本,供最终用户访问。 + +### 发布 +```python +resp = client.portal.release(portal_id, { + "systemId": "system_xxx" +}) +``` + +### 获取已发布版本 +```python +resp = client.portal.get_auth_portal(portal_id, {"platform": "Web"}) +# 返回: custom版本(优先) > release版本 +``` + +### 特点 +- 只读,不可直接修改 +- 用户看到的最终版本 +- 支持回滚到 model + +--- + +## 数据流转 + +``` +[创建门户] + │ + ▼ +[model - 设计态] + │ update() + │ create_form_data() + ▼ +[发布 release] + │ release() + ▼ +[release - 发布态] + │ + ▼ +[用户访问 get_auth_portal] + │ + ▼ +[用户自定义 custom] + │ update_custom_portal() + ▼ +[custom - 用户定制] +``` + +--- + +## 渲染优先级 + +当用户访问门户时,系统按以下顺序查找可用版本: + +``` +1. custom (用户自定义) - 最高优先 + └─ 如果用户有定制,返回用户定制版本 + +2. release (已发布版本) + └─ 如果没有定制,返回发布版本 + +3. model (设计模板) - 最低优先 + └─ 如果没有发布,返回设计模板 +``` + +--- + +## 代码示例 + +### 完整发布流程 + +```python +import json + +# 1. 创建门户 (model模式) +portal = client.portal.create({ + "fullName": "销售看板", + "enCode": "sales_dashboard", + "type": 0, + "systemId": "system_xxx" +}) +portal_id = portal.data.id + +# 2. 更新门户组件 (model) +client.portal.update({ + "id": portal_id, + "formData": json.dumps({ + "layoutId": 100, + "layout": [ + {"jnpfKey": "dataBoard", "title": "指标", "w": 12, "h": 4} + ] + }) +}) + +# 3. 创建门户管理 +client.portal.create_manage({ + "portalId": portal_id, + "systemId": "system_xxx", + "homeShow": 1, + "defaultPortal": 1 +}) + +# 4. 发布 (release模式) +client.portal.release(portal_id, {"systemId": "system_xxx"}) + +# 5. 用户访问时 (自动返回 custom > release) +resp = client.portal.get_auth_portal(portal_id, {"platform": "Web"}) +``` + +### 用户自定义布局 + +```python +# 用户调整布局后保存 +client.portal.update_custom_portal(portal_id, { + "formData": json.dumps({ + "layoutId": 101, + "layout": [ + # 新的布局 + ] + }) +}) +``` diff --git a/docs/portal/06-release-workflow.md b/docs/portal/06-release-workflow.md new file mode 100644 index 0000000..405c3ce --- /dev/null +++ b/docs/portal/06-release-workflow.md @@ -0,0 +1,205 @@ +# 发布流程 + +## 完整发布流程 + +``` +┌─────────────────────────────────────────────────────────┐ +│ 1. 创建门户 (type=model) │ +│ client.portal.create({...}) │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 2. 设计门户组件 │ +│ client.portal.update({formData: {...}}) │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 3. 创建门户管理配置 │ +│ client.portal.create_manage({...}) │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 4. 发布门户 │ +│ client.portal.release(portal_id, {...}) │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ 5. 设置默认门户 (可选) │ +│ client.portal.set_default(portal_id) │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## 代码示例 + +### 基本发布流程 + +```python +import json +from aibridge import JNPFClient + +client = JNPFClient(base_url="http://localhost:30000", app_code="myapp") +client.login("admin", password) + +system_id = "your_system_id" + +# 1. 创建门户 +portal = client.portal.create({ + "fullName": "销售数据看板", + "enCode": "sales_dashboard", + "type": 0, # 0=页面设计 + "systemId": system_id, + "state": 1 +}) +portal_id = portal.data.id +print(f"门户创建成功: {portal_id}") + +# 2. 设计门户组件 +layout_config = { + "layoutId": 100, + "layout": [ + { + "jnpfKey": "dataBoard", + "title": "关键指标", + "x": 0, "y": 0, "w": 12, "h": 4, + "option": { + "styleType": 1, + "rowNumber": 4, + "defaultValue": [ + {"fullName": "今日销售额", "num": 125000, "unit": "元", + "icon": "icon-ym icon-ym-wf-incomeRecognition"}, + {"fullName": "新增客户", "num": 23, "unit": "个", + "icon": "icon-ym icon-ym-wf-contractApproval"} + ] + } + }, + { + "jnpfKey": "barChart", + "title": "月度销售趋势", + "x": 0, "y": 4, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "di_xxx", # 数据接口ID + "mappingConfig": [ + {"field": "系列", "value": ""}, + {"field": "维度", "value": "month"}, + {"field": "数值", "value": "amount"} + ] + } + ] +} + +client.portal.update({ + "id": portal_id, + "formData": json.dumps(layout_config) +}) +print("门户组件更新成功") + +# 3. 创建门户管理配置 +manage = client.portal.create_manage({ + "portalId": portal_id, + "systemId": system_id, + "homeShow": 1, + "defaultPortal": 1, + "sort": 1, + "enabled": 1 +}) +print(f"门户管理创建成功: {manage.data.id}") + +# 4. 发布门户 +client.portal.release(portal_id, {"systemId": system_id}) +print("门户发布成功") + +# 5. 设置默认门户 +client.portal.set_default(portal_id) +print("默认门户设置成功") +``` + +--- + +## 发布配置参数 + +### release 方法参数 + +```python +client.portal.release(portal_id, { + "systemId": "system_xxx" # 目标系统ID +}) +``` + +### platformRelease 字段 + +发布时会在 base_portal 的 platformRelease 字段存储: + +```json +{"pc": 1, "app": 1} +``` + +| 平台 | 值 | 说明 | +|------|-----|------| +| pc | 0/1 | 是否发布PC端 | +| app | 0/1 | 是否发布APP端 | + +--- + +## 发布校验 + +发布前可使用 `get_system_filter` 检查目标系统是否可用: + +```python +# 获取可发布到的应用列表 +resp = client.portal.get_system_filter({"systemId": "system_xxx"}, portal_id) +print(resp.data) +``` + +--- + +## 回滚操作 + +### 取消发布 + +发布后的门户不会自动取消,如需更新: + +```python +# 1. 修改设计 +client.portal.update({ + "id": portal_id, + "formData": json.dumps(new_config) +}) + +# 2. 重新发布 +client.portal.release(portal_id, {"systemId": "system_xxx"}) +``` + +--- + +## 常见问题 + +### Q: 发布后不显示? + +1. 检查门户管理配置是否存在 +2. 确认 `homeShow` 和 `enabled` 为 1 +3. 检查 `set_default` 是否设置正确 +4. 确认用户有权限访问该门户 + +### Q: 发布失败? + +1. 检查 systemId 是否正确 +2. 使用 `get_system_filter` 验证目标系统 +3. 查看后端日志 `log/jnpf-java-boot/log_error.log` + +### Q: 如何更新已发布的门户? + +不需要取消发布,直接修改 designData 后重新 release 即可: + +```python +# 修改设计 +client.portal.update({...}) + +# 重新发布 +client.portal.release(portal_id, {...}) +``` diff --git a/docs/portal/07-examples.md b/docs/portal/07-examples.md new file mode 100644 index 0000000..8ab5f96 --- /dev/null +++ b/docs/portal/07-examples.md @@ -0,0 +1,322 @@ +# 使用示例 + +## 示例 1: 创建带图表的门户 + +### 目标 +创建一个销售数据看板,包含数据面板和柱状图。 + +```python +import json +from aibridge import JNPFClient + +client = JNPFClient(base_url="http://localhost:30000", app_code="sales") +client.login("admin", password) + +system_id = "your_system_id" + +# 1. 创建门户 +portal = client.portal.create({ + "fullName": "销售数据看板", + "enCode": "sales_dashboard", + "type": 0, + "systemId": system_id, + "state": 1 +}) +portal_id = portal.data.id + +# 2. 配置组件 +config = { + "layoutId": 100, + "layout": [ + { + "jnpfKey": "dataBoard", + "title": "销售概览", + "x": 0, "y": 0, "w": 12, "h": 4, + "option": { + "styleType": 1, + "rowNumber": 4, + "defaultValue": [ + {"fullName": "今日销售额", "unit": "元", "num": 125000, + "icon": "icon-ym icon-ym-wf-incomeRecognition", "iconColor": "rgb(255, 139, 88)"}, + {"fullName": "新增客户", "unit": "个", "num": 23, + "icon": "icon-ym icon-ym-wf-contractApproval", "iconColor": "rgb(123, 26, 225)"}, + {"fullName": "新增商机", "unit": "个", "num": 15, + "icon": "icon-ym icon-ym-wf-outgoingApply", "iconColor": "rgb(74, 184, 255)"}, + {"fullName": "合同金额", "unit": "元", "num": 856000, + "icon": "icon-ym icon-ym-wf-payDistribution", "iconColor": "rgb(252, 91, 135)"} + ] + } + }, + { + "jnpfKey": "barChart", + "title": "月度销售趋势", + "x": 0, "y": 4, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "di_sales_monthly", # 数据接口ID + "mappingConfig": [ + {"field": "系列", "value": ""}, + {"field": "维度", "value": "month"}, + {"field": "数值", "value": "amount"} + ] + }, + { + "jnpfKey": "pieChart", + "title": "产品分类占比", + "x": 6, "y": 4, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "di_sales_category", + "mappingConfig": [ + {"field": "系列", "value": ""}, + {"field": "维度", "value": "category"}, + {"field": "数值", "value": "amount"} + ] + } + ] +} + +client.portal.update({ + "id": portal_id, + "formData": json.dumps(config) +}) + +# 3. 发布 +client.portal.release(portal_id, {"systemId": system_id}) +print(f"销售看板创建成功: {portal_id}") +``` + +--- + +## 示例 2: 创建流程门户 + +### 目标 +创建展示流程待办事项的门户。 + +```python +import json + +# 创建流程门户 +portal = client.portal.create({ + "fullName": "流程工作台", + "enCode": "flow_workbench", + "type": 0, + "systemId": system_id +}) +portal_id = portal.data.id + +config = { + "layoutId": 100, + "layout": [ + { + "jnpfKey": "todo", + "title": "我的流程", + "x": 0, "y": 0, "w": 12, "h": 4, + "option": { + "styleType": 1, + "defaultValue": [ + {"fullName": "流程待签", "id": "flowToSign", "urlAddress": "/workFlow/flowToSign", + "icon": "icon-ym icon-ym-flowToSign", "iconBgColor": "#1997f4"}, + {"fullName": "流程待办", "id": "flowTodo", "urlAddress": "/workFlow/flowTodo", + "icon": "icon-ym icon-ym-flowTodo", "iconBgColor": "#f29700"}, + {"fullName": "流程在办", "id": "flowDoing", "urlAddress": "/workFlow/flowDoing", + "icon": "icon-ym icon-ym-flowDoing", "iconBgColor": "#495dfd"}, + {"fullName": "流程已办", "id": "flowDone", "urlAddress": "/workFlow/flowDone", + "icon": "icon-ym icon-ym-flowDone", "iconBgColor": "#7b1ae1"} + ], + "rowNumber": 4 + } + }, + { + "jnpfKey": "todoList", + "title": "待签事项", + "type": 0, + "x": 0, "y": 4, "w": 6, "h": 7 + }, + { + "jnpfKey": "todoList", + "title": "待办事项", + "type": 1, + "x": 6, "y": 4, "w": 6, "h": 7 + } + ] +} + +client.portal.update({ + "id": portal_id, + "formData": json.dumps(config) +}) +client.portal.release(portal_id, {"systemId": system_id}) +``` + +--- + +## 示例 3: 创建带筛选的图表门户 + +### 目标 +创建支持筛选的图表看板。 + +```python +import json + +portal = client.portal.create({ + "fullName": "人才信息看板", + "enCode": "talent_dashboard", + "type": 0, + "systemId": system_id +}) +portal_id = portal.data.id + +config = { + "layoutId": 100, + "layout": [ + { + "jnpfKey": "filter", + "title": "筛选", + "x": 0, "y": 0, "w": 12, "h": 3, + "option": { + "showActionButtonGroup": True, + "colCount": 12, + "filterList": [ + {"id": "keyWord", "fullName": "关键词", "sourceType": 2, "defaultValue": ""}, + {"id": "department", "fullName": "部门", "sourceType": 1, + "filterInfo": [], "defaultValue": ""} + ] + } + }, + { + "jnpfKey": "tableList", + "title": "人才列表", + "x": 0, "y": 3, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "di_talent_list" + }, + { + "jnpfKey": "barChart", + "title": "年龄分布", + "x": 6, "y": 3, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "di_talent_age" + } + ] +} + +client.portal.update({"id": portal_id, "formData": json.dumps(config)}) +client.portal.release(portal_id, {"systemId": system_id}) +``` + +--- + +## 示例 4: 获取并复制门户 + +```python +# 获取现有门户 +portal = client.portal.get_info("584307823228223493") +print(f"原始门户: {portal.data.fullName}") + +# 复制门户 +copy = client.portal.copy("584307823228223493") +new_id = copy.data.id + +# 修改名称 +client.portal.update({ + "id": new_id, + "fullName": "销售看板(副本)" +}) + +print(f"复制成功: {new_id}") +``` + +--- + +## 示例 5: 获取门户展示数据 + +```python +# 获取门户展示数据(含权限判断) +resp = client.portal.get_auth_portal("584307823228223493", {"platform": "Web"}) +print(f"门户数据: {resp.data}") +``` + +--- + +## 示例 6: 门户导出导入 + +```python +# 导出门户 +export_data = client.portal.export_portal("584307823228223493") +print(export_data.data) + +# 在其他环境导入 (通过其他系统API) +# POST /api/visualdev/Portal/Actions/Import +``` + +--- + +## 示例 7: 获取通知公告 + +```python +# 获取通知公告 +notice = client.portal.get_notice_list({"size": 5}) +print(f"公告列表: {notice.data}") + +# 获取未读邮件 +email = client.portal.get_email_list() +print(f"未读邮件: {email.data}") +``` + +--- + +## 示例 8: 获取地图数据 + +```python +# 获取全国省市区 +atlas = client.portal.get_atlas() +print(f"省市区数据: {atlas.data}") + +# 获取地图JSON +map_data = client.portal.get_map_data({"code": "100000"}) +print(f"地图JSON: {map_data.data}") +``` + +--- + +## 示例 9: 完整的多平台发布 + +```python +import json + +portal = client.portal.create({ + "fullName": "双平台门户", + "enCode": "dual_portal", + "type": 0, + "systemId": system_id +}) +portal_id = portal.data.id + +# PC端配置 +pc_config = { + "layoutId": 100, + "layout": [ + {"jnpfKey": "dataBoard", "title": "PC指标", "w": 12, "h": 4} + ] +} + +# 更新门户 +client.portal.update({ + "id": portal_id, + "formData": json.dumps(pc_config) +}) + +# 创建PC端管理 +client.portal.create_manage({ + "portalId": portal_id, + "systemId": system_id, + "platform": "Web", + "homeShow": 1, + "defaultPortal": 1 +}) + +# 发布PC端 +client.portal.release(portal_id, {"systemId": system_id}) + +# 设置默认 +client.portal.set_default(portal_id) +``` diff --git a/docs/portal/08-mock-data.md b/docs/portal/08-mock-data.md new file mode 100644 index 0000000..05613bd --- /dev/null +++ b/docs/portal/08-mock-data.md @@ -0,0 +1,294 @@ +# 模拟数据验证指南 + +## 概述 + +由于门户依赖 JNPF 平台环境,测试时需要使用 Mock 数据来验证代码逻辑。 + +--- + +## Mock 数据结构 + +### 门户基础数据 + +```python +MOCK_PORTAL = { + "id": "test_portal_001", + "fullName": "测试门户", + "enCode": "test_portal", + "category": "test_category", + "type": 0, + "state": 1, + "enabledLock": 0, + "platformRelease": '{"pc":1,"app":1}', + "systemId": "test_system_001" +} +``` + +### 组件配置数据 + +```python +# 数据面板 +MOCK_DATA_BOARD = { + "jnpfKey": "dataBoard", + "title": "测试数据面板", + "x": 0, "y": 0, "w": 12, "h": 4, + "option": { + "styleType": 1, + "rowNumber": 4, + "defaultValue": [ + {"fullName": "测试指标1", "num": 100, "unit": "个"}, + {"fullName": "测试指标2", "num": 200, "unit": "元"} + ] + } +} + +# 柱状图 +MOCK_BAR_CHART = { + "jnpfKey": "barChart", + "title": "测试柱状图", + "x": 0, "y": 4, "w": 6, "h": 8, + "dataType": "dynamic", + "propsApi": "test_di_001", + "mappingConfig": [ + {"field": "系列", "value": ""}, + {"field": "维度", "value": "x"}, + {"field": "数值", "value": "y"} + ] +} +``` + +### 地图数据 + +```python +MOCK_ATLAS_RESPONSE = { + "code": 200, + "data": [ + {"code": "110000", "name": "北京市"}, + {"code": "120000", "name": "天津市"}, + {"code": "310000", "name": "上海市"}, + {"code": "440000", "name": "广东省"} + ], + "msg": "操作成功" +} + +MOCK_MAP_GEOJSON = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {"name": "北京市"}, + "geometry": {"type": "Polygon", "coordinates": [[[116,40],[117,40],[117,39],[116,39],[116,40]]]} + } + ] +} +``` + +### 通知公告 + +```python +MOCK_NOTICE_RESPONSE = { + "code": 200, + "data": [ + { + "classify": "系统公告", + "fullName": "系统升级通知", + "content": "系统将于本周六进行升级...", + "creatorUser": "admin", + "releaseTime": "2024-01-15 10:00:00" + } + ], + "msg": "操作成功" +} +``` + +--- + +## 使用 unittest.mock 测试 + +### 测试门户 CRUD + +```python +import unittest +from unittest.mock import patch, MagicMock +import json + +class TestPortalAPI(unittest.TestCase): + + def setUp(self): + # Mock HTTP响应 + self.mock_response = MagicMock() + self.mock_response.json.return_value = {"code": 200, "data": {}, "msg": "操作成功"} + + @patch('requests.Session.request') + def test_get_list(self, mock_request): + mock_request.return_value = self.mock_response + mock_response.json.return_value = { + "code": 200, + "data": { + "list": [MOCK_PORTAL], + "pagination": {"currentPage": 1, "pageSize": 20, "total": 1} + }, + "msg": "操作成功" + } + + from aibridge import JNPFClient + client = JNPFClient(base_url="http://localhost:30000", app_code="test") + client.login("admin", "password") + + result = client.portal.get_list() + self.assertTrue(result.success) + + @patch('requests.Session.request') + def test_create_portal(self, mock_request): + mock_request.return_value = self.mock_response + mock_response.json.return_value = { + "code": 200, + "data": {"id": "new_portal_id"}, + "msg": "操作成功" + } + + from aibridge import JNPFClient + client = JNPFClient(base_url="http://localhost:30000", app_code="test") + client.login("admin", "password") + + result = client.portal.create({ + "fullName": "测试门户", + "enCode": "test_portal", + "type": 0 + }) + self.assertTrue(result.success) +``` + +### 测试组件配置 + +```python + def test_component_config_structure(self): + """验证组件配置结构""" + config = { + "layoutId": 100, + "layout": [MOCK_DATA_BOARD, MOCK_BAR_CHART] + } + config_str = json.dumps(config) + parsed = json.loads(config_str) + + self.assertEqual(parsed["layoutId"], 100) + self.assertEqual(len(parsed["layout"]), 2) + self.assertEqual(parsed["layout"][0]["jnpfKey"], "dataBoard") +``` + +--- + +## 本地测试脚本 + +创建 `aibridge/tests/test_portal_mock.py`: + +```python +"""门户模块 Mock 测试""" +import unittest +from unittest.mock import patch, MagicMock +import json + +MOCK_PORTAL_DATA = { + "id": "test_portal_001", + "fullName": "测试门户", + "enCode": "test_portal", + "type": 0, + "state": 1, + "systemId": "test_system" +} + +MOCK_LAYOUT_CONFIG = { + "layoutId": 100, + "layout": [ + { + "jnpfKey": "dataBoard", + "title": "测试指标", + "w": 12, "h": 4, + "option": { + "defaultValue": [ + {"fullName": "测试", "num": 100, "unit": "个"} + ] + } + } + ] +} + + +class TestPortalMock(unittest.TestCase): + + @patch('aibridge.client.JNPFClient.request') + def test_get_portal_info(self, mock_request): + mock_request.return_value = MagicMock( + success=True, + code=200, + data=MOCK_PORTAL_DATA, + msg="操作成功" + ) + + from aibridge import JNPFClient + client = JNPFClient() + result = client.portal.get_info("test_portal_001") + + self.assertTrue(result.success) + self.assertEqual(result.data["fullName"], "测试门户") + + @patch('aibridge.client.JNPFClient.request') + def test_create_portal_with_layout(self, mock_request): + mock_request.return_value = MagicMock( + success=True, + code=200, + data={"id": "new_portal"}, + msg="操作成功" + ) + + from aibridge import JNPFClient + client = JNPFClient() + + data = { + "fullName": "新门户", + "enCode": "new_portal", + "type": 0, + "formData": json.dumps(MOCK_LAYOUT_CONFIG) + } + result = client.portal.create(data) + + self.assertTrue(result.success) + + def test_layout_config_json(self): + """测试布局配置序列化""" + config_str = json.dumps(MOCK_LAYOUT_CONFIG) + self.assertIsInstance(config_str, str) + + parsed = json.loads(config_str) + self.assertEqual(parsed["layout"][0]["jnpfKey"], "dataBoard") + + +if __name__ == '__main__': + unittest.main() +``` + +--- + +## 验证检查清单 + +| 检查项 | 说明 | +|--------|------| +| 组件 jnpfKey 有效 | 必须在 21 种组件类型中 | +| w/h 在范围内 | w: 1-12, h: 1-20 | +| option 结构正确 | 对应组件的必填字段 | +| dataType 匹配 | static 需 defaultValue, dynamic 需 propsApi | +| visibility 有效 | 必须包含 "pc" 和/或 "app" | +| JSON 序列化正常 | formData 必须是有效 JSON | + +--- + +## 运行测试 + +```bash +# 运行所有测试 +cd $ccWorkDir +python -m pytest aibridge/tests/test_portal_mock.py -v + +# 运行特定测试 +python -m pytest aibridge/tests/test_portal_mock.py::TestPortalMock::test_create_portal_with_layout -v +``` diff --git a/docs/portal/README.md b/docs/portal/README.md new file mode 100644 index 0000000..078290c --- /dev/null +++ b/docs/portal/README.md @@ -0,0 +1,92 @@ +# JNPF 门户 (Portal) 开发指南 + +可视化门户是 JNPF 低代码平台的核心功能模块,支持通过拖拽配置快速构建数据看板。本文档提供完整的开发参考。 + +## 文档索引 + +| 文档 | 说明 | +|------|------| +| **README.md** | 本文档,速查入口 | +| [01-overview.md](01-overview.md) | 门户概述、核心概念 | +| [02-component-types.md](02-component-types.md) | 21种组件类型详解 | +| [03-api-reference.md](03-api-reference.md) | 27个API完整参考 | +| [04-portal-management.md](04-portal-management.md) | 门户管理机制 | +| [05-data-modes.md](05-data-modes.md) | model/custom/release 三种模式 | +| [06-release-workflow.md](06-release-workflow.md) | 发布流程 | +| [07-examples.md](07-examples.md) | 使用示例 | +| [08-mock-data.md](08-mock-data.md) | 模拟数据验证 | + +--- + +## 快速开始 + +```python +from aibridge import JNPFClient + +client = JNPFClient(base_url="http://localhost:30000", app_code="myapp") +client.login("admin", password) + +# 获取门户列表 +portals = client.portal.get_list() +print(portals.data) + +# 创建门户 +new_portal = client.portal.create({ + "fullName": "销售看板", + "enCode": "sales_dashboard", + "type": "model", + "systemId": "your_system_id" +}) + +# 发布门户 +client.portal.release(new_portal.id, {"systemId": "your_system_id"}) +``` + +--- + +## 组件速查 (21种) + +| 类别 | 数量 | 组件 | +|------|------|------| +| 布局控件 | 2 | `card`(卡片面板), `tab`(标签面板) | +| 基础控件 | 5 | `text`(文本), `image`(图片), `carousel`(轮播图), `video`(视频), `iframe` | +| 系统控件 | 4 | `todo`(我的待办), `todoList`(待签/待办/在办), `notice`(公告通知) | +| 图表控件 | 10 | `dataBoard`, `tableList`, `barChart`, `pieChart`, `lineChart`, `radarChart`, `timeAxis`, `rankList`, `mapChart`, `customEcharts` | +| 筛选控件 | 1 | `filter`(筛选器) | + +--- + +## 核心概念 + +### 三种数据模式 + +| 模式 | 说明 | 使用场景 | +|------|------|----------| +| **model** | 模板模式 | 门户设计态,未发布的草稿 | +| **custom** | 自定义模式 | 用户个性化定制(拖拽调整) | +| **release** | 发布模式 | 正式发布的门户,供最终用户使用 | + +### 发布流程 + +``` +创建门户(type=model) → 设计组件 → 创建管理配置 → 发布(release) → 设置默认 +``` + +--- + +## 示例门户 ID + +| 名称 | ID | 组件特点 | +|------|-----|----------| +| 常规门户 | 584307160905678853 | 柱状图、雷达图、排行榜、时间轴、地图、轮播图、我的待办 | +| 门户设计 | 584307823228223493 | 数据面板、表格列表、待办事项、公告通知、图片、排行榜、文本、Iframe、自定义echart | +| 流程门户 | 585481192002814853 | 我的待办、待签事项、在办事项、待办事项 | +| 筛选图表 | 797386216092729925 | 筛选器、表格列表、柱状图(动态数据接口) | + +--- + +## 常见问题 + +- **门户不显示**: 检查是否已发布(`release`),并确认门户管理配置正确 +- **图表无数据**: 确认 `dataType` 为 `dynamic` 且 `propsApi` 指向有效的数据接口ID +- **发布失败**: 使用 `get_system_filter()` 检查目标系统是否可用 diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..8f2e3cd --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,410 @@ +# 快速入门 + +> 5 分钟完成第一个功能模块的创建、发布、菜单配置和数据管理。 + +## 命名规范 + +| 类型 | 规则 | 示例 | +|------|------|------| +| 数据库表名 | `{business_name}`(snake_case,无前缀) | `product` | +| Java 类名 | `{BusinessName}Entity`(PascalCase) | `ProductEntity` | + +> **注意**: +> - 业务库已按系统名隔离,表名用 snake_case,**不加前缀**,不用字符分割 +> - 平台表(base_*)保持原样,如 `base_sales_vendor` +> - Java 类名只使用业务名(PascalCase),**不加 app_code 前缀**,避免 `AisProductEntity` 这样的重复前缀 + +## 配置构建器 + +AIBridge 提供 **6 个配置构建器**,覆盖 PC 端和移动端表单配置: + +| 构建器 | 用途 | +|-------|------| +| `build_field_model` | PC 单字段模型(25+ jnpfKey 类型) | +| `build_table_field_model` | PC 子表控件模型 | +| `build_form_data` | PC 表单布局配置 | +| `build_column_data` | PC 列表列配置 | +| `build_full_config` | 组装 formData + columnData + tables | +| `build_mobile_column_data` | 移动端列配置(f_app_column_data) | + +**移动端字段配置示例:** + +```python +from aibridge.builders.mobile_field_model import build_mobile_column_data + +fields = [ + {"fieldName": "客户名称", "field": "f_customer_name", "jnpfKey": "input", "required": True}, + {"fieldName": "状态", "field": "f_status", "jnpfKey": "select", "options": [{"fullName": "启用", "id": "1"}]}, +] +mobile_column = build_mobile_column_data(fields) +# 输出供 f_app_column_data 使用 +``` + +## 前置条件 + +- JNPF 平台已部署并运行(默认地址 `http://localhost:30000`) +- 已有管理员账号和密码 +- 已创建业务系统(获取 `app_code` 和 `system_id`) +- Python 3.8+ + +## 步骤 1:安装与配置 + +AIBridge 是项目的一部分,无需单独安装。只需确保 Python 3 环境可用。 + +```bash +# 验证 Python 版本 +python3 --version # 需要 Python 3.8+ +``` + +**运行方式:** + +```python +# 方式一:直接运行脚本(推荐) +cd /path/to/project +python3 aibridge/examples/quickstart.py + +# 方式二:在代码中使用 +import sys +sys.path.insert(0, "/path/to/project") # 确保项目根目录在 sys.path + +from aibridge import JNPFClient, JNPFConfig + +# 通过配置创建(推荐,自动读取 app_code、密码等) +config = JNPFConfig() +client = JNPFClient.from_config(config) + +# 或直接创建 +client = JNPFClient( + base_url="http://localhost:30000", + app_code="wj", + timeout=30, + verify_ssl=False, +) +``` + +**预期输出:** 无报错,客户端初始化完成。 + +## 步骤 2:登录 + +> **铁律 2**:前端页面用真实密码,后端 API 必须使用 96 字符 AES 密文 + +```python +# 通过配置创建(推荐,自动从 config.py 读取 app_code) +config = JNPFConfig() +client = JNPFClient.from_config(config) + +# ★ 密码必须是 96 字符 AES 密文(从浏览器提取,Python 无法生成正确密文) +# 获取方式:node .claude/scripts/extract_encrypted_password.js +resp = client.login() # 自动使用 CONFIG 中的账号密码 + +print(f"登录结果: code={resp.code}, msg={resp.msg}") +print(f"Token: {client.token[:20]}...") + +# 获取当前用户信息 +user_resp = client.get_user_info() +print(f"用户: {user_resp.data.get('userName')}") +``` + +**预期输出:** +``` +登录结果: code=200, msg=操作成功 +Token: bearer eyJhbGciOiJIUz... +用户: admin +``` + +## 步骤 3:创建功能表单 + +```python +from aibridge.builders.full_config import build_full_config, build_create_payload +from aibridge.models import FieldDef + +config = JNPFConfig() + +# 使用 FieldDef 定义业务字段(推荐,自动补全默认值) +fields = [ + FieldDef(field="f_name", field_name="名称", required=True), + FieldDef(field="f_code", field_name="编码", required=True), + FieldDef(field="f_type", field_name="类型", jnpf_key="select", options=[ + {"fullName": "电子产品", "id": "1"}, + {"fullName": "办公用品", "id": "2"}, + ]), + FieldDef(field="f_price", field_name="单价", jnpf_key="inputNumber", + data_type="decimal", data_length="18,2"), + FieldDef(field="f_description", field_name="描述"), +] + +# 构建完整配置 +full_cfg = build_full_config( + full_name="产品管理", + en_code="productManage", + table_name="product", # ★ 纯业务名 snake_case,不加前缀 + table_label="产品表", + description="产品信息管理", + category=config.business_category_id, # 功能表单分类ID(从config.py读取) + fields=[f.to_dict() for f in fields], + web_type=2, # 2=表单加列表 +) + +# 创建功能(dynamic_table=True 时跳过物理表校验,Release时自动建表) +payload = build_create_payload(full_cfg, dynamic_table=True) +resp = client.visual_dev.create(payload) + +if not resp.success: + print(f"创建失败: {resp.msg}") + exit(1) + +func_id = resp.id +# API 有时返回 id=null,需二次查询 +if not func_id: + func_id = client.visual_dev.get_id_by_en_code("productManage") +print(f"功能创建成功,ID: {func_id}") +``` + +**预期输出:** +``` +功能创建成功,ID: 4234567890123456789 +``` + +## 步骤 4:发布功能 + +```python +# 发布功能(systemId 在创建时已由 App-Code 自动设置,发布时继承) +release_resp = client.visual_dev.release(func_id) +print(f"发布结果: code={release_resp.code}, msg={release_resp.msg}") +``` + +**预期输出:** +``` +发布结果: code=200, msg=操作成功 + visual_dev: 200 操作成功 + visual_release: 200 操作成功 + module: 200 操作成功 +``` + +## 步骤 5:创建菜单 + +```python +# 5.1 创建目录菜单(type=1) +dir_resp = client.menu.create_directory_menu( + full_name="产品中心", + en_code="product_dir", + icon="icon-ym icon-ym-folder", + sort_code=100, + parent_id="-1", # 顶级目录 +) +print(f"目录菜单创建成功,ID: {dir_resp.id}") + +# 5.2 创建功能菜单(type=3),挂在目录下 +menu_resp = client.menu.create_form_menu( + full_name="产品列表", + en_code="productList", + visual_dev_id=func_id, + parent_id=dir_resp.id or "-1", + sort_code=1, +) +print(f"功能菜单创建成功,ID: {menu_resp.id}") +``` + +> **说明**:`create_form_menu` 已内置自动处理 fullName 唯一性冲突和 ID 查询,`menu_resp.id` 直接返回实际菜单 ID。 + +## 步骤 6:管理数据 + +```python +# 6.1 新增数据 +create_resp = client.visual_dev.create_model(func_id, { + "f_name": "蓝牙耳机", + "f_code": "BT-001", + "f_type": "电子产品", + "f_price": 299.00, + "f_description": "高品质无线蓝牙耳机", +}) +print(f"新增: code={create_resp.code}, id={create_resp.id}") + +# 6.2 查询列表 +list_resp = client.visual_dev.get_model_list(func_id, { + "currentPage": 1, + "pageSize": 20, +}) +records = list_resp.data.get('list', []) +print(f"查询: 共 {len(records)} 条记录") +for r in records: + print(f" - {r.get('f_name')} ({r.get('f_code')})") + +# 6.3 获取详情 +if records: + record_id = records[0].get("F_Id") or records[0].get("id") + detail_resp = client.visual_dev.get_model_info(func_id, record_id) + print(f"详情: {detail_resp.data.get('f_name')}") + +# 6.4 更新数据 +if records: + update_data = records[0].copy() + update_data["f_price"] = 259.00 + update_resp = client.visual_dev.update_model(func_id, update_data) + print(f"更新: code={update_resp.code}") + +# 6.5 删除数据 +if records: + record_id = records[0].get("F_Id") or records[0].get("id") + delete_resp = client.visual_dev.delete_model(func_id, record_id) + print(f"删除: code={delete_resp.code}") +``` + +## 步骤 7:软删除(推荐代替 delete) + +JNPF 的 `delete()` 可能未彻底清除数据,导致重新创建时 enCode 冲突。推荐使用 `soft_delete()`: + +```python +# 软删除菜单:parentId=-100、停用、改名改编码 +client.menu.soft_delete(menu_id) +# 效果:enCode → menu_{id},原编码自动释放 + +# 软删除功能表单:改名改编码、sortCode沉底 +client.visual_dev.soft_delete(func_id) +# 效果:enCode → func_{id},原编码自动释放 + +# 软删除后可以安全地用原编码重新创建 +``` + +## 步骤 8:创建移动端菜单(可选) + +移动端菜单与 Web 端菜单分开管理,使用 `category=App` 区分。 + +```python +# 方式一:自动创建父目录 +result = client.menu.create_app_form_menu_with_parent( + full_name="数据源管理", # 菜单名称 + en_code="menu1775466782807_source", # Web端菜单编码 + form_id="810886416123826501", # 表单ID + parent_name="数据管理", # 父目录名称(不存在则自动创建) + parent_en_code="data_manager", # 父目录编码 +) +print(f"父目录ID: {result['parent_id']}, 菜单ID: {result['menu_id']}") + +# 方式二:手动创建父目录后创建菜单 +parent_resp = client.menu.create_app_directory_menu( + full_name="数据管理", + en_code="data_manager", +) +parent_id = parent_resp.id + +client.menu.create_app_form_menu( + full_name="数据源管理", + en_code="menu1775466782807_source", # 自动追加 _app 后缀 + form_id="810886416123826501", + parent_id=parent_id, +) +``` + +> **说明**:移动端菜单的 `urlAddress` 格式为 `/pages/apply/dynamicModel/index?id={form_id}`, +> `propertyJson` 中的 `moduleId` 指向对应的表单 ID。 + +## 步骤 9:代码生成(含命名修复) + +> 使用 `CodeGenerator` 将已发布的功能表单导出为前后端代码,并自动修复 JNPF 类名前缀 bug。 + +```python +from aibridge.utils.code_generator import CodeGenerator + +gen = CodeGenerator(client, config) + +# 1. 生成代码(module_name 使用纯业务名 PascalCase) +result = gen.generate( + func_id=func_id, + module_name="Product", # 生成 ProductEntity,不加 Ais_ 前缀 + enable_flow=0, + tables='0', + form_type='2', + description="产品管理", +) +print(f"前端: {result['frontend_path']}") +print(f"后端: {result['backend_path']}") + +# 2. 自动修复类名前缀(old_prefix 从 formData 自动计算) +fix_result = gen.fix_class_names( + result['backend_path'], None, "Product", result['frontend_path'] +) +for old, new in fix_result['backend']: + print(f" {old} → {new}") +``` + +> **JNPF 命名 Bug**:JNPF CodeGenerator 生成 `Ais_aisprojectEntity` 而不是 `ProjectEntity`。 +> `fix_class_names()` 自动将 `Ais_aisproject*` 修复为 `Project*`,同时修复 Controller API 路径和前端 api.ts。 + +**便捷脚本**:`aibridge/utils/run-codegen.py` 一键完成代码生成 + 类名修复 + 菜单挂载: + +```bash +python3 aibridge/utils/run-codegen.py [menu_title] +``` + +## 完整流程总结 + +``` +创建客户端 → 登录 → 定义字段 → 构建配置 → 创建功能 → 发布 → 创建菜单 → 数据CRUD → 代码生成 +``` + +## 完整标准示例 + +**`aibridge/examples/quickstart.py`** 是端到端可运行的权威示例,覆盖所有主要操作: + +``` +登录 → 创建功能表单 → 发布 → 创建菜单 → 数据 CRUD → 代码生成 → 软删除 → 清理 +``` + +> **铁律 1**:DI(数据接口)作为临时查询手段,当需要复杂业务逻辑时,立即触发 `backend-dev` 技能,导出模型代码 + 编写业务 Helper。 + +运行方式: +```bash +cd /path/to/project +python3 aibridge/examples/quickstart.py +``` + +该示例包含完整的错误处理(id=None fallback、清理残留数据等),遇到问题时以此文件为准。 + +## 移动端 H5 开发与测试 + +### 1. 项目导入(必须用 HBuilderX) + +移动端项目必须通过 **HBuilderX** 导入,否则项目名无法识别: + +1. 下载 HBuilderX:https://www.dcloud.io/hbuilderx.html +2. 菜单:文件 → 导入 → 从本地项目导入 → 选择 `uniapp/`(基于 jnpf/移动端/jnpf-app-vue3 复制) + +### 2. 运行移动端 H5 + +```bash +# 在 HBuilderX 中 +# 菜单:运行 → 运行到浏览器 → Chrome(或按快捷键) + +# 或者使用命令行(项目需先用 HBuilderX 导入) +/Applications/HBuilderX.app/Contents/MacOS/cli launch web --project $ccWorkDir/uniapp +``` + +### 3. 移动端测试配置 + +测试配置文件:`test/playwright.mobile.config.ts` + +```bash +cd $ccWorkDir/test +npx playwright test mobile --reporter=line +``` + +### 4. 移动端 API 地址 + +| 环境 | 地址 | +|------|------| +| 后端 API | http://localhost:30000 | +| 移动端 H5 | http://127.0.0.1:3800 | +| PC 端 | http://localhost:3000 | + +### 5. 常见问题 + +- **"功能表单未发布移动端"**:需要为表单创建 App 端菜单,参见步骤8 +- **App 端菜单查询**:`client.menu.get_list({'category': 'App', ...})` + +## 下一步 + +- 阅读 [平台机制](platform-guide.md) 了解 App-Code、system_id 等核心概念 +- 阅读 [API 参考](api-reference.md) 查看全部可用接口 +- 阅读 [扩展开发指南](codedev/) 了解 codedev 模式开发 +- **后端开发需求**:立即触发 `backend-dev` 技能,在 `ssw-{app_code}/util/` 下编写业务 Helper diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..6705c3a --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,719 @@ +# 故障排查 + +> AIBridge 和 JNPF 平台的常见问题及解决方案。 + +## 1. 菜单不显示 + +### 症状 + +创建功能并发布后,在业务系统中看不到菜单。 + +### 原因 + +请求未携带正确的 `App-Code` 请求头。后端默认使用系统平台(`systemId = 309228585019769285`),导致创建的功能和菜单归属到系统平台。 + +### 排查步骤 + +```python +# 1. 检查客户端是否设置了 app_code(关键!) +print(f"App-Code: {client.app_code}") # 应为你的业务系统编码,如 "ais" + +# 2. 检查是否正确加载了配置 +# 错误方式:JNPFClient() 不会自动使用 config.py 中的 app_code +client = JNPFClient() # app_code 为空! +print(f"app_code: {client.app_code}") # 输出为空 + +# 正确方式:使用 from_config +config = JNPFConfig() # app_code="ais" from config.py +client = JNPFClient.from_config(config) +print(f"app_code: {client.app_code}") # 输出 "ais" + +# 3. 检查菜单列表 +from aibridge.modules.menu import MenuAPI +menu_api = MenuAPI(client) +menu_list = menu_api.get_list() +print(f"菜单数量: {len(menu_list.data or [])}") + +# 4. 检查菜单的 systemId +menu_info = menu_api.get_info("your_menu_id") +print(f"systemId: {menu_info.data.get('systemId')}") +``` + +### 解决方案 + +**必须使用 `JNPFClient.from_config(config)` 而非 `JNPFClient()`**: + +```python +from aibridge import JNPFClient, JNPFConfig + +# 正确:从 config.py 加载完整配置(包含 app_code) +config = JNPFConfig() # config.py 中已设置 app_code="ais" +client = JNPFClient.from_config(config) + +# 错误:直接创建 JNPFClient,app_code 为空 +client = JNPFClient() # app_code = "",会登录到平台系统! +``` + +**验证菜单归属:** + +```python +# 登录后查询业务系统菜单 +sys_menu = client.menu.get_system_menu() +print(f"业务系统菜单数量: {len(sys_menu.data)}") +for m in sys_menu.data: + print(f" {m.get('fullName')} systemId:{m.get('systemId')}") +``` + +> **注意:** +> - `JNPFClient()` 创建的实例 `app_code=""`,所有 API 请求都不会带 `App-Code` 请求头 +> - 后端 `VisualdevController.create()` 和 `ModuleController.create()` 会自动通过 `App-Code` 请求头解析 systemId 并写入数据库 +> - 菜单创建后需确认 `systemId` 是否为业务系统的 ID(如 ais 系统为 `808341719178283333`) +> - 如发现 systemId 错误,可通过 `menu.update({"id": menu_id, "systemId": business_system_id})` 修正 + +**验证:** 退出登录后重新登录,或清除浏览器缓存/localStorage,确认 `getUserInfo` API 返回的 `menuList` 包含目标菜单。 + +--- + +## 2. 功能创建成功但无法使用 + +### 症状 + +功能在后台可以看到,但前端点击菜单报错或无响应。 + +### 原因 + +功能未发布(`state=0`)。JNPF 的功能需要发布后才能在前端使用。 + +### 排查 + +```python +info = visual_dev.get_info(func_id) +print(f"发布状态: {info.data.get('state')}") # 0=未发布, 1=已发布 +``` + +### 解决方案 + +```python +visual_dev.release(func_id) +``` + +--- + +## 3. 数据接口执行失败 + +### 症状 + +调用 `DataInterfaceAPI.execute()` 时报错。 + +### 常见原因及解决方案 + +**3.1 数据接口不存在或 ID 错误** + +确认 `di_id` 正确: + +```python +from aibridge.modules.data_interface import DataInterfaceAPI +di_api = DataInterfaceAPI(client) +resp = di_api.get_list() +for item in resp.data.get("list", []): + print(f"接口: {item['fullName']} (id={item['id']})") +``` + +**3.2 数据接口没有 SQL 执行权限** + +确认数据接口配置了 SQL 类型的数据源,且使用的数据库连接(`dbLinkId: "0"`)有执行权限。 + +**3.3 SQL 语法错误** + +检查 SQL 语法,特别注意: +- 字符串值用单引号包裹 +- ID 值不能有换行或特殊字符 +- UPDATE 语句需要 WHERE 条件(避免全表更新) +- SQL 中不能包含 `{}` 空字面量(会被当作参数占位符解析) + +**3.4 isPostPosition 未设置导致 NPE** + +``` +后端日志: NullPointerException at handlePostVariate +``` + +`isPostPosition` 默认为 null,后端自动拆箱时 NPE。**解决:** 创建 payload 中设置 `"isPostPosition": 0`。 + +**3.5 DI 参数名必须与 SQL 占位符一致** + +```python +# SQL 中用 {code},paramList 中 field 也必须是 "code" +sql = "SELECT * FROM table WHERE f_code = {code}" +di.execute(di_id, {"code": "ABC"}) # 正确 +di.execute(di_id, {"f_code": "ABC"}) # 错误 +``` + +--- + +## 4. Token 过期 + +### 症状 + +``` +AuthError: [401] 登录已过期 +``` + +### 解决方案 + +```python +# 重新登录(密码必须是 96 字符 AES 密文) +# 获取方式:node .claude/scripts/extract_encrypted_password.js +client.login(account="admin", password="d4958348...") # 96字符AES密文 + +# 或使用已有 token +client.login_by_token("bearer eyJ...") +``` + +> **注意:** JNPF 登录返回的 token 已包含 `"bearer "` 前缀,不要重复添加。 + +--- + +## 5. formData/columnData JSON 格式错误 + +### 症状 + +创建功能成功但发布后前端报错,或表单显示异常。 + +### 常见格式问题 + +- `ruleList` 必须是对象:`{"matchLogic": "and", "conditionList": []}`,不能为 null +- `tabConfig` 不能为 null:应为 `{"on": False, "relationField": "", "hasAllTab": True}` +- `propertyJson` 必须是 JSON 字符串(`json.dumps({...})`),不是 Python dict +- `tables`、`formData`、`columnData` 必须是 JSON 字符串 + +### 推荐:使用构建器 + +```python +from aibridge.builders.full_config import build_full_config, build_create_payload + +config = build_full_config( + full_name="测试功能", en_code="testFunc", + table_name="base_test", table_label="测试表", + fields=[...], +) +payload = build_create_payload(config) # formData、columnData、tables 格式已保证正确 +``` + +--- + +## 6. 删除操作报外键约束错误 + +### 症状 + +删除功能、菜单、流程模板时报错,提示外键约束或"系统异常"。 + +### 依赖关系 + +``` +流程模板 → 引用 → 表单(visual_dev)→ 引用 → 发布记录(visual_release)→ 引用 → 菜单(module) +``` + +### 解决方案:正确的删除顺序 + +```python +# 1. 先删除流程模板(解除对表单的引用) +for item in client.workflow.get_template_list({"keyword": "xxx"}).data.get("list", []): + client.workflow.delete_template(item["id"]) + +# 2. 再删除功能菜单(type=3) +for item in client.menu.get_list({"keyword": "xxx"}).data.get("list", []): + if item.get("type") == 3: + client.menu.delete(item["id"]) + +# 3. 删除表单 +for item in client.visual_dev.get_list({"keyword": "xxx"}).data.get("list", []): + client.visual_dev.delete(item["id"]) + +# 4. 最后删除目录菜单(type=1) +for item in client.menu.get_list({"keyword": "目录名"}).data.get("list", []): + if item.get("type") == 1: + client.menu.delete(item["id"]) +``` + +### 菜单删除 NPE 的替代方案 + +`ModuleController.delete()` 在子菜单 `parentId` 为 null 时会 NPE(JNPF 后端 bug)。 +替代方案:使用 `menu_api.soft_delete()` 软删除。 + +### 推荐方案:soft_delete 代替 delete + +删除后重新创建同名/同编码资源会报"编码/名称不能重复",因为 JNPF 的 delete 可能未彻底清除数据。 + +```python +# ★ 推荐用 soft_delete:修改属性使其不可见且不冲突 +client.menu.soft_delete(menu_id) +# 效果:parentId=-100, enabledMark=0, 名称加ID后缀, enCode=menu_{id} + +client.visual_dev.soft_delete(func_id) +# 效果:名称加ID后缀, enCode=func_{id}, sortCode=999999 + +# 软删除后可以安全地用原编码重新创建 +client.menu.create_form_menu(full_name="客户列表", en_code="customerList", ...) +``` + +--- + +## 7. 创建功能报"请在数据库中添加对应的数据表" + +### 症状 + +调用 `visual_dev.create()` 时报错。 + +### 原因 + +JNPF 的 create 接口在创建时会校验 `tables` 中引用的物理表是否已存在。 + +### 解决方案 + +**方案 A:动态建表(推荐)** — 使用 `build_create_payload(config)`(默认 `dynamic_table=True`),create 时传空 tables 跳过校验,Release 时自动建表。 + +**方案 B:预建表模式** — 如果物理表已存在,使用 `build_create_payload(config, dynamic_table=False)`。 + +--- + +## 8. 流程发起报错 "map is null" 或 formData 无效 + +### 症状 + +`POST /api/workflow/task` 发起流程报"系统异常"。 + +### 原因 + +流程发起的 `formData` 字段类型为 `Map`。如果传入 JSON 字符串(`json.dumps(dict)`),会被反序列化为 String 而非 Map,导致 NPE。 + +### 解决方案 + +```python +# 正确:formData 直接传 dict +client.workflow.launch_task(version_id, { + "f_order_no": "CG-001", + "f_item_name": "中性笔", +}) +# 错误:不要 json.dumps 序列化 formData +``` + +### 发起流程后表单数据为空 + +如果 `launch_task` 返回成功,但流程详情中表单数据为空,检查: + +1. **字段名匹配**:确保 `formData` 中的字段名与流程模板中定义的字段完全一致 +2. **字段名前缀**:必须使用小写 `f_` 前缀(如 `f_order_no`) +3. **字段类型**:数字、日期等类型需与表单设计一致 + +```python +# 正确 +form_data = { + "f_order_no": "CG-001", # 小写 f_ 前缀 + snake_case + "f_amount": 1000, # 数字直接传 + "f_create_time": "2024-01-01" # 日期字符串 +} + +# 错误:少了 f_ 前缀 +form_data = { + "order_no": "CG-001", # 缺少 f_ 前缀 +} +``` + +--- + +## 9. 前端发起流程报 "该文件不存在: undefined.vue" + +### 症状 + +``` +该表单已删除 该文件不存在: ../views/workFlow/workFlowForm/undefined.vue +``` + +### 错误链 + +``` +前端 FlowParser.vue → getFlowTaskInfo +→ 后端 workflow_node 获取起始节点 formId +→ visualdevApi.getFormConfig(formId) 查 base_visualdev_release +→ 返回 null 或 enCode 为空 → formInfo.enCode = undefined +``` + +### 根因排查顺序 + +1. **前端 URL** 是否包含正确的 app 前缀(如 `/wj/`),否则 systemId 解析为默认平台值 +2. **workflow_node 表**中起始节点的 `f_form_id` 是否与 `base_visual_dev` 表 ID 一致 +3. **base_visualdev 和 workflow_template** 的 `f_system_id` 是否一致(多租户隔离) +4. **表单是否已发布**(`base_visualdev_release` 表是否有对应记录) +5. **流程模板是否已启用**(`enabledMark = 1`) + +### 诊断工具 + +```bash +python3 -m aibridge.examples.diagnose_workflow_form +``` + +--- + +## 10. 创建流程模板后 save_flow 报 "数据不存在" + +### 症状 + +`POST /api/workflow/template/Save` 返回 "数据不存在"。 + +### 原因 + +创建模板时未传 `flowXml/flowNodes/flowConfig`,导致后端 NPE,`templateJson` 未创建。 + +### 解决方案 + +```python +# 推荐使用便捷方法 +result = client.workflow.create_simple_flow( + full_name="审批流程", en_code="approvalFlow", + form_id=form_id, approver_user_ids=["user_id"], form_name="表单名称", +) +``` + +--- + +## 11. get_flow_info 返回 "数据不存在" + +### 症状 + +`GET /api/workflow/template/Info/{id}` 返回 "数据不存在"。 + +### 原因 + +`Info/{id}` 端点查的是 **version_id(flowId)**,不是 template_id。 + +### 解决方案 + +```python +versions = client.workflow.get_version_list(template_id) +flow_id = versions.data[0]["id"] +info = client.workflow.get_flow_info(flow_id) # 用 version_id +``` + +--- + +## 12. relationForm 弹出窗口报错或显示空白 + +### 症状 A:弹出窗口报 "Cannot read properties of undefined (reading 'includes')" + +`columnOptions` items 缺少 `value` 字段(应等于数据库字段名)。 + +### 症状 B:表单设计器列表字段显示空白 + +`columnData.columnOptions` items 缺少顶层 `prop` 字段(应等于 `__vModel__`)。 + +### 排查 + +```python +resp = client.visual_dev.get_info(form_id) +form_data = json.loads(resp.data["formData"]) +col_data = json.loads(resp.data["columnData"]) + +for field in form_data["fields"]: + if field.get("__vModel__") == "f_xxx": + for col in field.get("columnOptions", []): + print(f"value={col.get('value')}, prop={col.get('prop')}") +``` + +### 解决方案 + +**修复已有表单** — 从目标表单获取 columnOptions,确保每个 item 有 `value` 和 `prop` 字段后写回。 + +**两阶段创建(推荐)** — 先创建被引用表单(得到 form_id),再创建带 relationForm 的表单(设置 modelId)。参考 `aibridge/examples/create_image_management.py`。 + +--- + +## 13. select 字段下拉选项不显示 + +### 症状 + +下拉框点击后有选项,但选项文字为空。 + +### 正确的字段配置 + +```json +{ + "options": [ + {"fullName": "正常", "id": "normal"}, + {"fullName": "损坏", "id": "corrupted"} + ], + "props": { + "label": "fullName", + "value": "id", + "children": "" + }, + "__config__": { + "jnpfKey": "select", + "options": null + } +} +``` + +**关键点:** +- `options` 格式是 `{fullName, id}`,**不是** `{label, value}` +- `props.label` 必须指向 `"fullName"`,`props.value` 指向 `"id"` +- select 字段必须配置 `props`,否则后端报 `PropsModel.getLabel() is null` + +### 选项来源方式 + +**方式一:静态 options** — 在 `FieldDef` 中配置 `options` 列表。 + +**方式二:关联数据字典** — 设置 `__config__.dataType = "dictionary"` 和 `__config__.dictionaryType = dict_type_id`。 + +--- + +## 14. 创建表单/菜单报"编码/名称不能重复" + +### 症状 + +删除表单或菜单后,用相同 enCode/fullName 重新创建时报重复错误。 + +### 原因 + +JNPF 的 enCode/fullName/urlAddress 在全系统范围唯一校验,包括已软删除的记录。 + +### 解决方案 A:soft_delete(推荐) + +```python +# ★ 用 soft_delete 代替 delete,自动释放编码 +client.menu.soft_delete(menu_id) # enCode → menu_{id} +client.visual_dev.soft_delete(func_id) # enCode → func_{id} + +# 软删除后,`create_form_menu` / `create_page_menu` 会自动用临时名称创建再 rename +# 无需额外处理 +client.menu.create_form_menu(full_name="客户列表", en_code="customerList", ...) +``` + +### 解决方案 B:创建前检查 + 唯一编码 + +```python +# 创建前检查 +if client.visual_dev.check_en_code_exists("equipmentCategory"): + existing_id = client.visual_dev.get_id_by_en_code("equipmentCategory") + +# 使用时间戳生成唯一编码 +import time +unique_code = f"eqCategory{int(time.time() * 1000) % 1000000}" +``` + +--- + +## 15. 创建菜单成功但 id 为 None + +### 原因 + +JNPF Menu API 返回 `{"code":200,"msg":"新建成功"}` 但不包含 `data.id`,需通过 `get_id_by_en_code` 查询。 + +### 解决方案 + +`create_form_menu` / `create_page_menu` 已内置自动查询,`resp.id` 直接返回实际 ID: + +```python +resp = client.menu.create_form_menu(full_name="客户列表", en_code="customerList", ...) +print(f"菜单ID: {resp.id}") # ✅ 直接返回实际 ID,无需二次查询 +``` + +所有 `create_*` 方法已内置 id=null 自动修复。 + +--- + +## 16. DI Preview 执行 SQL 查不到数据(多租户隔离) + +### 症状 + +通过 DI Preview 执行 SELECT 返回空,但 List API 能看到数据。 + +### 原因 + +- **List/CRUD API**:通过 MyBatis-Plus 操作,自动添加租户过滤,连接租户库 +- **DI Preview**:通过 `dbLinkId` 指定的数据库连接直接执行 SQL,`dbLinkId=0` 连接的是**主库** + +### 可通过 DI Preview 访问的表(主库) + +`base_visual_dev`、`base_visual_release` 及动态建表的业务表。 + +租户库中的表(如 `base_data_interface`)需通过标准 API(如 `visual_dev.create_data()`)操作。 + +### 排查流程 + +| 步骤 | 操作 | 预期结果 | +|------|------|----------| +| 1 | 确认 DI 的 `dbLinkId` 参数 | 非 0 表示业务库 | +| 2 | 确认表所在数据库 | 主库 vs 租户库 | +| 3 | 确认 SQL 语法正确 | 可以直接执行 | +| 4 | 通过 List API 验证 | API 能查到说明数据存在 | + +> **提示**:如果 DI Preview 查不到但 List API 能查到,说明表在租户库,需要用 `dbLinkId` 指定对应数据源。 + +--- + +## 17. 连接失败 / 其他环境问题 + +### 连接失败 + +```python +client = JNPFClient( + base_url="http://localhost:30000", + verify_ssl=False, # 跳过 SSL 验证 + timeout=30, # 增加超时时间 +) +``` + +### f_delete_mark 为 NULL + +通过 SQL 直接 INSERT 时,确保 `f_delete_mark = 0`(正常)或 `1`(已删除),不能为 NULL。 + +### 自己发起的流程自己无法审批 + +JNPF 规则:发起人不能同时是同节点的审批人。测试时使用两个不同用户。 + +**测试步骤**: +1. 用户 A(发起人)登录 → 发起流程 +2. 用户 B(审批人)登录 → 待审核列表能看到 → 审批通过 +3. 用户 A 无法在自己的待审核列表中看到自己发起的任务 + +**如果需要自己审批**:可以在流程设计中将审批人设为"发起人自审",或设置会签/或签模式。 + +### 批量操作性能 + +逐个处理时增加 `time.sleep(0.3)` 间隔避免服务端限流。 + +--- + +## 18. relationForm 字段选择后无反应或列表为空 + +### 症状 + +- 弹出窗口报错或显示空白 +- 列表只显示序号,不显示名称 +- 选择后确定按钮无反应 + +### 根因 + +`relationForm` 需要 4 个关键配置: + +| 配置 | 说明 | 正确值 | 错误值 | +|------|------|--------|--------| +| `modelId` | 目标表单 ID | 被关联表单的 visual_dev ID | 空或错误 ID | +| `relationField` | 显示文本字段 | `f_name`(小写,表单字段定义中的字段名) | `f_id` | +| `propsValue` | 存储值字段 | `f_id`(小写,JNPF DataChange API 返回的主键是小写) | `F_Id`(大写) | +| `columnOptions` | 弹窗列表列配置 | `[{value: "f_name", label: "名称"}]`,从目标表单 `columnData` 提取 | 空 | + +> **关键**:`propsValue` 必须用小写 `f_id`,因为 JNPF 内部 DataChange API 返回的 JSON 主键是 `f_id`(小写),即使数据库列是 `F_Id`(大写)。 + +### 解决方案:两阶段创建 + 后处理 + +**第一阶段**:创建被引用的表单(目标表单),获取其 ID。 + +**第二阶段**:创建带 relationForm 的表单时,通过 `FieldDef.relation_config` 声明配置: + +```python +fields = [ + # ... 其他字段 ... + FieldDef(field="f_project_id", field_name="所属项目", + jnpf_key="relationForm", + relation_config={ + "modelId": "目标表单ID", # 被关联的表单ID + "relationField": "f_name", # 显示文本字段(小写) + "propsValue": "f_id", # 存储值(小写,不是 F_Id) + "popupTitle": "选择项目", + }), +] +``` + +**第三阶段**(发布后必须):从目标表单提取 `columnOptions` 并更新字段,然后重新发布: + +```python +import json + +def fix_relation_form(client, form_id, target_form_id): + """relationForm 后处理:从目标表单提取 columnOptions""" + # 1. 获取目标表单的列配置 + resp = client.request('GET', f'/api/visualdev/Base/{target_form_id}') + proj_col = json.loads(resp.data.get('columnData', '{}')) + col_opts = [ + {"value": f.get('__vModel__'), "label": f.get('__config__', {}).get('label')} + for f in proj_col.get('columnOptions', []) + if f.get('__vModel__') and f.get('__config__', {}).get('label') + ] + # 2. 更新当前表单的 relationForm 字段 + form_resp = client.request('GET', f'/api/visualdev/Base/{form_id}') + form_data = json.loads(form_resp.data.get('formData', '{}')) + for f in form_data.get('fields', []): + if f.get('__config__', {}).get('jnpfKey') == 'relationForm': + f['columnOptions'] = col_opts + upd = dict(form_resp.data) + upd['formData'] = json.dumps(form_data, ensure_ascii=False) + upd.pop('id', None) + r = client.request('PUT', f'/api/visualdev/Base/{form_id}', data=upd) + if r.code == 200: + client.visual_dev.release(form_id) + return r.code == 200 + +# 发布后调用 +if fix_relation_form(client, func_id, "目标表单ID"): + print("relationForm columnOptions 修复并重新发布成功") +``` + +> **注意**:由于目标表单需要先创建才能知道其 ID,`columnOptions` 无法在 `build_full_config` 阶段自动生成。必须在表单发布后,通过查询目标表单的 `columnData` 提取,然后更新并重新发布。 + +### 完整示例 + +参考 `aibridge/examples/deploy_all.py` 中 `AisProjectUser` 的定义(包含 relationForm 配置)。 + +--- + +## 调试方法论 + +> **核心原则:JNPF 是人工配置为主的低代码平台,当遇到 API 走不通的问题时,应优先参考前端 API 调用及代码实现,并尽快查看后端日志和源码。** + +### 排查顺序 + +``` +1. 前端代码 — 参考前端如何调用 API(请求格式、参数、请求头) + web/ + 重点: api/ 目录、stores/ 中的状态管理 + +2. Swagger 文档 — http://127.0.0.1:30000/doc.html#/home + +3. 后端日志 — log/jnpf-java-boot/log_error.log / log_total.log + 关键搜索: "错误提示"、"当前执行SQL"、"接口请求失败" + +4. 后端源码 — jnpf/后端/jnpf-java-boot/jnpf-system/jnpf-system-biz/ + 重点: DataInterfaceServiceImpl.java, VisualdevController.java +``` + +### 实用调试命令 + +```bash +# 查看最新的后端错误 +tail -50 log/jnpf-java-boot/log_error.log + +# 查看最近执行的 SQL +grep "当前执行SQL" log/jnpf-java-boot/log_total.log | tail -10 + +# 搜索特定错误 +grep -A 5 "错误提示" log/jnpf-java-boot/log_total.log | tail -20 +``` + +### Python 调试 + +```python +import logging +logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s") + +# 检查原始响应 +resp = client.request("GET", "/api/system/Menu/ModuleBySystem") +print(f"原始响应: {resp.raw}") + +# 快速失败 +from aibridge import APIError +try: + resp = client.require_success(client.request("POST", "/api/visualdev/Base", data=payload)) +except APIError as e: + print(f"API 错误: code={e.code}, msg={e.msg}, raw={e.raw}") +``` diff --git a/docs/workflow-guide.md b/docs/workflow-guide.md new file mode 100644 index 0000000..546e442 --- /dev/null +++ b/docs/workflow-guide.md @@ -0,0 +1,736 @@ +# 工作流指南 + +> JNPF 工作流(Workflow)完整开发指南:模板管理、审批操作、委托监控。 + +## 概述 + +JNPF 工作流模块支持完整的审批流程管理,包括流程模板创建、流程设计、审批操作(同意/拒绝/转审/退回/加签等)、流程委托和监控。 + +AIBridge 通过 `WorkflowAPI` 封装了全部工作流接口。 + +```python +from aibridge.modules.workflow import WorkflowAPI + +workflow = WorkflowAPI(client) +``` + +## 流程模板管理 + +### 创建流程模板 + +```python +# 创建流程模板 +resp = workflow.create_template({ + "fullName": "采购审批流程", + "enCode": "purchaseApproval", + "type": 1, # 流程类型 + "category": "your_category_id", + "formId": "visual_dev_func_id", # 关联的表单功能ID + "enabledMark": 1, + "sortCode": 100, +}) +template_id = resp.id +print(f"模板创建成功: {template_id}") +``` + +### 获取模板列表 + +```python +# 分页获取模板列表 +resp = workflow.get_template_list({ + "currentPage": 1, + "pageSize": 20, +}) +for item in resp.data.get("list", []): + print(f"流程: {item['fullName']} (id={item['id']}, type={item['type']})") +``` + +### 通过表单获取关联流程 + +```python +# 获取某表单关联的所有流程 +resp = workflow.get_flow_list(form_id="visual_dev_func_id") +for flow in resp.data: + print(f"关联流程: {flow.get('fullName')}") +``` + +### 模板 CRUD + +```python +# 获取模板详情 +info = workflow.get_template_info(template_id) + +# 修改模板 +workflow.update_template({ + "id": template_id, + "fullName": "采购审批流程(修订版)", +}) + +# 复制模板 +workflow.copy_template(template_id) + +# 删除模板 +workflow.delete_template(template_id) + +# 导出模板 +workflow.export_template(template_id) +``` + +## 流程设计 + +### 保存流程设计 + +```python +# 保存流程设计(包含节点、连线等完整配置) +workflow.save_flow({ + "id": template_id, + "flowTemplateJson": json.dumps(flow_design_data), + "flowTemplateNodes": json.dumps(flow_nodes), + "flowTemplateLines": json.dumps(flow_lines), +}) +``` + +### 获取流程设计详情 + +```python +# 获取流程引擎设计详情 +info = workflow.get_flow_info(template_id) +flow_data = info.data +# 包含节点配置、连线配置、表单绑定等 +``` + +### 流程版本管理 + +```python +# 获取版本列表 +versions = workflow.get_version_list(template_id) + +# 删除版本 +workflow.delete_version(version_id) + +# 复制创建新版本 +workflow.copy_version(version_id) +``` + +### 简单流程切换为标准流程 + +```python +# 简单流程 → 标准流程(不可逆) +workflow.change_type(template_id) +``` + +### 获取决策参数 + +```python +# 获取流程决策参数(用于条件分支配置) +params = workflow.get_decision_parameter(template_id) +``` + +## 流程表单绑定 + +### 获取流程表单信息 + +```python +# 通过小流程ID获取发起节点表单 +form_info = workflow.get_flow_form_info(template_id) + +# 通过大流程ID获取发起节点表单 +start_form = workflow.get_flow_start_form_info(template_id) + +# 获取流程版本ID和发起节点表单ID +form_ids = workflow.get_flow_start_form_id(template_id) +``` + +## 流程发起 + +### 新建流程发起 + +```python +# 创建并发起流程(填写表单 + 发起) +# 注意:formData 直接传 dict,不要 json.dumps +resp = workflow.create({ + "flowId": template_id, + "status": 1, # 1=发起 + "formData": { + "f_orderNo": "PO-2026-001", + "f_customer": "测试公司", + "f_amount": 5000.00, + "f_orderDate": int(time.time() * 1000), + "f_remark": "办公用品采购", + }, +}) +task_id = resp.id +print(f"流程发起成功: {task_id}") +``` + +### 获取发起列表 + +```python +# 获取我发起的流程列表 +resp = workflow.get_launch_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +### 发起后操作 + +```python +# 撤回发起 +workflow.launch_recall(task_id) + +# 撤销发起(终止流程) +workflow.revoke(task_id) + +# 催办 +workflow.press(task_id) + +# 获取事件日志 +workflow.get_event_log(task_id) +``` + +## 审批操作 + +### 获取待审核列表 + +```python +# category: 0=待审核 1=已审核 2=抄送我 3=所有 +resp = workflow.get_before_list(category=0, data={ + "currentPage": 1, + "pageSize": 20, +}) +for item in resp.data.get("list", []): + print(f"待审核: {item.get('fullName')} (operatorId={item.get('id')})") +``` + +### 审核(同意/拒绝) + +```python +# 同意 +workflow.audit(operator_id, { + "status": 1, # 1=同意 2=拒绝 3=驳回 + "handleOpinion": "同意采购", + "sign": "", + "copyIds": [], +}) + +# 拒绝 +workflow.audit(operator_id, { + "status": 2, + "handleOpinion": "预算超支,拒绝", +}) +``` + +### 签收/退签 + +```python +# 签收 +workflow.sign(operator_id) + +# 退签 +workflow.cancel_sign(operator_id) + +# 批量签收/退签(type: 0=签收 1=退签) +workflow.batch_sign({ + "ids": [operator_id_1, operator_id_2], + "type": 0, +}) +``` + +### 转审 + +将审批任务转给其他人处理: + +```python +workflow.transfer(operator_id, { + "handleOpinion": "转给部门经理处理", + "transferUserId": "target_user_id", +}) +``` + +### 退回 + +将流程退回到指定节点: + +```python +# 先获取可退回的节点列表 +nodes = workflow.get_back_node_list(operator_id) +# nodes.data 包含可退回的节点信息 + +# 退回到指定节点 +workflow.back(operator_id, { + "handleOpinion": "信息不完整,退回补充", + "targetNodeId": "target_node_id", +}) +``` + +### 加签/减签 + +```python +# 加签(增加审批人) +workflow.free_approver(operator_id, { + "handleOpinion": "请法务部会签", + "candidateList": [{"userId": "user_id_1"}, {"userId": "user_id_2"}], +}) + +# 减签(移除审批人) +workflow.reduce_approver(operator_id, { + "handleOpinion": "取消法务会签", + "operatorId": "operator_to_remove", +}) +``` + +### 暂存审批 + +```python +# 暂存审批意见(不提交) +workflow.save_audit(operator_id, { + "handleOpinion": "正在核实中...", +}) +``` + +### 协办 + +```python +# 协办(请他人协助处理) +workflow.assist(operator_id, { + "handleOpinion": "请协助核实金额", + "candidateList": [{"userId": "assistant_user_id"}], +}) + +# 协办保存 +workflow.save_assist(operator_id, { + "handleOpinion": "核实结果:金额正确", +}) +``` + +### 开始办理 + +```python +# 标记开始办理 +workflow.handle(operator_id) + +# 批量办理 +workflow.batch_handle({"ids": [op_id_1, op_id_2]}) +``` + +### 撤回审核 + +```python +workflow.audit_recall(operator_id, { + "handleOpinion": "审批有误,撤回重新审核", +}) +``` + +## 候选人 + +### 获取候选人列表 + +```python +# 获取当前节点的候选人 +workflow.get_candidate_user({ + "operatorId": operator_id, + "keyword": "", +}) +``` + +### 判断是否有候选人 + +```python +# 检查当前节点是否需要选择候选人 +workflow.get_candidates(operator_id, {}) +``` + +## 批量审批 + +```python +# 批量审批(0=通过 1=退回 2=转审) +workflow.batch_operation({ + "batchHandleList": [ + { + "operatorId": op_id_1, + "status": 1, + "handleOpinion": "批量通过", + }, + { + "operatorId": op_id_2, + "status": 1, + "handleOpinion": "批量通过", + }, + ], +}) + +# 获取批量审批候选人 +workflow.get_batch_candidate() + +# 获取批量审批流程列表 +workflow.get_batch_flow_selector() +``` + +## 进度查询 + +### 经办记录 + +```python +# 获取进度节点的经办列表 +records = workflow.get_record_list(task_id, node_id) +for record in records.data: + print(f"经办人: {record.get('handleUserName')} - {record.get('handleStatus')}") +``` + +### 抄送人员 + +```python +# 获取节点的抄送人员 +circulate = workflow.get_circulate_list(task_id, node_id) +``` + +### 查看发起节点表单 + +```python +# 查看发起节点填写的表单数据 +form = workflow.get_start_form_info(task_id) +``` + +### 查看子流程 + +```python +# 查看子流程信息 +workflow.get_sub_flow_info(node_code="sub_node", flow_id=task_id) +``` + +### 流程实例相关人员 + +```python +# 获取流程实例相关人员(分页) +workflow.get_task_user_list({ + "taskId": task_id, + "currentPage": 1, + "pageSize": 20, +}) +``` + +## 流程评论 + +```python +# 获取评论列表 +comments = workflow.get_comment_list({"taskId": task_id}) + +# 添加评论 +workflow.create_comment({ + "taskId": task_id, + "content": "请尽快处理", + "type": 1, +}) + +# 删除评论 +workflow.delete_comment(comment_id) +``` + +## 流程委托 + +### 获取委托列表 + +```python +delegates = workflow.get_delegate_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +委托用于将审批权临时转交给其他用户,通常在请假或出差时使用。 + +## 流程监控 + +### 获取监控列表 + +```python +monitors = workflow.get_monitor_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +流程监控用于管理员查看所有进行中的流程实例,支持终止异常流程等操作。 + +## Webhook + +### 获取 Webhook URL + +```python +# 获取 Webhook URL(用于外部系统触发流程) +url_info = workflow.get_webhook_url({"flowId": flow_id}) +webhook_url = url_info.data # 外部系统调用的 URL +``` + +### 获取 Webhook 字段 + +```python +# 获取 Webhook 需要传递的字段信息 +params = workflow.get_webhook_params(random_str) +# 返回 Webhook 需要的参数列表 +``` + +### 开启/关闭 Webhook + +```python +# 开启 Webhook 接收请求 +workflow.webhook_start(flow_id, random_str) +``` + +### Webhook 使用流程 + +``` +1. 调用 get_webhook_url 获取 Webhook URL +2. 调用 webhook_start 开启接收 +3. 外部系统向 Webhook URL 发送 POST 请求,携带流程表单数据 +4. JNPF 自动创建并启动流程实例 +``` + +## 流程模板其他功能 + +### 收藏流程 + +```python +# 获取收藏流程列表 +workflow.get_collect_flow_list() + +# 收藏/取消收藏 +workflow.set_collect_flow(template_id) +``` + +### 上架/下架 + +```python +# 上架/下架流程模板 +workflow.up_down_shelf({"id": template_id, "enabledMark": 1}) +``` + +### 流程选择器 + +```python +# 获取流程列表(用于发起页面选择) +workflow.get_flow_selector({"keyword": "采购"}) + +# 获取流程树形列表 +workflow.get_tree_list(form_type="3") # 3=工作流表单 +``` + +## 自定义按钮发起流程 + +在 OnlineDev 表单中,可以通过自定义按钮发起关联流程: + +```python +from aibridge.modules.visual_dev import VisualDevAPI + +visual_dev = VisualDevAPI(client) + +# 通过自定义按钮发起流程(formData 直接传 dict) +visual_dev.launch_flow(model_id, { + "id": record_id, + "formData": {"f_amount": 5000}, +}) +``` + +## 完整示例:创建「采购审批」工作流 + +以下示例演示从零开始创建一个带审批的完整功能,参考 `examples/create_procurement_workflow.py`。 + +### 完整流程 + +```python +from aibridge import JNPFClient, JNPFConfig +from aibridge.models import FieldDef +from aibridge.builders.full_config import build_full_config, build_create_payload + +# 1. 配置并登录 +config = JNPFConfig( + base_url="http://localhost:30000", + account="admin", + password="d4958348...", # 96字符AES密文(从浏览器提取) + app_code="your_app_code", +) +client = JNPFClient.from_config(config) +client.login() + +# 2. 定义字段 +fields = [ + FieldDef(field="f_orderNo", field_name="采购编号", required=True), + FieldDef(field="f_itemName", field_name="文具名称", required=True), + FieldDef(field="f_quantity", field_name="采购数量", jnpf_key="inputNumber", + data_type="int", data_length="10", required=True), + FieldDef(field="f_totalAmount", field_name="总金额", jnpf_key="inputNumber", + data_type="decimal", data_length="18"), + FieldDef(field="f_supplier", field_name="供应商", required=True), + FieldDef(field="f_reqPerson", field_name="申请人", required=True), +] + +# 3. 创建并发布表单(webType=3 表单列表工作流) +config_result = build_full_config( + full_name="文具采购", + en_code="stationeryProcurement", + table_name="base_stationery_procurement", + table_label="文具采购表", + description="文具采购申请与审批管理", + category="", + fields=[f.to_dict() for f in fields], + web_type=3, # 表单列表工作流 +) +payload = build_create_payload(config_result) # 动态建表模式 +resp = client.visual_dev.create(payload) +func_id = resp.id +client.visual_dev.release(func_id) # 发布,自动建表 + +# 4. 一步创建流程模板并发布 +# 内部:create_template(含 flowXml/flowNodes/flowConfig) → get_version_list → save_flow +flow_result = client.workflow.create_simple_flow( + full_name="文具采购审批", + en_code="stationeryProcurementFlow", + form_id=func_id, + approver_user_ids=["user_id_here"], # 审批人 ID + form_name="文具采购", + flow_type=1, # 简单流程 +) +version_id = flow_result["version_id"] + +# 5. 创建菜单 +dir_resp = client.menu.create_directory_menu("文具管理", "stationery_mgmt") +client.menu.create_form_menu("文具采购", "stationeryProcurement", + func_id, dir_resp.id, web_type=3) + +# 6. 发起流程 +task_resp = client.workflow.launch_task(version_id, { + "f_orderNo": "CG-2026-001", + "f_itemName": "中性笔(黑色)", + "f_quantity": 500, + "f_supplier": "晨光文具有限公司", + "f_reqPerson": "李明", +}) +task_id = task_resp.id + +# 7. 审批 +pending = client.workflow.get_pending_tasks() +operator_id = pending[0]["taskOperatorId"] +client.workflow.approve(operator_id, "同意采购") +``` + +### 便捷方法速查 + +| 方法 | 用途 | 说明 | +|------|------|------| +| `create_simple_flow()` | 一键创建并发布流程模板 | 整合 create_template + save_flow | +| `launch_task()` | 快捷发起流程 | formData 直接传 dict,不做 JSON 序列化 | +| `approve()` | 快捷审批通过 | 自动带 status=1 | +| `reject()` | 快捷审批拒绝 | 自动带 status=2 | +| `get_pending_tasks()` | 获取待审批列表 | 返回 list[dict] | + +## 关键经验与踩坑记录 + +### 1. create_template 必须包含 flowXml/flowNodes/flowConfig + +**问题**:`create_template()` 调用后端 `templateService.create()`,内部会调用 `flowUtil.create()`。如果 `flowNodes` 为 null,`flowUtil.create()` 会从 flowNodes 中解析起始节点时抛 NPE,导致 `templateJson` 条目未创建。后续 `save_flow` 调用 `getInfo(flowId)` 会报 "数据不存在"。 + +**解决**:AIBridge 的 `create_simple_flow()` 已在 `create_template` 调用中包含完整的 flowXml/flowNodes/flowConfig,避免此问题。 + +### 2. 审批需要 status 字段 + +**问题**:`POST /api/workflow/operator/Audit/{operatorId}` 需要在请求体中包含 `status` 字段: +- `status=1`:同意 +- `status=2`:拒绝 + +如果缺少 status 字段,审批操作可能不生效或报错。 + +**解决**:AIBridge 的 `approve()` 和 `reject()` 便捷方法已自动包含 `status` 字段。 + +### 3. launch_task 的 isFlow 参数必须是整数 + +**问题**:`POST /api/workflow/task` 请求体中 `isFlow` 字段,Java 后端类型为 `Integer`。 +如果传入 Python 布尔值 `True`,序列化为 JSON `true` 会导致 Jackson 反序列化失败: +``` +Cannot deserialize value of type java.lang.Integer from Boolean value +``` + +**解决**:AIBridge 的 `launch_task()` 已修复,内部使用整数 `1`: + +```python +# 正确:AIBridge 内部发送 isFlow: 1 +client.workflow.launch_task(version_id, {"f_orderNo": "CG-001", ...}) # ✓ + +# 错误:手动传布尔值 +# client.request("POST", "/api/workflow/task", data={"isFlow": True, ...}) # ✗ +``` + +### 4. 流程发起 formData 必须传 dict,不要 json.dumps + +**问题**:`POST /api/workflow/task` 的请求体中 `formData` 字段,后端 `FlowHandleModel.formData` +类型为 `Map`。如果传入 `json.dumps(dict)` 产生的 JSON 字符串,Jackson 会将其 +反序列化为 String 而非 Map,后续取值时抛 NPE("系统异常")。 + +**解决**:AIBridge 的 `launch_task()` 直接传 dict,不做序列化。 + +```python +# 正确:直接传 dict +client.workflow.launch_task(version_id, {"f_orderNo": "CG-001", "f_itemName": "中性笔"}) + +# 错误:不要手动序列化 +# client.workflow.launch_task(version_id, json.dumps({"f_orderNo": "CG-001"})) # ✗ +``` + +### 4. get_flow_info 的参数是 version_id,不是 template_id + +**问题**:`GET /api/workflow/template/Info/{id}` 查的是 templateJson 实体(version_id / flowId), +不是 template_id。用 template_id 调用会返回 "数据不存在"。 + +**解决**:先通过 `get_version_list(template_id)` 获取 version_id: + +```python +versions = client.workflow.get_version_list(template_id) +flow_id = versions.data[0]["id"] +info = client.workflow.get_flow_info(flow_id) # 用 flow_id,不是 template_id +``` + +### 5. 删除资源时的正确顺序 + +**问题**:流程模板通过 workflow_node 引用了表单的 formId,如果先删表单,会因外键约束报错。 + +**正确顺序**:流程模板 → 表单 → 功能菜单 → 目录菜单。 + +```python +# 1. 先删模板(解除表单引用) +client.workflow.delete_template(template_id) +# 2. 再删表单 +client.visual_dev.delete(func_id) +# 3. 删功能菜单 +client.menu.delete(menu_id) +# 4. 最后删目录菜单 +client.menu.delete(dir_id) +``` + +### 6. 前端发起流程报 undefined.vue 的排查 + +**问题**:前端报 "该文件不存在: ../views/workFlow/workFlowForm/undefined.vue"。 + +**根因**:后端 `getFormByTemplateId` 返回的表单信息中 `enCode` 为空,导致前端路径拼接为 `undefined.vue`。 + +**排查步骤**: + +1. 确认表单已发布(`base_visualdev_release` 有记录) +2. 确认 `workflow_node` 起始节点的 `f_form_id` 与 `base_visual_dev` ID 一致 +3. 确认 `App-Code` 正确(多租户隔离) +4. 运行诊断脚本:`python3 -m aibridge.examples.diagnose_workflow_form` + +### 5. 审批人不能与发起人相同 + +**问题**:审批时报"系统异常",可能是因为当前用户就是流程发起人,同时又被设为审批人。JNPF 规则不允许用户审批自己发起的流程。 + +**解决**:使用另一个用户账号登录来审批,或在创建流程时指定不同的审批人。 + +### 6. 动态建表模式 + +**问题**:`visual_dev.create()` 如果传非空 `tables`,后端会校验物理表是否存在和主键策略。新功能通常没有物理表,会报 "请在数据库中添加对应的数据表"。 + +**解决**:使用 `build_create_payload(config)` 默认传空 tables,`release()` 时后端自动从 formData 创建物理表。 + +### 7. webType=3 是工作流类型 + +创建需要审批流程的功能时,必须使用 `webType=3`(表单列表工作流),不能使用 `webType=2`(表单加列表)。只有 `webType=3` 的功能才能绑定流程模板。 diff --git a/docs/workflow/01-template-guide.md b/docs/workflow/01-template-guide.md new file mode 100644 index 0000000..26dd277 --- /dev/null +++ b/docs/workflow/01-template-guide.md @@ -0,0 +1,129 @@ +# 流程模板创建与配置 + +> 来源:前端 `views/onlineDev/flowEngine/DesignForm.vue`、后端 `DefinitionController.java` + +## 创建模板 + +### DesignForm.vue 关键代码 + +```typescript +// 模板创建/编辑 +const query = { + ...values, + iconBackground: state.iconBackground, + id: state.dataForm.id, + type: state.dataForm.type, // 0=标准, 1=简单, 2=任务, 4=决策 +}; +const formMethod = state.dataForm.id ? update : create; +formMethod(query).then((res) => { + if (type === 1) emit('design', { id, fullName, type }); +}); +``` + +### 模板字段说明 + +| 字段 | 说明 | 必填 | +|------|------|------| +| fullName | 流程名称 | 是 | +| enCode | 流程编码 | 是 | +| type | 流程类型 | 是 | +| category | 分类ID | 是 | +| icon | 图标 | 是 | +| iconBackground | 图标背景色 | 否 | +| showType | 显示位置 | 否 | +| sortCode | 排序 | 否 | +| description | 说明 | 否 | + +### 流程类型 (type) + +| type | 名称 | 说明 | +|------|------|------| +| 0 | 标准流程 | 用户自定义节点和连线 | +| 1 | 简单流程 | 预定义三节点 | +| 2 | 任务流程 | 任务处理节点 | +| 3 | 自由流程 | 自由选择审批人 | +| 4 | 决策流程 | 条件分支决策 | + +### API 调用 + +```python +# 创建模板 +resp = client.workflow.create_template({ + "fullName": "采购审批", + "enCode": "purchaseFlow", + "type": 1, + "category": "category_id", + "icon": "icon-ym icon-ym-flow", + "iconBackground": "#008cff", +}) +template_id = resp.id + +# 更新模板 +client.workflow.update_template({ + "id": template_id, + "fullName": "采购审批(修订版)", +}) + +# 删除模板 +client.workflow.delete_template(template_id) +``` + +## 版本管理 + +### 新增版本 + +```typescript +// copyVersion -> 返回新版本ID +copyVersion(currentVersion.id).then((res) => { + const newVersionId = res.data; +}); +``` + +### 版本状态 + +| state | 名称 | 说明 | +|-------|------|------| +| 0 | 设计中 | 可编辑 | +| 1 | 启用中 | 已发布运行 | +| 2 | 已归档 | 不可用 | + +### API 调用 + +```python +# 获取版本列表 +versions = client.workflow.get_version_list(template_id) +for v in versions.data: + print(f"版本: {v['fullName']}, state={v['state']}, id={v['id']}") + +# 新增版本(复制) +new_version = client.workflow.copy_version(version_id) + +# 删除版本 +client.workflow.delete_version(version_id) +``` + +## 模板信息获取 + +```python +# 获取模板详情 +info = client.workflow.get_template_info(template_id) + +# 获取流程设计信息(包含 flowNodes) +flow_info = client.workflow.get_flow_info(version_id) + +# 获取流程列表(分页) +list_resp = client.workflow.get_template_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +## 平台示例 + +| 模板 | ID | type | 说明 | +|------|-----|------|------| +| 请假申请 | 585824179933152389 | 0 | 自由审批,包含请假类型、时长验证 | +| 销售订单 | 585824509966156933 | 1 | 简单流程,商品明细 | +| CRM订单 | 585361795057715206 | 1 | 简单流程,商品明细、收款计划 | +| 物资申请 | 588008146002249413 | 1 | 简单流程 | +| 付款申请 | 588010241019348677 | 1 | 简单流程 | diff --git a/docs/workflow/02-flow-design-guide.md b/docs/workflow/02-flow-design-guide.md new file mode 100644 index 0000000..b414f9b --- /dev/null +++ b/docs/workflow/02-flow-design-guide.md @@ -0,0 +1,231 @@ +# 流程设计指南 + +> 来源:前端 `views/onlineDev/flowEngine/Form.vue`、FlowProcess 组件 + +## 流程设计器结构 + +### Form.vue 关键代码 + +```typescript +// 获取流程设计数据 +getFlowInfo(currentVersion.id).then((res) => { + state.dataForm = { ...state.dataForm, ...res.data }; + state.flowConfig = JSON.parse(state.dataForm.flowConfig || '{}'); +}); + +// 保存流程设计 +saveFlow({ + ...data, + id: template_id, + flowId: version_id, + flowConfig: JSON.stringify(flowConfig), +}).then((res) => { + if (data.type === 1) { + // 发布 + currentVersion.state = 1; + } +}); +``` + +## save_flow 接口 + +### 请求参数 + +```python +client.workflow.save_flow({ + "id": template_id, # 模板ID + "flowId": version_id, # 版本ID + "flowXml": flow_xml, # BPMN XML(需URL编码) + "flowNodes": flow_nodes, # 节点配置字典 + "flowConfig": flow_config, # JSON字符串 + "type": 1, # 0=保存, 1=发布 +}) +``` + +### flowXml 格式 + +**简单流程(type=1)** - 必须 URL 编码: +```xml + + + + + Flow_1iadlmn + + + Flow_1iadlmn + Flow_1kz1x8a + + ... + + +``` + +### flowNodes 结构 + +```python +{ + "global": { + "type": "global", + "nodeId": "global", + "formId": "form_id", + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "connectList": ["Flow_1", "Flow_2"], + }, + "Event_0oz4pwh": { # 发起节点 + "type": "start", + "nodeId": "Event_0oz4pwh", + "nodeName": "流程发起", + "formId": "form_id", + }, + "Activity_1qf73gq": { # 审批节点 + "type": "approver", + "nodeId": "Activity_1qf73gq", + "nodeName": "部门审批", + "formId": "form_id", + "assigneeType": 6, + "approvers": [{"id": "user_id", "type": "user"}], + "counterSign": 0, + "hasOpinion": True, + }, + "Event_0zlhfee": { # 结束节点 + "type": "end", + "nodeId": "Event_0zlhfee", + }, +} +``` + +### flowConfig 结构 + +```python +# 简单/标准/任务/自由流程 +{"visibleType": 1} # 1=公开, 2=权限设置 + +# 决策流程 +{ + "visibleType": 1, + "startParameterList": [], # 自定义入参 + "endParameterList": [], # 自定义出参 +} +``` + +## AIBridge 便捷方法 + +```python +# 一键创建简单流程(推荐) +result = client.workflow.create_simple_flow( + full_name="采购审批", + en_code="purchaseFlow", + form_id="visual_dev_id", + approver_user_ids=["user_id_1", "user_id_2"], +) +# 返回: {"template_id": "...", "version_id": "..."} + +# 创建标准流程 +result = client.workflow.create_standard_flow( + full_name="请假申请", + en_code="leaveFlow", + form_id="visual_dev_id", +) + +# 创建任务流程 +result = client.workflow.create_task_flow( + full_name="任务处理", + en_code="taskFlow", + form_id="visual_dev_id", + handler_user_ids=["user_id"], +) + +# 创建自由流程 +result = client.workflow.create_free_flow( + full_name="自由审批", + en_code="freeFlow", + form_id="visual_dev_id", + approver_user_ids=["user_id"], +) + +# 创建决策流程 +result = client.workflow.create_decision_flow( + full_name="条件审批", + en_code="decisionFlow", + form_id="visual_dev_id", + branch_a_user_ids=["user_id_1"], + branch_b_user_ids=["user_id_2"], +) +``` + +## 审批节点配置 (assigneeType) + +| 值 | 名称 | 配置项 | +|---|------|-------| +| 1 | 发起人上级 | managerLevel: 1-10 | +| 2 | 特定岗位 | assignList: 岗位列表 | +| 3 | 发起人自己 | - | +| 4 | 表单变量 | formFieldType, formField | +| 5 | 审批节点 | approverNodeId | +| 6 | 指定成员 | approvers: [{id, type}] | +| 7 | 候选人 | isCandidates: true | +| 9 | 数据接口 | interfaceConfig | +| 10 | 逐级审批 | managerLevel | + +## 会签配置 (counterSign) + +```python +{ + "counterSign": 1, # 0=或签, 1=会签, 2=依次审批 + "counterSignConfig": { + "auditType": 1, # 1=按百分比, 2=按人数 + "auditRatio": 100, # 通过比例 + "auditNum": 1, # 通过人数 + "rejectType": 0, # 拒绝规则 + "rejectRatio": 10, + "rejectNum": 1, + } +} +``` + +## 按钮配置 + +```python +{ + "hasAuditBtn": True, + "auditBtnText": "同意", + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": False, + "freeApproverBtnText": "加签", + "hasReduceApproverBtn": False, + "reduceApproverBtnText": "减签", + "hasTransferBtn": False, + "transferBtnText": "转审", + "hasAssistBtn": False, + "assistBtnText": "协办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", +} +``` + +## 超时配置 + +```python +{ + "timeLimitConfig": { + "on": 1, # 0=不启用, 1=启用 + "nodeLimit": 0, # 节点时限 + "duringDeal": 24, # 办理时长(小时) + }, + "overTimeConfig": { + "on": 2, # 0=不启用, 1=自动通过, 2=通知 + "firstOver": 24, # 首次超时时间 + "overNotice": True, + "overAutoApprove": False, + "overAutoApproveTime": 5, + } +} +``` diff --git a/docs/workflow/03-task-operation-guide.md b/docs/workflow/03-task-operation-guide.md new file mode 100644 index 0000000..a21b84c --- /dev/null +++ b/docs/workflow/03-task-operation-guide.md @@ -0,0 +1,219 @@ +# 任务操作指南 + +> 来源:前端 `views/workFlow/components/FlowParser.vue`、`flowTodo/index.vue` + +## 任务生命周期 + +``` +发起 → 待办 → 审批中 → 通过/拒绝/退回 → 结束 +``` + +## FlowParser.vue 核心代码 + +```typescript +// 获取任务详情 +function getBeforeInfo(config) { + const query = { + taskNodeId: config.taskNodeId, + operatorId: config.operatorId, + flowId: config.flowId, + opType: config.opType, + }; + getFlowTaskInfo(config.id || '0', query).then((res) => { + state.formInfo = res.data.formInfo || {}; + state.taskInfo = res.data.taskInfo || {}; + state.flowInfo = res.data.flowInfo || {}; + state.btnInfo = res.data.btnInfo || {}; + }); +} +``` + +## opType 含义 + +| opType | 含义 | 说明 | +|--------|------|------| +| -1 | 新建/编辑 | 我发起的新建/编辑 | +| 0 | 详情 | 我发起的详情 | +| 1 | 待签 | 待签收事宜 | +| 2 | 待办 | 待审批事宜 | +| 3 | 在办 | 审批中 | +| 4 | 已办 | 已完成 | +| 5 | 抄送 | 抄送事宜 | +| 6 | 监控 | 流程监控 | + +## 发起流程 + +### FlowPopup.vue + +```typescript +function toDetail(record) { + const data = { + id: record.taskId, + flowId: record.flowId, + opType: -1, // 发起 + operatorId: record.id, + }; + openFlowParser(true, data); +} +``` + +### API 调用 + +```python +# 发起流程 +task = client.workflow.launch_task(version_id, { + "f_amount": 5000, + "f_reason": "办公用品采购", +}) + +# 快捷发起(推荐) +task = client.workflow.create({ + "flowId": version_id, + "status": 1, + "flowUrgent": 1, + "isFlow": 1, + "formData": {"f_amount": 5000}, +}) +task_id = task.id +``` + +### launch_task 参数 + +```python +{ + "flowId": version_id, # 版本ID(必须) + "status": 1, # 1=发起, 0=暂存 + "flowUrgent": 1, # 紧急程度 1=普通 2=紧急 3=特别紧急 + "isFlow": 1, # 整数1,不是布尔值True + "formData": { # 表单数据,dict直接传 + "f_orderNo": "PO-001", + "f_amount": 5000, + } +} +``` + +## 待办列表 + +### flowTodo/index.vue + +```typescript +function toDetail(record) { + const data = { + id: record.taskId, + flowId: record.flowId, + opType: 2, // 待办 + operatorId: record.id, + }; + openFlowParser(true, data); +} +``` + +### API 调用 + +```python +# 获取待办列表 +resp = client.workflow.get_before_list("1", { + "currentPage": 1, + "pageSize": 20, +}) +for item in resp.data.get("list", []): + print(f"待办: {item['fullName']}, operatorId={item['id']}") + +# 快捷获取待办(推荐) +tasks = client.workflow.get_pending_tasks() +``` + +## 撤回发起 + +```python +# 撤回发起 +client.workflow.launch_recall(task_id, { + "handleOpinion": "撤回原因", +}) + +# 撤销发起 +client.workflow.revoke(task_id, { + "handleOpinion": "撤销原因", +}) +``` + +## 催办 + +```python +client.workflow.press(task_id) +``` + +## 获取流程实例人员 + +```python +# 获取实例相关人员 +resp = client.workflow.get_task_user_list({ + "taskId": task_id, + "currentPage": 1, + "pageSize": 20, +}) + +# 获取事件日志 +resp = client.workflow.get_event_log(task_id) + +# 获取流转记录 +resp = client.workflow.get_record_list(task_id, node_id) + +# 获取抄送人员 +resp = client.workflow.get_circulate_list(task_id, node_id) +``` + +## 发起列表 + +```python +# 获取我发起的流程 +resp = client.workflow.get_launch_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +## 任务状态 (taskInfo.status) + +| status | 名称 | 说明 | +|--------|------|------| +| 1 | 进行中 | 审批中 | +| 2 | 已通过 | 审批通过 | +| 3 | 已拒绝 | 审批拒绝 | +| 4 | 已终止 | 被终止 | +| 5 | 已暂停 | 暂停中 | +| 6 | 撤销中 | 撤销操作中 | +| 7 | 已撤销 | 已撤销 | +| 8 | 已退回 | 被退回 | +| 9 | 已撤回 | 已撤回 | + +## 发起后操作 + +| 方法 | 说明 | +|------|------| +| `launch_recall(task_id)` | 撤回发起 | +| `revoke(task_id)` | 撤销发起(终止流程) | +| `press(task_id)` | 催办 | + +## 批量操作 + +```python +# 批量签收 +client.workflow.batch_sign({ + "ids": [op_id_1, op_id_2], + "type": 0, # 0=签收, 1=退签 +}) + +# 批量办理 +client.workflow.batch_handle({ + "ids": [op_id_1, op_id_2], +}) + +# 批量审批 +client.workflow.batch_operation({ + "batchHandleList": [ + {"operatorId": op_id_1, "status": 1, "handleOpinion": "同意"}, + {"operatorId": op_id_2, "status": 1, "handleOpinion": "同意"}, + ], +}) +``` diff --git a/docs/workflow/04-approval-operation-guide.md b/docs/workflow/04-approval-operation-guide.md new file mode 100644 index 0000000..a559a76 --- /dev/null +++ b/docs/workflow/04-approval-operation-guide.md @@ -0,0 +1,209 @@ +# 审批操作指南 + +> 来源:前端 `FlowParser.vue`、后端 `TaskController.java` + +## 审批流程 + +``` +待办 → 签收 → 审批 → 通过/拒绝/退回 +``` + +## FlowParser.vue 审批代码 + +```typescript +// 审批通过/拒绝 +function handleApproval() { + const query = { + ...state.approvalData, + ...state.formData, + ...state.freeFlowConfig, + }; + if (state.eventType === 'audit') query.handleStatus = 1; + if (state.eventType === 'reject') query.handleStatus = 0; + + const approvalMethod = + state.eventType === 'freeApprover' ? freeApprover : + state.eventType === 'back' ? back : audit; + + approvalMethod(state.config.operatorId, query).then((res) => handleError(res)); +} +``` + +## 审批操作 + +### API 调用 + +```python +# 审批通过(推荐) +client.workflow.approve(operator_id, "同意") + +# 审批拒绝(推荐) +client.workflow.reject(operator_id, "不同意") + +# 通用审批 +client.workflow.audit(operator_id, { + "status": 1, # 1=同意, 2=拒绝 + "handleOpinion": "同意", + "sign": "", + "fileList": [], + "candidateList": [], +}) +``` + +### audit 参数 + +| 参数 | 说明 | 必填 | +|------|------|------| +| status | 审批状态 | 是 | +| handleOpinion | 审批意见 | 否 | +| sign | 签章 | 否 | +| fileList | 附件列表 | 否 | +| candidateList | 候选人列表 | 否 | + +## 签收/退签 + +```python +# 签收 +client.workflow.sign(operator_id) + +# 退签 +client.workflow.cancel_sign(operator_id) + +# 开始办理 +client.workflow.handle(operator_id) +``` + +## 转审 + +```python +# 转给其他人审批 +client.workflow.transfer(operator_id, { + "handleOpinion": "转给部门经理", + "transferUserId": "target_user_id", +}) +``` + +## 退回 + +### 获取可退回节点 + +```python +# 获取可退回的节点列表 +resp = client.workflow.get_back_node_list(operator_id) +nodes = resp.data # [{nodeId, nodeName, ...}] +``` + +### 执行退回 + +```python +# 退回 +client.workflow.back(operator_id, { + "handleOpinion": "信息不完整,退回补充", + "targetNodeId": "target_node_id", +}) +``` + +### backType 退回类型 + +| backType | 名称 | 说明 | +|----------|------|------| +| 1 | 重新审批 | 退回后重新走原流程 | +| 2 | 从当前节点审批 | 退回后跳过已审批节点 | +| 3 | 自定义审批 | 用户选择 | + +## 加签/减签 + +```python +# 加签(增加审批人) +client.workflow.free_approver(operator_id, { + "handleOpinion": "请法务会签", + "candidateList": [ + {"userId": "user_id_1"}, + {"userId": "user_id_2"}, + ], +}) + +# 减签(移除审批人) +client.workflow.reduce_approver(operator_id, { + "handleOpinion": "取消法务会签", + "operatorId": "operator_to_remove", +}) +``` + +## 协办 + +```python +# 协办(请他人协助处理) +client.workflow.assist(operator_id, { + "handleOpinion": "请协助核实金额", + "candidateList": [{"userId": "assistant_user_id"}], +}) + +# 协办保存 +client.workflow.save_assist(operator_id, { + "handleOpinion": "核实结果:金额正确", +}) +``` + +## 暂存审批 + +```python +# 暂存审批意见(不提交) +client.workflow.save_audit(operator_id, { + "handleOpinion": "正在核实中...", +}) +``` + +## 撤回审核 + +```python +# 撤回审核(审批人撤回自己的审批) +client.workflow.audit_recall(operator_id, { + "handleOpinion": "审批有误,撤回重新审核", +}) +``` + +## 候选人 + +```python +# 获取候选人列表 +resp = client.workflow.get_candidate_user({ + "operatorId": operator_id, + "keyword": "", +}) + +# 判断是否有候选人 +resp = client.workflow.get_candidates(operator_id, {}) +``` + +## 按钮与操作的映射 + +| 按钮 | 方法 | 说明 | +|------|------|------| +| 提交 | submit | 发起流程 | +| 签收 | sign | 签收任务 | +| 同意 | audit(status=1) | 审批通过 | +| 拒绝 | audit(status=2) | 审批拒绝 | +| 退回 | back | 退回 | +| 加签 | free_approver | 增加审批人 | +| 减签 | reduce_approver | 移除审批人 | +| 转审 | transfer | 转给其他人 | +| 协办 | assist | 请人协助 | +| 暂存 | save_audit | 暂存意见 | +| 撤回 | audit_recall | 撤回审批 | + +## 审批规则 + +1. **审批人不能与发起人相同** - JNPF 规则限制 +2. **已完成的任务不能加签** - 系统校验 +3. **被转办或被协办的不能加签** - 系统校验 +4. **不能给自己加签** - 系统校验(WF106) + +## 错误码 + +| 错误码 | 说明 | +|--------|------| +| WF081 | 已完成的任务不能加签 | +| WF106 | 不能给自己加签/审批 | +| DEFINITION_NOT_EXIST | 流程模板不存在 | +| TASK_NOT_EXIST | 任务不存在 | diff --git a/docs/workflow/05-advanced-features-guide.md b/docs/workflow/05-advanced-features-guide.md new file mode 100644 index 0000000..45aad7d --- /dev/null +++ b/docs/workflow/05-advanced-features-guide.md @@ -0,0 +1,201 @@ +# 高级功能指南 + +## 流程监控 + +### 监控按钮 + +```typescript +// FlowParser.vue - 流程监控 +if (btnInfo?.hasCancelBtn) monitorBtnList.push({ id: 'cancel', fullName: '终止' }); +if (btnInfo?.hasActivateBtn) monitorBtnList.push({ id: 'resurgence', fullName: '复活' }); +if (btnInfo?.hasPauseBtn) monitorBtnList.push({ id: 'pause', fullName: '暂停' }); +if (btnInfo?.hasAssignBtn) monitorBtnList.push({ id: 'assign', fullName: '指派' }); +``` + +### API 调用 + +```python +# 获取监控列表 +resp = client.workflow.get_monitor_list({ + "currentPage": 1, + "pageSize": 20, +}) + +# 终止流程 +client.workflow.cancel(task_id) + +# 暂停流程 +client.workflow.pause(task_id) + +# 复活流程 +client.workflow.resurgence(task_id) + +# 指派任务 +client.workflow.assign(task_id, { + "assignUserId": "user_id", +}) +``` + +## 流程委托 + +### 说明 +委托用于将审批权临时转交给其他用户,通常在请假或出差时使用。 + +```python +# 获取委托列表 +resp = client.workflow.get_delegate_list({ + "currentPage": 1, + "pageSize": 20, +}) +``` + +## Webhook + +### 使用流程 + +``` +1. get_webhook_url -> 获取 Webhook URL +2. webhook_start -> 开启接收 +3. 外部系统 POST 到 Webhook URL +4. JNPF 自动创建并启动流程 +``` + +### API 调用 + +```python +# 获取 Webhook URL +resp = client.workflow.get_webhook_url({"flowId": flow_id}) +webhook_url = resp.data # "http://..." + +# 获取 Webhook 字段 +resp = client.workflow.get_webhook_params(random_str) + +# 开启 Webhook +client.workflow.webhook_start(flow_id, random_str) +``` + +## 流程评论 + +```python +# 获取评论列表 +resp = client.workflow.get_comment_list({"taskId": task_id}) + +# 添加评论 +client.workflow.create_comment({ + "taskId": task_id, + "content": "请尽快处理", + "type": 1, +}) + +# 删除评论 +client.workflow.delete_comment(comment_id) +``` + +## 收藏流程 + +```python +# 获取收藏流程列表 +resp = client.workflow.get_collect_flow_list() + +# 收藏/取消收藏 +client.workflow.set_collect_flow(template_id) +``` + +## 上架/下架 + +```python +# 上架/下架流程模板 +client.workflow.up_down_shelf({ + "id": template_id, + "enabledMark": 1, # 1=上架, 0=下架 +}) +``` + +## 流程选择器 + +```python +# 获取流程列表(用于发起页面选择) +resp = client.workflow.get_flow_selector({"keyword": "采购"}) + +# 获取流程树形列表 +resp = client.workflow.get_tree_list(form_type="3") # 3=工作流表单 +``` + +## 决策参数 + +```python +# 获取流程决策参数(用于条件分支配置) +resp = client.workflow.get_decision_parameter(template_id) +``` + +## 节点跳转 + +### JumpCmd + +```java +// 后端 TaskController +public boolean jump(JumpFo fo) { + BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId()); + JumpCmd jumpCmd = new JumpCmd(fo.getInstanceId(), fo.getSource(), fo.getTarget(), "custom jump", bpmnModel, runtimeService); + managementService.executeCommand(jumpCmd); +} +``` + +### 获取可回退节点 + +```python +# 获取可回退的节点 +resp = client.workflow.get_back_node_list(operator_id) + +# 获取后续节点 +resp = client.workflow.get_task_next(task_id, node_id) +``` + +## 子流程 + +```python +# 查看子流程信息 +resp = client.workflow.get_sub_flow_info( + node_code="sub_node_code", + flow_id=task_id +) +``` + +## 外部节点重试 + +```python +# 外部节点重试 +client.workflow.retry_outside(node_id) +``` + +## 流程版本管理 + +```python +# 获取版本列表 +versions = client.workflow.get_version_list(template_id) + +# 新增版本 +new_version = client.workflow.copy_version(version_id) + +# 删除版本 +client.workflow.delete_version(version_id) + +# 切换为标准流程 +client.workflow.change_type(template_id) # 简单->标准(不可逆) +``` + +## 导出模板 + +```python +# 导出流程模板 +resp = client.workflow.export_template(template_id) +# 返回文件流 +``` + +## 复制模板 + +```python +# 复制流程模板 +resp = client.workflow.copy_template(template_id) +new_template_id = resp.id +``` diff --git a/docs/workflow/06-examples/01-simple-flow.md b/docs/workflow/06-examples/01-simple-flow.md new file mode 100644 index 0000000..16debb2 --- /dev/null +++ b/docs/workflow/06-examples/01-simple-flow.md @@ -0,0 +1,127 @@ +# 简单流程示例(type=1) + +> 来源:平台示例 crmOrder、salesOrder、materialapply、paymentapply + +## 特点 + +- 预定义三节点:发起 → 审批 → 结束 +- 快速配置,无需设计流程图 +- 支持指定审批人 + +## 平台示例 + +| 模板 | ID | 说明 | +|------|-----|------| +| CRM订单 | 585361795057715206 | 订单管理,含商品明细、收款计划 | +| 销售订单 | 585824509966156933 | 发票类型、商品明细 | +| 物资申请 | 588008146002249413 | 行政物资申请 | +| 付款申请 | 588010241019348677 | 财务付款申请 | + +## flowXml(URL编码后) + +```xml + + + + + Flow_1iadlmn + + + Flow_1iadlmn + Flow_1kz1x8a + + + + Flow_1kz1x8a + + + + +``` + +## flowNodes 结构 + +```python +{ + "global": { + "type": "global", + "nodeId": "global", + "formId": "form_id", + "titleType": 0, + "connectList": ["Flow_1iadlmn", "Flow_1kz1x8a"], + }, + "Event_0oz4pwh": { + "type": "start", + "nodeId": "Event_0oz4pwh", + "nodeName": "流程发起", + "formId": "form_id", + }, + "Activity_1qf73gq": { + "type": "approver", + "nodeId": "Activity_1qf73gq", + "nodeName": "部门审批", + "formId": "form_id", + "assigneeType": 6, + "approvers": [{"id": "user_id", "type": "user"}], + "counterSign": 0, + "hasOpinion": True, + "hasAuditBtn": True, + "hasRejectBtn": True, + }, + "Event_0zlhfee": { + "type": "end", + "nodeId": "Event_0zlhfee", + }, +} +``` + +## 代码示例 + +```python +from aibridge import JNPFClient, JNPFConfig + +config = JNPFConfig() +client = JNPFClient.from_config(config) +client.login() + +# 一键创建简单流程 +result = client.workflow.create_simple_flow( + full_name="采购审批", + en_code="purchaseFlow", + form_id="visual_dev_form_id", + approver_user_ids=["admin"], # 审批人 + form_name="采购申请", +) + +print(f"模板ID: {result['template_id']}") +print(f"版本ID: {result['version_id']}") + +# 发起流程 +task = client.workflow.launch_task(result["version_id"], { + "f_orderNo": "PO-2026-001", + "f_amount": 5000, + "f_reason": "办公用品采购", +}) +print(f"任务ID: {task.id}") + +# 审批 +tasks = client.workflow.get_pending_tasks() +if tasks: + client.workflow.approve(tasks[0]["taskOperatorId"], "同意采购") +``` + +## 审批按钮配置 + +```python +{ + "hasAuditBtn": True, + "auditBtnText": "同意", # 按钮文字 + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": False, + "hasTransferBtn": False, + "hasAssistBtn": False, +} +``` diff --git a/docs/workflow/06-examples/02-standard-flow.md b/docs/workflow/06-examples/02-standard-flow.md new file mode 100644 index 0000000..fd25bee --- /dev/null +++ b/docs/workflow/06-examples/02-standard-flow.md @@ -0,0 +1,135 @@ +# 自由审批流程示例(type=0) + +> 来源:平台示例 leaveApply、purapplyedae9、Paymentapplydc652、resignation + +## 特点 + +- 标准审批流程,用户自定义节点和连线 +- 可设计多级审批、会签、并行等复杂流程 +- 需要使用 FlowProcess 组件设计 + +## 平台示例 + +| 模板 | ID | 说明 | +|------|-----|------| +| 请假申请 | 585824179933152389 | 请假类型(事假/病假/婚假/产假/丧假/年假/调休)、时长验证 | +| 采购申请 | 585824148157105285 | 行政采购审批 | +| 付款申请(标准) | 585824103953335429 | 财务付款审批 | +| 离职申请触发 | 623164145176412357 | HR离职申请 | + +## flowXml(标准流程 - 空模板) + +```xml + + + + + + +``` + +## flowNodes(仅发起节点) + +```python +{ + "global": { + "type": "global", + "nodeId": "global", + "formId": "form_id", + "titleType": 0, + "connectList": [], + }, + "Event_04q7xii": { + "type": "start", + "nodeId": "Event_04q7xii", + "nodeName": "流程发起", + "formId": "form_id", + }, +} +``` + +## 设计器操作流程 + +``` +1. DesignForm.vue -> 创建模板 -> 获取 template_id +2. Form.vue -> 点击"确定并设计" -> 打开 FlowProcess 组件 +3. FlowProcess -> 添加节点 -> 配置节点属性 +4. 保存 -> save_flow +5. 发布 -> type=1 +``` + +## 多级审批配置 + +```python +{ + "Activity_dept": { + "type": "approver", + "nodeName": "部门经理审批", + "assigneeType": 1, # 发起人上级 + "managerLevel": 1, # 直属上级 + "counterSign": 0, # 或签 + }, + "Activity_hr": { + "type": "approver", + "nodeName": "HR审批", + "assigneeType": 6, # 指定成员 + "approvers": [{"id": "hr_user_id", "type": "user"}], + "counterSign": 1, # 会签 + "counterSignConfig": { + "auditType": 1, + "auditRatio": 100, + }, + }, +} +``` + +## 会签配置 + +```python +{ + "counterSign": 1, # 0=或签, 1=会签, 2=依次审批 + "counterSignConfig": { + "auditType": 1, # 1=按百分比, 2=按人数 + "auditRatio": 100, # 100%=全部通过 + "auditNum": 2, # 人数 + "rejectType": 0, + "rejectRatio": 10, + "rejectNum": 1, + } +} +``` + +## 代码示例 + +```python +from aibridge import JNPFClient, JNPFConfig + +config = JNPFConfig() +client = JNPFClient.from_config(config) +client.login() + +# 创建标准流程(只有发起节点,需要在设计器中添加审批节点) +result = client.workflow.create_standard_flow( + full_name="请假申请", + en_code="leaveFlow", + form_id="visual_dev_form_id", + form_name="请假申请表单", +) + +print(f"模板ID: {result['template_id']}") +print(f"版本ID: {result['version_id']}") + +# 获取流程信息(需要在设计器中设计后) +flow_info = client.workflow.get_flow_info(result["version_id"]) +print(f"flowNodes: {flow_info.data.get('flowNodes')}") +``` + +## 前端设计器源码 + +| 文件 | 说明 | +|------|------| +| `views/onlineDev/flowEngine/Form.vue` | 流程设计主入口 | +| `views/onlineDev/flowEngine/DesignForm.vue` | 模板基本信息表单 | +| `components/FlowProcess/` | BPMN 流程设计器组件 | +| `components/FlowProcess/src/helper/config.ts` | 节点默认配置 | +| `components/FlowProcess/src/propPanel/ApproverNode.vue` | 审批节点配置面板 | diff --git a/docs/workflow/06-examples/03-trigger-flow.md b/docs/workflow/06-examples/03-trigger-flow.md new file mode 100644 index 0000000..effbb7b --- /dev/null +++ b/docs/workflow/06-examples/03-trigger-flow.md @@ -0,0 +1,95 @@ +# 触发器流程示例(type=2) + +> 来源:平台示例 webhook、Timedtrigger、customeradd、messagetrigger + +## 特点 + +- 无审批环节 +- 由 Webhook 或定时器触发 +- 用于自动化任务 + +## 平台示例 + +| 模板 | ID | 说明 | +|------|-----|------| +| webhook触发 | 623157924671258821 | 纯Webhook触发,无表单 | +| 定时获取官网案例信息 | 623157956061429957 | 定时触发 | +| 客户新增事件触发 | 623157979998322885 | 数据事件触发 | +| 人员入职通知触发 | 624245824599098245 | 消息触发器 | + +## 与常规流程的区别 + +| 特性 | type=0/1 | type=2 触发器 | +|------|----------|---------------| +| 审批环节 | 有 | 无 | +| 表单 | 必需 | 可选 | +| flowId | 有 | 无 | +| 触发方式 | 人工发起 | Webhook/定时/事件 | + +## flowXml(触发器流程) + +```xml + + + + + + +``` + +## Webhook 配置 + +```python +# 获取 Webhook URL +resp = client.workflow.get_webhook_url({"flowId": template_id}) +webhook_url = resp.data + +# 开启 Webhook +client.workflow.webhook_start(template_id, random_str) + +# 外部系统调用 +import requests +requests.post(webhook_url, json={ + "f_data": "trigger data", +}) +``` + +## 触发器类型 + +### 1. Webhook 触发 +- 外部系统通过 HTTP POST 调用 +- 需要开启 webhook_start + +### 2. 定时触发 +- 配置 Cron 表达式 +- 系统自动定时执行 + +### 3. 数据事件触发 +- 绑定数据表变化事件 +- 如:客户新增时触发 + +## 后端实现 + +```java +// TriggerApi.java +public class TriggerApi { + // Webhook 触发入口 + public void webHookTrigger(String flowId, Map data) { + // 处理 Webhook 数据 + // 执行业务逻辑 + } + + // 定时触发入口 + public void timedTrigger(String flowId) { + // 获取配置的执行时间 + // 执行业务逻辑 + } +} +``` + +## 适用场景 + +1. **数据同步** - 当外部系统数据变化时同步到 JNPF +2. **定时任务** - 定期清理数据、发送报告 +3. **事件驱动** - 用户注册后自动发送欢迎邮件 +4. **消息通知** - 满足条件时发送通知 diff --git a/docs/workflow/06-examples/04-form-workflow.md b/docs/workflow/06-examples/04-form-workflow.md new file mode 100644 index 0000000..acdd7e8 --- /dev/null +++ b/docs/workflow/06-examples/04-form-workflow.md @@ -0,0 +1,175 @@ +# 表单工作流(webType=3) + +> 来源:平台示例 salesOrder、crmOrder 等所有需要审批的表单 + +## 特点 + +- 表单列表工作流(webType=3) +- 关联 VisualDev 表单 +- 通过菜单发起和审批 + +## webType 区别 + +| webType | 名称 | 说明 | +|---------|------|------| +| 1 | 纯表单 | 无列表 | +| 2 | 表单+列表 | 无流程 | +| 3 | 表单列表工作流 | 有流程审批 | +| 4 | 扩展字段 | 扩展其他字段 | + +## 创建流程表单 + +```python +from aibridge.builders.full_config import build_full_config, build_create_payload + +# 1. 构建表单配置 +config = build_full_config( + full_name="采购申请", + en_code="purchaseApply", + table_name="base_purchase_apply", + table_label="采购申请", + description="办公用品采购申请", + category="", + fields=[ + {"field": "f_orderNo", "fieldName": "单号", "jnpfKey": "comInput", "required": True}, + {"field": "f_amount", "fieldName": "金额", "jnpfKey": "inputNumber", "required": True}, + {"field": "f_reason", "fieldName": "理由", "jnpfKey": "textarea"}, + ], + web_type=3, # 关键:表单列表工作流 +) + +# 2. 创建表单 +payload = build_create_payload(config) +resp = client.visual_dev.create(payload) +func_id = resp.id + +# 3. 发布表单 +client.visual_dev.release(func_id) +``` + +## 创建菜单 + +```python +# 1. 创建目录菜单 +dir_resp = client.menu.create_directory_menu( + name="采购管理", + en_code="purchase_mgmt", + parent_id="root", +) + +# 2. 创建功能表单菜单 +menu_resp = client.menu.create_form_menu( + name="采购申请", + en_code="purchaseApply", + func_id=func_id, + parent_id=dir_resp.id, + web_type=3, # 关联工作流 +) +``` + +## 绑定流程模板 + +```python +# 创建流程模板 +result = client.workflow.create_simple_flow( + full_name="采购审批流程", + en_code="purchaseFlow", + form_id=func_id, # 关联表单 + approver_user_ids=["admin"], +) + +# 注意:需要在设计器中绑定到菜单 +``` + +## 发起流程 + +### 方式1:通过菜单发起 + +``` +菜单 -> 采购申请 -> 填写表单 -> 提交 -> 发起流程 +``` + +### 方式2:通过 API 发起 + +```python +# 获取版本ID +versions = client.workflow.get_version_list(template_id) +version_id = versions.data[0]["id"] + +# 发起流程 +task = client.workflow.launch_task(version_id, { + "f_orderNo": "PO-2026-001", + "f_amount": 5000, + "f_reason": "办公用品采购", +}) +``` + +## 审批流程 + +``` +待办 -> 审批 -> 通过/拒绝 -> 结束 +``` + +```python +# 获取待办 +tasks = client.workflow.get_pending_tasks() +if tasks: + operator_id = tasks[0]["taskOperatorId"] + + # 审批 + client.workflow.approve(operator_id, "同意") + + # 或拒绝 + client.workflow.reject(operator_id, "金额过高") +``` + +## 完整示例 + +```python +from aibridge import JNPFClient, JNPFConfig +from aibridge.builders.full_config import build_full_config, build_create_payload + +config = JNPFConfig() +client = JNPFClient.from_config(config) +client.login() + +# 1. 创建表单 +fields = [ + {"field": "f_title", "fieldName": "标题", "jnpfKey": "comInput", "required": True}, + {"field": "f_amount", "fieldName": "金额", "jnpfKey": "inputNumber", "required": True}, +] +config = build_full_config("采购申请", "purchase", "base_purchase", "采购申请", "", fields, web_type=3) +resp = client.visual_dev.create(build_create_payload(config)) +func_id = resp.id +client.visual_dev.release(func_id) + +# 2. 创建目录 +dir_resp = client.menu.create_directory_menu("采购管理", "purchase_mgmt", "root") + +# 3. 创建菜单 +client.menu.create_form_menu("采购申请", "purchase", func_id, dir_resp.id, web_type=3) + +# 4. 创建流程 +flow = client.workflow.create_simple_flow( + "采购审批", "purchaseFlow", func_id, ["admin"], "采购申请" +) + +# 5. 发起流程 +task = client.workflow.launch_task(flow["version_id"], { + "f_title": "办公用品采购", + "f_amount": 5000, +}) + +# 6. 审批 +tasks = client.workflow.get_pending_tasks() +if tasks: + client.workflow.approve(tasks[0]["taskOperatorId"], "同意") +``` + +## 关键配置项 + +| 配置 | 说明 | +|------|------| +| webType=3 | 表单列表工作流 | +| flowId | 关联的流程版本ID | +| formId | 关联的表单ID | diff --git a/docs/workflow/07-troubleshooting.md b/docs/workflow/07-troubleshooting.md new file mode 100644 index 0000000..7188c70 --- /dev/null +++ b/docs/workflow/07-troubleshooting.md @@ -0,0 +1,172 @@ +# 故障排查 + +> 来源:workflow-guide.md 踩坑记录、后端源码分析、工作流开发实践 + +## 常见错误 + +### 1. create_template 必须包含 flowXml/flowNodes/flowConfig + +**问题**:调用 `create_template` 后报 "数据不存在" + +**原因**:`create_template` 内部调用 `flowUtil.create()`,如果 `flowNodes` 为 null,会导致 NPE,`templateJson` 条目未创建 + +**解决**:使用 `create_simple_flow()` 或确保传入完整参数 + +```python +# 错误 +client.workflow.create_template({ + "fullName": "test", + "enCode": "test", + "type": 1, +}) + +# 正确 +client.workflow.create_simple_flow( + full_name="test", + en_code="test", + form_id="form_id", + approver_user_ids=["user_id"], +) +``` + +### 2. 审批需要 status 字段 + +**问题**:`audit` 调用不生效 + +**原因**:缺少 `status` 字段 + +**解决**:使用 `approve()` / `reject()` 或显式传入 status + +```python +# 正确 +client.workflow.audit(operator_id, { + "status": 1, # 1=同意, 2=拒绝 + "handleOpinion": "同意", +}) +``` + +### 3. launch_task 的 isFlow 必须是整数 + +**问题**:`Cannot deserialize value of type java.lang.Integer from Boolean` + +**原因**:Python `True` 序列化为 JSON `true`,Java 无法反序列化 + +**解决**:AIBridge 内部使用整数 `1` + +```python +# 正确 - AIBridge 内部处理 +client.workflow.launch_task(version_id, {"f_amount": 5000}) + +# 错误 - 不要手动传布尔值 +# client.request("POST", "/api/workflow/task", data={"isFlow": True}) # ✗ +``` + +### 4. formData 必须传 dict + +**问题**:"系统异常" 或数据取不到 + +**原因**:`formData` 后端类型为 `Map`,传 JSON 字符串会解析失败 + +**解决**:直接传 dict,不做序列化 + +```python +# 正确 +client.workflow.launch_task(version_id, {"f_amount": 5000}) + +# 错误 +# client.workflow.launch_task(version_id, json.dumps({"f_amount": 5000})) # ✗ +``` + +### 5. get_flow_info 参数是 version_id + +**问题**:"数据不存在" + +**原因**:用 template_id 而非 version_id + +**解决**: + +```python +# 先获取 version_id +versions = client.workflow.get_version_list(template_id) +version_id = versions.data[0]["id"] + +# 用 version_id 查询 +info = client.workflow.get_flow_info(version_id) +``` + +### 6. 审批人不能与发起人相同 + +**问题**:报"系统异常" + +**原因**:JNPF 规则不允许用户审批自己发起的流程 + +**解决**:使用另一个用户账号审批 + +### 7. 前端报 undefined.vue + +**问题**:报 "该文件不存在: ../views/workFlow/workFlowForm/undefined.vue" + +**排查**: +1. 确认表单已发布(`base_visualdev_release` 有记录) +2. 确认 `workflow_node` 起始节点的 `f_form_id` 与 `base_visual_dev` ID 一致 +3. 确认 `App-Code` 正确 + +### 8. create_template 后无法 save_flow + +**问题**:`save_flow` 报 "数据不存在" + +**原因**:`templateJson` 实体未创建 + +**解决**:使用 `create_simple_flow()` 或确保 create_template 时传入完整的 flowXml/flowNodes/flowConfig + +### 9. 删除资源顺序 + +**问题**:删除时报外键约束错误 + +**正确顺序**: +1. 流程模板 +2. 表单 +3. 功能菜单 +4. 目录菜单 + +```python +# 1. 先删模板 +client.workflow.delete_template(template_id) + +# 2. 再删表单 +client.visual_dev.delete(func_id) + +# 3. 删功能菜单 +client.menu.delete(menu_id) + +# 4. 最后删目录菜单 +client.menu.delete(dir_id) +``` + +## 错误码 + +| 错误码 | 说明 | +|--------|------| +| SUCCESS (200) | 成功 | +| FAILURE (999) | 失败 | +| DEPLOY_ERROR (9001) | 部署错误,检查 XML 格式 | +| DEFINITION_NOT_EXIST (9002) | 流程模板不存在 | +| INSTANCE_NOT_EXIST (9003) | 实例不存在 | +| TASK_NOT_EXIST (9004) | 任务不存在 | +| WF081 | 已完成的任务不能加签 | +| WF106 | 不能给自己加签/审批 | + +## 日志位置 + +| 日志 | 路径 | +|------|------| +| 错误日志 | `log/jnpf-java-boot/log_error.log` | +| 全量日志 | `log/jnpf-java-boot/log_total.log` | +| 后端源码 | `jnpf/后端/jnpf-java-boot/jnpf-flowable/` | + +## 调试建议 + +1. **API 调试**:使用 Swagger `http://127.0.0.1:30000/doc.html` +2. **查看日志**:优先查看 `log_error.log` +3. **参考前端**:查看前端 API 调用方式 +4. **检查数据库**:确认 `workflow_node`、`template_json` 等表数据正确 diff --git a/docs/workflow/README.md b/docs/workflow/README.md new file mode 100644 index 0000000..990e3a2 --- /dev/null +++ b/docs/workflow/README.md @@ -0,0 +1,183 @@ +# JNPF Workflow 文档索引 + +> JNPF 流程平台开发指南,整理自 17 条平台示例和前后端源码分析。 + +## JNPF 与 Flowable 引擎集成 + +JNPF 工作流基于 **Flowable** 引擎实现,流程数据存储在 JNPF 数据库,但流程执行由 Flowable 管理。 + +### 数据存储 + +| 组件 | 存储位置 | 说明 | +|------|----------|------| +| 流程模板 | `base_flow_template` 表 | JNPF 管理 | +| 流程版本 | `base_flow_template` 版本字段 | JNPF 管理 | +| 流程实例 | Flowable 表(ACT_*) | Flowable 引擎 | +| 任务节点 | Flowable 表(ACT_RU_*) | Flowable 引擎 | +| 表单数据 | `base_flow_task` 表 | JNPF 管理 | + +### 集成机制 + +1. **模板发布**:JNPF 保存流程模板(含 flowXml/flowNodes)到 `base_flow_template` +2. **流程发起**:JNPF 调用 Flowable API 创建流程实例,Flowable 生成任务节点 +3. **审批操作**:JNPF 调用 Flowable API 完成审批,Flowable 推进流程 +4. **任务查询**:JNPF 关联查询 Flowable 表和 JNPF 表,返回完整状态 + +### 关键表关系 + +``` +base_flow_template (模板) + ↓ version_id +base_flow_task (流程实例) ← 关联 → Flowable ACT_RU_* (任务) +``` + +### 与标准 Flowable 的差异 + +- JNPF 对 Flowable 做了封装,API 路径为 `/api/workflow/*` +- Flowable 原生 API 通过内部服务调用,不直接暴露 +- 表单数据绑定在 JNPF 层,Flowable 只负责流程控制 + +## 文档结构 + +``` +workflow/ +├── README.md # 本文档(速查入口) +├── 01-template-guide.md # 流程模板创建与配置 +├── 02-flow-design-guide.md # 流程设计指南 +├── 03-task-operation-guide.md # 任务操作指南 +├── 04-approval-operation-guide.md # 审批操作指南 +├── 05-advanced-features-guide.md # 高级功能指南 +├── 06-examples/ # 示例文档 +│ ├── 01-simple-flow.md # 简单流程(type=1) +│ ├── 02-standard-flow.md # 自由审批流程(type=0) +│ ├── 03-trigger-flow.md # 触发器流程(type=2) +│ └── 04-form-workflow.md # 表单工作流(webType=3) +└── 07-troubleshooting.md # 故障排查 + +../workflow-guide.md # 完整开发指南(详细) +``` + +## 快速参考 + +### 流程类型 +| type | 名称 | 说明 | +|------|------|------| +| 0 | 自由审批 | 标准审批流程,用户自定义节点和连线 | +| 1 | 简单流程 | 预定义三节点(发起→审批→结束) | +| 2 | 触发器流程 | Webhook/定时触发,无审批环节 | +| 3 | 自由流程 | 允许自由选择审批人 | +| 4 | 决策引擎 | 条件分支决策 | + +### 节点类型 +| type | 名称 | 说明 | +|------|------|------| +| start | 发起节点 | 流程发起 | +| approver | 审批节点 | 需要审批 | +| processing | 办理节点 | 任务处理 | +| subFlow | 子流程 | 调用子流程 | +| free | 自由节点 | 自由选择审批人 | +| gateway | 网关 | 条件路由 | + +### 审批人指定方式 (assigneeType) +| 值 | 名称 | 说明 | +|---|------|------| +| 1 | 发起人上级 | 发起人的 N 级上级 | +| 2 | 特定岗位 | 指定岗位审批 | +| 3 | 发起人自己 | 发起者自己审批 | +| 4 | 表单变量 | 从表单字段中选择审批人 | +| 5 | 审批节点 | 指定流程中某个节点审批人 | +| 6 | 指定成员 | 直接指定审批人 | +| 7 | 候选人 | 发起时选择审批人 | +| 9 | 数据接口 | 从接口获取审批人 | +| 10 | 逐级审批 | 按层级向上审批 | + +### 会签规则 (counterSign) +| 值 | 名称 | 说明 | +|---|------|------| +| 0 | 或签 | 一名审批人同意或拒绝即可 | +| 1 | 会签 | 无序会签,达到会签比例通过 | +| 2 | 依次审批 | 按顺序依次审批 | + +### 常用操作 +```python +# 创建简单流程 +result = client.workflow.create_simple_flow( + full_name="采购审批", + en_code="purchaseFlow", + form_id=func_id, + approver_user_ids=["user_id"], +) +version_id = result["version_id"] + +# 发起流程 +task = client.workflow.launch_task(version_id, {"f_amount": 5000}) + +# 审批 +client.workflow.approve(operator_id, "同意") + +# 拒绝 +client.workflow.reject(operator_id, "不同意") + +# 退回 +client.workflow.back(operator_id, {"targetNodeId": "node_id"}) +``` + +## 关键配置参考 + +### flowNodes 结构 +```json +{ + "global": { "formId": "", "titleType": 0 }, + "Event_0oz4pwh": { "type": "start", "formId": "" }, + "Activity_1qf73gq": { "type": "approver", "assigneeType": 6, "approvers": [] }, + "Event_0zlhfee": { "type": "end" } +} +``` + +### flowXml +BPMN 2.0 XML,简单流程需要 URL 编码。 + +### flowConfig +```json +{"visibleType": 1} +``` +- visibleType=1: 公开 +- visibleType=2: 权限设置 + +## 源码位置 + +### 前端 +| 文件 | 路径 | +|-----|------| +| 流程设计器 | `views/onlineDev/flowEngine/Form.vue` | +| 流程模板表单 | `views/onlineDev/flowEngine/DesignForm.vue` | +| 流程解析器 | `views/workFlow/components/FlowParser.vue` | +| 节点配置 | `views/workFlow/components/NodeFormParser.vue` | +| API: task | `src/api/workFlow/task.ts` | +| API: template | `src/api/workFlow/template.ts` | + +### 后端 +| 文件 | 路径 | +|-----|------| +| DefinitionController | `后端/jnpf-workflow/.../controller/DefinitionController.java` | +| TaskController | `后端/jnpf-workflow/.../controller/TaskController.java` | +| FlowUtil | `后端/jnpf-workflow-core/.../util/FlowUtil.java` | +| FlowableUtil | `后端/jnpf-workflow-core/.../util/FlowableUtil.java` | + +## 平台示例(17条) + +详见 [workflow_examples.md](../../docs/workflow_examples.md) + +| 类型 | 数量 | 示例 | +|------|------|------| +| type=0 自由审批 | 9 | leaveApply, 采购申请, 付款申请, 离职申请... | +| type=1 简单流程 | 4 | crmOrder, salesOrder, materialapply, paymentapply | +| type=2 触发器 | 4 | webhook, Timedtrigger, customeradd, messagetrigger | + +## 常见错误 + +1. **create_template 必须含 flowXml/flowNodes/flowConfig** - 否则 NPE +2. **审批需要 status 字段** - status=1 同意, status=2 拒绝 +3. **launch_task 的 isFlow 必须是整数** - 用 1 而非 True +4. **get_flow_info 参数是 version_id** - 不是 template_id +5. **审批人不能与发起人相同** - 会报系统异常 diff --git a/docs/低代码平台技术白皮书.md b/docs/低代码平台技术白皮书.md new file mode 100644 index 0000000..c2f5f7b --- /dev/null +++ b/docs/低代码平台技术白皮书.md @@ -0,0 +1,726 @@ +# JNPF快速开发平台 + +Java 单体技术白皮书(v6.2) + +$100 \%$ 源码交付 + +全新用户界面 + +前沿开源技术栈 + +拖拉拽灵活配置 + +可视化敏捷开发 + +网址:https://www.jnpfsoft.com + +客户服务电话:400-6868-969 + +# 目录 + +一 引言.. 1 + +二 整体架构. 2 + +三 平台特性. ... 3 + +3.1 构架特性. . 3 + +3.2 功能特性 ..... .. 3 + +四 技术栈 ..... 5 + +4.1 后端技术栈 .... + +4.2 前端技术栈. + +4.3 数据库支持. .8 + +4.4 开发环境.. .8 + +4.5 运行环境.. .9 + +五 核心功能模块. . 10 + +5.1 应用中心.. . 10 + +5.2 通用中心. .11 + +5.3 组织权限. ..14 + +5.4 账户体系. .15 + +5.5 表单设计. .16 + +5.6 流程设计(JnpfFlow) ........... .17 + +5.7 门户设计.. .22 + +5.8 报表设计(JnpfReport)....... ... 23 + +5.9 大屏设计. .....25 + +5.10 JnpfAI .. 26 + +5.11 打印设计(JnpfPrint) .. 30 + +5.12 国际化多语言支持. .... 31 + +5.13 第三方登录. 32 + +5.14 多租户实现方案. . 33 + +5.15 分布式任务调度. . 35 + +5.16 文件存储.. . 35 + +5.17 消息中心 .. . 35 + +六 配套方案. . 36 + +6.1 移动端 .. . 36 + +6.2 多数据源. .37 + +6.3 单点登录. .38 + +6.4 分库分表 $^ +$ 读写分离. .. 40 + +七 部署参考方案. . 41 + +7.1 All-in-One 部署方案 . . 41 + +7.2 高可用部署方案. ..42 + +八 部署方式.. . 44 + +# 一 引言 + +JNPF 快速开发平台依托 J2EE 技术体系 $'$ 基于 Spring Boot 框架精心封装而成,具备丰富的开箱即用功能,涵盖 RBAC 功能、Xss 防跨站攻击、自动生成前后端代码、兼容多种存储系统、SaaS 多租户等诸多实用模块。 + +平台能够在国产信创数据库、国产信创中间件、国产信创操作系统上顺利$\mathcal { M }$ 部署,并且包含多种通用技术组件。这些组件能让开发者将精力集中在业务功能开发上,降低技术难度,节省人力成本,缩短项目周期,有效提升开发效率。 + +技术领先:平台配备全新用户界面,极大优化产品整体用户体验。采用前后端分离技术架构,后端基于 Java 主流开发技术栈,前端运用 Vue3 全家桶+ Ant Design Vue 技术栈; + + 组件丰富:集成多个开箱即用的通用组件,如消息中心、文件服务、第三方登录等,全面满足各类开发需求; + + Saas 应用支持能力:可无缝切换至 SaaS 模式,支持企业搭建专属 SaaS 应用,灵活适应多样化业务模式; + +# 二 整体架构 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/217d39a697e517d5be75c24dbc722250a333d7a5c494fc6f045239bdac07091f.jpg) + + +JNPF 快速开发平台采用分层解耦、弹性扩展、信创兼容的架构设计理念,以支撑多样化业务场景和复杂部署环境。通过前后端分离架构实现业务逻辑与界面展示的解耦,同时适配国产信创生态,确保在全栈国产化环境中稳定运行。 + +架构设计以开发者效率提升为核心目标,通过封装通用技术组件、标准化接口协议和自动化部署流程,降低技术门槛;以系统可靠性为基础,采用分布式缓存、集群化部署和多租户隔离机制,保障高并发场景下的数据一致性和安全性;以业务灵活性为导向,支持快速集成第三方系统、自定义业务流程和动引态扩展功能模块,满足企业个性化需求。 + +# 三 平台特性 + +# 3.1 构架特性 + + 主体框架:核心技术采用 Spring Boot、MyBatis-Plus、Alibaba Druid、Hutool、Lombok等主流且成熟的技术,这些技术经过大量实践验证,确保架构稳定可靠,为平台的高效运行奠定坚实基础; + + 前后端分离:运用主流前后端分离框架设计,代码风格简洁规范,易于后端$= 1 2 1$ 开发工程师理解和上手,有效减少团队内部的沟通成本,提升开发协作效率; + + 统一接口管理:集成 Swagger/ Knife4j,可自动生成 Api 文档,方便接口的管理、测试和维护,提高开发效率; + + 数据库兼容:不仅支持 MySQL、SQLServer、Oracle、PostgreSQL 等主流数据库,还兼容达梦 (DM8)、人大金仓等国产信创数据库,全方位满足不同企业的数据存储需求,适应国产化发展趋势; + + 国产信创中间件适配:兼容东方通(TongWeb、TongRDS、 + +TongHttpServer)等国产信创中间件,适应国产信创环境的部署要求; + + 国产信创操作系统适配:可在麒麟服务器操作系统、统信 UOS、华为欧拉等国产服务器操作系统上顺利部署运行,完全符合国产化发展要求,为企业提供安全可靠的运行环境; + +# 3.2 功能特性 + + 灵活的权限控制:基于 RBAC 权限管理模式,该功能模块专门用于维护企业组织架构信息及员工信息,主要涵盖组织架构管理、部门管理、分级管理 + +员、角色管理、岗位管理等功能。用户可在此便捷地维护公司组织架构信息(组织 / 部门 / 角色 / 岗位)和用户信息,也能通过第三方应用(钉钉 / 企业微信)将组织架构信息一键导入系统,还可借助组织架构和员工信息导入功能实现数据的快速导入,满足企业复杂且多样化的权限管理需求; + + 第三方登录:提供开箱即用的第三方授权登录工具类库,具备统一的接口标准,支持接入任意 OAuth 网站,能够快速实现 OAuth 登录功能,简化用户登录流程,优化用户登录体验; + +单点登录:集成 OAuth 2.x、CAS,平台支持 OAuth 2.x、CAS、OpenIDConnect、SAML 2.0、JWT、SCIM 等多种标准协议,提供安全、标准、开放的用户身份管理 (IDM)、身份认证 (AM)、单点登录 (SSO) 等功能,在保障登录安全的同时,为用户带来便捷的登录体验; + + 多租户:借助 MyBatis-Plus 实现 SaaS 多租户隔离方案,通过数据隔离、权限隔离等方式,满足多租户场景下的数据隔离需求,确保不同租户之间的数据安全; + +# 四 技术栈 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/8a0ed4019659dcd559503fb355508987b1ebaef0b7809074348eed5146b5d2d6.jpg) + + +# 4.1 后端技术栈 + + 编辑语言:支持 Java8/11、Java17/21,适配不同版本的开发需求; + + 开发框架:采用 Spring Boot 2.7 / Spring Boot 3.5,提供高效的开发环境和丰富的功能支持; + + 持久层框架:使用 MyBatis-Plus,在 MyBatis 的基础上进行了增强,提供了更多便捷的操作方法,简化数据库操作; + +数据库连接池:采用 Alibaba Druid,具有高效的连接池管理能力,能够有效提升数据库访问性能,同时提供了丰富的监控功能; + +多数据源支持:通过 Dynamic-Datasource 实现多数据源的灵活管理和切换,满足复杂业务场景下对多数据源的需求; + + 数据库兼容:兼容 MySQL、SQLServer、Oracle、PostgreSQL、达梦数据库、人大金仓数据库等多种数据库类型,适应不同的企业数据环境; + + 分库分表解决方案:集成 Apache ShardingSphere,为大规模数据存储和访问提供有效的分库分表解决方案,提高系统的扩展性和性能; + + 权限认证框架:采用 Sa-Token+JWT,提供安全可靠的权限认证和授权功能,保障系统的安全访问; + + 代码生成器:使用 MyBatis-Plus-Generator,能够自动生成前后端代码,提高开发效率; + + 流程引擎:集成 Flowable 6.7,实现复杂的业务流程管理,满足企业的流程自动化需求; + + 模板引擎:采用 Velocity,方便进行模板渲染; + +$\angle$ 任务调度工具:使用 XXL-JOB,实现分布式任务调度,满足定时任务、批量处理等业务需求; + + 分布式锁组件:采用 Lock4j,解决分布式系统中的并发问题,确保数据的一致性; + + JSON 序列化工具:使用 Jackson&Fastjson,实现 JSON 数据的序列化和反序列化,方便数据传输和处理; + + 缓存数据库:使用 Redis,提高数据访问速度,减轻数据库压力; + + 校验框架:采用 Validation,实现数据的校验功能,确保输入数据的合法性; + + 分布式文件存储:兼容 MinIO 及多个云对象存储(阿里云 OSS、华为云OBS、七牛云 Kodo、腾讯云 COS 等),提供灵活的文件存储方案; + + 工具类框架:集成 Hutool、Lombok 等工具类框架,简化开发过程中的常用操作; + + Api 文档生成工具:使用 Knife4j,生成美观、实用的 Api 文档,方便接口 + +的管理和调用; + + 项目构建:采用 Maven,实现项目的依赖管理和构建自动化; + +# 4.2 前端技术栈 + + Vue3.0 全家桶:包括 Vue3、Vue Router、Vuex 等核心部分,为前端开发提供了完整的解决方案; + + Vben5:基于 Vue3 和 TypeScript 的企业级 UI 框架,拥有丰富组件库与完善设计规范; + +TypeScript:增强了 JavaScript 的类型检查,提高代码的可维护性和稳定性; + + Vite:作为前端构建工具,具有快速的热更新和构建速度,提升开发效率; + + Pinia:用于前端状态管理,替代传统的 Vuex,使用更加简洁、直观; + + Pnpm:作为包管理工具,具有高效的依赖管理能力,节省磁盘空间; + + Ant Design Vue 4.2:提供了丰富的 UI 组件,简化前端界面开发; + + Scss:作为 CSS 预处理器,增强了 CSS 的功能,提高样式开发效率; + + bpmn-js:用于流程建模和可视化,实现业务流程的图形化设计 + + UniverJS:报表编辑器 + + Dayjs:轻量级日期处理库 + + Fullcalendar:日历组件 + +monaco-editor:浏览器端代码编辑器,为开发者提供高效便捷的代码编辑环境; + +Sortablejs:可通过拖拽轻松调整元素顺序,提升操作体验,且支持多列拖拽排序,满足复杂布局需求; + + Tinymc:经典富文本编辑器 + + vue-i18n:实现前端的国际化支持,方便系统在不同语言环境下使用 + + vue-plugin-hiprint:用于前端打印模板设计和打印功能实现,满足各种打印需求 + +# 4.3 数据库支持 + + MySQL 5.7.x/8.x:广泛使用的开源关系型数据库,性能稳定,社区活跃 + +SQLServer 2012+:微软推出的关系型数据库,具有强大的功能和良好的兼容性 + + Oracle 11g:功能强大的商业关系型数据库,适用于大型企业级应用 + +PostgreSQL $^ { 1 2 + }$ :开源的关系型数据库,支持丰富的数据类型和先进的特性 + + 达梦数据库(DM8):国产优秀的关系型数据库,满足国产化信创需求 + + 人大金仓数据库(KingbaseES_V8R6):国产数据库,具有较高的安全性和可靠性 + +# 4.4 开发环境 + +
版本或建议
硬件开发电脑建议使用I3及以上CPU,16G及以上内存
操作系统Windows 10/11, MacOS
JDK默认使用JDK 21,兼容JDK 8/11、JDK17(需调整部分代码),推荐使用OpenJDK,如Liberica JDK、Eclipse Temurin、Alibaba Dragonwell、BiSheng等发行版;
Maven依赖管理工具,推荐使用3.6.3及以上版本
Redis数据缓存,推荐使用5.0及以上版本
数据库兼容MySQL 5.7.x/8.x、SQLServer 2012+、Oracle 11g、PostgreSQL 12+、达梦数据库(DM8)、人大金仓数据库(KingbaseES_V8R6);
IDE代码集成开发环境,推荐使用IDEA2024及以上版本,兼容 Eclipse、Spring Tool Suite等IDE工具
前端开发Node.js v20.15.0(某些情况下可能需要安装Python3)及以上版本;pnpm v9.12及以上版本;浏览器推荐使用Chrome最新版本;Visual Studio Code(简称VSCode);
移动端开发Node.js v20.15.0(某些情况下可能需要安装Python3)及以上版本;HBuilder X(最新版);
文件存储默认使用本地存储,兼容MinIO及多个云对象存储,如阿里云OSS、华为云OBS、七牛云Kodo、腾讯云COS等;
+ +# 4.5 运行环境 + +
版本或建议
服务器配置建议至少在 4C/16G/50G 的机器配置下运行;
操作系统建议使用 Windows Server 2019 及以上版本或主流 Linux 发行版本,推荐使
用 Linux 环境;适配信创服务器操作系统(麒麟、统信 UOS、OpenEuler);
JRE默认使用 JRE 21,兼容 JRE 8/11、JRE17(需调整部分代码),推荐使用 OpenJDK_jre,如 Eclipse Temurin、Alibaba Dragonwell、BiSheng 等发行版;
Redis数据缓存,推荐使用 5.0 及以上版本
数据库兼容 MySQL 5.7.x/8.x、SQLServer 2012+、Oracle 11g、PostgreSQL 12+、达梦数据库(DM8)、人大金仓数据库(KingbaseES_V8R6);
中间件(兼容)东方通 Tong-web、金蝶天燕-应用服务器 AAS v10;
文件存储默认使用本地存储,兼容 MinIO 及多个云对象存储,如阿里云 OSS、华为云 OBS、七牛云 Kodo、腾讯云 COS 等;
前端服务器Nginx 建议使用 1.18.0 及以上版本、OpenResty 或 TongHttpServer 6.0(国产信创)
+ +# 五 核心功能模块 + +# 5.1 应用中心 + +JNPF 6.x 系列的应用板块全新升级,由原来的应用分类升级为多应用隔离模式。每个应用都是独立的一套功能系统,支持应用的后台独立设计,包括:表单设计、流程设计、门户设计、报表设计、大屏设计及应用开发授权等功 + +能。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/b4311f0db34e4c388d863c3cb8b60d9ebd5c0044d39bb3043d4e4bc7c52184ed.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/1a358ace48e64d8e9dbeade3ef045ddb828acdf82415dc4e532a874cf59cd60c.jpg) + + +# 5.2 通用中心 + +通用中心作为平台的基础资源集中管控模块,集成公有变量、系统变量、系统函数三类核心资源,解决了传统开发中资源分散、查找繁琐的问题,帮助 + +用户提升开发与管理效率。 + +支持集中管理变量、函数 + +支持系统资源内置化 + + 支持自定义配置公有变量 + +支持多场景调用 + + +公有变量:可自定义、全平台调用 + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/7890c1a2016d5e02cd4790ef890c95f90930b2bfa97047a30b81d594b0dc504a.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/a4600be2ef6aaab31cba449ec8ac2737cfb2cc80468428f4b8f880c9d167fd2a.jpg) + + + +系统变量:平台内置,开箱即用 + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/175b44f774c885286224c200491c772359607d3361c0cde4ad0dd92d97bd521f.jpg) + + + +系统函数:数学函数库,支持复杂运算 + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/54c6cf5122d33e1e26e8073b0cf85277d9331f4511e709a99d62c0977c4da10a.jpg) + + +# 5.3 组织权限 + +JNPF 6.x 系列的组织权限逻辑全新升级,分为组织权限和角色权限两条权限体系来解决权限资源的划分问题。组织权限采用权限继承及隔离体系,而角色权限基于 RBAC 升级改造具有RBAC严谨性又增加灵活性。 + +支持权限的继承 + +支持权限的互斥、先决 + +支持权限的基数控制 + + 支持预置权限 + +支持权限的二次分配 + +支持职务与职责的权限划分 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/8dd0b85acf838a35a653ed17a7108520efaebbcb31e87310d854f7e3f2883522.jpg) + + +# 5.4 账户体系 + +为提供更流畅、便捷的用户体验。Jnpf 的账户体系重于账号管理和用户交$\scriptscriptstyle \bigcirc \wedge \bigcirc$ 互功能。账户架构核心在于:确保每位注册成员拥有独一无二的身份标识,使终端用户顺畅参与生态系统。 + +支持多种登录方式 + + 支持第三方社交账号登录 + + 支持单点登录 + + 支持APP扫码登录 + + 支持账号登录策略设置 + +支持账号审计日志 + +# 5.5 表单设计 + +配备大量可复用控件,通过操作界面元素,拖拽控件自动生成可视化应用;基于 Mybatis-plus-generator 自定义了一套代码生成器, 通过配置数据库entity、mapperxml、service)等代码,极大减少开发难度。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/b09b423208beddbed1c26611d39c38794fc48af1e284960ade88d256cc673302.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/ce96b5ba682f00324af66f5ef4db3b9bfe748569633b1e8b03b9471e0b3a54d2.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/0e5ec08160cc691d48a55d76b2eb672b6c963b86670fd95afef7cc148c4f7859.jpg) + + +# 5.6 流程设计(JnpfFlow) + +遵循 BPMN 行业标准不仅为流程相关人员提供一种通用、直观、易懂的方法来描述、理解和沟通流程设计,也减少流程设计、执行、管理阶段之间的交流偏差,同时通过标准 BPMN 设计模式,可以支持各种复杂的流程场景,为后续的流程设计扩展奠定基础,而且它还是市场日趋对标准化流程的需求。 + +BPMN 作为标准规范,定义了各行各业的业务流程,涉及范围十分广泛。JnpfFlow 所涉及的流程设计核心是工作流,作为日常办公审批使用时,也称为审批流。不过 BPMN 标准内容的十分之一还不到。因此JnpfFlow在BPMN标准上去除了与工作流无关的图形和定义,在此基础上针对国人的操作习惯设计一套符合中国特色的BPMN标准工作流设计器。 + +在技术上,流程引擎选择上,采用 Flowable 6.7,可视化设计底层采用bpmn-js,两者都是基于 BPMN 标准规范制定的Java开发包和Js插件库。 + +综上述,基于 BPMN 标准规范,由 Flowable 和 bpmn-js 作为技术落地,结合审批流业务场景,JnpfFlow 为流程设计提供了一套符合国内特色的审批流程设计器,其可涵盖 90%以上的审批流业务场景。其主要涵盖以下内容: + +# 5.6.1 简单流程 + +简单流程保留原工作流的瀑布流设计模式和操作习惯,流程流转的引擎从原来的自研引擎转为Flowable 引擎,遵循BPMN标准规范。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/575a9ca98fd171cc672de58b2fc9c5fe11ee4ab9aec47c803b5c86a41cc723ed.jpg) + + +# 5.6.2 标准流程 + +标准流程是以流程图设计方式的流程设计器,支持以拖拽形式编排流程,流程流转引擎同样是基于flowable引擎。 + +标准流程是以 BPMN 流程设计为底层支持,因此不仅涵盖了简单流程的所有业务场景,也可设计比较简单流程更为复杂的业务场景。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/049386aaea35dd4e9ea70f38083f601de78eaa624530223975c048b1d8fe41e6.jpg) + + +# 5.6.3 任务流程 + +可以设计并实现多样、复杂的自动化工作流。通过定义触发节点、执行节点,使得业务活动在触发后能够自动、有序执行,从而实现高效、可控的自动化工作流。 + +任务流程在集成助手基础上全新升级,基于BPMBN流程引擎为底座,打造可视化的业务逻辑编排流程,具备以下优势: + +● 省时提效:自动化处理重复性任务,在提高效率的同时减少人为错误; + +● 轻松构建工作流:通过添加、配置节点,就能快速建立所需工作流; + +● 可视化的任务流设计:采用 BPMN 的引擎设计,自上而下或自左向后自由切换排版,展示工作流中任务的编排和执行规则; + +● 错误追踪与重试:可查看每个节点的执行记录,便于快速定位、解决问题,并支持手动重试; + +● 丰富触发事件和执行动作:除增删改事件外,还支持流程事件触发,并可多选触发动作,节省系统资源; + +● 强大的数据处理能力:自动化的数据处理,打破表单间的数据壁垒,实现数据的自动更新与维护。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/5657ff7ae7790a11042fdc0be5210cb93bdce15beb49d59bd1d3cedeb74e42af.jpg) + + +# 5.6.4 自由流程 + +打破传统固定审批链路的局限,构建灵活可控的审批流转模式。以 “开始-自由节点-结束” 三大固定核心节点为基础,支持在自由节点新增触发节点及无条件连线,审批人可自主选择下一审批节点及责任人,同时提供审批自结与流转次数限制两种结束规则,适配企业非固定链路的灵活审批场景。 + +● 流转自主可控:审批人自主指定下一审批节点及责任人,适配多变业务需求; + +● 节点配置灵活:固定核心节点保障基础架构,自由节点支持拓展触发节点; + +● 异常精准管控:全局异常仅超管及指定人员处理,触发节点同步显示状态提示; + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/52fff833f449db2ffc3d8646130d1b3b1cb5890a23f1700b437e126811fb8d27.jpg) + + +# 5.6.5 决策流程 + +决策流是一种基于规则与条件自动执行逻辑判断与路径选择的数字化流程模型。它将依赖人工经验的复杂业务规则,转化为由预定义规则和结构化节点自动执行的流程图,实现判断过程的智能化与自动化。 + +支持漏斗型决策和覆盖型决策 + +支持自定义入参与出参 + +支持条件分支 + +支持规则集 + +支持赋值节点 + +支持多元计算 + +支持简单评分卡 + +支持交叉决策表 + +支持异常配置 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/4416a5c9ecd4d248583111b3c32b06c14936207385cad7ae46622c8221d3b7c0.jpg) + + +# 5.7 门户设计 + +门户界面是装载信息与工作内容的容器,将所有的信息从各个功能包括其他异构系统中抽取出来,进行分门别类的推送。实现内外系统统一信息平台,提升工作效率。 + +● 可定制性:门户控件可以根据用户需求进行定制,包括布局、样式、功能等; + +● 可重用性:一个门户可以被多个应用共享,提高了代码的重用性和维护性; + +● 可控制性:灵活的权限控制,满足不同业务门户,实现专属门户; + +● 可适配性:支持 PC 端和 APP 端快速切换和集中展示,实时展示数据,实现高效信息获取; + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/a9accc916e876b7c9ffbe1ab50791e2dc7461b3f6e09ccf45064908367523821.jpg) + + +# 5.8 报表设计(JnpfReport) + +JnpfReport是基于Univer电子表格功能,并在其之上扩展Jnpf自身的报表能力 。 + +Univer 提供了一个全面的企业级文档与数据协同的解决方案,支持电子表格、文本文档和演示幻灯片三大核心文档类型。通过灵活的 API 和插件机制,开发者可以在 Univer 的基础上进行个性化功能的定制和扩展,以适应不同用户在不同场景下的特定需求。 + +● 打破信息孤岛:通过数据接口连接各种信息系统,实现数据实时变化, + +从而提高整个企业的数据价值; + +● 自动化生成报表:减少人工输入和处理的错误,提高过效率,节省统计时间和人力成本; + +● 灵活性与自定义:用户可以根据自己的需求定制不同类型的报表(如数据、图表等),用户可以快速、高效地完成报表设计和生成,满足企业的个性化需求,为企业降低开发成本和时间投入; + +● 中国样式报表:类似 Excel 的用户界面和操作体验,使用户能够无缝地创建和编辑报表,提升了使用的便捷性和熟悉感; + +● 数据可视化呈现:将数据以图表的形式可视化呈现。帮助用户更好传达信息,对数据进行细化分析,帮助企业从多个角度对业务数据进行深入分析,企业可以更清晰了解业务状况,做出更明确的决策; + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/d6e6e5c3a611f8fe96083cdbe83869a01088f3f97eeb323d463eee078ffe13d5.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/32ed5480cb98fcdd4e8944ccede35ec001c6e15d976f1b0252b7b5b4174ac46f.jpg) + + +# 5.9 大屏设计 + +自由布局页面,拖拽控件至页面中,针对不同的控件进行内容设值和数据绑定,所见即所得的实现大屏可视化页面开发。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/eb014fcf1fdcc8e5fe7b8b12a5722226fc4f5c979c05d4120fcc14884728086e.jpg) + + +# 5.10 JnpfAI + +在 Jnpf 产品的开发与升级过程中,我们致⼒于将先进的 AI 技术融⼊到产品中, 以提升其功能和⽤户体验 。具体来说,我们通过结合强⼤的 AI⼤模型技术,为⽤户提供了—系列创新性的功能和服务,包括但不限于: + +# 5.10.1 AI 快速建表 + +利⽤AI 技术,⽤户可以更加快速地创建数据库表格。只需输⼊少量的信息或描述所需的数据结构,AI就能够⾃动⽣成符合需求的表单,极⼤地简化了表单创建流程。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/9f98e7180789bd1d01c457d9cda3ad7e6b70efff3e40b8ea79aecf7e8676476f.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/c365b746918140f9ee2fd346074271d4bf1af4a622ff134fe5175ccb0e19a7ae.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/e029cf4f69344d0a3378932258609bfcda179a3348b944859a72279565abb47b.jpg) + + +# 5.10.2 AI 推荐字段 + +当⽤户正在设计表单时,可以通过输⼊想要追加的字段信息让AI为你推荐满⾜需求的字段。这不仅帮助⾮专业⼈⼠更容易上⼿操作,同时也保证了表单设计的专业性和合理性。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/22776fa13e032c063e7c824cc6c9181c090aae9cda17feb1ca3426a980652b19.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/d686056279facf4f244376698ec5a34f80595570e2bcb94e39a71092a25520cd.jpg) + + +# 5.10.3 AI 创建流程 + +借助 AI 大模型的语义理解与流程建模能力,用户可通过自然语言描述业务场景,AI 将自动解析需求并生成符合逻辑的标准化流程,大幅缩短流程设计周期。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/6335154214e4bad49e1eb2d255cecd87b4663ca7bfb9a9cce1df47d1ae178463.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/1bb7e9bf5059fe09636e417349f569ff0bcd9d8528ecaf988c00cec495ba541c.jpg) + + +# 5.10.4 AI 咨询助手 + +⽀持集成多款国产 AI⼤模型,如 Deepseek 、通义千问 、⽂⾔—⼼ 、智谱 AI 等的智能助⼿,能够解答⽤户关于产品使⽤、技术⽀持等⽅⾯的问题。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/77d5b1707a3b6ac8cb0cf15e681f896437cb756e5abf95f320be06def0953c7d.jpg) + + +# 5.10.5 配置 AI 模型 + +提供灵活的 AI 模型管理与配置能力,支持用户导入、启用、切换多种 AI大模型,并针对不同业务场景绑定专属模型。 + +# 5.11 打印设计(JnpfPrint) + +支持可视化拖拽操作、套打等,支持数据集配置,提供常用组件、业务套件,符合个性化打印页面设计需求。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/8d2b33b415d7f79162f29de863387c60da23a497b22263bce0a881445f4b736f.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/ddc8df516e539a3d5c21c69d46425d23c300ce5372d7d0eb665d8c3ca559790b.jpg) + + +# 5.12 国际化多语言支持 + +允许用户在线设计自己的多语言。 + +支持自定义语言 + +支持自定义标记 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/30898cf4d473022ea066d7b8362457dd01a947a432e8504655ac07423897b823.jpg) + + +# 5.13 第三方登录 + +开箱即用的第三方授权登录工具类库,提供统一接口,支持接入任意OAuth网站,快速实现OAuth登录功能。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/d886582be28288babde8ed7eb1327caf4660d77e242bf2068fd8a7769566929a.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/600635892cd64753c35c3065d402899787e1a76b5457a4fb308292b10b659ca8.jpg) + + +# 5.14 多租户实现方案 + +多租户技术或称多重租赁技术,是一种软件架构技术,它是在探讨与实现如何于多用户的环境下共用相同的系统或程序组件,并且扔可确保各用户间数据的隔离性。在云计算时代,多租户技术在共用的数据中心以单一系统架构与服务提供多数客户端相同甚至可定制化的服务,并且仍然可以保障客户的数据隔离。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/92294b08108a5e3c2bf3722868d612a420a60b50244e5e84076dea7c5c1be907.jpg) + + +提供了三种多租户实现方式,满足不同维度用户的维护,不同维度数据的治理: + +# 5.14.1 独立数据库 + +数据库隔离模式,每个租户一个数据库,这种方案的用户数据隔离级别最高,安全性最好,但成本也高。 + +# 5.14.2 共享数据库,隔离数据架构 + +SCHEMA隔离模式,多个租户共享一个数据库,但一个租户独立使用一个SCHEMA。 + +# 5.14.3 共享数据库,共享数据结构 + +字段隔离模式,租户共享同一个数据库,同一个SCHEMA,但在表中通过 + +F_TenantId 区分租户的数据。 + +# 5.15 分布式任务调度 + +集成 XXL-JOB 跨语言分布式任务调度平台,开箱即用,第三方任意语言通过 RESTful API 对接调度中心或实现执行器,功能点包含执行器管理、调度任务、调度日志、任务进度监控、多任务模式、自定义任务参数等。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/dcdac77ff9227c0bfcc0543d9b374f931a9fbe19f155ffa8fdaa11c7fd475e4c.jpg) + + +# 5.16 文件存储 + +集成多个开箱即用的文件存储方案,兼容MinIO及多个云对象存储,如阿里云 OSS、华为云 OBS、七牛云 Kodo、腾讯云 COS等。 + +# 5.17 消息中心 + +提供了多种类型消息配置及发送的能力,提供消息发送的通用API,用户可通过此功能模块轻松实现多种类型消息的发送,无缝对接多种消息平台。功能点包含消息模板配置、消息发送配置、消息接收配置、账户配置(包含邮箱、短信、微信公众号、Webhook)、消息监控等。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/c41b42607d016f4f55d642e9c70d097802d5f6305457cb93dea3ed0814d5479b.jpg) + + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/8d361e2fe33171afb733cc233db17a08fef8eefe0586748c3a545be738bc0caa.jpg) + + +# 六 配套方案 + +# 6.1 移动端 + +基于 uni-app 跨平台应用开发框架,开发者编写一套代码,可同时构建发 + +布到 H5、微信小程序、iOS、Android、鸿蒙 Next(HarmonyOS) 等多个平台的应用,大大提高开发效率和降低维护成本。 + +# 6.2 多数据源 + +通过整合 dynamic-datasource-spring-boot-starter 为框架提供动态数据源、主从分离、读写分离能力。 + + 支持 数据源分组 ,适用于多种场景 纯粹多库 读写分离 一主多从 混合模式; + + 支持数据库敏感配置信息 加密(可自定义) ENC(); + +支持每个数据库独立初始化表结构 schema 和数据库 database; + +支持无数据源启动,支持懒加载数据源(需要的时候再创建连接); + + 支持 自定义注解 ,需继承 DS(3.2.0+); + + 提供并简化对 Druid,HikariCp,BeeCp,Dbcp2 的快速集成; + + 提供对 Mybatis-Plus,Quartz,ShardingJdbc,P6sy,Jndi 等组件的集成方案; + + 提供 自定义数据源来源 方案(如全从数据库加载); + + 提供项目启动后 动态增加移除数据源方案; + + 提供 Mybatis 环境下的 纯读写分离方案; + + 提供使用 spel 动态参数 解析数据源方案。内置 spel,session,header,支持自定义; + +支持 多层数据源嵌套切换 。(ServiceA >>> ServiceB >>> ServiceC); + +提供 基于 seata 的分布式事务方案 ; + +提供 本地多数据源事务方案; + +# 6.3 单点登录 + +支持 OAuth 2.x/OpenID Connect、SAML 2.0、JWT、CAS、SCIM 等标准协议,提供安全、标准和开放的用户身份管理(IDM)、身份认证(AM)、单点登录(SSO)、RBAC权限管理和资源管理等。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/aaf35a936682a84c632fee4b5a62e4a2c0aa983f77ca33d2283da172484c0191.jpg) + + +# 6.3.1 认证登录界面 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/37bdb6a7f2856202c2690d99daf84d2c6112d7139719bcaeb999c9478e57b83c.jpg) + + +# 6.3.2 认证主界面 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/73bf58b3858c3a52c657ffda51e8390147e2fc0202e92de0d263b0240060056c.jpg) + + +# 6.3.3 管理后台界面 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/ed374841d0c192ca8aa9e684d32a2060ac8021932e7bffb30fd0b2fd9a5a1c97.jpg) + + +# 6.4 分库分表 $+$ 读写分离 + +集成 sharding-jdbc,兼容任何基于 JDBC 的 ORM 框架,提供标准化的数据分片、读写分离、柔性事务和数据治理功能,支持垂直分库、垂直分表、水平分库、水平分表、读写分离、分布式事务和高可用等相关功能,可适用于如Java 同构、异构语言、容器、云原生等各种多样化的应用场景。 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/45b20385e1084378feba7f263905ea48eb4267fc685f92551c2f48129b5ac138.jpg) + + +# 七 部署参考方案 + +# 7.1 All-in-One 部署方案 + +前、后端部署在同一台服务器,适用于体验或演示环境 + +# 7.1.1 部署架构参考 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/ccef6f8d306ef5559d1481654208a8d0e77a999728be1d81f459f51e244765df.jpg) + + +# 7.1.2 服务器配置参考 + +
操作系统vCPU内存硬盘备注
openEuler-24.03-LTS-x86_644c16G50G最小配置需求,兼容统信UOS,OpenEuler,麒麟服务器版等国产信创环境
+ +# 7.1.3 组件/应用 + +
组件/应用版本备注
JREJRE 21默认使用 JRE 21,兼容 JRE 8/11、JRE17(需调整部分代码);推荐使用 OpenJDK,如 Liberica JDK、Eclipse Temurin、Alibaba Dragonwell、BiSheng 等发行版;
Redis5.0.x+数据缓存
MySQL8.0数据库
Nginx1.18.0+前端 Web 服务器
+ +# 7.2 高可用部署方案 + +适用于生产环境 + +# 7.2.1 部署架构参考 + +![image](https://cdn-mineru.openxlab.org.cn/result/2026-03-27/e4436726-82f5-4bea-8a80-f9dd952a8637/e7fdeb1cbecd728a3d3991dfc582930ae157be0e7268d625607fc00d1eb1543a.jpg) + + +# 7.2.2 配置参考 + + 本表数据仅为参考配置,需要根据实际业务场景调整; + + 一般一个应用占用 1c/1-3G; + + 高可用一个应用至少2个节点; + + 使用云服务器时,负载均衡可选择阿里云负载均衡SLB、腾讯云负载均衡CLB 或华为云弹性负载均衡ELB等方案; + + 数据库连接的问题:RDS 服务并发连接数应该600个以上; + +图片文件加载的问题:建议使用对象存储,如阿里云 OSS、华为云 OBS、七牛云 Kodo、腾讯云 COS等对象存储提供商; + + 关于配置冗余:一般考虑10%-20%的冗余; + +
操作系统用途组件/应用参考配置备注
openEuler-24.03-LTS-x86_64前端服务器Nginx(1.18.0+)2c/4G/40G+100G部署前端应用(主)
前端服务器Nginx(1.18.0+)2c/4G/40G+100G部署前端应用(备)
缓存集群服务器RedisCluster(5.0.x+)2c/8G/40G+100GRedis三主三从集群, SSD存储
数据库服务器MySQL 8.04c/16G/40G+300G主节点(master), SSD存储
数据库服务器MySQL 8.04c/16G/40G+300G从节点(Slave), SSD存储
应用服务器JRE 214c/16G/40G+100G部署后端主项目应用
应用服务器JRE 214c/16G/40G+100G部署后端主项目应用
应用服务器JRE 214c/16G/40G+100G部署后端主项目应用
应用服务器JRE 214c/16G/40G+100G部署 Flowable 服务端
应用服务器JRE 214c/16G/40G+100G部署报表服务端
应用服务器JRE 8/11/174c/16G/40G+200G部署任务调度服务端
文件存储MinIO2c/8G/40G+100GSSD 存储,也可以使用对象存储,如阿里云 OSS、华为云 OBS、七牛云Kodo、腾讯云COS等。
+ +# 八 部署方式 + +支持高可用集群、Docker 部署,满足不同规模企业的部署要求。 \ No newline at end of file diff --git a/docs/尚数网Harneess Engineering 培训.pptx b/docs/尚数网Harneess Engineering 培训.pptx new file mode 100644 index 0000000..778cb42 Binary files /dev/null and b/docs/尚数网Harneess Engineering 培训.pptx differ diff --git a/docs/开发流程.txt b/docs/开发流程.txt new file mode 100644 index 0000000..4ae05c3 --- /dev/null +++ b/docs/开发流程.txt @@ -0,0 +1,68 @@ +============= +阶段1:初始化环境 +============= +system_title = {} +app_code=dr +user=admin +password=123456 +doc_path=/Users/xs/desktop/ruoyi/数睿通 +/ssw-init-app + +============ +阶段2:设计 +============= +请完整分析{doc_path}文档、源码、数据库,通过aibridge使用jnpf来开发实现,应用系统名为 {system_title}app_code:{app_code} +请输出详细设计方案.md(包括基本框架、角色权限设计、模型设计[不要建表脚本])、组件选择、流程设计、功能表单/扩展代码、ui设计)等 ,注意jnpf已有能力,如用户、权限、流程、表单、可视化、报表、文件预览、xxl-job等使用jnpf 平台的。 +所有关联字段,在设计上优先考虑关联表单控件 +同时根据测试驱动开发原则,输出测试用例.md +过程文档统一输出到 docs/{app_code}/** + +注意项目数据库、表单、编码、类名、属性名 api地址 页面路径严格按照 jnpf平台+aibridge 规则 + +扩展功能,尽量不用di,应该用jnpf平台提供的代码生成器,把功能表单生成后端代码,在后端代码的基础上进行修改 + +可以通过代码生成后扩展代码来完成较复杂的功能,扩展代码放在包 boot/{company_code}-{app_code} +注意统一配置文件为aibridge/config.py 不要乱找 +jnpf有动态处理路由,pc端,views目录直接可以用 {company_code}/{app_code}/** 就可以访问 如 扩展页面 ssw/{app_code}/xxxx +移动端也可以用动态路由,pages目录下 按照 {company_code}/{app_code}/** 保存及访问 +先设计。 +过程比较长,制定计划文档跟踪,避免遗漏和token超了。 + +============ +阶段3:评审 +============= + +分出几个agent站在系统架构、项目管理、UI、程序设计、质量、测试、用户的角色上,开始虚拟评审。 +主要针对于对{doc_path}项目的源码、文档、数据库等读取,结合jnpf平台开发模式,对详细设计文档 测试用例 评审 +逐个文档、逐条内容再检查一遍覆盖情况,功能不要有遗漏 +评审发现问题完善到设计文档上。 + +============ +阶段4:执行 +============= +开始执行 +如果mvn找不到尝试PATH="$HOME/maven/bin:$PATH" 加入全局路径 +配置文件为aibridge/config.py 按配置文件调用aibridge 相关api来迁移 +执行过程要结合平台数据,逐条测试 +尽量不要使用DI,应该用jnpf平台提供的代码生成器,把功能表单生成后端代码,在后端代码的基础上进行修改 (注意导出代码不符合命名规范,要检查,可用visual_code fix_class_names 统一处理 ) + +==================================== +阶段5:测试 +======================================= +根据 docs/{app_code}/测试用例.md 文档 开始测试、验证每一个功能。 jnpf是人工配置为主,一定要用模拟浏览器来验证,而不仅仅是api方式 +aibridge/test已有playwright环境,避免重复安装依赖包。配置信息从aibridge/config.py读取 +测试发现的问题请直接修复,修复后要验证 + +==================================== +阶段6:总结 +======================================= +请将迁移总结写到 docs/{app_code}/总结.md 文档中 +包括存在问题/下一步计划、设计方案修改建议、测试用例修改建议,jnpf平台修改建议、aibridge修改建议等 + +==================================== +阶段7:迭代 +======================================= +根据总结文档、实际体验,进行阶段2开始迭代 + + "http://127.0.0.1:30000/v3/api-docs" | + diff --git a/examples/.DS_Store b/examples/.DS_Store new file mode 100644 index 0000000..9f072a6 Binary files /dev/null and b/examples/.DS_Store differ diff --git a/examples/.omc/state/last-tool-error.json b/examples/.omc/state/last-tool-error.json new file mode 100644 index 0000000..2f042af --- /dev/null +++ b/examples/.omc/state/last-tool-error.json @@ -0,0 +1,7 @@ +{ + "tool_name": "Bash", + "tool_input_preview": "{\"command\":\"cd /Users/xs/Desktop/6.2 && bash ./aibridge/examples/run-codegen.sh 808986025610185477 Project \\\"项目管理测试\\\" 2>&1\",\"timeout\":60000,\"description\":\"Run codegen\"}", + "error": "Exit code 1\n [\u001b[1;33mINFO\u001b[0m] 参数模式: func_id=808986025610185477, module_name=Project\n\n============================================================\n 代码生成 + 类名修复 + 菜单挂载\n============================================================\n [\u001b[1;33mINFO\u001b[0m] func_id=808986025610185477, module_name=Project, menu_title=项目管理测试\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.13/site-packages/requests/models.py\", line 971, in json\n return complexjson.loads(self.text, **kwargs)\n ...", + "timestamp": "2026-04-01T09:00:09.905Z", + "retry_count": 1 +} \ No newline at end of file diff --git a/examples/deploy_all.py b/examples/deploy_all.py new file mode 100644 index 0000000..f67b151 --- /dev/null +++ b/examples/deploy_all.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +"""Cube Studio 一键部署脚本 + +创建一级目录 + 21个功能表单(创建+发布)+ 功能菜单直接挂到一级目录下。 +""" + +import sys +import os +sys.path.insert(0, os.environ.get("ccWorkDir", "/Users/xs/Desktop/6.2")) + +from aibridge import JNPFClient, JNPFConfig +from aibridge.builders.full_config import build_full_config, build_create_payload +from aibridge.models import FieldDef + + +def login_client(): + config = JNPFConfig() + client = JNPFClient.from_config(config) + client.login() + return client, config + + +# ============================================================ +# 一级目录 +# ============================================================ +FIRST_LEVEL_DIRS = [ + {"name": "项目中心", "en_code": "ais_dir_project_center", "sort": 1}, + {"name": "镜像管理", "en_code": "ais_dir_image_mgmt", "sort": 2}, + {"name": "训练中心", "en_code": "ais_dir_train_center", "sort": 3}, + {"name": "模型管理", "en_code": "ais_dir_model_mgmt", "sort": 4}, + {"name": "数据中心", "en_code": "ais_dir_data_center", "sort": 5}, + {"name": "开发环境", "en_code": "ais_dir_dev_env", "sort": 6}, + {"name": "自动化", "en_code": "ais_dir_auto", "sort": 7}, + {"name": "监控中心", "en_code": "ais_dir_monitor", "sort": 8}, + {"name": "扩展功能", "en_code": "ais_dir_ext", "sort": 9}, +] + + +# ============================================================ +# 21个表单: (en_code, 中文名, 所属一级目录名, 字段列表) +# ============================================================ +FORM_DEFS = [ + # --- 项目中心 --- + ("AisProject", "项目管理", "项目中心", [ + FieldDef(field="F_Name", field_name="项目名称", required=True), + FieldDef(field="F_Code", field_name="项目标识", required=True), + FieldDef(field="F_Describe", field_name="项目描述"), + FieldDef(field="F_Manager", field_name="负责人"), + FieldDef(field="F_Member_Count", field_name="成员数量", jnpf_key="inputNumber"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "正常", "id": "1"}, {"fullName": "禁用", "id": "0"}]), + FieldDef(field="F_Remark", field_name="备注"), + ]), + ("AisProjectUser", "项目成员", "项目中心", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True, + jnpf_key="relationForm", + relation_config={ + "modelId": "808986025610185477", # 项目管理表单ID + "relationField": "F_Name", # 显示文本字段 + "propsValue": "f_id", # 存储值字段(小写 f_id) + "popupTitle": "选择项目", + }), + FieldDef(field="F_User_Id", field_name="用户", required=True), + FieldDef(field="F_Role", field_name="角色", jnpf_key="select", options=[ + {"fullName": "开发", "id": "dev"}, {"fullName": "运维", "id": "ops"}, {"fullName": "创建者", "id": "creator"}]), + FieldDef(field="F_Quota", field_name="资源配额"), + ]), + ("AisResourceQuota", "资源配额", "项目中心", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Quota_Type", field_name="配额类型", jnpf_key="select", options=[ + {"fullName": "GPU", "id": "gpu"}, {"fullName": "CPU", "id": "cpu"}, {"fullName": "内存", "id": "memory"}, {"fullName": "存储", "id": "storage"}]), + FieldDef(field="F_Quota_Value", field_name="配额值", required=True), + FieldDef(field="F_Describe", field_name="描述"), + ]), + # --- 镜像管理 --- + ("AisRepository", "镜像仓库", "镜像管理", [ + FieldDef(field="F_Name", field_name="仓库名称", required=True), + FieldDef(field="F_Server", field_name="仓库地址"), + FieldDef(field="F_User", field_name="用户名"), + FieldDef(field="F_Password", field_name="密码"), + FieldDef(field="F_Hubsecret", field_name="K8s Secret"), + FieldDef(field="F_Remark", field_name="备注"), + ]), + ("AisImages", "镜像管理", "镜像管理", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="镜像名称", required=True), + FieldDef(field="F_Describe", field_name="描述"), + FieldDef(field="F_Repository_Id", field_name="镜像仓库"), + 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"}]), + ]), + ("AisDocker", "Docker构建", "镜像管理", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="构建名称", required=True), + FieldDef(field="F_Git_Url", field_name="Git地址"), + FieldDef(field="F_Git_Ref", field_name="Git分支"), + FieldDef(field="F_Dockerfile_Path", field_name="Dockerfile路径"), + FieldDef(field="F_Image_Name", field_name="镜像名称", required=True), + FieldDef(field="F_Build_Status", field_name="构建状态", jnpf_key="select", options=[ + {"fullName": "构建中", "id": "building"}, {"fullName": "成功", "id": "success"}, {"fullName": "失败", "id": "failed"}]), + FieldDef(field="F_Build_Log", field_name="构建日志"), + ]), + # --- 训练中心 --- + ("AisJobTemplate", "任务模板", "训练中心", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="模板名称", required=True), + FieldDef(field="F_Job_Version", field_name="版本", jnpf_key="select", options=[ + {"fullName": "Release", "id": "Release"}, {"fullName": "Alpha", "id": "Alpha"}]), + FieldDef(field="F_Images_Id", field_name="镜像"), + FieldDef(field="F_HostAliases", field_name="域名映射"), + FieldDef(field="F_Workdir", field_name="工作目录"), + FieldDef(field="F_Entrypoint", field_name="入口命令"), + FieldDef(field="F_Args", field_name="启动参数"), + FieldDef(field="F_Env", field_name="环境变量"), + FieldDef(field="F_Volume_Mount", field_name="存储挂载"), + FieldDef(field="F_Privileged", field_name="特权模式", jnpf_key="switch"), + FieldDef(field="F_Expand", field_name="扩展配置"), + ]), + ("AisPipeline", "流水线管理", "训练中心", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="流水线名称", required=True), + FieldDef(field="F_Schedule_Type", field_name="调度类型", jnpf_key="select", options=[ + {"fullName": "一次性", "id": "once"}, {"fullName": "定时调度", "id": "crontab"}]), + FieldDef(field="F_Cron_Time", field_name="Cron表达式"), + FieldDef(field="F_Dag_Json", field_name="DAG配置"), + FieldDef(field="F_Pipeline_File", field_name="Pipeline YAML"), + FieldDef(field="F_Node_Selector", field_name="节点选择器"), + FieldDef(field="F_Parallelism", field_name="并行度", jnpf_key="inputNumber"), + FieldDef(field="F_Alert_Status", field_name="告警状态"), + FieldDef(field="F_Alert_User", field_name="告警用户"), + FieldDef(field="F_Parameter", field_name="参数配置"), + ]), + ("AisRunHistory", "运行历史", "训练中心", [ + FieldDef(field="F_Pipeline_Id", field_name="所属流水线", required=True), + FieldDef(field="F_Run_Id", field_name="运行ID"), + FieldDef(field="F_Status", field_name="运行状态", jnpf_key="select", options=[ + {"fullName": "运行中", "id": "running"}, {"fullName": "成功", "id": "success"}, {"fullName": "失败", "id": "failed"}, {"fullName": "取消", "id": "cancelled"}]), + FieldDef(field="F_Start_Time", field_name="开始时间"), + FieldDef(field="F_End_Time", field_name="结束时间"), + FieldDef(field="F_Duration", field_name="运行时长"), + FieldDef(field="F_Log_Url", field_name="日志地址"), + FieldDef(field="F_Parameter", field_name="运行参数"), + ]), + # --- 模型管理 --- + ("AisTrainingModel", "训练模型", "模型管理", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="模型名称", required=True), + FieldDef(field="F_Model_Version", field_name="模型版本"), + FieldDef(field="F_Model_Path", field_name="模型路径"), + FieldDef(field="F_Model_Format", field_name="模型格式"), + FieldDef(field="F_Framework", field_name="框架"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "训练中", "id": "training"}, {"fullName": "已完成", "id": "completed"}, {"fullName": "失败", "id": "failed"}]), + FieldDef(field="F_Metric", field_name="指标"), + FieldDef(field="F_Remark", field_name="备注"), + ]), + ("AisInferenceService", "推理服务", "模型管理", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="服务名称", required=True), + FieldDef(field="F_Model_Id", field_name="关联模型"), + FieldDef(field="F_Service_Type", field_name="服务类型"), + FieldDef(field="F_Resource_Memory", field_name="内存配置"), + FieldDef(field="F_Resource_Cpu", field_name="CPU配置"), + FieldDef(field="F_Resource_Gpu", field_name="GPU配置"), + FieldDef(field="F_Replicas", field_name="副本数", jnpf_key="inputNumber"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "运行中", "id": "running"}, {"fullName": "已停止", "id": "stopped"}]), + ]), + ("AisAihub", "AIHub", "模型管理", [ + FieldDef(field="F_Name", field_name="模型名称", required=True), + FieldDef(field="F_Provider", field_name="提供商"), + FieldDef(field="F_Category", field_name="类别"), + FieldDef(field="F_Describe", field_name="描述"), + FieldDef(field="F_Price", field_name="价格"), + FieldDef(field="F_Url", field_name="模型地址"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "上架", "id": "1"}, {"fullName": "下架", "id": "0"}]), + ]), + # --- 数据中心 --- + ("AisDataset", "数据集管理", "数据中心", [ + FieldDef(field="F_Name", field_name="数据集名称", required=True), + FieldDef(field="F_Type", field_name="数据集类型", jnpf_key="select", options=[ + {"fullName": "图片", "id": "image"}, {"fullName": "视频", "id": "video"}, {"fullName": "文本", "id": "text"}, {"fullName": "音频", "id": "audio"}, {"fullName": "其他", "id": "other"}]), + FieldDef(field="F_Path", field_name="数据集路径"), + FieldDef(field="F_Format", field_name="数据格式"), + FieldDef(field="F_Size", field_name="数据大小", jnpf_key="inputNumber"), + FieldDef(field="F_Sample_Count", field_name="样本数量", jnpf_key="inputNumber"), + FieldDef(field="F_Dataset_Version", field_name="数据集版本"), + FieldDef(field="F_Describe", field_name="描述"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "正常", "id": "1"}, {"fullName": "禁用", "id": "0"}]), + ]), + ("AisMetadataTable", "元数据管理", "数据中心", [ + FieldDef(field="F_Name", field_name="元数据名称", required=True), + FieldDef(field="F_Table_Name", field_name="表名"), + FieldDef(field="F_Describe", field_name="描述"), + FieldDef(field="F_Fields", field_name="字段定义"), + FieldDef(field="F_Tags", field_name="标签"), + ]), + ("AisMetadataMetric", "元数据指标", "数据中心", [ + FieldDef(field="F_Metadata_Id", field_name="所属元数据", required=True), + FieldDef(field="F_Name", field_name="指标名称", required=True), + FieldDef(field="F_Metric_Type", field_name="指标类型"), + FieldDef(field="F_Value", field_name="指标值"), + FieldDef(field="F_Unit", field_name="单位"), + FieldDef(field="F_Describe", field_name="描述"), + ]), + ("AisDimension", "维度管理", "数据中心", [ + FieldDef(field="F_Name", field_name="维度名称", required=True), + FieldDef(field="F_Code", field_name="维度编码"), + FieldDef(field="F_Type", field_name="维度类型"), + FieldDef(field="F_Describe", field_name="描述"), + ]), + ("AisSqllabQuery", "SQL查询", "数据中心", [ + FieldDef(field="F_Name", field_name="查询名称", required=True), + FieldDef(field="F_Sql_Text", field_name="SQL语句"), + FieldDef(field="F_Database", field_name="数据库"), + FieldDef(field="F_Status", field_name="状态"), + ]), + # --- 开发环境 --- + ("AisNotebook", "Notebook", "开发环境", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="Notebook名称", required=True), + FieldDef(field="F_Ide_Type", field_name="IDE类型", jnpf_key="select", options=[ + {"fullName": "JupyterLab", "id": "jupyter"}, {"fullName": "Theia", "id": "theia"}, {"fullName": "RStudio", "id": "rstudio"}]), + FieldDef(field="F_Images", field_name="镜像"), + FieldDef(field="F_Working_Dir", field_name="工作目录"), + FieldDef(field="F_Volume_Mount", field_name="存储挂载"), + FieldDef(field="F_Node_Selector", field_name="节点选择器"), + FieldDef(field="F_Resource_Memory", field_name="内存配置"), + FieldDef(field="F_Resource_Cpu", field_name="CPU配置"), + FieldDef(field="F_Resource_Gpu", field_name="GPU配置"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "运行中", "id": "running"}, {"fullName": "已停止", "id": "stopped"}]), + ]), + # --- 自动化 --- + ("AisNni", "NNI实验", "自动化", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="实验名称", required=True), + FieldDef(field="F_Config_Yaml", field_name="NNI配置"), + FieldDef(field="F_Search_Space", field_name="搜索空间"), + FieldDef(field="F_Trial_Command", field_name="Trial命令"), + FieldDef(field="F_Trial_Params", field_name="Trial参数"), + FieldDef(field="F_Max_Trial_Count", field_name="最大Trial数", jnpf_key="inputNumber"), + FieldDef(field="F_Concurrency", field_name="并发数", jnpf_key="inputNumber"), + FieldDef(field="F_Status", field_name="状态", jnpf_key="select", options=[ + {"fullName": "运行中", "id": "running"}, {"fullName": "已完成", "id": "completed"}, {"fullName": "失败", "id": "failed"}]), + ]), + ("AisEtlPipeline", "ETL流水线", "自动化", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="ETL名称", required=True), + FieldDef(field="F_Source_Type", field_name="数据源类型"), + FieldDef(field="F_Source_Config", field_name="数据源配置"), + FieldDef(field="F_Transform_Config", field_name="转换配置"), + FieldDef(field="F_Target_Type", field_name="目标类型"), + FieldDef(field="F_Target_Config", field_name="目标配置"), + FieldDef(field="F_Schedule_Type", field_name="调度类型"), + FieldDef(field="F_Cron_Time", field_name="Cron表达式"), + ]), + ("AisServicePipeline", "服务编排", "自动化", [ + FieldDef(field="F_Project_Id", field_name="所属项目", required=True), + FieldDef(field="F_Name", field_name="编排名称", required=True), + FieldDef(field="F_Service_Config", field_name="服务配置"), + FieldDef(field="F_Dag_Json", field_name="DAG配置"), + FieldDef(field="F_Status", field_name="状态"), + ]), +] + + +def get_dir_id_by_name(client, dir_name): + """从菜单树中按 fullName 查找目录 ID""" + resp = client.menu.get_list({"currentPage": 1, "pageSize": 500}) + for m in (resp.data or {}).get("list", []): + if m.get("fullName") == dir_name: + return m.get("id") + for c in (m.get("children") or []): + if c.get("fullName") == dir_name: + return c.get("id") + return None + + +def main(): + print("=" * 60) + print("Cube Studio 一键部署") + print("=" * 60) + + client, config = login_client() + print(f"登录成功: {config.app_code} ({config.system_title})") + + # ================================================================ + # Step 1: 创建一级目录 + # ================================================================ + print("\n[Step 1/3] 创建一级目录...") + dir_ids = {} + for d in FIRST_LEVEL_DIRS: + name, en_code, sort = d["name"], d["en_code"], d["sort"] + existing_id = get_dir_id_by_name(client, name) + if existing_id: + dir_ids[name] = existing_id + print(f" 跳过 {name}: 已存在 (id={existing_id})") + continue + + resp = client.menu.create_directory_menu( + full_name=name, en_code=en_code, parent_id="-1", sort_code=sort, + ) + did = resp.id + if not did: + did = get_dir_id_by_name(client, name) + if did: + dir_ids[name] = did + print(f" ✅ {name}: id={did}") + else: + print(f" ❌ {name}: 创建失败 {resp}") + + print(f" 一级目录: {len(dir_ids)}/{len(FIRST_LEVEL_DIRS)}") + + # ================================================================ + # Step 2: 创建功能表单 + 发布 + # ================================================================ + print("\n[Step 2/3] 创建功能表单...") + existing_forms = set() + resp = client.visual_dev.get_list({"currentPage": 1, "pageSize": 200}) + for item in (resp.data or {}).get("list", []): + existing_forms.add(item.get("enCode")) + + form_id_map = {} # en_code -> func_id + ok = 0 + for en_code, cn_name, _, fields in FORM_DEFS: + if en_code in existing_forms: + # 已存在则查 ID + r = client.visual_dev.get_list({"enCode": en_code, "currentPage": 1, "pageSize": 10}) + for item in (r.data or {}).get("list", []): + if item.get("enCode") == en_code: + form_id_map[en_code] = item.get("id") + break + print(f" 跳过 {cn_name} ({en_code}): 已存在") + ok += 1 + continue + + table_name = f"ais_{en_code.lower()}" + field_dicts = [f.to_dict() if hasattr(f, 'to_dict') else f for f in fields] + cfg = build_full_config( + full_name=cn_name, en_code=en_code, table_name=table_name, + table_label=f"{cn_name}表", description=f"{cn_name}功能", + category=config.business_category_id, fields=field_dicts, + db_link_id=config.db_link_id, web_type=2, + ) + payload = build_create_payload(cfg, dynamic_table=True) + + resp = client.visual_dev.create(payload) + func_id = resp.id + if not func_id: + print(f" ❌ {cn_name}: {resp.msg}") + continue + + rel = client.visual_dev.release(func_id) + form_id_map[en_code] = func_id + ok += 1 + print(f" ✅ {cn_name} ({en_code}): func_id={func_id}") + + print(f" 功能表单: {ok}/{len(FORM_DEFS)}") + + # ================================================================ + # Step 3: 创建功能菜单,直接挂到一级目录 + # ================================================================ + print("\n[Step 3/3] 创建功能菜单...") + menu_ok = 0 + menu_skip = 0 + for en_code, cn_name, parent_dir, _ in FORM_DEFS: + parent_id = dir_ids.get(parent_dir) + if not parent_id: + print(f" ❌ {cn_name}: 一级目录 {parent_dir} 不存在") + continue + + func_id = form_id_map.get(en_code) + if not func_id: + print(f" ❌ {cn_name}: 表单 {en_code} 不存在") + continue + + # 检查菜单是否已存在 + resp = client.menu.get_list({"currentPage": 1, "pageSize": 500}) + found = False + for m in (resp.data or {}).get("list", []): + if m.get("fullName") == parent_dir: + for c in (m.get("children") or []): + if c.get("enCode") == en_code: + found = True + break + if not found: + for m2 in (resp.data or {}).get("list", []): + for c in (m2.get("children") or []): + for gc in (c.get("children") or []): + if gc.get("enCode") == en_code: + found = True + break + + if found: + menu_skip += 1 + print(f" 跳过 {cn_name}: 菜单已存在") + continue + + resp = client.menu.create_form_menu( + full_name=cn_name, en_code=en_code, + visual_dev_id=func_id, parent_id=str(parent_id), sort_code=1, + ) + mid = resp.id + if not mid: + mid = client.menu.get_id_by_en_code(en_code) + if mid: + menu_ok += 1 + print(f" ✅ {cn_name} → {parent_dir} (id={mid})") + else: + print(f" ❌ {cn_name}: {resp}") + + print(f" 功能菜单: 新建={menu_ok}, 跳过={menu_skip}") + + print(f"\n{'=' * 60}") + print(f"部署完成! 目录={len(dir_ids)}, 表单={ok}, 菜单={menu_ok}") + + +if __name__ == "__main__": + main() diff --git a/examples/quickstart.py b/examples/quickstart.py new file mode 100644 index 0000000..33f359a --- /dev/null +++ b/examples/quickstart.py @@ -0,0 +1,470 @@ +#!/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() diff --git a/exceptions.py b/exceptions.py new file mode 100644 index 0000000..222b823 --- /dev/null +++ b/exceptions.py @@ -0,0 +1,25 @@ +"""AIBridge 异常体系""" + + +class JNPFError(Exception): + """基础异常""" + pass + + +class AuthError(JNPFError): + """认证异常(登录失败、Token失效等)""" + + def __init__(self, msg=None, code=None, raw=None): + super().__init__(msg) + self.msg = msg + self.code = code + self.raw = raw + + +class APIError(JNPFError): + """API 调用异常(请求失败、参数错误等)""" + + def __init__(self, message, code=None, response=None): + super().__init__(message) + self.code = code + self.response = response diff --git a/models.py b/models.py new file mode 100644 index 0000000..83e2dd1 --- /dev/null +++ b/models.py @@ -0,0 +1,128 @@ +"""AIBridge 数据模型""" + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + + +@dataclass +class APIResponse: + """JNPF 统一响应模型 + + JNPF API 返回格式: { "code": 200, "data": ..., "msg": "操作成功" } + """ + code: int = 0 + data: Any = None + msg: str = "" + raw: dict = field(default_factory=dict) + _id: Optional[str] = field(default=None, repr=False) + + @property + def success(self) -> bool: + return self.code == 200 + + @property + def id(self) -> Optional[str]: + """快捷获取返回数据的 id 字段 + + 兼容两种响应格式: + - data 为 dict → 取 data["id"] + - data 为 str → 直接返回(部分 API 如模板创建直接返回 ID 字符串) + - _id 为内部字段,可通过 setter 或 create_model_and_get_id 设置 + """ + if self._id is not None: + return self._id + if isinstance(self.data, str): + return self.data + if isinstance(self.data, dict): + return self.data.get("id") + return None + + @id.setter + def id(self, value: Optional[str]): + """允许外部设置 id 字段(用于 create_model_and_get_id 等场景)""" + self._id = value + + +@dataclass +class PaginatedResponse: + """分页响应模型""" + list: List[dict] = field(default_factory=list) + pagination: dict = field(default_factory=dict) + total: int = 0 + page: int = 1 + page_size: int = 20 + + @classmethod + def from_response(cls, resp: APIResponse) -> "PaginatedResponse": + """从 APIResponse 构建分页响应""" + data = resp.data if isinstance(resp.data, dict) else {} + pagination = data.get("pagination") or {} + record_list = data.get("list") or [] + return cls( + list=record_list if isinstance(record_list, list) else [], + pagination=pagination, + total=pagination.get("total", len(record_list)), + page=pagination.get("currentPage", 1), + page_size=pagination.get("pageSize", 20), + ) + + +@dataclass +class FieldDef: + """字段定义(简洁格式,用于配置构建器) + + Attributes: + field: 数据库字段名,如 "F_Full_Name" + field_name: 字段中文名,如 "销售商名称" + jnpf_key: JNPF 控件类型,默认 "input" + required: 是否必填 + data_type: 数据类型,默认 "varchar" + data_length: 数据长度,默认 "200" + options: 下拉选项列表,仅 select/radio/checkbox/cascader/treeSelect 支持。 + 格式为 [{"fullName": "显示文本", "id": "值"}, ...] + dictionary_type: 数据字典类型编码 + relation_config: 关联表单配置,仅 relationForm/popupSelect/popupTable 使用。 + 格式为 { + "modelId": "目标表单ID", + "relationField": "显示字段名(如 F_Name)", + "propsValue": "存储字段名(如 f_id,小写)", + "columnOptions": [{"value": "F_Name", "label": "名称"}, ...], + "popupTitle": "选择弹窗标题", + "hasPage": True, + "pageSize": 20, + } + """ + field: str + field_name: str + jnpf_key: str = "input" + required: bool = False + data_type: str = "varchar" + data_length: str = "200" + options: List[Dict[str, Any]] = None + dictionary_type: str = "" + relation_config: Dict[str, Any] = None + + def to_dict(self) -> dict: + # f_version 是 JNPF 系统保留字段,禁止使用 + if self.field.lower() == "f_version": + raise ValueError(f"字段名 '{self.field}' 是 JNPF 系统保留字段,禁止使用。") + # 提示字段命名规范(f_xx_xx 格式) + import re + if not re.match(r'^f_[a-z][a-z0-9]*(_[a-z0-9]+)*$', self.field): + print(f"⚠️ 提示:字段名建议使用 f_xx_xx 格式(如 f_user_name),当前:{self.field}") + result = { + "field": self.field, + "fieldName": self.field_name, + "jnpfKey": self.jnpf_key, + "required": self.required, + "dataType": self.data_type, + "dataLength": self.data_length, + "options": self.options, + "dictionaryType": self.dictionary_type, + } + if self.relation_config: + for k, v in self.relation_config.items(): + if k == "columnOptions": + continue # columnOptions 由 build_full_config 从 columnData 自动提取 + result[k] = v + return result diff --git a/modules/.DS_Store b/modules/.DS_Store new file mode 100644 index 0000000..3f4329e Binary files /dev/null and b/modules/.DS_Store differ diff --git a/modules/__init__.py b/modules/__init__.py new file mode 100644 index 0000000..7f14afd --- /dev/null +++ b/modules/__init__.py @@ -0,0 +1,30 @@ +"""AIBridge API 模块""" + +from aibridge.modules.auth import AuthAPI +from aibridge.modules.menu import MenuAPI +from aibridge.modules.user import UserAPI +from aibridge.modules.organize import OrganizeAPI +from aibridge.modules.role import RoleAPI +from aibridge.modules.position import PositionAPI +from aibridge.modules.dictionary import DictionaryAPI +from aibridge.modules.visual_dev import VisualDevAPI +from aibridge.modules.online_dev import OnlineDevAPI +from aibridge.modules.workflow import WorkflowAPI +from aibridge.modules.data_interface import DataInterfaceAPI +from aibridge.modules.interface_oauth import InterfaceOauthAPI +from aibridge.modules.portal import PortalAPI +from aibridge.modules.message import MessageAPI +from aibridge.modules.data_source import DataSourceAPI +from aibridge.modules.data_model import DataModelAPI +from aibridge.modules.print_dev import PrintDevAPI +from aibridge.modules.report import ReportAPI +from aibridge.modules.sys_config import SysConfigAPI +from aibridge.modules.file import FileAPI + +__all__ = [ + "AuthAPI", "MenuAPI", "UserAPI", "OrganizeAPI", "RoleAPI", "PositionAPI", + "DictionaryAPI", "VisualDevAPI", "OnlineDevAPI", "WorkflowAPI", + "DataInterfaceAPI", "InterfaceOauthAPI", "PortalAPI", "MessageAPI", "DataSourceAPI", + "DataModelAPI", + "PrintDevAPI", "ReportAPI", "SysConfigAPI", "FileAPI", +] diff --git a/modules/__pycache__/__init__.cpython-312.pyc b/modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..ed6481d Binary files /dev/null and b/modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/modules/__pycache__/__init__.cpython-313.pyc b/modules/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..b7f0d6f Binary files /dev/null and b/modules/__pycache__/__init__.cpython-313.pyc differ diff --git a/modules/__pycache__/auth.cpython-312.pyc b/modules/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000..cc1b002 Binary files /dev/null and b/modules/__pycache__/auth.cpython-312.pyc differ diff --git a/modules/__pycache__/auth.cpython-313.pyc b/modules/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000..2104998 Binary files /dev/null and b/modules/__pycache__/auth.cpython-313.pyc differ diff --git a/modules/__pycache__/data_interface.cpython-312.pyc b/modules/__pycache__/data_interface.cpython-312.pyc new file mode 100644 index 0000000..171129d Binary files /dev/null and b/modules/__pycache__/data_interface.cpython-312.pyc differ diff --git a/modules/__pycache__/data_interface.cpython-313.pyc b/modules/__pycache__/data_interface.cpython-313.pyc new file mode 100644 index 0000000..cfba256 Binary files /dev/null and b/modules/__pycache__/data_interface.cpython-313.pyc differ diff --git a/modules/__pycache__/data_model.cpython-312.pyc b/modules/__pycache__/data_model.cpython-312.pyc new file mode 100644 index 0000000..74add42 Binary files /dev/null and b/modules/__pycache__/data_model.cpython-312.pyc differ diff --git a/modules/__pycache__/data_model.cpython-313.pyc b/modules/__pycache__/data_model.cpython-313.pyc new file mode 100644 index 0000000..aeadbbf Binary files /dev/null and b/modules/__pycache__/data_model.cpython-313.pyc differ diff --git a/modules/__pycache__/data_source.cpython-312.pyc b/modules/__pycache__/data_source.cpython-312.pyc new file mode 100644 index 0000000..a9a3f3e Binary files /dev/null and b/modules/__pycache__/data_source.cpython-312.pyc differ diff --git a/modules/__pycache__/data_source.cpython-313.pyc b/modules/__pycache__/data_source.cpython-313.pyc new file mode 100644 index 0000000..db8ccd7 Binary files /dev/null and b/modules/__pycache__/data_source.cpython-313.pyc differ diff --git a/modules/__pycache__/dictionary.cpython-312.pyc b/modules/__pycache__/dictionary.cpython-312.pyc new file mode 100644 index 0000000..53490a2 Binary files /dev/null and b/modules/__pycache__/dictionary.cpython-312.pyc differ diff --git a/modules/__pycache__/dictionary.cpython-313.pyc b/modules/__pycache__/dictionary.cpython-313.pyc new file mode 100644 index 0000000..504bf7d Binary files /dev/null and b/modules/__pycache__/dictionary.cpython-313.pyc differ diff --git a/modules/__pycache__/file.cpython-312.pyc b/modules/__pycache__/file.cpython-312.pyc new file mode 100644 index 0000000..37de446 Binary files /dev/null and b/modules/__pycache__/file.cpython-312.pyc differ diff --git a/modules/__pycache__/file.cpython-313.pyc b/modules/__pycache__/file.cpython-313.pyc new file mode 100644 index 0000000..624b215 Binary files /dev/null and b/modules/__pycache__/file.cpython-313.pyc differ diff --git a/modules/__pycache__/interface_oauth.cpython-312.pyc b/modules/__pycache__/interface_oauth.cpython-312.pyc new file mode 100644 index 0000000..2519a2b Binary files /dev/null and b/modules/__pycache__/interface_oauth.cpython-312.pyc differ diff --git a/modules/__pycache__/interface_oauth.cpython-313.pyc b/modules/__pycache__/interface_oauth.cpython-313.pyc new file mode 100644 index 0000000..17e9a90 Binary files /dev/null and b/modules/__pycache__/interface_oauth.cpython-313.pyc differ diff --git a/modules/__pycache__/menu.cpython-312.pyc b/modules/__pycache__/menu.cpython-312.pyc new file mode 100644 index 0000000..e6f761b Binary files /dev/null and b/modules/__pycache__/menu.cpython-312.pyc differ diff --git a/modules/__pycache__/menu.cpython-313.pyc b/modules/__pycache__/menu.cpython-313.pyc new file mode 100644 index 0000000..7cb140a Binary files /dev/null and b/modules/__pycache__/menu.cpython-313.pyc differ diff --git a/modules/__pycache__/message.cpython-312.pyc b/modules/__pycache__/message.cpython-312.pyc new file mode 100644 index 0000000..95769f9 Binary files /dev/null and b/modules/__pycache__/message.cpython-312.pyc differ diff --git a/modules/__pycache__/message.cpython-313.pyc b/modules/__pycache__/message.cpython-313.pyc new file mode 100644 index 0000000..19a591c Binary files /dev/null and b/modules/__pycache__/message.cpython-313.pyc differ diff --git a/modules/__pycache__/online_dev.cpython-312.pyc b/modules/__pycache__/online_dev.cpython-312.pyc new file mode 100644 index 0000000..561497e Binary files /dev/null and b/modules/__pycache__/online_dev.cpython-312.pyc differ diff --git a/modules/__pycache__/online_dev.cpython-313.pyc b/modules/__pycache__/online_dev.cpython-313.pyc new file mode 100644 index 0000000..53f3847 Binary files /dev/null and b/modules/__pycache__/online_dev.cpython-313.pyc differ diff --git a/modules/__pycache__/organize.cpython-312.pyc b/modules/__pycache__/organize.cpython-312.pyc new file mode 100644 index 0000000..bd225da Binary files /dev/null and b/modules/__pycache__/organize.cpython-312.pyc differ diff --git a/modules/__pycache__/organize.cpython-313.pyc b/modules/__pycache__/organize.cpython-313.pyc new file mode 100644 index 0000000..7edefd3 Binary files /dev/null and b/modules/__pycache__/organize.cpython-313.pyc differ diff --git a/modules/__pycache__/portal.cpython-312.pyc b/modules/__pycache__/portal.cpython-312.pyc new file mode 100644 index 0000000..b5b5745 Binary files /dev/null and b/modules/__pycache__/portal.cpython-312.pyc differ diff --git a/modules/__pycache__/portal.cpython-313.pyc b/modules/__pycache__/portal.cpython-313.pyc new file mode 100644 index 0000000..fc02d6e Binary files /dev/null and b/modules/__pycache__/portal.cpython-313.pyc differ diff --git a/modules/__pycache__/position.cpython-312.pyc b/modules/__pycache__/position.cpython-312.pyc new file mode 100644 index 0000000..886a9f6 Binary files /dev/null and b/modules/__pycache__/position.cpython-312.pyc differ diff --git a/modules/__pycache__/position.cpython-313.pyc b/modules/__pycache__/position.cpython-313.pyc new file mode 100644 index 0000000..e4bbb73 Binary files /dev/null and b/modules/__pycache__/position.cpython-313.pyc differ diff --git a/modules/__pycache__/print_dev.cpython-312.pyc b/modules/__pycache__/print_dev.cpython-312.pyc new file mode 100644 index 0000000..d00f258 Binary files /dev/null and b/modules/__pycache__/print_dev.cpython-312.pyc differ diff --git a/modules/__pycache__/print_dev.cpython-313.pyc b/modules/__pycache__/print_dev.cpython-313.pyc new file mode 100644 index 0000000..990ac23 Binary files /dev/null and b/modules/__pycache__/print_dev.cpython-313.pyc differ diff --git a/modules/__pycache__/report.cpython-312.pyc b/modules/__pycache__/report.cpython-312.pyc new file mode 100644 index 0000000..abf26f8 Binary files /dev/null and b/modules/__pycache__/report.cpython-312.pyc differ diff --git a/modules/__pycache__/report.cpython-313.pyc b/modules/__pycache__/report.cpython-313.pyc new file mode 100644 index 0000000..d20c925 Binary files /dev/null and b/modules/__pycache__/report.cpython-313.pyc differ diff --git a/modules/__pycache__/role.cpython-312.pyc b/modules/__pycache__/role.cpython-312.pyc new file mode 100644 index 0000000..9952fae Binary files /dev/null and b/modules/__pycache__/role.cpython-312.pyc differ diff --git a/modules/__pycache__/role.cpython-313.pyc b/modules/__pycache__/role.cpython-313.pyc new file mode 100644 index 0000000..cd020ed Binary files /dev/null and b/modules/__pycache__/role.cpython-313.pyc differ diff --git a/modules/__pycache__/sys_config.cpython-312.pyc b/modules/__pycache__/sys_config.cpython-312.pyc new file mode 100644 index 0000000..a0800c5 Binary files /dev/null and b/modules/__pycache__/sys_config.cpython-312.pyc differ diff --git a/modules/__pycache__/sys_config.cpython-313.pyc b/modules/__pycache__/sys_config.cpython-313.pyc new file mode 100644 index 0000000..a5a4ee4 Binary files /dev/null and b/modules/__pycache__/sys_config.cpython-313.pyc differ diff --git a/modules/__pycache__/user.cpython-312.pyc b/modules/__pycache__/user.cpython-312.pyc new file mode 100644 index 0000000..a6a395f Binary files /dev/null and b/modules/__pycache__/user.cpython-312.pyc differ diff --git a/modules/__pycache__/user.cpython-313.pyc b/modules/__pycache__/user.cpython-313.pyc new file mode 100644 index 0000000..59d444b Binary files /dev/null and b/modules/__pycache__/user.cpython-313.pyc differ diff --git a/modules/__pycache__/visual_dev.cpython-312.pyc b/modules/__pycache__/visual_dev.cpython-312.pyc new file mode 100644 index 0000000..a495b38 Binary files /dev/null and b/modules/__pycache__/visual_dev.cpython-312.pyc differ diff --git a/modules/__pycache__/visual_dev.cpython-313.pyc b/modules/__pycache__/visual_dev.cpython-313.pyc new file mode 100644 index 0000000..5ac8b43 Binary files /dev/null and b/modules/__pycache__/visual_dev.cpython-313.pyc differ diff --git a/modules/__pycache__/workflow.cpython-312.pyc b/modules/__pycache__/workflow.cpython-312.pyc new file mode 100644 index 0000000..8fefa98 Binary files /dev/null and b/modules/__pycache__/workflow.cpython-312.pyc differ diff --git a/modules/__pycache__/workflow.cpython-313.pyc b/modules/__pycache__/workflow.cpython-313.pyc new file mode 100644 index 0000000..a2021a0 Binary files /dev/null and b/modules/__pycache__/workflow.cpython-313.pyc differ diff --git a/modules/auth.py b/modules/auth.py new file mode 100644 index 0000000..0a3ccdc --- /dev/null +++ b/modules/auth.py @@ -0,0 +1,68 @@ +"""认证模块 + +对应前端源码: + api/core/auth.ts - 登录/登出/SSO + api/core/user.ts - 用户信息/扫码登录 +""" + +from typing import Optional +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class AuthAPI: + """认证 API""" + + def __init__(self, client: JNPFClient): + self._client = client + + def login(self, account: str, password: str) -> APIResponse: + """登录(自动处理密码加密)""" + return self._client.login(account, password) + + def logout(self) -> APIResponse: + """退出登录""" + return self._client.logout() + + def get_user_info(self, system_code: str = "", + is_backend: int = 0) -> APIResponse: + """获取当前用户信息""" + return self._client.get_user_info(system_code, is_backend) + + def get_login_config(self) -> APIResponse: + """获取登录配置""" + return self._client.get_login_config() + + def get_config(self, account: str) -> APIResponse: + """获取系统默认配置""" + return self._client.request("GET", f"/api/oauth/getConfig/{account}") + + def get_ticket(self) -> APIResponse: + """获取登录票据""" + return self._client.request("GET", "/api/oauth/getTicket") + + def get_ticket_status(self, ticket: str) -> APIResponse: + """根据票据获取登录状态""" + return self._client.request("GET", f"/api/oauth/getTicketStatus/{ticket}") + + def unlock(self, data: dict) -> APIResponse: + """锁屏解锁""" + return self._client.request("POST", "/api/oauth/LockScreen", data=data) + + def socials_login(self, params: dict) -> APIResponse: + """第三方登录回调""" + return self._client.request("POST", "/api/oauth/Login/socials", + params=params, + _form_urlencoded=True) + + def get_code_certificate(self) -> APIResponse: + """扫码登录获取凭证""" + return self._client.request("GET", "/api/oauth/codeCertificate") + + def get_code_certificate_status(self, ticket: str) -> APIResponse: + """扫码登录获取凭证状态""" + return self._client.request("GET", f"/api/oauth/codeCertificateStatus/{ticket}") + + def update_password_message(self) -> APIResponse: + """修改密码信息发送""" + return self._client.request("POST", "/api/oauth/updatePasswordMessage") diff --git a/modules/data_interface.py b/modules/data_interface.py new file mode 100644 index 0000000..4ef6f69 --- /dev/null +++ b/modules/data_interface.py @@ -0,0 +1,578 @@ +"""数据接口模块 + +对应前端源码: api/systemData/dataInterface.ts + +关键机制(基于后端源码分析 DataInterfaceServiceImpl.java): + - SQL 占位符: {参数名},最终替换为 ? 由 PreparedStatement 执行 + - 参数通过 Preview 端点的 paramList 传递(sourceType=1 用 defaultValue) + - action=1 为增删改(不检查敏感词),action=3 为查询 + - 系统变量: @snowFlakeID(雪花ID), @userId, @organizeId, @keyword, @pageSize, @offsetSize 等 + - isPostPosition 必须为 0,否则 Preview 时 handlePostVariate 因 null 拆箱 NPE + - SQL 模板中不能包含 {} 空字面量(会被当作参数占位符解析) + - 多租户隔离: DI Preview 通过 dbLinkId 指定的数据库连接执行 SQL, + dbLinkId=0 在多租户环境下连接主库,部分表(如 base_data_interface) + 的数据可能仅通过 MyBatis-Plus 的租户过滤可访问 + - type: 1=SQL操作, 2=静态数据, 3=API操作 + - hasPage=1 启用分页,需同时配置 dataCountJson 数量统计SQL + - 分页变量: @offsetSize=(当前页-1)*每页条数, @pageSize=每页条数, @keyword=关键词 + +参考: + - 后端: DataInterfaceServiceImpl.java(executeSql/customizationParameter/infoToId) + - 前端: api/systemData/dataInterface.ts + - Swagger: http://127.0.0.1:30000/doc.html#/home(仅本地可用) + - 文档: aibridge/docs/datainterface/ + +28个示例接口 (base_data_interface f_creator_time < 2026-10-1): + 1. 83ae1f5e5c26447b8c4849ead352b048 - 当前用户 (SQL, {@userId}) + 2. a0c3186292df4fe2842f66dee0ea7729 - 查询当前组织 (SQL, 多表JOIN) + 3. fdfd02c7628a4ea4a0b125463e7933e0 - 查询当前组织以及子组织 (SQL) + 4. ebcc44be142e43b795c0d769abd6d25a - 用户列表 (SQL, 多表JOIN) + 5. cd6fe911f90048f0bba7ef9f38251d96 - 柱状图 (静态) + 6. be312b18a1664d8787e0dfcd2412969f - 折线图 (静态) + 7. 79e5455c2f0d4d8ba2b444249bae0490 - 饼图 (静态) + 8. 8ce8ccf7a3bf48a79a0c2bff20b46726 - 象形图 (静态) + 9. 78814d0a32fa41ae8427b708bfadb808 - 雷达图 (静态) + 10. 04d910fb47f4469e907a5c85949329cb - 散点图 (静态) + 11. 3044325436d347af9b59a617f10e3ab6 - 漏斗图 (静态) + 12. bd993fb8dc914076a3848b0c121b17ca - 查询当前用户以及下属 (SQL) + 13. 360711881444294853 - 获取订单商品接口 (API, GET) + 14. 395176542063304069 - 视图表数据 (SQL, 视图查询) + 15. 395178064327220613 - 列表树形表格 (SQL, F_Id/F_PId) + 16. 395538362724780101 - 访问jnpf接口认证示例 (API, 内部调用) + 17. 398809921702874629 - 菜单 (SQL, base_module) + 18. 398826053293854213 - 系统菜单接口(示例)(API, 8参数) + 19. 400305221865071237 - 测试 (SQL, 带参数) + 20. 420587863533428357 - 行政区划 (SQL, {parentId}) + 21. 469125039078305029 - API真分页 (API, hasPage=1) + 22. 469125798494792965 - SQL真分页 (SQL, LIMIT分页) + 23. 469471490920740869 - 添加公告接口 (API, POST) + 24. 469492643924081285 - 树形sql_字段列表 (SQL, 树形) + 25. 469493539378625157 - 下拉多参_字段列表 (SQL, 多参数) + 26. 469493805800815237 - 区域下拉补全_字段列表 (SQL, 联想) + 27. 469493919109937797 - 测试级联_字段列表 (静态, 级联) + 28. 469500704067746437 - 当前组织_字段列表 (SQL, {@organizeId}) +""" + +import json +from typing import Any, Dict, List, Optional + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class DataInterfaceAPI: + """数据接口 API + + 提供数据接口的 CRUD 管理,以及通过 Preview 端点执行参数化 SQL 的能力。 + + 典型用法:: + + di = DataInterfaceAPI(client) + + # 创建查询接口 + di_id = di.create_sql_interface( + full_name="按编码查询", + en_code="query_by_code", + sql="SELECT * FROM base_table WHERE f_code = {code} AND f_delete_mark = 0", + parameters=[{"field": "code", "fieldName": "编码", "dataType": "varchar", + "required": 1, "sourceType": 1}], + action=3, + ) + + # 执行查询 + result = di.execute(di_id, {"code": "ABC001"}) + for row in result: + print(row) + """ + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/DataInterface" + + # ==================== 基础 CRUD ==================== + + def get_list(self, data: dict = None) -> APIResponse: + """获取接口列表(分页) + + 注意: 必须传 category 参数,否则返回空列表。 + + Args: + data: 查询参数,常用字段: + - currentPage, pageSize: 分页 + - category: 分类 ID(必填) + - keyword: 关键字搜索 + """ + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self) -> APIResponse: + """获取接口列表下拉框""" + return self._client.request("GET", f"{self._prefix}/Selector") + + def create(self, data: dict) -> APIResponse: + """新建接口""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改接口""" + di_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{di_id}", data=data) + + def get_info(self, di_id: str) -> APIResponse: + """获取接口信息""" + return self._client.request("GET", f"{self._prefix}/{di_id}") + + def delete(self, di_id: str) -> APIResponse: + """删除接口""" + return self._client.request("DELETE", f"{self._prefix}/{di_id}") + + def copy(self, di_id: str) -> APIResponse: + """复制接口""" + return self._client.request("POST", f"{self._prefix}/{di_id}/Actions/Copy") + + # ==================== 执行与预览 ==================== + + def preview(self, di_id: str, data: dict = None) -> APIResponse: + """预览/执行接口 + + Args: + di_id: 接口 ID + data: 请求体,查询接口通常传: + {"paramList": [{"field": "参数名", "defaultValue": "值", + "dataType": "varchar", "sourceType": 1}]} + """ + return self._client.request("POST", f"{self._prefix}/{di_id}/Actions/Preview", data=data or {}) + + def execute(self, di_id: str, params: dict) -> List[Dict[str, Any]]: + """通过 Preview 端点带参数执行数据接口(简化版) + + 自动将 params dict 转换为 paramList 格式。 + + Args: + di_id: 接口 ID + params: 参数字典,如 {"code": "ABC001", "name": "测试"} + + Returns: + 查询接口返回行列表 (action=3); + 增删改接口返回空列表 (action=1,正常行为)。 + + Raises: + RuntimeError: 执行失败时抛出 + """ + param_list = [ + { + "field": key, + "defaultValue": str(value) if value is not None else "", + "dataType": "varchar", + "sourceType": 3, + "required": 0, + } + for key, value in params.items() + ] + resp = self.preview(di_id, {"paramList": param_list}) + if resp.code != 200: + raise RuntimeError(f"接口执行失败: code={resp.code}, msg={resp.msg}") + data = resp.data if resp.data else [] + return data if isinstance(data, list) else [data] + + def get_param(self, di_id: str) -> APIResponse: + """获取数据接口参数""" + return self._client.request("GET", f"{self._prefix}/GetParam/{di_id}") + + def export_data(self, di_id: str) -> APIResponse: + """导出数据接口数据""" + return self._client.request("GET", f"{self._prefix}/{di_id}/Actions/Export") + + def get_log(self, di_id: str, data: dict = None) -> APIResponse: + """获取数据接口调用日志""" + return self._client.request("GET", f"{self._prefix}Log/{di_id}", params=data) + + def get_data_select(self, data: dict) -> APIResponse: + """获取接口列表数据""" + interface_id = data.get("interfaceId") + return self._client.request("POST", f"{self._prefix}/{interface_id}/Actions/List", data=data) + + def get_data_info_by_ids(self, di_id: str, data: dict) -> APIResponse: + """获取多条接口详情数据""" + return self._client.request("POST", f"{self._prefix}/{di_id}/Actions/InfoByIds", data=data) + + def get_selector_list(self, data: dict = None) -> APIResponse: + """获取接口列表(工作流选择用,带分页)""" + return self._client.request("GET", f"{self._prefix}/getList", params=data) + + def get_fields(self, di_id: str, data: dict = None) -> APIResponse: + """获取接口字段""" + return self._client.request("POST", f"{self._prefix}/{di_id}/Actions/GetFields", data=data or {}) + + # ==================== 验证示例 ==================== + # 场景1: SQL无参数查询 (当前用户) + # result = execute("83ae1f5e5c26447b8c4849ead352b048", {}) + # 返回: [{'f_real_name': '管理员'}] + + # 场景2: SQL带参数 (行政区划) + # result = execute("420587863533428357", {"parentId": "0"}) + + # 场景3: SQL分页查询 + # result = execute("469125798494792965", {"keyword": ""}) + # 返回分页格式: {"list": [...], "pagination": {"currentPage": 1, "pageSize": 20, "total": 100}} + + # 场景4: 静态数据 (饼图) + # result = execute("79e5455c2f0d4d8ba2b444249bae0490", {}) + # 返回: {"title": {...}, "series": [...]} + + # 场景5: API调用 (需外部系统支持) + # result = execute("360711881444294853", {"keyword": ""}) + + # ==================== 扩展接口机制 ==================== + # dataExceptionJson(异常验证脚本): 仅 type=3 (API) 接口支持 + # - 返回 true: 继续处理结果 + # - 返回 false: 重新调用API(最多3次重试) + # - 错误码: SYS121=HTTP失败, SYS122=结果为空, SYS123=JS异常 + # + # dataJsJson(数据处理脚本): 所有类型(SQL/静态/API)都支持 + # - 在最终返回前执行,可对结果进行转换、计算字段等处理 + # + # 执行流程: checkRequestParams → callHTTP → handlePostVariate → dataExceptionJson → dataJsJson → 返回 + + # ==================== 高阶方法 ==================== + + @staticmethod + def build_payload( + full_name: str, + en_code: str, + sql: str, + parameters: List[dict], + category: str, + action: int = 1, + db_link_id: str = "0", + ) -> dict: + """构建数据接口创建 payload + + 固化了以下关键经验: + - isPostPosition 必须为 0(避免后端 NPE) + - dataConfigJson 包含完整的 sqlData/apiData/staticData 结构 + - action: 1=增删改, 3=查询 + + Args: + full_name: 接口名称 + en_code: 接口编码(同 category 下唯一) + sql: 参数化 SQL,使用 {参数名} 作为占位符。 + 注意: SQL 中不能包含 {} 空字面量(会被解析为参数占位符)。 + 系统变量: @snowFlakeID, @userId, @organizeId 等。 + parameters: 参数定义列表,每个元素: + {"field": "参数名", "fieldName": "中文名", "dataType": "varchar", + "required": 0/1, "sourceType": 1} + sourceType: 1=字段(defaultValue), 2=自定义(relationField), + 3=空, 4=系统变量 + category: 分类 ID + action: 1=增删改, 3=查询 + db_link_id: 数据库连接 ID,"0" 表示主数据库。 + 注意: 多租户环境下 dbLinkId=0 连接主库,部分业务表可能不在主库中。 + """ + return { + "fullName": full_name, + "enCode": en_code, + "type": 1, + "action": action, + "category": category, + "enabledMark": 1, + "hasPage": 0, + "isPostPosition": 0, # 必须为 0,否则 Preview 时后端 NPE + "dbLinkId": db_link_id, + "dataConfigJson": json.dumps({ + "staticData": "", + "sqlData": {"dbLinkId": db_link_id, "sql": sql}, + "apiData": { + "method": 1, "url": "", + "header": [], "query": [], "body": "", "bodyType": 0, + }, + }, ensure_ascii=False), + "parameterJson": json.dumps(parameters, ensure_ascii=False), + "dataCountJson": "", + "dataEchoJson": "", + "dataJsJson": "", + "dataExceptionJson": "", + } + + def create_sql_interface( + self, + full_name: str, + en_code: str, + sql: str, + parameters: List[dict], + category: str, + action: int = 1, + db_link_id: str = "0", + ) -> str: + """创建 SQL 数据接口并返回其 ID + + 封装了 create + list 查找的两步流程。 + + Args: + 同 build_payload() 参数。 + Returns: + 创建成功后的接口 ID。 + Raises: + RuntimeError: 创建失败或列表中未找到。 + """ + payload = self.build_payload( + full_name=full_name, + en_code=en_code, + sql=sql, + parameters=parameters, + category=category, + action=action, + db_link_id=db_link_id, + ) + resp = self.create(payload) + if not resp.success: + raise RuntimeError(f"创建接口失败: {resp.msg}") + + # 创建 API 不直接返回 ID,需要通过列表查找 + list_resp = self.get_list({ + "category": category, + "keyword": en_code, + "pageSize": 10, + }) + if not list_resp.success: + raise RuntimeError(f"查询接口列表失败: {list_resp.msg}") + + for item in list_resp.data.get("list", []): + if item.get("enCode") == en_code: + return item.get("id") + + raise RuntimeError(f"接口创建成功但列表中未找到: {en_code}") + + def safe_delete(self, di_id: str) -> bool: + """安全删除接口(不抛异常) + + Returns: + True 删除成功,False 删除失败。 + """ + try: + resp = self.delete(di_id) + return resp.success + except Exception: + return False + + # ==================== 增删改扩展方法 ==================== + + def build_insert_payload( + self, + full_name: str, + en_code: str, + table_name: str, + fields: List[str], + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> dict: + """构建 INSERT 数据接口 payload + + Args: + full_name: 接口名称 + en_code: 接口编码 + table_name: 表名(不含前缀) + fields: 要插入的字段列表,如 ["f_name", "f_value"] + parameters: 参数定义列表 + category: 分类 ID + db_link_id: 数据库连接 ID + """ + field_str = ", ".join(fields) + value_placeholders = ", ".join([f"{{{f[2:]}}}" for f in fields]) # f_name -> {name} + sql = f"INSERT INTO {table_name} ({field_str}) VALUES ({value_placeholders})" + return self.build_payload( + full_name=full_name, + en_code=en_code, + sql=sql, + parameters=parameters, + category=category, + action=1, + db_link_id=db_link_id, + ) + + def build_update_payload( + self, + full_name: str, + en_code: str, + table_name: str, + set_fields: List[str], + where_field: str, + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> dict: + """构建 UPDATE 数据接口 payload + + Args: + full_name: 接口名称 + en_code: 接口编码 + table_name: 表名 + set_fields: 要更新的字段列表,如 ["f_name", "f_value"] + where_field: WHERE 条件字段(主键),如 "f_id" + parameters: 参数定义列表 + category: 分类 ID + db_link_id: 数据库连接 ID + """ + set_clause = ", ".join([f"{f} = {{{f[2:]}}}" for f in set_fields]) + sql = f"UPDATE {table_name} SET {set_clause} WHERE {where_field} = {{{where_field[2:]}}}" + return self.build_payload( + full_name=full_name, + en_code=en_code, + sql=sql, + parameters=parameters, + category=category, + action=2, + db_link_id=db_link_id, + ) + + def build_delete_payload( + self, + full_name: str, + en_code: str, + table_name: str, + where_field: str, + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> dict: + """构建 DELETE 数据接口 payload + + Args: + full_name: 接口名称 + en_code: 接口编码 + table_name: 表名 + where_field: WHERE 条件字段(主键),如 "f_id" + parameters: 参数定义列表 + category: 分类 ID + db_link_id: 数据库连接 ID + """ + sql = f"DELETE FROM {table_name} WHERE {where_field} = {{{where_field[2:]}}}" + return self.build_payload( + full_name=full_name, + en_code=en_code, + sql=sql, + parameters=parameters, + category=category, + action=4, + db_link_id=db_link_id, + ) + + def build_select_payload( + self, + full_name: str, + en_code: str, + sql: str, + parameters: List[dict], + category: str, + has_page: int = 0, + db_link_id: str = "0", + ) -> dict: + """构建 SELECT 数据接口 payload(支持分页) + + Args: + full_name: 接口名称 + en_code: 接口编码 + sql: 查询 SQL(可包含 LIMIT 和分页变量) + parameters: 参数定义列表 + category: 分类 ID + has_page: 是否分页(1=分页,0=不分页) + db_link_id: 数据库连接 ID + """ + payload = self.build_payload( + full_name=full_name, + en_code=en_code, + sql=sql, + parameters=parameters, + category=category, + action=3, + db_link_id=db_link_id, + ) + payload["hasPage"] = has_page + return payload + + def create_insert_interface( + self, + full_name: str, + en_code: str, + table_name: str, + fields: List[str], + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> str: + """创建 INSERT 数据接口""" + payload = self.build_insert_payload( + full_name, en_code, table_name, fields, parameters, category, db_link_id + ) + resp = self.create(payload) + if not resp.success: + raise RuntimeError(f"创建INSERT接口失败: {resp.msg}") + return self._find_di_id(en_code, category) + + def create_update_interface( + self, + full_name: str, + en_code: str, + table_name: str, + set_fields: List[str], + where_field: str, + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> str: + """创建 UPDATE 数据接口""" + payload = self.build_update_payload( + full_name, en_code, table_name, set_fields, where_field, parameters, category, db_link_id + ) + resp = self.create(payload) + if not resp.success: + raise RuntimeError(f"创建UPDATE接口失败: {resp.msg}") + return self._find_di_id(en_code, category) + + def create_delete_interface( + self, + full_name: str, + en_code: str, + table_name: str, + where_field: str, + parameters: List[dict], + category: str, + db_link_id: str = "0", + ) -> str: + """创建 DELETE 数据接口""" + payload = self.build_delete_payload( + full_name, en_code, table_name, where_field, parameters, category, db_link_id + ) + resp = self.create(payload) + if not resp.success: + raise RuntimeError(f"创建DELETE接口失败: {resp.msg}") + return self._find_di_id(en_code, category) + + def create_select_interface( + self, + full_name: str, + en_code: str, + sql: str, + parameters: List[dict], + category: str, + has_page: int = 0, + db_link_id: str = "0", + ) -> str: + """创建 SELECT 数据接口""" + payload = self.build_select_payload( + full_name, en_code, sql, parameters, category, has_page, db_link_id + ) + resp = self.create(payload) + if not resp.success: + raise RuntimeError(f"创建SELECT接口失败: {resp.msg}") + return self._find_di_id(en_code, category) + + def _find_di_id(self, en_code: str, category: str) -> str: + """根据编码和分类查找 DI ID""" + list_resp = self.get_list({"category": category, "keyword": en_code, "pageSize": 10}) + if not list_resp.success: + raise RuntimeError(f"查询接口列表失败: {list_resp.msg}") + for item in list_resp.data.get("list", []): + if item.get("enCode") == en_code: + return item.get("id") + raise RuntimeError(f"接口创建成功但列表中未找到: {en_code}") diff --git a/modules/data_model.py b/modules/data_model.py new file mode 100644 index 0000000..020f01e --- /dev/null +++ b/modules/data_model.py @@ -0,0 +1,199 @@ +"""数据库表管理模块 + +对应前端源码: api/systemData/dataModel.ts +提供数据库表和字段的 CRUD 操作,支持通过 DataSource 管理数据库连接。 +用于创建/查询/修改/删除数据库表、获取表字段列表等。 + +优先使用此模块(配合 DataSource)来操作数据库,而非直接执行 SQL。 +""" + +from typing import Any, Dict, Optional + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class DataModelAPI: + """数据库表管理 API + + 用法:: + + # 查询表列表 + resp = client.data_model.get_table_list("0") # 主数据库 link_id="0" + for t in resp.data.get("list", []): + print(t["table"], t["comment"]) + + # 查询表详情 + resp = client.data_model.get_table_info("0", "base_my_table") + fields = resp.data.get("tableFieldList", []) + + # 查询表字段列表 + resp = client.data_model.get_field_list("0", "base_my_table") + """ + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/DataModel" + + def get_table_list(self, link_id: str, data: dict = None) -> APIResponse: + """获取数据库表列表 + + Args: + link_id: 数据连接 ID,"0" 表示主数据库 + data: 查询参数,支持 keyword/currentPage/pageSize + """ + return self._client.request("GET", f"{self._prefix}/{link_id}/Tables", + params=data) + + def get_table_list_all(self, link_id: str, data: dict = None) -> APIResponse: + """获取数据库表列表(含视图) + + Args: + link_id: 数据连接 ID + data: 查询参数 + """ + return self._client.request("GET", f"{self._prefix}/{link_id}/TableAll", + params=data) + + def preview_table(self, link_id: str, table: str, data: dict = None) -> APIResponse: + """预览数据库表数据 + + Args: + link_id: 数据连接 ID + table: 表名 + data: 查询参数 + """ + return self._client.request("GET", f"{self._prefix}/{link_id}/Table/{table}/Preview", + params=data) + + def create_table(self, link_id: str, data: dict) -> APIResponse: + """新建数据库表 + + Args: + link_id: 数据连接 ID + data: 表定义数据 + """ + return self._client.request("POST", f"{self._prefix}/{link_id}/Table", data=data) + + def update_table(self, link_id: str, data: dict) -> APIResponse: + """修改数据库表 + + Args: + link_id: 数据连接 ID + data: 表定义数据(含表名标识) + """ + return self._client.request("PUT", f"{self._prefix}/{link_id}/Table", data=data) + + def get_table_info(self, link_id: str, table: str) -> APIResponse: + """获取数据库表详情(含字段列表) + + Args: + link_id: 数据连接 ID + table: 表名 + + Returns: + data.tableInfo: 表基本信息 {table, tableName} + data.tableFieldList: 字段列表 [{field, fieldName, dataType, dataLength, primaryKey, ...}] + """ + return self._client.request("GET", f"{self._prefix}/{link_id}/Table/{table}") + + def delete_table(self, link_id: str, table: str) -> APIResponse: + """删除数据库表 + + Args: + link_id: 数据连接 ID + table: 表名 + + 注意:如果表被功能表单引用,删除会失败。 + """ + return self._client.request("DELETE", f"{self._prefix}/{link_id}/Table/{table}") + + def get_field_list(self, link_id: str, table: str, field_type: str = "0") -> APIResponse: + """获取数据库表字段列表 + + Args: + link_id: 数据连接 ID + table: 表名 + field_type: 字段类型 (0=全部, 1=仅主表字段, 2=仅关联字段) + """ + return self._client.request("GET", + f"{self._prefix}/{link_id}/Tables/{table}/Fields", + params={"type": field_type}) + + def add_fields(self, link_id: str, data: dict) -> APIResponse: + """新增字段到数据库表 + + Args: + link_id: 数据连接 ID + data: 字段定义数据 + """ + return self._client.request("PUT", f"{self._prefix}/{link_id}/addFields", data=data) + + def export_table(self, link_id: str, table: str) -> APIResponse: + """导出数据库表结构 + + Args: + link_id: 数据连接 ID + table: 表名 + """ + return self._client.request("GET", + f"{self._prefix}/{link_id}/Table/{table}/Actions/Export") + + # ==================== 便捷查询方法 ==================== + + def query(self, link_id: str, table: str, keyword: str = "", field: str = "", + current_page: int = 1, page_size: int = 20) -> APIResponse: + """简单查询表数据(封装 Preview 接口) + + Args: + link_id: 数据连接 ID,"0"=主数据库 + table: 表名 + keyword: 关键字搜索(可选) + field: 搜索字段名(可选,如 "f_en_code") + current_page: 当前页(默认 1) + page_size: 每页条数(默认 20) + + Returns: + APIResponse,resp.data 包含: + - list: 数据列表 + - pagination: {currentPage, pageSize, total} + + 示例:: + resp = client.data_model.query("0", "base_module", keyword="admin", field="f_en_code") + for row in resp.data.get("list", []): + print(row["f_en_code"], row.get("f_full_name")) + """ + params = { + "currentPage": current_page, + "pageSize": page_size, + } + # 默认用 f_id 排序(主键雪花ID,所有表都有这个字段) + params["field"] = field if field else "f_id" + if keyword: + params["keyword"] = keyword + return self._client.request("GET", + f"{self._prefix}/{link_id}/Table/{table}/Preview", + params=params) + + def query_one(self, link_id: str, table: str, field: str, value: str) -> Optional[Dict]: + """查询单条记录 + + Args: + link_id: 数据连接 ID + table: 表名 + field: 字段名(如 "f_en_code") + value: 字段值 + + Returns: + 匹配的记录 dict,未找到返回 None + + 示例:: + record = client.data_model.query_one("0", "base_module", "f_en_code", "admin") + if record: + print(record["f_full_name"]) + """ + resp = self.query(link_id, table, keyword=value, field=field, page_size=1) + if resp.success and resp.data: + records = resp.data.get("list", []) + return records[0] if records else None + return None diff --git a/modules/data_source.py b/modules/data_source.py new file mode 100644 index 0000000..2bf0e68 --- /dev/null +++ b/modules/data_source.py @@ -0,0 +1,135 @@ +"""数据源模块 + +对应前端源码: api/systemData/dataSource.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class DataSourceAPI: + """数据源 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/DataSource" + self._sync_prefix = "/api/system/DataSync" + + def get_list(self, data: dict = None) -> APIResponse: + """获取数据连接列表""" + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self, type_: str = "") -> APIResponse: + """获取数据连接下拉框列表""" + params = {"type": type_} if type_ else {} + return self._client.request("GET", f"{self._prefix}/Selector", params=params) + + def create(self, data: dict) -> APIResponse: + """新建数据连接""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改数据连接""" + ds_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{ds_id}", data=data) + + def get_info(self, ds_id: str) -> APIResponse: + """获取数据连接信息""" + return self._client.request("GET", f"{self._prefix}/{ds_id}") + + def delete(self, ds_id: str) -> APIResponse: + """删除数据连接""" + return self._client.request("DELETE", f"{self._prefix}/{ds_id}") + + def test_connection(self, data: dict) -> APIResponse: + """测试数据连接""" + return self._client.request("POST", f"{self._prefix}/Actions/Test", data=data) + + def data_sync(self, data: dict) -> APIResponse: + """同步校验""" + return self._client.request("POST", self._sync_prefix, data=data) + + def execute(self, data: dict) -> APIResponse: + """同步数据""" + return self._client.request("POST", f"{self._sync_prefix}/Actions/Execute", data=data) + + def batch_execute(self, data: dict) -> APIResponse: + """批量同步数据""" + return self._client.request("POST", f"{self._sync_prefix}/Actions/batchExecute", data=data) + + def check_db_link(self, data: dict) -> APIResponse: + """校验数据库连接""" + return self._client.request("POST", f"{self._sync_prefix}/Actions/checkDbLink", data=data) + + # ==================== 扩展数据源接口(ssw-common) ==================== + + def create_db_link(self, full_name: str, service_name: str, + db_type: str = "MySQL", description: str = "") -> APIResponse: + """创建数据库连接(数据源,使用系统默认配置) + + Args: + full_name: 连接名称 + service_name: 服务名/数据库名 + db_type: 数据库类型 (默认 MySQL) + description: 描述 + """ + data = { + "fullName": full_name, + "dbType": db_type, + "serviceName": service_name, + "description": description, + } + return self._client.request("POST", "/api/common/dblinkExt/create", data=data) + + def get_db_link_id(self, en_code: str) -> APIResponse: + """根据编码获取数据源ID + + 注意:此 API 返回的 ID 在 msg 字段中,非 data 字段。 + + Args: + en_code: 连接编码 + + Returns: + APIResponse,data 字段为 string 类型的 ID + """ + resp = self._client.request("GET", f"/api/common/dblinkExt/id/{en_code}") + # API 返回格式:{"code": 600, "msg": "2043175204557139968", "data": null} + # ID 实际在 msg 字段中 + if resp.code == 200 and resp.msg and resp.msg.isdigit(): + resp.data = str(resp.msg) + return resp + + def test_connection_ext(self, db_type: str, host: str, port: int, + user_name: str, password: str, service_name: str) -> APIResponse: + """测试数据库连接(扩展) + + Args: + db_type: 数据库类型 + host: 主机地址 + port: 端口 + user_name: 用户名 + password: 密码 + service_name: 服务名/数据库名 + """ + data = { + "dbType": db_type, + "host": host, + "port": port, + "userName": user_name, + "password": password, + "serviceName": service_name, + } + return self._client.request("POST", "/api/common/dblinkExt/test", data=data) + + def create_database(self, db_name: str, db_type: str = "MySQL") -> APIResponse: + """创建数据库(使用系统默认配置) + + Args: + db_name: 数据库名 + db_type: 数据库类型 (默认 MySQL) + """ + data = { + "dbName": db_name, + "dbType": db_type, + } + return self._client.request("POST", "/api/common/dblinkExt/createDatabase", data=data) diff --git a/modules/dictionary.py b/modules/dictionary.py new file mode 100644 index 0000000..b7218d5 --- /dev/null +++ b/modules/dictionary.py @@ -0,0 +1,83 @@ +"""数据字典模块 + +对应前端源码: api/systemData/dictionary.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class DictionaryAPI: + """数据字典 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._data_prefix = "/api/system/DictionaryData" + self._type_prefix = "/api/system/DictionaryType" + + # ==================== 字典分类 ==================== + + def get_type_list(self) -> APIResponse: + """获取数据字典分类列表""" + return self._client.request("GET", self._type_prefix) + + def get_type_selector(self, id: str = "0") -> APIResponse: + """获取字典分类下拉框列表""" + return self._client.request("GET", f"{self._type_prefix}/Selector/{id}") + + def create_type(self, data: dict) -> APIResponse: + """添加字典分类""" + return self._client.request("POST", self._type_prefix, data=data) + + def update_type(self, data: dict) -> APIResponse: + """修改字典分类""" + type_id = data.get("id") + return self._client.request("PUT", f"{self._type_prefix}/{type_id}", data=data) + + def get_type_info(self, type_id: str) -> APIResponse: + """获取字典分类信息""" + return self._client.request("GET", f"{self._type_prefix}/{type_id}") + + def delete_type(self, type_id: str) -> APIResponse: + """删除字典分类""" + return self._client.request("DELETE", f"{self._type_prefix}/{type_id}") + + # ==================== 字典数据 ==================== + + def get_data_list(self, type_id: str, params: dict = None) -> APIResponse: + """获取数据字典分类下的数据列表""" + return self._client.request("GET", f"{self._data_prefix}/{type_id}", params=params) + + def get_all(self) -> APIResponse: + """获取数据字典列表(分类+内容)""" + return self._client.request("GET", f"{self._data_prefix}/All") + + def get_data_type_selector(self, type_id: str, is_tree: bool, id: str = "0") -> APIResponse: + """获取字典分类下拉框(项目上级)""" + return self._client.request("GET", f"{self._data_prefix}/{type_id}/Selector/{id}", + params={"isTree": is_tree}) + + def get_data_selector(self, type_id: str) -> APIResponse: + """获取字典数据下拉框列表""" + return self._client.request("GET", f"{self._data_prefix}/{type_id}/Data/Selector") + + def create_data(self, data: dict) -> APIResponse: + """添加数据字典""" + return self._client.request("POST", self._data_prefix, data=data) + + def update_data(self, data: dict) -> APIResponse: + """修改数据字典""" + data_id = data.get("id") + return self._client.request("PUT", f"{self._data_prefix}/{data_id}", data=data) + + def get_data_info(self, data_id: str) -> APIResponse: + """获取数据字典信息""" + return self._client.request("GET", f"{self._data_prefix}/{data_id}/Info") + + def delete_data(self, data_id: str) -> APIResponse: + """删除数据字典""" + return self._client.request("DELETE", f"{self._data_prefix}/{data_id}") + + def export_data(self, type_id: str) -> APIResponse: + """导出数据字典数据""" + return self._client.request("GET", f"{self._data_prefix}/{type_id}/Actions/Export") diff --git a/modules/file.py b/modules/file.py new file mode 100644 index 0000000..26b50cd --- /dev/null +++ b/modules/file.py @@ -0,0 +1,132 @@ +"""文件管理模块 + +对应前端源码: api/core/common.ts + api/teamwork/document.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class FileAPI: + """文件管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._doc_prefix = "/api/file/Document" + + # ==================== 通用文件操作 ==================== + + def get_download_url(self, file_type: str, file_name: str = "") -> APIResponse: + """获取下载文件链接""" + return self._client.request("GET", f"/api/file/Download/{file_type}/{file_name}") + + def get_pack_download_url(self, file_type: str, data: dict) -> APIResponse: + """获取打包下载链接""" + return self._client.request("POST", f"/api/file/PackDownload/{file_type}", data=data) + + def preview(self, data: dict) -> APIResponse: + """预览文件""" + return self._client.request("GET", "/api/file/Uploader/Preview", params=data) + + def chunk_merge(self, data: dict) -> APIResponse: + """分片组装""" + return self._client.request("POST", "/api/file/merge", data=data) + + def template_download(self, url: str, data: dict = None) -> APIResponse: + """下载导入示例模板""" + return self._client.request("GET", f"/api/{url}/TemplateDownload", params=data) + + def import_preview(self, url: str, data: dict = None) -> APIResponse: + """导入预览""" + return self._client.request("GET", f"/api/{url}/ImportPreview", params=data) + + def import_data(self, url: str, data: dict) -> APIResponse: + """导入数据""" + return self._client.request("POST", f"/api/{url}/ImportData", data=data) + + def get_import_exception_data(self, url: str, data: dict) -> APIResponse: + """导出错误数据""" + return self._client.request("POST", f"/api/{url}/ImportExceptionData", data=data) + + # ==================== 知识管理/文档管理 ==================== + + def get_all_list(self, data: dict = None) -> APIResponse: + """获取知识管理列表(全部文档)""" + return self._client.request("GET", self._doc_prefix, params=data) + + def create_folder(self, data: dict) -> APIResponse: + """添加文件夹""" + return self._client.request("POST", self._doc_prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改文件名/文件夹名""" + doc_id = data.get("id") + return self._client.request("PUT", f"{self._doc_prefix}/{doc_id}", data=data) + + def batch_delete(self, ids: list) -> APIResponse: + """批量删除文件/文件夹""" + return self._client.request("POST", f"{self._doc_prefix}/BatchDelete", data={"ids": ids}) + + def get_folder_tree(self, ids: list = None) -> APIResponse: + """获取知识管理列表(文件夹树)""" + return self._client.request("POST", f"{self._doc_prefix}/FolderTree", data={"ids": ids or []}) + + def get_info(self, doc_id: str) -> APIResponse: + """获取文件/文件夹信息""" + return self._client.request("GET", f"{self._doc_prefix}/{doc_id}") + + def move_to(self, to_id: str, ids: list) -> APIResponse: + """批量移动文件/文件夹""" + return self._client.request("PUT", f"{self._doc_prefix}/Actions/MoveTo/{to_id}", data={"ids": ids}) + + def share_cancel(self, ids: list) -> APIResponse: + """批量取消分享""" + return self._client.request("POST", f"{self._doc_prefix}/Actions/CancelShare", data={"ids": ids}) + + def create_share(self, ids: list, user_ids: list) -> APIResponse: + """批量分享文件/文件夹""" + return self._client.request("POST", f"{self._doc_prefix}/Actions/Share", + data={"ids": ids, "userIds": user_ids}) + + def create_single_share(self, doc_id: str, user_ids: list) -> APIResponse: + """单个分享文件/文件夹""" + return self._client.request("POST", f"{self._doc_prefix}/Actions/ShareAdjustment/{doc_id}", + data={"userIds": user_ids}) + + def get_share_out_list(self, data: dict = None) -> APIResponse: + """获取我的共享列表""" + return self._client.request("GET", f"{self._doc_prefix}/Share", params=data) + + def get_share_tome_list(self, data: dict = None) -> APIResponse: + """获取共享给我列表""" + return self._client.request("GET", f"{self._doc_prefix}/ShareTome", params=data) + + def get_share_user_list(self, document_id: str) -> APIResponse: + """获取共享人员""" + return self._client.request("GET", f"{self._doc_prefix}/ShareUser/{document_id}") + + # ==================== 回收站 ==================== + + def get_trash_list(self, data: dict = None) -> APIResponse: + """获取回收站列表""" + return self._client.request("GET", f"{self._doc_prefix}/Trash", params=data) + + def trash_delete(self, ids: list) -> APIResponse: + """回收站(批量彻底删除)""" + return self._client.request("POST", f"{self._doc_prefix}/Trash", data={"ids": ids}) + + def trash_recovery(self, ids: list) -> APIResponse: + """回收站(批量还原)""" + return self._client.request("POST", f"{self._doc_prefix}/Trash/Actions/Recovery", data={"ids": ids}) + + def pack_download(self, ids: list) -> APIResponse: + """批量下载文件""" + return self._client.request("POST", f"{self._doc_prefix}/PackDownload", data={"ids": ids}) + + def document_merge(self, data: dict) -> APIResponse: + """分片组装(知识库)""" + return self._client.request("POST", f"{self._doc_prefix}/merge", data=data) + + def upload_blob(self, data: dict) -> APIResponse: + """上传 Blob(流程归档)""" + return self._client.request("POST", f"{self._doc_prefix}/UploadBlob", data=data) diff --git a/modules/interface_oauth.py b/modules/interface_oauth.py new file mode 100644 index 0000000..6ff37b4 --- /dev/null +++ b/modules/interface_oauth.py @@ -0,0 +1,247 @@ +"""接口认证 (InterfaceOauth) 模块 + +对应前端源码: api/systemData/interfaceOauth.ts + +关键机制(基于后端源码分析): + - AppId/AppSecret 认证:外部系统通过 appId + appSecret 调用接口 + - 签名验证:verifySignature=1 时启用 HMAC-SHA256 签名验证 + - 授权接口绑定:一个 AppId 可授权访问多个数据接口 + - 用户秘钥:UserKey 用于标识调用方用户 + - 黑/白名单:IP 白名单限制,支持黑名单排除 + - 使用期限:usefulLife 可设置有效期 + +认证流程(基于 infoToIdNew 方法): + 1. 从请求头 Authorization 解析 appId 和签名 + 2. 验证 appId 有效性、接口在授权列表中、启用状态 + 3. 若 verifySignature=1:验证时间戳(1分钟内)和 HMAC-SHA256 签名 + 4. 若 verifySignature=0:仅验证 appSecret 匹配 + 5. 验证使用期限 + 6. 通过 UserKey 获取用户 token + 7. 验证 IP 白名单 + 8. 调用实际数据接口 + +参考: + - 后端: InterfaceOauthController.java, InterfaceOauthServiceImpl.java + - 后端工具: InterfaceUtil.java(签名算法) + - 前端: api/systemData/interfaceOauth.ts + - 实体: base_data_interface_oauth 表 +""" + +import json +from typing import Any, Dict, List, Optional + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class InterfaceOauthAPI: + """接口认证 API + + 提供接口认证的 CRUD 管理,以及外部系统调用数据接口的能力。 + + 典型用法:: + + oauth = InterfaceOauthAPI(client) + + # 创建认证 + oauth_id = oauth.create({ + "appId": "my_app", + "appName": "我的应用", + "appSecret": "生成的秘钥", + "verifySignature": 0, + }) + + # 绑定授权接口 + oauth.bind_interfaces(oauth_id, ["di_id_1", "di_id_2"]) + + # 外部系统调用(使用生成的 appId 和 appSecret) + # GET /api/system/DataInterface/{id}/Actions/Response + # Header: Authorization: {appId}::{signature} (verifySignature=1) + # 或 {appId}::{appSecret} (verifySignature=0) + # Header: YmDate: {timestamp} (verifySignature=1 时必需) + # Header: UserKey: {userKey} (用户标识) + """ + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/InterfaceOauth" + + # ==================== 基础 CRUD ==================== + + def get_list(self, data: dict = None) -> APIResponse: + """获取接口认证列表(分页) + + Args: + data: 查询参数,常用字段: + - currentPage, pageSize: 分页 + - keyword: 关键字搜索 + """ + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self) -> APIResponse: + """获取接口认证下拉框""" + return self._client.request("GET", f"{self._prefix}/Selector") + + def create(self, data: dict) -> APIResponse: + """新建接口认证 + + Args: + data: 认证配置,常用字段: + - appId: 应用ID(唯一) + - appName: 应用名称 + - appSecret: 秘钥(可调用 get_app_secret 获取) + - verifySignature: 0=不验签, 1=验签 + - usefulLife: 使用期限(日期,可为空表示永久) + - whiteList: IP白名单(多个用英文逗号分隔) + - enabledMark: 1=启用, 0=禁用 + """ + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改接口认证""" + oauth_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{oauth_id}", data=data) + + def get_info(self, oauth_id: str) -> APIResponse: + """获取接口认证详情(含授权接口列表和用户列表)""" + return self._client.request("GET", f"{self._prefix}/{oauth_id}") + + def delete(self, oauth_id: str) -> APIResponse: + """删除接口认证""" + return self._client.request("DELETE", f"{self._prefix}/{oauth_id}") + + # ==================== 秘钥管理 ==================== + + def get_app_secret(self) -> APIResponse: + """获取新的应用秘钥 + + Returns: + 返回新生成的 UUID 秘钥(去连字符) + """ + return self._client.request("GET", f"{self._prefix}/getAppSecret") + + # ==================== 授权管理 ==================== + + def get_interface_list(self, oauth_id: str) -> APIResponse: + """获取已授权的接口列表 + + Args: + oauth_id: 接口认证ID + """ + return self._client.request("GET", f"{self._prefix}/getInterfaceList/{oauth_id}") + + def bind_interfaces(self, oauth_id: str, interface_ids: List[str]) -> APIResponse: + """绑定授权接口 + + Args: + oauth_id: 接口认证ID + interface_ids: 数据接口ID列表 + """ + data = { + "interfaceIdentId": oauth_id, + "dataInterfaceIds": ",".join(interface_ids), + } + return self._client.request("POST", f"{self._prefix}/saveInterfaceList", data=data) + + # ==================== 用户授权 ==================== + + def get_user_list(self, oauth_id: str) -> APIResponse: + """获取授权用户列表""" + resp = self.get_info(oauth_id) + if resp.success and resp.data: + return resp.data.get("userList", []) + return [] + + def save_user_list(self, oauth_id: str, users: List[dict]) -> APIResponse: + """保存授权用户 + + Args: + oauth_id: 接口认证ID + users: 用户列表,每个元素: + - userId: 用户ID + - userKey: 用户标识 + """ + data = { + "interfaceIdentId": oauth_id, + "userList": users, + } + return self._client.request("POST", f"{self._prefix}/SaveUserList", data=data) + + # ==================== 日志 ==================== + + def get_log(self, oauth_id: str, data: dict = None) -> APIResponse: + """获取接口调用日志 + + Args: + oauth_id: 接口认证ID + data: 查询参数: + - currentPage, pageSize: 分页 + """ + return self._client.request("GET", f"{self._prefix}/dataInterfaceLog/{oauth_id}", params=data) + + # ==================== 外部调用 ==================== + + @staticmethod + def build_authorization_header(app_id: str, app_secret: str, method: str = "GET", + url_path: str = "", timestamp: int = None, + verify_signature: bool = False) -> dict: + """构建外部调用所需的请求头(仅用于参考,实际应从后端获取) + + Args: + app_id: 应用ID + app_secret: 应用秘钥 + method: 请求方法 + url_path: 请求路径(如 /api/system/DataInterface/{id}/Actions/Response) + timestamp: 时间戳(毫秒),verifySignature=1 时必需 + verify_signature: 是否启用签名验证 + + Returns: + 请求头字典,包含: + - Authorization: {appId}::{signature} 或 {appId}::{appSecret} + - YmDate: 时间戳(仅验签时) + - UserKey: 用户标识 + """ + headers = {} + + if verify_signature: + import base64 + import hmac + import hashlib + from urllib.parse import quote + + if timestamp is None: + import time + timestamp = int(time.time() * 1000) + + # 签名源字符串: method + '\n' + url + '\n' + timestamp + '\n' + host + '\n' + source = f"{method}\n{url_path}\n{timestamp}\n\n" + signature = hmac.new( + base64.b64decode(app_secret), + source.encode('utf-8'), + hashlib.sha256 + ).hexdigest() + + headers["Authorization"] = f"{app_id}::{signature}" + headers["YmDate"] = str(timestamp) + else: + headers["Authorization"] = f"{app_id}::{app_secret}" + + return headers + + # ==================== 验证示例 ==================== + # 场景1: 创建接口认证 + # secret_resp = oauth.get_app_secret() + # app_secret = secret_resp.data + # oauth.create({ + # "appId": "test_app", + # "appName": "测试应用", + # "appSecret": app_secret, + # "verifySignature": 0, + # "enabledMark": 1, + # }) + + # 场景2: 绑定授权接口 + # oauth.bind_interfaces(oauth_id, ["di_id_1", "di_id_2"]) + + # 场景3: 获取调用日志 + # logs = oauth.get_log(oauth_id, {"currentPage": 1, "pageSize": 20}) diff --git a/modules/menu.py b/modules/menu.py new file mode 100644 index 0000000..2505854 --- /dev/null +++ b/modules/menu.py @@ -0,0 +1,375 @@ +"""菜单管理模块 + +对应前端源码: api/system/menu.ts + +parentId 规则: +- "-1" 表示顶级菜单 +- 或已存在的目录菜单(type=1)的 ID +- 禁止使用 systemId! + +类型 (type): +- 1: 目录菜单 +- 2: Vue 扩展页面 +- 3: 功能表单菜单 + +编码规则 (en_code): +- 业务字母开头 ^[a-zA-Z] +- 字母+数字组成 [a-zA-Z0-9]* +- 末尾是字母 [a-zA-Z]$ +- 示例: customerList, orderMgmt, productInfo + +url_address 规则 (type=2): +- 不能为空 +- 必须以 ssw/{app_code}/ 开头 +- 示例: ssw/tdc/jyzs/AiSmartInput +""" + +import json +import random +import re +import string +import warnings + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +def _random_suffix() -> str: + return ''.join(random.choices(string.digits, k=6)) + + +def _validate_en_code_warning(en_code: str) -> None: + """校验菜单编码格式,违规则发出警告(不阻止执行)""" + if not en_code: + warnings.warn("菜单 enCode 为空") + return + if not re.match(r"^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z]$", en_code): + warnings.warn( + f"菜单 enCode '{en_code}' 不符合规范(业务字母开头,字母+数字组成,末尾是字母):" + r"^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z]$" + ) + + +def _validate_url_address_warning(url_address: str, app_code: str) -> None: + """校验 url_address 格式,违规则发出警告(不阻止执行)""" + if not url_address: + warnings.warn("create_page_menu 的 url_address 不能为空") + return + expected_prefix = f"ssw/{app_code}/" + if not url_address.startswith(expected_prefix): + warnings.warn( + f"create_page_menu 的 url_address '{url_address}' 应以 '{expected_prefix}' 开头" + ) + + +def _unique_name(api, base_name: str) -> str: + """检查名称是否已存在,存在则加随机后缀""" + try: + resp = api._client.data_model.query_one("0", "base_module", "f_full_name", base_name) + if resp: + return f"{base_name}_{_random_suffix()}" + except Exception: + pass + return base_name + + +class MenuAPI: + """菜单管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/Menu" + + # ==================== 基础 CRUD ==================== + + def get_list(self, data: dict = None) -> APIResponse: + """获取菜单列表""" + return self._client.request("GET", f"{self._prefix}/ModuleBySystem", params=data or {}) + + def get_all_menus(self) -> list: + """获取当前应用的所有菜单(扁平列表,包含目录) + + 使用 data_model.query 直接查询 base_module 表,并按 system_id 过滤。 + """ + result = [] + page = 1 + system_id = self._client.config.system_id # 数字ID,不是 app_code + while True: + resp = self._client.data_model.query("0", "base_module", + current_page=page, page_size=500) + if not resp.success or not resp.data: + break + items = resp.data.get("list", []) + if not items: + break + for item in items: + # 按 system_id 过滤 + if item.get("f_system_id") != system_id: + continue + result.append({ + "id": item.get("f_id"), + "parentId": item.get("f_parent_id"), + "type": item.get("f_type"), + "fullName": item.get("f_full_name"), + "enCode": item.get("f_en_code"), + }) + if len(items) < 500: + break + page += 1 + return result + + def get_user_menu_tree(self) -> list: + """获取当前用户可见的菜单树(从 /api/oauth/CurrentUser 获取) + + 这是用户登录后浏览器实际使用的菜单数据,包含完整的多级嵌套结构。 + 比 get_tree() 更准确,直接反映用户在界面看到的菜单。 + + Returns: + 树形结构菜单列表,每个节点包含 children 数组 + """ + import time + resp = self._client.request("GET", "/api/oauth/CurrentUser", params={ + "systemCode": self._client.app_code, + "isBackend": "0", + "_t": str(int(time.time() * 1000)) + }) + if resp.success and resp.data: + return resp.data.get("menuList", []) + return [] + + def get_children(self, parent_id: str) -> list: + """获取指定菜单的子菜单""" + tree = self.get_user_menu_tree() + + def find_children(menus, target_id): + for m in menus: + if m.get("id") == target_id: + return m.get("children", []) + if m.get("children"): + result = find_children(m.get("children"), target_id) + if result is not None: + return result + return None + + result = find_children(tree, parent_id) + return result if result is not None else [] + + def get_info(self, menu_id: str) -> APIResponse: + """获取菜单详情""" + return self._client.request("GET", f"{self._prefix}/{menu_id}") + + def create(self, data: dict) -> APIResponse: + """新建菜单""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改菜单(自动合并完整数据)""" + menu_id = data.get("id") + info = self.get_info(menu_id) + if info.code != 200: + return info + full_data = info.data.copy() + full_data.update(data) + return self._client.request("PUT", f"{self._prefix}/{menu_id}", json_data=full_data) + + def delete(self, menu_id: str) -> APIResponse: + """删除菜单(建议用 soft_delete)""" + return self._client.request("DELETE", f"{self._prefix}/{menu_id}") + + # ==================== 查询辅助 ==================== + + def get_id_by_en_code(self, en_code: str) -> str | None: + """通过编码查询菜单 ID(精确匹配,仅返回完全一致的一条)""" + try: + resp = self._client.data_model.query("0", "base_module", keyword=en_code, field="f_en_code", page_size=999) + if resp.success and resp.data: + records = resp.data.get("list", []) + # 精确匹配 en_code + for record in records: + if record.get("f_en_code") == en_code: + return record.get("f_id") + return None + except Exception: + return None + + def get_id_by_name(self, full_name: str) -> str | None: + """通过名称查询菜单 ID""" + resp = self._client.request("GET", f"{self._prefix}/Selector/0", params={"category": "Web"}) + if resp.success and resp.data: + for item in resp.data.get("list", []): + if item.get("fullName") == full_name: + return item.get("id") + return None + + def check_en_code_exists(self, en_code: str) -> bool: + """检查编码是否已存在""" + return self.get_id_by_en_code(en_code) is not None + + def check_name_exists(self, full_name: str) -> bool: + """检查名称是否已存在""" + return self.get_id_by_name(full_name) is not None + + # ==================== parentId ==================== + + def update_parent(self, menu_id: str, new_parent_id: str) -> APIResponse: + """修改菜单的父级""" + info = self.get_info(menu_id) + if info.code != 200: + return info + data = info.data.copy() + data["parentId"] = new_parent_id + return self.update(data) + + def batch_update_parent(self, menu_ids: list, new_parent_id: str) -> dict: + """批量修改父级""" + results = {"success": 0, "failed": 0} + for menu_id in menu_ids: + if self.update_parent(menu_id, new_parent_id).code == 200: + results["success"] += 1 + else: + results["failed"] += 1 + return results + + # ==================== 软删除 ==================== + + def soft_delete(self, menu_id: str) -> APIResponse: + """软删除:停用 + 改名,避免重建冲突""" + info = self.get_info(menu_id) + if info.code != 200: + return info + data = info.data.copy() + data["enabledMark"] = 0 + data["sortCode"] = 1000 + name = data.get("fullName", "") + if f"({menu_id})" not in name: + data["fullName"] = f"{name}({menu_id})" + code = data.get("enCode", "") + if f"_{menu_id}" not in code: + data["enCode"] = f"{code}_{menu_id}" + return self.update(data) + + def move_to_deleted(self, menu_ids: list) -> dict: + """批量软删除""" + return {mid: self.soft_delete(mid).code == 200 for mid in menu_ids} + + # ==================== 创建菜单 ==================== + + def _build_menu_data(self, menu_type: int, full_name: str, en_code: str, + parent_id: str, icon: str = "", sort_code: int = 0, + url_address: str = "", property_json: str = "", + category: str = "Web") -> dict: + """构建菜单数据""" + return { + "parentId": parent_id, + "fullName": _unique_name(self, full_name), + "enCode": en_code, + "type": menu_type, + "category": category, + "icon": icon, + "urlAddress": url_address, + "propertyJson": property_json or '{"ids":[]}', + "enabledMark": 1, + "sortCode": sort_code, + "isButtonAuthorize": 0, + "isColumnAuthorize": 0, + "isDataAuthorize": 0, + "isFormAuthorize": 0, + "isCollapse": False, + "noShow": 0, + } + + def _create_with_fix(self, data: dict, en_code: str, full_name: str, + parent_id: str, rename_fields: dict = None) -> APIResponse: + """创建菜单并自动修复 parentId""" + resp = self.create(data) + actual_id = self.get_id_by_en_code(en_code) + if actual_id: + rename_data = {"id": actual_id, "fullName": full_name, "enCode": en_code} + if rename_fields: + rename_data.update(rename_fields) + self.update(rename_data) + info = self.get_info(actual_id) + if info.success and info.data.get("parentId") != parent_id: + self.update_parent(actual_id, parent_id) + result = APIResponse(code=resp.code, data={"id": actual_id}, msg=resp.msg) + result.id = actual_id + return result + + def create_directory_menu(self, full_name: str, en_code: str, + icon: str = "icon-ym icon-ym-folder", + sort_code: int = 0, parent_id: str = "-1") -> APIResponse: + """创建目录菜单(type=1)""" + _validate_en_code_warning(en_code) + data = self._build_menu_data(1, full_name, en_code, parent_id, icon, sort_code) + return self._create_with_fix(data, en_code, full_name, parent_id) + + def create_form_menu(self, full_name: str, en_code: str, visual_dev_id: str, + parent_id: str, web_type: int = 2, sort_code: int = 0) -> APIResponse: + """创建功能表单菜单(type=3)""" + _validate_en_code_warning(en_code) + prop = json.dumps({"moduleId": visual_dev_id, "webType": web_type, "isTree": 0}, ensure_ascii=False) + url = f"model/{en_code}" + data = self._build_menu_data(3, full_name, en_code, parent_id, "", sort_code, url, prop) + return self._create_with_fix(data, en_code, full_name, parent_id, {"urlAddress": url}) + + def create_page_menu(self, full_name: str, en_code: str, url_address: str, + parent_id: str = "-1", icon: str = "", sort_code: int = 0, + module_id: str = None, web_type: int = 2) -> APIResponse: + """创建 Vue 页面菜单(type=2)""" + _validate_en_code_warning(en_code) + _validate_url_address_warning(url_address, self._client.app_code) + prop = json.dumps({"moduleId": module_id or "", "webType": web_type, "isTree": 0}, ensure_ascii=False) + data = self._build_menu_data(2, full_name, en_code, parent_id, icon, sort_code, url_address, prop) + return self._create_with_fix(data, en_code, full_name, parent_id) + + # ==================== 移动端 App 菜单 ==================== + + def create_app_directory_menu(self, full_name: str, en_code: str, + icon: str = "icon-ym icon-ym-folder", + sort_code: int = 0, parent_id: str = "-1") -> APIResponse: + """创建移动端目录菜单(category=App)""" + _validate_en_code_warning(en_code) + data = self._build_menu_data(1, full_name, en_code, parent_id, icon, sort_code, category="App") + resp = self.create(data) + actual_id = self.get_id_by_en_code(en_code) + if actual_id: + self.update({"id": actual_id, "fullName": full_name, "enCode": en_code}) + result = APIResponse(code=resp.code, data={"id": actual_id}, msg=resp.msg) + result.id = actual_id + return result + + def create_app_form_menu(self, full_name: str, en_code: str, form_id: str, + parent_id: str, icon: str = "icon-ym icon-ym-webForm", + sort_code: int = 0, web_type: int = 2) -> APIResponse: + """创建移动端功能菜单(category=App)""" + app_en_code = f"{en_code}_app" if not en_code.endswith("_app") else en_code + _validate_en_code_warning(app_en_code) + prop = json.dumps({"moduleId": form_id, "webType": web_type, "isTree": 0}, ensure_ascii=False) + url = f"/pages/apply/dynamicModel/index?id={form_id}" + data = self._build_menu_data(3, full_name, en_code, parent_id, icon, sort_code, url, prop, "App") + resp = self.create(data) + actual_id = self.get_id_by_en_code(en_code) + if actual_id: + self.update({"id": actual_id, "fullName": full_name, "enCode": en_code}) + result = APIResponse(code=resp.code, data={"id": actual_id}, msg=resp.msg) + result.id = actual_id + return result + + def create_app_form_menu_with_parent(self, full_name: str, en_code: str, form_id: str, + parent_name: str, parent_en_code: str, + icon: str = "icon-ym icon-ym-webForm", + sort_code: int = 0, web_type: int = 2) -> dict: + """创建移动端菜单,自动创建父目录""" + # 确保父目录存在 + parent_id = self.get_id_by_en_code(parent_en_code) + if not parent_id: + dir_resp = self.create_app_directory_menu(parent_name, parent_en_code, sort_code=0) + parent_id = dir_resp.id or self.get_id_by_en_code(parent_en_code) + + app_en_code = f"{en_code}_app" if not en_code.endswith("_app") else en_code + existing = self.get_id_by_en_code(app_en_code) + if existing: + return {"parent_id": parent_id, "menu_id": existing, "parent_created": False, "code": 200} + + resp = self.create_app_form_menu(full_name, app_en_code, form_id, parent_id, icon, sort_code, web_type) + return {"parent_id": parent_id, "menu_id": resp.id, "parent_created": False, "code": resp.code} diff --git a/modules/message.py b/modules/message.py new file mode 100644 index 0000000..0326e66 --- /dev/null +++ b/modules/message.py @@ -0,0 +1,75 @@ +"""消息公告模块 + +对应前端源码: api/system/message.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class MessageAPI: + """消息公告 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._notice_prefix = "/api/message/Notice" + self._msg_prefix = "/api/message" + + # ==================== 系统公告 ==================== + + def get_notice_list(self, data: dict) -> APIResponse: + """获取系统公告列表""" + return self._client.request("POST", f"{self._notice_prefix}/List", data=data) + + def create_notice(self, data: dict) -> APIResponse: + """新建公告""" + return self._client.request("POST", self._notice_prefix, data=data) + + def update_notice(self, data: dict) -> APIResponse: + """修改公告""" + notice_id = data.get("id") + return self._client.request("PUT", f"{self._notice_prefix}/{notice_id}", data=data) + + def get_notice_info(self, notice_id: str) -> APIResponse: + """获取公告详情""" + return self._client.request("GET", f"{self._notice_prefix}/{notice_id}") + + def delete_notice(self, notice_id: str) -> APIResponse: + """删除公告""" + return self._client.request("DELETE", f"{self._notice_prefix}/{notice_id}") + + def release_notice(self, notice_id: str) -> APIResponse: + """发布公告""" + return self._client.request("PUT", f"{self._notice_prefix}/{notice_id}/Actions/Release") + + # ==================== 消息中心 ==================== + + def get_message_list(self, data: dict = None) -> APIResponse: + """获取消息中心列表""" + return self._client.request("GET", self._msg_prefix, params=data) + + def read_all(self, data: dict = None) -> APIResponse: + """全部已读""" + return self._client.request("POST", f"{self._msg_prefix}/Actions/ReadAll", data=data or {}) + + def read_info(self, msg_id: str) -> APIResponse: + """查看消息内容""" + return self._client.request("GET", f"{self._msg_prefix}/ReadInfo/{msg_id}") + + def delete_message(self, data: dict) -> APIResponse: + """删除消息""" + return self._client.request("DELETE", f"{self._msg_prefix}/Record", data=data) + + # ==================== IM ==================== + + def get_im_reply(self, data: dict = None) -> APIResponse: + """获取 IM 对话列表""" + return self._client.request("GET", f"{self._msg_prefix}/imreply", params=data) + + def delete_chat_record(self, chat_id: str) -> APIResponse: + """删除聊天记录""" + return self._client.request("DELETE", f"{self._msg_prefix}/imreply/deleteChatRecord/{chat_id}") + + def remove_chat_record(self, chat_id: str) -> APIResponse: + """移除聊天记录""" + return self._client.request("DELETE", f"{self._msg_prefix}/imreply/relocation/{chat_id}") diff --git a/modules/online_dev.py b/modules/online_dev.py new file mode 100644 index 0000000..7646f33 --- /dev/null +++ b/modules/online_dev.py @@ -0,0 +1,63 @@ +"""OnlineDev 数据操作模块(独立引用) + +注意:OnlineDev 的数据操作 API 已整合在 visual_dev.py 的 VisualDevAPI 中。 +本模块提供面向数据操作的更便捷的接口包装。 +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse, PaginatedResponse + + +class OnlineDevAPI: + """OnlineDev 数据操作便捷 API + + 面向"以表单为中心"的数据 CRUD 操作, + 内部调用 VisualDevAPI 的对应方法。 + """ + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/visualdev/OnlineDev" + + def get_config(self, model_id: str, **kwargs) -> APIResponse: + """获取列表配置""" + return self._client.request("GET", f"{self._prefix}/{model_id}/Config", params=kwargs) + + def get_form_data(self, model_id: str) -> APIResponse: + """获取表单配置""" + return self._client.request("GET", f"{self._prefix}/{model_id}/FormData") + + def list(self, model_id: str, data: dict = None) -> APIResponse: + """获取数据列表(分页)""" + return self._client.request("POST", f"{self._prefix}/{model_id}/List", data=data or {}) + + def create(self, model_id: str, data: dict) -> APIResponse: + """新建数据记录""" + return self._client.request("POST", f"{self._prefix}/{model_id}", data=data) + + def update(self, model_id: str, record_id: str, data: dict) -> APIResponse: + """更新数据记录""" + return self._client.request("PUT", f"{self._prefix}/{model_id}/{record_id}", data=data) + + def get(self, model_id: str, record_id: str, menu_id: str = "") -> APIResponse: + """获取数据记录详情""" + return self._client.request("GET", f"{self._prefix}/{model_id}/{record_id}", + params={"menuId": menu_id}) + + def delete(self, model_id: str, record_id: str) -> APIResponse: + """删除数据记录""" + return self._client.request("DELETE", f"{self._prefix}/{model_id}/{record_id}") + + def batch_delete(self, model_id: str, ids: list) -> APIResponse: + """批量删除""" + return self._client.request("POST", f"{self._prefix}/batchDelete/{model_id}", + data={"ids": ids}) + + def export_data(self, model_id: str, data: dict = None) -> APIResponse: + """导出数据""" + return self._client.request("POST", f"{self._prefix}/{model_id}/Actions/ExportData", + data=data or {}) + + def import_template(self, model_id: str) -> APIResponse: + """获取导入模板""" + return self._client.request("GET", f"{self._prefix}/{model_id}/Template") diff --git a/modules/organize.py b/modules/organize.py new file mode 100644 index 0000000..e5f89de --- /dev/null +++ b/modules/organize.py @@ -0,0 +1,82 @@ +"""组织管理模块 + +对应前端源码: api/permission/organize.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class OrganizeAPI: + """组织管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/permission/Organize" + self._dept_prefix = "/api/permission/Organize/Department" + + def get_async_list(self, data: dict) -> APIResponse: + """获取组织列表(异步,按 parentId 加载)""" + parent_id = data.get("parentId", "0") + return self._client.request("GET", f"{self._prefix}/AsyncList/{parent_id}", params=data) + + def get_list(self, data: dict = None) -> APIResponse: + """获取组织列表""" + return self._client.request("GET", self._prefix, params=data) + + def create(self, data: dict) -> APIResponse: + """新建组织""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改组织""" + org_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{org_id}", data=data) + + def get_info(self, org_id: str) -> APIResponse: + """获取组织信息""" + return self._client.request("GET", f"{self._prefix}/{org_id}") + + def delete(self, org_id: str) -> APIResponse: + """删除组织""" + return self._client.request("DELETE", f"{self._prefix}/{org_id}") + + def get_selector(self, data: dict = None) -> APIResponse: + """获取组织下拉框列表""" + if not data: + data = {"parentId": "0"} + return self._client.request("GET", f"{self._prefix}/Selector", params=data) + + def get_selected_list(self, ids: list) -> APIResponse: + """获取选中组织基本信息""" + return self._client.request("POST", f"{self._prefix}/SelectedList", data={"ids": ids}) + + def get_organize_condition(self, ids: list) -> APIResponse: + """通过组织ID获取组织列表""" + return self._client.request("POST", f"{self._prefix}/OrganizeCondition", data={"ids": ids}) + + def get_org_and_pos_selector(self, data: dict = None) -> APIResponse: + """获取组织和岗位下拉框列表""" + if not data: + data = {"id": "0", "type": "organize"} + return self._client.request("GET", f"{self._prefix}/AsyncPosList", params=data) + + def export_excel(self, data: dict = None) -> APIResponse: + """导出组织 Excel""" + return self._client.request("GET", f"{self._prefix}/ExportData", params=data) + + def template_download(self) -> APIResponse: + """导入模板下载""" + return self._client.request("GET", f"{self._prefix}/TemplateDownload") + + def import_data(self, data: dict) -> APIResponse: + """导入""" + return self._client.request("POST", f"{self._prefix}/ImportData", data=data) + + def import_preview(self, data: dict = None) -> APIResponse: + """导入预览""" + return self._client.request("GET", f"{self._prefix}/ImportPreview", params=data) + + def export_exception_data(self, data: dict) -> APIResponse: + """导出错误数据""" + return self._client.request("POST", f"{self._prefix}/ExportExceptionData", data=data) diff --git a/modules/portal.py b/modules/portal.py new file mode 100644 index 0000000..6ea76c0 --- /dev/null +++ b/modules/portal.py @@ -0,0 +1,147 @@ +"""门户管理模块 + +对应前端源码: api/onlineDev/portal.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class PortalAPI: + """门户管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/visualdev/Portal" + self._manage_prefix = "/api/system/PortalManage" + self._dashboard_prefix = "/api/visualdev/Dashboard" + self._atlas_prefix = "/api/system/atlas" + + def get_list(self, data: dict = None) -> APIResponse: + """获取门户列表""" + return self._client.request("GET", self._prefix, params=data) + + def get_info(self, portal_id: str) -> APIResponse: + """获取门户信息""" + return self._client.request("GET", f"{self._prefix}/{portal_id}") + + def delete(self, portal_id: str) -> APIResponse: + """删除门户""" + return self._client.request("DELETE", f"{self._prefix}/{portal_id}") + + def update(self, data: dict) -> APIResponse: + """修改门户""" + portal_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{portal_id}", data=data) + + def create(self, data: dict) -> APIResponse: + """新建门户""" + return self._client.request("POST", self._prefix, data=data) + + def copy(self, portal_id: str) -> APIResponse: + """复制门户""" + return self._client.request("POST", f"{self._prefix}/{portal_id}/Actions/Copy") + + def export_portal(self, portal_id: str) -> APIResponse: + """导出门户""" + return self._client.request("POST", f"{self._prefix}/{portal_id}/Actions/Export") + + def get_selector(self, type_: str = None, system_id: str = None) -> APIResponse: + """获取门户下拉框列表""" + params = {"platform": "Web"} + if type_: + params["type"] = type_ + if system_id: + params["systemId"] = system_id + return self._client.request("GET", f"{self._prefix}/Selector", params=params) + + def get_home_portal_list(self) -> APIResponse: + """获取应用首页门户列表 + + 对应前端: getHomePortalList + GET /api/visualdev/Portal/Selector/Menu + + Returns: + APIResponse: 首页门户列表 + """ + return self._client.request("GET", f"{self._prefix}/Selector/Menu") + + def get_system_filter(self, data: dict, id_: str) -> APIResponse: + """获取应用列表(发布过滤) + + 对应前端: getSystemListFilter + GET /api/visualdev/Portal/systemFilter/{id} + + Args: + data: 查询参数 (包含 systemId 等) + id_: 门户ID + + Returns: + APIResponse: 可发布的系统列表 + """ + return self._client.request("GET", f"{self._prefix}/systemFilter/{id_}", params=data) + + def set_default(self, portal_id: str) -> APIResponse: + """切换用户门户默认显示""" + return self._client.request("PUT", f"{self._prefix}/{portal_id}/Actions/SetDefault?platform=Web") + + def get_auth_portal(self, portal_id: str, data: dict = None) -> APIResponse: + """获取门户展示数据(权限)""" + return self._client.request("GET", f"{self._prefix}/{portal_id}/auth", params=data) + + def update_custom_portal(self, portal_id: str, data: dict) -> APIResponse: + """用户拖拽后更新""" + return self._client.request("PUT", f"{self._prefix}/Custom/Save/{portal_id}", data=data) + + def release(self, portal_id: str, data: dict = None) -> APIResponse: + """发布门户""" + return self._client.request("PUT", f"{self._prefix}/Actions/release/{portal_id}", data=data or {}) + + # ==================== 仪表盘 ==================== + + def get_notice_list(self, data: dict) -> APIResponse: + """获取通知公告""" + return self._client.request("POST", f"{self._dashboard_prefix}/Notice", data=data) + + def get_email_list(self) -> APIResponse: + """获取未读邮件""" + return self._client.request("GET", f"{self._dashboard_prefix}/Email") + + # ==================== 门户管理 ==================== + + def get_manage_list(self, data: dict) -> APIResponse: + """获取门户管理列表""" + system_id = data.get("systemId", "") + return self._client.request("GET", f"{self._manage_prefix}/list/{system_id}", params=data) + + def get_manage_selector(self, data: dict) -> APIResponse: + """获取门户名称列表""" + system_id = data.get("systemId", "") + return self._client.request("GET", f"{self._prefix}/manage/Selector/{system_id}", params=data) + + def get_manage_info(self, manage_id: str) -> APIResponse: + """获取门户管理详情""" + return self._client.request("GET", f"{self._manage_prefix}/{manage_id}") + + def create_manage(self, data: dict) -> APIResponse: + """新建门户管理""" + return self._client.request("POST", self._manage_prefix, data=data) + + def update_manage(self, data: dict) -> APIResponse: + """编辑门户管理""" + manage_id = data.get("id") + return self._client.request("PUT", f"{self._manage_prefix}/{manage_id}", data=data) + + def delete_manage(self, manage_id: str) -> APIResponse: + """删除门户管理""" + return self._client.request("DELETE", f"{self._manage_prefix}/{manage_id}") + + # ==================== 地图 ==================== + + def get_atlas(self) -> APIResponse: + """获取全国省市区""" + return self._client.request("GET", self._atlas_prefix) + + def get_map_data(self, data: dict) -> APIResponse: + """获取地图 JSON""" + return self._client.request("GET", f"{self._atlas_prefix}/geojson", params=data) diff --git a/modules/position.py b/modules/position.py new file mode 100644 index 0000000..73de0cc --- /dev/null +++ b/modules/position.py @@ -0,0 +1,40 @@ +"""岗位管理模块 + +对应前端源码: api/permission/position.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class PositionAPI: + """岗位管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/permission/Position" + + def get_list(self, data: dict = None) -> APIResponse: + """获取岗位列表""" + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self, data: dict = None) -> APIResponse: + """获取岗位下拉框列表""" + return self._client.request("GET", f"{self._prefix}/Selector", params=data) + + def create(self, data: dict) -> APIResponse: + """新建岗位""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改岗位""" + pos_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{pos_id}", data=data) + + def get_info(self, pos_id: str) -> APIResponse: + """获取岗位信息""" + return self._client.request("GET", f"{self._prefix}/{pos_id}") + + def delete(self, pos_id: str) -> APIResponse: + """删除岗位""" + return self._client.request("DELETE", f"{self._prefix}/{pos_id}") diff --git a/modules/print_dev.py b/modules/print_dev.py new file mode 100644 index 0000000..a8c9bd2 --- /dev/null +++ b/modules/print_dev.py @@ -0,0 +1,84 @@ +"""打印模板模块 + +对应前端源码: api/system/printDev.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class PrintDevAPI: + """打印模板 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/printDev" + + def get_list(self, data: dict = None) -> APIResponse: + """获取打印模板列表""" + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self) -> APIResponse: + """获取打印模板下拉框列表""" + return self._client.request("GET", f"{self._prefix}/Selector") + + def get_work_selector(self, data: dict = None) -> APIResponse: + """获取打印模板业务列表""" + return self._client.request("GET", f"{self._prefix}/WorkSelector", params=data) + + def get_by_ids(self, data: dict) -> APIResponse: + """获取打印模板列表(批量ID)""" + return self._client.request("POST", f"{self._prefix}/getListOptions", data=data) + + def create(self, data: dict) -> APIResponse: + """新建打印模板""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改打印模板""" + pd_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{pd_id}", data=data) + + def get_info(self, pd_id: str) -> APIResponse: + """获取打印模板信息""" + return self._client.request("GET", f"{self._prefix}/{pd_id}") + + def delete(self, pd_id: str) -> APIResponse: + """删除打印模板""" + return self._client.request("DELETE", f"{self._prefix}/{pd_id}") + + def copy(self, pd_id: str) -> APIResponse: + """复制打印模板""" + return self._client.request("POST", f"{self._prefix}/{pd_id}/Actions/Copy") + + def export_data(self, pd_id: str) -> APIResponse: + """导出打印模板数据""" + return self._client.request("GET", f"{self._prefix}/{pd_id}/Actions/Export") + + def get_preview(self, pd_id: str) -> APIResponse: + """获取打印预览""" + return self._client.request("GET", f"{self._prefix}/{pd_id}/Actions/Preview") + + def get_batch_data(self, data: dict) -> APIResponse: + """批量打印获取数据和打印模板""" + return self._client.request("POST", f"{self._prefix}/BatchData", data=data) + + def save_version(self, data: dict) -> APIResponse: + """修改打印设计""" + return self._client.request("POST", f"{self._prefix}/Save", data=data) + + def get_version_info(self, version_id: str) -> APIResponse: + """获取打印设计详情""" + return self._client.request("GET", f"{self._prefix}/Info/{version_id}") + + def get_version_list(self, pd_id: str) -> APIResponse: + """获取打印版本""" + return self._client.request("GET", f"{self._prefix}/Version/{pd_id}") + + def delete_version(self, version_id: str) -> APIResponse: + """删除打印版本""" + return self._client.request("DELETE", f"{self._prefix}/Info/{version_id}") + + def copy_version(self, version_id: str) -> APIResponse: + """新增打印版本""" + return self._client.request("POST", f"{self._prefix}/Info/{version_id}") diff --git a/modules/report.py b/modules/report.py new file mode 100644 index 0000000..9fbd432 --- /dev/null +++ b/modules/report.py @@ -0,0 +1,94 @@ +"""Univer 报表模块 + +对应前端源码: api/onlineDev/report.ts +注意:使用 report_client(报表独立接口) +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class ReportAPI: + """Univer 报表 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/Report" + + def get_list(self, data: dict = None) -> APIResponse: + """获取报表模板列表""" + return self._client.request("GET", self._prefix, params=data, use_report_client=True) + + def create(self, data: dict) -> APIResponse: + """新建报表模板""" + return self._client.request("POST", self._prefix, data=data, use_report_client=True) + + def update(self, data: dict) -> APIResponse: + """修改报表模板""" + report_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{report_id}", data=data, use_report_client=True) + + def get_info(self, report_id: str) -> APIResponse: + """获取报表模板信息""" + return self._client.request("GET", f"{self._prefix}/{report_id}", use_report_client=True) + + def delete(self, report_id: str) -> APIResponse: + """删除报表模板""" + return self._client.request("DELETE", f"{self._prefix}/{report_id}", use_report_client=True) + + def copy(self, report_id: str) -> APIResponse: + """复制报表模板""" + return self._client.request("POST", f"{self._prefix}/{report_id}/Actions/Copy", use_report_client=True) + + def get_data(self, data: dict) -> APIResponse: + """获取数据和报表模板""" + return self._client.request("POST", f"{self._prefix}/Data", data=data, use_report_client=True) + + def save_version(self, data: dict) -> APIResponse: + """修改报表设计""" + return self._client.request("POST", f"{self._prefix}/Save", data=data, use_report_client=True) + + def get_version_info(self, version_id: str) -> APIResponse: + """获取报表设计详情""" + return self._client.request("GET", f"{self._prefix}/Info/{version_id}", use_report_client=True) + + def get_version_list(self, report_id: str) -> APIResponse: + """获取报表版本""" + return self._client.request("GET", f"{self._prefix}/Version/{report_id}", use_report_client=True) + + def delete_version(self, version_id: str) -> APIResponse: + """删除报表版本""" + return self._client.request("DELETE", f"{self._prefix}/Info/{version_id}", use_report_client=True) + + def copy_version(self, version_id: str) -> APIResponse: + """新增报表版本""" + return self._client.request("POST", f"{self._prefix}/Info/{version_id}", use_report_client=True) + + def get_preview_design(self, report_id: str, data: dict = None) -> APIResponse: + """预览设计""" + return self._client.request("POST", f"{self._prefix}/data/{report_id}/preview", + data=data or {}, use_report_client=True) + + def get_preview_template(self, report_id: str, data: dict = None) -> APIResponse: + """预览设计(通过报表大ID获取)""" + return self._client.request("POST", f"{self._prefix}/data/{report_id}/previewTemplate", + data=data or {}, use_report_client=True) + + def get_selector(self) -> APIResponse: + """获取报表下拉框列表""" + return self._client.request("GET", f"{self._prefix}/Selector", use_report_client=True) + + def get_release_menu(self, report_id: str) -> APIResponse: + """获取已发布菜单""" + return self._client.request("GET", f"{self._prefix}/{report_id}/getReleaseMenu", + use_report_client=True) + + def create_menu(self, report_id: str, data: dict) -> APIResponse: + """生成菜单""" + return self._client.request("POST", f"{self._prefix}/{report_id}/Actions/Module", + data=data, use_report_client=True) + + def get_preview_query_list(self, report_id: str) -> APIResponse: + """获取查询条件(通过报表大ID获取)""" + return self._client.request("GET", f"{self._prefix}/data/{report_id}/getQueryList", + use_report_client=True) diff --git a/modules/role.py b/modules/role.py new file mode 100644 index 0000000..c959e88 --- /dev/null +++ b/modules/role.py @@ -0,0 +1,64 @@ +"""角色管理模块 + +对应前端源码: api/permission/role.ts, api/permission/roleRelation.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class RoleAPI: + """角色管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/permission/Role" + self._relation_prefix = "/api/permission/RoleRelation" + + def get_list(self, data: dict = None) -> APIResponse: + """获取角色列表""" + return self._client.request("GET", self._prefix, params=data) + + def get_selector(self, type_: str = "", is_system=None) -> APIResponse: + """获取角色下拉框列表""" + params = {} + if type_: + params["type"] = type_ + if is_system is not None: + params["isSystem"] = is_system + return self._client.request("GET", f"{self._prefix}/Selector", params=params) + + def create(self, data: dict) -> APIResponse: + """新建角色""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改角色""" + role_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{role_id}", data=data) + + def get_info(self, role_id: str) -> APIResponse: + """获取角色信息""" + return self._client.request("GET", f"{self._prefix}/{role_id}") + + def delete(self, role_id: str) -> APIResponse: + """删除角色""" + return self._client.request("DELETE", f"{self._prefix}/{role_id}") + + def get_role_by_condition(self, data: dict) -> APIResponse: + """获取选中角色基本信息""" + return self._client.request("POST", f"{self._prefix}/RoleCondition", data=data) + + # ==================== 角色关联 ==================== + + def create_role_relation(self, data: dict) -> APIResponse: + """创建角色关联""" + return self._client.request("POST", self._relation_prefix, data=data) + + def delete_role_relation(self, relation_id: str) -> APIResponse: + """删除角色关联""" + return self._client.request("DELETE", f"{self._relation_prefix}/{relation_id}") + + def get_role_relation_list(self, data: dict = None) -> APIResponse: + """获取角色关联列表""" + return self._client.request("GET", self._relation_prefix, params=data) diff --git a/modules/sys_config.py b/modules/sys_config.py new file mode 100644 index 0000000..a4ba0cf --- /dev/null +++ b/modules/sys_config.py @@ -0,0 +1,82 @@ +"""系统配置模块 + +对应前端源码: api/system/sysConfig.ts +""" + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class SysConfigAPI: + """系统配置 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/system/SysConfig" + self._syn_prefix = "/api/system/SynThirdInfo" + + def get_config(self) -> APIResponse: + """获取系统配置""" + return self._client.request("GET", self._prefix) + + def update(self, data: dict) -> APIResponse: + """更新系统配置""" + return self._client.request("PUT", self._prefix, data=data) + + def test_qy(self, data: dict, type_: str) -> APIResponse: + """测试企业微信配置连接""" + return self._client.request("POST", f"{self._prefix}/{type_}/testQyWebChatConnect", data=data) + + def test_ding(self, data: dict) -> APIResponse: + """测试钉钉配置连接""" + return self._client.request("POST", f"{self._prefix}/testDingTalkConnect", data=data) + + def get_admin_list(self) -> APIResponse: + """获取系统管理员""" + return self._client.request("GET", f"{self._prefix}/getAdminList") + + def set_admin_list(self, data: dict) -> APIResponse: + """设置系统管理员""" + return self._client.request("PUT", f"{self._prefix}/setAdminList", data=data) + + def get_socials_config(self) -> APIResponse: + """获取第三方同步配置""" + return self._client.request("GET", f"{self._prefix}/socials") + + def update_socials_config(self, data: dict) -> APIResponse: + """更新第三方同步配置""" + return self._client.request("PUT", f"{self._prefix}/socials", data=data) + + # ==================== 第三方同步 ==================== + + def syn_organize_to_ding(self, type_: str, department_id: str) -> APIResponse: + """同步组织到钉钉""" + return self._client.request("GET", f"{self._syn_prefix}/synAllOrganizeSysToDing", + params={"type": type_, "departmentId": department_id}) + + def syn_user_to_ding(self, type_: str, department_id: str) -> APIResponse: + """同步用户到钉钉""" + return self._client.request("GET", f"{self._syn_prefix}/synAllUserSysToDing", + params={"type": type_, "departmentId": department_id}) + + def syn_organize_to_qy(self, type_: str, department_id: str) -> APIResponse: + """同步组织到企业微信""" + return self._client.request("GET", f"{self._syn_prefix}/synAllOrganizeSysToQy", + params={"type": type_, "departmentId": department_id}) + + def syn_user_to_qy(self, type_: str, department_id: str) -> APIResponse: + """同步用户到企业微信""" + return self._client.request("GET", f"{self._syn_prefix}/synAllUserSysToQy", + params={"type": type_, "departmentId": department_id}) + + def get_syn_data(self, type_: str) -> APIResponse: + """获取第三方同步统计信息 (1=企业微信, 2=钉钉)""" + return self._client.request("GET", f"{self._syn_prefix}/getSynThirdTotal/{type_}") + + def clear_syn(self, type_: str) -> APIResponse: + """解除第三方同步""" + return self._client.request("GET", f"{self._syn_prefix}/clearAllSyn", params={"type": type_}) + + def get_handle_num(self, data: dict) -> APIResponse: + """获取同步失败/未同步原因""" + return self._client.request("GET", f"{self._syn_prefix}/getHandleNum", params=data) diff --git a/modules/user.py b/modules/user.py new file mode 100644 index 0000000..53e9c40 --- /dev/null +++ b/modules/user.py @@ -0,0 +1,123 @@ +"""用户管理模块 + +对应前端源码: api/permission/user.ts +""" + +from typing import Optional, List +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class UserAPI: + """用户管理 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/permission/Users" + + def get_list(self, params: dict = None) -> APIResponse: + """获取用户列表(分页)""" + return self._client.request("GET", self._prefix, params=params) + + def get_selector(self, data: dict = None) -> APIResponse: + """获取用户下拉框列表""" + return self._client.request("GET", f"{self._prefix}/Selector", params=data) + + def create(self, data: dict) -> APIResponse: + """新建用户""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改用户""" + user_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{user_id}", data=data) + + def get_info(self, user_id: str) -> APIResponse: + """获取用户信息""" + return self._client.request("GET", f"{self._prefix}/{user_id}") + + def delete(self, user_id: str) -> APIResponse: + """删除用户""" + return self._client.request("DELETE", f"{self._prefix}/{user_id}") + + def batch_delete(self, data: dict) -> APIResponse: + """批量删除用户""" + return self._client.request("POST", f"{self._prefix}/BatchDelete", data=data) + + def reset_password(self, user_id: str, data: dict = None) -> APIResponse: + """重置用户密码""" + return self._client.request("POST", f"{self._prefix}/{user_id}/Actions/ResetPassword", data=data or {}) + + def batch_update_state(self, data: dict) -> APIResponse: + """批量更新用户状态""" + return self._client.request("POST", f"{self._prefix}/BatchUpdateState", data=data) + + def unlock(self, user_id: str) -> APIResponse: + """解除锁定""" + return self._client.request("PUT", f"{self._prefix}/{user_id}/Actions/unlock") + + def get_user_info_list(self, ids: list) -> APIResponse: + """获取用户基本信息""" + return self._client.request("POST", f"{self._prefix}/getUserList", data={"ids": ids}) + + def export_excel(self, data: dict = None) -> APIResponse: + """导出用户 Excel""" + return self._client.request("GET", f"{self._prefix}/ExportData", params=data) + + def template_download(self) -> APIResponse: + """用户导入模板下载""" + return self._client.request("GET", f"{self._prefix}/TemplateDownload") + + def import_data(self, data: dict) -> APIResponse: + """导入用户""" + return self._client.request("POST", f"{self._prefix}/ImportData", data=data) + + def import_preview(self, data: dict = None) -> APIResponse: + """导入预览""" + return self._client.request("GET", f"{self._prefix}/ImportPreview", params=data) + + def export_exception_data(self, data: dict) -> APIResponse: + """导出错误数据""" + return self._client.request("POST", f"{self._prefix}/ExportExceptionData", data=data) + + def get_selected_list(self, ids: list) -> APIResponse: + """获取选中组织/岗位/角色/用户基本信息""" + return self._client.request("POST", f"{self._prefix}/getSelectedList", data={"ids": ids}) + + def get_work_by_user(self, data: dict = None) -> APIResponse: + """获取离职交接数据""" + return self._client.request("GET", f"{self._prefix}/getWorkByUser", params=data) + + def work_handover(self, data: dict) -> APIResponse: + """工作交接""" + return self._client.request("POST", f"{self._prefix}/workHandover", data=data) + + def get_receive_user_list(self, data: dict = None) -> APIResponse: + """获取用户列表(同部门/同岗位/同公司)""" + return self._client.request("GET", f"{self._prefix}/ReceiveUserList", params=data) + + def get_same_pos_user(self, data: dict) -> APIResponse: + """通过用户ID获取相同岗位用户""" + user_id = data.get("id") + return self._client.request("GET", f"{self._prefix}/{user_id}/SelectorByUserPosId", params=data) + + def get_user_position(self, user_id: str) -> APIResponse: + """获取用户岗位""" + return self._client.request("GET", f"{self._prefix}/{user_id}/GetPosition") + + def set_user_position(self, data: dict) -> APIResponse: + """设置用户岗位""" + user_id = data.get("id") + return self._client.request("POST", f"{self._prefix}/{user_id}/SetPosition", data=data) + + def batch_set_user_position(self, data: dict) -> APIResponse: + """批量设置用户岗位""" + return self._client.request("POST", f"{self._prefix}/SetPositionBatch", data=data) + + def get_auth_group(self, data: dict = None) -> APIResponse: + """获取权限分组""" + return self._client.request("GET", f"{self._prefix}/getAllPermission", params=data) + + def get_auth_list(self, data: dict = None) -> APIResponse: + """用户查看权限""" + return self._client.request("GET", f"{self._prefix}/Authorize", params=data) diff --git a/modules/visual_dev.py b/modules/visual_dev.py new file mode 100644 index 0000000..8ac6146 --- /dev/null +++ b/modules/visual_dev.py @@ -0,0 +1,330 @@ +"""可视化开发核心模块 + +对应前端源码: api/onlineDev/visualDev.ts +包含功能 CRUD、发布、复制、配置获取、代码生成、AI 表单、OCR 等 +""" + +import json +from typing import Optional + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class VisualDevAPI: + """可视化开发 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._prefix = "/api/visualdev/Base" + self._online_prefix = "/api/visualdev/OnlineDev" + self._gen_prefix = "/api/visualdev/Generater" + self._personal_prefix = "/api/visualdev/personal" + self._log_prefix = "/api/visualdev/OnlineLog" + + # ==================== 功能 CRUD ==================== + + def get_list(self, data: dict = None) -> APIResponse: + """获取功能列表""" + return self._client.request("GET", self._prefix, params=data) + + # ==================== 重复检查 ==================== + + def check_en_code_exists(self, en_code: str) -> bool: + """检查功能编码是否已存在 + + Args: + en_code: 功能编码 + + Returns: + True=已存在,False=不存在 + """ + resp = self.get_list({"keyword": en_code, "currentPage": 1, "pageSize": 20}) + if resp.code != 200: + return False + for item in resp.data.get("list", []): + if item.get("enCode") == en_code: + return True + return False + + def check_name_exists(self, full_name: str) -> bool: + """检查功能名称是否已存在 + + Args: + full_name: 功能名称 + + Returns: + True=已存在,False=不存在 + """ + resp = self.get_list({"keyword": full_name, "currentPage": 1, "pageSize": 20}) + if resp.code != 200: + return False + for item in resp.data.get("list", []): + if item.get("fullName") == full_name: + return True + return False + + def get_id_by_en_code(self, en_code: str) -> Optional[str]: + """通过编码查询功能 ID + + Args: + en_code: 功能编码 + + Returns: + 功能 ID,未找到返回 None + """ + resp = self.get_list({"keyword": en_code, "currentPage": 1, "pageSize": 20}) + if resp.code != 200: + return None + for item in resp.data.get("list", []): + if item.get("enCode") == en_code: + return item.get("id") + return None + + def get_form_list(self, data: dict = None) -> APIResponse: + """获取功能列表(集成助手用)""" + return self._client.request("GET", f"{self._prefix}/list", params=data) + + def create(self, data: dict) -> APIResponse: + """新建功能""" + return self._client.request("POST", self._prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """修改功能""" + func_id = data.get("id") + return self._client.request("PUT", f"{self._prefix}/{func_id}", data=data) + + def get_info(self, func_id: str) -> APIResponse: + """获取功能详情""" + return self._client.request("GET", f"{self._prefix}/{func_id}") + + def delete(self, func_id: str) -> APIResponse: + """删除功能""" + return self._client.request("DELETE", f"{self._prefix}/{func_id}") + + def soft_delete(self, func_id: str) -> APIResponse: + """软删除功能 - 修改属性使其不可见且不冲突 + + 由于 JNPF 平台删除后重新创建同名/同编码功能会提示已存在, + 此方法通过以下方式软删除: + 1. 功能名加上 ID 后缀(避免名称冲突) + 2. en_code 改为 func_{id}(避免编码冲突) + 3. sortCode 设为极大值(沉底,不影响正常查看) + + Args: + func_id: 要删除的功能 ID + + Returns: + APIResponse + """ + resp = self.get_info(func_id) + if resp.code != 200: + return resp + + data = resp.data.copy() + + # 名称加 ID 后缀 + original_name = data.get("fullName", "") + if f"({func_id})" not in original_name: + data["fullName"] = f"{original_name}({func_id})" + + # en_code 改为 func_{id} + data["enCode"] = f"func_{func_id}" + + # 排序码沉底 + data["sortCode"] = 999999 + + return self.update(data) + + def copy(self, func_id: str) -> APIResponse: + """复制功能""" + return self._client.request("POST", f"{self._prefix}/{func_id}/Actions/Copy") + + def release(self, func_id: str) -> APIResponse: + """发布功能(复制到 base_visual_release,state 设为 1)""" + return self._client.request("POST", f"{self._prefix}/{func_id}/Actions/Release") + + def get_release_menu(self, func_id: str) -> APIResponse: + """获取已发布菜单""" + return self._client.request("GET", f"{self._prefix}/{func_id}/getReleaseMenu") + + def create_menu(self, func_id: str, data: dict) -> APIResponse: + """生成菜单""" + return self._client.request("POST", f"{self._prefix}/{func_id}/Actions/Module", data=data) + + def get_form_data_fields(self, func_id: str, filter_type: int = 0) -> APIResponse: + """获取表单主表属性列表""" + return self._client.request("GET", f"{self._prefix}/{func_id}/FormDataFields", + params={"filterType": filter_type}) + + def get_field_data_select(self, data: dict) -> APIResponse: + """获取表单主表数据下拉框""" + model_id = data.get("modelId") + return self._client.request("GET", f"{self._prefix}/{model_id}/FieldDataSelect", params=data) + + def get_selector(self, data: dict = None) -> APIResponse: + """获取功能下拉框列表""" + return self._client.request("GET", f"{self._prefix}/Selector", params=data) + + def get_column_list(self, data: dict) -> APIResponse: + """获取列表字段""" + return self._client.request("GET", f"{self._prefix}/getColumnList", params=data) + + def get_list_by_system(self, data: dict) -> APIResponse: + """获取跨应用菜单""" + return self._client.request("GET", f"{self._prefix}/getListBySystem", params=data) + + # ==================== OnlineDev 数据操作 ==================== + + def get_config(self, model_id: str, data: dict = None) -> APIResponse: + """获取列表表单配置 JSON""" + return self._client.request("GET", f"{self._online_prefix}/{model_id}/Config", params=data) + + def get_config_by_menu_id(self, data: dict = None) -> APIResponse: + """通过菜单 ID 获取列表表单配置 JSON""" + return self._client.request("GET", f"{self._online_prefix}/Config", params=data) + + def get_form_data(self, model_id: str) -> APIResponse: + """获取表单配置 JSON""" + return self._client.request("GET", f"{self._online_prefix}/{model_id}/FormData") + + def get_model_list(self, model_id: str, data: dict) -> APIResponse: + """获取数据列表""" + return self._client.request("POST", f"{self._online_prefix}/{model_id}/List", data=data) + + def create_model(self, model_id: str, data: dict, menu_id: str = "") -> APIResponse: + """新建数据 + + 注意:JNPF API 返回不包含 data 字段,此方法会通过查询列表最近一条数据id,非常微弱几率可能有覆盖情况 + 自动补充返回的 id 属性。 + """ + payload = {"data": json.dumps(data, ensure_ascii=False)} + if menu_id: + payload["menuId"] = menu_id + resp = self._client.request("POST", f"{self._online_prefix}/{model_id}", data=payload) + + # JNPF create API 不返回 data/id,通过查询列表补充 + if resp.success: + list_resp = self.get_model_list(model_id, {"currentPage": 1, "pageSize": 1}) + if list_resp.success and list_resp.data: + records = list_resp.data.get("list", []) + if records: + resp.id = records[0].get("id") + resp.data = {"id": resp.id} + return resp + + def update_model(self, model_id: str, data: dict) -> APIResponse: + """修改数据""" + record_id = data.get("id") + payload = {"id": record_id, "data": json.dumps(data, ensure_ascii=False)} + return self._client.request("PUT", f"{self._online_prefix}/{model_id}/{record_id}", data=payload) + + def get_model_info(self, model_id: str, record_id: str, menu_id: str = "") -> APIResponse: + """获取数据详情""" + return self._client.request("GET", f"{self._online_prefix}/{model_id}/{record_id}", + params={"menuId": menu_id}) + + def delete_model(self, model_id: str, record_id: str) -> APIResponse: + """删除数据""" + return self._client.request("DELETE", f"{self._online_prefix}/{model_id}/{record_id}") + + def batch_delete_model(self, model_id: str, data: dict) -> APIResponse: + """批量删除数据""" + return self._client.request("POST", f"{self._online_prefix}/batchDelete/{model_id}", data=data) + + def get_data_change(self, model_id: str, data: dict) -> APIResponse: + """获取数据详情(变更对比)""" + return self._client.request("POST", f"{self._online_prefix}/{model_id}/DataChange", data=data) + + def export_model_data(self, model_id: str, data: dict) -> APIResponse: + """导出数据""" + return self._client.request("POST", f"{self._online_prefix}/{model_id}/Actions/ExportData", data=data) + + def get_template(self, model_id: str) -> APIResponse: + """下载导入模板""" + return self._client.request("GET", f"{self._online_prefix}/{model_id}/Template") + + def export_data(self, model_id: str) -> APIResponse: + """导出模板""" + return self._client.request("POST", f"{self._online_prefix}/{model_id}/Actions/Export") + + def launch_flow(self, model_id: str, data: dict) -> APIResponse: + """自定义按钮发起流程""" + return self._client.request("POST", f"{self._online_prefix}/{model_id}/actionLaunchFlow", data=data) + + def get_relation_query(self, data: dict) -> APIResponse: + """获取关联查询数据列表""" + return self._client.request("POST", f"{self._online_prefix}/RelationQuery", data=data) + + def get_data_log_list(self, data: dict) -> APIResponse: + """获取修改记录列表""" + return self._client.request("GET", self._log_prefix, params=data) + + # ==================== 个人视图 ==================== + + def get_view_list(self, data: dict) -> APIResponse: + """获取视图列表""" + return self._client.request("GET", self._personal_prefix, params=data) + + def create_view(self, data: dict) -> APIResponse: + """新建视图""" + return self._client.request("POST", self._personal_prefix, data=data) + + def update_view(self, data: dict) -> APIResponse: + """修改视图""" + view_id = data.get("id") + return self._client.request("PUT", f"{self._personal_prefix}/{view_id}", data=data) + + def delete_view(self, view_id: str, menu_id: str) -> APIResponse: + """删除视图""" + return self._client.request("DELETE", f"{self._personal_prefix}/{view_id}?menuId={menu_id}") + + def set_default_view(self, view_id: str, menu_id: str) -> APIResponse: + """设置默认视图""" + return self._client.request("PUT", f"{self._personal_prefix}/{view_id}/setDefault?menuId={menu_id}") + + # ==================== 代码生成(基础)==================== + + def download_code(self, func_id: str, data: dict = None) -> APIResponse: + """下载代码""" + params = data or {} + return self._client.request("POST", f"{self._gen_prefix}/{func_id}/Actions/DownloadCode", data=params) + + 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) + + # ==================== AI / OCR / 跨应用 ==================== + + def get_ai_info(self, data: dict) -> APIResponse: + """获取 AI 字段(AI 表单生成)""" + return self._client.request("POST", "/api/visualdev/ai/form", data=data) + + def get_ocr_data(self, data: dict) -> APIResponse: + """OCR 识别""" + return self._client.request("POST", "/api/visualdev/ocr", data=data) + + def get_share_list(self) -> APIResponse: + """获取跨应用表单列表""" + return self._client.request("GET", "/api/visualdev/share") + + def get_share_info(self, ids: list) -> APIResponse: + """获取跨应用表单详情""" + return self._client.request("POST", "/api/visualdev/share/SelectedList", data={"ids": ids}) + + def save_share(self, data: dict) -> APIResponse: + """保存跨应用回显""" + return self._client.request("POST", "/api/visualdev/share/save", data=data) + + def get_share_selector(self) -> APIResponse: + """获取功能下拉框列表(包含跨应用表单)""" + return self._client.request("GET", "/api/visualdev/share/Selector") \ No newline at end of file diff --git a/modules/workflow.py b/modules/workflow.py new file mode 100644 index 0000000..fbe74fe --- /dev/null +++ b/modules/workflow.py @@ -0,0 +1,2021 @@ +"""工作流模块 + +对应前端源码: + api/workFlow/task.ts - 流程任务/审批操作 + api/workFlow/template.ts - 流程模板/版本/Webhook + api/workFlow/formDesign.ts - 表单设计 + api/workFlow/flowDelegate.ts - 流程委托 + api/workFlow/flowMonitor.ts - 流程监控 + api/workFlow/trigger.ts - 触发器 + views/workFlow/workFlowForm/dynamicForm/ - 动态表单发起 + views/workFlow/components/FlowParser.vue - 流程解析/事件分发 + views/onlineDev/flowEngine/ - 流程设计器 + components/FlowProcess/ - BPMN 流程组件 + jnpf-bpmn/lib/helper/defaultXml.ts - 默认 BPMN XML 模板 + jnpf-bpmn/lib/utils/nodeUtil.ts - 节点工具(自动网关等) +""" + +import json +import urllib.parse +from typing import Any, Dict, List, Optional + +from aibridge.client import JNPFClient +from aibridge.models import APIResponse + + +class WorkflowAPI: + """工作流 API""" + + def __init__(self, client: JNPFClient): + self._client = client + self._task_prefix = "/api/workflow/task" + self._operator_prefix = "/api/workflow/operator" + self._template_prefix = "/api/workflow/template" + self._comment_prefix = "/api/workflow/comment" + self._webhook_prefix = "/api/workflow/Hooks" + self._delegate_prefix = "/api/workflow/FlowDelegate" + self._monitor_prefix = "/api/workflow/FlowMonitor" + self._trigger_prefix = "/api/workflow/Trigger" + self._form_design_prefix = "/api/workflow/FormDesign" + + # ==================== 流程任务 ==================== + + def get_launch_list(self, data: dict = None) -> APIResponse: + """获取流程发起列表""" + return self._client.request("GET", self._task_prefix, params=data) + + def get_task_info(self, task_id: str, data: dict = None) -> APIResponse: + """获取待我审批详情""" + return self._client.request("GET", f"{self._task_prefix}/{task_id}", params=data) + + def create(self, data: dict) -> APIResponse: + """新建流程发起(填写表单并发起)""" + return self._client.request("POST", self._task_prefix, data=data) + + def update(self, data: dict) -> APIResponse: + """更新流程发起""" + task_id = data.get("id") + return self._client.request("PUT", f"{self._task_prefix}/{task_id}", data=data) + + def delete(self, task_id: str) -> APIResponse: + """删除流程发起""" + return self._client.request("DELETE", f"{self._task_prefix}/{task_id}") + + def launch_recall(self, task_id: str, data: dict = None) -> APIResponse: + """流程发起撤回""" + return self._client.request("PUT", f"{self._task_prefix}/Recall/{task_id}", data=data or {}) + + def revoke(self, task_id: str, data: dict = None) -> APIResponse: + """流程发起撤销""" + return self._client.request("PUT", f"{self._task_prefix}/Revoke/{task_id}", data=data or {}) + + def press(self, task_id: str) -> APIResponse: + """流程发起催办""" + return self._client.request("POST", f"{self._task_prefix}/Press/{task_id}") + + def get_event_log(self, task_id: str) -> APIResponse: + """获取事件日志""" + return self._client.request("GET", f"{self._task_prefix}/{task_id}/EventLog") + + def get_task_user_list(self, data: dict) -> APIResponse: + """获取流程实例相关人员(分页)""" + return self._client.request("GET", f"{self._task_prefix}/TaskUserList/{data['taskId']}", params=data) + + def get_sub_flow_info(self, node_code: str, flow_id: str) -> APIResponse: + """查看子流程""" + return self._client.request("GET", f"{self._task_prefix}/SubFlowInfo", + params={"taskId": flow_id, "nodeCode": node_code}) + + def get_start_form_info(self, task_id: str) -> APIResponse: + """查看发起节点表单""" + return self._client.request("GET", f"{self._task_prefix}/ViewStartForm/{task_id}") + + def retry_outside(self, node_id: str) -> APIResponse: + """外部节点重试""" + return self._client.request("GET", f"{self._task_prefix}/Hooks/Retry/{node_id}") + + # ==================== 审批操作 ==================== + + def get_before_list(self, category: str, data: dict = None) -> APIResponse: + """获取待我审核列表""" + return self._client.request("GET", f"{self._operator_prefix}/List/{category}", params=data) + + def audit(self, operator_id: str, data: dict) -> APIResponse: + """审核(同意/拒绝)""" + return self._client.request("POST", f"{self._operator_prefix}/Audit/{operator_id}", data=data) + + def sign(self, operator_id: str) -> APIResponse: + """签收""" + return self.batch_sign({"ids": [operator_id], "type": 0}) + + def cancel_sign(self, operator_id: str) -> APIResponse: + """退签""" + return self.batch_sign({"ids": [operator_id], "type": 1}) + + def batch_sign(self, data: dict) -> APIResponse: + """批量签收/退签""" + return self._client.request("POST", f"{self._operator_prefix}/Sign", data=data) + + def handle(self, operator_id: str) -> APIResponse: + """开始办理""" + return self.batch_handle({"ids": [operator_id]}) + + def batch_handle(self, data: dict) -> APIResponse: + """批量办理""" + return self._client.request("POST", f"{self._operator_prefix}/Transact", data=data) + + def save_audit(self, operator_id: str, data: dict) -> APIResponse: + """暂存审批""" + return self._client.request("POST", f"{self._operator_prefix}/SaveAudit/{operator_id}", data=data) + + def assist(self, operator_id: str, data: dict) -> APIResponse: + """协办""" + return self._client.request("POST", f"{self._operator_prefix}/Assist/{operator_id}", data=data) + + def save_assist(self, operator_id: str, data: dict) -> APIResponse: + """协办保存""" + return self._client.request("POST", f"{self._operator_prefix}/AssistSave/{operator_id}", data=data) + + def audit_recall(self, operator_id: str, data: dict) -> APIResponse: + """撤回审核""" + return self._client.request("POST", f"{self._operator_prefix}/Recall/{operator_id}", data=data) + + def transfer(self, operator_id: str, data: dict) -> APIResponse: + """转审""" + return self._client.request("POST", f"{self._operator_prefix}/Transfer/{operator_id}", data=data) + + def back(self, operator_id: str, data: dict) -> APIResponse: + """退回审核""" + return self._client.request("POST", f"{self._operator_prefix}/SendBack/{operator_id}", data=data) + + def get_back_node_list(self, operator_id: str) -> APIResponse: + """获取退回下拉接口""" + return self._client.request("GET", f"{self._operator_prefix}/SendBackNodeList/{operator_id}") + + def free_approver(self, operator_id: str, data: dict) -> APIResponse: + """加签""" + return self._client.request("POST", f"{self._operator_prefix}/AddSign/{operator_id}", data=data) + + def reduce_approver(self, operator_id: str, data: dict) -> APIResponse: + """减签""" + return self._client.request("POST", f"{self._operator_prefix}/ReduceApprover/{operator_id}", data=data) + + def get_candidate_user(self, data: dict) -> APIResponse: + """获取候选人列表""" + operator_id = data.pop("operatorId", 0) + return self._client.request("POST", f"{self._operator_prefix}/CandidateUser/{operator_id}", data=data) + + def get_candidates(self, operator_id: str, data: dict) -> APIResponse: + """判断是否有候选人""" + return self._client.request("POST", f"{self._operator_prefix}/CandidateNode/{operator_id}", data=data) + + def batch_operation(self, data: dict) -> APIResponse: + """批量审批(0-通过 1-退回 2-转审)""" + return self._client.request("POST", f"{self._operator_prefix}/BatchOperation", data=data) + + def get_batch_candidate(self, data: dict = None) -> APIResponse: + """获取批量审批候选人""" + return self._client.request("GET", f"{self._operator_prefix}/BatchCandidate", params=data) + + def get_batch_flow_selector(self) -> APIResponse: + """获取批量审批流程""" + return self._client.request("GET", f"{self._operator_prefix}/BatchFlowSelector") + + def get_batch_version_selector(self, flow_id: str) -> APIResponse: + """获取批量审批流程版本""" + return self._client.request("GET", f"{self._operator_prefix}/BatchVersionSelector/{flow_id}") + + def get_batch_node_selector(self, flow_id: str) -> APIResponse: + """获取批量审批流程节点""" + return self._client.request("GET", f"{self._operator_prefix}/BatchNodeSelector/{flow_id}") + + def get_batch_node(self, flow_id: str, node_code: str) -> APIResponse: + """获取批量审批流程节点属性""" + return self._client.request("GET", f"{self._operator_prefix}/BatchNode", + params={"flowId": flow_id, "nodeCode": node_code}) + + def check_info(self, task_operator_id: str, op_type: str) -> APIResponse: + """判断是否有查看权限""" + return self._client.request("GET", f"{self._operator_prefix}/{task_operator_id}/Info", + params={"opType": op_type}) + + def get_record_list(self, task_id: str, node_id: str) -> APIResponse: + """进度节点经办列表""" + return self._client.request("GET", f"{self._operator_prefix}/RecordList", + params={"taskId": task_id, "nodeId": node_id}) + + def get_circulate_list(self, task_id: str, node_id: str) -> APIResponse: + """抄送人员""" + return self._client.request("GET", f"{self._operator_prefix}/CirculateList", + params={"taskId": task_id, "nodeId": node_id}) + + # ==================== 流程模板 ==================== + + def get_template_list(self, data: dict = None) -> APIResponse: + """获取流程模板列表(分页)""" + return self._client.request("GET", self._template_prefix, params=data) + + def get_flow_list(self, form_id: str) -> APIResponse: + """通过表单 ID 获取流程列表""" + return self._client.request("GET", f"{self._template_prefix}/{form_id}/FlowList") + + def create_template(self, data: dict) -> APIResponse: + """新建流程模板""" + return self._client.request("POST", self._template_prefix, data=data) + + def update_template(self, data: dict) -> APIResponse: + """修改流程模板""" + template_id = data.get("id") + return self._client.request("PUT", f"{self._template_prefix}/{template_id}", data=data) + + def get_template_info(self, template_id: str) -> APIResponse: + """获取流程模板信息""" + return self._client.request("GET", f"{self._template_prefix}/{template_id}") + + def delete_template(self, template_id: str) -> APIResponse: + """删除流程模板""" + return self._client.request("DELETE", f"{self._template_prefix}/{template_id}") + + def copy_template(self, template_id: str) -> APIResponse: + """复制流程模板""" + return self._client.request("POST", f"{self._template_prefix}/{template_id}/Actions/Copy") + + def export_template(self, template_id: str) -> APIResponse: + """导出流程模板""" + return self._client.request("GET", f"{self._template_prefix}/{template_id}/Actions/Export") + + def save_flow(self, data: dict) -> APIResponse: + """保存流程设计""" + return self._client.request("POST", f"{self._template_prefix}/Save", data=data) + + def get_flow_info(self, flow_id: str) -> APIResponse: + """获取流程引擎设计详情(含 flowNodes 中各节点的 formId) + + 注意:参数 flow_id 是 templateJson 实体 ID(即 version_id / flowId), + 不是 template_id。可通过 get_version_list(template_id) 获取 version_id。 + 后端对应 TemplateJsonServiceImpl.getInfoVo(flowId)。 + """ + return self._client.request("GET", f"{self._template_prefix}/Info/{flow_id}") + + def get_version_list(self, template_id: str) -> APIResponse: + """获取流程引擎版本列表""" + return self._client.request("GET", f"{self._template_prefix}/Version/{template_id}") + + def delete_version(self, version_id: str) -> APIResponse: + """删除流程版本""" + return self._client.request("DELETE", f"{self._template_prefix}/Info/{version_id}") + + def copy_version(self, version_id: str) -> APIResponse: + """新增流程版本""" + return self._client.request("POST", f"{self._template_prefix}/Info/{version_id}") + + def get_flow_selector(self, data: dict = None) -> APIResponse: + """列表流程列表(分页)""" + return self._client.request("GET", f"{self._template_prefix}/Selector", params=data) + + def get_flow_form_info(self, template_id: str) -> APIResponse: + """获取流程发起节点表单信息(小流程ID)""" + return self._client.request("GET", f"{self._template_prefix}/{template_id}/FormInfo") + + def get_flow_start_form_info(self, template_id: str) -> APIResponse: + """获取流程发起节点表单信息(大流程ID)""" + return self._client.request("GET", f"{self._template_prefix}/StartForm/{template_id}") + + def get_flow_start_form_id(self, template_id: str) -> APIResponse: + """获取流程版本ID和发起节点表单ID(大流程ID)""" + return self._client.request("GET", f"{self._template_prefix}/StartFormId/{template_id}") + + def get_tree_list(self, form_type: str = "") -> APIResponse: + """所属流程列表(树形)""" + return self._client.request("GET", f"{self._template_prefix}/TreeList", + params={"formType": form_type}) + + def change_type(self, template_id: str) -> APIResponse: + """简单流程切换为标准流程""" + return self._client.request("PUT", f"{self._template_prefix}/{template_id}/UpdateType") + + def get_collect_flow_list(self, data: dict = None) -> APIResponse: + """获取收藏流程列表""" + return self._client.request("GET", f"{self._template_prefix}/getCommonFlowList", params=data) + + def set_collect_flow(self, template_id: str) -> APIResponse: + """收藏/取消收藏流程""" + return self._client.request("POST", f"{self._template_prefix}/SetCommonFlow/{template_id}") + + def up_down_shelf(self, data: dict) -> APIResponse: + """上架/下架""" + template_id = data.get("id") + return self._client.request("PUT", f"{self._template_prefix}/{template_id}/UpDownShelf", data=data) + + def get_decision_parameter(self, template_id: str) -> APIResponse: + """获取决策参数""" + return self._client.request("GET", f"{self._template_prefix}/{template_id}/DecisionParameter") + + # ==================== 流程评论 ==================== + + def get_comment_list(self, data: dict) -> APIResponse: + """获取流程评论列表""" + return self._client.request("GET", self._comment_prefix, params=data) + + def create_comment(self, data: dict) -> APIResponse: + """新建流程评论""" + return self._client.request("POST", self._comment_prefix, data=data) + + def delete_comment(self, comment_id: str) -> APIResponse: + """删除流程评论""" + return self._client.request("DELETE", f"{self._comment_prefix}/{comment_id}") + + # ==================== Webhook ==================== + + def get_webhook_url(self, data: dict) -> APIResponse: + """获取 Webhook URL""" + return self._client.request("GET", f"{self._webhook_prefix}/getUrl", params=data) + + def get_webhook_params(self, random_str: str) -> APIResponse: + """获取 Webhook 字段""" + return self._client.request("GET", f"{self._webhook_prefix}/getParams/{random_str}") + + def webhook_start(self, flow_id: str, random_str: str) -> APIResponse: + """Webhook 开启接收请求""" + return self._client.request("GET", f"{self._webhook_prefix}/{flow_id}/start/{random_str}") + + # ==================== 流程委托 ==================== + + def get_delegate_list(self, data: dict = None) -> APIResponse: + """获取流程委托列表""" + return self._client.request("GET", self._delegate_prefix, params=data) + + # ==================== 流程监控 ==================== + + def get_monitor_list(self, data: dict = None) -> APIResponse: + """获取流程监控列表""" + return self._client.request("GET", self._monitor_prefix, params=data) + + # ==================== 高级便捷方法 ==================== + + @staticmethod + def build_simple_flow_xml() -> str: + """获取简单流程默认 BPMN XML + + 来源: jnpf-bpmn/lib/helper/defaultXml.ts -> simpleDefaultXml + 结构: StartEvent(Event_0oz4pwh) -> UserTask(Activity_1qf73gq) -> EndEvent(Event_0zlhfee) + + Returns: + URL 编码后的 BPMN XML 字符串(后端 saveFlow 接口期望的格式) + """ + xml = """ + + + + Flow_1iadlmn + + + Flow_1iadlmn + Flow_1kz1x8a + + + + Flow_1kz1x8a + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + return urllib.parse.quote(xml) + + @staticmethod + def build_simple_flow_nodes( + form_id: str, + form_name: str = "", + approver_name: str = "部门审批", + approver_user_ids: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """构建简单流程的 flowNodes 配置 + + 参考: FlowProcess/src/helper/config.ts 中的 defaultGlobalForm/defaultStartForm/defaultApproverForm/defaultEndForm + + Args: + form_id: 关联的可视化开发表单 ID + form_name: 表单名称 + approver_name: 审批节点名称 + approver_user_ids: 审批人用户 ID 列表 + + Returns: + flowNodes 字典 + """ + approvers = [ + {"id": uid, "type": "user"} + for uid in (approver_user_ids or []) + ] + + return { + "global": { + "type": "global", + "nodeId": "global", + "allFormMap": {}, + "allDecisionMap": {}, + "formId": form_id, + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "titleContent": "", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "hasCommentDeletedTips": True, + "hasSignFor": False, + "hasAloneConfigureForms": False, + "hasContinueAfterReject": False, + "hasInitiatorPressOverdueNode": True, + "autoSubmitConfig": { + "adjacentNodeApproverRepeated": False, + "ApproverHasApproval": False, + "initiatorApproverRepeated": False, + }, + "recallRule": 1, + "errorRule": 1, + "errorRuleUser": [], + "fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""}, + "globalParameterList": [], + "publicParameterList": [], + "approvalFieldList": [], + "isShowConditions": True, + "showNameType": 0, + "connectList": ["Flow_1iadlmn", "Flow_1kz1x8a"], + }, + "Event_0oz4pwh": { + "type": "start", + "nodeId": "Event_0oz4pwh", + "nodeName": "流程发起", + "formId": form_id, + "formName": form_name, + "formOperates": [], + "divideRule": "inclusion", + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24}, + "noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5}, + "waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "freeNode": False, + }, + "Activity_1qf73gq": { + "type": "approver", + "nodeId": "Activity_1qf73gq", + "nodeName": approver_name, + "formId": form_id, + "formName": form_name, + "formOperates": [], + "assignList": [], + "assigneeType": 6, + "approverType": 1, + "managerApproverType": 1, + "managerLevel": 1, + "formFieldType": 1, + "formField": "", + "approverNodeId": "", + "prevNodeList": [], + "approvers": approvers, + "approversSortList": [], + "extraRule": 1, + "counterSign": 0, + "counterSignConfig": { + "auditType": 1, "auditRatio": 100, "auditNum": 1, + "rejectType": 0, "rejectRatio": 10, "rejectNum": 1, + "calculateType": 1, + }, + "circulateUser": [], + "extraCopyRule": 1, + "isCustomCopy": False, + "isInitiatorCopy": False, + "isFormFieldCopy": False, + "copyFormFieldType": 1, + "copyFormField": "", + "hasOpinion": True, + "opinionRequired": False, + "hasSign": False, + "hasFile": False, + "hasApprovalField": False, + "approvalField": [], + "hasAuditBtn": True, + "auditBtnText": "同意", + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": False, + "freeApproverBtnText": "加签", + "hasReduceApproverBtn": False, + "reduceApproverBtnText": "减签", + "hasTransferBtn": False, + "transferBtnText": "转审", + "hasAssistBtn": False, + "assistBtnText": "协办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", + "backType": 1, + "backNodeCode": 0, + "customBtns": [], + "auxiliaryInfo": [], + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "parameterList": [], + "hasAutoApprover": False, + "autoAuditRule": {"conditions": [], "matchLogic": "and"}, + "autoRejectRule": {"conditions": [], "matchLogic": "and"}, + "divideRule": "inclusion", + "interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []}, + "approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "content": "", + "timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""}, + "overTimeConfig": { + "on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, + "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, + "overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2, + "overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [], + "reApprovers": "", "overTimeExtraRule": 3, + }, + "noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "isCandidates": False, + "approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1}, + "approvalNumber": 1, + "oneSelfEndApproval": True, + "freeNode": False, + }, + "Event_0zlhfee": { + "type": "end", + "nodeId": "Event_0zlhfee", + "nodeName": "结束节点", + "endParameterList": [], + }, + } + + def create_simple_flow( + self, + full_name: str, + en_code: str, + form_id: str, + approver_user_ids: List[str], + form_name: str = "", + flow_type: int = 1, + description: str = "", + icon: str = "icon-ym icon-ym-flow", + release_immediately: bool = True, + ) -> Dict[str, str]: + """一键创建简单流程模板并保存设计 + + 整合 create_template + get_version_list + save_flow 三个步骤。 + + Args: + full_name: 流程名称 + en_code: 流程编码 + form_id: 关联的可视化开发表单 ID + approver_user_ids: 审批人用户 ID 列表 + form_name: 表单名称(显示用) + flow_type: 流程类型 0=标准 1=简单 2=任务 3=自由 4=决策 + description: 流程说明 + icon: 流程图标 + release_immediately: 是否立即发布(type=1 in saveFlow) + + Returns: + dict: { + "template_id": 模板 ID, + "version_id": 版本 ID, + } + + Raises: + RuntimeError: 任一步骤失败 + """ + # 1. 创建模板(必须包含 flowXml/flowNodes/flowConfig, + # 否则后端 flowUtil.create() 解析 flowNodes 时 NPE, + # 导致 templateJson 条目未创建,后续 save_flow 报 "数据不存在") + flow_xml = self.build_simple_flow_xml() + flow_nodes = self.build_simple_flow_nodes(form_id, form_name, approver_user_ids=approver_user_ids) + flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False) + + resp = self.create_template({ + "fullName": full_name, + "enCode": en_code, + "type": flow_type, + "category": "", + "icon": icon, + "iconBackground": "#008cff", + "showType": 0, + "sortCode": 0, + "description": description, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + }) + if not resp.success: + raise RuntimeError(f"创建流程模板失败: {resp.msg}") + template_id = resp.id + + # 2. 获取版本 ID + resp = self.get_version_list(template_id) + if not resp.success or not resp.data: + raise RuntimeError(f"获取版本列表失败: {resp.msg}") + version_id = resp.data[0]["id"] + + # 3. 保存流程设计(复用已构建的 flowXml/flowNodes/flowConfig) + resp = self.save_flow({ + "id": template_id, + "flowId": version_id, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + "type": 1 if release_immediately else 0, + }) + if not resp.success: + raise RuntimeError(f"保存流程设计失败: {resp.msg}") + + return { + "template_id": template_id, + "version_id": version_id, + } + + def launch_task(self, flow_version_id: str, form_data: dict, + urgent: int = 1, draft: bool = False) -> APIResponse: + """快捷发起流程 + + Args: + flow_version_id: 流程版本 ID(通过 get_version_list 获取) + form_data: 表单数据(dict 直接传给后端,后端 FlowHandleModel.formData 为 Map) + urgent: 紧急程度 1=普通 + draft: 是否暂存(False=直接提交) + + Returns: + APIResponse: 包含任务 ID + """ + data = { + "flowId": flow_version_id, + "status": 0 if draft else 1, + "flowUrgent": urgent, + "isFlow": 1, # 使用整数 1 而非布尔值 True,避免 Java 反序列化失败 + "formData": form_data, + } + return self.create(data) + + def approve(self, operator_id: str, opinion: str = "同意") -> APIResponse: + """快捷审批通过 + + Args: + operator_id: 待审批操作 ID(从 get_before_list 获取的 taskOperatorId) + opinion: 审批意见 + + Returns: + APIResponse + """ + return self.audit(operator_id, { + "status": 1, # 1=同意 + "handleOpinion": opinion, + "sign": "", + }) + + def reject(self, operator_id: str, opinion: str = "不同意") -> APIResponse: + """快捷审批拒绝 + + Args: + operator_id: 待审批操作 ID + opinion: 审批意见 + + Returns: + APIResponse + """ + return self.audit(operator_id, { + "status": 2, # 2=拒绝 + "handleOpinion": opinion, + "sign": "", + }) + + def get_pending_tasks(self, page: int = 1, page_size: int = 20) -> List[dict]: + """快捷获取待审批列表 + + Args: + page: 页码 + page_size: 每页数量 + + Returns: + 任务列表 + """ + resp = self.get_before_list("1", { + "currentPage": page, + "pageSize": page_size, + }) + if not resp.success: + return [] + return resp.data.get("list", []) + + # ==================== 标准流程 (type=0) ==================== + + @staticmethod + def build_standard_flow_xml() -> str: + """获取标准流程默认 BPMN XML + + 标准流程只有一个空的 StartEvent,用户需要在流程设计器中自行添加节点和连线。 + 不需要 URL 编码(后端直接解析 XML 字符串)。 + + Returns: + BPMN XML 字符串 + """ + return """ + + + + + + + + + + + +""" + + @staticmethod + def build_standard_flow_nodes( + form_id: str, + form_name: str = "", + ) -> Dict[str, Any]: + """构建标准流程的 flowNodes 配置 + + 标准流程只有一个发起节点,用户需要在流程设计器中自行添加审批节点。 + + Args: + form_id: 关联的可视化开发表单 ID + form_name: 表单名称 + + Returns: + flowNodes 字典 + """ + return { + "global": { + "type": "global", + "nodeId": "global", + "allFormMap": {}, + "allDecisionMap": {}, + "formId": form_id, + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "titleContent": "", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "hasCommentDeletedTips": True, + "hasSignFor": False, + "hasAloneConfigureForms": False, + "hasContinueAfterReject": False, + "hasInitiatorPressOverdueNode": True, + "autoSubmitConfig": { + "adjacentNodeApproverRepeated": False, + "ApproverHasApproval": False, + "initiatorApproverRepeated": False, + }, + "recallRule": 1, + "errorRule": 1, + "errorRuleUser": [], + "fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""}, + "globalParameterList": [], + "publicParameterList": [], + "approvalFieldList": [], + "isShowConditions": True, + "showNameType": 0, + "connectList": [], + }, + "Event_04q7xii": { + "type": "start", + "nodeId": "Event_04q7xii", + "nodeName": "流程发起", + "formId": form_id, + "formName": form_name, + "formOperates": [], + "divideRule": "inclusion", + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24}, + "noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5}, + "waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "freeNode": False, + }, + } + + def create_standard_flow( + self, + full_name: str, + en_code: str, + form_id: str, + form_name: str = "", + description: str = "", + icon: str = "icon-ym icon-ym-flow", + ) -> Dict[str, str]: + """创建标准流程模板 + + 标准流程只有一个发起节点,用户需要在流程设计器中自行添加审批节点和连线。 + + Args: + full_name: 流程名称 + en_code: 流程编码 + form_id: 关联的可视化开发表单 ID + form_name: 表单名称(显示用) + description: 流程说明 + icon: 流程图标 + + Returns: + dict: { + "template_id": 模板 ID, + "version_id": 版本 ID, + } + """ + flow_xml = self.build_standard_flow_xml() + flow_nodes = self.build_standard_flow_nodes(form_id, form_name) + flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False) + + resp = self.create_template({ + "fullName": full_name, + "enCode": en_code, + "type": 0, # 标准流程 + "category": "", + "icon": icon, + "iconBackground": "#008cff", + "showType": 0, + "sortCode": 0, + "description": description, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + }) + if not resp.success: + raise RuntimeError(f"创建标准流程模板失败: {resp.msg}") + + template_id = resp.id + + resp = self.get_version_list(template_id) + if not resp.success or not resp.data: + raise RuntimeError(f"获取版本列表失败: {resp.msg}") + version_id = resp.data[0]["id"] + + resp = self.save_flow({ + "id": template_id, + "flowId": version_id, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + "type": 0, + }) + if not resp.success: + raise RuntimeError(f"保存流程设计失败: {resp.msg}") + + return { + "template_id": template_id, + "version_id": version_id, + } + + # ==================== 任务流程 (type=2) ==================== + + @staticmethod + def build_task_flow_xml() -> str: + """获取任务流程默认 BPMN XML + + 任务流程结构: StartEvent -> UserTask -> EndEvent(与简单流程相同,但节点类型不同) + 需要 URL 编码。 + + Returns: + URL 编码后的 BPMN XML 字符串 + """ + xml = """ + + + + Flow_1iadlmn + + + Flow_1iadlmn + Flow_1kz1x8a + + + + Flow_1kz1x8a + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + return urllib.parse.quote(xml) + + @staticmethod + def build_task_flow_nodes( + form_id: str, + form_name: str = "", + handler_name: str = "任务处理", + handler_user_ids: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """构建任务流程的 flowNodes 配置 + + 任务流程与简单流程类似,但节点类型为 'processing'(办理节点)而非 'approver'(审批节点)。 + + Args: + form_id: 关联的可视化开发表单 ID + form_name: 表单名称 + handler_name: 任务节点名称 + handler_user_ids: 任务处理人用户 ID 列表 + + Returns: + flowNodes 字典 + """ + handlers = [ + {"id": uid, "type": "user"} + for uid in (handler_user_ids or []) + ] + + return { + "global": { + "type": "global", + "nodeId": "global", + "allFormMap": {}, + "allDecisionMap": {}, + "formId": form_id, + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "titleContent": "", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "hasCommentDeletedTips": True, + "hasSignFor": False, + "hasAloneConfigureForms": False, + "hasContinueAfterReject": False, + "hasInitiatorPressOverdueNode": True, + "autoSubmitConfig": { + "adjacentNodeApproverRepeated": False, + "ApproverHasApproval": False, + "initiatorApproverRepeated": False, + }, + "recallRule": 1, + "errorRule": 1, + "errorRuleUser": [], + "fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""}, + "globalParameterList": [], + "publicParameterList": [], + "approvalFieldList": [], + "isShowConditions": True, + "showNameType": 0, + "connectList": ["Flow_1iadlmn", "Flow_1kz1x8a"], + }, + "Event_0oz4pwh": { + "type": "start", + "nodeId": "Event_0oz4pwh", + "nodeName": "流程发起", + "formId": form_id, + "formName": form_name, + "formOperates": [], + "divideRule": "inclusion", + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24}, + "noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5}, + "waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "freeNode": False, + }, + "Activity_1qf73gq": { + "type": "processing", + "nodeId": "Activity_1qf73gq", + "nodeName": handler_name, + "formId": form_id, + "formName": form_name, + "formOperates": [], + "assignList": [], + "assigneeType": 6, + "approverType": 1, + "managerApproverType": 1, + "managerLevel": 1, + "formFieldType": 1, + "formField": "", + "approverNodeId": "", + "prevNodeList": [], + "approvers": handlers, + "approversSortList": [], + "extraRule": 1, + "counterSign": 0, + "counterSignConfig": { + "auditType": 1, "auditRatio": 100, "auditNum": 1, + "rejectType": 0, "rejectRatio": 10, "rejectNum": 1, + "calculateType": 1, + }, + "circulateUser": [], + "extraCopyRule": 1, + "isCustomCopy": False, + "isInitiatorCopy": False, + "isFormFieldCopy": False, + "copyFormFieldType": 1, + "copyFormField": "", + "hasOpinion": True, + "opinionRequired": False, + "hasSign": False, + "hasFile": False, + "hasApprovalField": False, + "approvalField": [], + "hasAuditBtn": True, + "auditBtnText": "确认办理", + "hasBackBtn": False, + "backBtnText": "退回", + "hasTransferBtn": False, + "transferBtnText": "转办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", + "backType": 1, + "backNodeCode": 0, + "customBtns": [], + "auxiliaryInfo": [], + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "parameterList": [], + "hasAutoApprover": False, + "autoAuditRule": {"conditions": [], "matchLogic": "and"}, + "autoRejectRule": {"conditions": [], "matchLogic": "and"}, + "divideRule": "inclusion", + "interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []}, + "backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "content": "", + "timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""}, + "overTimeConfig": { + "on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, + "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, + "overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2, + "overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [], + "reApprovers": "", "overTimeExtraRule": 3, + }, + "noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "isCandidates": False, + "approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1}, + "approvalNumber": 1, + "oneSelfEndApproval": True, + "freeNode": False, + }, + "Event_0zlhfee": { + "type": "end", + "nodeId": "Event_0zlhfee", + "nodeName": "结束节点", + "endParameterList": [], + }, + } + + def create_task_flow( + self, + full_name: str, + en_code: str, + form_id: str, + handler_user_ids: List[str], + form_name: str = "", + description: str = "", + icon: str = "icon-ym icon-ym-flow", + ) -> Dict[str, str]: + """创建任务流程模板 + + 任务流程与简单流程类似,但使用办理节点(processing)而非审批节点(approver)。 + + Args: + full_name: 流程名称 + en_code: 流程编码 + form_id: 关联的可视化开发表单 ID + handler_user_ids: 任务处理人用户 ID 列表 + form_name: 表单名称 + description: 流程说明 + icon: 流程图标 + + Returns: + dict: { + "template_id": 模板 ID, + "version_id": 版本 ID, + } + """ + flow_xml = self.build_task_flow_xml() + flow_nodes = self.build_task_flow_nodes(form_id, form_name, handler_user_ids=handler_user_ids) + flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False) + + resp = self.create_template({ + "fullName": full_name, + "enCode": en_code, + "type": 2, # 任务流程 + "category": "", + "icon": icon, + "iconBackground": "#008cff", + "showType": 0, + "sortCode": 0, + "description": description, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + }) + if not resp.success: + raise RuntimeError(f"创建任务流程模板失败: {resp.msg}") + template_id = resp.id + + resp = self.get_version_list(template_id) + if not resp.success or not resp.data: + raise RuntimeError(f"获取版本列表失败: {resp.msg}") + version_id = resp.data[0]["id"] + + resp = self.save_flow({ + "id": template_id, + "flowId": version_id, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + "type": 0, + }) + if not resp.success: + raise RuntimeError(f"保存流程设计失败: {resp.msg}") + + return { + "template_id": template_id, + "version_id": version_id, + } + + # ==================== 自由流程 (type=3) ==================== + + @staticmethod + def build_free_flow_xml() -> str: + """获取自由流程默认 BPMN XML + + 自由流程与简单流程结构相同(StartEvent -> UserTask -> EndEvent), + 但节点 ID 不同,且布局为横向。 + 需要 URL 编码。 + + Returns: + URL 编码后的 BPMN XML 字符串 + """ + xml = """ + + + + Flow_026otk8 + + + Flow_026otk8 + Flow_0hyov7e + + + + + Flow_0hyov7e + + + + + + + + + + + + + + + + + + + + + + + + + +""" + return urllib.parse.quote(xml) + + @staticmethod + def build_free_flow_nodes( + form_id: str, + form_name: str = "", + approver_name: str = "自由审批", + approver_user_ids: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """构建自由流程的 flowNodes 配置 + + 自由流程使用自由节点(freeNode: true),允许自由选择后续审批人。 + + Args: + form_id: 关联的可视化开发表单 ID + form_name: 表单名称 + approver_name: 审批节点名称 + approver_user_ids: 审批人用户 ID 列表 + + Returns: + flowNodes 字典 + """ + approvers = [ + {"id": uid, "type": "user"} + for uid in (approver_user_ids or []) + ] + + return { + "global": { + "type": "global", + "nodeId": "global", + "allFormMap": {}, + "allDecisionMap": {}, + "formId": form_id, + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "titleContent": "", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "hasCommentDeletedTips": True, + "hasSignFor": False, + "hasAloneConfigureForms": False, + "hasContinueAfterReject": False, + "hasInitiatorPressOverdueNode": True, + "autoSubmitConfig": { + "adjacentNodeApproverRepeated": False, + "ApproverHasApproval": False, + "initiatorApproverRepeated": False, + }, + "recallRule": 1, + "errorRule": 1, + "errorRuleUser": [], + "fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""}, + "globalParameterList": [], + "publicParameterList": [], + "approvalFieldList": [], + "isShowConditions": True, + "showNameType": 0, + "connectList": ["Flow_026otk8", "Flow_0hyov7e"], + }, + "Event_04q7xii": { + "type": "start", + "nodeId": "Event_04q7xii", + "nodeName": "流程发起", + "formId": form_id, + "formName": form_name, + "formOperates": [], + "divideRule": "inclusion", + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24}, + "noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5}, + "waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "freeNode": False, + }, + "Activity_0x7jbm1": { + "type": "free", + "nodeId": "Activity_0x7jbm1", + "nodeName": approver_name, + "approvalNumber": 10, + "oneSelfEndApproval": True, + "formId": form_id, + "formName": form_name, + "formOperates": [], + "assignList": [], + "assigneeType": 6, + "approverType": 1, + "managerApproverType": 1, + "managerLevel": 1, + "formFieldType": 1, + "formField": "", + "approverNodeId": "", + "prevNodeList": [], + "approvers": approvers, + "approversSortList": [], + "extraRule": 1, + "counterSign": 0, + "counterSignConfig": { + "auditType": 1, "auditRatio": 100, "auditNum": 1, + "rejectType": 0, "rejectRatio": 10, "rejectNum": 1, + "calculateType": 1, + }, + "circulateUser": [], + "extraCopyRule": 1, + "isCustomCopy": False, + "isInitiatorCopy": False, + "isFormFieldCopy": False, + "copyFormFieldType": 1, + "copyFormField": "", + "hasOpinion": True, + "opinionRequired": False, + "hasSign": False, + "hasFile": False, + "hasApprovalField": False, + "approvalField": [], + "hasAuditBtn": True, + "auditBtnText": "同意", + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": True, + "freeApproverBtnText": "加签", + "hasReduceApproverBtn": False, + "reduceApproverBtnText": "减签", + "hasTransferBtn": False, + "transferBtnText": "转审", + "hasAssistBtn": False, + "assistBtnText": "协办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", + "backType": 1, + "backNodeCode": 0, + "customBtns": [], + "auxiliaryInfo": [], + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "parameterList": [], + "hasAutoApprover": False, + "autoAuditRule": {"conditions": [], "matchLogic": "and"}, + "autoRejectRule": {"conditions": [], "matchLogic": "and"}, + "divideRule": "inclusion", + "interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []}, + "approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "content": "", + "timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""}, + "overTimeConfig": { + "on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, + "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, + "overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2, + "overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [], + "reApprovers": "", "overTimeExtraRule": 3, + }, + "noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "isCandidates": False, + "approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1}, + "approvalNumber": 10, + "oneSelfEndApproval": True, + "freeNode": True, + }, + "Event_06nxded": { + "type": "end", + "nodeId": "Event_06nxded", + "nodeName": "结束节点", + "endParameterList": [], + }, + } + + def create_free_flow( + self, + full_name: str, + en_code: str, + form_id: str, + approver_user_ids: Optional[List[str]] = None, + form_name: str = "", + description: str = "", + icon: str = "icon-ym icon-ym-flow", + ) -> Dict[str, str]: + """创建自由流程模板 + + 自由流程使用自由节点,允许在审批过程中动态添加审批人。 + + Args: + full_name: 流程名称 + en_code: 流程编码 + form_id: 关联的可视化开发表单 ID + approver_user_ids: 审批人用户 ID 列表(可选,初始审批人) + form_name: 表单名称 + description: 流程说明 + icon: 流程图标 + + Returns: + dict: { + "template_id": 模板 ID, + "version_id": 版本 ID, + } + """ + flow_xml = self.build_free_flow_xml() + flow_nodes = self.build_free_flow_nodes(form_id, form_name, approver_user_ids=approver_user_ids) + flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False) + + resp = self.create_template({ + "fullName": full_name, + "enCode": en_code, + "type": 3, # 自由流程 + "category": "", + "icon": icon, + "iconBackground": "#008cff", + "showType": 0, + "sortCode": 0, + "description": description, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + }) + if not resp.success: + raise RuntimeError(f"创建自由流程模板失败: {resp.msg}") + template_id = resp.id + + resp = self.get_version_list(template_id) + if not resp.success or not resp.data: + raise RuntimeError(f"获取版本列表失败: {resp.msg}") + version_id = resp.data[0]["id"] + + resp = self.save_flow({ + "id": template_id, + "flowId": version_id, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + "type": 0, + }) + if not resp.success: + raise RuntimeError(f"保存流程设计失败: {resp.msg}") + + return { + "template_id": template_id, + "version_id": version_id, + } + + # ==================== 决策流程 (type=4) ==================== + + @staticmethod + def build_decision_flow_xml() -> str: + """获取决策流程默认 BPMN XML + + 决策流程结构: StartEvent -> ExclusiveGateway -> UserTask (多个) -> EndEvent + 需要 URL 编码。 + + Returns: + URL 编码后的 BPMN XML 字符串 + """ + xml = """ + + + + Flow_1 + + + Flow_1 + Flow_2a + Flow_2b + + + + ${condition_a} + + + ${condition_b} + + + Flow_2a + Flow_3 + + + Flow_2b + Flow_4 + + + + + Flow_3 + Flow_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + return urllib.parse.quote(xml) + + @staticmethod + def build_decision_flow_nodes( + form_id: str, + form_name: str = "", + branch_a_name: str = "分支A审批", + branch_b_name: str = "分支B审批", + branch_a_user_ids: Optional[List[str]] = None, + branch_b_user_ids: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """构建决策流程的 flowNodes 配置 + + 决策流程使用排他网关,根据条件选择不同的审批分支。 + + Args: + form_id: 关联的可视化开发表单 ID + form_name: 表单名称 + branch_a_name: 分支A节点名称 + branch_b_name: 分支B节点名称 + branch_a_user_ids: 分支A审批人用户 ID 列表 + branch_b_user_ids: 分支B审批人用户 ID 列表 + + Returns: + flowNodes 字典 + """ + approvers_a = [{"id": uid, "type": "user"} for uid in (branch_a_user_ids or [])] + approvers_b = [{"id": uid, "type": "user"} for uid in (branch_b_user_ids or [])] + + return { + "global": { + "type": "global", + "nodeId": "global", + "allFormMap": {}, + "allDecisionMap": {}, + "formId": form_id, + "titleType": 0, + "defaultContent": "{发起用户名}的{流程名称}", + "titleContent": "", + "hasSign": False, + "hasRevoke": False, + "hasComment": True, + "hasCommentDeletedTips": True, + "hasSignFor": False, + "hasAloneConfigureForms": False, + "hasContinueAfterReject": False, + "hasInitiatorPressOverdueNode": True, + "autoSubmitConfig": { + "adjacentNodeApproverRepeated": False, + "ApproverHasApproval": False, + "initiatorApproverRepeated": False, + }, + "recallRule": 1, + "errorRule": 1, + "errorRuleUser": [], + "fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""}, + "globalParameterList": [], + "publicParameterList": [], + "approvalFieldList": [], + "isShowConditions": True, + "showNameType": 1, + "connectList": ["Flow_1", "Flow_2a", "Flow_2b", "Flow_3", "Flow_4"], + }, + "Event_1": { + "type": "start", + "nodeId": "Event_1", + "nodeName": "流程发起", + "formId": form_id, + "formName": form_name, + "formOperates": [], + "divideRule": "inclusion", + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24}, + "noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5}, + "waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []}, + "initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "freeNode": False, + }, + "Gateway_1": { + "type": "gateway", + "nodeId": "Gateway_1", + "nodeName": "条件路由", + "divideRule": "exclusive", + "gatewayType": "exclusive", + }, + "Flow_2a": { + "type": "connect", + "nodeId": "Flow_2a", + "nodeName": "条件A", + "conditions": [ + {"fieldName": "condition_a", "symbol": "==", "fieldValue": True} + ], + "matchLogic": "and", + "isDefault": False, + }, + "Flow_2b": { + "type": "connect", + "nodeId": "Flow_2b", + "nodeName": "条件B", + "conditions": [ + {"fieldName": "condition_b", "symbol": "==", "fieldValue": True} + ], + "matchLogic": "and", + "isDefault": True, + }, + "Activity_1": { + "type": "approver", + "nodeId": "Activity_1", + "nodeName": branch_a_name, + "formId": form_id, + "formName": form_name, + "formOperates": [], + "assignList": [], + "assigneeType": 6, + "approverType": 1, + "managerApproverType": 1, + "managerLevel": 1, + "formFieldType": 1, + "formField": "", + "approverNodeId": "", + "prevNodeList": [], + "approvers": approvers_a, + "approversSortList": [], + "extraRule": 1, + "counterSign": 0, + "counterSignConfig": { + "auditType": 1, "auditRatio": 100, "auditNum": 1, + "rejectType": 0, "rejectRatio": 10, "rejectNum": 1, + "calculateType": 1, + }, + "circulateUser": [], + "extraCopyRule": 1, + "isCustomCopy": False, + "isInitiatorCopy": False, + "isFormFieldCopy": False, + "copyFormFieldType": 1, + "copyFormField": "", + "hasOpinion": True, + "opinionRequired": False, + "hasSign": False, + "hasFile": False, + "hasApprovalField": False, + "approvalField": [], + "hasAuditBtn": True, + "auditBtnText": "同意", + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": False, + "freeApproverBtnText": "加签", + "hasReduceApproverBtn": False, + "reduceApproverBtnText": "减签", + "hasTransferBtn": False, + "transferBtnText": "转审", + "hasAssistBtn": False, + "assistBtnText": "协办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", + "backType": 1, + "backNodeCode": 0, + "customBtns": [], + "auxiliaryInfo": [], + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "parameterList": [], + "hasAutoApprover": False, + "autoAuditRule": {"conditions": [], "matchLogic": "and"}, + "autoRejectRule": {"conditions": [], "matchLogic": "and"}, + "divideRule": "exclusive", + "interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []}, + "approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "content": "", + "timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""}, + "overTimeConfig": { + "on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, + "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, + "overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2, + "overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [], + "reApprovers": "", "overTimeExtraRule": 3, + }, + "noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "isCandidates": False, + "approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1}, + "approvalNumber": 1, + "oneSelfEndApproval": True, + "freeNode": False, + }, + "Activity_2": { + "type": "approver", + "nodeId": "Activity_2", + "nodeName": branch_b_name, + "formId": form_id, + "formName": form_name, + "formOperates": [], + "assignList": [], + "assigneeType": 6, + "approverType": 1, + "managerApproverType": 1, + "managerLevel": 1, + "formFieldType": 1, + "formField": "", + "approverNodeId": "", + "prevNodeList": [], + "approvers": approvers_b, + "approversSortList": [], + "extraRule": 1, + "counterSign": 0, + "counterSignConfig": { + "auditType": 1, "auditRatio": 100, "auditNum": 1, + "rejectType": 0, "rejectRatio": 10, "rejectNum": 1, + "calculateType": 1, + }, + "circulateUser": [], + "extraCopyRule": 1, + "isCustomCopy": False, + "isInitiatorCopy": False, + "isFormFieldCopy": False, + "copyFormFieldType": 1, + "copyFormField": "", + "hasOpinion": True, + "opinionRequired": False, + "hasSign": False, + "hasFile": False, + "hasApprovalField": False, + "approvalField": [], + "hasAuditBtn": True, + "auditBtnText": "同意", + "hasRejectBtn": True, + "rejectBtnText": "拒绝", + "hasBackBtn": False, + "backBtnText": "退回", + "hasFreeApproverBtn": False, + "freeApproverBtnText": "加签", + "hasReduceApproverBtn": False, + "reduceApproverBtnText": "减签", + "hasTransferBtn": False, + "transferBtnText": "转审", + "hasAssistBtn": False, + "assistBtnText": "协办", + "hasSaveAuditBtn": False, + "saveAuditBtnText": "暂存", + "backType": 1, + "backNodeCode": 0, + "customBtns": [], + "auxiliaryInfo": [], + "printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"}, + "parameterList": [], + "hasAutoApprover": False, + "autoAuditRule": {"conditions": [], "matchLogic": "and"}, + "autoRejectRule": {"conditions": [], "matchLogic": "and"}, + "divideRule": "exclusive", + "interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []}, + "approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []}, + "content": "", + "timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""}, + "overTimeConfig": { + "on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, + "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, + "overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2, + "overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [], + "reApprovers": "", "overTimeExtraRule": 3, + }, + "noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5}, + "approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []}, + "isCandidates": False, + "approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1}, + "approvalNumber": 1, + "oneSelfEndApproval": True, + "freeNode": False, + }, + "Event_end": { + "type": "end", + "nodeId": "Event_end", + "nodeName": "结束节点", + "endParameterList": [], + }, + } + + def create_decision_flow( + self, + full_name: str, + en_code: str, + form_id: str, + branch_a_user_ids: Optional[List[str]] = None, + branch_b_user_ids: Optional[List[str]] = None, + form_name: str = "", + description: str = "", + icon: str = "icon-ym icon-ym-flow", + ) -> Dict[str, str]: + """创建决策流程模板 + + 决策流程使用排他网关,根据条件选择不同的审批分支。 + + Args: + full_name: 流程名称 + en_code: 流程编码 + form_id: 关联的可视化开发表单 ID + branch_a_user_ids: 分支A审批人用户 ID 列表 + branch_b_user_ids: 分支B审批人用户 ID 列表 + form_name: 表单名称 + description: 流程说明 + icon: 流程图标 + + Returns: + dict: { + "template_id": 模板 ID, + "version_id": 版本 ID, + } + """ + flow_xml = self.build_decision_flow_xml() + flow_nodes = self.build_decision_flow_nodes( + form_id, form_name, + branch_a_user_ids=branch_a_user_ids, + branch_b_user_ids=branch_b_user_ids, + ) + flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False) + + resp = self.create_template({ + "fullName": full_name, + "enCode": en_code, + "type": 4, # 决策流程 + "category": "", + "icon": icon, + "iconBackground": "#008cff", + "showType": 0, + "sortCode": 0, + "description": description, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + }) + if not resp.success: + raise RuntimeError(f"创建决策流程模板失败: {resp.msg}") + template_id = resp.id + + resp = self.get_version_list(template_id) + if not resp.success or not resp.data: + raise RuntimeError(f"获取版本列表失败: {resp.msg}") + version_id = resp.data[0]["id"] + + resp = self.save_flow({ + "id": template_id, + "flowId": version_id, + "flowXml": flow_xml, + "flowNodes": flow_nodes, + "flowConfig": flow_config, + "type": 0, + }) + if not resp.success: + raise RuntimeError(f"保存流程设计失败: {resp.msg}") + + return { + "template_id": template_id, + "version_id": version_id, + } diff --git a/scripts/deploy_data_source.py b/scripts/deploy_data_source.py new file mode 100644 index 0000000..1c93cea --- /dev/null +++ b/scripts/deploy_data_source.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""数据源管理功能 - 完整部署脚本 + +执行步骤: +1. 创建 VisualDev 表单 +2. 发布表单 +3. 创建目录菜单和功能菜单 +4. 生成前后端代码 + +用法: + python3 aibridge/scripts/deploy_data_source.py +""" + +import sys +import os +sys.path.insert(0, os.environ.get("ccWorkDir", "/home/ubuntu/ccWorkDir")) + +from aibridge import JNPFClient, JNPFConfig +from aibridge.builders.full_config import build_full_config, build_create_payload +from aibridge.models import FieldDef + + +def main(): + print("=" * 60) + print("数据源管理功能部署") + print("=" * 60) + + # 1. 初始化客户端 + config = JNPFConfig(app_code="dr") + print(f"应用: {config.app_code} ({config.system_title})") + print(f"system_id: {config.system_id}") + print(f"db_link_id: {config.db_link_id}") + print(f"business_category_id: {config.business_category_id}") + + client = JNPFClient.from_config(config) + client.login() + print("登录成功") + + # 2. 检查表单是否已存在 + resp = client.visual_dev.get_list({"currentPage": 1, "pageSize": 100}) + existing_forms = {} + for item in (resp.data or {}).get("list", []): + existing_forms[item.get("enCode")] = item.get("id") + + # 3. 定义字段 + fields = [ + FieldDef(field="f_source_name", field_name="数据源名称", required=True), + FieldDef(field="f_source_type", field_name="数据源类型", jnpf_key="select", options=[ + {"fullName": "MySQL", "id": "MySQL"}, + {"fullName": "Oracle", "id": "Oracle"}, + {"fullName": "PostgreSQL", "id": "PostgreSQL"}, + {"fullName": "MongoDB", "id": "MongoDB"}, + {"fullName": "API", "id": "API"}, + {"fullName": "文件", "id": "文件"}, + ]), + FieldDef(field="f_connection_config", field_name="连接配置", jnpf_key="textarea"), + FieldDef(field="f_database_name", field_name="数据库名称"), + FieldDef(field="f_connection_status", field_name="连接状态", jnpf_key="select", options=[ + {"fullName": "未连接", "id": "0"}, + {"fullName": "已连接", "id": "1"}, + {"fullName": "连接失败", "id": "2"}, + ]), + FieldDef(field="f_last_test_time", field_name="最后测试时间", jnpf_key="datePicker", format="yyyy-MM-dd HH:mm:ss"), + ] + + # 4. 创建表单 + en_code = "dataSource" + if en_code in existing_forms: + func_id = existing_forms[en_code] + print(f"\n表单已存在: {en_code} (func_id={func_id})") + else: + print(f"\n[Step 1] 创建表单: {en_code}") + config_obj = build_full_config( + full_name="数据源管理", + en_code=en_code, + table_name="data_source", + table_label="数据源表", + description="数据源配置管理", + category=config.business_category_id, + fields=[f.to_dict() for f in fields], + web_type=2, + ) + payload = build_create_payload(config_obj, dynamic_table=True) + + resp = client.visual_dev.create(payload) + func_id = resp.id + if not func_id: + print(f"创建失败: {resp.msg}") + return + + print(f"表单创建成功: func_id={func_id}") + + # 5. 发布表单 + print(f"\n[Step 2] 发布表单...") + rel = client.visual_dev.release(func_id) + if rel.code != 200: + print(f"发布失败: {rel.msg}") + return + print("表单发布成功") + + # 6. 创建菜单 + print(f"\n[Step 3] 创建菜单...") + + # 查找或创建"系统管理"目录 + resp = client.menu.get_list({"currentPage": 1, "pageSize": 500}) + parent_dir_id = None + for m in (resp.data or {}).get("list", []): + if m.get("fullName") in ["系统管理", "系统支撑", "系统配置"]: + parent_dir_id = m.get("id") + break + + if not parent_dir_id: + # 创建系统管理目录 + dir_resp = client.menu.create_directory_menu( + full_name="系统管理", + en_code="sys_mgmt", + parent_id="-1", + sort_code=99, + ) + parent_dir_id = dir_resp.id + if not parent_dir_id: + parent_dir_id = resp.data["list"][0]["id"] if resp.data["list"] else None + + if not parent_dir_id: + print("无法创建菜单:找不到父级目录") + return + + # 创建数据源管理子目录 + dir_resp = client.menu.create_directory_menu( + full_name="数据源管理", + en_code="data_source_dir", + parent_id=str(parent_dir_id), + sort_code=1, + ) + dir_id = dir_resp.id + if not dir_id: + # 目录可能已存在,查找它 + for m in (resp.data or {}).get("list", []): + if m.get("id") == parent_dir_id: + for c in (m.get("children") or []): + if c.get("fullName") == "数据源管理": + dir_id = c.get("id") + break + + if not dir_id: + print("无法创建数据源管理目录") + return + + # 创建功能菜单 + menu_resp = client.menu.create_form_menu( + full_name="数据源配置", + en_code=en_code, + visual_dev_id=func_id, + parent_id=str(dir_id), + sort_code=1, + ) + menu_id = menu_resp.id + if not menu_id: + print("功能菜单可能已存在") + else: + print(f"功能菜单创建成功: menu_id={menu_id}") + + print(f"\n✅ 部署完成!") + print(f" func_id: {func_id}") + print(f" menu_id: {menu_id}") + print(f"\n下一步: 使用 CodeGenerator 生成代码") + print(f" from aibridge.utils.code_generator import CodeGenerator") + print(f" gen = CodeGenerator(client, config)") + print(f" result = gen.generate(func_id='{func_id}', module_name='DataSource', auto_fix_names=True)") + + +if __name__ == "__main__": + main() diff --git a/utils/.DS_Store b/utils/.DS_Store new file mode 100644 index 0000000..acb1e00 Binary files /dev/null and b/utils/.DS_Store differ diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..97fc924 --- /dev/null +++ b/utils/__init__.py @@ -0,0 +1,5 @@ +"""AIBridge 工具模块""" + +from aibridge.utils.code_generator import CodeGenerator + +__all__ = ["CodeGenerator"] diff --git a/utils/__pycache__/__init__.cpython-312.pyc b/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..506dbc1 Binary files /dev/null and b/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/utils/__pycache__/__init__.cpython-313.pyc b/utils/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..5bcce55 Binary files /dev/null and b/utils/__pycache__/__init__.cpython-313.pyc differ diff --git a/utils/__pycache__/code_generator.cpython-312.pyc b/utils/__pycache__/code_generator.cpython-312.pyc new file mode 100644 index 0000000..53965d4 Binary files /dev/null and b/utils/__pycache__/code_generator.cpython-312.pyc differ diff --git a/utils/__pycache__/code_generator.cpython-313.pyc b/utils/__pycache__/code_generator.cpython-313.pyc new file mode 100644 index 0000000..79665f3 Binary files /dev/null and b/utils/__pycache__/code_generator.cpython-313.pyc differ diff --git a/utils/__pycache__/generater.cpython-313.pyc b/utils/__pycache__/generater.cpython-313.pyc new file mode 100644 index 0000000..4eac454 Binary files /dev/null and b/utils/__pycache__/generater.cpython-313.pyc differ diff --git a/utils/__pycache__/modulestructure.cpython-312.pyc b/utils/__pycache__/modulestructure.cpython-312.pyc new file mode 100644 index 0000000..c018793 Binary files /dev/null and b/utils/__pycache__/modulestructure.cpython-312.pyc differ diff --git a/utils/__pycache__/modulestructure.cpython-313.pyc b/utils/__pycache__/modulestructure.cpython-313.pyc new file mode 100644 index 0000000..4c02472 Binary files /dev/null and b/utils/__pycache__/modulestructure.cpython-313.pyc differ diff --git a/utils/api_test.py b/utils/api_test.py new file mode 100644 index 0000000..a7b5832 --- /dev/null +++ b/utils/api_test.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +""" +AIBridge API 集成测试 + +配置来源:aibridge/config.py(通过 JNPFConfig 读取) + +用法: + cd $ccWorkDir + python3 aibridge/utils/api_test.py # 运行全部测试 + python3 api_test.py auth # 仅认证 + python3 api_test.py menu # 仅菜单 + python3 api_test.py visualDev # 仅可视化开发 + python3 api_test.py workflow # 仅工作流 + python3 api_test.py dataInterface # 仅数据接口 + python3 api_test.py dataModel # 仅数据模型 + python3 api_test.py oauth # 仅接口认证(OAuth) + python3 api_test.py oauthBind # 仅接口认证绑定 +""" + +import sys +import os +import json +import time +import argparse +from datetime import datetime + +# 配置路径 +AIBRIDGE_ROOT = os.environ['ccWorkDir'] +sys.path.insert(0, AIBRIDGE_ROOT) + +from aibridge import JNPFClient, JNPFConfig + + +def load_config(): + """从 aibridge/config.py 读取配置""" + config = JNPFConfig() + if not config.app_code: + print("\n[ERROR] aibridge/config.py 中 app_code 为空!") + print(" 原因:硬编码默认 app_code 会导致登录到系统控制后台(错误应用)。") + print(" 解决:在 aibridge/config.py 中正确配置 app_code\n") + sys.exit(1) + return config + + +def run_tests(client, targets): + """执行测试用例""" + results = [] + all_tests = { + 'auth': test_auth, + 'menu': test_menu_list, + 'menuCreate': test_menu_create, + 'visualDev': test_visual_dev, + 'workflow': test_workflow, + 'dataInterface': test_data_interface, + 'dataModel': test_data_model, + 'oauth': test_oauth, + 'oauthBind': test_oauth_bind, + } + + to_run = list(targets) if targets else list(all_tests.keys()) + + for name in to_run: + if name in all_tests: + try: + print(f"\n[{name}] 测试中...") + ok, msg = all_tests[name](client) + results.append({'name': name, 'ok': ok, 'msg': msg}) + print(f" 结果: {'✓ 通过' if ok else '✗ 失败'} {msg}") + except Exception as e: + print(f" 异常: {e}") + results.append({'name': name, 'ok': False, 'msg': str(e)}) + else: + print(f" 未知测试: {name}") + + return results + + +def print_summary(results, config): + """打印汇总""" + print("\n" + "=" * 50) + print("测试汇总") + print("=" * 50) + print(f"配置来源: aibridge/config.py") + print(f"base_url: {config.base_url}") + print(f"app_code: {config.app_code}") + print(f"account: {config.account}") + print("=" * 50) + + passed = sum(1 for r in results if r['ok']) + for r in results: + print(f" {'✓' if r['ok'] else '✗'} {r['name']}: {'通过' if r['ok'] else '失败'} {r['msg']}") + + print(f"\n通过: {passed} / {len(results)}") + print("=" * 50) + + # 保存结果 + ts = datetime.now().strftime('%Y%m%d_%H%M%S') + results_dir = os.path.join(os.path.dirname(__file__), 'results') + os.makedirs(results_dir, exist_ok=True) + report_path = os.path.join(results_dir, f'api-test-summary_{ts}.json') + with open(report_path, 'w', encoding='utf-8') as f: + json.dump({ + 'config': { + 'base_url': config.base_url, + 'app_code': config.app_code, + 'account': config.account, + }, + 'results': results, + 'timestamp': ts, + }, f, ensure_ascii=False, indent=2) + print(f"结果已保存: {results_dir}/api-test-summary_{ts}.json") + return passed == len(results) + + +# ── 测试用例 ───────────────────────────────────────── + +def test_auth(client): + """TC-Auth-001: 认证""" + result = client.get_user_info() + return result.success, f"用户: {result.data.get('userName', 'N/A')}" + + +def test_menu_list(client): + """TC-Menu-001: 获取菜单列表""" + resp = client.menu.get_list({"currentPage": 1, "pageSize": 50}) + count = len(resp.data.get("list", [])) if resp.data else 0 + return resp.success, f"菜单数: {count}" + + +def test_menu_create(client): + """TC-Menu-002: 创建目录菜单""" + test_name = f"E2E测试目录_{int(time.time())}" + resp = client.menu.create_directory_menu( + full_name=test_name, + en_code=f"e2e_test_dir_{int(time.time())}", + icon="icon-ym icon-ym-folder", + sort_code=999, + parent_id="-1", + ) + return resp.success, f"id={resp.id}" if resp.id else resp.msg + + +def test_visual_dev(client): + """TC-VisualDev-001: 获取已发布表单""" + resp = client.visual_dev.get_list({"currentPage": 1, "pageSize": 10}) + forms = resp.data.get("list", []) if resp.data else [] + published = [f for f in forms if f.get("state") == 1] + return resp.success, f"总数={len(forms)}, 已发布={len(published)}" + + +def test_workflow(client): + """TC-Workflow-001: 获取流程模板""" + resp = client.workflow.get_template_list({"currentPage": 1, "pageSize": 10}) + count = len(resp.data.get("list", [])) if resp.data else 0 + return resp.success, f"流程数: {count}" + + +def test_data_interface(client): + """TC-DI-001: 获取数据接口""" + resp = client.data_interface.get_list({"currentPage": 1, "pageSize": 3}) + count = len(resp.data.get("list", [])) if resp.data else 0 + return resp.success, f"接口数: {count}" + + +def test_data_model(client): + """TC-DataModel-001: 数据模型 - 获取业务库连接列表""" + resp = client.data_source.get_list() + count = len(resp.data.get("list", [])) if resp.data else 0 + return resp.success, f"数据源数: {count}" + + +def test_oauth(client): + """TC-OAuth-001: 接口认证 - 创建认证""" + oauth = client.interface_oauth + # 获取新秘钥 + secret_resp = oauth.get_app_secret() + if not secret_resp.success: + return False, f"获取秘钥失败: {secret_resp.msg}" + app_secret = secret_resp.data + # 创建认证 + test_app_id = f"e2e_test_app_{int(time.time())}" + resp = oauth.create({ + "appId": test_app_id, + "appName": "E2E测试应用", + "appSecret": app_secret, + "verifySignature": 0, + "enabledMark": 1, + }) + return resp.success, f"appId={test_app_id}, msg={resp.msg}" + + +def test_oauth_bind(client): + """TC-OAuth-002: 接口认证 - 绑定授权接口""" + oauth = client.interface_oauth + # 先获取列表找一个认证 + list_resp = oauth.get_list({"currentPage": 1, "pageSize": 10}) + if not list_resp.success or not list_resp.data: + return False, "获取认证列表失败" + items = list_resp.data.get("list", []) + if not items: + return False, "认证列表为空" + oauth_id = items[0].get("id") + # 获取数据接口列表 + di_resp = client.data_interface.get_list({"currentPage": 1, "pageSize": 3}) + if not di_resp.success or not di_resp.data: + return False, "获取接口列表失败" + di_items = di_resp.data.get("list", []) + if not di_items: + return False, "接口列表为空" + di_ids = [di_items[0].get("id")] + # 绑定接口 + bind_resp = oauth.bind_interfaces(oauth_id, di_ids) + return bind_resp.success, f"oauth_id={oauth_id}, di_id={di_ids[0]}, msg={bind_resp.msg}" + + +# ── 主入口 ───────────────────────────────────────── + +def main(): + parser = argparse.ArgumentParser(description='AIBridge API 集成测试') + parser.add_argument('targets', nargs='*', help='测试目标: auth menu menuCreate visualDev workflow dataInterface dataModel') + args = parser.parse_args() + + print("=" * 50) + print("AIBridge API 集成测试") + print("=" * 50) + + config = load_config() + print(f"base_url: {config.base_url}") + print(f"app_code: {config.app_code}") + print(f"account: {config.account}") + print("=" * 50) + + client = JNPFClient.from_config(config) + print("\n登录中...") + login_resp = client.login() + if not login_resp.success: + print(f"登录失败: {login_resp.msg}") + sys.exit(1) + print("登录成功") + + targets = args.targets if args.targets else [] + results = run_tests(client, targets) + ok = print_summary(results, config) + sys.exit(0 if ok else 1) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/utils/code_generator.py b/utils/code_generator.py new file mode 100644 index 0000000..5b604d9 --- /dev/null +++ b/utils/code_generator.py @@ -0,0 +1,816 @@ +"""代码生成模块 + +从 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 create\()(\s*@RequestBody\s+@Valid\s+\$\{Name\}Form\s+\$\{name\}Form)?(\s*\))' + content = re.sub(create_pattern, '@PostMapping\n @Operation(summary = "创建")\n public ActionResult 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 diff --git a/utils/modulestructure.py b/utils/modulestructure.py new file mode 100644 index 0000000..0e39bc2 --- /dev/null +++ b/utils/modulestructure.py @@ -0,0 +1,195 @@ +"""JNPF 模块目录结构和 pom.xml 生成器 + +从 code_generator.py 中提取的独立模块,负责: +- 创建 Maven 多模块项目目录结构 +- 生成父 pom.xml 和子模块 (entity/biz/controller) pom.xml + +使用方法: + from aibridge.utils.modulestructure import ModuleStructureCreator + from aibridge.config import JNPFConfig + + config = JNPFConfig() # 或 config.jyzs.JNPFConfig() + creator = ModuleStructureCreator( + module_name="DataSourceConfig", + package="ssw.dr", # 模块包名 + backend_base="/path/to/boot", + boot_parent="ssw-boot", # 父 pom artifactId + ) + creator.create() +""" + +import os +from typing import Optional + + +class ModuleStructureCreator: + """创建 JNPF Maven 多模块项目的目录结构和 pom.xml""" + + def __init__( + self, + module_name: str, + package: str, + backend_base: str, + boot_parent: str = "ssw-boot", + ): + """ + Args: + module_name: 业务模块名(kebab-case),如 ssw-dr(artifactId) + package: Java 包名,如 ssw.dr + backend_base: 后端根目录,如 /path/to/boot + boot_parent: 父 pom 的 artifactId,如 ssw-boot + """ + self.module_name = module_name # 如 "ssw-dr" + self.package = package # 如 "ssw.dr" + self.backend_base = backend_base # 如 "/path/to/boot" + self.boot_parent = boot_parent # 如 "ssw-boot" + + def create(self): + """创建完整的模块目录结构和所有 pom.xml""" + base = self.backend_base + module = self.module_name + pkg = self.package + + # 父模块 + parent_dir = os.path.join(base, module) + os.makedirs(parent_dir, exist_ok=True) + self._write_file(os.path.join(parent_dir, 'pom.xml'), self._parent_pom()) + + # Entity 模块 + entity_dir = os.path.join(parent_dir, f"{module}-entity", "src", "main", "java", *pkg.split('.')) + os.makedirs(os.path.join(entity_dir, 'entity'), exist_ok=True) + os.makedirs(os.path.join(entity_dir, 'model'), exist_ok=True) + self._write_file(os.path.join(parent_dir, f"{module}-entity", 'pom.xml'), self._entity_pom()) + + # Biz 模块 + biz_dir = os.path.join(parent_dir, f"{module}-biz", "src", "main", "java") + os.makedirs(os.path.join(biz_dir, *pkg.split('.'), 'service'), exist_ok=True) + os.makedirs(os.path.join(biz_dir, 'jnpf', 'mapper'), exist_ok=True) + self._write_file(os.path.join(parent_dir, f"{module}-biz", 'pom.xml'), self._biz_pom()) + + # Controller 模块 + controller_dir = os.path.join(parent_dir, f"{module}-controller", "src", "main", "java", *pkg.split('.')) + os.makedirs(os.path.join(controller_dir, 'controller'), exist_ok=True) + self._write_file(os.path.join(parent_dir, f"{module}-controller", 'pom.xml'), self._controller_pom()) + + def _write_file(self, path: str, content: str): + """写文件(仅当文件不存在时)""" + os.makedirs(os.path.dirname(path), exist_ok=True) + if not os.path.exists(path): + with open(path, 'w', encoding='utf-8') as f: + f.write(content) + + def _parent_pom(self) -> str: + return f''' + + 4.0.0 + + com.jnpf + {self.boot_parent} + 6.2.0-RELEASE + + + {self.module_name} + pom + + {self.module_name}-entity + {self.module_name}-biz + {self.module_name}-controller + + +''' + + def _entity_pom(self) -> str: + return f''' + + + {self.module_name} + com.jnpf + 6.2.0-RELEASE + + 4.0.0 + {self.module_name}-entity + + + + com.jnpf + jnpf-common-all + ${{project.version}} + + + com.jnpf + jnpf-generater-base + ${{project.version}} + + + +''' + + def _biz_pom(self) -> str: + return f''' + + + {self.module_name} + com.jnpf + 6.2.0-RELEASE + + 4.0.0 + {self.module_name}-biz + + + + com.jnpf + {self.module_name}-entity + ${{project.version}} + + + com.alibaba + fastjson + + + org.apache.commons + commons-lang3 + 3.12.0 + + + com.jnpf + jnpf-common-all + ${{project.version}} + + + +''' + + def _controller_pom(self) -> str: + return f''' + + + {self.module_name} + com.jnpf + 6.2.0-RELEASE + + 4.0.0 + {self.module_name}-controller + + + + com.jnpf + {self.module_name}-biz + ${{project.version}} + + + com.jnpf + jnpf-common-all + ${{project.version}} + + + +''' diff --git a/utils/results/api-test-summary_20260414_193130.json b/utils/results/api-test-summary_20260414_193130.json new file mode 100644 index 0000000..7a6abf0 --- /dev/null +++ b/utils/results/api-test-summary_20260414_193130.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "dr", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 1" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=813820336230367237" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 3" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 6" + } + ], + "timestamp": "20260414_193130" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260414_193328.json b/utils/results/api-test-summary_20260414_193328.json new file mode 100644 index 0000000..3fbc5e4 --- /dev/null +++ b/utils/results/api-test-summary_20260414_193328.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "dr", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 2" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=813820831921602629" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 3" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 6" + } + ], + "timestamp": "20260414_193328" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260417_222221.json b/utils/results/api-test-summary_20260417_222221.json new file mode 100644 index 0000000..9c9ed87 --- /dev/null +++ b/utils/results/api-test-summary_20260417_222221.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "jyzs", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 1" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=814950494274322629" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=5, 已发布=5" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 6" + } + ], + "timestamp": "20260417_222221" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260418_174954.json b/utils/results/api-test-summary_20260418_174954.json new file mode 100644 index 0000000..d23c4f5 --- /dev/null +++ b/utils/results/api-test-summary_20260418_174954.json @@ -0,0 +1,15 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "sswportal", + "account": "admin" + }, + "results": [ + { + "name": "visualDev", + "ok": true, + "msg": "总数=6, 已发布=6" + } + ], + "timestamp": "20260418_174954" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260421_185058.json b/utils/results/api-test-summary_20260421_185058.json new file mode 100644 index 0000000..bc29373 --- /dev/null +++ b/utils/results/api-test-summary_20260421_185058.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 13" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816346850486387077" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 8" + } + ], + "timestamp": "20260421_185058" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260421_192808.json b/utils/results/api-test-summary_20260421_192808.json new file mode 100644 index 0000000..b5792e2 --- /dev/null +++ b/utils/results/api-test-summary_20260421_192808.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 13" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816356206183448965" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 8" + } + ], + "timestamp": "20260421_192808" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_161331.json b/utils/results/api-test-summary_20260422_161331.json new file mode 100644 index 0000000..22974e2 --- /dev/null +++ b/utils/results/api-test-summary_20260422_161331.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 1" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816669615433187909" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=9" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_161331" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_165419.json b/utils/results/api-test-summary_20260422_165419.json new file mode 100644 index 0000000..55d0bee --- /dev/null +++ b/utils/results/api-test-summary_20260422_165419.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 3" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816679882124689989" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=9" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_165419" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_174813.json b/utils/results/api-test-summary_20260422_174813.json new file mode 100644 index 0000000..bad51a0 --- /dev/null +++ b/utils/results/api-test-summary_20260422_174813.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 4" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816693446810010181" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=0" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_174813" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_174843.json b/utils/results/api-test-summary_20260422_174843.json new file mode 100644 index 0000000..ddf7372 --- /dev/null +++ b/utils/results/api-test-summary_20260422_174843.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 5" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816693574279103045" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=0" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_174843" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_175547.json b/utils/results/api-test-summary_20260422_175547.json new file mode 100644 index 0000000..3dd79ec --- /dev/null +++ b/utils/results/api-test-summary_20260422_175547.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 7" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816695350885614149" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=0" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_175547" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260422_183605.json b/utils/results/api-test-summary_20260422_183605.json new file mode 100644 index 0000000..e64e497 --- /dev/null +++ b/utils/results/api-test-summary_20260422_183605.json @@ -0,0 +1,45 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tdc", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 8" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=816705494218441285" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=0" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + } + ], + "timestamp": "20260422_183605" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260423_220501.json b/utils/results/api-test-summary_20260423_220501.json new file mode 100644 index 0000000..a2beac0 --- /dev/null +++ b/utils/results/api-test-summary_20260423_220501.json @@ -0,0 +1,15 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "oauth", + "ok": true, + "msg": "appId=e2e_test_app_1776953101, msg=New created successfully" + } + ], + "timestamp": "20260423_220501" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260423_220505.json b/utils/results/api-test-summary_20260423_220505.json new file mode 100644 index 0000000..66c1c11 --- /dev/null +++ b/utils/results/api-test-summary_20260423_220505.json @@ -0,0 +1,15 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "oauthBind", + "ok": false, + "msg": "接口列表为空" + } + ], + "timestamp": "20260423_220505" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260424_130453.json b/utils/results/api-test-summary_20260424_130453.json new file mode 100644 index 0000000..98292bb --- /dev/null +++ b/utils/results/api-test-summary_20260424_130453.json @@ -0,0 +1,55 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 11" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=817346921319369797" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 0" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + }, + { + "name": "oauth", + "ok": false, + "msg": "appId=e2e_test_app_1777007093, msg=The name cannot be repeated" + }, + { + "name": "oauthBind", + "ok": false, + "msg": "接口列表为空" + } + ], + "timestamp": "20260424_130453" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260424_183300.json b/utils/results/api-test-summary_20260424_183300.json new file mode 100644 index 0000000..1792849 --- /dev/null +++ b/utils/results/api-test-summary_20260424_183300.json @@ -0,0 +1,15 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + } + ], + "timestamp": "20260424_183300" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260424_183304.json b/utils/results/api-test-summary_20260424_183304.json new file mode 100644 index 0000000..48f5b22 --- /dev/null +++ b/utils/results/api-test-summary_20260424_183304.json @@ -0,0 +1,15 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "tds", + "account": "admin" + }, + "results": [ + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + } + ], + "timestamp": "20260424_183304" +} \ No newline at end of file diff --git a/utils/results/api-test-summary_20260506_184737.json b/utils/results/api-test-summary_20260506_184737.json new file mode 100644 index 0000000..df4a56d --- /dev/null +++ b/utils/results/api-test-summary_20260506_184737.json @@ -0,0 +1,55 @@ +{ + "config": { + "base_url": "http://localhost:30000", + "app_code": "dr", + "account": "admin" + }, + "results": [ + { + "name": "auth", + "ok": true, + "msg": "用户: N/A" + }, + { + "name": "menu", + "ok": true, + "msg": "菜单数: 10" + }, + { + "name": "menuCreate", + "ok": true, + "msg": "id=821781823766922181" + }, + { + "name": "visualDev", + "ok": true, + "msg": "总数=10, 已发布=10" + }, + { + "name": "workflow", + "ok": true, + "msg": "流程数: 5" + }, + { + "name": "dataInterface", + "ok": true, + "msg": "接口数: 0" + }, + { + "name": "dataModel", + "ok": true, + "msg": "数据源数: 9" + }, + { + "name": "oauth", + "ok": false, + "msg": "appId=e2e_test_app_1778064457, msg=The name cannot be repeated" + }, + { + "name": "oauthBind", + "ok": false, + "msg": "接口列表为空" + } + ], + "timestamp": "20260506_184737" +} \ No newline at end of file diff --git a/utils/run-codegen.py b/utils/run-codegen.py new file mode 100644 index 0000000..0d2d5a5 --- /dev/null +++ b/utils/run-codegen.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""AIBridge 代码生成与菜单挂载脚本 + +用法: + python3 run-codegen.py # 交互模式(显示系统菜单树供选择) + python3 run-codegen.py [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()