oa_engine.py 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615
  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 import or_
  9. from sqlalchemy.orm import Session
  10. from app.core.utils import generate_uuid
  11. from app.crud import oa_approval as oa_crud
  12. from app.models.models import (
  13. OaApp,
  14. OaAppVersion,
  15. OaInstance,
  16. OaInstanceEvent,
  17. OaRelation,
  18. OaTask,
  19. SysDept,
  20. SysPost,
  21. SysUser,
  22. )
  23. from app.services.oa_assignee import (
  24. AssigneeResolveError,
  25. normalize_cc_assignee_types,
  26. resolve_assignees,
  27. resolve_cc_assignees,
  28. )
  29. from app.services.oa_formula import FormulaError, apply_formulas_and_linkages, eval_formula
  30. from app.services.oa_confirmation_kit_sync import apply_confirmation_kit_user_sync
  31. from app.services.oa_resignation_kit_sync import apply_resignation_kit_user_sync
  32. import logging
  33. logger = logging.getLogger(__name__)
  34. class OaEngineError(ValueError):
  35. """引擎业务错误"""
  36. _AUTO_PASS_COMMENT = "系统自动通过"
  37. INITIATOR_CONDITION_FIELD = "__initiator__"
  38. def _loads(text: Optional[str], default: Any = None) -> Any:
  39. if text is None or text == "":
  40. return default
  41. if not isinstance(text, str):
  42. return text
  43. try:
  44. return json.loads(text)
  45. except (TypeError, ValueError):
  46. return default
  47. def _dumps(data: Any) -> str:
  48. return json.dumps(data if data is not None else {}, ensure_ascii=False)
  49. def _normalize_initiator_select_by_node(raw: Any) -> Dict[str, List[str]]:
  50. if not isinstance(raw, dict):
  51. return {}
  52. out: Dict[str, List[str]] = {}
  53. for k, v in raw.items():
  54. nid = str(k or "").strip()
  55. if not nid or not isinstance(v, (list, tuple)):
  56. continue
  57. ids: List[str] = []
  58. seen = set()
  59. for x in v:
  60. uid = str(x or "").strip()
  61. if uid and uid not in seen:
  62. seen.add(uid)
  63. ids.append(uid)
  64. out[nid] = ids
  65. return out
  66. def _ids_for_initiator_select_node(
  67. select_by_node: Optional[Dict[str, List[str]]], node_id: str
  68. ) -> List[str]:
  69. m = select_by_node or {}
  70. nid = str(node_id or "").strip()
  71. if not nid:
  72. return []
  73. return list(m.get(nid) or [])
  74. def _load_initiator_select_by_node(inst: Any) -> Dict[str, List[str]]:
  75. return _normalize_initiator_select_by_node(
  76. _loads(getattr(inst, "initiator_select_json", None), {}) or {}
  77. )
  78. def _node_type(node: Dict[str, Any]) -> str:
  79. return (node.get("type") or "").strip()
  80. def _subtree_contains(node: Optional[Dict[str, Any]], node_id: str) -> bool:
  81. """节点子树(含自身、child、条件分支)是否包含指定 id。"""
  82. if not isinstance(node, dict):
  83. return False
  84. if (node.get("id") or "") == node_id:
  85. return True
  86. child = node.get("child")
  87. if isinstance(child, dict) and _subtree_contains(child, node_id):
  88. return True
  89. for g in node.get("conditionGroups") or []:
  90. if isinstance(g, dict) and _subtree_contains(g.get("child"), node_id):
  91. return True
  92. return False
  93. def _merge_after_branch_end(
  94. root: Dict[str, Any], end_id: str
  95. ) -> Optional[Dict[str, Any]]:
  96. """若 end 落在某条件分支组内,返回最近一层条件节点的汇合后 child(若有)。"""
  97. def walk(node: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
  98. if not isinstance(node, dict):
  99. return None
  100. if _node_type(node) == "condition":
  101. for g in node.get("conditionGroups") or []:
  102. if not isinstance(g, dict):
  103. continue
  104. if not _subtree_contains(g.get("child"), end_id):
  105. continue
  106. # 优先内层条件的汇合,再回退到本层
  107. nested = walk(g.get("child"))
  108. if nested is not None:
  109. return nested
  110. merge = node.get("child")
  111. return merge if isinstance(merge, dict) else None
  112. merge_child = node.get("child")
  113. if isinstance(merge_child, dict):
  114. return walk(merge_child)
  115. return None
  116. child = node.get("child")
  117. if isinstance(child, dict):
  118. return walk(child)
  119. return None
  120. return walk(root)
  121. def _flow_root(flow_tree: Any) -> Dict[str, Any]:
  122. if not isinstance(flow_tree, dict):
  123. raise OaEngineError("流程树无效")
  124. if isinstance(flow_tree.get("root"), dict):
  125. return flow_tree["root"]
  126. return flow_tree
  127. def _find_node(root: Dict[str, Any], node_key: str) -> Optional[Dict[str, Any]]:
  128. if not root or not node_key:
  129. return None
  130. if (root.get("id") or "") == node_key:
  131. return root
  132. child = root.get("child")
  133. if isinstance(child, dict):
  134. found = _find_node(child, node_key)
  135. if found:
  136. return found
  137. for g in root.get("conditionGroups") or []:
  138. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  139. found = _find_node(g["child"], node_key)
  140. if found:
  141. return found
  142. return None
  143. def _flow_node_key_order(root: Dict[str, Any]) -> Dict[str, int]:
  144. """按流程树先序遍历为 node.id 分配稳定序号(用于详情时间轴排序)。"""
  145. order: Dict[str, int] = {}
  146. counter = 0
  147. def walk(node: Any) -> None:
  148. nonlocal counter
  149. if not isinstance(node, dict):
  150. return
  151. nid = (node.get("id") or "").strip()
  152. if nid and nid not in order:
  153. order[nid] = counter
  154. counter += 1
  155. if _node_type(node) == "condition":
  156. for g in node.get("conditionGroups") or []:
  157. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  158. walk(g["child"])
  159. child = node.get("child")
  160. if isinstance(child, dict):
  161. walk(child)
  162. walk(root)
  163. return order
  164. def _next_task_order_num(db: Session, instance_id: str) -> int:
  165. """同一实例内任务展示序号取 max+1(无任务从 1 起)。"""
  166. rows = (
  167. db.query(OaTask.order_num)
  168. .filter(OaTask.instance_id == instance_id, OaTask.del_flag == 0)
  169. .all()
  170. )
  171. vals = [int(r[0]) for r in rows if r[0] is not None]
  172. return (max(vals) + 1) if vals else 1
  173. def _sort_tasks_for_detail(
  174. tasks: List[OaTask], *, flow_root: Optional[Dict[str, Any]]
  175. ) -> List[OaTask]:
  176. """详情时间轴:按流程树节点顺序,再 order_num / create_time(兼容旧数据同秒创建)。"""
  177. node_order = _flow_node_key_order(flow_root) if isinstance(flow_root, dict) else {}
  178. far = 10**9
  179. def key(t: OaTask) -> Tuple[int, int, int, datetime, str]:
  180. nk = (t.node_key or "").strip()
  181. return (
  182. int(getattr(t, "round_no", None) or 1),
  183. node_order.get(nk, far),
  184. int(t.order_num) if t.order_num is not None else 0,
  185. t.create_time or datetime.min,
  186. t.id or "",
  187. )
  188. return sorted(tasks, key=key)
  189. def _fmt_dt(dt: Any) -> str:
  190. if not dt:
  191. return ""
  192. if hasattr(dt, "strftime"):
  193. return dt.strftime("%Y-%m-%d %H:%M:%S")
  194. return str(dt)
  195. def _terminal_item(
  196. status: str,
  197. title: str,
  198. inst: Any,
  199. name_map: Optional[Dict[str, str]] = None,
  200. ) -> Dict[str, Any]:
  201. name_map = name_map or {}
  202. uid = ""
  203. uname = ""
  204. comment = ""
  205. # 撤销终态:归因发起人,勿让任务节点承担「已撤销」语义
  206. if status == "cancelled":
  207. uid = (getattr(inst, "initiator_user_id", None) or "").strip()
  208. uname = name_map.get(uid, "") or uid
  209. comment = "发起人撤销"
  210. return {
  211. "kind": "terminal",
  212. "roundNo": getattr(inst, "current_round", None) or 1,
  213. "title": title,
  214. "status": status,
  215. "assigneeUserId": uid,
  216. "assigneeUserName": uname,
  217. "timestamp": _fmt_dt(getattr(inst, "update_time", None)),
  218. "commentText": comment,
  219. "nodeKey": "",
  220. "taskType": "",
  221. }
  222. def _task_round(t: Any) -> int:
  223. v = getattr(t, "round_no", None)
  224. try:
  225. if v is None:
  226. return 1
  227. return int(v)
  228. except (TypeError, ValueError):
  229. return 1
  230. def _append_pending_nodes(
  231. items: List[Dict[str, Any]],
  232. *,
  233. flow_root: Dict[str, Any],
  234. reached_keys: set,
  235. round_no: int,
  236. ) -> None:
  237. """兜底:按整棵树先序挂未到达节点(无路径解析 / 无人员)。"""
  238. order = _flow_node_key_order(flow_root)
  239. for nid, _idx in sorted(order.items(), key=lambda x: x[1]):
  240. node = _find_node(flow_root, nid)
  241. if not node:
  242. continue
  243. nt = _node_type(node)
  244. if nt not in ("approval", "cc", "end") or nid in reached_keys:
  245. continue
  246. if nt == "end":
  247. title = node.get("name") or "结束"
  248. elif nt == "cc":
  249. title = node.get("name") or "抄送人"
  250. else:
  251. title = node.get("name") or "审批人"
  252. items.append(
  253. {
  254. "kind": "pending_node",
  255. "roundNo": round_no,
  256. "title": title,
  257. "status": "not_reached",
  258. "assigneeUserId": "",
  259. "assigneeUserName": "",
  260. "timestamp": "",
  261. "commentText": "",
  262. "nodeKey": nid,
  263. "taskType": nt,
  264. "signMode": "",
  265. "people": [],
  266. }
  267. )
  268. def _pending_people_for_node(
  269. db: Session,
  270. *,
  271. node: Dict[str, Any],
  272. tenant_no: str,
  273. initiator_user_id: str,
  274. initiator_dept_id: Optional[str],
  275. advanced: Dict[str, Any],
  276. initiator_select_by_node: Optional[Dict[str, List[str]]],
  277. ) -> Tuple[List[Dict[str, Any]], str, str]:
  278. """解析未到达节点的展示人员与签批模式。返回 (people, sign_mode, resolve_source)。"""
  279. ntype = _node_type(node)
  280. cfg = node.get("approverConfig") or {}
  281. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  282. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "").strip()
  283. if ntype == "cc":
  284. sign_mode = "cc"
  285. elif not sign_mode and assignee_type != "initiator_select":
  286. sign_mode = "or"
  287. people: List[Dict[str, Any]] = []
  288. node_select_ids = _ids_for_initiator_select_node(
  289. initiator_select_by_node, node.get("id") or ""
  290. )
  291. resolve_source = assignee_type
  292. if ntype == "cc":
  293. types = normalize_cc_assignee_types(cfg)
  294. assignees, meta = resolve_cc_assignees(
  295. db,
  296. tenant_no=tenant_no,
  297. assignee_config=cfg,
  298. initiator_user_id=initiator_user_id,
  299. initiator_dept_id=initiator_dept_id,
  300. advanced=advanced,
  301. initiator_select_user_ids=node_select_ids,
  302. )
  303. resolve_source = str(meta.get("resolve_source") or "")
  304. if not resolve_source:
  305. resolve_source = "multi" if len(types) > 1 else (types[0] if types else "")
  306. for uid in assignees:
  307. people.append(
  308. {
  309. "id": uid,
  310. "nickName": "",
  311. "status": "not_reached",
  312. "timestamp": "",
  313. "commentText": "",
  314. "taskId": "",
  315. }
  316. )
  317. elif assignee_type == "initiator_select":
  318. for uid in node_select_ids:
  319. people.append(
  320. {
  321. "id": uid,
  322. "nickName": "", # 下方统一补名
  323. "status": "not_reached",
  324. "timestamp": "",
  325. "commentText": "",
  326. "taskId": "",
  327. }
  328. )
  329. else:
  330. try:
  331. assignees, _meta = resolve_assignees(
  332. db,
  333. tenant_no=tenant_no,
  334. assignee_config=cfg,
  335. initiator_user_id=initiator_user_id,
  336. initiator_dept_id=initiator_dept_id,
  337. advanced=advanced,
  338. initiator_select_user_ids=node_select_ids,
  339. )
  340. for uid in assignees:
  341. people.append(
  342. {
  343. "id": uid,
  344. "nickName": "",
  345. "status": "not_reached",
  346. "timestamp": "",
  347. "commentText": "",
  348. "taskId": "",
  349. }
  350. )
  351. except AssigneeResolveError:
  352. people = []
  353. if people:
  354. name_map = _user_name_map(db, [p["id"] for p in people if p.get("id")])
  355. for p in people:
  356. p["nickName"] = name_map.get(p["id"], "") or p["id"]
  357. return people, sign_mode, resolve_source
  358. def _iter_resolved_path_nodes(
  359. root: Optional[Dict[str, Any]],
  360. form_data: Optional[Dict[str, Any]],
  361. *,
  362. initiator_user_id: Optional[str] = None,
  363. flow_root: Optional[Dict[str, Any]] = None,
  364. ) -> Optional[List[Dict[str, Any]]]:
  365. """沿条件命中路径收集节点;无法匹配时返回 None。"""
  366. if not isinstance(root, dict):
  367. return []
  368. data = form_data or {}
  369. tree_root = flow_root if isinstance(flow_root, dict) else root
  370. out: List[Dict[str, Any]] = []
  371. cur: Optional[Dict[str, Any]] = root
  372. while cur and isinstance(cur, dict):
  373. ntype = _node_type(cur)
  374. if ntype == "end":
  375. end_id = (cur.get("id") or "").strip()
  376. # 分支叶子 end 若后面还有汇合主链,不算真正结束
  377. if end_id and _merge_after_branch_end(tree_root, end_id) is not None:
  378. break
  379. out.append(cur)
  380. break
  381. if ntype == "condition":
  382. g = _match_condition_group(
  383. cur.get("conditionGroups") or [], data, initiator_user_id=initiator_user_id
  384. )
  385. if not g:
  386. return None
  387. child = g.get("child")
  388. if isinstance(child, dict):
  389. sub = _iter_resolved_path_nodes(
  390. child,
  391. data,
  392. initiator_user_id=initiator_user_id,
  393. flow_root=tree_root,
  394. )
  395. if sub is None:
  396. return None
  397. out.extend(sub)
  398. cur = cur.get("child")
  399. continue
  400. out.append(cur)
  401. cur = cur.get("child")
  402. return out
  403. def _append_pending_nodes_on_path(
  404. items: List[Dict[str, Any]],
  405. *,
  406. db: Session,
  407. flow_root: Dict[str, Any],
  408. reached_keys: set,
  409. round_no: int,
  410. tenant_no: str,
  411. initiator_user_id: str,
  412. initiator_dept_id: Optional[str],
  413. advanced: Dict[str, Any],
  414. form_data: Optional[Dict[str, Any]],
  415. initiator_select_by_node: Optional[Dict[str, List[str]]],
  416. ) -> None:
  417. """按命中路径列出全部后续审批/抄送/结束节点(含人员),对齐发起预览。"""
  418. path = _iter_resolved_path_nodes(
  419. flow_root, form_data, initiator_user_id=initiator_user_id
  420. )
  421. if path is None:
  422. already = {
  423. (x.get("nodeKey") or "").strip()
  424. for x in items
  425. if x.get("kind") in ("task", "pending_node") and (x.get("nodeKey") or "").strip()
  426. }
  427. _append_pending_nodes(
  428. items,
  429. flow_root=flow_root,
  430. reached_keys=reached_keys | already,
  431. round_no=round_no,
  432. )
  433. return
  434. for node in path:
  435. ntype = _node_type(node)
  436. if ntype not in ("approval", "cc", "end"):
  437. continue
  438. nid = (node.get("id") or "").strip()
  439. if not nid or nid in reached_keys:
  440. continue
  441. if ntype == "end":
  442. items.append(
  443. {
  444. "kind": "pending_node",
  445. "roundNo": round_no,
  446. "title": node.get("name") or "结束",
  447. "status": "not_reached",
  448. "assigneeUserId": "",
  449. "assigneeUserName": "",
  450. "timestamp": "",
  451. "commentText": "",
  452. "nodeKey": nid,
  453. "taskType": "end",
  454. "signMode": "",
  455. "people": [],
  456. }
  457. )
  458. continue
  459. people, sign_mode, _src = _pending_people_for_node(
  460. db,
  461. node=node,
  462. tenant_no=tenant_no,
  463. initiator_user_id=initiator_user_id,
  464. initiator_dept_id=initiator_dept_id,
  465. advanced=advanced,
  466. initiator_select_by_node=initiator_select_by_node,
  467. )
  468. items.append(
  469. {
  470. "kind": "pending_node",
  471. "roundNo": round_no,
  472. "title": node.get("name") or ("抄送人" if ntype == "cc" else "审批人"),
  473. "status": "not_reached",
  474. "assigneeUserId": "",
  475. "assigneeUserName": "",
  476. "timestamp": "",
  477. "commentText": "",
  478. "nodeKey": nid,
  479. "taskType": ntype,
  480. "signMode": sign_mode,
  481. "people": people,
  482. }
  483. )
  484. def _progress_person(t: Any, name_map: Dict[str, str]) -> Dict[str, Any]:
  485. uid = (getattr(t, "assignee_user_id", None) or "").strip()
  486. return {
  487. "id": uid,
  488. "nickName": name_map.get(uid, "") or uid,
  489. "status": getattr(t, "status", None) or "",
  490. "timestamp": _fmt_dt(getattr(t, "update_time", None) or getattr(t, "create_time", None)),
  491. "commentText": getattr(t, "comment_text", None) or "",
  492. "taskId": getattr(t, "id", None) or "",
  493. "transferToUserId": "",
  494. "transferToUserName": "",
  495. }
  496. def _enrich_transfer_targets(
  497. people: List[Dict[str, Any]],
  498. group: List[Any],
  499. name_map: Dict[str, str],
  500. ) -> None:
  501. """为已转交人员补齐 transferTo*:同节点 resolve_source=transfer 且 create_by=转交人 的新任务处理人。"""
  502. by_creator: Dict[str, List[Any]] = {}
  503. for t in group:
  504. if (getattr(t, "resolve_source", None) or "").strip() != "transfer":
  505. continue
  506. creator = (getattr(t, "create_by", None) or "").strip()
  507. if not creator:
  508. continue
  509. by_creator.setdefault(creator, []).append(t)
  510. for p in people:
  511. if (p.get("status") or "") != "transferred":
  512. continue
  513. uid = (p.get("id") or "").strip()
  514. if not uid:
  515. continue
  516. candidates = by_creator.get(uid) or []
  517. if not candidates:
  518. continue
  519. # 连续转交时同一人可能只对应一次;若有多条取创建时间最接近转交时间的
  520. p_ts = (p.get("timestamp") or "").strip()
  521. def _score(t: Any) -> tuple:
  522. cts = _fmt_dt(getattr(t, "create_time", None))
  523. # 优先同秒/最近;无时间时靠后
  524. if p_ts and cts:
  525. return (0, abs(_dt_sort_key(cts) - _dt_sort_key(p_ts)), cts)
  526. return (1, 0, cts or "")
  527. target_task = sorted(candidates, key=_score)[0]
  528. tid = (getattr(target_task, "assignee_user_id", None) or "").strip()
  529. if not tid:
  530. continue
  531. p["transferToUserId"] = tid
  532. p["transferToUserName"] = name_map.get(tid, "") or tid
  533. def _dt_sort_key(s: str) -> int:
  534. """将 'YYYY-MM-DD HH:MM:SS' 粗转为可比较整数;非法则 0。"""
  535. raw = (s or "").strip().replace("-", "").replace(":", "").replace(" ", "")
  536. try:
  537. return int(raw[:14]) if raw else 0
  538. except ValueError:
  539. return 0
  540. def _aggregate_node_status(statuses: List[str]) -> str:
  541. """同节点多人任务收成卡片状态:拒绝/打回优先,其次待办,再已同意。"""
  542. sset = [str(s or "").strip() for s in statuses]
  543. if any(s == "rejected" for s in sset):
  544. return "rejected"
  545. if any(s == "returned" for s in sset):
  546. return "returned"
  547. if any(s in ("pending", "running") for s in sset):
  548. return "pending"
  549. if any(s == "approved" for s in sset):
  550. return "approved"
  551. if any(s == "completed" for s in sset):
  552. return "completed"
  553. if sset and all(s == "done" for s in sset):
  554. return "done"
  555. return sset[0] if sset else "pending"
  556. def _group_tasks_by_node(sorted_tasks: List[Any]) -> List[List[Any]]:
  557. """按 node_key 合并同节点多人(或签/会签/抄送),无 key 的任务各自独立。"""
  558. buckets: OrderedDict[str, List[Any]] = OrderedDict()
  559. for t in sorted_tasks:
  560. nk = (getattr(t, "node_key", None) or "").strip()
  561. key = nk if nk else f"__task_{(getattr(t, 'id', None) or id(t))}"
  562. buckets.setdefault(key, []).append(t)
  563. return list(buckets.values())
  564. def build_progress_items(
  565. *,
  566. inst: Any,
  567. flow_root: Optional[Dict[str, Any]],
  568. tasks: List[Any],
  569. name_map: Dict[str, str],
  570. events: Optional[List[Any]] = None,
  571. db: Optional[Session] = None,
  572. advanced: Optional[Dict[str, Any]] = None,
  573. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  574. ) -> List[Dict[str, Any]]:
  575. """投影审批进度:发起人 → 树序 tasks(同节点多人合并)→ 未到达;终态收尾。
  576. 钉钉对齐:打回结果落在审批任务节点上,不另插 kind=return / terminal 终态「已打回」行;不做同单多轮分段。
  577. 或签/会签:同一 nodeKey 只出一张卡片,people 列出各审批人及状态。
  578. 进行中:按命中路径把后续审批/抄送节点全部挂为未到达(尽量解析人员)。
  579. """
  580. events = list(events or [])
  581. sorted_tasks = _sort_tasks_for_detail(list(tasks), flow_root=flow_root)
  582. # 展示压成单轴(roundNo 统一为 1);历史多轮任务仍按树序合并展示
  583. rn = 1
  584. submit_ts = _fmt_dt(getattr(inst, "create_time", None))
  585. for e in events:
  586. if (getattr(e, "event_type", None) or "") == "submit":
  587. submit_ts = _fmt_dt(getattr(e, "create_time", None)) or submit_ts
  588. break
  589. items: List[Dict[str, Any]] = [
  590. {
  591. "kind": "submit",
  592. "roundNo": rn,
  593. "title": "发起人",
  594. "status": "submitted",
  595. "assigneeUserId": inst.initiator_user_id,
  596. "assigneeUserName": name_map.get(inst.initiator_user_id or "", ""),
  597. "timestamp": submit_ts,
  598. "commentText": "",
  599. "nodeKey": "",
  600. "taskType": "",
  601. "signMode": "",
  602. "people": [],
  603. }
  604. ]
  605. reached_keys = {
  606. (t.node_key or "").strip() for t in sorted_tasks if (t.node_key or "").strip()
  607. }
  608. for group in _group_tasks_by_node(sorted_tasks):
  609. head = group[0]
  610. people = [_progress_person(t, name_map) for t in group]
  611. _enrich_transfer_targets(people, group, name_map)
  612. statuses = [p["status"] for p in people]
  613. node_status = _aggregate_node_status(statuses)
  614. # 时间:优先取已操作人最新时间,否则取组内最新
  615. acted = [
  616. p
  617. for p in people
  618. if p["status"] in ("approved", "rejected", "returned", "completed", "transferred")
  619. ]
  620. ts_src = acted or people
  621. timestamp = ""
  622. for p in ts_src:
  623. if p.get("timestamp") and (not timestamp or p["timestamp"] > timestamp):
  624. timestamp = p["timestamp"]
  625. # 整节点仅系统清待办(cancelled)时勿带时间,避免像审批人操作过
  626. if node_status == "cancelled":
  627. timestamp = ""
  628. comments = [
  629. f"{p['nickName']}:{p['commentText']}"
  630. if len(people) > 1 and p.get("nickName")
  631. else p["commentText"]
  632. for p in people
  633. if (p.get("commentText") or "").strip()
  634. ]
  635. sign_mode = (getattr(head, "sign_mode", None) or "").strip()
  636. primary = next(
  637. (p for p in people if p["status"] == node_status),
  638. people[0] if people else None,
  639. )
  640. items.append(
  641. {
  642. "kind": "task",
  643. "roundNo": rn,
  644. "title": head.node_name or head.node_key or "-",
  645. "status": node_status,
  646. "assigneeUserId": (primary or {}).get("id", "") if len(people) == 1 else "",
  647. "assigneeUserName": (primary or {}).get("nickName", "")
  648. if len(people) == 1
  649. else "",
  650. "timestamp": timestamp,
  651. "commentText": ";".join(comments),
  652. "nodeKey": head.node_key or "",
  653. "taskType": head.task_type or "",
  654. "resolveSource": getattr(head, "resolve_source", None) or "",
  655. "signMode": sign_mode,
  656. "taskId": getattr(head, "id", None) or "",
  657. "people": people,
  658. }
  659. )
  660. if inst.status == "running" and isinstance(flow_root, dict):
  661. form_data = _loads(getattr(inst, "form_data_json", None), {}) or {}
  662. if not isinstance(form_data, dict):
  663. form_data = {}
  664. # 自选人:优先入参 → 实例 JSON → 旧数据从任务按 node_key 聚合
  665. select_by_node = _normalize_initiator_select_by_node(initiator_select_by_node)
  666. if not select_by_node:
  667. select_by_node = _load_initiator_select_by_node(inst)
  668. if not select_by_node:
  669. for t in sorted_tasks:
  670. src = (getattr(t, "resolve_source", None) or "").strip()
  671. uid = (getattr(t, "assignee_user_id", None) or "").strip()
  672. nk = (getattr(t, "node_key", None) or "").strip()
  673. if src == "initiator_select" and uid and nk:
  674. bucket = select_by_node.setdefault(nk, [])
  675. if uid not in bucket:
  676. bucket.append(uid)
  677. if db is not None:
  678. _append_pending_nodes_on_path(
  679. items,
  680. db=db,
  681. flow_root=flow_root,
  682. reached_keys=reached_keys,
  683. round_no=rn,
  684. tenant_no=getattr(inst, "tenant_no", None) or "",
  685. initiator_user_id=inst.initiator_user_id or "",
  686. initiator_dept_id=getattr(inst, "initiator_dept_id", None),
  687. advanced=advanced or dict(oa_crud.DEFAULT_ADVANCED_SETTINGS),
  688. form_data=form_data,
  689. initiator_select_by_node=select_by_node,
  690. )
  691. else:
  692. _append_pending_nodes(
  693. items, flow_root=flow_root, reached_keys=reached_keys, round_no=rn
  694. )
  695. if inst.status == "completed":
  696. items.append(_terminal_item("done", "流程结束", inst, name_map))
  697. elif inst.status == "rejected":
  698. items.append(_terminal_item("rejected", "流程结束(已拒绝)", inst, name_map))
  699. elif inst.status == "cancelled":
  700. items.append(_terminal_item("cancelled", "已撤销", inst, name_map))
  701. # returned:打回结果只落在审批任务节点上,不再追加独立终态「已打回」行
  702. return items
  703. def _add_instance_event(
  704. db: Session,
  705. *,
  706. inst: OaInstance,
  707. event_type: str,
  708. actor_user_id: Optional[str],
  709. round_no: int,
  710. comment: Optional[str] = None,
  711. task_id: Optional[str] = None,
  712. node_key: Optional[str] = None,
  713. ) -> OaInstanceEvent:
  714. now = datetime.now()
  715. ev = OaInstanceEvent(
  716. id=generate_uuid(),
  717. instance_id=inst.id,
  718. round_no=round_no,
  719. event_type=event_type,
  720. actor_user_id=actor_user_id,
  721. task_id=task_id,
  722. node_key=node_key,
  723. comment_text=(comment or "").strip() or None,
  724. tenant_no=inst.tenant_no,
  725. order_num=0,
  726. remark=None,
  727. create_by=actor_user_id,
  728. create_dept_id=inst.initiator_dept_id or "",
  729. create_time=now,
  730. update_by=actor_user_id,
  731. update_time=now,
  732. del_flag=0,
  733. )
  734. db.add(ev)
  735. return ev
  736. def _advanced(ver: OaAppVersion) -> Dict[str, Any]:
  737. data = _loads(ver.advanced_settings_json, {}) or {}
  738. if not isinstance(data, dict):
  739. return dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  740. merged = dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  741. merged.update(data)
  742. return merged
  743. def _check_initiator_scope(app: OaApp, user_id: str) -> None:
  744. scope = (app.initiator_scope or "all").strip()
  745. if scope == "all":
  746. return
  747. ids = _loads(app.initiator_user_ids, []) or []
  748. if user_id not in ids:
  749. raise OaEngineError("您不在该审批的发起范围内")
  750. def _instance_to_dict(inst: OaInstance, *, app_name: str = "") -> Dict[str, Any]:
  751. return {
  752. "id": inst.id,
  753. "appId": inst.app_id,
  754. "appVersionId": inst.app_version_id,
  755. "appName": app_name,
  756. "title": inst.title or "",
  757. "initiatorUserId": inst.initiator_user_id,
  758. "initiatorDeptId": inst.initiator_dept_id or "",
  759. "formDataJson": _loads(inst.form_data_json, {}),
  760. "status": inst.status,
  761. "sourceInstanceId": getattr(inst, "source_instance_id", None) or "",
  762. "currentRound": int(getattr(inst, "current_round", None) or 1),
  763. "createTime": inst.create_time.strftime("%Y-%m-%d %H:%M:%S") if inst.create_time else "",
  764. "updateTime": inst.update_time.strftime("%Y-%m-%d %H:%M:%S") if inst.update_time else "",
  765. }
  766. def _task_to_dict(t: OaTask, *, assignee_user_name: str = "") -> Dict[str, Any]:
  767. return {
  768. "id": t.id,
  769. "instanceId": t.instance_id,
  770. "nodeKey": t.node_key or "",
  771. "nodeName": t.node_name or "",
  772. "taskType": t.task_type,
  773. "assigneeUserId": t.assignee_user_id,
  774. "assigneeUserName": assignee_user_name or t.assignee_user_id or "",
  775. "status": t.status,
  776. "commentText": t.comment_text or "",
  777. "resolveSource": t.resolve_source or "",
  778. "signMode": t.sign_mode or "",
  779. "isRead": bool(int(getattr(t, "is_read", 0) or 0)),
  780. "readTime": (
  781. t.read_time.strftime("%Y-%m-%d %H:%M:%S")
  782. if getattr(t, "read_time", None)
  783. else ""
  784. ),
  785. "createTime": t.create_time.strftime("%Y-%m-%d %H:%M:%S") if t.create_time else "",
  786. "updateTime": t.update_time.strftime("%Y-%m-%d %H:%M:%S") if t.update_time else "",
  787. }
  788. _INSTANCE_STATUS_NODE_LABEL = {
  789. "completed": "已完成",
  790. "rejected": "已拒绝",
  791. "returned": "已打回",
  792. "cancelled": "已撤销",
  793. }
  794. def _instance_progress_summary(
  795. inst: OaInstance,
  796. *,
  797. app_name: str,
  798. initiator_user_name: str,
  799. pending_approval_tasks: List[OaTask],
  800. name_map: Dict[str, str],
  801. ) -> Dict[str, Any]:
  802. status = (inst.status or "").strip()
  803. apply_time = (
  804. inst.create_time.strftime("%Y-%m-%d %H:%M:%S") if inst.create_time else ""
  805. )
  806. if status == "running":
  807. node_names: List[str] = []
  808. seen_nodes = set()
  809. approver_names: List[str] = []
  810. for t in pending_approval_tasks:
  811. nn = (t.node_name or t.node_key or "").strip()
  812. if nn and nn not in seen_nodes:
  813. seen_nodes.add(nn)
  814. node_names.append(nn)
  815. uid = (t.assignee_user_id or "").strip()
  816. if uid:
  817. approver_names.append(name_map.get(uid, uid))
  818. current_node = "、".join(node_names) if node_names else "-"
  819. current_approvers = "、".join(approver_names) if approver_names else "-"
  820. else:
  821. current_node = _INSTANCE_STATUS_NODE_LABEL.get(status, status or "-")
  822. current_approvers = "-"
  823. return {
  824. "appName": app_name or (inst.title or ""),
  825. "initiatorUserId": inst.initiator_user_id or "",
  826. "initiatorUserName": initiator_user_name
  827. or name_map.get(inst.initiator_user_id or "", inst.initiator_user_id or ""),
  828. "applyTime": apply_time,
  829. "instanceStatus": status,
  830. "currentNodeName": current_node,
  831. "currentApproverNames": current_approvers,
  832. }
  833. def _enrich_list_rows(
  834. db: Session,
  835. *,
  836. tenant_no: str,
  837. rows: List[Dict[str, Any]],
  838. instances: List[OaInstance],
  839. preview_limit: int = 3,
  840. ) -> List[Dict[str, Any]]:
  841. if not rows:
  842. return []
  843. from app.services.oa_related_approval import flatten_form_fields_for_summary
  844. limit = max(0, int(preview_limit or 3))
  845. inst_by_id = {i.id: i for i in instances}
  846. app_ids = list({i.app_id for i in instances if i.app_id})
  847. apps = (
  848. db.query(OaApp)
  849. .filter(
  850. OaApp.id.in_(app_ids),
  851. OaApp.tenant_no == tenant_no,
  852. OaApp.del_flag == 0,
  853. )
  854. .all()
  855. if app_ids
  856. else []
  857. )
  858. app_name_by_id = {a.id: (a.app_name or "") for a in apps}
  859. ver_ids = list({i.app_version_id for i in instances if i.app_version_id})
  860. ver_by_id: Dict[str, OaAppVersion] = {}
  861. if ver_ids:
  862. for v in (
  863. db.query(OaAppVersion)
  864. .filter(OaAppVersion.id.in_(ver_ids), OaAppVersion.del_flag == 0)
  865. .all()
  866. ):
  867. ver_by_id[v.id] = v
  868. inst_ids = list(inst_by_id.keys())
  869. pending_tasks = (
  870. db.query(OaTask)
  871. .filter(
  872. OaTask.tenant_no == tenant_no,
  873. OaTask.del_flag == 0,
  874. OaTask.instance_id.in_(inst_ids),
  875. OaTask.task_type == "approval",
  876. OaTask.status == "pending",
  877. )
  878. .order_by(OaTask.create_time.asc())
  879. .all()
  880. if inst_ids
  881. else []
  882. )
  883. pending_by_inst: Dict[str, List[OaTask]] = {}
  884. for t in pending_tasks:
  885. pending_by_inst.setdefault(t.instance_id, []).append(t)
  886. user_ids: List[str] = []
  887. for i in instances:
  888. if i.initiator_user_id:
  889. user_ids.append(i.initiator_user_id)
  890. for t in pending_tasks:
  891. if t.assignee_user_id:
  892. user_ids.append(t.assignee_user_id)
  893. name_map = _user_name_map(db, user_ids)
  894. out: List[Dict[str, Any]] = []
  895. for row in rows:
  896. iid = row.get("instanceId") or row.get("id")
  897. inst = inst_by_id.get(iid)
  898. if not inst:
  899. out.append(row)
  900. continue
  901. summary = _instance_progress_summary(
  902. inst,
  903. app_name=app_name_by_id.get(inst.app_id, ""),
  904. initiator_user_name=name_map.get(inst.initiator_user_id or "", ""),
  905. pending_approval_tasks=pending_by_inst.get(inst.id, []),
  906. name_map=name_map,
  907. )
  908. ver = ver_by_id.get(inst.app_version_id or "")
  909. schema = _loads(getattr(ver, "form_schema_json", None), {}) if ver else {}
  910. form_data = _loads(inst.form_data_json, {}) or {}
  911. preview = []
  912. for f in flatten_form_fields_for_summary(schema, form_data)[:limit]:
  913. item = dict(f)
  914. item["label"] = item.get("label") or ""
  915. item["value"] = item.get("value") or ""
  916. preview.append(item)
  917. merged = dict(row)
  918. merged.update(summary)
  919. merged["previewFields"] = preview
  920. st = (inst.status or "").strip()
  921. if st in _FINISH_STATUSES and inst.update_time:
  922. merged["finishTime"] = inst.update_time.strftime("%Y-%m-%d %H:%M:%S")
  923. else:
  924. merged["finishTime"] = None
  925. out.append(merged)
  926. return out
  927. def _user_name_map(db: Session, user_ids: List[str]) -> Dict[str, str]:
  928. ids = [uid for uid in {str(u or "").strip() for u in user_ids} if uid]
  929. if not ids:
  930. return {}
  931. rows = db.query(SysUser.id, SysUser.nick_name).filter(SysUser.id.in_(ids)).all()
  932. return {r.id: (r.nick_name or r.id) for r in rows}
  933. def _dept_name(db: Session, dept_id: Optional[str], *, tenant_no: str) -> str:
  934. did = (dept_id or "").strip()
  935. if not did:
  936. return ""
  937. row = (
  938. db.query(SysDept.dept_name)
  939. .filter(SysDept.id == did, SysDept.tenant_no == tenant_no, SysDept.del_flag == 0)
  940. .first()
  941. )
  942. if not row:
  943. return ""
  944. return (row[0] or "").strip()
  945. def list_templates(db: Session, *, tenant_no: str, user_id: str) -> List[Dict[str, Any]]:
  946. apps = (
  947. db.query(OaApp)
  948. .filter(OaApp.tenant_no == tenant_no, OaApp.del_flag == 0, OaApp.status == "1")
  949. .order_by(OaApp.order_num.asc(), OaApp.create_time.desc())
  950. .all()
  951. )
  952. out: List[Dict[str, Any]] = []
  953. for app in apps:
  954. pub = oa_crud._find_latest_published(db, app.id, tenant_no)
  955. if not pub:
  956. continue
  957. try:
  958. _check_initiator_scope(app, user_id)
  959. except OaEngineError:
  960. continue
  961. out.append(
  962. {
  963. "id": app.id,
  964. "appName": app.app_name,
  965. "groupId": app.group_id or "",
  966. "iconUrl": app.icon_url or "",
  967. "description": app.description or "",
  968. "versionId": pub.id,
  969. "versionNo": pub.version_no,
  970. }
  971. )
  972. return out
  973. def get_template_detail(
  974. db: Session, *, tenant_no: str, app_id: str, user_id: str
  975. ) -> Dict[str, Any]:
  976. app = oa_crud.get_app(db, app_id, tenant_no)
  977. if not app or app.status != "1":
  978. raise OaEngineError("应用不存在或已停用")
  979. _check_initiator_scope(app, user_id)
  980. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  981. if not pub:
  982. raise OaEngineError("应用尚未发布")
  983. return {
  984. "id": app.id,
  985. "appName": app.app_name,
  986. "groupId": app.group_id or "",
  987. "iconUrl": app.icon_url or "",
  988. "description": app.description or "",
  989. "versionId": pub.id,
  990. "versionNo": pub.version_no,
  991. "formSchemaJson": _loads(pub.form_schema_json, {}),
  992. "flowTreeJson": _loads(pub.flow_tree_json, {}),
  993. "advancedSettingsJson": _advanced(pub),
  994. }
  995. _ASSIGNEE_TYPE_LABEL = {
  996. "users": "指定成员",
  997. "posts": "职位",
  998. "dept_leader": "发起人部门负责人",
  999. "direct_supervisor": "发起人的主管",
  1000. "initiator_select": "发起人自选",
  1001. }
  1002. def _post_name_map(db: Session, tenant_no: str, post_ids: List[str]) -> List[str]:
  1003. names: List[str] = []
  1004. ids = [str(x).strip() for x in (post_ids or []) if str(x).strip()]
  1005. if not ids:
  1006. return names
  1007. rows = (
  1008. db.query(SysPost)
  1009. .filter(SysPost.tenant_no == tenant_no, SysPost.id.in_(ids), SysPost.del_flag == 0)
  1010. .all()
  1011. )
  1012. by_id = {r.id: (r.post_name or r.post_code or r.id) for r in rows}
  1013. for pid in ids:
  1014. label = by_id.get(pid)
  1015. if label and label not in names:
  1016. names.append(label)
  1017. return names
  1018. def _assignee_meta(db: Session, tenant_no: str, cfg: Dict[str, Any]) -> str:
  1019. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  1020. base = _ASSIGNEE_TYPE_LABEL.get(assignee_type, assignee_type or "未配置审批人")
  1021. if assignee_type == "posts":
  1022. names = _post_name_map(
  1023. db,
  1024. tenant_no,
  1025. cfg.get("postIds") or cfg.get("post_ids") or [],
  1026. )
  1027. if names:
  1028. return f"{base} · {'/'.join(names)}"
  1029. return base
  1030. def _assignee_meta_for_cc(
  1031. db: Session, tenant_no: str, cfg: Dict[str, Any], types: List[str]
  1032. ) -> str:
  1033. if not types:
  1034. return "未配置抄送人"
  1035. if len(types) == 1:
  1036. return _assignee_meta(db, tenant_no, {**cfg, "assigneeType": types[0]})
  1037. labels = [_ASSIGNEE_TYPE_LABEL.get(t, t) for t in types]
  1038. return " + ".join(labels)
  1039. def _preview_people(db: Session, user_ids: List[str]) -> List[Dict[str, str]]:
  1040. name_map = _user_name_map(db, user_ids)
  1041. out: List[Dict[str, str]] = []
  1042. for uid in user_ids:
  1043. out.append({"id": uid, "nickName": name_map.get(uid) or uid})
  1044. return out
  1045. _FLOW_PREVIEW_PENDING_MSG = "必填信息填写后,流程将自动显示"
  1046. _FLOW_PREVIEW_UNMATCHED_MSG = "流程条件无法匹配,请检查表单或联系管理员"
  1047. _FORMULA_FIELD_RE = re.compile(r"\{([^{}]+)\}")
  1048. def _form_value_present(form_data: Optional[Dict[str, Any]], field: str) -> bool:
  1049. """条件字段是否已有有效值(0 / false 视为已填)。"""
  1050. if not field:
  1051. return True
  1052. data = form_data or {}
  1053. if field not in data:
  1054. return False
  1055. val = data.get(field)
  1056. if val is None:
  1057. return False
  1058. if isinstance(val, str) and not val.strip():
  1059. return False
  1060. if isinstance(val, (list, tuple, set, dict)) and len(val) == 0:
  1061. return False
  1062. return True
  1063. def _collect_condition_fields(node: Optional[Dict[str, Any]]) -> List[str]:
  1064. """收集流程树中非默认条件分支引用的表单字段(去重保序)。
  1065. 系统伪字段 ``__initiator__`` 不依赖 formData,不纳入预览门闩。
  1066. """
  1067. fields: List[str] = []
  1068. seen = set()
  1069. def add(name: Any) -> None:
  1070. key = str(name or "").strip()
  1071. if not key or key in seen:
  1072. return
  1073. if key == INITIATOR_CONDITION_FIELD:
  1074. return
  1075. seen.add(key)
  1076. fields.append(key)
  1077. def walk(n: Any) -> None:
  1078. if not isinstance(n, dict):
  1079. return
  1080. if _node_type(n) == "condition":
  1081. for g in n.get("conditionGroups") or []:
  1082. if not isinstance(g, dict):
  1083. continue
  1084. rules = g.get("rules")
  1085. when = g.get("when")
  1086. if g.get("isDefault") or (not rules and not when):
  1087. child = g.get("child")
  1088. if isinstance(child, dict):
  1089. walk(child)
  1090. continue
  1091. if isinstance(rules, list) and rules:
  1092. for r in rules:
  1093. if isinstance(r, dict) and r.get("field") is not None:
  1094. add(r.get("field"))
  1095. elif isinstance(rules, str) and rules.strip():
  1096. for m in _FORMULA_FIELD_RE.findall(rules):
  1097. add(m)
  1098. elif when:
  1099. for m in _FORMULA_FIELD_RE.findall(str(when)):
  1100. add(m)
  1101. child = g.get("child")
  1102. if isinstance(child, dict):
  1103. walk(child)
  1104. join_child = n.get("child")
  1105. if isinstance(join_child, dict):
  1106. walk(join_child)
  1107. return
  1108. child = n.get("child")
  1109. if isinstance(child, dict):
  1110. walk(child)
  1111. for g in n.get("conditionGroups") or []:
  1112. if isinstance(g, dict) and isinstance(g.get("child"), dict):
  1113. walk(g.get("child"))
  1114. walk(node)
  1115. return fields
  1116. def _condition_fields_ready(
  1117. root: Optional[Dict[str, Any]], form_data: Optional[Dict[str, Any]]
  1118. ) -> bool:
  1119. fields = _collect_condition_fields(root)
  1120. if not fields:
  1121. return True
  1122. data = form_data or {}
  1123. return all(_form_value_present(data, f) for f in fields)
  1124. def _walk_preview_nodes(
  1125. db: Session,
  1126. *,
  1127. node: Optional[Dict[str, Any]],
  1128. tenant_no: str,
  1129. initiator_user_id: str,
  1130. initiator_dept_id: Optional[str],
  1131. advanced: Dict[str, Any],
  1132. initiator_select_by_node: Optional[Dict[str, List[str]]],
  1133. form_data: Optional[Dict[str, Any]],
  1134. steps: List[Dict[str, Any]],
  1135. flow_root: Optional[Dict[str, Any]] = None,
  1136. ) -> bool:
  1137. """沿最终路径写入 steps。条件无法匹配时返回 False。"""
  1138. cur = node
  1139. data = form_data or {}
  1140. tree_root = (
  1141. flow_root if isinstance(flow_root, dict) else (node if isinstance(node, dict) else {})
  1142. )
  1143. while cur and isinstance(cur, dict):
  1144. ntype = _node_type(cur)
  1145. if ntype == "start":
  1146. people = _preview_people(db, [initiator_user_id] if initiator_user_id else [])
  1147. steps.append(
  1148. {
  1149. "id": cur.get("id") or "",
  1150. "type": "start",
  1151. "name": cur.get("name") or "发起人",
  1152. "signMode": "",
  1153. "assigneeType": "",
  1154. "meta": "",
  1155. "people": people,
  1156. "resolveError": "",
  1157. }
  1158. )
  1159. cur = cur.get("child")
  1160. continue
  1161. if ntype == "end":
  1162. end_id = (cur.get("id") or "").strip()
  1163. # 分支叶子 end 后若有汇合主链,不写入「结束」(与引擎推进一致)
  1164. if end_id and _merge_after_branch_end(tree_root, end_id) is not None:
  1165. break
  1166. steps.append(
  1167. {
  1168. "id": cur.get("id") or "",
  1169. "type": "end",
  1170. "name": cur.get("name") or "结束",
  1171. "signMode": "",
  1172. "assigneeType": "",
  1173. "meta": "",
  1174. "people": [],
  1175. "resolveError": "",
  1176. }
  1177. )
  1178. break
  1179. if ntype == "condition":
  1180. groups = cur.get("conditionGroups") or []
  1181. g = _match_condition_group(
  1182. groups, data, initiator_user_id=initiator_user_id
  1183. )
  1184. if not g:
  1185. return False
  1186. child = g.get("child")
  1187. if isinstance(child, dict):
  1188. ok = _walk_preview_nodes(
  1189. db,
  1190. node=child,
  1191. tenant_no=tenant_no,
  1192. initiator_user_id=initiator_user_id,
  1193. initiator_dept_id=initiator_dept_id,
  1194. advanced=advanced,
  1195. initiator_select_by_node=initiator_select_by_node,
  1196. form_data=data,
  1197. steps=steps,
  1198. flow_root=tree_root,
  1199. )
  1200. if not ok:
  1201. return False
  1202. cur = cur.get("child")
  1203. continue
  1204. if ntype in ("approval", "cc"):
  1205. cfg = cur.get("approverConfig") or {}
  1206. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "").strip()
  1207. people: List[Dict[str, str]] = []
  1208. resolve_error = ""
  1209. node_select_ids = _ids_for_initiator_select_node(
  1210. initiator_select_by_node, cur.get("id") or ""
  1211. )
  1212. if ntype == "cc":
  1213. types = normalize_cc_assignee_types(cfg)
  1214. if "initiator_select" in types:
  1215. display_type = "initiator_select"
  1216. elif len(types) == 1:
  1217. display_type = types[0]
  1218. elif types:
  1219. display_type = "multi"
  1220. else:
  1221. display_type = ""
  1222. sign_mode = "cc"
  1223. meta = _assignee_meta_for_cc(db, tenant_no, cfg, types)
  1224. assignees, _meta = resolve_cc_assignees(
  1225. db,
  1226. tenant_no=tenant_no,
  1227. assignee_config=cfg,
  1228. initiator_user_id=initiator_user_id,
  1229. initiator_dept_id=initiator_dept_id,
  1230. advanced=advanced,
  1231. initiator_select_user_ids=node_select_ids,
  1232. )
  1233. people = _preview_people(db, assignees)
  1234. steps.append(
  1235. {
  1236. "id": cur.get("id") or "",
  1237. "type": ntype,
  1238. "name": cur.get("name") or "抄送人",
  1239. "signMode": sign_mode,
  1240. "assigneeType": display_type,
  1241. "assigneeTypes": types,
  1242. "meta": meta,
  1243. "people": people,
  1244. "resolveError": resolve_error,
  1245. }
  1246. )
  1247. else:
  1248. assignee_type = (
  1249. cfg.get("assigneeType") or cfg.get("assignee_type") or ""
  1250. ).strip()
  1251. if not sign_mode and assignee_type != "initiator_select":
  1252. sign_mode = "or"
  1253. meta = _assignee_meta(db, tenant_no, cfg)
  1254. if assignee_type == "initiator_select":
  1255. people = _preview_people(
  1256. db, [str(x) for x in node_select_ids if str(x).strip()]
  1257. )
  1258. if not people:
  1259. meta = meta or "发起人自选"
  1260. else:
  1261. try:
  1262. assignees, _meta = resolve_assignees(
  1263. db,
  1264. tenant_no=tenant_no,
  1265. assignee_config=cfg,
  1266. initiator_user_id=initiator_user_id,
  1267. initiator_dept_id=initiator_dept_id,
  1268. advanced=advanced,
  1269. initiator_select_user_ids=node_select_ids,
  1270. )
  1271. people = _preview_people(db, assignees)
  1272. except AssigneeResolveError as e:
  1273. resolve_error = str(e)
  1274. steps.append(
  1275. {
  1276. "id": cur.get("id") or "",
  1277. "type": ntype,
  1278. "name": cur.get("name") or "审批人",
  1279. "signMode": sign_mode,
  1280. "assigneeType": assignee_type,
  1281. "meta": meta,
  1282. "people": people,
  1283. "resolveError": resolve_error,
  1284. }
  1285. )
  1286. cur = cur.get("child")
  1287. continue
  1288. cur = cur.get("child")
  1289. return True
  1290. def preview_start_flow(
  1291. db: Session,
  1292. *,
  1293. tenant_no: str,
  1294. app_id: str,
  1295. initiator_user_id: str,
  1296. initiator_dept_id: Optional[str] = None,
  1297. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1298. form_data: Optional[Dict[str, Any]] = None,
  1299. ) -> Dict[str, Any]:
  1300. """发起前预览审批链:条件字段齐后只走命中路径并解析人员。"""
  1301. app = oa_crud.get_app(db, app_id, tenant_no)
  1302. if not app or app.status != "1":
  1303. raise OaEngineError("应用不存在或已停用")
  1304. _check_initiator_scope(app, initiator_user_id)
  1305. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  1306. if not pub:
  1307. raise OaEngineError("应用尚未发布")
  1308. initiator = (
  1309. db.query(SysUser)
  1310. .filter(
  1311. SysUser.id == initiator_user_id,
  1312. SysUser.tenant_no == tenant_no,
  1313. SysUser.del_flag == 0,
  1314. )
  1315. .first()
  1316. )
  1317. dept_id = (initiator_dept_id or "").strip() or (
  1318. (initiator.dept_id or "") if initiator else ""
  1319. )
  1320. flow = _loads(pub.flow_tree_json, {}) or {}
  1321. root = flow.get("root") if isinstance(flow, dict) else None
  1322. if not isinstance(root, dict):
  1323. root = flow if isinstance(flow, dict) else {}
  1324. data = dict(form_data or {})
  1325. if not _condition_fields_ready(root, data):
  1326. return {
  1327. "resolved": False,
  1328. "message": _FLOW_PREVIEW_PENDING_MSG,
  1329. "steps": [],
  1330. }
  1331. steps: List[Dict[str, Any]] = []
  1332. select_by_node = _normalize_initiator_select_by_node(initiator_select_by_node)
  1333. ok = _walk_preview_nodes(
  1334. db,
  1335. node=root,
  1336. tenant_no=tenant_no,
  1337. initiator_user_id=initiator_user_id,
  1338. initiator_dept_id=dept_id or None,
  1339. advanced=_advanced(pub),
  1340. initiator_select_by_node=select_by_node,
  1341. form_data=data,
  1342. steps=steps,
  1343. flow_root=root,
  1344. )
  1345. if not ok:
  1346. return {
  1347. "resolved": False,
  1348. "message": _FLOW_PREVIEW_UNMATCHED_MSG,
  1349. "steps": [],
  1350. }
  1351. return {"resolved": True, "message": "", "steps": steps}
  1352. def _create_tasks_for_node(
  1353. db: Session,
  1354. *,
  1355. inst: OaInstance,
  1356. node: Dict[str, Any],
  1357. ver: OaAppVersion,
  1358. user_id: Optional[str],
  1359. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1360. order_num_start: Optional[int] = None,
  1361. ) -> List[OaTask]:
  1362. ntype = _node_type(node)
  1363. now = datetime.now()
  1364. created: List[OaTask] = []
  1365. if ntype == "cc":
  1366. task_type = "cc"
  1367. elif ntype == "approval":
  1368. task_type = "approval"
  1369. else:
  1370. return created
  1371. cfg = node.get("approverConfig") or {}
  1372. node_select_ids = _ids_for_initiator_select_node(
  1373. initiator_select_by_node, node.get("id") or ""
  1374. )
  1375. advanced = _advanced(ver)
  1376. if ntype == "cc":
  1377. assignees, meta = resolve_cc_assignees(
  1378. db,
  1379. tenant_no=inst.tenant_no,
  1380. assignee_config=cfg,
  1381. initiator_user_id=inst.initiator_user_id,
  1382. initiator_dept_id=inst.initiator_dept_id,
  1383. advanced=advanced,
  1384. initiator_select_user_ids=node_select_ids,
  1385. )
  1386. if not assignees:
  1387. return created
  1388. else:
  1389. assignee_type = (cfg.get("assigneeType") or cfg.get("assignee_type") or "").strip()
  1390. if assignee_type == "initiator_select" and not node_select_ids:
  1391. raise OaEngineError("发起人未选择审批人")
  1392. try:
  1393. assignees, meta = resolve_assignees(
  1394. db,
  1395. tenant_no=inst.tenant_no,
  1396. assignee_config=cfg,
  1397. initiator_user_id=inst.initiator_user_id,
  1398. initiator_dept_id=inst.initiator_dept_id,
  1399. advanced=advanced,
  1400. initiator_select_user_ids=node_select_ids,
  1401. )
  1402. except AssigneeResolveError as e:
  1403. raise OaEngineError(str(e)) from e
  1404. sign_mode = (cfg.get("signMode") or cfg.get("sign_mode") or "or").strip() or "or"
  1405. resolve_source = meta.get("resolve_source")
  1406. status = "done" if task_type == "cc" else "pending"
  1407. seq = order_num_start if order_num_start is not None else _next_task_order_num(db, inst.id)
  1408. for uid in assignees:
  1409. t = OaTask(
  1410. id=generate_uuid(),
  1411. instance_id=inst.id,
  1412. node_key=node.get("id") or "",
  1413. node_name=node.get("name") or "",
  1414. task_type=task_type,
  1415. assignee_user_id=uid,
  1416. status=status,
  1417. comment_text=None,
  1418. resolve_source=resolve_source,
  1419. sign_mode=sign_mode if task_type == "approval" else None,
  1420. is_read=0,
  1421. read_time=None,
  1422. round_no=int(getattr(inst, "current_round", None) or 1),
  1423. tenant_no=inst.tenant_no,
  1424. order_num=seq,
  1425. remark=None,
  1426. create_by=user_id,
  1427. create_dept_id=inst.initiator_dept_id or "",
  1428. create_time=now,
  1429. update_by=user_id,
  1430. update_time=now,
  1431. del_flag=0,
  1432. )
  1433. seq += 1
  1434. db.add(t)
  1435. created.append(t)
  1436. return created
  1437. def _eval_condition_rules(
  1438. rules: List[Any],
  1439. form_data: Dict[str, Any],
  1440. *,
  1441. initiator_user_id: Optional[str] = None,
  1442. ) -> bool:
  1443. """AND 多条 {field, op, value};contains 走人员/职位/部门集合交集,其余走公式。"""
  1444. from app.services.oa_dept_select import dept_contains_match
  1445. from app.services.oa_person_select import person_contains_match
  1446. from app.services.oa_post_select import post_contains_match
  1447. for r in rules:
  1448. if not isinstance(r, dict):
  1449. return False
  1450. field = r.get("field")
  1451. op = r.get("op") or "=="
  1452. val = r.get("value")
  1453. if field is None:
  1454. return False
  1455. if op == "contains":
  1456. if field == INITIATOR_CONDITION_FIELD:
  1457. uid = (initiator_user_id or "").strip()
  1458. if isinstance(val, list):
  1459. allowed = {str(x or "").strip() for x in val if str(x or "").strip()}
  1460. elif isinstance(val, str) and val.strip():
  1461. allowed = {val.strip()}
  1462. else:
  1463. allowed = set()
  1464. if not uid or uid not in allowed:
  1465. return False
  1466. continue
  1467. form_val = form_data.get(field)
  1468. if not (
  1469. person_contains_match(form_val, val)
  1470. or post_contains_match(form_val, val)
  1471. or dept_contains_match(form_val, val)
  1472. ):
  1473. return False
  1474. continue
  1475. if isinstance(val, str):
  1476. expr = f"{{{field}}} {op} '{val}'"
  1477. else:
  1478. expr = f"{{{field}}} {op} {val}"
  1479. try:
  1480. if not eval_formula(expr, form_data):
  1481. return False
  1482. except FormulaError:
  1483. return False
  1484. return True
  1485. def _match_condition_group(
  1486. groups: List[Any],
  1487. form_data: Dict[str, Any],
  1488. *,
  1489. initiator_user_id: Optional[str] = None,
  1490. ) -> Optional[Dict[str, Any]]:
  1491. default_g = None
  1492. for g in groups:
  1493. if not isinstance(g, dict):
  1494. continue
  1495. rules = g.get("rules")
  1496. when = g.get("when")
  1497. # 空规则 = 默认分支
  1498. if (not rules and not when) or g.get("isDefault"):
  1499. default_g = g
  1500. continue
  1501. if when:
  1502. try:
  1503. if eval_formula(str(when), form_data):
  1504. return g
  1505. except FormulaError:
  1506. continue
  1507. continue
  1508. if isinstance(rules, str):
  1509. try:
  1510. if eval_formula(str(rules), form_data):
  1511. return g
  1512. except FormulaError:
  1513. continue
  1514. continue
  1515. if isinstance(rules, list) and rules:
  1516. try:
  1517. if _eval_condition_rules(
  1518. rules, form_data, initiator_user_id=initiator_user_id
  1519. ):
  1520. return g
  1521. except FormulaError:
  1522. continue
  1523. continue
  1524. default_g = g
  1525. return default_g
  1526. def advance_from(
  1527. db: Session,
  1528. *,
  1529. inst: OaInstance,
  1530. ver: OaAppVersion,
  1531. from_node: Optional[Dict[str, Any]],
  1532. user_id: Optional[str],
  1533. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1534. ) -> List[str]:
  1535. """从某节点的下一跳开始推进;from_node 为 None 表示从 start 进入。
  1536. 返回本次推进新创建的任务 id 列表(含抄送与嵌套自动通过产生的后续任务)。
  1537. """
  1538. root = _flow_root(_loads(ver.flow_tree_json, {}))
  1539. form_data = _loads(inst.form_data_json, {}) or {}
  1540. created_ids: List[str] = []
  1541. def next_node(node: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  1542. ntype = _node_type(node)
  1543. if ntype == "condition":
  1544. groups = node.get("conditionGroups") or []
  1545. g = _match_condition_group(
  1546. groups, form_data, initiator_user_id=inst.initiator_user_id
  1547. )
  1548. if not g or not isinstance(g.get("child"), dict):
  1549. raise OaEngineError("条件分支无法匹配出线")
  1550. return g["child"]
  1551. child = node.get("child")
  1552. return child if isinstance(child, dict) else None
  1553. # 起点
  1554. if from_node is None:
  1555. cur = next_node(root) if _node_type(root) == "start" else root
  1556. else:
  1557. cur = next_node(from_node)
  1558. # 同一次推进里可能连续落抄送+审批:共用递增序号,避免 create_time 同秒时乱序
  1559. next_order = _next_task_order_num(db, inst.id)
  1560. safety = 0
  1561. while cur and safety < 50:
  1562. safety += 1
  1563. ntype = _node_type(cur)
  1564. if ntype == "end":
  1565. merge = _merge_after_branch_end(root, cur.get("id") or "")
  1566. if merge is not None:
  1567. cur = merge
  1568. continue
  1569. inst.status = "completed"
  1570. inst.update_time = datetime.now()
  1571. db.add(inst)
  1572. try:
  1573. apply_confirmation_kit_user_sync(db, inst)
  1574. except Exception:
  1575. logger.exception(
  1576. "confirmation kit user sync failed instance=%s", getattr(inst, "id", None)
  1577. )
  1578. try:
  1579. apply_resignation_kit_user_sync(db, inst)
  1580. except Exception:
  1581. logger.exception(
  1582. "resignation kit user sync failed instance=%s", getattr(inst, "id", None)
  1583. )
  1584. return created_ids
  1585. if ntype == "condition":
  1586. cur = next_node(cur)
  1587. continue
  1588. if ntype in ("approval", "cc"):
  1589. tasks = _create_tasks_for_node(
  1590. db,
  1591. inst=inst,
  1592. node=cur,
  1593. ver=ver,
  1594. user_id=user_id,
  1595. initiator_select_by_node=initiator_select_by_node,
  1596. order_num_start=next_order,
  1597. )
  1598. created_ids.extend([t.id for t in tasks if getattr(t, "id", None)])
  1599. next_order += max(len(tasks), 1)
  1600. if ntype == "cc":
  1601. # 抄送不阻断,继续往下
  1602. cur = next_node(cur)
  1603. continue
  1604. if not tasks:
  1605. raise OaEngineError("审批节点未生成任务")
  1606. nested = _maybe_auto_pass_initiator(
  1607. db,
  1608. inst=inst,
  1609. ver=ver,
  1610. tasks=tasks,
  1611. user_id=user_id,
  1612. )
  1613. created_ids.extend(nested or [])
  1614. return created_ids
  1615. # 未知类型跳过子节点
  1616. cur = next_node(cur)
  1617. # 无结束也无待办:异常结束
  1618. if inst.status == "running":
  1619. raise OaEngineError("流程推进异常:未到达结束且无待办任务")
  1620. return created_ids
  1621. def start_instance(
  1622. db: Session,
  1623. *,
  1624. tenant_no: str,
  1625. app_id: str,
  1626. initiator_user_id: str,
  1627. initiator_dept_id: Optional[str] = None,
  1628. form_data: Optional[Dict[str, Any]] = None,
  1629. title: Optional[str] = None,
  1630. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  1631. related_instance_ids: Optional[List[str]] = None,
  1632. source_instance_id: Optional[str] = None,
  1633. ) -> Dict[str, Any]:
  1634. # source_instance_id 保留入参兼容,不再写入关联(复制开新单不挂旧单)
  1635. _ = source_instance_id
  1636. app = oa_crud.get_app(db, app_id, tenant_no)
  1637. if not app or app.status != "1":
  1638. raise OaEngineError("应用不存在或已停用")
  1639. _check_initiator_scope(app, initiator_user_id)
  1640. ver = oa_crud._find_latest_published(db, app_id, tenant_no)
  1641. if not ver:
  1642. raise OaEngineError("应用尚未发布,无法发起")
  1643. schema = _loads(ver.form_schema_json, {})
  1644. data = dict(form_data or {})
  1645. try:
  1646. data = apply_formulas_and_linkages(schema, data)
  1647. except FormulaError as e:
  1648. raise OaEngineError(f"公式计算失败: {e}") from e
  1649. from app.services.oa_leave_hours import apply_leave_kit_hours, validate_leave_kit_form_values
  1650. from app.services.oa_trip_days import apply_trip_kit_days, validate_trip_kit_form_values
  1651. from app.services.oa_overtime_hours import (
  1652. apply_overtime_kit_hours,
  1653. validate_overtime_kit_form_values,
  1654. )
  1655. from app.services.cn_holiday import is_rest_day as cn_is_rest_day
  1656. data = apply_leave_kit_hours(schema, data)
  1657. leave_errs = validate_leave_kit_form_values(schema, data)
  1658. if leave_errs:
  1659. raise OaEngineError(leave_errs[0])
  1660. data = apply_trip_kit_days(schema, data)
  1661. trip_errs = validate_trip_kit_form_values(schema, data)
  1662. if trip_errs:
  1663. raise OaEngineError(trip_errs[0])
  1664. def _ot_rest(ymd: str) -> bool:
  1665. from datetime import datetime as _dt
  1666. d = _dt.strptime(ymd, "%Y-%m-%d").date()
  1667. return cn_is_rest_day(db, d)
  1668. data = apply_overtime_kit_hours(schema, data, _ot_rest)
  1669. ot_errs = validate_overtime_kit_form_values(schema, data)
  1670. if ot_errs:
  1671. raise OaEngineError(ot_errs[0])
  1672. user = (
  1673. db.query(SysUser)
  1674. .filter(SysUser.id == initiator_user_id, SysUser.del_flag == 0)
  1675. .first()
  1676. )
  1677. dept_id = (initiator_dept_id or (user.dept_id if user else "") or "").strip() or None
  1678. from app.services.oa_owner_fields import apply_owner_field_defaults
  1679. data = apply_owner_field_defaults(
  1680. schema,
  1681. data,
  1682. user_id=initiator_user_id,
  1683. user_name=(user.nick_name if user else "") or "",
  1684. dept_id=dept_id,
  1685. dept_name=_dept_name(db, dept_id, tenant_no=tenant_no) if dept_id else None,
  1686. )
  1687. from app.services.oa_dept_select import validate_dept_form_values
  1688. from app.services.oa_money_field import validate_money_form_values
  1689. from app.services.oa_person_select import validate_person_form_values
  1690. from app.services.oa_post_select import validate_post_form_values
  1691. from app.services.oa_receive_account import validate_receive_account_form_values
  1692. dept_errs = validate_dept_form_values(schema, data)
  1693. if dept_errs:
  1694. raise OaEngineError(dept_errs[0])
  1695. money_errs = validate_money_form_values(schema, data)
  1696. if money_errs:
  1697. raise OaEngineError(money_errs[0])
  1698. person_errs = validate_person_form_values(schema, data)
  1699. if person_errs:
  1700. raise OaEngineError(person_errs[0])
  1701. post_errs = validate_post_form_values(schema, data)
  1702. if post_errs:
  1703. raise OaEngineError(post_errs[0])
  1704. recv_errs = validate_receive_account_form_values(schema, data)
  1705. if recv_errs:
  1706. raise OaEngineError(recv_errs[0])
  1707. now = datetime.now()
  1708. title_text = (title or app.app_name or "").strip()
  1709. normalized_select = _normalize_initiator_select_by_node(initiator_select_by_node)
  1710. inst = OaInstance(
  1711. id=generate_uuid(),
  1712. app_id=app_id,
  1713. app_version_id=ver.id,
  1714. title=title_text[:200],
  1715. initiator_user_id=initiator_user_id,
  1716. initiator_dept_id=dept_id,
  1717. form_data_json=_dumps(data),
  1718. initiator_select_json=_dumps(normalized_select),
  1719. status="running",
  1720. source_instance_id=None,
  1721. current_round=1,
  1722. tenant_no=tenant_no,
  1723. order_num=0,
  1724. remark=None,
  1725. create_by=initiator_user_id,
  1726. create_dept_id=dept_id or "",
  1727. create_time=now,
  1728. update_by=initiator_user_id,
  1729. update_time=now,
  1730. del_flag=0,
  1731. )
  1732. db.add(inst)
  1733. from app.services.oa_related_approval import (
  1734. assert_linkable_instance,
  1735. merge_relation_targets,
  1736. )
  1737. targets = merge_relation_targets(schema, data, related_instance_ids)
  1738. for field_key, to_id in targets:
  1739. target = (
  1740. db.query(OaInstance)
  1741. .filter(
  1742. OaInstance.id == to_id,
  1743. OaInstance.tenant_no == tenant_no,
  1744. OaInstance.del_flag == 0,
  1745. )
  1746. .first()
  1747. )
  1748. assert_linkable_instance(
  1749. target, user_id=initiator_user_id, tenant_no=tenant_no, db=db
  1750. )
  1751. db.add(
  1752. OaRelation(
  1753. id=generate_uuid(),
  1754. from_instance_id=inst.id,
  1755. to_instance_id=to_id,
  1756. field_key=field_key,
  1757. tenant_no=tenant_no,
  1758. order_num=0,
  1759. remark=None,
  1760. create_by=initiator_user_id,
  1761. create_dept_id=dept_id or "",
  1762. create_time=now,
  1763. update_by=initiator_user_id,
  1764. update_time=now,
  1765. del_flag=0,
  1766. )
  1767. )
  1768. _add_instance_event(
  1769. db,
  1770. inst=inst,
  1771. event_type="submit",
  1772. actor_user_id=initiator_user_id,
  1773. round_no=1,
  1774. )
  1775. created = advance_from(
  1776. db,
  1777. inst=inst,
  1778. ver=ver,
  1779. from_node=None,
  1780. user_id=initiator_user_id,
  1781. initiator_select_by_node=normalized_select,
  1782. )
  1783. db.commit()
  1784. from app.services.oa_wechat_notify import schedule_oa_task_notifies
  1785. schedule_oa_task_notifies(created or [])
  1786. db.refresh(inst)
  1787. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  1788. def _get_instance(db: Session, instance_id: str, tenant_no: str) -> OaInstance:
  1789. inst = (
  1790. db.query(OaInstance)
  1791. .filter(OaInstance.id == instance_id, OaInstance.tenant_no == tenant_no, OaInstance.del_flag == 0)
  1792. .first()
  1793. )
  1794. if not inst:
  1795. raise OaEngineError("实例不存在")
  1796. return inst
  1797. def get_instance_detail(
  1798. db: Session, instance_id: str, *, tenant_no: str, viewer_user_id: str = ""
  1799. ) -> Dict[str, Any]:
  1800. inst = _get_instance(db, instance_id, tenant_no)
  1801. app = oa_crud.get_app(db, inst.app_id, tenant_no)
  1802. ver = (
  1803. db.query(OaAppVersion)
  1804. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  1805. .first()
  1806. )
  1807. tasks = (
  1808. db.query(OaTask)
  1809. .filter(OaTask.instance_id == instance_id, OaTask.del_flag == 0)
  1810. .all()
  1811. )
  1812. flow_root = None
  1813. if ver:
  1814. try:
  1815. flow_root = _flow_root(_loads(ver.flow_tree_json, {}))
  1816. except OaEngineError:
  1817. flow_root = None
  1818. tasks = _sort_tasks_for_detail(tasks, flow_root=flow_root)
  1819. rels = (
  1820. db.query(OaRelation)
  1821. .filter(OaRelation.from_instance_id == instance_id, OaRelation.del_flag == 0)
  1822. .all()
  1823. )
  1824. name_map = _user_name_map(
  1825. db,
  1826. [t.assignee_user_id for t in tasks if t.assignee_user_id]
  1827. + ([inst.initiator_user_id] if inst.initiator_user_id else []),
  1828. )
  1829. data = _instance_to_dict(inst, app_name=app.app_name if app else "")
  1830. data["initiatorUserName"] = name_map.get(inst.initiator_user_id or "", inst.initiator_user_id or "")
  1831. data["initiatorDeptName"] = _dept_name(
  1832. db, inst.initiator_dept_id, tenant_no=tenant_no
  1833. )
  1834. data["tasks"] = [
  1835. _task_to_dict(t, assignee_user_name=name_map.get(t.assignee_user_id or "", ""))
  1836. for t in tasks
  1837. ]
  1838. data["relatedInstanceIds"] = [r.to_instance_id for r in rels]
  1839. data["formSchemaJson"] = _loads(ver.form_schema_json, {}) if ver else {}
  1840. adv = _advanced(ver) if ver else dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  1841. data["advancedSettingsJson"] = adv
  1842. data["allowAddSign"] = bool(adv.get("allowAddSign", True))
  1843. data["allowReturn"] = bool(adv.get("allowReturn", True))
  1844. events = (
  1845. db.query(OaInstanceEvent)
  1846. .filter(OaInstanceEvent.instance_id == instance_id, OaInstanceEvent.del_flag == 0)
  1847. .order_by(OaInstanceEvent.create_time.asc())
  1848. .all()
  1849. )
  1850. event_actors = [e.actor_user_id for e in events if e.actor_user_id]
  1851. if event_actors:
  1852. name_map.update(_user_name_map(db, event_actors))
  1853. data["progress"] = build_progress_items(
  1854. inst=inst,
  1855. flow_root=flow_root,
  1856. tasks=tasks,
  1857. name_map=name_map,
  1858. events=events,
  1859. db=db,
  1860. advanced=adv,
  1861. )
  1862. # 不再暴露旧单/重提单关联跳转
  1863. data["sourceInstanceId"] = ""
  1864. data["resubmittedInstanceId"] = ""
  1865. from app.services import oa_instance_comment as oa_comment
  1866. data["comments"] = oa_comment.list_comments(
  1867. db,
  1868. instance_id=instance_id,
  1869. tenant_no=tenant_no,
  1870. viewer_user_id=viewer_user_id or "",
  1871. )
  1872. return data
  1873. def _normalize_cc_read_status(raw: Optional[str]) -> str:
  1874. v = (raw or "").strip().lower() or "unread"
  1875. if v not in ("unread", "read", "all"):
  1876. raise OaEngineError("readStatus 仅支持 unread、read、all")
  1877. return v
  1878. def _apply_cc_task_read(
  1879. db: Session,
  1880. *,
  1881. task: OaTask,
  1882. user_id: str,
  1883. now: datetime,
  1884. ) -> bool:
  1885. """将抄送任务标为已读。返回是否发生了写入。幂等时返回 False。"""
  1886. if int(getattr(task, "is_read", 0) or 0) == 1:
  1887. return False
  1888. task.is_read = 1
  1889. task.read_time = now
  1890. task.update_by = user_id
  1891. task.update_time = now
  1892. db.add(task)
  1893. return True
  1894. def count_cc_unread(db: Session, *, tenant_no: str, user_id: str) -> int:
  1895. return (
  1896. db.query(OaTask)
  1897. .filter(
  1898. OaTask.tenant_no == tenant_no,
  1899. OaTask.del_flag == 0,
  1900. OaTask.assignee_user_id == user_id,
  1901. OaTask.task_type == "cc",
  1902. OaTask.is_read == 0,
  1903. )
  1904. .count()
  1905. )
  1906. def count_pending_tasks(db: Session, *, tenant_no: str, user_id: str) -> int:
  1907. return (
  1908. db.query(OaTask)
  1909. .filter(
  1910. OaTask.tenant_no == tenant_no,
  1911. OaTask.del_flag == 0,
  1912. OaTask.assignee_user_id == user_id,
  1913. OaTask.task_type == "approval",
  1914. OaTask.status == "pending",
  1915. )
  1916. .count()
  1917. )
  1918. def mark_cc_task_read(
  1919. db: Session, *, tenant_no: str, user_id: str, task_id: str
  1920. ) -> Dict[str, Any]:
  1921. task = (
  1922. db.query(OaTask)
  1923. .filter(
  1924. OaTask.id == task_id,
  1925. OaTask.tenant_no == tenant_no,
  1926. OaTask.del_flag == 0,
  1927. )
  1928. .first()
  1929. )
  1930. if not task or task.task_type != "cc" or task.assignee_user_id != user_id:
  1931. raise OaEngineError("抄送任务不存在或无权操作")
  1932. now = datetime.now()
  1933. _apply_cc_task_read(db, task=task, user_id=user_id, now=now)
  1934. db.commit()
  1935. db.refresh(task)
  1936. return _task_to_dict(task)
  1937. def mark_cc_tasks_read_batch(
  1938. db: Session, *, tenant_no: str, user_id: str, ids: List[str]
  1939. ) -> Dict[str, Any]:
  1940. id_list = [x.strip() for x in (ids or []) if (x or "").strip()]
  1941. if not id_list:
  1942. return {"updated": 0}
  1943. rows = (
  1944. db.query(OaTask)
  1945. .filter(
  1946. OaTask.tenant_no == tenant_no,
  1947. OaTask.del_flag == 0,
  1948. OaTask.assignee_user_id == user_id,
  1949. OaTask.task_type == "cc",
  1950. OaTask.id.in_(id_list),
  1951. )
  1952. .all()
  1953. )
  1954. now = datetime.now()
  1955. updated = 0
  1956. for t in rows:
  1957. if _apply_cc_task_read(db, task=t, user_id=user_id, now=now):
  1958. updated += 1
  1959. db.commit()
  1960. return {"updated": updated}
  1961. _INSTANCE_STATUS_FILTER_VALUES = frozenset(
  1962. {"running", "completed", "rejected", "returned", "cancelled"}
  1963. )
  1964. _FINISH_STATUSES = frozenset({"completed", "rejected", "cancelled"})
  1965. def _parse_day_start(s: Optional[str]) -> Optional[datetime]:
  1966. raw = (s or "").strip()
  1967. if not raw:
  1968. return None
  1969. try:
  1970. d = datetime.strptime(raw[:10], "%Y-%m-%d")
  1971. except ValueError:
  1972. return None
  1973. return d.replace(hour=0, minute=0, second=0, microsecond=0)
  1974. def _parse_day_end(s: Optional[str]) -> Optional[datetime]:
  1975. raw = (s or "").strip()
  1976. if not raw:
  1977. return None
  1978. try:
  1979. d = datetime.strptime(raw[:10], "%Y-%m-%d")
  1980. except ValueError:
  1981. return None
  1982. return d.replace(hour=23, minute=59, second=59, microsecond=999999)
  1983. def _apply_instance_list_filters(
  1984. q,
  1985. *,
  1986. app_name: Optional[str] = None,
  1987. initiator_name: Optional[str] = None,
  1988. keyword: Optional[str] = None,
  1989. apply_time_from: Optional[str] = None,
  1990. apply_time_to: Optional[str] = None,
  1991. instance_status: Optional[str] = None,
  1992. joined_app: bool = False,
  1993. joined_initiator: bool = False,
  1994. ):
  1995. """在已包含 OaInstance 的 query 上叠加列表筛选。返回 (query, joined_app, joined_initiator)。"""
  1996. combined = (keyword or "").strip()
  1997. if combined:
  1998. if not joined_app:
  1999. q = q.outerjoin(
  2000. OaApp,
  2001. (OaApp.id == OaInstance.app_id) & (OaApp.del_flag == 0),
  2002. )
  2003. joined_app = True
  2004. if not joined_initiator:
  2005. q = q.outerjoin(
  2006. SysUser,
  2007. (SysUser.id == OaInstance.initiator_user_id) & (SysUser.del_flag == 0),
  2008. )
  2009. joined_initiator = True
  2010. like = f"%{combined}%"
  2011. q = q.filter(
  2012. or_(
  2013. OaApp.app_name.like(like),
  2014. OaInstance.title.like(like),
  2015. SysUser.nick_name.like(like),
  2016. )
  2017. )
  2018. else:
  2019. kw = (app_name or "").strip()
  2020. if kw:
  2021. if not joined_app:
  2022. q = q.outerjoin(
  2023. OaApp,
  2024. (OaApp.id == OaInstance.app_id) & (OaApp.del_flag == 0),
  2025. )
  2026. joined_app = True
  2027. like = f"%{kw}%"
  2028. q = q.filter(or_(OaApp.app_name.like(like), OaInstance.title.like(like)))
  2029. iname = (initiator_name or "").strip()
  2030. if iname:
  2031. if not joined_initiator:
  2032. q = q.outerjoin(
  2033. SysUser,
  2034. (SysUser.id == OaInstance.initiator_user_id) & (SysUser.del_flag == 0),
  2035. )
  2036. joined_initiator = True
  2037. q = q.filter(SysUser.nick_name.like(f"%{iname}%"))
  2038. t0 = _parse_day_start(apply_time_from)
  2039. if t0 is not None:
  2040. q = q.filter(OaInstance.create_time >= t0)
  2041. t1 = _parse_day_end(apply_time_to)
  2042. if t1 is not None:
  2043. q = q.filter(OaInstance.create_time <= t1)
  2044. st = (instance_status or "").strip()
  2045. if st in _INSTANCE_STATUS_FILTER_VALUES:
  2046. q = q.filter(OaInstance.status == st)
  2047. return q, joined_app, joined_initiator
  2048. def _filter_by_initiator_dept(q, db: Session, *, tenant_no: str, initiator_dept_id: Optional[str]):
  2049. """按发起部门(含下级)过滤;空参数不改 query。"""
  2050. did = (initiator_dept_id or "").strip()
  2051. if not did:
  2052. return q
  2053. from app.core.data_scope import _get_child_dept_ids
  2054. dept_ids = _get_child_dept_ids(db, did, tenant_no)
  2055. if not dept_ids:
  2056. return q.filter(OaInstance.id == "")
  2057. return q.filter(OaInstance.initiator_dept_id.in_(dept_ids))
  2058. def list_instance_history(
  2059. db: Session,
  2060. *,
  2061. tenant_no: str,
  2062. user_id: str,
  2063. can_view_all: bool,
  2064. app_id: str,
  2065. instance_id: Optional[str] = None,
  2066. initiator_name: Optional[str] = None,
  2067. apply_time_from: Optional[str] = None,
  2068. apply_time_to: Optional[str] = None,
  2069. finish_time_from: Optional[str] = None,
  2070. finish_time_to: Optional[str] = None,
  2071. instance_status: Optional[str] = None,
  2072. initiator_dept_id: Optional[str] = None,
  2073. page: int = 1,
  2074. page_size: int = 20,
  2075. ) -> Dict[str, Any]:
  2076. app_id = (app_id or "").strip()
  2077. if not app_id:
  2078. raise OaEngineError("appId 不能为空")
  2079. page = max(1, int(page or 1))
  2080. page_size = min(100, max(1, int(page_size or 20)))
  2081. offset = (page - 1) * page_size
  2082. q = db.query(OaInstance).filter(
  2083. OaInstance.tenant_no == tenant_no,
  2084. OaInstance.del_flag == 0,
  2085. OaInstance.app_id == app_id,
  2086. )
  2087. if not can_view_all:
  2088. q = q.filter(OaInstance.initiator_user_id == user_id)
  2089. initiator_name = None
  2090. q = _filter_by_initiator_dept(
  2091. q, db, tenant_no=tenant_no, initiator_dept_id=initiator_dept_id
  2092. )
  2093. iid = (instance_id or "").strip()
  2094. if iid:
  2095. q = q.filter(OaInstance.id.like(f"%{iid}%"))
  2096. q, _, _ = _apply_instance_list_filters(
  2097. q,
  2098. initiator_name=initiator_name,
  2099. apply_time_from=apply_time_from,
  2100. apply_time_to=apply_time_to,
  2101. instance_status=instance_status,
  2102. )
  2103. ft0 = _parse_day_start(finish_time_from)
  2104. ft1 = _parse_day_end(finish_time_to)
  2105. if ft0 is not None or ft1 is not None:
  2106. q = q.filter(OaInstance.status.in_(tuple(_FINISH_STATUSES)))
  2107. if ft0 is not None:
  2108. q = q.filter(OaInstance.update_time >= ft0)
  2109. if ft1 is not None:
  2110. q = q.filter(OaInstance.update_time <= ft1)
  2111. total = q.count()
  2112. insts = (
  2113. q.order_by(OaInstance.create_time.desc())
  2114. .offset(offset)
  2115. .limit(page_size)
  2116. .all()
  2117. )
  2118. rows = [_instance_to_dict(i) for i in insts]
  2119. return {
  2120. "list": _enrich_list_rows(
  2121. db,
  2122. tenant_no=tenant_no,
  2123. rows=rows,
  2124. instances=insts,
  2125. preview_limit=6,
  2126. ),
  2127. "total": int(total),
  2128. "canViewAll": bool(can_view_all),
  2129. }
  2130. _HISTORY_EXPORT_MAX_ROWS = 5000
  2131. _EXPORT_RESULT_TEXT = {
  2132. "completed": "审批通过",
  2133. "approved": "审批通过",
  2134. "rejected": "审批拒绝",
  2135. "returned": "已打回",
  2136. "cancelled": "已撤销",
  2137. "running": "",
  2138. "pending": "",
  2139. }
  2140. _EXPORT_STATUS_TEXT = {
  2141. "completed": "已结束",
  2142. "approved": "已结束",
  2143. "rejected": "已结束",
  2144. "cancelled": "已结束",
  2145. "returned": "已打回",
  2146. "running": "进行中",
  2147. "pending": "待处理",
  2148. }
  2149. _EXPORT_ACTION_TEXT = {
  2150. "submitted": "提交申请",
  2151. "approved": "同意",
  2152. "rejected": "拒绝",
  2153. "returned": "打回",
  2154. "completed": "同意",
  2155. "pending": "待处理",
  2156. "cancelled": "取消",
  2157. "transferred": "转交",
  2158. "done": "抄送",
  2159. }
  2160. _FIXED_HISTORY_EXPORT_COLUMNS: List[Tuple[str, str]] = [
  2161. ("instanceNo", "审批编号"),
  2162. ("createTime", "创建时间"),
  2163. ("initiatorName", "创建人"),
  2164. ("currentAssignee", "当前负责人"),
  2165. ("approvalResult", "审批结果"),
  2166. ("approvalStatus", "审批状态"),
  2167. ("updateTime", "更新时间"),
  2168. ("finishTime", "完成时间"),
  2169. ("initiatorDept", "创建人部门"),
  2170. ("title", "审批单标题"),
  2171. ("historyApprovers", "历史审批人"),
  2172. ("duration", "耗时(时:分:秒)"),
  2173. ("approvalRecord", "审批记录"),
  2174. ]
  2175. def _format_export_duration(start: Optional[datetime], end: Optional[datetime]) -> str:
  2176. if not start or not end:
  2177. return ""
  2178. delta = end - start
  2179. if delta.total_seconds() < 0:
  2180. return ""
  2181. total = int(delta.total_seconds())
  2182. h, rem = divmod(total, 3600)
  2183. m, s = divmod(rem, 60)
  2184. return f"{h}:{m}:{s}"
  2185. def _export_upload_cell_value(field: Dict[str, Any]) -> str:
  2186. files = field.get("files") or []
  2187. if not isinstance(files, list):
  2188. return str(field.get("value") or "")
  2189. urls: List[str] = []
  2190. for f in files:
  2191. if not isinstance(f, dict):
  2192. continue
  2193. u = str(f.get("url") or "").strip()
  2194. if u:
  2195. urls.append(u)
  2196. if urls:
  2197. return ",".join(urls)
  2198. return str(field.get("value") or "")
  2199. def _export_progress_action(status: str, *, task_type: str = "") -> str:
  2200. st = (status or "").strip()
  2201. if (task_type or "").strip() == "cc" or st == "done":
  2202. return "抄送"
  2203. return _EXPORT_ACTION_TEXT.get(st, st or "")
  2204. def _format_export_progress_record(progress: List[Dict[str, Any]]) -> str:
  2205. lines: List[str] = []
  2206. for item in progress or []:
  2207. kind = (item.get("kind") or "").strip()
  2208. title = (item.get("title") or "").strip()
  2209. ts = (item.get("timestamp") or "").strip()
  2210. task_type = (item.get("taskType") or "").strip()
  2211. if kind == "submit":
  2212. name = (item.get("assigneeUserName") or "").strip()
  2213. if not name:
  2214. continue
  2215. lines.append(f"{name}|提交申请|{ts}|提交申请")
  2216. continue
  2217. people = item.get("people") or []
  2218. if isinstance(people, list) and people:
  2219. for p in people:
  2220. if not isinstance(p, dict):
  2221. continue
  2222. name = (p.get("nickName") or p.get("assigneeUserName") or "").strip()
  2223. if not name:
  2224. continue
  2225. pst = (p.get("status") or "").strip()
  2226. if pst in ("pending", "running", "cancelled") and task_type != "cc":
  2227. continue
  2228. node = title or (item.get("nodeKey") or "").strip() or "-"
  2229. pts = (p.get("timestamp") or ts or "").strip()
  2230. action = _export_progress_action(pst, task_type=task_type)
  2231. comment = (p.get("commentText") or "").strip()
  2232. seg = f"{name}|{node}|{pts}|{action}"
  2233. if comment:
  2234. seg += f"|{comment}"
  2235. lines.append(seg)
  2236. continue
  2237. name = (item.get("assigneeUserName") or "").strip()
  2238. if not name:
  2239. continue
  2240. st = (item.get("status") or "").strip()
  2241. if st in ("pending", "running", "cancelled") and task_type != "cc":
  2242. continue
  2243. node = title or (item.get("nodeKey") or "").strip() or "-"
  2244. action = _export_progress_action(st, task_type=task_type)
  2245. comment = (item.get("commentText") or "").strip()
  2246. seg = f"{name}|{node}|{ts}|{action}"
  2247. if comment:
  2248. seg += f"|{comment}"
  2249. lines.append(seg)
  2250. return ";\r\n".join(lines)
  2251. def _collect_history_approver_names(progress: List[Dict[str, Any]]) -> str:
  2252. names: List[str] = []
  2253. seen = set()
  2254. for item in progress or []:
  2255. if (item.get("kind") or "").strip() == "submit":
  2256. continue
  2257. people = item.get("people") or []
  2258. if isinstance(people, list) and people:
  2259. for p in people:
  2260. if not isinstance(p, dict):
  2261. continue
  2262. st = (p.get("status") or "").strip()
  2263. if st not in ("approved", "completed", "rejected", "returned", "transferred"):
  2264. continue
  2265. name = (p.get("nickName") or p.get("assigneeUserName") or "").strip()
  2266. if name and name not in seen:
  2267. seen.add(name)
  2268. names.append(name)
  2269. continue
  2270. st = (item.get("status") or "").strip()
  2271. if st not in ("approved", "completed", "rejected", "returned", "transferred"):
  2272. continue
  2273. name = (item.get("assigneeUserName") or "").strip()
  2274. if name and name not in seen:
  2275. seen.add(name)
  2276. names.append(name)
  2277. return ",".join(names)
  2278. def _build_history_export_business_columns(schema: Any) -> List[Dict[str, Any]]:
  2279. from app.services.oa_related_approval import LAYOUT_SKIP, _schema_rules
  2280. cols: List[Dict[str, Any]] = []
  2281. for rule in _schema_rules(schema):
  2282. typ = str(rule.get("type") or "")
  2283. if not typ or typ in LAYOUT_SKIP:
  2284. continue
  2285. field = str(rule.get("field") or "").strip()
  2286. if not field:
  2287. continue
  2288. label = str(rule.get("title") or rule.get("label") or field)
  2289. if typ == "relatedApproval":
  2290. cols.append(
  2291. {
  2292. "key": field,
  2293. "label": label,
  2294. "kind": "related",
  2295. "subLabel": "关联标题",
  2296. }
  2297. )
  2298. else:
  2299. cols.append({"key": field, "label": label, "kind": "business"})
  2300. return cols
  2301. def _merge_history_export_business_columns(col_lists: List[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:
  2302. merged: List[Dict[str, Any]] = []
  2303. seen = set()
  2304. for cols in col_lists:
  2305. for c in cols:
  2306. key = str(c.get("key") or "")
  2307. if not key or key in seen:
  2308. continue
  2309. seen.add(key)
  2310. merged.append(dict(c))
  2311. return merged
  2312. def _history_export_query(
  2313. db: Session,
  2314. *,
  2315. tenant_no: str,
  2316. user_id: str,
  2317. can_view_all: bool,
  2318. app_id: str,
  2319. instance_id: Optional[str] = None,
  2320. instance_ids: Optional[List[str]] = None,
  2321. initiator_name: Optional[str] = None,
  2322. apply_time_from: Optional[str] = None,
  2323. apply_time_to: Optional[str] = None,
  2324. finish_time_from: Optional[str] = None,
  2325. finish_time_to: Optional[str] = None,
  2326. instance_status: Optional[str] = None,
  2327. initiator_dept_id: Optional[str] = None,
  2328. ):
  2329. q = db.query(OaInstance).filter(
  2330. OaInstance.tenant_no == tenant_no,
  2331. OaInstance.del_flag == 0,
  2332. OaInstance.app_id == app_id,
  2333. )
  2334. if not can_view_all:
  2335. q = q.filter(OaInstance.initiator_user_id == user_id)
  2336. initiator_name = None
  2337. q = _filter_by_initiator_dept(
  2338. q, db, tenant_no=tenant_no, initiator_dept_id=initiator_dept_id
  2339. )
  2340. clean_ids = [str(x).strip() for x in (instance_ids or []) if str(x).strip()]
  2341. if clean_ids:
  2342. q = q.filter(OaInstance.id.in_(clean_ids))
  2343. else:
  2344. iid = (instance_id or "").strip()
  2345. if iid:
  2346. q = q.filter(OaInstance.id.like(f"%{iid}%"))
  2347. q, _, _ = _apply_instance_list_filters(
  2348. q,
  2349. initiator_name=initiator_name,
  2350. apply_time_from=apply_time_from,
  2351. apply_time_to=apply_time_to,
  2352. instance_status=instance_status,
  2353. )
  2354. ft0 = _parse_day_start(finish_time_from)
  2355. ft1 = _parse_day_end(finish_time_to)
  2356. if ft0 is not None or ft1 is not None:
  2357. q = q.filter(OaInstance.status.in_(tuple(_FINISH_STATUSES)))
  2358. if ft0 is not None:
  2359. q = q.filter(OaInstance.update_time >= ft0)
  2360. if ft1 is not None:
  2361. q = q.filter(OaInstance.update_time <= ft1)
  2362. return q
  2363. def export_instance_history(
  2364. db: Session,
  2365. *,
  2366. tenant_no: str,
  2367. user_id: str,
  2368. can_view_all: bool,
  2369. app_id: str,
  2370. instance_id: Optional[str] = None,
  2371. instance_ids: Optional[List[str]] = None,
  2372. initiator_name: Optional[str] = None,
  2373. apply_time_from: Optional[str] = None,
  2374. apply_time_to: Optional[str] = None,
  2375. finish_time_from: Optional[str] = None,
  2376. finish_time_to: Optional[str] = None,
  2377. instance_status: Optional[str] = None,
  2378. initiator_dept_id: Optional[str] = None,
  2379. ) -> Dict[str, Any]:
  2380. from app.services.oa_related_approval import flatten_form_fields_for_summary
  2381. app_id = (app_id or "").strip()
  2382. if not app_id:
  2383. raise OaEngineError("appId 不能为空")
  2384. app = oa_crud.get_app(db, app_id, tenant_no)
  2385. app_name = (app.app_name or "") if app else ""
  2386. q = _history_export_query(
  2387. db,
  2388. tenant_no=tenant_no,
  2389. user_id=user_id,
  2390. can_view_all=can_view_all,
  2391. app_id=app_id,
  2392. instance_id=instance_id,
  2393. instance_ids=instance_ids,
  2394. initiator_name=initiator_name,
  2395. apply_time_from=apply_time_from,
  2396. apply_time_to=apply_time_to,
  2397. finish_time_from=finish_time_from,
  2398. finish_time_to=finish_time_to,
  2399. instance_status=instance_status,
  2400. initiator_dept_id=initiator_dept_id,
  2401. )
  2402. total = q.count()
  2403. if total > _HISTORY_EXPORT_MAX_ROWS:
  2404. raise OaEngineError(f"导出条数超过上限 {_HISTORY_EXPORT_MAX_ROWS},请缩小筛选范围")
  2405. insts = q.order_by(OaInstance.create_time.desc()).limit(_HISTORY_EXPORT_MAX_ROWS).all()
  2406. if not insts:
  2407. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  2408. schema = _loads(getattr(pub, "form_schema_json", None), {}) if pub else {}
  2409. business_columns = _build_history_export_business_columns(schema)
  2410. return {
  2411. "appName": app_name,
  2412. "businessColumns": business_columns,
  2413. "fixedColumns": [{"key": k, "label": lb} for k, lb in _FIXED_HISTORY_EXPORT_COLUMNS],
  2414. "rows": [],
  2415. "total": 0,
  2416. }
  2417. ver_by_id: Dict[str, OaAppVersion] = {}
  2418. ver_ids = list({i.app_version_id for i in insts if i.app_version_id})
  2419. if ver_ids:
  2420. for v in (
  2421. db.query(OaAppVersion)
  2422. .filter(OaAppVersion.id.in_(ver_ids), OaAppVersion.del_flag == 0)
  2423. .all()
  2424. ):
  2425. ver_by_id[v.id] = v
  2426. pub = oa_crud._find_latest_published(db, app_id, tenant_no)
  2427. pub_schema = _loads(getattr(pub, "form_schema_json", None), {}) if pub else {}
  2428. col_lists = [_build_history_export_business_columns(pub_schema)]
  2429. for inst in insts:
  2430. ver = ver_by_id.get(inst.app_version_id or "")
  2431. schema = _loads(getattr(ver, "form_schema_json", None), {}) if ver else {}
  2432. col_lists.append(_build_history_export_business_columns(schema))
  2433. business_columns = _merge_history_export_business_columns(col_lists)
  2434. inst_ids = [i.id for i in insts]
  2435. all_tasks = (
  2436. db.query(OaTask)
  2437. .filter(OaTask.instance_id.in_(inst_ids), OaTask.del_flag == 0)
  2438. .all()
  2439. )
  2440. tasks_by_inst: Dict[str, List[OaTask]] = {}
  2441. user_ids: List[str] = []
  2442. for t in all_tasks:
  2443. tasks_by_inst.setdefault(t.instance_id, []).append(t)
  2444. if t.assignee_user_id:
  2445. user_ids.append(t.assignee_user_id)
  2446. all_events = (
  2447. db.query(OaInstanceEvent)
  2448. .filter(OaInstanceEvent.instance_id.in_(inst_ids), OaInstanceEvent.del_flag == 0)
  2449. .order_by(OaInstanceEvent.create_time.asc())
  2450. .all()
  2451. )
  2452. events_by_inst: Dict[str, List[OaInstanceEvent]] = {}
  2453. for e in all_events:
  2454. events_by_inst.setdefault(e.instance_id, []).append(e)
  2455. if e.actor_user_id:
  2456. user_ids.append(e.actor_user_id)
  2457. for inst in insts:
  2458. if inst.initiator_user_id:
  2459. user_ids.append(inst.initiator_user_id)
  2460. name_map = _user_name_map(db, user_ids)
  2461. related_ids: List[str] = []
  2462. flat_by_inst: Dict[str, List[Dict[str, Any]]] = {}
  2463. for inst in insts:
  2464. ver = ver_by_id.get(inst.app_version_id or "")
  2465. schema = _loads(getattr(ver, "form_schema_json", None), {}) if ver else {}
  2466. form_data = _loads(inst.form_data_json, {}) or {}
  2467. flat = flatten_form_fields_for_summary(schema, form_data)
  2468. flat_by_inst[inst.id] = flat
  2469. for f in flat:
  2470. for rid in f.get("relatedIds") or []:
  2471. rid_s = str(rid or "").strip()
  2472. if rid_s:
  2473. related_ids.append(rid_s)
  2474. related_title_map: Dict[str, str] = {}
  2475. if related_ids:
  2476. rel_insts = (
  2477. db.query(OaInstance)
  2478. .filter(
  2479. OaInstance.tenant_no == tenant_no,
  2480. OaInstance.del_flag == 0,
  2481. OaInstance.id.in_(list(set(related_ids))),
  2482. )
  2483. .all()
  2484. )
  2485. rel_app_ids = list({r.app_id for r in rel_insts if r.app_id})
  2486. rel_app_map = {}
  2487. if rel_app_ids:
  2488. for a in db.query(OaApp).filter(OaApp.id.in_(rel_app_ids)).all():
  2489. rel_app_map[a.id] = a.app_name or ""
  2490. for r in rel_insts:
  2491. initiator = name_map.get(r.initiator_user_id or "", "")
  2492. related_title_map[r.id] = (
  2493. f"{initiator}提交的{rel_app_map.get(r.app_id, '')}" if initiator else (r.title or r.id)
  2494. )
  2495. pending_by_inst: Dict[str, List[OaTask]] = {}
  2496. for t in all_tasks:
  2497. if (t.task_type or "") == "approval" and (t.status or "") == "pending":
  2498. pending_by_inst.setdefault(t.instance_id, []).append(t)
  2499. rows_out: List[Dict[str, Any]] = []
  2500. for idx, inst in enumerate(insts, start=1):
  2501. ver = ver_by_id.get(inst.app_version_id or "")
  2502. flow_root = None
  2503. if ver:
  2504. try:
  2505. flow_root = _flow_root(_loads(ver.flow_tree_json, {}))
  2506. except OaEngineError:
  2507. flow_root = None
  2508. tasks = _sort_tasks_for_detail(tasks_by_inst.get(inst.id, []), flow_root=flow_root)
  2509. events = events_by_inst.get(inst.id, [])
  2510. adv = _advanced(ver) if ver else dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  2511. progress = build_progress_items(
  2512. inst=inst,
  2513. flow_root=flow_root,
  2514. tasks=tasks,
  2515. name_map=name_map,
  2516. events=events,
  2517. db=db,
  2518. advanced=adv,
  2519. )
  2520. summary = _instance_progress_summary(
  2521. inst,
  2522. app_name=app_name,
  2523. initiator_user_name=name_map.get(inst.initiator_user_id or "", ""),
  2524. pending_approval_tasks=pending_by_inst.get(inst.id, []),
  2525. name_map=name_map,
  2526. )
  2527. st = (inst.status or "").strip()
  2528. finish_time = (
  2529. inst.update_time.strftime("%Y-%m-%d %H:%M:%S")
  2530. if st in _FINISH_STATUSES and inst.update_time
  2531. else ""
  2532. )
  2533. duration_end = inst.update_time if st in _FINISH_STATUSES else None
  2534. business: Dict[str, Any] = {}
  2535. flat_map = {str(f.get("fieldKey") or ""): f for f in flat_by_inst.get(inst.id, [])}
  2536. for col in business_columns:
  2537. key = str(col.get("key") or "")
  2538. field = flat_map.get(key) or {}
  2539. if col.get("kind") == "related":
  2540. ids = field.get("relatedIds") or []
  2541. business[key] = f"已关联 {len(ids)} 条" if ids else ""
  2542. titles = [related_title_map.get(str(i), str(i)) for i in ids]
  2543. business[f"{key}__titles"] = "、".join(t for t in titles if t)
  2544. elif field.get("fieldType") in ("upload", "fcUpload", "image", "oaAttachment"):
  2545. business[key] = _export_upload_cell_value(field)
  2546. else:
  2547. business[key] = str(field.get("value") or "")
  2548. rows_out.append(
  2549. {
  2550. "index": idx,
  2551. "id": inst.id,
  2552. "business": business,
  2553. "fixed": {
  2554. "instanceNo": inst.id,
  2555. "createTime": summary.get("applyTime") or "",
  2556. "initiatorName": summary.get("initiatorUserName") or "",
  2557. "currentAssignee": summary.get("currentApproverNames") or "-",
  2558. "approvalResult": _EXPORT_RESULT_TEXT.get(st, st),
  2559. "approvalStatus": _EXPORT_STATUS_TEXT.get(st, st),
  2560. "updateTime": inst.update_time.strftime("%Y-%m-%d %H:%M:%S")
  2561. if inst.update_time
  2562. else "",
  2563. "finishTime": finish_time,
  2564. "initiatorDept": _dept_name(
  2565. db, inst.initiator_dept_id, tenant_no=tenant_no
  2566. ),
  2567. "title": inst.title or "",
  2568. "historyApprovers": _collect_history_approver_names(progress),
  2569. "duration": _format_export_duration(inst.create_time, duration_end),
  2570. "approvalRecord": _format_export_progress_record(progress),
  2571. },
  2572. }
  2573. )
  2574. return {
  2575. "appName": app_name,
  2576. "businessColumns": business_columns,
  2577. "fixedColumns": [{"key": k, "label": lb} for k, lb in _FIXED_HISTORY_EXPORT_COLUMNS],
  2578. "rows": rows_out,
  2579. "total": len(rows_out),
  2580. }
  2581. def list_tasks(
  2582. db: Session,
  2583. *,
  2584. tenant_no: str,
  2585. user_id: str,
  2586. kind: str,
  2587. read_status: Optional[str] = None,
  2588. app_name: Optional[str] = None,
  2589. initiator_name: Optional[str] = None,
  2590. keyword: Optional[str] = None,
  2591. apply_time_from: Optional[str] = None,
  2592. apply_time_to: Optional[str] = None,
  2593. instance_status: Optional[str] = None,
  2594. page: int = 1,
  2595. page_size: int = 20,
  2596. ) -> Dict[str, Any]:
  2597. kind = (kind or "").strip()
  2598. page = max(1, int(page or 1))
  2599. page_size = min(100, max(1, int(page_size or 20)))
  2600. offset = (page - 1) * page_size
  2601. if kind == "mine":
  2602. q = db.query(OaInstance).filter(
  2603. OaInstance.tenant_no == tenant_no,
  2604. OaInstance.del_flag == 0,
  2605. OaInstance.initiator_user_id == user_id,
  2606. )
  2607. q, _, _ = _apply_instance_list_filters(
  2608. q,
  2609. app_name=app_name,
  2610. initiator_name=initiator_name,
  2611. keyword=keyword,
  2612. apply_time_from=apply_time_from,
  2613. apply_time_to=apply_time_to,
  2614. instance_status=instance_status,
  2615. )
  2616. total = q.count()
  2617. insts = (
  2618. q.order_by(OaInstance.create_time.desc())
  2619. .offset(offset)
  2620. .limit(page_size)
  2621. .all()
  2622. )
  2623. rows = [_instance_to_dict(i) for i in insts]
  2624. return {
  2625. "list": _enrich_list_rows(db, tenant_no=tenant_no, rows=rows, instances=insts),
  2626. "total": int(total),
  2627. }
  2628. if kind == "mention":
  2629. from app.services.oa_instance_comment import list_mentioned_instance_ids
  2630. ids = list_mentioned_instance_ids(db, tenant_no=tenant_no, user_id=user_id)
  2631. if not ids:
  2632. return {"list": [], "total": 0}
  2633. q = db.query(OaInstance).filter(
  2634. OaInstance.tenant_no == tenant_no,
  2635. OaInstance.del_flag == 0,
  2636. OaInstance.id.in_(ids),
  2637. )
  2638. q, _, _ = _apply_instance_list_filters(
  2639. q,
  2640. app_name=app_name,
  2641. initiator_name=initiator_name,
  2642. keyword=keyword,
  2643. apply_time_from=apply_time_from,
  2644. apply_time_to=apply_time_to,
  2645. instance_status=instance_status,
  2646. )
  2647. insts = q.all()
  2648. rank = {iid: i for i, iid in enumerate(ids)}
  2649. insts.sort(key=lambda inst: rank.get(inst.id, len(ids)))
  2650. total = len(insts)
  2651. insts = insts[offset : offset + page_size]
  2652. rows = [_instance_to_dict(i) for i in insts]
  2653. return {
  2654. "list": _enrich_list_rows(db, tenant_no=tenant_no, rows=rows, instances=insts),
  2655. "total": int(total),
  2656. }
  2657. if kind == "pending":
  2658. q = db.query(OaTask).filter(
  2659. OaTask.tenant_no == tenant_no,
  2660. OaTask.del_flag == 0,
  2661. OaTask.assignee_user_id == user_id,
  2662. OaTask.task_type == "approval",
  2663. OaTask.status == "pending",
  2664. )
  2665. elif kind == "done":
  2666. q = db.query(OaTask).filter(
  2667. OaTask.tenant_no == tenant_no,
  2668. OaTask.del_flag == 0,
  2669. OaTask.assignee_user_id == user_id,
  2670. OaTask.task_type == "approval",
  2671. OaTask.status.in_(("approved", "rejected", "returned", "transferred")),
  2672. )
  2673. elif kind == "cc":
  2674. q = db.query(OaTask).filter(
  2675. OaTask.tenant_no == tenant_no,
  2676. OaTask.del_flag == 0,
  2677. OaTask.assignee_user_id == user_id,
  2678. OaTask.task_type == "cc",
  2679. )
  2680. rs = _normalize_cc_read_status(read_status)
  2681. if rs == "unread":
  2682. q = q.filter(OaTask.is_read == 0)
  2683. elif rs == "read":
  2684. q = q.filter(OaTask.is_read == 1)
  2685. # all: 不加 is_read 条件
  2686. else:
  2687. raise OaEngineError(f"不支持的列表类型: {kind}")
  2688. need_inst_join = any(
  2689. [
  2690. (keyword or "").strip(),
  2691. (app_name or "").strip(),
  2692. (initiator_name or "").strip(),
  2693. (apply_time_from or "").strip(),
  2694. (apply_time_to or "").strip(),
  2695. (instance_status or "").strip() in _INSTANCE_STATUS_FILTER_VALUES,
  2696. ]
  2697. )
  2698. if need_inst_join:
  2699. q = q.join(
  2700. OaInstance,
  2701. (OaInstance.id == OaTask.instance_id)
  2702. & (OaInstance.tenant_no == tenant_no)
  2703. & (OaInstance.del_flag == 0),
  2704. )
  2705. q, _, _ = _apply_instance_list_filters(
  2706. q,
  2707. app_name=app_name,
  2708. initiator_name=initiator_name,
  2709. keyword=keyword,
  2710. apply_time_from=apply_time_from,
  2711. apply_time_to=apply_time_to,
  2712. instance_status=instance_status,
  2713. )
  2714. total = q.count()
  2715. rows_orm = (
  2716. q.order_by(OaTask.create_time.desc()).offset(offset).limit(page_size).all()
  2717. )
  2718. rows = [_task_to_dict(t) for t in rows_orm]
  2719. inst_ids = list({t.instance_id for t in rows_orm if t.instance_id})
  2720. insts = (
  2721. db.query(OaInstance)
  2722. .filter(
  2723. OaInstance.tenant_no == tenant_no,
  2724. OaInstance.del_flag == 0,
  2725. OaInstance.id.in_(inst_ids),
  2726. )
  2727. .all()
  2728. if inst_ids
  2729. else []
  2730. )
  2731. return {
  2732. "list": _enrich_list_rows(db, tenant_no=tenant_no, rows=rows, instances=insts),
  2733. "total": int(total),
  2734. }
  2735. def _approve_task_core(
  2736. db: Session,
  2737. *,
  2738. task: OaTask,
  2739. inst: OaInstance,
  2740. ver: OaAppVersion,
  2741. user_id: str,
  2742. comment: Optional[str],
  2743. ) -> List[str]:
  2744. """将 pending 审批任务置为 approved 并按或签/会签决定是否推进。
  2745. 返回 advance_from 新创建的任务 id 列表;会签未齐、未推进时返回空列表。
  2746. 调用方负责 commit(若需要)。
  2747. """
  2748. now = datetime.now()
  2749. task.comment_text = (comment or "").strip() or None
  2750. task.status = "approved"
  2751. task.update_by = user_id
  2752. task.update_time = now
  2753. db.add(task)
  2754. # Session 默认 autoflush=False:不先 flush 时,后续按 status=pending 的查询仍会命中本任务,
  2755. # 或签「取消同节点其余待办」会把本人已同意覆盖成 done。
  2756. db.flush()
  2757. sign_mode = (task.sign_mode or "or").strip() or "or"
  2758. pending_same = (
  2759. db.query(OaTask)
  2760. .filter(
  2761. OaTask.instance_id == inst.id,
  2762. OaTask.node_key == task.node_key,
  2763. OaTask.task_type == "approval",
  2764. OaTask.id != task.id,
  2765. OaTask.status == "pending",
  2766. OaTask.del_flag == 0,
  2767. )
  2768. .count()
  2769. )
  2770. if sign_mode == "and" and pending_same > 0:
  2771. return []
  2772. if sign_mode != "and":
  2773. for s in (
  2774. db.query(OaTask)
  2775. .filter(
  2776. OaTask.instance_id == inst.id,
  2777. OaTask.node_key == task.node_key,
  2778. OaTask.id != task.id,
  2779. OaTask.status == "pending",
  2780. OaTask.del_flag == 0,
  2781. )
  2782. .all()
  2783. ):
  2784. s.status = "done"
  2785. s.update_by = user_id
  2786. s.update_time = now
  2787. db.add(s)
  2788. root = _flow_root(_loads(ver.flow_tree_json, {}))
  2789. node = _find_node(root, task.node_key or "")
  2790. if not node:
  2791. raise OaEngineError("找不到对应流程节点")
  2792. return advance_from(
  2793. db,
  2794. inst=inst,
  2795. ver=ver,
  2796. from_node=node,
  2797. user_id=user_id,
  2798. initiator_select_by_node=_load_initiator_select_by_node(inst),
  2799. )
  2800. def _maybe_auto_pass_initiator(
  2801. db: Session,
  2802. *,
  2803. inst: OaInstance,
  2804. ver: OaAppVersion,
  2805. tasks: List[OaTask],
  2806. user_id: Optional[str],
  2807. ) -> List[str]:
  2808. _ = user_id
  2809. advanced = _advanced(ver)
  2810. if not advanced.get("autoPassWhenApproverIsInitiator"):
  2811. return []
  2812. if inst.status != "running":
  2813. return []
  2814. initiator = (inst.initiator_user_id or "").strip()
  2815. if not initiator:
  2816. return []
  2817. self_task = None
  2818. for t in tasks:
  2819. if (
  2820. t.task_type == "approval"
  2821. and t.status == "pending"
  2822. and (t.assignee_user_id or "") == initiator
  2823. ):
  2824. self_task = t
  2825. break
  2826. if not self_task:
  2827. return []
  2828. return _approve_task_core(
  2829. db,
  2830. task=self_task,
  2831. inst=inst,
  2832. ver=ver,
  2833. user_id=initiator,
  2834. comment=_AUTO_PASS_COMMENT,
  2835. )
  2836. def complete_task(
  2837. db: Session,
  2838. task_id: str,
  2839. *,
  2840. tenant_no: str,
  2841. user_id: str,
  2842. action: str,
  2843. comment: Optional[str] = None,
  2844. ) -> Dict[str, Any]:
  2845. action = (action or "").strip()
  2846. if action not in ("approve", "reject"):
  2847. raise OaEngineError("不支持的操作")
  2848. task = (
  2849. db.query(OaTask)
  2850. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  2851. .first()
  2852. )
  2853. if not task:
  2854. raise OaEngineError("任务不存在")
  2855. if task.assignee_user_id != user_id:
  2856. raise OaEngineError("无权处理该任务")
  2857. if task.task_type != "approval" or task.status != "pending":
  2858. raise OaEngineError("任务状态不可处理")
  2859. inst = _get_instance(db, task.instance_id, tenant_no)
  2860. if inst.status != "running":
  2861. raise OaEngineError("实例已结束")
  2862. ver = (
  2863. db.query(OaAppVersion)
  2864. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  2865. .first()
  2866. )
  2867. if not ver:
  2868. raise OaEngineError("流程版本不存在")
  2869. advanced = _advanced(ver)
  2870. if advanced.get("commentRequired") and not (comment or "").strip():
  2871. raise OaEngineError("请填写审批意见")
  2872. if action == "reject":
  2873. now = datetime.now()
  2874. task.comment_text = (comment or "").strip() or None
  2875. task.status = "rejected"
  2876. task.update_by = user_id
  2877. task.update_time = now
  2878. db.add(task)
  2879. db.flush()
  2880. siblings = (
  2881. db.query(OaTask)
  2882. .filter(
  2883. OaTask.instance_id == inst.id,
  2884. OaTask.node_key == task.node_key,
  2885. OaTask.id != task.id,
  2886. OaTask.status == "pending",
  2887. OaTask.del_flag == 0,
  2888. )
  2889. .all()
  2890. )
  2891. for s in siblings:
  2892. s.status = "done"
  2893. s.update_by = user_id
  2894. s.update_time = now
  2895. db.add(s)
  2896. inst.status = "rejected"
  2897. inst.update_by = user_id
  2898. inst.update_time = now
  2899. db.add(inst)
  2900. db.commit()
  2901. from app.services.oa_wechat_notify import schedule_oa_applicant_progress
  2902. schedule_oa_applicant_progress(
  2903. instance_id=inst.id,
  2904. actor_user_id=user_id,
  2905. action="reject",
  2906. task_id=task.id,
  2907. )
  2908. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  2909. created = _approve_task_core(
  2910. db,
  2911. task=task,
  2912. inst=inst,
  2913. ver=ver,
  2914. user_id=user_id,
  2915. comment=comment,
  2916. )
  2917. db.commit()
  2918. from app.services.oa_wechat_notify import (
  2919. schedule_oa_applicant_progress,
  2920. schedule_oa_task_notifies,
  2921. )
  2922. schedule_oa_task_notifies(created or [])
  2923. schedule_oa_applicant_progress(
  2924. instance_id=inst.id,
  2925. actor_user_id=user_id,
  2926. action="approve",
  2927. task_id=task.id,
  2928. )
  2929. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  2930. def add_sign(
  2931. db: Session,
  2932. task_id: str,
  2933. *,
  2934. tenant_no: str,
  2935. user_id: str,
  2936. user_ids: List[str],
  2937. comment: Optional[str] = None,
  2938. ) -> Dict[str, Any]:
  2939. """当前待办处理人加签:为同节点新增待办审批人。"""
  2940. task = (
  2941. db.query(OaTask)
  2942. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  2943. .first()
  2944. )
  2945. if not task:
  2946. raise OaEngineError("任务不存在")
  2947. if task.assignee_user_id != user_id:
  2948. raise OaEngineError("无权加签该任务")
  2949. if task.task_type != "approval" or task.status != "pending":
  2950. raise OaEngineError("仅待处理的审批任务可加签")
  2951. inst = _get_instance(db, task.instance_id, tenant_no)
  2952. if inst.status != "running":
  2953. raise OaEngineError("实例已结束")
  2954. ver = (
  2955. db.query(OaAppVersion)
  2956. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  2957. .first()
  2958. )
  2959. if not ver:
  2960. raise OaEngineError("流程版本不存在")
  2961. advanced = _advanced(ver)
  2962. if not advanced.get("allowAddSign", True):
  2963. raise OaEngineError("该应用不允许加签")
  2964. ids = []
  2965. seen = set()
  2966. for uid in user_ids or []:
  2967. uid = (uid or "").strip()
  2968. if not uid or uid in seen:
  2969. continue
  2970. seen.add(uid)
  2971. ids.append(uid)
  2972. if not ids:
  2973. raise OaEngineError("请选择加签人")
  2974. existing = {
  2975. r.assignee_user_id
  2976. for r in db.query(OaTask)
  2977. .filter(
  2978. OaTask.instance_id == inst.id,
  2979. OaTask.node_key == task.node_key,
  2980. OaTask.del_flag == 0,
  2981. OaTask.status == "pending",
  2982. )
  2983. .all()
  2984. }
  2985. now = datetime.now()
  2986. created_ids: List[str] = []
  2987. next_order = _next_task_order_num(db, inst.id)
  2988. for uid in ids:
  2989. if uid in existing:
  2990. continue
  2991. # 校验用户有效
  2992. u = (
  2993. db.query(SysUser)
  2994. .filter(
  2995. SysUser.id == uid,
  2996. SysUser.tenant_no == tenant_no,
  2997. SysUser.del_flag == 0,
  2998. SysUser.status == "1",
  2999. )
  3000. .first()
  3001. )
  3002. if not u:
  3003. raise OaEngineError(f"加签用户无效:{uid}")
  3004. new_id = generate_uuid()
  3005. db.add(
  3006. OaTask(
  3007. id=new_id,
  3008. instance_id=inst.id,
  3009. node_key=task.node_key,
  3010. node_name=task.node_name,
  3011. task_type="approval",
  3012. assignee_user_id=uid,
  3013. status="pending",
  3014. comment_text=None,
  3015. resolve_source="add_sign",
  3016. sign_mode=task.sign_mode or "or",
  3017. round_no=int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1),
  3018. tenant_no=tenant_no,
  3019. order_num=next_order,
  3020. remark=(comment or "").strip() or None,
  3021. create_by=user_id,
  3022. create_dept_id=inst.initiator_dept_id or "",
  3023. create_time=now,
  3024. update_by=user_id,
  3025. update_time=now,
  3026. del_flag=0,
  3027. )
  3028. )
  3029. next_order += 1
  3030. created_ids.append(new_id)
  3031. if not created_ids:
  3032. raise OaEngineError("所选用户已在当前节点待办中")
  3033. # 加签后默认按会签语义收口更稳妥:保留原 sign_mode;若原或签则一人通过仍可结束
  3034. if comment:
  3035. task.comment_text = ((task.comment_text or "") + f"\n[加签说明] {comment}").strip()
  3036. task.update_by = user_id
  3037. task.update_time = now
  3038. db.add(task)
  3039. db.commit()
  3040. from app.services.oa_wechat_notify import (
  3041. schedule_oa_applicant_progress,
  3042. schedule_oa_task_notifies,
  3043. )
  3044. schedule_oa_task_notifies(created_ids)
  3045. schedule_oa_applicant_progress(
  3046. instance_id=inst.id,
  3047. actor_user_id=user_id,
  3048. action="add_sign",
  3049. task_id=task.id,
  3050. )
  3051. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  3052. def transfer_task(
  3053. db: Session,
  3054. task_id: str,
  3055. *,
  3056. tenant_no: str,
  3057. user_id: str,
  3058. target_user_id: str,
  3059. comment: Optional[str] = None,
  3060. ) -> Dict[str, Any]:
  3061. """当前待办处理人转交:结束本人待办并为同节点目标用户新建 pending 任务。"""
  3062. task = (
  3063. db.query(OaTask)
  3064. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  3065. .first()
  3066. )
  3067. if not task:
  3068. raise OaEngineError("任务不存在")
  3069. if task.assignee_user_id != user_id:
  3070. raise OaEngineError("无权转交该任务")
  3071. if task.task_type != "approval" or task.status != "pending":
  3072. raise OaEngineError("仅待处理的审批任务可转交")
  3073. inst = _get_instance(db, task.instance_id, tenant_no)
  3074. if inst.status != "running":
  3075. raise OaEngineError("实例已结束")
  3076. target = (target_user_id or "").strip()
  3077. if not target:
  3078. raise OaEngineError("请选择转交人")
  3079. if target == user_id:
  3080. raise OaEngineError("不能转交给自己")
  3081. u = (
  3082. db.query(SysUser)
  3083. .filter(
  3084. SysUser.id == target,
  3085. SysUser.tenant_no == tenant_no,
  3086. SysUser.del_flag == 0,
  3087. SysUser.status == "1",
  3088. )
  3089. .first()
  3090. )
  3091. if not u:
  3092. raise OaEngineError(f"转交用户无效:{target}")
  3093. existing = {
  3094. r.assignee_user_id
  3095. for r in db.query(OaTask)
  3096. .filter(
  3097. OaTask.instance_id == inst.id,
  3098. OaTask.node_key == task.node_key,
  3099. OaTask.del_flag == 0,
  3100. OaTask.status == "pending",
  3101. )
  3102. .all()
  3103. }
  3104. if target in existing:
  3105. raise OaEngineError("该用户已在当前节点待办中")
  3106. now = datetime.now()
  3107. comment_text = (comment or "").strip() or None
  3108. round_no = int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1)
  3109. task.status = "transferred"
  3110. task.comment_text = comment_text
  3111. task.update_by = user_id
  3112. task.update_time = now
  3113. db.add(task)
  3114. next_order = _next_task_order_num(db, inst.id)
  3115. new_task_id = generate_uuid()
  3116. db.add(
  3117. OaTask(
  3118. id=new_task_id,
  3119. instance_id=inst.id,
  3120. node_key=task.node_key,
  3121. node_name=task.node_name,
  3122. task_type="approval",
  3123. assignee_user_id=target,
  3124. status="pending",
  3125. comment_text=None,
  3126. resolve_source="transfer",
  3127. sign_mode=task.sign_mode or "or",
  3128. round_no=round_no,
  3129. tenant_no=tenant_no,
  3130. order_num=next_order,
  3131. remark=comment_text,
  3132. create_by=user_id,
  3133. create_dept_id=inst.initiator_dept_id or "",
  3134. create_time=now,
  3135. update_by=user_id,
  3136. update_time=now,
  3137. del_flag=0,
  3138. )
  3139. )
  3140. event_comment = comment_text or f"转交给 {target}"
  3141. _add_instance_event(
  3142. db,
  3143. inst=inst,
  3144. event_type="transfer",
  3145. actor_user_id=user_id,
  3146. round_no=round_no,
  3147. comment=event_comment,
  3148. task_id=task.id,
  3149. node_key=task.node_key,
  3150. )
  3151. db.commit()
  3152. from app.services.oa_wechat_notify import (
  3153. schedule_oa_applicant_progress,
  3154. schedule_oa_task_notifies,
  3155. )
  3156. schedule_oa_task_notifies([new_task_id])
  3157. schedule_oa_applicant_progress(
  3158. instance_id=inst.id,
  3159. actor_user_id=user_id,
  3160. action="transfer",
  3161. task_id=task.id,
  3162. )
  3163. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  3164. def return_task(
  3165. db: Session,
  3166. task_id: str,
  3167. *,
  3168. tenant_no: str,
  3169. user_id: str,
  3170. comment: Optional[str] = None,
  3171. ) -> Dict[str, Any]:
  3172. """审批人打回:本单终态 returned;再办须复制表单开新实例。"""
  3173. task = (
  3174. db.query(OaTask)
  3175. .filter(OaTask.id == task_id, OaTask.tenant_no == tenant_no, OaTask.del_flag == 0)
  3176. .first()
  3177. )
  3178. if not task:
  3179. raise OaEngineError("任务不存在")
  3180. if task.assignee_user_id != user_id:
  3181. raise OaEngineError("无权打回该任务")
  3182. if task.task_type != "approval" or task.status != "pending":
  3183. raise OaEngineError("仅待处理的审批任务可打回")
  3184. inst = _get_instance(db, task.instance_id, tenant_no)
  3185. if inst.status != "running":
  3186. raise OaEngineError("仅进行中的审批可打回")
  3187. ver = (
  3188. db.query(OaAppVersion)
  3189. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  3190. .first()
  3191. )
  3192. if not ver:
  3193. raise OaEngineError("流程版本不存在")
  3194. advanced = _advanced(ver)
  3195. if not advanced.get("allowReturn", True):
  3196. raise OaEngineError("该应用不允许打回")
  3197. comment_text = (comment or "").strip()
  3198. if not comment_text:
  3199. raise OaEngineError("打回意见必填")
  3200. now = datetime.now()
  3201. round_no = int(getattr(inst, "current_round", None) or getattr(task, "round_no", None) or 1)
  3202. task.status = "returned"
  3203. task.comment_text = comment_text
  3204. task.update_by = user_id
  3205. task.update_time = now
  3206. db.add(task)
  3207. for t in (
  3208. db.query(OaTask)
  3209. .filter(
  3210. OaTask.instance_id == inst.id,
  3211. OaTask.status == "pending",
  3212. OaTask.del_flag == 0,
  3213. OaTask.id != task.id,
  3214. )
  3215. .all()
  3216. ):
  3217. t.status = "cancelled"
  3218. t.update_by = user_id
  3219. t.update_time = now
  3220. db.add(t)
  3221. inst.status = "returned"
  3222. inst.update_by = user_id
  3223. inst.update_time = now
  3224. db.add(inst)
  3225. _add_instance_event(
  3226. db,
  3227. inst=inst,
  3228. event_type="return",
  3229. actor_user_id=user_id,
  3230. round_no=round_no,
  3231. comment=comment_text,
  3232. task_id=task.id,
  3233. node_key=task.node_key,
  3234. )
  3235. db.commit()
  3236. from app.services.oa_wechat_notify import schedule_oa_applicant_progress
  3237. schedule_oa_applicant_progress(
  3238. instance_id=inst.id,
  3239. actor_user_id=user_id,
  3240. action="return",
  3241. task_id=task.id,
  3242. )
  3243. return get_instance_detail(db, inst.id, tenant_no=tenant_no)
  3244. def resubmit_instance(
  3245. db: Session,
  3246. instance_id: str,
  3247. *,
  3248. tenant_no: str,
  3249. user_id: str,
  3250. form_data: Optional[Dict[str, Any]] = None,
  3251. initiator_select_by_node: Optional[Dict[str, List[str]]] = None,
  3252. ) -> Dict[str, Any]:
  3253. """已废弃:同实例再次提交。请复制表单重新发起新实例。"""
  3254. _ = (db, instance_id, tenant_no, user_id, form_data, initiator_select_by_node)
  3255. raise OaEngineError("同实例再次提交已废弃,请复制表单重新发起")
  3256. def withdraw_instance(
  3257. db: Session, instance_id: str, *, tenant_no: str, user_id: str
  3258. ) -> Dict[str, Any]:
  3259. inst = _get_instance(db, instance_id, tenant_no)
  3260. if inst.initiator_user_id != user_id:
  3261. raise OaEngineError("仅发起人可撤销")
  3262. if inst.status != "running":
  3263. raise OaEngineError("仅运行中的实例可撤销")
  3264. ver = (
  3265. db.query(OaAppVersion)
  3266. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  3267. .first()
  3268. )
  3269. advanced = _advanced(ver) if ver else dict(oa_crud.DEFAULT_ADVANCED_SETTINGS)
  3270. if not advanced.get("allowWithdrawRunning", True):
  3271. raise OaEngineError("该应用不允许撤销进行中的审批")
  3272. now = datetime.now()
  3273. inst.status = "cancelled"
  3274. inst.update_by = user_id
  3275. inst.update_time = now
  3276. db.add(inst)
  3277. for t in (
  3278. db.query(OaTask)
  3279. .filter(OaTask.instance_id == inst.id, OaTask.status == "pending", OaTask.del_flag == 0)
  3280. .all()
  3281. ):
  3282. t.status = "cancelled"
  3283. t.update_by = user_id
  3284. t.update_time = now
  3285. db.add(t)
  3286. _add_instance_event(
  3287. db,
  3288. inst=inst,
  3289. event_type="withdraw",
  3290. actor_user_id=user_id,
  3291. round_no=int(getattr(inst, "current_round", None) or 1),
  3292. )
  3293. db.commit()
  3294. return get_instance_detail(db, inst.id, tenant_no=tenant_no)