oa_related_approval.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. """关联审批单:字段扁平化与 form_data 抽链"""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Optional, Sequence, Tuple
  4. from app.models.models import OaApp, OaAppVersion, OaInstance
  5. from app.services.oa_engine import OaEngineError, _loads
  6. LAYOUT_SKIP = frozenset(
  7. {"fcRow", "fcTable", "col", "row", "elCard", "space", "divider", "html", "title", "text", "tag"}
  8. )
  9. UPLOAD_TYPES = frozenset({"upload", "fcUpload", "image", "oaAttachment"})
  10. LONG_TYPES = frozenset({"textarea", "input"})
  11. def _walk_rules(rules: Any, out: List[dict]) -> None:
  12. if not isinstance(rules, list):
  13. return
  14. for r in rules:
  15. if not isinstance(r, dict):
  16. continue
  17. out.append(r)
  18. children = r.get("children") or (r.get("props") or {}).get("rule") or []
  19. if isinstance(children, list):
  20. _walk_rules(children, out)
  21. def _schema_rules(schema: Any) -> List[dict]:
  22. if isinstance(schema, list):
  23. out: List[dict] = []
  24. _walk_rules(schema, out)
  25. return out
  26. if not isinstance(schema, dict):
  27. return []
  28. out = []
  29. _walk_rules(schema.get("rule") or schema.get("rules") or [], out)
  30. return out
  31. def _extract_upload_urls(raw: Any) -> List[str]:
  32. """Normalize FormCreate upload / 业务附件值为 URL 列表。"""
  33. if raw is None or raw == "" or raw == []:
  34. return []
  35. if isinstance(raw, list):
  36. items: List[Any] = raw
  37. elif isinstance(raw, str):
  38. items = [x.strip() for x in raw.split(",") if x.strip()]
  39. elif isinstance(raw, dict):
  40. items = [raw]
  41. else:
  42. items = [raw]
  43. urls: List[str] = []
  44. for it in items:
  45. if it is None or it == "":
  46. continue
  47. if isinstance(it, dict):
  48. u = it.get("url") or it.get("fileUrl") or ""
  49. resp = it.get("response")
  50. if not u and isinstance(resp, dict):
  51. data = resp.get("data") if isinstance(resp.get("data"), dict) else {}
  52. u = resp.get("url") or resp.get("fileUrl") or data.get("url") or data.get("fileUrl") or ""
  53. u = str(u or "").strip()
  54. if u:
  55. urls.append(u)
  56. continue
  57. s = str(it).strip()
  58. if s:
  59. urls.append(s)
  60. return urls
  61. def _normalize_related_ids(raw: Any) -> List[str]:
  62. """Order-preserving dedupe of related approval instance ids."""
  63. if isinstance(raw, list):
  64. ids = raw
  65. elif raw is None or raw == "":
  66. ids = []
  67. else:
  68. ids = [raw]
  69. seen = set()
  70. out: List[str] = []
  71. for x in ids:
  72. tid = str(x or "").strip()
  73. if not tid or tid in seen:
  74. continue
  75. seen.add(tid)
  76. out.append(tid)
  77. return out
  78. def _format_value(typ: str, raw: Any) -> Tuple[str, bool]:
  79. """returns (text, fullWidth)"""
  80. if typ in UPLOAD_TYPES:
  81. urls = _extract_upload_urls(raw)
  82. if not urls:
  83. return "0 个", False
  84. # 展示附件地址(多条用中文顿号);地址较长默认占满一行
  85. return "、".join(urls), True
  86. if typ == "relatedApproval":
  87. if isinstance(raw, list):
  88. n = len([x for x in raw if str(x).strip()])
  89. elif raw:
  90. n = 1
  91. else:
  92. n = 0
  93. return f"已关联 {n} 条", False
  94. if typ == "dept":
  95. if isinstance(raw, list):
  96. names = []
  97. for x in raw:
  98. if isinstance(x, dict):
  99. n = str(x.get("name") or "").strip()
  100. if n:
  101. names.append(n)
  102. return "、".join(names) if names else "", False
  103. if isinstance(raw, dict):
  104. return str(raw.get("name") or "").strip(), False
  105. return "", False
  106. if isinstance(raw, list):
  107. text = "、".join(str(x) for x in raw if x is not None and str(x) != "")
  108. elif isinstance(raw, dict):
  109. text = str(raw.get("label") or raw.get("value") or raw)
  110. else:
  111. text = "" if raw is None else str(raw)
  112. full = typ in LONG_TYPES and len(text) > 40
  113. return text, full
  114. def flatten_form_fields_for_summary(schema: Any, form_data: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
  115. data = form_data or {}
  116. out: List[Dict[str, Any]] = []
  117. for rule in _schema_rules(schema):
  118. typ = str(rule.get("type") or "")
  119. if not typ or typ in LAYOUT_SKIP:
  120. continue
  121. field = str(rule.get("field") or "").strip()
  122. if not field:
  123. continue
  124. label = str(rule.get("title") or rule.get("label") or field)
  125. raw = data.get(field)
  126. if typ == "relatedApproval":
  127. ids = _normalize_related_ids(raw)
  128. item: Dict[str, Any] = {
  129. "label": label,
  130. "value": f"已关联 {len(ids)} 条",
  131. "relatedIds": ids,
  132. }
  133. out.append(item)
  134. continue
  135. text, full = _format_value(typ, raw)
  136. item = {"label": label, "value": text}
  137. if full:
  138. item["fullWidth"] = True
  139. out.append(item)
  140. return out
  141. def extract_related_approval_links(
  142. schema: Any, form_data: Optional[Dict[str, Any]]
  143. ) -> List[Tuple[str, str]]:
  144. """Ordered unique (field_key, to_instance_id)."""
  145. data = form_data or {}
  146. seen = set()
  147. links: List[Tuple[str, str]] = []
  148. for rule in _schema_rules(schema):
  149. if str(rule.get("type") or "") != "relatedApproval":
  150. continue
  151. field = str(rule.get("field") or "").strip()
  152. if not field:
  153. continue
  154. raw = data.get(field)
  155. ids: Sequence[Any]
  156. if isinstance(raw, list):
  157. ids = raw
  158. elif raw is None or raw == "":
  159. ids = []
  160. else:
  161. ids = [raw]
  162. for x in ids:
  163. tid = str(x or "").strip()
  164. if not tid:
  165. continue
  166. key = (field, tid)
  167. if key in seen:
  168. continue
  169. seen.add(key)
  170. links.append((field, tid))
  171. return links
  172. def merge_relation_targets(
  173. schema: Any,
  174. form_data: Optional[Dict[str, Any]],
  175. legacy_ids: Optional[List[str]] = None,
  176. ) -> List[Tuple[Optional[str], str]]:
  177. """Returns (field_key|None, to_id) — form fields first, then legacy without key."""
  178. links = extract_related_approval_links(schema, form_data)
  179. result: List[Tuple[Optional[str], str]] = [(f, i) for f, i in links]
  180. seen_ids = {i for _, i in links}
  181. for x in legacy_ids or []:
  182. tid = str(x or "").strip()
  183. if not tid or tid in seen_ids:
  184. continue
  185. result.append((None, tid))
  186. seen_ids.add(tid)
  187. return result
  188. def assert_linkable_instance(inst: OaInstance, *, user_id: str, tenant_no: str) -> None:
  189. if not inst or inst.del_flag != 0 or inst.tenant_no != tenant_no:
  190. raise OaEngineError("关联的审批单不存在")
  191. if (inst.initiator_user_id or "") != user_id:
  192. raise OaEngineError("只能关联本人发起的审批单")
  193. if (inst.status or "") != "completed":
  194. raise OaEngineError("只能关联已通过的审批单")
  195. def list_related_candidates(
  196. db,
  197. *,
  198. tenant_no: str,
  199. user_id: str,
  200. keyword: str = "",
  201. page: int = 1,
  202. page_size: int = 20,
  203. ) -> Dict[str, Any]:
  204. q = db.query(OaInstance).filter(
  205. OaInstance.tenant_no == tenant_no,
  206. OaInstance.del_flag == 0,
  207. OaInstance.initiator_user_id == user_id,
  208. OaInstance.status == "completed",
  209. )
  210. kw = (keyword or "").strip()
  211. if kw:
  212. from sqlalchemy import or_
  213. app_ids = [
  214. row[0]
  215. for row in db.query(OaApp.id)
  216. .filter(
  217. OaApp.tenant_no == tenant_no,
  218. OaApp.del_flag == 0,
  219. OaApp.app_name.like(f"%{kw}%"),
  220. )
  221. .all()
  222. ]
  223. clauses = [OaInstance.title.like(f"%{kw}%")]
  224. if app_ids:
  225. clauses.append(OaInstance.app_id.in_(app_ids))
  226. q = q.filter(or_(*clauses))
  227. total = q.count()
  228. page = max(1, int(page or 1))
  229. page_size = min(100, max(1, int(page_size or 20)))
  230. rows = (
  231. q.order_by(OaInstance.create_time.desc())
  232. .offset((page - 1) * page_size)
  233. .limit(page_size)
  234. .all()
  235. )
  236. app_map = {}
  237. ids = list({r.app_id for r in rows if r.app_id})
  238. if ids:
  239. for a in db.query(OaApp).filter(OaApp.id.in_(ids)).all():
  240. app_map[a.id] = a.app_name or ""
  241. items = []
  242. for r in rows:
  243. items.append(
  244. {
  245. "id": r.id,
  246. "appName": app_map.get(r.app_id, ""),
  247. "title": r.title or "",
  248. "applyTime": r.create_time.strftime("%Y-%m-%d %H:%M:%S") if r.create_time else "",
  249. "status": r.status or "",
  250. }
  251. )
  252. return {"list": items, "total": total, "page": page, "pageSize": page_size}
  253. def build_related_summaries(
  254. db,
  255. *,
  256. tenant_no: str,
  257. user_id: str,
  258. ids: List[str],
  259. mode: str = "picker",
  260. ) -> List[Dict[str, Any]]:
  261. mode = (mode or "picker").strip()
  262. out: List[Dict[str, Any]] = []
  263. clean = [str(i).strip() for i in ids if str(i).strip()]
  264. if not clean:
  265. return out
  266. insts = (
  267. db.query(OaInstance)
  268. .filter(
  269. OaInstance.tenant_no == tenant_no,
  270. OaInstance.del_flag == 0,
  271. OaInstance.id.in_(clean),
  272. )
  273. .all()
  274. )
  275. by_id = {i.id: i for i in insts}
  276. for iid in clean:
  277. inst = by_id.get(iid)
  278. if not inst:
  279. out.append(
  280. {
  281. "id": iid,
  282. "unavailable": True,
  283. "appName": "",
  284. "applyTime": "",
  285. "status": "",
  286. "fields": [],
  287. }
  288. )
  289. continue
  290. if mode == "picker":
  291. try:
  292. assert_linkable_instance(inst, user_id=user_id, tenant_no=tenant_no)
  293. except OaEngineError:
  294. out.append(
  295. {
  296. "id": iid,
  297. "unavailable": True,
  298. "appName": "",
  299. "applyTime": "",
  300. "status": "",
  301. "fields": [],
  302. }
  303. )
  304. continue
  305. app = db.query(OaApp).filter(OaApp.id == inst.app_id, OaApp.del_flag == 0).first()
  306. ver = (
  307. db.query(OaAppVersion)
  308. .filter(OaAppVersion.id == inst.app_version_id, OaAppVersion.del_flag == 0)
  309. .first()
  310. )
  311. schema = _loads(ver.form_schema_json, {}) if ver else {}
  312. form_data = _loads(inst.form_data_json, {}) if inst.form_data_json else {}
  313. out.append(
  314. {
  315. "id": inst.id,
  316. "unavailable": False,
  317. "appName": (app.app_name if app else "") or (inst.title or ""),
  318. "applyTime": inst.create_time.strftime("%Y-%m-%d %H:%M:%S") if inst.create_time else "",
  319. "status": inst.status or "",
  320. "fields": flatten_form_fields_for_summary(schema, form_data),
  321. }
  322. )
  323. return out