oa_engine.py 83 KB

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