oa_engine.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  1. """OA 审批运行时引擎(钉钉式竖向树)"""
  2. from __future__ import annotations
  3. import json
  4. import re
  5. from collections import OrderedDict
  6. from datetime import datetime
  7. from typing import Any, Dict, List, Optional, Tuple
  8. from sqlalchemy.orm import Session
  9. from app.core.utils import generate_uuid
  10. from app.crud import oa_approval as oa_crud
  11. from app.models.models import (
  12. OaApp,
  13. OaAppVersion,
  14. OaInstance,
  15. OaInstanceEvent,
  16. OaRelation,
  17. OaRole,
  18. OaTask,
  19. SysDept,
  20. SysUser,
  21. )
  22. from app.services.oa_assignee import AssigneeResolveError, resolve_assignees
  23. from app.services.oa_formula import FormulaError, apply_formulas_and_linkages, eval_formula
  24. class OaEngineError(ValueError):
  25. """引擎业务错误"""
  26. _AUTO_PASS_COMMENT = "系统自动通过"
  27. def _loads(text: Optional[str], default: Any = None) -> Any:
  28. if text is None or text == "":
  29. return default
  30. if not isinstance(text, str):
  31. return text
  32. try:
  33. return json.loads(text)
  34. except (TypeError, ValueError):
  35. return default
  36. def _dumps(data: Any) -> str:
  37. return json.dumps(data if data is not None else {}, ensure_ascii=False)
  38. def _normalize_initiator_select_by_node(raw: Any) -> Dict[str, List[str]]:
  39. if not isinstance(raw, dict):
  40. return {}
  41. out: Dict[str, List[str]] = {}
  42. for k, v in raw.items():
  43. nid = str(k or "").strip()
  44. if not nid or not isinstance(v, (list, tuple)):
  45. continue
  46. ids: List[str] = []
  47. seen = set()
  48. for x in v:
  49. uid = str(x or "").strip()
  50. if uid and uid not in seen:
  51. seen.add(uid)
  52. ids.append(uid)
  53. out[nid] = ids
  54. return out
  55. def _ids_for_initiator_select_node(
  56. select_by_node: Optional[Dict[str, List[str]]], node_id: str
  57. ) -> List[str]:
  58. m = select_by_node or {}
  59. nid = str(node_id or "").strip()
  60. if not nid:
  61. return []
  62. return list(m.get(nid) or [])
  63. def _load_initiator_select_by_node(inst: Any) -> Dict[str, List[str]]:
  64. return _normalize_initiator_select_by_node(
  65. _loads(getattr(inst, "initiator_select_json", None), {}) or {}
  66. )
  67. def _node_type(node: Dict[str, Any]) -> str:
  68. return (node.get("type") or "").strip()
  69. def _subtree_contains(node: Optional[Dict[str, Any]], node_id: str) -> bool:
  70. """节点子树(含自身、child、条件分支)是否包含指定 id。"""
  71. if not isinstance(node, dict):
  72. return False
  73. if (node.get("id") or "") == node_id:
  74. return True
  75. child = node.get("child")
  76. if isinstance(child, dict) and _subtree_contains(child, node_id):
  77. return True
  78. for g in node.get("conditionGroups") or []:
  79. if isinstance(g, dict) and _subtree_contains(g.get("child"), node_id):
  80. return True
  81. return False
  82. def _merge_after_branch_end(
  83. root: Dict[str, Any], end_id: str
  84. ) -> Optional[Dict[str, Any]]:
  85. """若 end 落在某条件分支组内,且该条件节点有汇合后 child,则返回汇合节点。"""
  86. def walk(node: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
  87. if not isinstance(node, dict):
  88. return None
  89. if _node_type(node) == "condition":
  90. for g in node.get("conditionGroups") or []:
  91. if not isinstance(g, dict):
  92. continue
  93. if _subtree_contains(g.get("child"), end_id):
  94. merge = node.get("child")
  95. return merge if isinstance(merge, dict) else None
  96. merge_child = node.get("child")
  97. if isinstance(merge_child, dict):
  98. return walk(merge_child)
  99. return None
  100. child = node.get("child")
  101. if isinstance(child, dict):
  102. return walk(child)
  103. return None
  104. return walk(root)
  105. def _flow_root(flow_tree: Any) -> Dict[str, Any]:
  106. if not isinstance(flow_tree, dict):
  107. raise OaEngineError("流程树无效")
  108. if isinstance(flow_tree.get("root"), dict):
  109. return flow_tree["root"]
  110. return flow_tree
  111. def _find_node(root: Dict[str, Any], node_key: str) -> Optional[Dict[str, Any]]:
  112. if not root or not node_key:
  113. return None
  114. if (root.get("id") or "") == node_key:
  115. return root
  116. child = root.get("child")
  117. if isinstance(child, dict):
  118. found = _find_node(child, node_key)
  119. if found:
  120. return found
  121. for g in root.get("conditionGroups") or []:
  122. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  123. found = _find_node(g["child"], node_key)
  124. if found:
  125. return found
  126. return None
  127. def _flow_node_key_order(root: Dict[str, Any]) -> Dict[str, int]:
  128. """按流程树先序遍历为 node.id 分配稳定序号(用于详情时间轴排序)。"""
  129. order: Dict[str, int] = {}
  130. counter = 0
  131. def walk(node: Any) -> None:
  132. nonlocal counter
  133. if not isinstance(node, dict):
  134. return
  135. nid = (node.get("id") or "").strip()
  136. if nid and nid not in order:
  137. order[nid] = counter
  138. counter += 1
  139. if _node_type(node) == "condition":
  140. for g in node.get("conditionGroups") or []:
  141. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  142. walk(g["child"])
  143. child = node.get("child")
  144. if isinstance(child, dict):
  145. walk(child)
  146. walk(root)
  147. return order
  148. def _next_task_order_num(db: Session, instance_id: str) -> int:
  149. """同一实例内任务展示序号取 max+1(无任务从 1 起)。"""
  150. rows = (
  151. db.query(OaTask.order_num)
  152. .filter(OaTask.instance_id == instance_id, OaTask.del_flag == 0)
  153. .all()
  154. )
  155. vals = [int(r[0]) for r in rows if r[0] is not None]
  156. return (max(vals) + 1) if vals else 1
  157. def _sort_tasks_for_detail(
  158. tasks: List[OaTask], *, flow_root: Optional[Dict[str, Any]]
  159. ) -> List[OaTask]:
  160. """详情时间轴:按流程树节点顺序,再 order_num / create_time(兼容旧数据同秒创建)。"""
  161. node_order = _flow_node_key_order(flow_root) if isinstance(flow_root, dict) else {}
  162. far = 10**9
  163. def key(t: OaTask) -> Tuple[int, int, int, datetime, str]:
  164. nk = (t.node_key or "").strip()
  165. return (
  166. int(getattr(t, "round_no", None) or 1),
  167. node_order.get(nk, far),
  168. int(t.order_num) if t.order_num is not None else 0,
  169. t.create_time or datetime.min,
  170. t.id or "",
  171. )
  172. return sorted(tasks, key=key)
  173. def _fmt_dt(dt: Any) -> str:
  174. if not dt:
  175. return ""
  176. if hasattr(dt, "strftime"):
  177. return dt.strftime("%Y-%m-%d %H:%M:%S")
  178. return str(dt)
  179. def _terminal_item(status: str, title: str, inst: Any) -> Dict[str, Any]:
  180. return {
  181. "kind": "terminal",
  182. "roundNo": getattr(inst, "current_round", None) or 1,
  183. "title": title,
  184. "status": status,
  185. "assigneeUserId": "",
  186. "assigneeUserName": "",
  187. "timestamp": _fmt_dt(getattr(inst, "update_time", None)),
  188. "commentText": "",
  189. "nodeKey": "",
  190. "taskType": "",
  191. }
  192. def _task_round(t: Any) -> int:
  193. v = getattr(t, "round_no", None)
  194. try:
  195. if v is None:
  196. return 1
  197. return int(v)
  198. except (TypeError, ValueError):
  199. return 1
  200. def _append_pending_nodes(
  201. items: List[Dict[str, Any]],
  202. *,
  203. flow_root: Dict[str, Any],
  204. reached_keys: set,
  205. round_no: int,
  206. ) -> None:
  207. """兜底:按整棵树先序挂未到达节点(无路径解析 / 无人员)。"""
  208. order = _flow_node_key_order(flow_root)
  209. for nid, _idx in sorted(order.items(), key=lambda x: x[1]):
  210. node = _find_node(flow_root, nid)
  211. if not node:
  212. continue
  213. nt = _node_type(node)
  214. if nt not in ("approval", "cc", "end") or nid in reached_keys:
  215. continue
  216. if nt == "end":
  217. title = node.get("name") or "结束"
  218. elif nt == "cc":
  219. title = node.get("name") or "抄送人"
  220. else:
  221. title = node.get("name") or "审批人"
  222. items.append(
  223. {
  224. "kind": "pending_node",
  225. "roundNo": round_no,
  226. "title": title,
  227. "status": "not_reached",
  228. "assigneeUserId": "",
  229. "assigneeUserName": "",
  230. "timestamp": "",
  231. "commentText": "",
  232. "nodeKey": nid,
  233. "taskType": nt,
  234. "signMode": "",
  235. "people": [],
  236. }
  237. )
  238. def _pending_people_for_node(
  239. db: Session,
  240. *,
  241. node: Dict[str, Any],
  242. tenant_no: str,
  243. initiator_user_id: str,
  244. initiator_dept_id: Optional[str],
  245. advanced: Dict[str, Any],
  246. initiator_select_by_node: Optional[Dict[str, List[str]]],
  247. ) -> Tuple[List[Dict[str, Any]], str, str]:
  248. """解析未到达节点的展示人员与签批模式。返回 (people, sign_mode, resolve_source)。"""
  249. ntype = _node_type(node)
  250. cfg = node.get("approverConfig") or {}
  251. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  252. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "").strip()
  253. if ntype == "cc":
  254. sign_mode = "cc"
  255. elif not sign_mode and assignee_type != "initiator_select":
  256. sign_mode = "or"
  257. people: List[Dict[str, Any]] = []
  258. node_select_ids = _ids_for_initiator_select_node(
  259. initiator_select_by_node, node.get("id") or ""
  260. )
  261. if assignee_type == "initiator_select":
  262. for uid in node_select_ids:
  263. people.append(
  264. {
  265. "id": uid,
  266. "nickName": "", # 下方统一补名
  267. "status": "not_reached",
  268. "timestamp": "",
  269. "commentText": "",
  270. "taskId": "",
  271. }
  272. )
  273. else:
  274. try:
  275. assignees, _meta = resolve_assignees(
  276. db,
  277. tenant_no=tenant_no,
  278. assignee_config=cfg,
  279. initiator_user_id=initiator_user_id,
  280. initiator_dept_id=initiator_dept_id,
  281. advanced=advanced,
  282. initiator_select_user_ids=node_select_ids,
  283. )
  284. for uid in assignees:
  285. people.append(
  286. {
  287. "id": uid,
  288. "nickName": "",
  289. "status": "not_reached",
  290. "timestamp": "",
  291. "commentText": "",
  292. "taskId": "",
  293. }
  294. )
  295. except AssigneeResolveError:
  296. people = []
  297. if people:
  298. name_map = _user_name_map(db, [p["id"] for p in people if p.get("id")])
  299. for p in people:
  300. p["nickName"] = name_map.get(p["id"], "") or p["id"]
  301. return people, sign_mode, assignee_type
  302. def _iter_resolved_path_nodes(
  303. root: Optional[Dict[str, Any]], form_data: Optional[Dict[str, Any]]
  304. ) -> Optional[List[Dict[str, Any]]]:
  305. """沿条件命中路径收集节点;无法匹配时返回 None。"""
  306. if not isinstance(root, dict):
  307. return []
  308. data = form_data or {}
  309. out: List[Dict[str, Any]] = []
  310. cur: Optional[Dict[str, Any]] = root
  311. while cur and isinstance(cur, dict):
  312. ntype = _node_type(cur)
  313. if ntype == "end":
  314. out.append(cur)
  315. break
  316. if ntype == "condition":
  317. g = _match_condition_group(cur.get("conditionGroups") or [], data)
  318. if not g:
  319. return None
  320. child = g.get("child")
  321. if isinstance(child, dict):
  322. sub = _iter_resolved_path_nodes(child, data)
  323. if sub is None:
  324. return None
  325. out.extend(sub)
  326. cur = cur.get("child")
  327. continue
  328. out.append(cur)
  329. cur = cur.get("child")
  330. return out
  331. def _append_pending_nodes_on_path(
  332. items: List[Dict[str, Any]],
  333. *,
  334. db: Session,
  335. flow_root: Dict[str, Any],
  336. reached_keys: set,
  337. round_no: int,
  338. tenant_no: str,
  339. initiator_user_id: str,
  340. initiator_dept_id: Optional[str],
  341. advanced: Dict[str, Any],
  342. form_data: Optional[Dict[str, Any]],
  343. initiator_select_by_node: Optional[Dict[str, List[str]]],
  344. ) -> None:
  345. """按命中路径列出全部后续审批/抄送/结束节点(含人员),对齐发起预览。"""
  346. path = _iter_resolved_path_nodes(flow_root, form_data)
  347. if path is None:
  348. already = {
  349. (x.get("nodeKey") or "").strip()
  350. for x in items
  351. if x.get("kind") in ("task", "pending_node") and (x.get("nodeKey") or "").strip()
  352. }
  353. _append_pending_nodes(
  354. items,
  355. flow_root=flow_root,
  356. reached_keys=reached_keys | already,
  357. round_no=round_no,
  358. )
  359. return
  360. for node in path:
  361. ntype = _node_type(node)
  362. if ntype not in ("approval", "cc", "end"):
  363. continue
  364. nid = (node.get("id") or "").strip()
  365. if not nid or nid in reached_keys:
  366. continue
  367. if ntype == "end":
  368. items.append(
  369. {
  370. "kind": "pending_node",
  371. "roundNo": round_no,
  372. "title": node.get("name") or "结束",
  373. "status": "not_reached",
  374. "assigneeUserId": "",
  375. "assigneeUserName": "",
  376. "timestamp": "",
  377. "commentText": "",
  378. "nodeKey": nid,
  379. "taskType": "end",
  380. "signMode": "",
  381. "people": [],
  382. }
  383. )
  384. continue
  385. people, sign_mode, _src = _pending_people_for_node(
  386. db,
  387. node=node,
  388. tenant_no=tenant_no,
  389. initiator_user_id=initiator_user_id,
  390. initiator_dept_id=initiator_dept_id,
  391. advanced=advanced,
  392. initiator_select_by_node=initiator_select_by_node,
  393. )
  394. items.append(
  395. {
  396. "kind": "pending_node",
  397. "roundNo": round_no,
  398. "title": node.get("name") or ("抄送人" if ntype == "cc" else "审批人"),
  399. "status": "not_reached",
  400. "assigneeUserId": "",
  401. "assigneeUserName": "",
  402. "timestamp": "",
  403. "commentText": "",
  404. "nodeKey": nid,
  405. "taskType": ntype,
  406. "signMode": sign_mode,
  407. "people": people,
  408. }
  409. )
  410. def _progress_person(t: Any, name_map: Dict[str, str]) -> Dict[str, Any]:
  411. uid = (getattr(t, "assignee_user_id", None) or "").strip()
  412. return {
  413. "id": uid,
  414. "nickName": name_map.get(uid, "") or uid,
  415. "status": getattr(t, "status", None) or "",
  416. "timestamp": _fmt_dt(getattr(t, "update_time", None) or getattr(t, "create_time", None)),
  417. "commentText": getattr(t, "comment_text", None) or "",
  418. "taskId": getattr(t, "id", None) or "",
  419. "transferToUserId": "",
  420. "transferToUserName": "",
  421. }
  422. def _enrich_transfer_targets(
  423. people: List[Dict[str, Any]],
  424. group: List[Any],
  425. name_map: Dict[str, str],
  426. ) -> None:
  427. """为已转交人员补齐 transferTo*:同节点 resolve_source=transfer 且 create_by=转交人 的新任务处理人。"""
  428. by_creator: Dict[str, List[Any]] = {}
  429. for t in group:
  430. if (getattr(t, "resolve_source", None) or "").strip() != "transfer":
  431. continue
  432. creator = (getattr(t, "create_by", None) or "").strip()
  433. if not creator:
  434. continue
  435. by_creator.setdefault(creator, []).append(t)
  436. for p in people:
  437. if (p.get("status") or "") != "transferred":
  438. continue
  439. uid = (p.get("id") or "").strip()
  440. if not uid:
  441. continue
  442. candidates = by_creator.get(uid) or []
  443. if not candidates:
  444. continue
  445. # 连续转交时同一人可能只对应一次;若有多条取创建时间最接近转交时间的
  446. p_ts = (p.get("timestamp") or "").strip()
  447. def _score(t: Any) -> tuple:
  448. cts = _fmt_dt(getattr(t, "create_time", None))
  449. # 优先同秒/最近;无时间时靠后
  450. if p_ts and cts:
  451. return (0, abs(_dt_sort_key(cts) - _dt_sort_key(p_ts)), cts)
  452. return (1, 0, cts or "")
  453. target_task = sorted(candidates, key=_score)[0]
  454. tid = (getattr(target_task, "assignee_user_id", None) or "").strip()
  455. if not tid:
  456. continue
  457. p["transferToUserId"] = tid
  458. p["transferToUserName"] = name_map.get(tid, "") or tid
  459. def _dt_sort_key(s: str) -> int:
  460. """将 'YYYY-MM-DD HH:MM:SS' 粗转为可比较整数;非法则 0。"""
  461. raw = (s or "").strip().replace("-", "").replace(":", "").replace(" ", "")
  462. try:
  463. return int(raw[:14]) if raw else 0
  464. except ValueError:
  465. return 0
  466. def _aggregate_node_status(statuses: List[str]) -> str:
  467. """同节点多人任务收成卡片状态:拒绝/打回优先,其次待办,再已同意。"""
  468. sset = [str(s or "").strip() for s in statuses]
  469. if any(s == "rejected" for s in sset):
  470. return "rejected"
  471. if any(s == "returned" for s in sset):
  472. return "returned"
  473. if any(s in ("pending", "running") for s in sset):
  474. return "pending"
  475. if any(s == "approved" for s in sset):
  476. return "approved"
  477. if any(s == "completed" for s in sset):
  478. return "completed"
  479. if sset and all(s == "done" for s in sset):
  480. return "done"
  481. return sset[0] if sset else "pending"
  482. def _group_tasks_by_node(sorted_tasks: List[Any]) -> List[List[Any]]:
  483. """按 node_key 合并同节点多人(或签/会签/抄送),无 key 的任务各自独立。"""
  484. buckets: OrderedDict[str, List[Any]] = OrderedDict()
  485. for t in sorted_tasks:
  486. nk = (getattr(t, "node_key", None) or "").strip()
  487. key = nk if nk else f"__task_{(getattr(t, 'id', None) or id(t))}"
  488. buckets.setdefault(key, []).append(t)
  489. return list(buckets.values())
  490. def build_progress_items(
  491. *,
  492. inst: Any,
  493. flow_root: Optional[Dict[str, Any]],
  494. tasks: List[Any],
  495. name_map: Dict[str, str],
  496. events: Optional[List[Any]] = None,
  497. db: Optional[Session] = None,
  498. advanced: Optional[Dict[str, Any]] = None,
  499. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  500. ) -> List[Dict[str, Any]]:
  501. """投影审批进度:发起人 → 树序 tasks(同节点多人合并)→ 未到达;终态收尾。
  502. 钉钉对齐:打回结果落在审批任务节点上,不另插 kind=return / terminal 终态「已打回」行;不做同单多轮分段。
  503. 或签/会签:同一 nodeKey 只出一张卡片,people 列出各审批人及状态。
  504. 进行中:按命中路径把后续审批/抄送节点全部挂为未到达(尽量解析人员)。
  505. """
  506. events = list(events or [])
  507. sorted_tasks = _sort_tasks_for_detail(list(tasks), flow_root=flow_root)
  508. # 展示压成单轴(roundNo 统一为 1);历史多轮任务仍按树序合并展示
  509. rn = 1
  510. submit_ts = _fmt_dt(getattr(inst, "create_time", None))
  511. for e in events:
  512. if (getattr(e, "event_type", None) or "") == "submit":
  513. submit_ts = _fmt_dt(getattr(e, "create_time", None)) or submit_ts
  514. break
  515. items: List[Dict[str, Any]] = [
  516. {
  517. "kind": "submit",
  518. "roundNo": rn,
  519. "title": "发起人",
  520. "status": "submitted",
  521. "assigneeUserId": inst.initiator_user_id,
  522. "assigneeUserName": name_map.get(inst.initiator_user_id or "", ""),
  523. "timestamp": submit_ts,
  524. "commentText": "",
  525. "nodeKey": "",
  526. "taskType": "",
  527. "signMode": "",
  528. "people": [],
  529. }
  530. ]
  531. reached_keys = {
  532. (t.node_key or "").strip() for t in sorted_tasks if (t.node_key or "").strip()
  533. }
  534. for group in _group_tasks_by_node(sorted_tasks):
  535. head = group[0]
  536. people = [_progress_person(t, name_map) for t in group]
  537. _enrich_transfer_targets(people, group, name_map)
  538. statuses = [p["status"] for p in people]
  539. node_status = _aggregate_node_status(statuses)
  540. # 时间:优先取已操作人最新时间,否则取组内最新
  541. acted = [
  542. p
  543. for p in people
  544. if p["status"] in ("approved", "rejected", "returned", "completed", "transferred")
  545. ]
  546. ts_src = acted or people
  547. timestamp = ""
  548. for p in ts_src:
  549. if p.get("timestamp") and (not timestamp or p["timestamp"] > timestamp):
  550. timestamp = p["timestamp"]
  551. comments = [
  552. f"{p['nickName']}:{p['commentText']}"
  553. if len(people) > 1 and p.get("nickName")
  554. else p["commentText"]
  555. for p in people
  556. if (p.get("commentText") or "").strip()
  557. ]
  558. sign_mode = (getattr(head, "sign_mode", None) or "").strip()
  559. primary = next(
  560. (p for p in people if p["status"] == node_status),
  561. people[0] if people else None,
  562. )
  563. items.append(
  564. {
  565. "kind": "task",
  566. "roundNo": rn,
  567. "title": head.node_name or head.node_key or "-",
  568. "status": node_status,
  569. "assigneeUserId": (primary or {}).get("id", "") if len(people) == 1 else "",
  570. "assigneeUserName": (primary or {}).get("nickName", "")
  571. if len(people) == 1
  572. else "",
  573. "timestamp": timestamp,
  574. "commentText": ";".join(comments),
  575. "nodeKey": head.node_key or "",
  576. "taskType": head.task_type or "",
  577. "resolveSource": getattr(head, "resolve_source", None) or "",
  578. "signMode": sign_mode,
  579. "taskId": getattr(head, "id", None) or "",
  580. "people": people,
  581. }
  582. )
  583. if inst.status == "running" and isinstance(flow_root, dict):
  584. form_data = _loads(getattr(inst, "form_data_json", None), {}) or {}
  585. if not isinstance(form_data, dict):
  586. form_data = {}
  587. # 自选人:优先入参 → 实例 JSON → 旧数据从任务按 node_key 聚合
  588. select_by_node = _normalize_initiator_select_by_node(initiator_select_by_node)
  589. if not select_by_node:
  590. select_by_node = _load_initiator_select_by_node(inst)
  591. if not select_by_node:
  592. for t in sorted_tasks:
  593. src = (getattr(t, "resolve_source", None) or "").strip()
  594. uid = (getattr(t, "assignee_user_id", None) or "").strip()
  595. nk = (getattr(t, "node_key", None) or "").strip()
  596. if src == "initiator_select" and uid and nk:
  597. bucket = select_by_node.setdefault(nk, [])
  598. if uid not in bucket:
  599. bucket.append(uid)
  600. if db is not None:
  601. _append_pending_nodes_on_path(
  602. items,
  603. db=db,
  604. flow_root=flow_root,
  605. reached_keys=reached_keys,
  606. round_no=rn,
  607. tenant_no=getattr(inst, "tenant_no", None) or "",
  608. initiator_user_id=inst.initiator_user_id or "",
  609. initiator_dept_id=getattr(inst, "initiator_dept_id", None),
  610. advanced=advanced or dict(oa_crud.DEFAULT_ADVANCED_SETTINGS),
  611. form_data=form_data,
  612. initiator_select_by_node=select_by_node,
  613. )
  614. else:
  615. _append_pending_nodes(
  616. items, flow_root=flow_root, reached_keys=reached_keys, round_no=rn
  617. )
  618. if inst.status == "completed":
  619. items.append(_terminal_item("done", "流程结束", inst))
  620. elif inst.status == "rejected":
  621. items.append(_terminal_item("rejected", "流程结束(已拒绝)", inst))
  622. elif inst.status == "cancelled":
  623. items.append(_terminal_item("cancelled", "已撤销", inst))
  624. # returned:打回结果只落在审批任务节点上,不再追加独立终态「已打回」行
  625. return items
  626. def _add_instance_event(
  627. db: Session,
  628. *,
  629. inst: OaInstance,
  630. event_type: str,
  631. actor_user_id: Optional[str],
  632. round_no: int,
  633. comment: Optional[str] = None,
  634. task_id: Optional[str] = None,
  635. node_key: Optional[str] = None,
  636. ) -> OaInstanceEvent:
  637. now = datetime.now()
  638. ev = OaInstanceEvent(
  639. id=generate_uuid(),
  640. instance_id=inst.id,
  641. round_no=round_no,
  642. event_type=event_type,
  643. actor_user_id=actor_user_id,
  644. task_id=task_id,
  645. node_key=node_key,
  646. comment_text=(comment or "").strip() or None,
  647. tenant_no=inst.tenant_no,
  648. order_num=0,
  649. remark=None,
  650. create_by=actor_user_id,
  651. create_dept_id=inst.initiator_dept_id or "",
  652. create_time=now,
  653. update_by=actor_user_id,
  654. update_time=now,
  655. del_flag=0,
  656. )
  657. db.add(ev)
  658. return ev
  659. def _advanced(ver: OaAppVersion) -> Dict[str, Any]:
  660. data = _loads(ver.advanced_settings_json, {}) or {}
  661. if not isinstance(data, dict):
  662. return dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  663. merged = dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  664. merged.update(data)
  665. return merged
  666. def _check_initiator_scope(app: OaApp, user_id: str) -> None:
  667. scope = (app.initiator_scope or "all").strip()
  668. if scope == "all":
  669. return
  670. ids = _loads(app.initiator_user_ids, []) or []
  671. if user_id not in ids:
  672. raise OaEngineError("您不在该审批的发起范围内")
  673. def _instance_to_dict(inst: OaInstance, *, app_name: str = "") -> Dict[str, Any]:
  674. return {
  675. "id": inst.id,
  676. "appId": inst.app_id,
  677. "appVersionId": inst.app_version_id,
  678. "appName": app_name,
  679. "title": inst.title or "",
  680. "initiatorUserId": inst.initiator_user_id,
  681. "initiatorDeptId": inst.initiator_dept_id or "",
  682. "formDataJson": _loads(inst.form_data_json, {}),
  683. "status": inst.status,
  684. "sourceInstanceId": getattr(inst, "source_instance_id", None) or "",
  685. "currentRound": int(getattr(inst, "current_round", None) or 1),
  686. "createTime": inst.create_time.strftime("%Y-%m-%d %H:%M:%S") if inst.create_time else "",
  687. "updateTime": inst.update_time.strftime("%Y-%m-%d %H:%M:%S") if inst.update_time else "",
  688. }
  689. def _task_to_dict(t: OaTask, *, assignee_user_name: str = "") -> Dict[str, Any]:
  690. return {
  691. "id": t.id,
  692. "instanceId": t.instance_id,
  693. "nodeKey": t.node_key or "",
  694. "nodeName": t.node_name or "",
  695. "taskType": t.task_type,
  696. "assigneeUserId": t.assignee_user_id,
  697. "assigneeUserName": assignee_user_name or t.assignee_user_id or "",
  698. "status": t.status,
  699. "commentText": t.comment_text or "",
  700. "resolveSource": t.resolve_source or "",
  701. "signMode": t.sign_mode or "",
  702. "createTime": t.create_time.strftime("%Y-%m-%d %H:%M:%S") if t.create_time else "",
  703. "updateTime": t.update_time.strftime("%Y-%m-%d %H:%M:%S") if t.update_time else "",
  704. }
  705. _INSTANCE_STATUS_NODE_LABEL = {
  706. "completed": "已完成",
  707. "rejected": "已拒绝",
  708. "returned": "已打回",
  709. "cancelled": "已撤销",
  710. }
  711. def _instance_progress_summary(
  712. inst: OaInstance,
  713. *,
  714. app_name: str,
  715. initiator_user_name: str,
  716. pending_approval_tasks: List[OaTask],
  717. name_map: Dict[str, str],
  718. ) -> Dict[str, Any]:
  719. status = (inst.status or "").strip()
  720. apply_time = (
  721. inst.create_time.strftime("%Y-%m-%d %H:%M:%S") if inst.create_time else ""
  722. )
  723. if status == "running":
  724. node_names: List[str] = []
  725. seen_nodes = set()
  726. approver_names: List[str] = []
  727. for t in pending_approval_tasks:
  728. nn = (t.node_name or t.node_key or "").strip()
  729. if nn and nn not in seen_nodes:
  730. seen_nodes.add(nn)
  731. node_names.append(nn)
  732. uid = (t.assignee_user_id or "").strip()
  733. if uid:
  734. approver_names.append(name_map.get(uid, uid))
  735. current_node = "、".join(node_names) if node_names else "-"
  736. current_approvers = "、".join(approver_names) if approver_names else "-"
  737. else:
  738. current_node = _INSTANCE_STATUS_NODE_LABEL.get(status, status or "-")
  739. current_approvers = "-"
  740. return {
  741. "appName": app_name or (inst.title or ""),
  742. "initiatorUserId": inst.initiator_user_id or "",
  743. "initiatorUserName": initiator_user_name
  744. or name_map.get(inst.initiator_user_id or "", inst.initiator_user_id or ""),
  745. "applyTime": apply_time,
  746. "instanceStatus": status,
  747. "currentNodeName": current_node,
  748. "currentApproverNames": current_approvers,
  749. }
  750. def _enrich_list_rows(
  751. db: Session,
  752. *,
  753. tenant_no: str,
  754. rows: List[Dict[str, Any]],
  755. instances: List[OaInstance],
  756. ) -> List[Dict[str, Any]]:
  757. if not rows:
  758. return []
  759. inst_by_id = {i.id: i for i in instances}
  760. app_ids = list({i.app_id for i in instances if i.app_id})
  761. apps = (
  762. db.query(OaApp)
  763. .filter(
  764. OaApp.id.in_(app_ids),
  765. OaApp.tenant_no == tenant_no,
  766. OaApp.del_flag == 0,
  767. )
  768. .all()
  769. if app_ids
  770. else []
  771. )
  772. app_name_by_id = {a.id: (a.app_name or "") for a in apps}
  773. inst_ids = list(inst_by_id.keys())
  774. pending_tasks = (
  775. db.query(OaTask)
  776. .filter(
  777. OaTask.tenant_no == tenant_no,
  778. OaTask.del_flag == 0,
  779. OaTask.instance_id.in_(inst_ids),
  780. OaTask.task_type == "approval",
  781. OaTask.status == "pending",
  782. )
  783. .order_by(OaTask.create_time.asc())
  784. .all()
  785. if inst_ids
  786. else []
  787. )
  788. pending_by_inst: Dict[str, List[OaTask]] = {}
  789. for t in pending_tasks:
  790. pending_by_inst.setdefault(t.instance_id, []).append(t)
  791. user_ids: List[str] = []
  792. for i in instances:
  793. if i.initiator_user_id:
  794. user_ids.append(i.initiator_user_id)
  795. for t in pending_tasks:
  796. if t.assignee_user_id:
  797. user_ids.append(t.assignee_user_id)
  798. name_map = _user_name_map(db, user_ids)
  799. out: List[Dict[str, Any]] = []
  800. for row in rows:
  801. iid = row.get("instanceId") or row.get("id")
  802. inst = inst_by_id.get(iid)
  803. if not inst:
  804. out.append(row)
  805. continue
  806. summary = _instance_progress_summary(
  807. inst,
  808. app_name=app_name_by_id.get(inst.app_id, ""),
  809. initiator_user_name=name_map.get(inst.initiator_user_id or "", ""),
  810. pending_approval_tasks=pending_by_inst.get(inst.id, []),
  811. name_map=name_map,
  812. )
  813. merged = dict(row)
  814. merged.update(summary)
  815. out.append(merged)
  816. return out
  817. def _user_name_map(db: Session, user_ids: List[str]) -> Dict[str, str]:
  818. ids = [uid for uid in {str(u or "").strip() for u in user_ids} if uid]
  819. if not ids:
  820. return {}
  821. rows = db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(ids)).all()
  822. return {r.id: (r.nick_name or r.id) for r in rows}
  823. def _dept_name(db: Session, dept_id: Optional[str], *, tenant_no: str) -> str:
  824. did = (dept_id or "").strip()
  825. if not did:
  826. return ""
  827. row = (
  828. db.query(SysDept.dept_name)
  829. .filter(SysDept.id == did, SysDept.tenant_no == tenant_no, SysDept.del_flag == 0)
  830. .first()
  831. )
  832. if not row:
  833. return ""
  834. return (row[0] or "").strip()
  835. def list_templates(db: Session, *, tenant_no: str, user_id: str) -> List[Dict[str, Any]]:
  836. apps = (
  837. db.query(OaApp)
  838. .filter(OaApp.tenant_no == tenant_no, OaApp.del_flag == 0, OaApp.status == "1")
  839. .order_by(OaApp.order_num.asc(), OaApp.create_time.desc())
  840. .all()
  841. )
  842. out: List[Dict[str, Any]] = []
  843. for app in apps:
  844. pub = oa_crud._find_latest_published(db, app.id, tenant_no)
  845. if not pub:
  846. continue
  847. try:
  848. _check_initiator_scope(app, user_id)
  849. except OaEngineError:
  850. continue
  851. out.append(
  852. {
  853. "id": app.id,
  854. "appName": app.app_name,
  855. "groupId": app.group_id or "",
  856. "iconUrl": app.icon_url or "",
  857. "description": app.description or "",
  858. "versionId": pub.id,
  859. "versionNo": pub.version_no,
  860. }
  861. )
  862. return out
  863. def get_template_detail(
  864. db: Session, *, tenant_no: str, app_id: str, user_id: str
  865. ) -> Dict[str, Any]:
  866. app = oa_crud.get_app(db, app_id, tenant_no)
  867. if not app or app.status != "1":
  868. raise OaEngineError("应用不存在或已停用")
  869. _check_initiator_scope(app, user_id)
  870. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  871. if not pub:
  872. raise OaEngineError("应用尚未发布")
  873. return {
  874. "id": app.id,
  875. "appName": app.app_name,
  876. "groupId": app.group_id or "",
  877. "iconUrl": app.icon_url or "",
  878. "description": app.description or "",
  879. "versionId": pub.id,
  880. "versionNo": pub.version_no,
  881. "formSchemaJson": _loads(pub.form_schema_json, {}),
  882. "flowTreeJson": _loads(pub.flow_tree_json, {}),
  883. "advancedSettingsJson": _advanced(pub),
  884. }
  885. _ASSIGNEE_TYPE_LABEL = {
  886. "users": "指定成员",
  887. "oa_roles": "工作流角色",
  888. "dept_leader": "发起人部门负责人",
  889. "direct_supervisor": "发起人的主管",
  890. "initiator_select": "发起人自选",
  891. }
  892. def _role_name_map(db: Session, tenant_no: str, role_ids: List[str], codes: List[str]) -> List[str]:
  893. names: List[str] = []
  894. ids = [str(x).strip() for x in (role_ids or []) if str(x).strip()]
  895. code_list = [str(c).strip().upper() for c in (codes or []) if str(c).strip()]
  896. if ids:
  897. rows = (
  898. db.query(OaRole)
  899. .filter(OaRole.tenant_no == tenant_no, OaRole.id.in_(ids), OaRole.del_flag == 0)
  900. .all()
  901. )
  902. names.extend([(r.role_name or r.role_code or r.id) for r in rows])
  903. if code_list:
  904. rows = (
  905. db.query(OaRole)
  906. .filter(
  907. OaRole.tenant_no == tenant_no,
  908. OaRole.role_code.in_(code_list),
  909. OaRole.del_flag == 0,
  910. )
  911. .all()
  912. )
  913. for r in rows:
  914. label = r.role_name or r.role_code or r.id
  915. if label not in names:
  916. names.append(label)
  917. return names
  918. def _assignee_meta(db: Session, tenant_no: str, cfg: Dict[str, Any]) -> str:
  919. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  920. base = _ASSIGNEE_TYPE_LABEL.get(assignee_type, assignee_type or "未配置审批人")
  921. if assignee_type == "oa_roles":
  922. names = _role_name_map(
  923. db,
  924. tenant_no,
  925. cfg.get("oaRoleIds") or cfg.get("oa_role_ids") or [],
  926. cfg.get("oaRoleCodes") or cfg.get("oa_role_codes") or [],
  927. )
  928. if names:
  929. return f"{base} · {'/'.join(names)}"
  930. return base
  931. def _preview_people(db: Session, user_ids: List[str]) -> List[Dict[str, str]]:
  932. name_map = _user_name_map(db, user_ids)
  933. out: List[Dict[str, str]] = []
  934. for uid in user_ids:
  935. out.append({"id": uid, "nickName": name_map.get(uid) or uid})
  936. return out
  937. _FLOW_PREVIEW_PENDING_MSG = "必填信息填写后,流程将自动显示"
  938. _FLOW_PREVIEW_UNMATCHED_MSG = "流程条件无法匹配,请检查表单或联系管理员"
  939. _FORMULA_FIELD_RE = re.compile(r"\{([^{}]+)\}")
  940. def _form_value_present(form_data: Optional[Dict[str, Any]], field: str) -> bool:
  941. """条件字段是否已有有效值(0 / false 视为已填)。"""
  942. if not field:
  943. return True
  944. data = form_data or {}
  945. if field not in data:
  946. return False
  947. val = data.get(field)
  948. if val is None:
  949. return False
  950. if isinstance(val, str) and not val.strip():
  951. return False
  952. if isinstance(val, (list, tuple, set, dict)) and len(val) == 0:
  953. return False
  954. return True
  955. def _collect_condition_fields(node: Optional[Dict[str, Any]]) -> List[str]:
  956. """收集流程树中非默认条件分支引用的表单字段(去重保序)。"""
  957. fields: List[str] = []
  958. seen = set()
  959. def add(name: Any) -> None:
  960. key = str(name or "").strip()
  961. if not key or key in seen:
  962. return
  963. seen.add(key)
  964. fields.append(key)
  965. def walk(n: Any) -> None:
  966. if not isinstance(n, dict):
  967. return
  968. if _node_type(n) == "condition":
  969. for g in n.get("conditionGroups") or []:
  970. if not isinstance(g, dict):
  971. continue
  972. rules = g.get("rules")
  973. when = g.get("when")
  974. if g.get("isDefault") or (not rules and not when):
  975. child = g.get("child")
  976. if isinstance(child, dict):
  977. walk(child)
  978. continue
  979. if isinstance(rules, list) and rules:
  980. for r in rules:
  981. if isinstance(r, dict) and r.get("field") is not None:
  982. add(r.get("field"))
  983. elif isinstance(rules, str) and rules.strip():
  984. for m in _FORMULA_FIELD_RE.findall(rules):
  985. add(m)
  986. elif when:
  987. for m in _FORMULA_FIELD_RE.findall(str(when)):
  988. add(m)
  989. child = g.get("child")
  990. if isinstance(child, dict):
  991. walk(child)
  992. join_child = n.get("child")
  993. if isinstance(join_child, dict):
  994. walk(join_child)
  995. return
  996. child = n.get("child")
  997. if isinstance(child, dict):
  998. walk(child)
  999. for g in n.get("conditionGroups") or []:
  1000. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  1001. walk(g.get("child"))
  1002. walk(node)
  1003. return fields
  1004. def _condition_fields_ready(
  1005. root: Optional[Dict[str, Any]], form_data: Optional[Dict[str, Any]]
  1006. ) -> bool:
  1007. fields = _collect_condition_fields(root)
  1008. if not fields:
  1009. return True
  1010. data = form_data or {}
  1011. return all(_form_value_present(data, f) for f in fields)
  1012. def _walk_preview_nodes(
  1013. db: Session,
  1014. *,
  1015. node: Optional[Dict[str, Any]],
  1016. tenant_no: str,
  1017. initiator_user_id: str,
  1018. initiator_dept_id: Optional[str],
  1019. advanced: Dict[str, Any],
  1020. initiator_select_by_node: Optional[Dict[str, List[str]]],
  1021. form_data: Optional[Dict[str, Any]],
  1022. steps: List[Dict[str, Any]],
  1023. ) -> bool:
  1024. """沿最终路径写入 steps。条件无法匹配时返回 False。"""
  1025. cur = node
  1026. data = form_data or {}
  1027. while cur and isinstance(cur, dict):
  1028. ntype = _node_type(cur)
  1029. if ntype == "start":
  1030. people = _preview_people(db, [initiator_user_id] if initiator_user_id else [])
  1031. steps.append(
  1032. {
  1033. "id": cur.get("id") or "",
  1034. "type": "start",
  1035. "name": cur.get("name") or "发起人",
  1036. "signMode": "",
  1037. "assigneeType": "",
  1038. "meta": "",
  1039. "people": people,
  1040. "resolveError": "",
  1041. }
  1042. )
  1043. cur = cur.get("child")
  1044. continue
  1045. if ntype == "end":
  1046. steps.append(
  1047. {
  1048. "id": cur.get("id") or "",
  1049. "type": "end",
  1050. "name": cur.get("name") or "结束",
  1051. "signMode": "",
  1052. "assigneeType": "",
  1053. "meta": "",
  1054. "people": [],
  1055. "resolveError": "",
  1056. }
  1057. )
  1058. break
  1059. if ntype == "condition":
  1060. groups = cur.get("conditionGroups") or []
  1061. g = _match_condition_group(groups, data)
  1062. if not g:
  1063. return False
  1064. child = g.get("child")
  1065. if isinstance(child, dict):
  1066. ok = _walk_preview_nodes(
  1067. db,
  1068. node=child,
  1069. tenant_no=tenant_no,
  1070. initiator_user_id=initiator_user_id,
  1071. initiator_dept_id=initiator_dept_id,
  1072. advanced=advanced,
  1073. initiator_select_by_node=initiator_select_by_node,
  1074. form_data=data,
  1075. steps=steps,
  1076. )
  1077. if not ok:
  1078. return False
  1079. cur = cur.get("child")
  1080. continue
  1081. if ntype in ("approval", "cc"):
  1082. cfg = cur.get("approverConfig") or {}
  1083. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  1084. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "").strip()
  1085. if ntype == "cc":
  1086. sign_mode = "cc"
  1087. elif not sign_mode and assignee_type != "initiator_select":
  1088. sign_mode = "or"
  1089. meta = _assignee_meta(db, tenant_no, cfg)
  1090. people: List[Dict[str, str]] = []
  1091. resolve_error = ""
  1092. node_select_ids = _ids_for_initiator_select_node(
  1093. initiator_select_by_node, cur.get("id") or ""
  1094. )
  1095. if assignee_type == "initiator_select":
  1096. people = _preview_people(db, [str(x) for x in node_select_ids if str(x).strip()])
  1097. if not people:
  1098. meta = meta or "发起人自选"
  1099. else:
  1100. try:
  1101. assignees, _meta = resolve_assignees(
  1102. db,
  1103. tenant_no=tenant_no,
  1104. assignee_config=cfg,
  1105. initiator_user_id=initiator_user_id,
  1106. initiator_dept_id=initiator_dept_id,
  1107. advanced=advanced,
  1108. initiator_select_user_ids=node_select_ids,
  1109. )
  1110. people = _preview_people(db, assignees)
  1111. except AssigneeResolveError as e:
  1112. resolve_error = str(e)
  1113. steps.append(
  1114. {
  1115. "id": cur.get("id") or "",
  1116. "type": ntype,
  1117. "name": cur.get("name") or ("抄送人" if ntype == "cc" else "审批人"),
  1118. "signMode": sign_mode,
  1119. "assigneeType": assignee_type,
  1120. "meta": meta,
  1121. "people": people,
  1122. "resolveError": resolve_error,
  1123. }
  1124. )
  1125. cur = cur.get("child")
  1126. continue
  1127. cur = cur.get("child")
  1128. return True
  1129. def preview_start_flow(
  1130. db: Session,
  1131. *,
  1132. tenant_no: str,
  1133. app_id: str,
  1134. initiator_user_id: str,
  1135. initiator_dept_id: Optional[str] = None,
  1136. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1137. form_data: Optional[Dict[str, Any]] = None,
  1138. ) -> Dict[str, Any]:
  1139. """发起前预览审批链:条件字段齐后只走命中路径并解析人员。"""
  1140. app = oa_crud.get_app(db, app_id, tenant_no)
  1141. if not app or app.status != "1":
  1142. raise OaEngineError("应用不存在或已停用")
  1143. _check_initiator_scope(app, initiator_user_id)
  1144. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  1145. if not pub:
  1146. raise OaEngineError("应用尚未发布")
  1147. initiator = (
  1148. db.query(SysUser)
  1149. .filter(
  1150. SysUser.id == initiator_user_id,
  1151. SysUser.tenant_no == tenant_no,
  1152. SysUser.del_flag == 0,
  1153. )
  1154. .first()
  1155. )
  1156. dept_id = (initiator_dept_id or "").strip() or (
  1157. (initiator.dept_id or "") if initiator else ""
  1158. )
  1159. flow = _loads(pub.flow_tree_json, {}) or {}
  1160. root = flow.get("root") if isinstance(flow, dict) else None
  1161. if not isinstance(root, dict):
  1162. root = flow if isinstance(flow, dict) else {}
  1163. data = dict(form_data or {})
  1164. if not _condition_fields_ready(root, data):
  1165. return {
  1166. "resolved": False,
  1167. "message": _FLOW_PREVIEW_PENDING_MSG,
  1168. "steps": [],
  1169. }
  1170. steps: List[Dict[str, Any]] = []
  1171. select_by_node = _normalize_initiator_select_by_node(initiator_select_by_node)
  1172. ok = _walk_preview_nodes(
  1173. db,
  1174. node=root,
  1175. tenant_no=tenant_no,
  1176. initiator_user_id=initiator_user_id,
  1177. initiator_dept_id=dept_id or None,
  1178. advanced=_advanced(pub),
  1179. initiator_select_by_node=select_by_node,
  1180. form_data=data,
  1181. steps=steps,
  1182. )
  1183. if not ok:
  1184. return {
  1185. "resolved": False,
  1186. "message": _FLOW_PREVIEW_UNMATCHED_MSG,
  1187. "steps": [],
  1188. }
  1189. return {"resolved": True, "message": "", "steps": steps}
  1190. def _create_tasks_for_node(
  1191. db: Session,
  1192. *,
  1193. inst: OaInstance,
  1194. node: Dict[str, Any],
  1195. ver: OaAppVersion,
  1196. user_id: Optional[str],
  1197. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1198. order_num_start: Optional[int] = None,
  1199. ) -> List[OaTask]:
  1200. ntype = _node_type(node)
  1201. now = datetime.now()
  1202. created: List[OaTask] = []
  1203. if ntype == "cc":
  1204. task_type = "cc"
  1205. elif ntype == "approval":
  1206. task_type = "approval"
  1207. else:
  1208. return created
  1209. cfg = node.get("approverConfig") or {}
  1210. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  1211. node_select_ids = _ids_for_initiator_select_node(
  1212. initiator_select_by_node, node.get("id") or ""
  1213. )
  1214. if assignee_type == "initiator_select":
  1215. if ntype == "cc" and not node_select_ids:
  1216. return created
  1217. if ntype == "approval" and not node_select_ids:
  1218. raise OaEngineError("发起人未选择审批人")
  1219. advanced = _advanced(ver)
  1220. try:
  1221. assignees, meta = resolve_assignees(
  1222. db,
  1223. tenant_no=inst.tenant_no,
  1224. assignee_config=cfg,
  1225. initiator_user_id=inst.initiator_user_id,
  1226. initiator_dept_id=inst.initiator_dept_id,
  1227. advanced=advanced,
  1228. initiator_select_user_ids=node_select_ids,
  1229. )
  1230. except AssigneeResolveError as e:
  1231. raise OaEngineError(str(e)) from e
  1232. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "or").strip() or "or"
  1233. resolve_source = meta.get("resolve_source")
  1234. status = "done" if task_type == "cc" else "pending"
  1235. seq = order_num_start if order_num_start is not None else _next_task_order_num(db, inst.id)
  1236. for uid in assignees:
  1237. t = OaTask(
  1238. id=generate_uuid(),
  1239. instance_id=inst.id,
  1240. node_key=node.get("id") or "",
  1241. node_name=node.get("name") or "",
  1242. task_type=task_type,
  1243. assignee_user_id=uid,
  1244. status=status,
  1245. comment_text=None,
  1246. resolve_source=resolve_source,
  1247. sign_mode=sign_mode if task_type == "approval" else None,
  1248. round_no=int(getattr(inst, "current_round", None) or 1),
  1249. tenant_no=inst.tenant_no,
  1250. order_num=seq,
  1251. remark=None,
  1252. create_by=user_id,
  1253. create_dept_id=inst.initiator_dept_id or "",
  1254. create_time=now,
  1255. update_by=user_id,
  1256. update_time=now,
  1257. del_flag=0,
  1258. )
  1259. seq += 1
  1260. db.add(t)
  1261. created.append(t)
  1262. return created
  1263. def _match_condition_group(groups: List[Any], form_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  1264. default_g = None
  1265. for g in groups:
  1266. if not isinstance(g, dict):
  1267. continue
  1268. rules = g.get("rules")
  1269. when = g.get("when")
  1270. # 空规则 = 默认分支
  1271. if (not rules and not when) or g.get("isDefault"):
  1272. default_g = g
  1273. continue
  1274. expr = when
  1275. if not expr and isinstance(rules, str):
  1276. expr = rules
  1277. if not expr and isinstance(rules, list) and rules:
  1278. # 简化:每条 {field, op, value} 用 AND
  1279. parts = []
  1280. for r in rules:
  1281. if not isinstance(r, dict):
  1282. continue
  1283. field = r.get("field")
  1284. op = r.get("op") or "=="
  1285. val = r.get("value")
  1286. if field is None:
  1287. continue
  1288. if isinstance(val, str):
  1289. parts.append(f"{{{field}}} {op} '{val}'")
  1290. else:
  1291. parts.append(f"{{{field}}} {op} {val}")
  1292. expr = " and ".join(parts) if parts else None
  1293. if not expr:
  1294. default_g = g
  1295. continue
  1296. try:
  1297. if eval_formula(str(expr), form_data):
  1298. return g
  1299. except FormulaError:
  1300. continue
  1301. return default_g
  1302. def advance_from(
  1303. db: Session,
  1304. *,
  1305. inst: OaInstance,
  1306. ver: OaAppVersion,
  1307. from_node: Optional[Dict[str, Any]],
  1308. user_id: Optional[str],
  1309. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1310. ) -> None:
  1311. """从某节点的下一跳开始推进;from_node 为 None 表示从 start 进入。"""
  1312. root = _flow_root(_loads(ver.flow_tree_json, {}))
  1313. form_data = _loads(inst.form_data_json, {}) or {}
  1314. def next_node(node: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  1315. ntype = _node_type(node)
  1316. if ntype == "condition":
  1317. groups = node.get("conditionGroups") or []
  1318. g = _match_condition_group(groups, form_data)
  1319. if not g or not isinstance(g.get("child"), dict):
  1320. raise OaEngineError("条件分支无法匹配出线")
  1321. return g["child"]
  1322. child = node.get("child")
  1323. return child if isinstance(child, dict) else None
  1324. # 起点
  1325. if from_node is None:
  1326. cur = next_node(root) if _node_type(root) == "start" else root
  1327. else:
  1328. cur = next_node(from_node)
  1329. # 同一次推进里可能连续落抄送+审批:共用递增序号,避免 create_time 同秒时乱序
  1330. next_order = _next_task_order_num(db, inst.id)
  1331. safety = 0
  1332. while cur and safety < 50:
  1333. safety += 1
  1334. ntype = _node_type(cur)
  1335. if ntype == "end":
  1336. merge = _merge_after_branch_end(root, cur.get("id") or "")
  1337. if merge is not None:
  1338. cur = merge
  1339. continue
  1340. inst.status = "completed"
  1341. inst.update_time = datetime.now()
  1342. db.add(inst)
  1343. return
  1344. if ntype == "condition":
  1345. cur = next_node(cur)
  1346. continue
  1347. if ntype in ("approval", "cc"):
  1348. tasks = _create_tasks_for_node(
  1349. db,
  1350. inst=inst,
  1351. node=cur,
  1352. ver=ver,
  1353. user_id=user_id,
  1354. initiator_select_by_node=initiator_select_by_node,
  1355. order_num_start=next_order,
  1356. )
  1357. next_order += max(len(tasks), 1)
  1358. if ntype == "cc":
  1359. # 抄送不阻断,继续往下
  1360. cur = next_node(cur)
  1361. continue
  1362. if not tasks:
  1363. raise OaEngineError("审批节点未生成任务")
  1364. _maybe_auto_pass_initiator(
  1365. db,
  1366. inst=inst,
  1367. ver=ver,
  1368. tasks=tasks,
  1369. user_id=user_id,
  1370. )
  1371. return
  1372. # 未知类型跳过子节点
  1373. cur = next_node(cur)
  1374. # 无结束也无待办:异常结束
  1375. if inst.status == "running":
  1376. raise OaEngineError("流程推进异常:未到达结束且无待办任务")
  1377. def start_instance(
  1378. db: Session,
  1379. *,
  1380. tenant_no: str,
  1381. app_id: str,
  1382. initiator_user_id: str,
  1383. initiator_dept_id: Optional[str] = None,
  1384. form_data: Optional[Dict[str, Any]] = None,
  1385. title: Optional[str] = None,
  1386. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1387. related_instance_ids: Optional[List[str]] = None,
  1388. source_instance_id: Optional[str] = None,
  1389. ) -> Dict[str, Any]:
  1390. # source_instance_id 保留入参兼容,不再写入关联(复制开新单不挂旧单)
  1391. _ = source_instance_id
  1392. app = oa_crud.get_app(db, app_id, tenant_no)
  1393. if not app or app.status != "1":
  1394. raise OaEngineError("应用不存在或已停用")
  1395. _check_initiator_scope(app, initiator_user_id)
  1396. ver = oa_crud._find_latest_published(db, app_id, tenant_no)
  1397. if not ver:
  1398. raise OaEngineError("应用尚未发布,无法发起")
  1399. schema = _loads(ver.form_schema_json, {})
  1400. data = dict(form_data or {})
  1401. try:
  1402. data = apply_formulas_and_linkages(schema, data)
  1403. except FormulaError as e:
  1404. raise OaEngineError(f"公式计算失败: {e}") from e
  1405. from app.services.oa_dept_select import validate_dept_form_values
  1406. dept_errs = validate_dept_form_values(schema, data)
  1407. if dept_errs:
  1408. raise OaEngineError(dept_errs[0])
  1409. user = (
  1410. db.query(SysUser)
  1411. .filter(SysUser.id == initiator_user_id, SysUser.del_flag == 0)
  1412. .first()
  1413. )
  1414. dept_id = (initiator_dept_id or (user.dept_id if user else "") or "").strip() or None
  1415. now = datetime.now()
  1416. title_text = (title or app.app_name or "").strip()
  1417. normalized_select = _normalize_initiator_select_by_node(initiator_select_by_node)
  1418. inst = OaInstance(
  1419. id=generate_uuid(),
  1420. app_id=app_id,
  1421. app_version_id=ver.id,
  1422. title=title_text[:200],
  1423. initiator_user_id=initiator_user_id,
  1424. initiator_dept_id=dept_id,
  1425. form_data_json=_dumps(data),
  1426. initiator_select_json=_dumps(normalized_select),
  1427. status="running",
  1428. source_instance_id=None,
  1429. current_round=1,
  1430. tenant_no=tenant_no,
  1431. order_num=0,
  1432. remark=None,
  1433. create_by=initiator_user_id,
  1434. create_dept_id=dept_id or "",
  1435. create_time=now,
  1436. update_by=initiator_user_id,
  1437. update_time=now,
  1438. del_flag=0,
  1439. )
  1440. db.add(inst)
  1441. from app.services.oa_related_approval import (
  1442. assert_linkable_instance,
  1443. merge_relation_targets,
  1444. )
  1445. targets = merge_relation_targets(schema, data, related_instance_ids)
  1446. for field_key, to_id in targets:
  1447. target = (
  1448. db.query(OaInstance)
  1449. .filter(
  1450. OaInstance.id == to_id,
  1451. OaInstance.tenant_no == tenant_no,
  1452. OaInstance.del_flag == 0,
  1453. )
  1454. .first()
  1455. )
  1456. assert_linkable_instance(target, user_id=initiator_user_id, tenant_no=tenant_no)
  1457. db.add(
  1458. OaRelation(
  1459. id=generate_uuid(),
  1460. from_instance_id=inst.id,
  1461. to_instance_id=to_id,
  1462. field_key=field_key,
  1463. tenant_no=tenant_no,
  1464. order_num=0,
  1465. remark=None,
  1466. create_by=initiator_user_id,
  1467. create_dept_id=dept_id or "",
  1468. create_time=now,
  1469. update_by=initiator_user_id,
  1470. update_time=now,
  1471. del_flag=0,
  1472. )
  1473. )
  1474. _add_instance_event(
  1475. db,
  1476. inst=inst,
  1477. event_type="submit",
  1478. actor_user_id=initiator_user_id,
  1479. round_no=1,
  1480. )
  1481. advance_from(
  1482. db,
  1483. inst=inst,
  1484. ver=ver,
  1485. from_node=None,
  1486. user_id=initiator_user_id,
  1487. initiator_select_by_node=normalized_select,
  1488. )
  1489. db.commit()
  1490. db.refresh(inst)
  1491. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  1492. def _get_instance(db: Session, instance_id: str, tenant_no: str) -> OaInstance:
  1493. inst = (
  1494. db.query(OaInstance)
  1495. .filter(OaInstance.id == instance_id, OaInstance.tenant_no == tenant_no, OaInstance.del_flag == 0)
  1496. .first()
  1497. )
  1498. if not inst:
  1499. raise OaEngineError("实例不存在")
  1500. return inst
  1501. def get_instance_detail(db: Session, instance_id: str, *, tenant_no: str) -> Dict[str, Any]:
  1502. inst = _get_instance(db, instance_id, tenant_no)
  1503. app = oa_crud.get_app(db, inst.app_id, tenant_no)
  1504. ver = (
  1505. db.query(OaAppVersion)
  1506. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  1507. .first()
  1508. )
  1509. tasks = (
  1510. db.query(OaTask)
  1511. .filter(OaTask.instance_id == instance_id, OaTask.del_flag == 0)
  1512. .all()
  1513. )
  1514. flow_root = None
  1515. if ver:
  1516. try:
  1517. flow_root = _flow_root(_loads(ver.flow_tree_json, {}))
  1518. except OaEngineError:
  1519. flow_root = None
  1520. tasks = _sort_tasks_for_detail(tasks, flow_root=flow_root)
  1521. rels = (
  1522. db.query(OaRelation)
  1523. .filter(OaRelation.from_instance_id == instance_id, OaRelation.del_flag == 0)
  1524. .all()
  1525. )
  1526. name_map = _user_name_map(
  1527. db,
  1528. [t.assignee_user_id for t in tasks if t.assignee_user_id]
  1529. + ([inst.initiator_user_id] if inst.initiator_user_id else []),
  1530. )
  1531. data = _instance_to_dict(inst, app_name=app.app_name if app else "")
  1532. data["initiatorUserName"] = name_map.get(inst.initiator_user_id or "", inst.initiator_user_id or "")
  1533. data["initiatorDeptName"] = _dept_name(
  1534. db, inst.initiator_dept_id, tenant_no=tenant_no
  1535. )
  1536. data["tasks"] = [
  1537. _task_to_dict(t, assignee_user_name=name_map.get(t.assignee_user_id or "", ""))
  1538. for t in tasks
  1539. ]
  1540. data["relatedInstanceIds"] = [r.to_instance_id for r in rels]
  1541. data["formSchemaJson"] = _loads(ver.form_schema_json, {}) if ver else {}
  1542. adv = _advanced(ver) if ver else dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  1543. data["advancedSettingsJson"] = adv
  1544. data["allowAddSign"] = bool(adv.get("allowAddSign", True))
  1545. data["allowReturn"] = bool(adv.get("allowReturn", True))
  1546. events = (
  1547. db.query(OaInstanceEvent)
  1548. .filter(OaInstanceEvent.instance_id == instance_id, OaInstanceEvent.del_flag == 0)
  1549. .order_by(OaInstanceEvent.create_time.asc())
  1550. .all()
  1551. )
  1552. event_actors = [e.actor_user_id for e in events if e.actor_user_id]
  1553. if event_actors:
  1554. name_map.update(_user_name_map(db, event_actors))
  1555. data["progress"] = build_progress_items(
  1556. inst=inst,
  1557. flow_root=flow_root,
  1558. tasks=tasks,
  1559. name_map=name_map,
  1560. events=events,
  1561. db=db,
  1562. advanced=adv,
  1563. )
  1564. # 不再暴露旧单/重提单关联跳转
  1565. data["sourceInstanceId"] = ""
  1566. data["resubmittedInstanceId"] = ""
  1567. return data
  1568. def list_tasks(
  1569. db: Session,
  1570. *,
  1571. tenant_no: str,
  1572. user_id: str,
  1573. kind: str,
  1574. ) -> List[Dict[str, Any]]:
  1575. kind = (kind or "").strip()
  1576. if kind == "pending":
  1577. q = db.query(OaTask).filter(
  1578. OaTask.tenant_no == tenant_no,
  1579. OaTask.del_flag == 0,
  1580. OaTask.assignee_user_id == user_id,
  1581. OaTask.task_type == "approval",
  1582. OaTask.status == "pending",
  1583. )
  1584. elif kind == "done":
  1585. q = db.query(OaTask).filter(
  1586. OaTask.tenant_no == tenant_no,
  1587. OaTask.del_flag == 0,
  1588. OaTask.assignee_user_id == user_id,
  1589. OaTask.task_type == "approval",
  1590. OaTask.status.in_(("approved", "rejected", "returned", "transferred")),
  1591. )
  1592. elif kind == "cc":
  1593. q = db.query(OaTask).filter(
  1594. OaTask.tenant_no == tenant_no,
  1595. OaTask.del_flag == 0,
  1596. OaTask.assignee_user_id == user_id,
  1597. OaTask.task_type == "cc",
  1598. )
  1599. elif kind == "mine":
  1600. insts = (
  1601. db.query(OaInstance)
  1602. .filter(
  1603. OaInstance.tenant_no == tenant_no,
  1604. OaInstance.del_flag == 0,
  1605. OaInstance.initiator_user_id == user_id,
  1606. )
  1607. .order_by(OaInstance.create_time.desc())
  1608. .all()
  1609. )
  1610. rows = [_instance_to_dict(i) for i in insts]
  1611. return _enrich_list_rows(db, tenant_no=tenant_no, rows=rows, instances=insts)
  1612. else:
  1613. raise OaEngineError(f"不支持的列表类型: {kind}")
  1614. rows_orm = q.order_by(OaTask.create_time.desc()).all()
  1615. rows = [_task_to_dict(t) for t in rows_orm]
  1616. inst_ids = list({t.instance_id for t in rows_orm if t.instance_id})
  1617. insts = (
  1618. db.query(OaInstance)
  1619. .filter(
  1620. OaInstance.tenant_no == tenant_no,
  1621. OaInstance.del_flag == 0,
  1622. OaInstance.id.in_(inst_ids),
  1623. )
  1624. .all()
  1625. if inst_ids
  1626. else []
  1627. )
  1628. return _enrich_list_rows(db, tenant_no=tenant_no, rows=rows, instances=insts)
  1629. def _approve_task_core(
  1630. db: Session,
  1631. *,
  1632. task: OaTask,
  1633. inst: OaInstance,
  1634. ver: OaAppVersion,
  1635. user_id: str,
  1636. comment: Optional[str],
  1637. ) -> bool:
  1638. """将 pending 审批任务置为 approved 并按或签/会签决定是否推进。
  1639. 返回 True 表示已调用 advance_from 推进;False 表示会签未齐、未推进。
  1640. 调用方负责 commit(若需要)。
  1641. """
  1642. now = datetime.now()
  1643. task.comment_text = (comment or "").strip() or None
  1644. task.status = "approved"
  1645. task.update_by = user_id
  1646. task.update_time = now
  1647. db.add(task)
  1648. # Session 默认 autoflush=False:不先 flush 时,后续按 status=pending 的查询仍会命中本任务,
  1649. # 或签「取消同节点其余待办」会把本人已同意覆盖成 done。
  1650. db.flush()
  1651. sign_mode = (task.sign_mode or "or").strip() or "or"
  1652. pending_same = (
  1653. db.query(OaTask)
  1654. .filter(
  1655. OaTask.instance_id == inst.id,
  1656. OaTask.node_key == task.node_key,
  1657. OaTask.task_type == "approval",
  1658. OaTask.id != task.id,
  1659. OaTask.status == "pending",
  1660. OaTask.del_flag == 0,
  1661. )
  1662. .count()
  1663. )
  1664. if sign_mode == "and" and pending_same > 0:
  1665. return False
  1666. if sign_mode != "and":
  1667. for s in (
  1668. db.query(OaTask)
  1669. .filter(
  1670. OaTask.instance_id == inst.id,
  1671. OaTask.node_key == task.node_key,
  1672. OaTask.id != task.id,
  1673. OaTask.status == "pending",
  1674. OaTask.del_flag == 0,
  1675. )
  1676. .all()
  1677. ):
  1678. s.status = "done"
  1679. s.update_by = user_id
  1680. s.update_time = now
  1681. db.add(s)
  1682. root = _flow_root(_loads(ver.flow_tree_json, {}))
  1683. node = _find_node(root, task.node_key or "")
  1684. if not node:
  1685. raise OaEngineError("找不到对应流程节点")
  1686. advance_from(
  1687. db,
  1688. inst=inst,
  1689. ver=ver,
  1690. from_node=node,
  1691. user_id=user_id,
  1692. initiator_select_by_node=_load_initiator_select_by_node(inst),
  1693. )
  1694. return True
  1695. def _maybe_auto_pass_initiator(
  1696. db: Session,
  1697. *,
  1698. inst: OaInstance,
  1699. ver: OaAppVersion,
  1700. tasks: List[OaTask],
  1701. user_id: Optional[str],
  1702. ) -> None:
  1703. _ = user_id
  1704. advanced = _advanced(ver)
  1705. if not advanced.get("autoPassWhenApproverIsInitiator"):
  1706. return
  1707. if inst.status != "running":
  1708. return
  1709. initiator = (inst.initiator_user_id or "").strip()
  1710. if not initiator:
  1711. return
  1712. self_task = None
  1713. for t in tasks:
  1714. if (
  1715. t.task_type == "approval"
  1716. and t.status == "pending"
  1717. and (t.assignee_user_id or "") == initiator
  1718. ):
  1719. self_task = t
  1720. break
  1721. if not self_task:
  1722. return
  1723. _approve_task_core(
  1724. db,
  1725. task=self_task,
  1726. inst=inst,
  1727. ver=ver,
  1728. user_id=initiator,
  1729. comment=_AUTO_PASS_COMMENT,
  1730. )
  1731. def complete_task(
  1732. db: Session,
  1733. task_id: str,
  1734. *,
  1735. tenant_no: str,
  1736. user_id: str,
  1737. action: str,
  1738. comment: Optional[str] = None,
  1739. ) -> Dict[str, Any]:
  1740. action = (action or "").strip()
  1741. if action not in ("approve", "reject"):
  1742. raise OaEngineError("不支持的操作")
  1743. task = (
  1744. db.query(OaTask)
  1745. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  1746. .first()
  1747. )
  1748. if not task:
  1749. raise OaEngineError("任务不存在")
  1750. if task.assignee_user_id != user_id:
  1751. raise OaEngineError("无权处理该任务")
  1752. if task.task_type != "approval" or task.status != "pending":
  1753. raise OaEngineError("任务状态不可处理")
  1754. inst = _get_instance(db, task.instance_id, tenant_no)
  1755. if inst.status != "running":
  1756. raise OaEngineError("实例已结束")
  1757. ver = (
  1758. db.query(OaAppVersion)
  1759. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  1760. .first()
  1761. )
  1762. if not ver:
  1763. raise OaEngineError("流程版本不存在")
  1764. advanced = _advanced(ver)
  1765. if advanced.get("commentRequired") and not (comment or "").strip():
  1766. raise OaEngineError("请填写审批意见")
  1767. if action == "reject":
  1768. now = datetime.now()
  1769. task.comment_text = (comment or "").strip() or None
  1770. task.status = "rejected"
  1771. task.update_by = user_id
  1772. task.update_time = now
  1773. db.add(task)
  1774. db.flush()
  1775. siblings = (
  1776. db.query(OaTask)
  1777. .filter(
  1778. OaTask.instance_id == inst.id,
  1779. OaTask.node_key == task.node_key,
  1780. OaTask.id != task.id,
  1781. OaTask.status == "pending",
  1782. OaTask.del_flag == 0,
  1783. )
  1784. .all()
  1785. )
  1786. for s in siblings:
  1787. s.status = "done"
  1788. s.update_by = user_id
  1789. s.update_time = now
  1790. db.add(s)
  1791. inst.status = "rejected"
  1792. inst.update_by = user_id
  1793. inst.update_time = now
  1794. db.add(inst)
  1795. db.commit()
  1796. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  1797. _approve_task_core(
  1798. db,
  1799. task=task,
  1800. inst=inst,
  1801. ver=ver,
  1802. user_id=user_id,
  1803. comment=comment,
  1804. )
  1805. db.commit()
  1806. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  1807. def add_sign(
  1808. db: Session,
  1809. task_id: str,
  1810. *,
  1811. tenant_no: str,
  1812. user_id: str,
  1813. user_ids: List[str],
  1814. comment: Optional[str] = None,
  1815. ) -> Dict[str, Any]:
  1816. """当前待办处理人加签:为同节点新增待办审批人。"""
  1817. task = (
  1818. db.query(OaTask)
  1819. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  1820. .first()
  1821. )
  1822. if not task:
  1823. raise OaEngineError("任务不存在")
  1824. if task.assignee_user_id != user_id:
  1825. raise OaEngineError("无权加签该任务")
  1826. if task.task_type != "approval" or task.status != "pending":
  1827. raise OaEngineError("仅待处理的审批任务可加签")
  1828. inst = _get_instance(db, task.instance_id, tenant_no)
  1829. if inst.status != "running":
  1830. raise OaEngineError("实例已结束")
  1831. ver = (
  1832. db.query(OaAppVersion)
  1833. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  1834. .first()
  1835. )
  1836. if not ver:
  1837. raise OaEngineError("流程版本不存在")
  1838. advanced = _advanced(ver)
  1839. if not advanced.get("allowAddSign", True):
  1840. raise OaEngineError("该应用不允许加签")
  1841. ids = []
  1842. seen = set()
  1843. for uid in user_ids or []:
  1844. uid = (uid or "").strip()
  1845. if not uid or uid in seen:
  1846. continue
  1847. seen.add(uid)
  1848. ids.append(uid)
  1849. if not ids:
  1850. raise OaEngineError("请选择加签人")
  1851. existing = {
  1852. r.assignee_user_id
  1853. for r in db.query(OaTask)
  1854. .filter(
  1855. OaTask.instance_id == inst.id,
  1856. OaTask.node_key == task.node_key,
  1857. OaTask.del_flag == 0,
  1858. OaTask.status == "pending",
  1859. )
  1860. .all()
  1861. }
  1862. now = datetime.now()
  1863. created = 0
  1864. next_order = _next_task_order_num(db, inst.id)
  1865. for uid in ids:
  1866. if uid in existing:
  1867. continue
  1868. # 校验用户有效
  1869. u = (
  1870. db.query(SysUser)
  1871. .filter(
  1872. SysUser.id == uid,
  1873. SysUser.tenant_no == tenant_no,
  1874. SysUser.del_flag == 0,
  1875. SysUser.status == "1",
  1876. )
  1877. .first()
  1878. )
  1879. if not u:
  1880. raise OaEngineError(f"加签用户无效:{uid}")
  1881. db.add(
  1882. OaTask(
  1883. id=generate_uuid(),
  1884. instance_id=inst.id,
  1885. node_key=task.node_key,
  1886. node_name=task.node_name,
  1887. task_type="approval",
  1888. assignee_user_id=uid,
  1889. status="pending",
  1890. comment_text=None,
  1891. resolve_source="add_sign",
  1892. sign_mode=task.sign_mode or "or",
  1893. round_no=int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1),
  1894. tenant_no=tenant_no,
  1895. order_num=next_order,
  1896. remark=(comment or "").strip() or None,
  1897. create_by=user_id,
  1898. create_dept_id=inst.initiator_dept_id or "",
  1899. create_time=now,
  1900. update_by=user_id,
  1901. update_time=now,
  1902. del_flag=0,
  1903. )
  1904. )
  1905. next_order += 1
  1906. created += 1
  1907. if created == 0:
  1908. raise OaEngineError("所选用户已在当前节点待办中")
  1909. # 加签后默认按会签语义收口更稳妥:保留原 sign_mode;若原或签则一人通过仍可结束
  1910. if comment:
  1911. task.comment_text = ((task.comment_text or "") + f"\n[加签说明] {comment}").strip()
  1912. task.update_by = user_id
  1913. task.update_time = now
  1914. db.add(task)
  1915. db.commit()
  1916. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  1917. def transfer_task(
  1918. db: Session,
  1919. task_id: str,
  1920. *,
  1921. tenant_no: str,
  1922. user_id: str,
  1923. target_user_id: str,
  1924. comment: Optional[str] = None,
  1925. ) -> Dict[str, Any]:
  1926. """当前待办处理人转交:结束本人待办并为同节点目标用户新建 pending 任务。"""
  1927. task = (
  1928. db.query(OaTask)
  1929. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  1930. .first()
  1931. )
  1932. if not task:
  1933. raise OaEngineError("任务不存在")
  1934. if task.assignee_user_id != user_id:
  1935. raise OaEngineError("无权转交该任务")
  1936. if task.task_type != "approval" or task.status != "pending":
  1937. raise OaEngineError("仅待处理的审批任务可转交")
  1938. inst = _get_instance(db, task.instance_id, tenant_no)
  1939. if inst.status != "running":
  1940. raise OaEngineError("实例已结束")
  1941. target = (target_user_id or "").strip()
  1942. if not target:
  1943. raise OaEngineError("请选择转交人")
  1944. if target == user_id:
  1945. raise OaEngineError("不能转交给自己")
  1946. u = (
  1947. db.query(SysUser)
  1948. .filter(
  1949. SysUser.id == target,
  1950. SysUser.tenant_no == tenant_no,
  1951. SysUser.del_flag == 0,
  1952. SysUser.status == "1",
  1953. )
  1954. .first()
  1955. )
  1956. if not u:
  1957. raise OaEngineError(f"转交用户无效:{target}")
  1958. existing = {
  1959. r.assignee_user_id
  1960. for r in db.query(OaTask)
  1961. .filter(
  1962. OaTask.instance_id == inst.id,
  1963. OaTask.node_key == task.node_key,
  1964. OaTask.del_flag == 0,
  1965. OaTask.status == "pending",
  1966. )
  1967. .all()
  1968. }
  1969. if target in existing:
  1970. raise OaEngineError("该用户已在当前节点待办中")
  1971. now = datetime.now()
  1972. comment_text = (comment or "").strip() or None
  1973. round_no = int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1)
  1974. task.status = "transferred"
  1975. task.comment_text = comment_text
  1976. task.update_by = user_id
  1977. task.update_time = now
  1978. db.add(task)
  1979. next_order = _next_task_order_num(db, inst.id)
  1980. db.add(
  1981. OaTask(
  1982. id=generate_uuid(),
  1983. instance_id=inst.id,
  1984. node_key=task.node_key,
  1985. node_name=task.node_name,
  1986. task_type="approval",
  1987. assignee_user_id=target,
  1988. status="pending",
  1989. comment_text=None,
  1990. resolve_source="transfer",
  1991. sign_mode=task.sign_mode or "or",
  1992. round_no=round_no,
  1993. tenant_no=tenant_no,
  1994. order_num=next_order,
  1995. remark=comment_text,
  1996. create_by=user_id,
  1997. create_dept_id=inst.initiator_dept_id or "",
  1998. create_time=now,
  1999. update_by=user_id,
  2000. update_time=now,
  2001. del_flag=0,
  2002. )
  2003. )
  2004. event_comment = comment_text or f"转交给 {target}"
  2005. _add_instance_event(
  2006. db,
  2007. inst=inst,
  2008. event_type="transfer",
  2009. actor_user_id=user_id,
  2010. round_no=round_no,
  2011. comment=event_comment,
  2012. task_id=task.id,
  2013. node_key=task.node_key,
  2014. )
  2015. db.commit()
  2016. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  2017. def return_task(
  2018. db: Session,
  2019. task_id: str,
  2020. *,
  2021. tenant_no: str,
  2022. user_id: str,
  2023. comment: Optional[str] = None,
  2024. ) -> Dict[str, Any]:
  2025. """审批人打回:本单终态 returned;再办须复制表单开新实例。"""
  2026. task = (
  2027. db.query(OaTask)
  2028. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  2029. .first()
  2030. )
  2031. if not task:
  2032. raise OaEngineError("任务不存在")
  2033. if task.assignee_user_id != user_id:
  2034. raise OaEngineError("无权打回该任务")
  2035. if task.task_type != "approval" or task.status != "pending":
  2036. raise OaEngineError("仅待处理的审批任务可打回")
  2037. inst = _get_instance(db, task.instance_id, tenant_no)
  2038. if inst.status != "running":
  2039. raise OaEngineError("仅进行中的审批可打回")
  2040. ver = (
  2041. db.query(OaAppVersion)
  2042. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  2043. .first()
  2044. )
  2045. if not ver:
  2046. raise OaEngineError("流程版本不存在")
  2047. advanced = _advanced(ver)
  2048. if not advanced.get("allowReturn", True):
  2049. raise OaEngineError("该应用不允许打回")
  2050. comment_text = (comment or "").strip()
  2051. if not comment_text:
  2052. raise OaEngineError("打回意见必填")
  2053. now = datetime.now()
  2054. round_no = int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1)
  2055. task.status = "returned"
  2056. task.comment_text = comment_text
  2057. task.update_by = user_id
  2058. task.update_time = now
  2059. db.add(task)
  2060. for t in (
  2061. db.query(OaTask)
  2062. .filter(
  2063. OaTask.instance_id == inst.id,
  2064. OaTask.status == "pending",
  2065. OaTask.del_flag == 0,
  2066. OaTask.id != task.id,
  2067. )
  2068. .all()
  2069. ):
  2070. t.status = "cancelled"
  2071. t.update_by = user_id
  2072. t.update_time = now
  2073. db.add(t)
  2074. inst.status = "returned"
  2075. inst.update_by = user_id
  2076. inst.update_time = now
  2077. db.add(inst)
  2078. _add_instance_event(
  2079. db,
  2080. inst=inst,
  2081. event_type="return",
  2082. actor_user_id=user_id,
  2083. round_no=round_no,
  2084. comment=comment_text,
  2085. task_id=task.id,
  2086. node_key=task.node_key,
  2087. )
  2088. db.commit()
  2089. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  2090. def resubmit_instance(
  2091. db: Session,
  2092. instance_id: str,
  2093. *,
  2094. tenant_no: str,
  2095. user_id: str,
  2096. form_data: Optional[Dict[str, Any]] = None,
  2097. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  2098. ) -> Dict[str, Any]:
  2099. """已废弃:同实例再次提交。请复制表单重新发起新实例。"""
  2100. _ = (db, instance_id, tenant_no, user_id, form_data, initiator_select_by_node)
  2101. raise OaEngineError("同实例再次提交已废弃,请复制表单重新发起")
  2102. def withdraw_instance(
  2103. db: Session, instance_id: str, *, tenant_no: str, user_id: str
  2104. ) -> Dict[str, Any]:
  2105. inst = _get_instance(db, instance_id, tenant_no)
  2106. if inst.initiator_user_id != user_id:
  2107. raise OaEngineError("仅发起人可撤销")
  2108. if inst.status != "running":
  2109. raise OaEngineError("仅运行中的实例可撤销")
  2110. ver = (
  2111. db.query(OaAppVersion)
  2112. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  2113. .first()
  2114. )
  2115. advanced = _advanced(ver) if ver else dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  2116. if not advanced.get("allowWithdrawRunning", True):
  2117. raise OaEngineError("该应用不允许撤销进行中的审批")
  2118. now = datetime.now()
  2119. inst.status = "cancelled"
  2120. inst.update_by = user_id
  2121. inst.update_time = now
  2122. db.add(inst)
  2123. for t in (
  2124. db.query(OaTask)
  2125. .filter(OaTask.instance_id == inst.id, OaTask.status == "pending", OaTask.del_flag == 0)
  2126. .all()
  2127. ):
  2128. t.status = "cancelled"
  2129. t.update_by = user_id
  2130. t.update_time = now
  2131. db.add(t)
  2132. _add_instance_event(
  2133. db,
  2134. inst=inst,
  2135. event_type="withdraw",
  2136. actor_user_id=user_id,
  2137. round_no=int(getattr(inst, "current_round", None) or 1),
  2138. )
  2139. db.commit()
  2140. return get_instance_detail(db, inst.id, tenant_no=tenant_no)