oa_publish.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. """OA 审批应用发布校验与发布落库"""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Optional, Set, Tuple
  4. from sqlalchemy.orm import Session
  5. from app.crud import oa_approval as oa_crud
  6. from app.models.models import OaRole
  7. # 可填控件(FormCreate / 自建控件字典交集;布局类不计)
  8. FILLABLE_TYPES = frozenset(
  9. {
  10. "input",
  11. "textarea",
  12. "inputNumber",
  13. "number",
  14. "radio",
  15. "checkbox",
  16. "select",
  17. "switch",
  18. "datePicker",
  19. "date",
  20. "dateRange",
  21. "timePicker",
  22. "time",
  23. "phone",
  24. "image",
  25. "upload",
  26. "money",
  27. "dept",
  28. "region",
  29. "formula",
  30. "relatedApproval",
  31. "rate",
  32. "slider",
  33. "cascader",
  34. }
  35. )
  36. LAYOUT_TYPES = frozenset(
  37. {
  38. "fcRow",
  39. "col",
  40. "column",
  41. "fcTable",
  42. "html",
  43. "divider",
  44. "card",
  45. "space",
  46. "tabs",
  47. "tabPane",
  48. "group",
  49. "object",
  50. }
  51. )
  52. VALID_ASSIGNEE_TYPES = frozenset(
  53. {
  54. "users",
  55. "oa_roles",
  56. "dept_leader",
  57. "direct_supervisor",
  58. "initiator_select",
  59. }
  60. )
  61. VALID_NODE_TYPES = frozenset({"start", "approval", "cc", "condition", "end"})
  62. # 发布允许的控件 type(未知 type 拒绝)
  63. ALLOWED_CONTROL_TYPES = FILLABLE_TYPES | LAYOUT_TYPES
  64. CONDITION_ELIGIBLE_TYPES = frozenset(
  65. {
  66. "input",
  67. "inputNumber",
  68. "number",
  69. "money",
  70. "radio",
  71. "select",
  72. "datePicker",
  73. "date",
  74. }
  75. )
  76. def _extract_rules(form_schema: Any) -> List[Dict[str, Any]]:
  77. if form_schema is None:
  78. return []
  79. if isinstance(form_schema, list):
  80. return [r for r in form_schema if isinstance(r, dict)]
  81. if isinstance(form_schema, dict):
  82. rules = form_schema.get("rule") or form_schema.get("rules") or form_schema.get("fields")
  83. if isinstance(rules, list):
  84. return [r for r in rules if isinstance(r, dict)]
  85. # 单字段对象
  86. if form_schema.get("type") or form_schema.get("field"):
  87. return [form_schema]
  88. return []
  89. def _walk_form_rules(rules: List[Dict[str, Any]], out: List[Dict[str, Any]]) -> None:
  90. for rule in rules:
  91. out.append(rule)
  92. children = rule.get("children") or rule.get("props", {}).get("rule") or []
  93. if isinstance(children, list):
  94. _walk_form_rules([c for c in children if isinstance(c, dict)], out)
  95. def count_fillable_fields(form_schema: Any) -> int:
  96. flat: List[Dict[str, Any]] = []
  97. _walk_form_rules(_extract_rules(form_schema), flat)
  98. n = 0
  99. for rule in flat:
  100. t = (rule.get("type") or "").strip()
  101. if t in LAYOUT_TYPES:
  102. continue
  103. field = rule.get("field") or rule.get("name")
  104. if t in FILLABLE_TYPES or (field and t and t not in LAYOUT_TYPES):
  105. n += 1
  106. return n
  107. def _rule_use_in_condition(rule: Dict[str, Any]) -> bool:
  108. if rule.get("useInCondition") is True:
  109. return True
  110. props = rule.get("props") or {}
  111. return isinstance(props, dict) and props.get("useInCondition") is True
  112. def index_condition_fields(form_schema: Any) -> Dict[str, Dict[str, Any]]:
  113. """field -> rule(仅 useInCondition 且 type 合格)"""
  114. flat: List[Dict[str, Any]] = []
  115. _walk_form_rules(_extract_rules(form_schema), flat)
  116. out: Dict[str, Dict[str, Any]] = {}
  117. for rule in flat:
  118. t = (rule.get("type") or "").strip()
  119. field = (rule.get("field") or rule.get("name") or "").strip()
  120. if not field or t not in CONDITION_ELIGIBLE_TYPES:
  121. continue
  122. if _rule_use_in_condition(rule):
  123. out[field] = rule
  124. return out
  125. def normalize_use_in_condition_required(form_schema: Any) -> Any:
  126. """就地/深拷贝皆可:打标字段强制 required/$required。发布前调用。"""
  127. import copy
  128. schema = copy.deepcopy(form_schema) if form_schema is not None else {"rule": []}
  129. def walk(list_rules: List[Dict[str, Any]]) -> None:
  130. for rule in list_rules:
  131. if _rule_use_in_condition(rule):
  132. rule["useInCondition"] = True
  133. rule["$required"] = True
  134. rule["required"] = True
  135. props = rule.get("props")
  136. if isinstance(props, dict):
  137. props["useInCondition"] = True
  138. children = rule.get("children") or (rule.get("props") or {}).get("rule") or []
  139. if isinstance(children, list):
  140. walk([c for c in children if isinstance(c, dict)])
  141. if isinstance(schema, list):
  142. walk([r for r in schema if isinstance(r, dict)])
  143. elif isinstance(schema, dict):
  144. r = schema.get("rule")
  145. if isinstance(r, list):
  146. walk([x for x in r if isinstance(x, dict)])
  147. return schema
  148. def _node_type(node: Dict[str, Any]) -> str:
  149. return (node.get("type") or node.get("nodeType") or "").strip()
  150. def validate_flow_tree(flow_tree: Any) -> List[str]:
  151. errors: List[str] = []
  152. if not flow_tree or not isinstance(flow_tree, dict):
  153. return ["流程树不能为空"]
  154. root = flow_tree
  155. # 兼容 { root: node } 包装
  156. if "root" in flow_tree and isinstance(flow_tree["root"], dict):
  157. root = flow_tree["root"]
  158. if _node_type(root) != "start":
  159. errors.append("流程树根节点必须是发起人(start)")
  160. seen_end = False
  161. def walk(node: Optional[Dict[str, Any]], path: str) -> None:
  162. nonlocal seen_end
  163. if not node or not isinstance(node, dict):
  164. errors.append(f"{path}:节点缺失")
  165. return
  166. ntype = _node_type(node)
  167. if ntype not in VALID_NODE_TYPES:
  168. errors.append(f"{path}:不支持的节点类型「{ntype or '(空)'}」")
  169. return
  170. if ntype == "end":
  171. seen_end = True
  172. if node.get("child"):
  173. errors.append(f"{path}:结束节点后不应再有子节点")
  174. return
  175. if ntype in ("approval", "cc"):
  176. cfg = node.get("approverConfig") or node.get("approver_config") or {}
  177. if not isinstance(cfg, dict):
  178. cfg = {}
  179. # 抄送也需要明确接收人策略
  180. at = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  181. if not at:
  182. errors.append(f"{path}:未配置审批人/抄送人策略")
  183. elif at not in VALID_ASSIGNEE_TYPES:
  184. errors.append(f"{path}:不支持的审批人类型「{at}」")
  185. elif at == "users":
  186. ids = cfg.get("userIds") or cfg.get("user_ids") or []
  187. if not ids:
  188. errors.append(f"{path}:指定成员不能为空")
  189. elif at == "oa_roles":
  190. rids = cfg.get("oaRoleIds") or cfg.get("oa_role_ids") or []
  191. codes = cfg.get("oaRoleCodes") or cfg.get("oa_role_codes") or []
  192. if not rids and not codes:
  193. errors.append(f"{path}:工作流角色不能为空")
  194. # dept_leader / direct_supervisor / initiator_select:类型本身即完备
  195. if ntype == "condition":
  196. groups = node.get("conditionGroups") or node.get("condition_groups") or []
  197. if not isinstance(groups, list) or len(groups) < 1:
  198. errors.append(f"{path}:条件分支至少需要一组出线")
  199. else:
  200. for i, g in enumerate(groups):
  201. if not isinstance(g, dict):
  202. errors.append(f"{path}.条件组[{i}]:格式非法")
  203. continue
  204. is_default = bool(g.get("isDefault"))
  205. rules = g.get("rules") if isinstance(g.get("rules"), list) else []
  206. when = (g.get("when") or "").strip() if isinstance(g.get("when"), str) else ""
  207. valid_rules = [
  208. r
  209. for r in rules
  210. if isinstance(r, dict)
  211. and (r.get("field") or "").strip()
  212. and (r.get("op") or "").strip()
  213. and r.get("value") is not None
  214. and str(r.get("value")).strip() != ""
  215. ]
  216. if is_default:
  217. pass
  218. elif valid_rules:
  219. pass
  220. elif when and not valid_rules:
  221. errors.append(
  222. f"{path}.条件组[{i}]:请用可视化规则重新配置条件(不再支持仅公式)"
  223. )
  224. else:
  225. errors.append(f"{path}.条件组[{i}]:请完善条件分支规则")
  226. child = g.get("child")
  227. if not child:
  228. errors.append(f"{path}.条件组[{i}]:缺少下游节点")
  229. else:
  230. gname = g.get("name") or f"分支{i + 1}"
  231. walk(child if isinstance(child, dict) else None, f"{path}/{gname}")
  232. # 条件分支汇合后的主链(可选)
  233. merge = node.get("child")
  234. if merge is not None:
  235. if not isinstance(merge, dict):
  236. errors.append(f"{path}:汇合后子节点格式非法")
  237. else:
  238. walk(merge, f"{path}/汇合")
  239. return
  240. child = node.get("child")
  241. if child is None:
  242. if ntype != "end":
  243. errors.append(f"{path}:须连接到后续节点直至结束")
  244. return
  245. if not isinstance(child, dict):
  246. errors.append(f"{path}:子节点格式非法")
  247. return
  248. cname = child.get("name") or _node_type(child) or "next"
  249. walk(child, f"{path}/{cname}")
  250. walk(root, root.get("name") or "发起人")
  251. if not seen_end:
  252. errors.append("流程树未能到达结束节点")
  253. return errors
  254. def validate_condition_rules_against_form(form_schema: Any, flow_tree: Any) -> List[str]:
  255. indexed = index_condition_fields(form_schema)
  256. errors: List[str] = []
  257. seen: Set[str] = set()
  258. def collect_fields(node: Optional[Dict[str, Any]]) -> None:
  259. if not node or not isinstance(node, dict):
  260. return
  261. for g in node.get("conditionGroups") or node.get("condition_groups") or []:
  262. if not isinstance(g, dict) or g.get("isDefault"):
  263. continue
  264. rules = g.get("rules") if isinstance(g.get("rules"), list) else []
  265. for r in rules:
  266. if not isinstance(r, dict):
  267. continue
  268. field = (r.get("field") or "").strip()
  269. if not field or field in seen:
  270. continue
  271. seen.add(field)
  272. if field not in indexed:
  273. errors.append(f"条件引用了无效字段:{field}")
  274. child = g.get("child")
  275. if isinstance(child, dict):
  276. collect_fields(child)
  277. child = node.get("child")
  278. if isinstance(child, dict):
  279. collect_fields(child)
  280. root = flow_tree
  281. if isinstance(flow_tree, dict) and isinstance(flow_tree.get("root"), dict):
  282. root = flow_tree["root"]
  283. collect_fields(root if isinstance(root, dict) else None)
  284. return errors
  285. def validate_oa_roles_referenced(
  286. db: Session, *, tenant_no: str, flow_tree: Any
  287. ) -> List[str]:
  288. role_ids: Set[str] = set()
  289. role_codes: Set[str] = set()
  290. def collect(node: Optional[Dict[str, Any]]) -> None:
  291. if not node or not isinstance(node, dict):
  292. return
  293. cfg = node.get("approverConfig") or {}
  294. if isinstance(cfg, dict):
  295. at = (cfg.get("assigneeType") or "").strip()
  296. if at == "oa_roles":
  297. for rid in cfg.get("oaRoleIds") or cfg.get("oa_role_ids") or []:
  298. if rid:
  299. role_ids.add(str(rid))
  300. for code in cfg.get("oaRoleCodes") or cfg.get("oa_role_codes") or []:
  301. if code:
  302. role_codes.add(str(code).upper())
  303. child = node.get("child")
  304. if isinstance(child, dict):
  305. collect(child)
  306. for g in node.get("conditionGroups") or []:
  307. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  308. collect(g["child"])
  309. root = flow_tree
  310. if isinstance(flow_tree, dict) and isinstance(flow_tree.get("root"), dict):
  311. root = flow_tree["root"]
  312. collect(root if isinstance(root, dict) else None)
  313. errors: List[str] = []
  314. if role_ids:
  315. rows = (
  316. db.query(OaRole)
  317. .filter(
  318. OaRole.id.in_(list(role_ids)),
  319. OaRole.tenant_no == tenant_no,
  320. OaRole.del_flag == 0,
  321. )
  322. .all()
  323. )
  324. found = {r.id: r for r in rows}
  325. for rid in role_ids:
  326. r = found.get(rid)
  327. if not r:
  328. errors.append(f"引用的工作流角色不存在:{rid}")
  329. elif r.status != "1":
  330. errors.append(f"工作流角色已停用:{r.role_name or rid}")
  331. if role_codes:
  332. rows = (
  333. db.query(OaRole)
  334. .filter(
  335. OaRole.role_code.in_(list(role_codes)),
  336. OaRole.tenant_no == tenant_no,
  337. OaRole.del_flag == 0,
  338. )
  339. .all()
  340. )
  341. found_codes = {r.role_code.upper(): r for r in rows}
  342. for code in role_codes:
  343. r = found_codes.get(code)
  344. if not r:
  345. errors.append(f"引用的工作流角色编码不存在:{code}")
  346. elif r.status != "1":
  347. errors.append(f"工作流角色已停用:{r.role_name or code}")
  348. return errors
  349. def validate_control_types(form_schema: Any) -> List[str]:
  350. flat: List[Dict[str, Any]] = []
  351. _walk_form_rules(_extract_rules(form_schema), flat)
  352. errors: List[str] = []
  353. unknown: Set[str] = set()
  354. for rule in flat:
  355. t = (rule.get("type") or "").strip()
  356. if not t:
  357. continue
  358. if t not in ALLOWED_CONTROL_TYPES:
  359. unknown.add(t)
  360. for t in sorted(unknown):
  361. errors.append(f"不支持的表单控件类型:{t}")
  362. return errors
  363. def validate_draft_for_publish(
  364. db: Session,
  365. *,
  366. tenant_no: str,
  367. form_schema: Any,
  368. flow_tree: Any,
  369. basic: Optional[Dict[str, Any]] = None,
  370. ) -> List[str]:
  371. errors: List[str] = []
  372. app_name = ""
  373. if basic and isinstance(basic, dict):
  374. app_name = (basic.get("appName") or "").strip()
  375. if not app_name:
  376. # 校验侧也可能只传 schema;名称在 publish 时再查 app
  377. pass
  378. if count_fillable_fields(form_schema) < 1:
  379. errors.append("表单至少需要 1 个可填字段")
  380. form_schema = normalize_use_in_condition_required(form_schema)
  381. errors.extend(validate_control_types(form_schema))
  382. errors.extend(validate_flow_tree(flow_tree))
  383. errors.extend(validate_condition_rules_against_form(form_schema, flow_tree))
  384. errors.extend(validate_oa_roles_referenced(db, tenant_no=tenant_no, flow_tree=flow_tree))
  385. return errors
  386. def publish_app(
  387. db: Session,
  388. app_id: str,
  389. *,
  390. tenant_no: str,
  391. user_id: Optional[str] = None,
  392. ) -> Tuple[Dict[str, Any], List[str]]:
  393. """
  394. 校验并发布当前草稿。
  395. 成功返回 (draft_dict_like_published_info, []);
  396. 失败返回 ({}, errors)。
  397. """
  398. app = oa_crud.get_app(db, app_id, tenant_no)
  399. if not app:
  400. return {}, ["应用不存在"]
  401. if not (app.app_name or "").strip():
  402. return {}, ["应用名称不能为空"]
  403. draft_payload = oa_crud.get_or_create_draft(db, app_id, tenant_no=tenant_no, user_id=user_id)
  404. form_schema = draft_payload.get("formSchemaJson")
  405. form_schema = normalize_use_in_condition_required(form_schema)
  406. flow_tree = draft_payload.get("flowTreeJson")
  407. errors = validate_draft_for_publish(
  408. db,
  409. tenant_no=tenant_no,
  410. form_schema=form_schema,
  411. flow_tree=flow_tree,
  412. basic=draft_payload.get("basic"),
  413. )
  414. if errors:
  415. return {}, errors
  416. draft = oa_crud._find_draft(db, app_id, tenant_no)
  417. if not draft:
  418. return {}, ["草稿不存在"]
  419. draft.form_schema_json = oa_crud._dumps(form_schema)
  420. from datetime import datetime
  421. from app.models.models import OaAppVersion
  422. now = datetime.now()
  423. olds = (
  424. db.query(OaAppVersion)
  425. .filter(
  426. OaAppVersion.app_id == app_id,
  427. OaAppVersion.tenant_no == tenant_no,
  428. OaAppVersion.is_latest_published == "1",
  429. OaAppVersion.del_flag == 0,
  430. )
  431. .all()
  432. )
  433. for old in olds:
  434. old.is_latest_published = "0"
  435. old.update_by = user_id
  436. old.update_time = now
  437. db.add(old)
  438. draft.status = "published"
  439. draft.is_latest_published = "1"
  440. draft.update_by = user_id
  441. draft.update_time = now
  442. db.add(draft)
  443. # 发布后不应再残留其它草稿(并发/重复创建等);否则列表 hasDraft 仍为 true
  444. leftover_drafts = (
  445. db.query(OaAppVersion)
  446. .filter(
  447. OaAppVersion.app_id == app_id,
  448. OaAppVersion.tenant_no == tenant_no,
  449. OaAppVersion.status == "draft",
  450. OaAppVersion.del_flag == 0,
  451. OaAppVersion.id != draft.id,
  452. )
  453. .all()
  454. )
  455. for leftover in leftover_drafts:
  456. leftover.del_flag = 1
  457. leftover.update_by = user_id
  458. leftover.update_time = now
  459. db.add(leftover)
  460. app.update_by = user_id
  461. app.update_time = now
  462. db.add(app)
  463. db.commit()
  464. db.refresh(draft)
  465. return {
  466. "appId": app.id,
  467. "versionId": draft.id,
  468. "versionNo": draft.version_no,
  469. "status": draft.status,
  470. "isLatestPublished": draft.is_latest_published,
  471. "appName": app.app_name,
  472. }, []