oa_engine.py 88 KB

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