Files
2026-05-18 09:28:15 +08:00

129 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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