feat(oa): validate visual condition rules on publish
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
e1c41af308
commit
9ae239347a
2 files changed
+219
No files matched your search
@@ -72,6 +72,10 @@ VALID_NODE_TYPES = frozenset({"start", "approval", "cc", "condition", "end"})
|
||||
# 发布允许的控件 type(未知 type 拒绝)
|
||||
ALLOWED_CONTROL_TYPES = FILLABLE_TYPES | LAYOUT_TYPES | frozenset({"oaAttachment"})
|
||||
|
||||
CONDITION_ELIGIBLE_TYPES = frozenset(
|
||||
{"inputNumber", "number", "money", "radio", "select", "datePicker", "date"}
|
||||
)
|
||||
|
||||
|
||||
def _extract_rules(form_schema: Any) -> List[Dict[str, Any]]:
|
||||
if form_schema is None:
|
||||
@@ -110,6 +114,56 @@ def count_fillable_fields(form_schema: Any) -> int:
|
||||
return n
|
||||
|
||||
|
||||
def _rule_use_in_condition(rule: Dict[str, Any]) -> bool:
|
||||
if rule.get("useInCondition") is True:
|
||||
return True
|
||||
props = rule.get("props") or {}
|
||||
return isinstance(props, dict) and props.get("useInCondition") is True
|
||||
|
||||
|
||||
def index_condition_fields(form_schema: Any) -> Dict[str, Dict[str, Any]]:
|
||||
"""field -> rule(仅 useInCondition 且 type 合格)"""
|
||||
flat: List[Dict[str, Any]] = []
|
||||
_walk_form_rules(_extract_rules(form_schema), flat)
|
||||
out: Dict[str, Dict[str, Any]] = {}
|
||||
for rule in flat:
|
||||
t = (rule.get("type") or "").strip()
|
||||
field = (rule.get("field") or rule.get("name") or "").strip()
|
||||
if not field or t not in CONDITION_ELIGIBLE_TYPES:
|
||||
continue
|
||||
if _rule_use_in_condition(rule):
|
||||
out[field] = rule
|
||||
return out
|
||||
|
||||
|
||||
def normalize_use_in_condition_required(form_schema: Any) -> Any:
|
||||
"""就地/深拷贝皆可:打标字段强制 required/$required。发布前调用。"""
|
||||
import copy
|
||||
|
||||
schema = copy.deepcopy(form_schema) if form_schema is not None else {"rule": []}
|
||||
|
||||
def walk(list_rules: List[Dict[str, Any]]) -> None:
|
||||
for rule in list_rules:
|
||||
if _rule_use_in_condition(rule):
|
||||
rule["useInCondition"] = True
|
||||
rule["$required"] = True
|
||||
rule["required"] = True
|
||||
props = rule.get("props")
|
||||
if isinstance(props, dict):
|
||||
props["useInCondition"] = True
|
||||
children = rule.get("children") or (rule.get("props") or {}).get("rule") or []
|
||||
if isinstance(children, list):
|
||||
walk([c for c in children if isinstance(c, dict)])
|
||||
|
||||
if isinstance(schema, list):
|
||||
walk([r for r in schema if isinstance(r, dict)])
|
||||
elif isinstance(schema, dict):
|
||||
r = schema.get("rule")
|
||||
if isinstance(r, list):
|
||||
walk([x for x in r if isinstance(x, dict)])
|
||||
return schema
|
||||
|
||||
|
||||
def _node_type(node: Dict[str, Any]) -> str:
|
||||
return (node.get("type") or node.get("nodeType") or "").strip()
|
||||
|
||||
@@ -175,6 +229,28 @@ def validate_flow_tree(flow_tree: Any) -> List[str]:
|
||||
if not isinstance(g, dict):
|
||||
errors.append(f"{path}.条件组[{i}]:格式非法")
|
||||
continue
|
||||
is_default = bool(g.get("isDefault"))
|
||||
rules = g.get("rules") if isinstance(g.get("rules"), list) else []
|
||||
when = (g.get("when") or "").strip() if isinstance(g.get("when"), str) else ""
|
||||
valid_rules = [
|
||||
r
|
||||
for r in rules
|
||||
if isinstance(r, dict)
|
||||
and (r.get("field") or "").strip()
|
||||
and (r.get("op") or "").strip()
|
||||
and r.get("value") is not None
|
||||
and str(r.get("value")).strip() != ""
|
||||
]
|
||||
if is_default:
|
||||
pass
|
||||
elif valid_rules:
|
||||
pass
|
||||
elif when and not valid_rules:
|
||||
errors.append(
|
||||
f"{path}.条件组[{i}]:请用可视化规则重新配置条件(不再支持仅公式)"
|
||||
)
|
||||
else:
|
||||
errors.append(f"{path}.条件组[{i}]:请完善条件分支规则")
|
||||
child = g.get("child")
|
||||
if not child:
|
||||
errors.append(f"{path}.条件组[{i}]:缺少下游节点")
|
||||
@@ -201,6 +277,41 @@ def validate_flow_tree(flow_tree: Any) -> List[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def validate_condition_rules_against_form(form_schema: Any, flow_tree: Any) -> List[str]:
|
||||
indexed = index_condition_fields(form_schema)
|
||||
errors: List[str] = []
|
||||
seen: Set[str] = set()
|
||||
|
||||
def collect_fields(node: Optional[Dict[str, Any]]) -> None:
|
||||
if not node or not isinstance(node, dict):
|
||||
return
|
||||
for g in node.get("conditionGroups") or node.get("condition_groups") or []:
|
||||
if not isinstance(g, dict) or g.get("isDefault"):
|
||||
continue
|
||||
rules = g.get("rules") if isinstance(g.get("rules"), list) else []
|
||||
for r in rules:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
field = (r.get("field") or "").strip()
|
||||
if not field or field in seen:
|
||||
continue
|
||||
seen.add(field)
|
||||
if field not in indexed:
|
||||
errors.append(f"条件引用了无效字段:{field}")
|
||||
child = g.get("child")
|
||||
if isinstance(child, dict):
|
||||
collect_fields(child)
|
||||
child = node.get("child")
|
||||
if isinstance(child, dict):
|
||||
collect_fields(child)
|
||||
|
||||
root = flow_tree
|
||||
if isinstance(flow_tree, dict) and isinstance(flow_tree.get("root"), dict):
|
||||
root = flow_tree["root"]
|
||||
collect_fields(root if isinstance(root, dict) else None)
|
||||
return errors
|
||||
|
||||
|
||||
def validate_oa_roles_referenced(
|
||||
db: Session, *, tenant_no: str, flow_tree: Any
|
||||
) -> List[str]:
|
||||
@@ -303,8 +414,10 @@ def validate_draft_for_publish(
|
||||
pass
|
||||
if count_fillable_fields(form_schema) < 1:
|
||||
errors.append("表单至少需要 1 个可填字段")
|
||||
form_schema = normalize_use_in_condition_required(form_schema)
|
||||
errors.extend(validate_control_types(form_schema))
|
||||
errors.extend(validate_flow_tree(flow_tree))
|
||||
errors.extend(validate_condition_rules_against_form(form_schema, flow_tree))
|
||||
errors.extend(validate_oa_roles_referenced(db, tenant_no=tenant_no, flow_tree=flow_tree))
|
||||
return errors
|
||||
|
||||
@@ -329,6 +442,7 @@ def publish_app(
|
||||
|
||||
draft_payload = oa_crud.get_or_create_draft(db, app_id, tenant_no=tenant_no, user_id=user_id)
|
||||
form_schema = draft_payload.get("formSchemaJson")
|
||||
form_schema = normalize_use_in_condition_required(form_schema)
|
||||
flow_tree = draft_payload.get("flowTreeJson")
|
||||
errors = validate_draft_for_publish(
|
||||
db,
|
||||
@@ -344,6 +458,8 @@ def publish_app(
|
||||
if not draft:
|
||||
return {}, ["草稿不存在"]
|
||||
|
||||
draft.form_schema_json = oa_crud._dumps(form_schema)
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.models import OaAppVersion
|
||||
|
||||
@@ -25,6 +25,42 @@ def _linear_ok_flow():
|
||||
}
|
||||
|
||||
|
||||
def _condition_flow(rules=None, when=None, is_default=False):
|
||||
return {
|
||||
"type": "start",
|
||||
"name": "发起人",
|
||||
"child": {
|
||||
"type": "condition",
|
||||
"name": "条件",
|
||||
"conditionGroups": [
|
||||
{
|
||||
"name": "分支1",
|
||||
"rules": rules if rules is not None else [],
|
||||
"when": when,
|
||||
"isDefault": False,
|
||||
"child": {
|
||||
"type": "approval",
|
||||
"name": "审批A",
|
||||
"approverConfig": {"assigneeType": "dept_leader"},
|
||||
"child": {"type": "end", "name": "结束"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "默认",
|
||||
"rules": [],
|
||||
"isDefault": True,
|
||||
"child": {
|
||||
"type": "approval",
|
||||
"name": "审批B",
|
||||
"approverConfig": {"assigneeType": "dept_leader"},
|
||||
"child": {"type": "end", "name": "结束"},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class TestOaPublishValidate(unittest.TestCase):
|
||||
def test_count_fillable_fields(self):
|
||||
schema = {
|
||||
@@ -140,5 +176,72 @@ class TestOaPublishValidate(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestConditionPublish(unittest.TestCase):
|
||||
def test_when_only_rejected(self):
|
||||
errs = validate_flow_tree(_condition_flow(rules=[], when="{days} > 3"))
|
||||
self.assertTrue(any("可视化" in e or "重新配置" in e or "rules" in e for e in errs))
|
||||
|
||||
def test_rules_empty_non_default_rejected(self):
|
||||
errs = validate_flow_tree(_condition_flow(rules=[]))
|
||||
self.assertTrue(any("条件" in e for e in errs))
|
||||
|
||||
def test_rules_ok(self):
|
||||
errs = validate_flow_tree(
|
||||
_condition_flow(rules=[{"field": "days", "op": ">", "value": 3}])
|
||||
)
|
||||
self.assertEqual(errs, [])
|
||||
|
||||
def test_invalid_field_reference(self):
|
||||
db = MagicMock()
|
||||
with patch(
|
||||
"app.services.oa_publish.validate_oa_roles_referenced",
|
||||
return_value=[],
|
||||
):
|
||||
errs = validate_draft_for_publish(
|
||||
db,
|
||||
tenant_no="zkxw",
|
||||
form_schema={
|
||||
"rule": [
|
||||
{
|
||||
"type": "inputNumber",
|
||||
"field": "days",
|
||||
"title": "天数",
|
||||
"useInCondition": True,
|
||||
"$required": True,
|
||||
}
|
||||
]
|
||||
},
|
||||
flow_tree=_condition_flow(
|
||||
rules=[{"field": "other", "op": ">", "value": 1}]
|
||||
),
|
||||
)
|
||||
self.assertTrue(any("无效字段" in e or "other" in e for e in errs))
|
||||
|
||||
def test_field_not_flagged_rejected(self):
|
||||
db = MagicMock()
|
||||
with patch(
|
||||
"app.services.oa_publish.validate_oa_roles_referenced",
|
||||
return_value=[],
|
||||
):
|
||||
errs = validate_draft_for_publish(
|
||||
db,
|
||||
tenant_no="zkxw",
|
||||
form_schema={
|
||||
"rule": [
|
||||
{
|
||||
"type": "inputNumber",
|
||||
"field": "days",
|
||||
"title": "天数",
|
||||
"useInCondition": False,
|
||||
}
|
||||
]
|
||||
},
|
||||
flow_tree=_condition_flow(
|
||||
rules=[{"field": "days", "op": ">", "value": 3}]
|
||||
),
|
||||
)
|
||||
self.assertTrue(any("无效字段" in e or "参与" in e for e in errs))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user