Files
aibridge/builders/mobile_field_model.py
2026-05-18 09:28:15 +08:00

202 lines
7.2 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.
"""移动端字段模型构建器
将 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
]