402 lines
13 KiB
Python
402 lines
13 KiB
Python
"""
|
|
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 <app_code>") |