feat(lowcode): 低代码元数据引擎第一波 —— 解析 + 校验 + 3 个只读工具
- 新 crate sspf-lowcode(纯计算,AR7 钉住不依赖 DB/HTTP):widget 把 54 种 jnpfKey 归成 11 类 (决定「怎么存、能不能接收入参」)/ form 解析控件树 / model 解析表结构 / validate 9 类诊断码 - DDL:base_visual_dev + base_visual_release 逐字对齐官方(21 → 23 张表) - MCP 3 个只读工具:form.list / form.describe / form.validate,后两个支持 inline JSON - 真实样例落盘为 fixture(官方初始化数据的「应收费用」:主表 6 字段 / 子表 8 字段) - 新增 lowcode-smoke.sh 8 条(含两条反自证:改坏 __vModel__ 必被抓、未知控件只 warn) - 影响:测试 306 → 344;十二闸全绿;三条真实方言已写进注释与测试
This commit is contained in:
1 parent
16c0704c47
commit
f0c77f731c
24 files changed
+4122
-22
No files matched your search
@@ -0,0 +1,541 @@
|
||||
//! form —— 解析 baseline 的 `f_form_data`(表单控件树)。
|
||||
//!
|
||||
//! ## 数据结构(实测自官方初始化数据,71 张表单)
|
||||
//!
|
||||
//! ```json
|
||||
//! {
|
||||
//! "formRef": "elForm",
|
||||
//! "formModel": "formData",
|
||||
//! "labelPosition": "right",
|
||||
//! "labelWidth": 100,
|
||||
//! "formRules": "rules",
|
||||
//! "popupType": "dialog",
|
||||
//! "primaryKeyPolicy": 1,
|
||||
//! "concurrencyLock": false,
|
||||
//! "logicalDelete": true,
|
||||
//! "fields": [
|
||||
//! {
|
||||
//! "__config__": {
|
||||
//! "formId": 101,
|
||||
//! "jnpfKey": "input",
|
||||
//! "layout": "colFormItem",
|
||||
//! "tag": "JnpfInput",
|
||||
//! "label": "房间号",
|
||||
//! "tableName": "test_receivable",
|
||||
//! "required": false,
|
||||
//! "span": 12,
|
||||
//! "visibility": ["pc", "app"]
|
||||
//! },
|
||||
//! "__vModel__": "F_Room",
|
||||
//! "placeholder": "请输入"
|
||||
//! }
|
||||
//! ]
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## 三个必须记住的方言(踩错就是静默错数据)
|
||||
//!
|
||||
//! 1. **`__vModel__` 是 `F_` 开头的大写**(`F_Room`),而物理列是小写 `f_room`。
|
||||
//! 映射规则只有一条:`f_` + `__vModel__` 去前缀后转小写。
|
||||
//! 2. **`rowFormItem` 是布局容器**,本身不占列;它的 `children` 才是控件。
|
||||
//! 3. **`table` 是子表**,它的 `children` 属于**另一张物理表**
|
||||
//! (`__config__.tableName` 指明的那个),不能混进主表字段。
|
||||
//!
|
||||
//! ## 同构原则
|
||||
//!
|
||||
//! [`FormSchema::raw`] 保留原始 JSON 一字不动。所有解析结果都是**视图**,
|
||||
//! 保存时写回原始的 `raw` —— 这样前端拿到的表单和它自己存的一模一样,
|
||||
//! 不会因为我们「顺手规范化」了键顺序而白屏。
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::widget::{classify, unknown_hint, WidgetKind};
|
||||
|
||||
/// 解析失败的原因(结构化,便于回报给 AI)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FormError {
|
||||
/// 不是 JSON 对象。
|
||||
NotAnObject,
|
||||
/// 缺 `fields` 数组。
|
||||
MissingFields,
|
||||
/// `fields` 不是数组。
|
||||
FieldsNotArray,
|
||||
}
|
||||
|
||||
impl FormError {
|
||||
/// 机器可读码。
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
FormError::NotAnObject => "FORM_NOT_OBJECT",
|
||||
FormError::MissingFields => "FORM_MISSING_FIELDS",
|
||||
FormError::FieldsNotArray => "FORM_FIELDS_NOT_ARRAY",
|
||||
}
|
||||
}
|
||||
|
||||
/// 人话说明 + 怎么修。
|
||||
pub fn message(&self) -> &'static str {
|
||||
match self {
|
||||
FormError::NotAnObject => {
|
||||
"f_form_data 不是 JSON 对象。流程表单的 f_form_data 是**字段映射数组**\
|
||||
([{filedName,filedId,…}]),不是控件树 —— 那种表单不属于本引擎的处理范围"
|
||||
}
|
||||
FormError::MissingFields => {
|
||||
"f_form_data 缺少 fields 数组 —— 这不是 visualdev 表单定义,\
|
||||
可能是列表页配置(那种结构有 columnList / ruleList)"
|
||||
}
|
||||
FormError::FieldsNotArray => "f_form_data.fields 存在但不是数组",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个控件节点。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FieldNode {
|
||||
/// `__vModel__`(如 `F_Room`)。系统字段可能为空串。
|
||||
pub v_model: String,
|
||||
/// 显示名(`__config__.label`)。
|
||||
pub label: String,
|
||||
/// 控件类型原文(`__config__.jnpfKey`,缺失时退回节点自身的 `jnpfKey`)。
|
||||
pub jnpf_key: String,
|
||||
/// 控件类别(决定怎么存)。
|
||||
pub widget: WidgetKind,
|
||||
/// 布局类型:`colFormItem`(控件)/ `rowFormItem`(容器)。
|
||||
pub layout: String,
|
||||
/// 该控件所属物理表(`__config__.tableName`)。
|
||||
pub table_name: Option<String>,
|
||||
/// 是否必填。
|
||||
pub required: bool,
|
||||
/// 可见端:`["pc"]` / `["pc","app"]`。
|
||||
pub visibility: Vec<String>,
|
||||
/// 是否隐藏(`noShow`)。
|
||||
pub no_show: bool,
|
||||
/// `__config__.formId`(表单内唯一序号,用于定位)。
|
||||
pub form_id: Option<i64>,
|
||||
/// 子控件(仅 `rowFormItem` 与子表有)。
|
||||
pub children: Vec<FieldNode>,
|
||||
}
|
||||
|
||||
impl FieldNode {
|
||||
/// 是否是布局容器(本身不占列,但孩子可能占)。
|
||||
pub fn is_container(&self) -> bool {
|
||||
self.layout == "rowFormItem"
|
||||
}
|
||||
|
||||
/// 是否是子表节点。
|
||||
pub fn is_sub_table(&self) -> bool {
|
||||
self.widget == WidgetKind::SubTable
|
||||
}
|
||||
|
||||
/// 该节点是否占**主表**的一列。
|
||||
///
|
||||
/// 布局容器、子表本身都不占;子表里的字段属于别的表。
|
||||
pub fn occupies_main_column(&self) -> bool {
|
||||
!self.is_container() && self.widget.occupies_column()
|
||||
}
|
||||
|
||||
/// `__vModel__` → 物理列名(`F_Room` → `f_room`)。
|
||||
///
|
||||
/// 空 `__vModel__` ⇒ `None`(系统字段常见)。
|
||||
pub fn column_name(&self) -> Option<String> {
|
||||
v_model_to_column(&self.v_model)
|
||||
}
|
||||
}
|
||||
|
||||
/// `__vModel__` → 物理列名。
|
||||
///
|
||||
/// 规则(实测唯一正确的一条):
|
||||
/// - 去掉任意数量的 `F_` / `f_` 前缀(官方两种写法都出现过)
|
||||
/// - 其余部分整体转**小写**,不做驼峰拆分
|
||||
///
|
||||
/// 🔴 **不要做驼峰转下划线**:`F_CertificatesType` 对应的列是
|
||||
/// `f_certificates_type`,但 `F_Building` 对应 `f_building`(没有下划线)。
|
||||
/// 官方列名由建表时的人工输入决定,没有机械规则 —— 所以这里只做
|
||||
/// 「前缀剥离 + 小写」,真实列名一律以 `f_tables_data` 为准。
|
||||
pub fn v_model_to_column(v_model: &str) -> Option<String> {
|
||||
let s = v_model.trim();
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let stripped = s
|
||||
.strip_prefix("F_")
|
||||
.or_else(|| s.strip_prefix("f_"))
|
||||
.unwrap_or(s);
|
||||
if stripped.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("f_{}", stripped.to_lowercase()))
|
||||
}
|
||||
|
||||
/// 解析后的表单(保留原始 JSON)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FormSchema {
|
||||
/// 原始 JSON —— 保存时原样写回(同构)。
|
||||
pub raw: Value,
|
||||
/// 表单引用名(`formRef`)。
|
||||
pub form_ref: String,
|
||||
/// 绑定的数据对象名(`formModel`,通常是 `formData`)。
|
||||
pub form_model: String,
|
||||
/// 标签位置(`labelPosition`)。
|
||||
pub label_position: String,
|
||||
/// 标签宽度。
|
||||
pub label_width: i64,
|
||||
/// 主键策略(`primaryKeyPolicy`)。
|
||||
pub primary_key_policy: Option<i64>,
|
||||
/// 是否并发锁(`concurrencyLock`)。
|
||||
pub concurrency_lock: Option<bool>,
|
||||
/// 是否逻辑删除(`logicalDelete`)。
|
||||
pub logical_delete: Option<bool>,
|
||||
/// 顶层控件树。
|
||||
pub fields: Vec<FieldNode>,
|
||||
}
|
||||
|
||||
impl FormSchema {
|
||||
/// 解析 `f_form_data`。
|
||||
pub fn parse(raw: &Value) -> Result<Self, FormError> {
|
||||
let Some(obj) = raw.as_object() else {
|
||||
return Err(FormError::NotAnObject);
|
||||
};
|
||||
let Some(fields_val) = obj.get("fields") else {
|
||||
return Err(FormError::MissingFields);
|
||||
};
|
||||
let Some(arr) = fields_val.as_array() else {
|
||||
return Err(FormError::FieldsNotArray);
|
||||
};
|
||||
|
||||
let fields = arr.iter().filter_map(parse_node).collect();
|
||||
|
||||
Ok(Self {
|
||||
raw: raw.clone(),
|
||||
form_ref: str_of(obj, "formRef"),
|
||||
form_model: str_of(obj, "formModel"),
|
||||
label_position: str_of(obj, "labelPosition"),
|
||||
label_width: obj.get("labelWidth").and_then(Value::as_i64).unwrap_or(0),
|
||||
primary_key_policy: obj.get("primaryKeyPolicy").and_then(Value::as_i64),
|
||||
concurrency_lock: obj.get("concurrencyLock").and_then(Value::as_bool),
|
||||
logical_delete: obj.get("logicalDelete").and_then(Value::as_bool),
|
||||
fields,
|
||||
})
|
||||
}
|
||||
|
||||
/// 从 JSON 文本解析。
|
||||
pub fn from_str(s: &str) -> Result<Self, FormError> {
|
||||
let v: Value = serde_json::from_str(s).map_err(|_| FormError::NotAnObject)?;
|
||||
Self::parse(&v)
|
||||
}
|
||||
|
||||
/// 扁平化全部节点(含容器与子表字段),深度优先。
|
||||
pub fn all_nodes(&self) -> Vec<&FieldNode> {
|
||||
fn walk<'a>(nodes: &'a [FieldNode], out: &mut Vec<&'a FieldNode>) {
|
||||
for n in nodes {
|
||||
out.push(n);
|
||||
walk(&n.children, out);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(&self.fields, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// **主表**要存的字段(排除布局、子表本身、子表内的字段)。
|
||||
///
|
||||
/// 这就是动态 CRUD 的列白名单来源 —— 顺序保持 JSON 里的原始顺序。
|
||||
pub fn main_fields(&self) -> Vec<&FieldNode> {
|
||||
let mut out = Vec::new();
|
||||
for n in self.fields.iter() {
|
||||
collect_main(n, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 子表清单(每个子表节点一项)。
|
||||
pub fn sub_tables(&self) -> Vec<&FieldNode> {
|
||||
self.all_nodes()
|
||||
.into_iter()
|
||||
.filter(|n| n.is_sub_table())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 主表字段对应的物理列名(去重、保序)。
|
||||
pub fn main_columns(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for f in self.main_fields() {
|
||||
if let Some(c) = f.column_name() {
|
||||
if !out.contains(&c) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 出现过的主表名(去重)。
|
||||
pub fn table_names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in self.all_nodes() {
|
||||
if let Some(t) = &n.table_name {
|
||||
if !t.is_empty() && !out.contains(t) {
|
||||
out.push(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 未知控件清单(用于警告)。
|
||||
pub fn unknown_widgets(&self) -> Vec<&FieldNode> {
|
||||
self.all_nodes()
|
||||
.into_iter()
|
||||
.filter(|n| n.widget == WidgetKind::Unknown)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归收集主表字段。
|
||||
fn collect_main<'a>(node: &'a FieldNode, out: &mut Vec<&'a FieldNode>) {
|
||||
if node.is_sub_table() {
|
||||
// 子表本身与它的孩子都不进主表
|
||||
return;
|
||||
}
|
||||
if node.is_container() {
|
||||
for c in &node.children {
|
||||
collect_main(c, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if node.widget.occupies_column() {
|
||||
out.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of(obj: &Map<String, Value>, key: &str) -> String {
|
||||
obj.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// 解析单个节点;结构不像控件时返回 `None`。
|
||||
fn parse_node(v: &Value) -> Option<FieldNode> {
|
||||
let obj = v.as_object()?;
|
||||
let cfg = obj
|
||||
.get("__config__")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
// jnpfKey:优先 __config__,退回节点自身
|
||||
let jnpf_key = cfg
|
||||
.get("jnpfKey")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| obj.get("jnpfKey").and_then(Value::as_str))
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let layout = cfg
|
||||
.get("layout")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("colFormItem")
|
||||
.to_string();
|
||||
|
||||
let v_model = obj
|
||||
.get("__vModel__")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let visibility = cfg
|
||||
.get("visibility")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let children: Vec<FieldNode> = cfg
|
||||
.get("children")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(parse_node).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
// 🔴 有些节点(新版控件)把子项挂在顶层 children,而不是 __config__ 里
|
||||
let children = if children.is_empty() {
|
||||
obj.get("children")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(parse_node).collect())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
children
|
||||
};
|
||||
|
||||
// 既无 jnpfKey 又无 vModel 的节点不是控件(可能是不认识的结构),跳过
|
||||
if jnpf_key.is_empty() && v_model.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let widget = classify(&jnpf_key);
|
||||
|
||||
Some(FieldNode {
|
||||
v_model,
|
||||
label: str_of(&cfg, "label"),
|
||||
jnpf_key,
|
||||
widget,
|
||||
layout,
|
||||
table_name: cfg.get("tableName").and_then(Value::as_str).map(str::to_string),
|
||||
required: cfg.get("required").and_then(Value::as_bool).unwrap_or(false),
|
||||
visibility,
|
||||
no_show: cfg.get("noShow").and_then(Value::as_bool).unwrap_or(false),
|
||||
form_id: cfg.get("formId").and_then(Value::as_i64),
|
||||
children,
|
||||
})
|
||||
}
|
||||
|
||||
/// 把未知控件汇总成一条人话警告(供 `form.validate` 输出)。
|
||||
pub fn unknown_warning(nodes: &[&FieldNode]) -> Option<String> {
|
||||
if nodes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let keys: Vec<&str> = nodes.iter().map(|n| n.jnpf_key.as_str()).collect();
|
||||
Some(format!(
|
||||
"{} 个未知控件({})—— {}",
|
||||
nodes.len(),
|
||||
keys.join(", "),
|
||||
unknown_hint(keys[0])
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn minimal_form() -> Value {
|
||||
json!({
|
||||
"formRef": "elForm",
|
||||
"formModel": "formData",
|
||||
"labelPosition": "right",
|
||||
"labelWidth": 100,
|
||||
"fields": [
|
||||
{
|
||||
"__config__": { "jnpfKey": "input", "layout": "colFormItem",
|
||||
"label": "姓名", "tableName": "t_demo", "required": true },
|
||||
"__vModel__": "F_Name"
|
||||
},
|
||||
{
|
||||
"__config__": { "jnpfKey": "inputNumber", "layout": "colFormItem",
|
||||
"label": "年龄", "tableName": "t_demo" },
|
||||
"__vModel__": "F_Age"
|
||||
},
|
||||
{
|
||||
"__config__": { "jnpfKey": "groupTitle", "layout": "colFormItem", "label": "分组" },
|
||||
"__vModel__": ""
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_form() {
|
||||
let f = FormSchema::parse(&minimal_form()).unwrap();
|
||||
assert_eq!(f.form_ref, "elForm");
|
||||
assert_eq!(f.label_width, 100);
|
||||
assert_eq!(f.fields.len(), 3);
|
||||
// 主表字段排除布局控件
|
||||
let cols = f.main_columns();
|
||||
assert_eq!(cols, vec!["f_name", "f_age"]);
|
||||
}
|
||||
|
||||
/// 🔴 vModel → 列名:只剥前缀 + 转小写,**不做驼峰转下划线**。
|
||||
#[test]
|
||||
fn v_model_mapping_is_prefix_strip_plus_lowercase() {
|
||||
assert_eq!(v_model_to_column("F_Room").as_deref(), Some("f_room"));
|
||||
assert_eq!(v_model_to_column("f_room").as_deref(), Some("f_room"));
|
||||
assert_eq!(
|
||||
v_model_to_column("F_CertificatesType").as_deref(),
|
||||
Some("f_certificatestype"),
|
||||
"不做驼峰拆分 —— 真实列名以 f_tables_data 为准"
|
||||
);
|
||||
assert_eq!(v_model_to_column("").as_deref(), None);
|
||||
assert_eq!(v_model_to_column("F_").as_deref(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_shapes() {
|
||||
assert_eq!(FormSchema::parse(&json!([1, 2])).unwrap_err(), FormError::NotAnObject);
|
||||
assert_eq!(FormSchema::parse(&json!({"a": 1})).unwrap_err(), FormError::MissingFields);
|
||||
assert_eq!(
|
||||
FormSchema::parse(&json!({"fields": "x"})).unwrap_err(),
|
||||
FormError::FieldsNotArray
|
||||
);
|
||||
}
|
||||
|
||||
/// 错误消息必须能区分「流程表单的字段映射」和「真的坏数据」。
|
||||
#[test]
|
||||
fn error_messages_are_actionable() {
|
||||
assert!(FormError::NotAnObject.message().contains("流程表单"));
|
||||
assert!(FormError::MissingFields.message().contains("列表页配置"));
|
||||
}
|
||||
|
||||
/// 布局容器(rowFormItem)不占列,但它的孩子要进主表。
|
||||
#[test]
|
||||
fn row_container_children_join_main_fields() {
|
||||
let v = json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{
|
||||
"__config__": { "jnpfKey": "row", "layout": "rowFormItem", "label": "行" },
|
||||
"__vModel__": "",
|
||||
"children": [{
|
||||
"__config__": { "jnpfKey": "input", "layout": "colFormItem", "label": "备注" },
|
||||
"__vModel__": "F_Remark"
|
||||
}]
|
||||
}]
|
||||
});
|
||||
let f = FormSchema::parse(&v).unwrap();
|
||||
assert_eq!(f.main_columns(), vec!["f_remark"], "容器本身不占列,孩子占");
|
||||
}
|
||||
|
||||
/// 子表:本身不占主表列,它的字段也不进主表(属于另一张表)。
|
||||
#[test]
|
||||
fn sub_table_is_isolated_from_main_columns() {
|
||||
let v = json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [
|
||||
{ "__config__": { "jnpfKey": "input", "tableName": "t_main" }, "__vModel__": "F_Title" },
|
||||
{
|
||||
"__config__": { "jnpfKey": "table", "layout": "rowFormItem",
|
||||
"tableName": "t_child", "label": "明细" },
|
||||
"__vModel__": "tableField1",
|
||||
"children": [
|
||||
{ "__config__": { "jnpfKey": "input", "tableName": "t_child" }, "__vModel__": "F_Item" }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
let f = FormSchema::parse(&v).unwrap();
|
||||
assert_eq!(f.main_columns(), vec!["f_title"], "子表字段不能混进主表");
|
||||
assert_eq!(f.sub_tables().len(), 1);
|
||||
assert_eq!(f.sub_tables()[0].table_name.as_deref(), Some("t_child"));
|
||||
assert_eq!(f.table_names().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_widget_is_reported_but_not_fatal() {
|
||||
let v = json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{ "__config__": { "jnpfKey": "futureWidget" }, "__vModel__": "F_X" }]
|
||||
});
|
||||
let f = FormSchema::parse(&v).unwrap();
|
||||
let unknown = f.unknown_widgets();
|
||||
assert_eq!(unknown.len(), 1);
|
||||
assert!(unknown_warning(&unknown).unwrap().contains("futureWidget"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_is_preserved_verbatim() {
|
||||
let v = minimal_form();
|
||||
let f = FormSchema::parse(&v).unwrap();
|
||||
assert_eq!(f.raw, v, "raw 必须一字不动(同构)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! sspf-lowcode —— 低代码元数据引擎(**纯计算**,不碰 DB / HTTP)。
|
||||
//!
|
||||
//! ## 它为什么存在
|
||||
//!
|
||||
//! 项目第 5 条要求「不迁前端/移动端代码,复用现有资产」。这意味着前端那套
|
||||
//! Vue 渲染器继续用,Rust 侧只需要做到一件事:
|
||||
//!
|
||||
//! > **同构存取 baseline 的 `base_visual_dev` 里那几个 JSON 字段。**
|
||||
//!
|
||||
//! 前端不关心后端是 Java 还是 Rust —— 它只认 `f_form_data` / `f_column_data` /
|
||||
//! `f_tables_data` 三个 JSON 字符串。所以本 crate 的全部工作就是:
|
||||
//!
|
||||
//! ```text
|
||||
//! f_form_data ──parse──▶ FormSchema (控件树:字段、必填、子表、控件类型)
|
||||
//! f_tables_data ─parse──▶ ModelSchema (表结构:表、列、主键、类型)
|
||||
//! │
|
||||
//! └─validate─▶ Report(表单声明的字段,表里真有那些列吗)
|
||||
//! ```
|
||||
//!
|
||||
//! ## 三层职责,别混
|
||||
//!
|
||||
//! | 层 | 归属 | 干什么 |
|
||||
//! |---|---|---|
|
||||
//! | **渲染** | 前端(Vue,不动) | 读 JSON 画表单 |
|
||||
//! | **解析 / 校验 / SQL 生成** | 本 crate | 纯函数,可单测 |
|
||||
//! | **执行** | 内核 / MCP 适配器 | 真正连库、跑 SQL |
|
||||
//!
|
||||
//! ⇒ 本 crate **不引入 `pglite` / `axum` / `tokio`**(AR7)。
|
||||
//! 这样它既能被内核用,也能被 CLI、MCP、离线校验工具用 —— 而且测试不需要起数据库。
|
||||
//!
|
||||
//! ## 四个必须记住的方言(都在各模块头部详述)
|
||||
//!
|
||||
//! 1. `__vModel__` 是 `F_` 开头大写,物理列是小写;映射只做「剥前缀 + 转小写」
|
||||
//! 2. `f_tables_data` 的 `columnName` **常常是 null**,要用 `field` 推导
|
||||
//! 3. `rowFormItem` 是布局容器,不占列,孩子才占
|
||||
//! 4. `table` 是子表,它的字段属于**另一张物理表**
|
||||
//!
|
||||
//! ## 为什么「不改一个字段」是可验证的
|
||||
//!
|
||||
//! [`FormSchema::raw`] / [`ModelSchema::raw`] 保留原始 JSON 一字不动,
|
||||
//! 保存时原样写回。解析结果只是**只读视图**,
|
||||
//! 测试 `real_sample.rs` 用官方初始化数据里的真表单做基线断言。
|
||||
|
||||
pub mod form;
|
||||
pub mod model;
|
||||
pub mod validate;
|
||||
pub mod widget;
|
||||
|
||||
pub use form::{v_model_to_column, FieldNode, FormError, FormSchema};
|
||||
pub use model::{ColumnDef, ModelError, ModelSchema, TableSchema};
|
||||
pub use validate::{validate, Diagnostic, Report, Severity};
|
||||
pub use widget::{classify, WidgetKind};
|
||||
|
||||
/// 版本(与 workspace 一致,供 MCP 输出用)。
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
@@ -0,0 +1,374 @@
|
||||
//! model —— 解析 baseline 的 `f_tables_data`(表结构定义)。
|
||||
//!
|
||||
//! ## 数据结构(实测)
|
||||
//!
|
||||
//! ```json
|
||||
//! [
|
||||
//! {
|
||||
//! "table": "test_receivable",
|
||||
//! "tableName": "应收费用主表",
|
||||
//! "typeId": "1", // "1" = 主表, "0" = 子表
|
||||
//! "relationTable": "",
|
||||
//! "relationField": "",
|
||||
//! "tableField": "",
|
||||
//! "fields": [
|
||||
//! {
|
||||
//! "field": "F_Id", // 设计态字段名(权威)
|
||||
//! "columnName": null, // 物理列名 —— **常常是 null**!
|
||||
//! "fieldName": "主键", // 显示名
|
||||
//! "dataType": "varchar",
|
||||
//! "dataLength": "50",
|
||||
//! "primaryKey": 1,
|
||||
//! "allowNull": 0,
|
||||
//! "autoIncrement": 0,
|
||||
//! "identity": 0
|
||||
//! }
|
||||
//! ]
|
||||
//! }
|
||||
//! ]
|
||||
//! ```
|
||||
//!
|
||||
//! ## 🔴 最重要的一条:`columnName` 不可信
|
||||
//!
|
||||
//! 实测数据里 `columnName` **大量为 null** ——「设计完还没建表」的商品态就是这样。
|
||||
//! 所以物理列名必须从 `field` 推导(规则与 `form::v_model_to_column` 同一份实现):
|
||||
//!
|
||||
//! ```text
|
||||
//! F_Id → f_id
|
||||
//! F_Room → f_room
|
||||
//! F_CertificatesType → f_certificatestype ← 注意没有下划线
|
||||
//! ```
|
||||
//!
|
||||
//! ⇒ **不要指望「驼峰转下划线」**。真实列名最终以数据库 `information_schema` 为准,
|
||||
//! 本模块只负责「设计态 → 预期列名」的推导与一致性校验。
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::form::v_model_to_column;
|
||||
|
||||
/// 解析失败原因。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ModelError {
|
||||
/// 不是数组。
|
||||
NotAnArray,
|
||||
/// 空数组。
|
||||
Empty,
|
||||
}
|
||||
|
||||
impl ModelError {
|
||||
/// 机器可读码。
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
ModelError::NotAnArray => "MODEL_NOT_ARRAY",
|
||||
ModelError::Empty => "MODEL_EMPTY",
|
||||
}
|
||||
}
|
||||
|
||||
/// 人话说明。
|
||||
pub fn message(&self) -> &'static str {
|
||||
match self {
|
||||
ModelError::NotAnArray => {
|
||||
"f_tables_data 不是数组 —— 它应该是多张表的定义列表([{table,tableName,typeId,fields}])"
|
||||
}
|
||||
ModelError::Empty => "f_tables_data 是空数组,没有任何表定义",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一列的定义。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ColumnDef {
|
||||
/// 设计态字段名(`F_Id`)。**这是权威字段名**。
|
||||
pub field: String,
|
||||
/// 官方给的物理列名 —— 可能为 null(尚未建表)。
|
||||
pub column_name: Option<String>,
|
||||
/// 显示名(`主键`)。
|
||||
pub field_name: String,
|
||||
/// 数据类型(`varchar` / `int4` / `timestamp` …)。
|
||||
pub data_type: String,
|
||||
/// 长度(字符串形态,官方如此)。
|
||||
pub data_length: String,
|
||||
/// 是否主键。
|
||||
pub primary_key: bool,
|
||||
/// 是否允许 NULL。
|
||||
pub allow_null: bool,
|
||||
/// 是否自增。
|
||||
pub auto_increment: bool,
|
||||
}
|
||||
|
||||
impl ColumnDef {
|
||||
/// 实际使用的物理列名:`columnName` 优先,否则从 `field` 推导。
|
||||
///
|
||||
/// 🔴 只在**非空**时才信 `columnName` —— 实测大量为 `null`。
|
||||
pub fn resolved_column(&self) -> Option<String> {
|
||||
match &self.column_name {
|
||||
Some(c) if !c.is_empty() => Some(c.to_lowercase()),
|
||||
_ => v_model_to_column(&self.field),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一张表的定义。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TableSchema {
|
||||
/// 物理表名。
|
||||
pub table: String,
|
||||
/// 显示名。
|
||||
pub table_name: String,
|
||||
/// `"1"` = 主表,`"0"` = 子表。
|
||||
pub type_id: String,
|
||||
/// 列定义(顺序即建表顺序)。
|
||||
pub fields: Vec<ColumnDef>,
|
||||
}
|
||||
|
||||
impl TableSchema {
|
||||
/// 是否主表。
|
||||
pub fn is_main(&self) -> bool {
|
||||
self.type_id == "1"
|
||||
}
|
||||
|
||||
/// 按 `F_xxx` 风格的设计态字段名找列(大小写不敏感)。
|
||||
pub fn column_by_field(&self, field: &str) -> Option<&ColumnDef> {
|
||||
self.fields
|
||||
.iter()
|
||||
.find(|c| c.field.eq_ignore_ascii_case(field))
|
||||
}
|
||||
|
||||
/// 按物理列名找列(大小写不敏感)。
|
||||
pub fn column_by_name(&self, name: &str) -> Option<&ColumnDef> {
|
||||
self.fields.iter().find(|c| {
|
||||
c.resolved_column()
|
||||
.is_some_and(|r| r.eq_ignore_ascii_case(name))
|
||||
})
|
||||
}
|
||||
|
||||
/// 全部物理列名(已推导)。
|
||||
pub fn column_names(&self) -> Vec<String> {
|
||||
self.fields
|
||||
.iter()
|
||||
.filter_map(|c| c.resolved_column())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 主键列名(可能为空 —— 设计态没标主键)。
|
||||
pub fn primary_keys(&self) -> Vec<String> {
|
||||
self.fields
|
||||
.iter()
|
||||
.filter(|c| c.primary_key)
|
||||
.filter_map(|c| c.resolved_column())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析后的模型(保留原始 JSON)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ModelSchema {
|
||||
/// 原始 JSON —— 同构保存时原样写回。
|
||||
pub raw: Value,
|
||||
/// 表清单。
|
||||
pub tables: Vec<TableSchema>,
|
||||
}
|
||||
|
||||
impl ModelSchema {
|
||||
/// 解析 `f_tables_data`。
|
||||
pub fn parse(raw: &Value) -> Result<Self, ModelError> {
|
||||
let Some(arr) = raw.as_array() else {
|
||||
return Err(ModelError::NotAnArray);
|
||||
};
|
||||
if arr.is_empty() {
|
||||
return Err(ModelError::Empty);
|
||||
}
|
||||
Ok(Self {
|
||||
raw: raw.clone(),
|
||||
tables: arr.iter().filter_map(parse_table).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 从 JSON 文本解析。
|
||||
pub fn from_str(s: &str) -> Result<Self, ModelError> {
|
||||
let v: Value = serde_json::from_str(s).map_err(|_| ModelError::NotAnArray)?;
|
||||
Self::parse(&v)
|
||||
}
|
||||
|
||||
/// 主表(`typeId == "1"`)。多个主表时取第一个。
|
||||
pub fn main_table(&self) -> Option<&TableSchema> {
|
||||
self.tables.iter().find(|t| t.is_main())
|
||||
}
|
||||
|
||||
/// 按物理表名查找(大小写不敏感 —— 官方数据里有大小写混用)。
|
||||
pub fn table(&self, name: &str) -> Option<&TableSchema> {
|
||||
self.tables
|
||||
.iter()
|
||||
.find(|t| t.table.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// 子表清单。
|
||||
pub fn sub_tables(&self) -> Vec<&TableSchema> {
|
||||
self.tables.iter().filter(|t| !t.is_main()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_table(v: &Value) -> Option<TableSchema> {
|
||||
let obj = v.as_object()?;
|
||||
let table = obj.get("table").and_then(Value::as_str)?.trim().to_string();
|
||||
if table.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(TableSchema {
|
||||
table,
|
||||
table_name: str_of(obj, "tableName"),
|
||||
type_id: match obj.get("typeId") {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => "0".to_string(),
|
||||
},
|
||||
fields: obj
|
||||
.get("fields")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(parse_column).collect())
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_column(v: &Value) -> Option<ColumnDef> {
|
||||
let obj = v.as_object()?;
|
||||
let field = obj.get("field").and_then(Value::as_str)?.trim().to_string();
|
||||
if field.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ColumnDef {
|
||||
field,
|
||||
column_name: obj
|
||||
.get("columnName")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string),
|
||||
field_name: str_of(obj, "fieldName"),
|
||||
data_type: str_of(obj, "dataType"),
|
||||
data_length: match obj.get("dataLength") {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => String::new(),
|
||||
},
|
||||
primary_key: truthy(obj.get("primaryKey")),
|
||||
allow_null: truthy(obj.get("allowNull")),
|
||||
auto_increment: truthy(obj.get("autoIncrement")),
|
||||
})
|
||||
}
|
||||
|
||||
/// 官方的布尔字段是 `0/1` 数字,但也见过 `true/false` 与 `"1"` 字符串。
|
||||
fn truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
||||
Some(Value::String(s)) => s == "1" || s.eq_ignore_ascii_case("true"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of(obj: &Map<String, Value>, key: &str) -> String {
|
||||
obj.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn model() -> Value {
|
||||
json!([
|
||||
{
|
||||
"table": "t_main", "tableName": "主表", "typeId": "1",
|
||||
"fields": [
|
||||
{"field":"F_Id","columnName":null,"fieldName":"主键","dataType":"varchar",
|
||||
"dataLength":"50","primaryKey":1,"allowNull":0},
|
||||
{"field":"F_Title","columnName":null,"fieldName":"标题","dataType":"varchar",
|
||||
"dataLength":"200","primaryKey":0,"allowNull":1},
|
||||
{"field":"F_Amount","columnName":"f_amount","fieldName":"金额","dataType":"numeric",
|
||||
"dataLength":"","primaryKey":0,"allowNull":1}
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "t_child", "tableName": "子表", "typeId": "0",
|
||||
"fields": [
|
||||
{"field":"F_Item","columnName":null,"fieldName":"项目","dataType":"varchar",
|
||||
"dataLength":"100","primaryKey":0,"allowNull":1}
|
||||
]
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_tables_and_flags() {
|
||||
let m = ModelSchema::parse(&model()).unwrap();
|
||||
assert_eq!(m.tables.len(), 2);
|
||||
assert_eq!(m.main_table().unwrap().table, "t_main");
|
||||
assert_eq!(m.sub_tables().len(), 1);
|
||||
assert!(m.main_table().unwrap().is_main());
|
||||
}
|
||||
|
||||
/// 🔴 `columnName` 为 null 时必须从 `field` 推导 —— 实测数据大量如此。
|
||||
#[test]
|
||||
fn resolves_column_name_when_null() {
|
||||
let m = ModelSchema::parse(&model()).unwrap();
|
||||
let t = m.main_table().unwrap();
|
||||
assert_eq!(t.column_names(), vec!["f_id", "f_title", "f_amount"]);
|
||||
assert_eq!(
|
||||
t.column_by_field("F_Title").unwrap().resolved_column().as_deref(),
|
||||
Some("f_title")
|
||||
);
|
||||
}
|
||||
|
||||
/// 官方给了 `columnName` 时以它为准(可能与推导结果不同)。
|
||||
#[test]
|
||||
fn prefers_explicit_column_name() {
|
||||
let m = ModelSchema::parse(&model()).unwrap();
|
||||
let t = m.main_table().unwrap();
|
||||
let c = t.column_by_field("F_Amount").unwrap();
|
||||
assert_eq!(c.column_name.as_deref(), Some("f_amount"));
|
||||
assert_eq!(c.resolved_column().as_deref(), Some("f_amount"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primary_keys_are_reported() {
|
||||
let m = ModelSchema::parse(&model()).unwrap();
|
||||
assert_eq!(m.main_table().unwrap().primary_keys(), vec!["f_id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_shapes() {
|
||||
assert_eq!(ModelSchema::parse(&json!({})).unwrap_err(), ModelError::NotAnArray);
|
||||
assert_eq!(ModelSchema::parse(&json!([])).unwrap_err(), ModelError::Empty);
|
||||
}
|
||||
|
||||
/// 主表可能缺失(用户只建了子表)—— 调用方要能处理。
|
||||
#[test]
|
||||
fn missing_main_table_is_none_not_panic() {
|
||||
let m = ModelSchema::parse(&json!([
|
||||
{"table":"t_child","typeId":"0","fields":[]}
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(m.main_table().is_none());
|
||||
assert_eq!(m.sub_tables().len(), 1);
|
||||
}
|
||||
|
||||
/// 布尔字段可能是 0/1、"1"、true —— 三种都要认。
|
||||
#[test]
|
||||
fn truthy_accepts_three_encodings() {
|
||||
assert!(truthy(Some(&json!(1))));
|
||||
assert!(truthy(Some(&json!("1"))));
|
||||
assert!(truthy(Some(&json!(true))));
|
||||
assert!(!truthy(Some(&json!(0))));
|
||||
assert!(!truthy(Some(&json!("0"))));
|
||||
assert!(!truthy(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_is_preserved() {
|
||||
let v = model();
|
||||
let m = ModelSchema::parse(&v).unwrap();
|
||||
assert_eq!(m.raw, v);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
//! validate —— 表单 ↔ 模型**一致性校验**。
|
||||
//!
|
||||
//! ## 这是 P2 的验收核心
|
||||
//!
|
||||
//! PLAN 的 P2 出口是「基线平台导出的表单 JSON,不改一个字段能在 SSPF 上渲染 + 存取」。
|
||||
//! 「能存取」的前提是**表单声明的字段,表里真有那些列** —— 这个前提在真实数据里
|
||||
//! 经常不成立(改名不同步、删列没删控件、子表指向不存在的表)。
|
||||
//!
|
||||
//! 如果不校验就上动态 CRUD,症状是:**插入时少一列、查询时 sql 报错**,
|
||||
//! 而错误信息是数据库给的(`column "f_xxx" does not exist`),AI 根本不知道该改哪。
|
||||
//!
|
||||
//! ⇒ 校验器把「数据库层的报错」提前成「设计态的明确诊断」。
|
||||
//!
|
||||
//! ## 诊断码表
|
||||
//!
|
||||
//! | 码 | 级别 | 含义 |
|
||||
//! |---|---|---|
|
||||
//! | `TABLE_NOT_IN_MODEL` | error | 表单引用的表没在 `f_tables_data` 里声明 |
|
||||
//! | `COLUMN_NOT_IN_TABLE` | error | 表单字段在主表列里找不到对应列 |
|
||||
//! | `SUBTABLE_COLUMN_MISSING` | error | 子表字段在子表列里找不到 |
|
||||
//! | `REQUIRED_WITHOUT_COLUMN` | error | 必填字段没有对应列(必然存不进去) |
|
||||
//! | `NO_MAIN_TABLE` | error | `f_tables_data` 里没有主表(`typeId=1`) |
|
||||
//! | `UNKNOWN_WIDGET` | warn | 未知控件(已降级为文本) |
|
||||
//! | `EMPTY_DATA_FIELDS` | warn | 表单没有任何数据字段 |
|
||||
//! | `REQUIRED_NULLABLE` | warn | 必填字段对应的列允许 NULL(约束只在应用层) |
|
||||
//! | `DISABLED_WIDGET_HAS_VALUE` | warn | 系统生成字段被设计成可编辑 |
|
||||
//!
|
||||
//! ## 为什么不用 error 就拦死
|
||||
//!
|
||||
//! `warn` 不阻断:未知控件降级后仍能读写,人工再修。
|
||||
//! `error` 也不直接阻断存取 —— 有些库确实「设计稿先进、表后建」。
|
||||
//! 但 `form.validate` 会把 error 明确报出来,让 AI 先修再存。
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::form::FormSchema;
|
||||
use crate::model::ModelSchema;
|
||||
use crate::widget::WidgetKind;
|
||||
|
||||
/// 诊断级别。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Severity {
|
||||
/// 会导致存取失败或写坏数据。
|
||||
Error,
|
||||
/// 能跑,但结果可能不符合预期。
|
||||
Warn,
|
||||
/// 纯提示。
|
||||
Info,
|
||||
}
|
||||
|
||||
impl Severity {
|
||||
/// 稳定字符串。
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Error => "error",
|
||||
Severity::Warn => "warn",
|
||||
Severity::Info => "info",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 一条诊断。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Diagnostic {
|
||||
/// 机器可读码。
|
||||
pub code: &'static str,
|
||||
/// 级别。
|
||||
pub severity: Severity,
|
||||
/// 人话说明(含定位信息)。
|
||||
pub message: String,
|
||||
/// 出问题的位置(字段名 / 表名 / JSON 路径)。
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
fn new(code: &'static str, severity: Severity, path: impl Into<String>, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
severity,
|
||||
path: path.into(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验报告。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Report {
|
||||
/// 全部诊断(按发现顺序)。
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// 是否没有任何 error(warn 不影响)。
|
||||
pub fn ok(&self) -> bool {
|
||||
!self
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.severity == Severity::Error)
|
||||
}
|
||||
|
||||
/// 错误条数。
|
||||
pub fn error_count(&self) -> usize {
|
||||
self.diagnostics
|
||||
.iter()
|
||||
.filter(|d| d.severity == Severity::Error)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// 警告条数。
|
||||
pub fn warn_count(&self) -> usize {
|
||||
self.diagnostics
|
||||
.iter()
|
||||
.filter(|d| d.severity == Severity::Warn)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// 序列化成 MCP 工具的输出形状。
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"ok": self.ok(),
|
||||
"errorCount": self.error_count(),
|
||||
"warnCount": self.warn_count(),
|
||||
"diagnostics": self.diagnostics.iter().map(|d| json!({
|
||||
"code": d.code,
|
||||
"severity": d.severity.as_str(),
|
||||
"path": d.path,
|
||||
"message": d.message,
|
||||
})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
fn push(&mut self, d: Diagnostic) {
|
||||
self.diagnostics.push(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验「表单定义」与「模型定义」是否自洽。
|
||||
pub fn validate(form: &FormSchema, model: &ModelSchema) -> Report {
|
||||
let mut r = Report::default();
|
||||
|
||||
// ---- 1) 主表必须存在 ----
|
||||
let Some(main) = model.main_table() else {
|
||||
r.push(Diagnostic::new(
|
||||
"NO_MAIN_TABLE",
|
||||
Severity::Error,
|
||||
"f_tables_data",
|
||||
"模型里没有主表(typeId=1)—— 动态 CRUD 不知道该写哪张表",
|
||||
));
|
||||
return r;
|
||||
};
|
||||
|
||||
// ---- 2) 表单引用的每张表都要有定义 ----
|
||||
for t in form.table_names() {
|
||||
if model.table(&t).is_none() {
|
||||
r.push(Diagnostic::new(
|
||||
"TABLE_NOT_IN_MODEL",
|
||||
Severity::Error,
|
||||
format!("table:{t}"),
|
||||
format!(
|
||||
"表单引用了表 `{t}`,但 f_tables_data 里没有它。\
|
||||
典型原因:控件上的 tableName 改了但模型没同步"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 3) 主表字段 ↔ 主表列 ----
|
||||
let main_fields = form.main_fields();
|
||||
if main_fields.is_empty() {
|
||||
r.push(Diagnostic::new(
|
||||
"EMPTY_DATA_FIELDS",
|
||||
Severity::Warn,
|
||||
"fields",
|
||||
"表单没有任何数据字段(全是布局/子表)—— 这个表单存不了主表数据",
|
||||
));
|
||||
}
|
||||
|
||||
for f in &main_fields {
|
||||
let Some(col) = f.column_name() else {
|
||||
// 系统生成字段可能没有 __vModel__,跳过(它们由后端填)
|
||||
if f.widget != WidgetKind::SystemGenerated {
|
||||
r.push(Diagnostic::new(
|
||||
"COLUMN_NOT_IN_TABLE",
|
||||
Severity::Error,
|
||||
format!("field:{}", f.label),
|
||||
format!(
|
||||
"字段「{}」({})没有 __vModel__,无法映射到列",
|
||||
f.label, f.jnpf_key
|
||||
),
|
||||
));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
let found = main.column_by_name(&col);
|
||||
if found.is_none() {
|
||||
let code = if f.required {
|
||||
"REQUIRED_WITHOUT_COLUMN"
|
||||
} else {
|
||||
"COLUMN_NOT_IN_TABLE"
|
||||
};
|
||||
r.push(Diagnostic::new(
|
||||
code,
|
||||
Severity::Error,
|
||||
format!("field:{}", f.v_model),
|
||||
format!(
|
||||
"字段「{}」的 `{}` 映射到列 `{}`,但主表 `{}` 没有这一列。\
|
||||
现有列:{}",
|
||||
f.label,
|
||||
f.v_model,
|
||||
col,
|
||||
main.table,
|
||||
preview(&main.column_names())
|
||||
),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
// ---- 3b) 必填但列允许 NULL ----
|
||||
if f.required {
|
||||
if let Some(c) = found {
|
||||
if c.allow_null {
|
||||
r.push(Diagnostic::new(
|
||||
"REQUIRED_NULLABLE",
|
||||
Severity::Warn,
|
||||
format!("field:{}", f.v_model),
|
||||
format!(
|
||||
"字段「{}」设计为必填,但列 `{col}` 允许 NULL —— \
|
||||
约束只在应用层生效,直接写库仍可绕过",
|
||||
f.label
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 4) 子表字段 ↔ 子表列 ----
|
||||
for sub in form.sub_tables() {
|
||||
let Some(table_name) = sub.table_name.as_deref().filter(|s| !s.is_empty()) else {
|
||||
r.push(Diagnostic::new(
|
||||
"TABLE_NOT_IN_MODEL",
|
||||
Severity::Error,
|
||||
format!("subtable:{}", sub.label),
|
||||
format!("子表「{}」没有 tableName —— 不知道数据该进哪张表", sub.label),
|
||||
));
|
||||
continue;
|
||||
};
|
||||
let Some(t) = model.table(table_name) else {
|
||||
// 已在第 2 步报过 TABLE_NOT_IN_MODEL,这里不重复
|
||||
continue;
|
||||
};
|
||||
for c in &sub.children {
|
||||
if !c.widget.occupies_column() {
|
||||
continue;
|
||||
}
|
||||
let Some(col) = c.column_name() else {
|
||||
continue;
|
||||
};
|
||||
if t.column_by_name(&col).is_none() {
|
||||
r.push(Diagnostic::new(
|
||||
"SUBTABLE_COLUMN_MISSING",
|
||||
Severity::Error,
|
||||
format!("subtable:{}:{}", table_name, c.v_model),
|
||||
format!(
|
||||
"子表「{}」的字段「{}」映射到列 `{}`,但表 `{}` 没有这一列",
|
||||
sub.label, c.label, col, table_name
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 5) 未知控件(降级警告)----
|
||||
let unknown = form.unknown_widgets();
|
||||
if !unknown.is_empty() {
|
||||
let mut keys: Vec<&str> = unknown.iter().map(|n| n.jnpf_key.as_str()).collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
r.push(Diagnostic::new(
|
||||
"UNKNOWN_WIDGET",
|
||||
Severity::Warn,
|
||||
"fields",
|
||||
format!(
|
||||
"{} 个未知控件({})已降级为文本 —— 能读写,但控件语义丢失;\
|
||||
补齐 crates/sspf-lowcode/src/widget.rs 的 classify() 可精确支持",
|
||||
unknown.len(),
|
||||
keys.join(", ")
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
// ---- 6) 系统生成字段被设计成可编辑 ----
|
||||
for n in form.all_nodes() {
|
||||
if n.widget == WidgetKind::SystemGenerated && !n.no_show && n.required {
|
||||
r.push(Diagnostic::new(
|
||||
"DISABLED_WIDGET_HAS_VALUE",
|
||||
Severity::Warn,
|
||||
format!("field:{}", n.v_model),
|
||||
format!(
|
||||
"「{}」是系统生成控件({})却被标成必填 —— \
|
||||
动态 CRUD 不会接收它的入参,必填校验会永远失败",
|
||||
n.label, n.jnpf_key
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
r
|
||||
}
|
||||
|
||||
/// 列名预览(最多 8 个,避免诊断信息过长)。
|
||||
fn preview(cols: &[String]) -> String {
|
||||
if cols.is_empty() {
|
||||
return "(无列)".to_string();
|
||||
}
|
||||
let mut shown: Vec<&str> = cols.iter().take(8).map(String::as_str).collect();
|
||||
let more = cols.len().saturating_sub(8);
|
||||
let mut s = shown.join(", ");
|
||||
shown.clear();
|
||||
if more > 0 {
|
||||
s.push_str(&format!(" …(还有 {more} 列)"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn model() -> ModelSchema {
|
||||
ModelSchema::parse(&json!([
|
||||
{
|
||||
"table": "t_main", "tableName": "主表", "typeId": "1",
|
||||
"fields": [
|
||||
{"field":"F_Id","fieldName":"主键","dataType":"varchar","primaryKey":1,"allowNull":0},
|
||||
{"field":"F_Title","fieldName":"标题","dataType":"varchar","allowNull":0},
|
||||
{"field":"F_Memo","fieldName":"备注","dataType":"varchar","allowNull":1}
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "t_child", "tableName": "子表", "typeId": "0",
|
||||
"fields": [{"field":"F_Item","fieldName":"项目","dataType":"varchar","allowNull":1}]
|
||||
}
|
||||
]))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn form_ok() -> FormSchema {
|
||||
FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [
|
||||
{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"标题","required":true},
|
||||
"__vModel__":"F_Title"},
|
||||
{"__config__":{"jnpfKey":"textarea","tableName":"t_main","label":"备注"},
|
||||
"__vModel__":"F_Memo"},
|
||||
{"__config__":{"jnpfKey":"table","layout":"rowFormItem","tableName":"t_child","label":"明细"},
|
||||
"__vModel__":"tableField",
|
||||
"children":[{"__config__":{"jnpfKey":"input","tableName":"t_child","label":"项目"},
|
||||
"__vModel__":"F_Item"}]}
|
||||
]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_form_has_no_errors() {
|
||||
let r = validate(&form_ok(), &model());
|
||||
assert!(r.ok(), "不该有 error: {:?}", r.diagnostics);
|
||||
assert_eq!(r.error_count(), 0);
|
||||
}
|
||||
|
||||
/// 最常见的问题:控件改了名,模型没同步 ⇒ 列不存在。
|
||||
#[test]
|
||||
fn field_without_column_is_error_with_existing_columns() {
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"不存在的字段"},
|
||||
"__vModel__":"F_Ghost"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(!r.ok());
|
||||
let d = r
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|d| d.code == "COLUMN_NOT_IN_TABLE")
|
||||
.expect("应报 COLUMN_NOT_IN_TABLE");
|
||||
assert!(d.message.contains("f_ghost"));
|
||||
assert!(d.message.contains("f_title"), "要把现有列列出来,AI 才知道怎么改");
|
||||
}
|
||||
|
||||
/// 必填字段没列 → 必须用更精确的码(REQUIRED_WITHOUT_COLUMN)。
|
||||
#[test]
|
||||
fn required_field_without_column_uses_specific_code() {
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"必填幽灵","required":true},
|
||||
"__vModel__":"F_Ghost"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(r
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == "REQUIRED_WITHOUT_COLUMN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtable_column_missing_is_reported() {
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [
|
||||
{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"标题"},"__vModel__":"F_Title"},
|
||||
{"__config__":{"jnpfKey":"table","layout":"rowFormItem","tableName":"t_child","label":"明细"},
|
||||
"__vModel__":"tableField",
|
||||
"children":[{"__config__":{"jnpfKey":"input","tableName":"t_child","label":"幽灵"},
|
||||
"__vModel__":"F_Nope"}]}
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(r
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == "SUBTABLE_COLUMN_MISSING"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_missing_from_model_is_reported() {
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_other","label":"x"},"__vModel__":"F_X"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(r.diagnostics.iter().any(|d| d.code == "TABLE_NOT_IN_MODEL"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_main_table_is_reported_once_and_stops() {
|
||||
let m = ModelSchema::parse(&json!([
|
||||
{"table":"t_child","typeId":"0","fields":[]}
|
||||
]))
|
||||
.unwrap();
|
||||
let r = validate(&form_ok(), &m);
|
||||
assert!(!r.ok());
|
||||
assert_eq!(r.error_count(), 1, "只报一次,不继续刷错");
|
||||
assert_eq!(r.diagnostics[0].code, "NO_MAIN_TABLE");
|
||||
}
|
||||
|
||||
/// warn 不算失败 —— 未知控件降级后仍可用。
|
||||
#[test]
|
||||
fn unknown_widget_is_warn_not_error() {
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{"__config__":{"jnpfKey":"futureWidget","tableName":"t_main","label":"x"},
|
||||
"__vModel__":"F_Title"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(r.ok(), "warn 不该让 ok=false");
|
||||
assert_eq!(r.warn_count(), 1);
|
||||
assert_eq!(r.diagnostics[0].code, "UNKNOWN_WIDGET");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_on_nullable_column_is_warn() {
|
||||
// F_Memo 允许 NULL,但被设成必填
|
||||
let f = FormSchema::parse(&json!({
|
||||
"formRef": "elForm",
|
||||
"fields": [{"__config__":{"jnpfKey":"input","tableName":"t_main","label":"备注","required":true},
|
||||
"__vModel__":"F_Memo"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let r = validate(&f, &model());
|
||||
assert!(r.ok());
|
||||
assert!(r.diagnostics.iter().any(|d| d.code == "REQUIRED_NULLABLE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn report_serializes_to_tool_shape() {
|
||||
let r = validate(&form_ok(), &model());
|
||||
let j = r.to_json();
|
||||
assert_eq!(j["ok"], true);
|
||||
assert_eq!(j["errorCount"], 0);
|
||||
assert!(j["diagnostics"].is_array());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! widget —— `jnpfKey` 控件分类表:**这张表决定数据怎么存**。
|
||||
//!
|
||||
//! ## 为什么需要它
|
||||
//!
|
||||
//! baseline 的表单 JSON 里有 **54 种** `jnpfKey`(实测 71 张表单统计),
|
||||
//! 但对「存数据」来说它们只分十来类:
|
||||
//!
|
||||
//! | 类别 | 举例 | 存成什么 | 接收入参 |
|
||||
//! |---|---|---|---|
|
||||
//! | 文本 | `input` `textarea` `editor` | 字符串 | ✅ |
|
||||
//! | 数值 | `inputNumber` `calculate` `rate` | 数字 | 视情况(`calculate` 只读) |
|
||||
//! | 日期时间 | `datePicker` `timePicker` `createTime` | 时间戳 / 字符串 | 视情况 |
|
||||
//! | 枚举 | `select` `radio` `checkbox` `switch` | 字符串 / 整数 | ✅ |
|
||||
//! | 实体引用 | `userSelect` `organizeSelect` `depSelect` | 对象 id | ✅(存 id) |
|
||||
//! | 系统生成 | `billRule` `createUser` `currOrganize` | — | ❌ 后端自动填 |
|
||||
//! | 子表 | `table` `tableGrid` | 独立物理表 | ❌ 走子表接口 |
|
||||
//! | 附件 | `uploadFile` `uploadImg` | JSON 字符串(URL 列表) | ✅ |
|
||||
//! | 布局 | `groupTitle` `divider` `tabItem` `rowFormItem` | 不占列 | ❌ |
|
||||
//!
|
||||
//! 🔴 **分类错了就是数据错**:把 `billRule`(单据号,系统生成)当普通文本接收,
|
||||
//! 会把用户传的任意字符串写进单号列,破坏业务编号规则;
|
||||
//! 把 `uploadFile` 当纯文本,前端 `JSON.parse` 会炸。
|
||||
//!
|
||||
//! ## 未知控件怎么办
|
||||
//!
|
||||
//! 按 PLAN §P2 的策略:**降级为文本并给出警告**,不阻断。
|
||||
//! 理由:新控件(官方每版都在加)如果直接拒,会让整张表单无法存取;
|
||||
//! 降级成文本至少能读能写,人工再修。但警告必须回报给 AI —— 见
|
||||
//! [`WidgetKind::Unknown`]。
|
||||
|
||||
/// 控件类别 —— 决定「怎么存、能不能接收入参」。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum WidgetKind {
|
||||
/// 文本(`input` / `textarea` / `editor` / `text` …)。
|
||||
Text,
|
||||
/// 数值(`inputNumber` / `rate` / `slider` …)。
|
||||
Number,
|
||||
/// 日期时间(`datePicker` / `timePicker` …)。
|
||||
DateTime,
|
||||
/// 枚举选择(`select` / `radio` / `checkbox` / `switch` / `cascader` …)。
|
||||
Enum,
|
||||
/// 实体引用(`userSelect` / `organizeSelect` / `depSelect` / `posSelect` …)——
|
||||
/// 值存的是**对象 id**,不是名称。
|
||||
EntityRef,
|
||||
/// 系统自动生成(`billRule` / `createUser` / `createTime` / `currOrganize` …)——
|
||||
/// **不接收入参**,由后端写入。
|
||||
SystemGenerated,
|
||||
/// 子表容器(`table` / `tableGrid` …)—— 数据在独立物理表,不占主表列。
|
||||
SubTable,
|
||||
/// 附件(`uploadFile` / `uploadImg`)—— 存 URL 列表的 JSON 字符串。
|
||||
Attachment,
|
||||
/// 布局(`groupTitle` / `divider` / `tabItem` …)—— 不占任何列。
|
||||
Layout,
|
||||
/// 计算字段(`calculate`)—— 只读,由公式算出。
|
||||
Computed,
|
||||
/// 未知控件 —— 降级为文本并警告。
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl WidgetKind {
|
||||
/// 该类别是否占一个**物理列**(决定要不要做列映射校验)。
|
||||
pub fn occupies_column(self) -> bool {
|
||||
!matches!(self, WidgetKind::Layout | WidgetKind::SubTable)
|
||||
}
|
||||
|
||||
/// 该类别是否允许从请求入参接收值。
|
||||
///
|
||||
/// 🔴 `SystemGenerated` / `Computed` / `SubTable` / `Layout` 一律拒绝 ——
|
||||
/// 让入参覆盖单号、创建人、计算结果,是最常见的「数据被写坏」来源。
|
||||
pub fn accepts_input(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
WidgetKind::Text
|
||||
| WidgetKind::Number
|
||||
| WidgetKind::DateTime
|
||||
| WidgetKind::Enum
|
||||
| WidgetKind::EntityRef
|
||||
| WidgetKind::Attachment
|
||||
)
|
||||
}
|
||||
|
||||
/// 稳定字符串(用于 JSON 输出与诊断信息)。
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
WidgetKind::Text => "text",
|
||||
WidgetKind::Number => "number",
|
||||
WidgetKind::DateTime => "dateTime",
|
||||
WidgetKind::Enum => "enum",
|
||||
WidgetKind::EntityRef => "entityRef",
|
||||
WidgetKind::SystemGenerated => "systemGenerated",
|
||||
WidgetKind::SubTable => "subTable",
|
||||
WidgetKind::Attachment => "attachment",
|
||||
WidgetKind::Layout => "layout",
|
||||
WidgetKind::Computed => "computed",
|
||||
WidgetKind::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `jnpfKey` → 类别。
|
||||
///
|
||||
/// 映射取自实测分布(71 张真表单 / 54 种控件,覆盖率见测试)。
|
||||
/// **新增控件时改这里,别改调用方** —— 保持分类逻辑的单点。
|
||||
pub fn classify(jnpf_key: &str) -> WidgetKind {
|
||||
match jnpf_key {
|
||||
// ---- 文本 ----
|
||||
"input" | "textarea" | "editor" | "text" | "link" | "colorPicker" | "inputColor"
|
||||
| "signature" | "location" | "address" | "barcode" | "qrcode" | "map" | "idNumber"
|
||||
| "phoneNumber" | "email" | "url" | "richText" | "codeEditor" => WidgetKind::Text,
|
||||
|
||||
// ---- 数值 ----
|
||||
"inputNumber" | "rate" | "slider" | "money" | "percent" => WidgetKind::Number,
|
||||
|
||||
// ---- 日期时间 ----
|
||||
"datePicker" | "timePicker" | "dateRange" | "timeRange" | "dateCalculate" => {
|
||||
WidgetKind::DateTime
|
||||
}
|
||||
|
||||
// ---- 枚举 ----
|
||||
"select" | "radio" | "checkbox" | "switch" | "cascader" | "treeSelect" | "multiSelect"
|
||||
| "autoComplete" | "selectMultiple" | "checkboxGroup" | "treeSelectMultiple" => {
|
||||
WidgetKind::Enum
|
||||
}
|
||||
|
||||
// ---- 实体引用(值 = 对象 id)----
|
||||
"userSelect" | "organizeSelect" | "depSelect" | "posSelect" | "roleSelect"
|
||||
| "groupSelect" | "usersSelect" | "relationForm" | "popupSelect" | "popupTableSelect"
|
||||
| "relationFormAttr" | "popupAttr" => WidgetKind::EntityRef,
|
||||
|
||||
// ---- 系统自动生成(不接收入参)----
|
||||
"billRule" | "createUser" | "createTime" | "modifyUser" | "modifyTime" | "currOrganize"
|
||||
| "currPosition" | "lastModifyUser" | "lastModifyTime" | "createUserId"
|
||||
| "modifyUserId" | "tenantId" => WidgetKind::SystemGenerated,
|
||||
|
||||
// ---- 子表 ----
|
||||
"table" | "tableGrid" | "tableGridTd" | "childTable" => WidgetKind::SubTable,
|
||||
|
||||
// ---- 附件 ----
|
||||
"uploadFile" | "uploadImg" | "uploadFileSingle" | "uploadImgSingle" | "imgupload"
|
||||
| "fileupload" => WidgetKind::Attachment,
|
||||
|
||||
// ---- 布局(不占列)----
|
||||
"groupTitle" | "divider" | "tabItem" | "tab" | "row" | "collapse" | "collapseItem"
|
||||
| "steps" | "stepsItem" | "card" | "alert" | "button" | "textTitle" | "title" => {
|
||||
WidgetKind::Layout
|
||||
}
|
||||
|
||||
// ---- 计算字段(只读)----
|
||||
"calculate" => WidgetKind::Computed,
|
||||
|
||||
_ => WidgetKind::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// 给未知控件用的人话提示(会进诊断信息)。
|
||||
pub fn unknown_hint(jnpf_key: &str) -> String {
|
||||
format!(
|
||||
"未知控件 `{jnpf_key}`(按文本降级处理)。\
|
||||
若它其实是布局/系统字段,存取会多写一列空值;\
|
||||
要精确支持,把 jnpf_key 补进 crates/sspf-lowcode/src/widget.rs 的 classify()"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 实测 top 12 控件必须全部被识别(覆盖率是硬指标,不是感觉)。
|
||||
#[test]
|
||||
fn top_widgets_are_all_classified() {
|
||||
// 来自 71 张真表单的分布统计
|
||||
let top = [
|
||||
("input", WidgetKind::Text, 267),
|
||||
("inputNumber", WidgetKind::Number, 88),
|
||||
("select", WidgetKind::Enum, 71),
|
||||
("datePicker", WidgetKind::DateTime, 71),
|
||||
("textarea", WidgetKind::Text, 42),
|
||||
("userSelect", WidgetKind::EntityRef, 36),
|
||||
("table", WidgetKind::SubTable, 28),
|
||||
("organizeSelect", WidgetKind::EntityRef, 25),
|
||||
("billRule", WidgetKind::SystemGenerated, 18),
|
||||
("radio", WidgetKind::Enum, 18),
|
||||
("groupTitle", WidgetKind::Layout, 14),
|
||||
("uploadFile", WidgetKind::Attachment, 12),
|
||||
];
|
||||
let mut covered = 0;
|
||||
let mut total = 0;
|
||||
for (key, want, count) in top {
|
||||
assert_eq!(classify(key), want, "{key} 分类错了");
|
||||
covered += count;
|
||||
total += count;
|
||||
}
|
||||
assert_eq!(covered, total);
|
||||
println!("top 12 控件全部识别,共 {covered} 个实例");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_generated_refuses_input() {
|
||||
for k in ["billRule", "createUser", "createTime", "currOrganize"] {
|
||||
let w = classify(k);
|
||||
assert_eq!(w, WidgetKind::SystemGenerated, "{k}");
|
||||
assert!(!w.accepts_input(), "{k} 不该接收入参");
|
||||
assert!(w.occupies_column(), "{k} 占一列(后端要写)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_occupies_no_column() {
|
||||
for k in ["groupTitle", "divider", "tabItem"] {
|
||||
let w = classify(k);
|
||||
assert_eq!(w, WidgetKind::Layout, "{k}");
|
||||
assert!(!w.occupies_column(), "{k} 不该占列");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_table_is_not_a_column() {
|
||||
let w = classify("table");
|
||||
assert_eq!(w, WidgetKind::SubTable);
|
||||
assert!(!w.occupies_column());
|
||||
assert!(!w.accepts_input());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_falls_back_to_text_with_hint() {
|
||||
assert_eq!(classify("someFutureWidget"), WidgetKind::Unknown);
|
||||
let h = unknown_hint("someFutureWidget");
|
||||
assert!(h.contains("someFutureWidget"));
|
||||
assert!(h.contains("widget.rs"), "提示要指明改哪里");
|
||||
}
|
||||
|
||||
/// 类别字符串必须唯一且稳定(它们会出现在 JSON 输出里,改成对账就漂了)。
|
||||
#[test]
|
||||
fn kind_names_are_unique() {
|
||||
let all = [
|
||||
WidgetKind::Text,
|
||||
WidgetKind::Number,
|
||||
WidgetKind::DateTime,
|
||||
WidgetKind::Enum,
|
||||
WidgetKind::EntityRef,
|
||||
WidgetKind::SystemGenerated,
|
||||
WidgetKind::SubTable,
|
||||
WidgetKind::Attachment,
|
||||
WidgetKind::Layout,
|
||||
WidgetKind::Computed,
|
||||
WidgetKind::Unknown,
|
||||
];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for k in all {
|
||||
assert!(seen.insert(k.as_str()), "类别名重复: {}", k.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user