oa_owner_fields.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """OA 归属人 / 归属部门:只读强制回填与校验辅助"""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Optional
  4. def _walk_rules(rules: Any, out: List[dict]) -> None:
  5. if not isinstance(rules, list):
  6. return
  7. for r in rules:
  8. if not isinstance(r, dict):
  9. continue
  10. out.append(r)
  11. children = r.get("children") or (r.get("props") or {}).get("rule") or []
  12. if isinstance(children, list):
  13. _walk_rules(children, out)
  14. def _schema_rules(schema: Any) -> List[dict]:
  15. if isinstance(schema, list):
  16. out: List[dict] = []
  17. _walk_rules(schema, out)
  18. return out
  19. if not isinstance(schema, dict):
  20. return []
  21. out: List[dict] = []
  22. _walk_rules(schema.get("rule") or schema.get("rules") or [], out)
  23. return out
  24. def _rule_props(rule: dict) -> dict:
  25. props = rule.get("props")
  26. return props if isinstance(props, dict) else {}
  27. def _allow_modify(rule: dict) -> bool:
  28. return _rule_props(rule).get("allowModify") is True
  29. def apply_owner_field_defaults(
  30. schema: Any,
  31. form_data: Optional[Dict[str, Any]],
  32. *,
  33. user_id: str,
  34. user_name: str,
  35. dept_id: Optional[str],
  36. dept_name: Optional[str],
  37. ) -> Dict[str, Any]:
  38. """
  39. 归属字段处理:
  40. - allowModify 为假:强制写入当前发起人 / 主部门(防篡改)
  41. - allowModify 为真且字段为空:补默认值
  42. """
  43. data = dict(form_data or {})
  44. uid = (user_id or "").strip()
  45. uname = (user_name or "").strip() or uid
  46. did = (dept_id or "").strip()
  47. dname = (dept_name or "").strip() or did
  48. person_val = {"id": uid, "name": uname} if uid else None
  49. dept_val = {"id": did, "name": dname} if did else None
  50. for rule in _schema_rules(schema):
  51. typ = str(rule.get("type") or "")
  52. field = str(rule.get("field") or "").strip()
  53. if not field:
  54. continue
  55. allow = _allow_modify(rule)
  56. cur = data.get(field)
  57. empty = cur is None or cur == "" or cur == [] or (
  58. isinstance(cur, dict) and not str(cur.get("id") or "").strip()
  59. )
  60. if typ == "ownerPerson" and person_val:
  61. if not allow or empty:
  62. data[field] = dict(person_val)
  63. elif typ == "ownerDept" and dept_val:
  64. if not allow or empty:
  65. data[field] = dict(dept_val)
  66. return data