document_query_service.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. """主案、子方案只读查询、DTO和查看审计。"""
  2. from __future__ import annotations
  3. import json
  4. import logging
  5. from datetime import datetime, timezone
  6. from typing import Any, Mapping
  7. from sqlalchemy import String, and_, cast, func, or_, select
  8. from dms.common.enums import (
  9. AuditAction,
  10. AuditTarget,
  11. DocumentStatus,
  12. DocumentType,
  13. RoleCode,
  14. SecurityLevel,
  15. VisibilityType,
  16. )
  17. from dms.common.errors import (
  18. DocumentViewForbiddenError,
  19. InvalidArgumentError,
  20. MainPlanNotFoundError,
  21. ResourceNotFoundError,
  22. SecurityLevelForbiddenError,
  23. )
  24. from dms.common.pagination import PageRequest, page_result
  25. from dms.common.response import serialize_id
  26. from dms.common.time_range import parse_datetime, parse_updated_range
  27. from dms.database.transaction import transaction
  28. from dms.extensions import db
  29. from dms.models import AttachmentBinding, Category, Document, Permission
  30. from dms.security.auth_context import AuthContext, get_auth_context
  31. from dms.services.audit_service import business_audit
  32. from dms.services.authorization_service import (
  33. PlanAccess,
  34. evaluate_plan_access,
  35. plan_allowed_actions,
  36. )
  37. from dms.services.document_password_service import (
  38. is_view_locked,
  39. protected_actions_of,
  40. view_password_verified,
  41. )
  42. logger = logging.getLogger(__name__)
  43. PLAN_TYPES = (DocumentType.MAIN.value, DocumentType.SUB_PLAN.value)
  44. DOCUMENT_SORTS = {
  45. "documentName": Document.document_name,
  46. "createdAt": Document.created_at,
  47. "updatedAt": Document.updated_at,
  48. "viewCount": Document.view_count,
  49. "downloadCount": Document.download_count,
  50. "sortNo": Document.sort_no,
  51. }
  52. def parse_string_id(value: str, *, field: str = "id") -> int:
  53. if not value.isdecimal() or int(value) <= 0:
  54. raise InvalidArgumentError(f"{field}必须是正整数形式的字符串ID")
  55. return int(value)
  56. def _integer(
  57. params: Mapping[str, str],
  58. name: str,
  59. default: int,
  60. ) -> int:
  61. raw = params.get(name)
  62. if raw is None:
  63. return default
  64. if not raw.isdecimal():
  65. raise InvalidArgumentError(f"{name}必须是正整数")
  66. return int(raw)
  67. def _page(params: Mapping[str, str]) -> PageRequest:
  68. return PageRequest(
  69. page=_integer(params, "page", 1),
  70. page_size=_integer(params, "pageSize", 20),
  71. )
  72. def _enum(value: str | None, enum_type, name: str) -> str | None:
  73. if value is None or value == "":
  74. return None
  75. try:
  76. return enum_type(value).value
  77. except ValueError as exc:
  78. raise InvalidArgumentError(f"{name}不是有效枚举值") from exc
  79. def _date(value: str | None, name: str) -> datetime | None:
  80. return parse_datetime(value, name=name)
  81. def _sort(
  82. params: Mapping[str, str],
  83. *,
  84. allowed: dict[str, Any] = DOCUMENT_SORTS,
  85. default: str = "updatedAt",
  86. ) -> tuple[Any, str]:
  87. sort_by = params.get("sortBy", default)
  88. direction = params.get("sortDirection", "desc").lower()
  89. if sort_by not in allowed:
  90. raise InvalidArgumentError("sortBy不是允许的排序字段")
  91. if direction not in {"asc", "desc"}:
  92. raise InvalidArgumentError("sortDirection必须是asc或desc")
  93. column = allowed[sort_by]
  94. return (column.asc() if direction == "asc" else column.desc()), direction
  95. def _iso(value: datetime) -> str:
  96. return value.replace(tzinfo=timezone.utc).isoformat(timespec="milliseconds").replace(
  97. "+00:00", "Z"
  98. )
  99. def _permission_summary(
  100. access: PlanAccess,
  101. document: Document,
  102. ) -> tuple[dict[str, object], str]:
  103. source = access.source
  104. if source is None:
  105. return {
  106. "organizationCount": 0,
  107. "userCount": 0,
  108. "inheritedFromMainPlan": False,
  109. }, "未配置"
  110. permissions = db.session.scalars(
  111. select(Permission).where(
  112. Permission.document_id == source.id,
  113. Permission.is_deleted.is_(False),
  114. )
  115. ).all()
  116. organization_count = sum(item.subject_type == "ORG" for item in permissions)
  117. user_count = sum(item.subject_type == "USER" for item in permissions)
  118. visibility = VisibilityType(source.visibility_type)
  119. if visibility == VisibilityType.ALL_AUTHENTICATED:
  120. visibility_summary = "全部已登录用户"
  121. else:
  122. names = [item.subject_name for item in permissions if item.can_view]
  123. visibility_summary = "、".join(names) if names else "未配置"
  124. return {
  125. "organizationCount": organization_count,
  126. "userCount": user_count,
  127. "inheritedFromMainPlan": document.document_type
  128. == DocumentType.SUB_PLAN.value,
  129. }, visibility_summary
  130. _SNIPPET_BEFORE = 40
  131. _SNIPPET_AFTER = 80
  132. def _content_snippet(content_text: str | None, keyword: str | None) -> str | None:
  133. """当 keyword 命中正文时,截取包含命中区域的片段。
  134. 前后各保留若干字符作为上下文;若未触达正文首尾则以"……"标识截断。
  135. 未命中或任一参数为空时返回 None。
  136. """
  137. if not content_text or not keyword or not keyword.strip():
  138. return None
  139. kw = keyword.strip()
  140. pos = content_text.lower().find(kw.lower())
  141. if pos < 0:
  142. return None
  143. start = max(pos - _SNIPPET_BEFORE, 0)
  144. end = min(pos + len(kw) + _SNIPPET_AFTER, len(content_text))
  145. snippet = content_text[start:end]
  146. if start > 0:
  147. snippet = "……" + snippet
  148. if end < len(content_text):
  149. snippet += "……"
  150. return snippet
  151. def document_summary(
  152. document: Document,
  153. context: AuthContext,
  154. access: PlanAccess,
  155. keyword: str | None = None,
  156. ) -> dict[str, object]:
  157. # 无权限方案也在列表展示(需求:全员可见列表),但授权名单属敏感信息,
  158. # visibilitySummary 以占位符返回;正文片段同样只在有权限时生成。
  159. if access.allowed:
  160. _, visibility_summary = _permission_summary(access, document)
  161. else:
  162. visibility_summary = "-"
  163. source = access.source or document
  164. view_locked = is_view_locked(document, context)
  165. result: dict[str, object] = {
  166. "id": serialize_id(document.id),
  167. "documentName": document.document_name,
  168. "summary": document.summary,
  169. "description": document.description if access.allowed else None,
  170. "documentType": document.document_type,
  171. "status": document.document_status,
  172. "securityLevel": document.security_level,
  173. "visibilityType": source.visibility_type,
  174. "visibilitySummary": visibility_summary,
  175. "attachmentType": document.attachment_type,
  176. "categoryId": serialize_id(document.category_id),
  177. "categoryName": document.category_name,
  178. "categoryPath": document.category_path,
  179. "organizationId": serialize_id(document.organization_id),
  180. "organizationName": document.organization_name,
  181. "parentDocumentId": serialize_id(document.parent_document_id),
  182. "rootDocumentId": serialize_id(
  183. document.id
  184. if document.document_type == DocumentType.MAIN.value
  185. else document.root_document_id
  186. ),
  187. "tags": document.tags or [],
  188. "fileExtension": document.file_extension,
  189. "childCount": document.child_count,
  190. "attachmentCount": document.attachment_count,
  191. "viewCount": document.view_count,
  192. "downloadCount": document.download_count,
  193. "createdByName": document.created_by_name,
  194. "createdAt": _iso(document.created_at),
  195. "updatedAt": _iso(document.updated_at),
  196. "rowVersion": document.row_version,
  197. "allowedActions": plan_allowed_actions(document, context, access),
  198. "hasPassword": document.password_hash is not None,
  199. "passwordProtectedActions": protected_actions_of(document),
  200. "viewLocked": view_locked,
  201. }
  202. if not view_locked:
  203. snippet = _content_snippet(document.content_text, keyword)
  204. if snippet is not None:
  205. result["contentSnippet"] = snippet
  206. return result
  207. def document_detail(
  208. document: Document,
  209. context: AuthContext,
  210. access: PlanAccess,
  211. ) -> dict[str, object]:
  212. result = document_summary(document, context, access)
  213. permission_summary, _ = _permission_summary(access, document)
  214. verified = view_password_verified(document, context)
  215. result.update(
  216. {
  217. "originalFileName": document.original_file_name,
  218. "mimeType": document.mime_type,
  219. "fileSize": document.file_size,
  220. "fileHash": document.file_hash,
  221. "permissionSummary": permission_summary,
  222. "viewPasswordVerified": verified,
  223. "contentText": document.content_text if verified else None,
  224. }
  225. )
  226. return result
  227. def _require_plan_access(document: Document, context: AuthContext) -> PlanAccess:
  228. access = evaluate_plan_access(document, context)
  229. if access.allowed:
  230. return access
  231. if access.reason == "SECURITY":
  232. raise SecurityLevelForbiddenError()
  233. raise DocumentViewForbiddenError()
  234. def _escape_like(keyword: str) -> str:
  235. return keyword.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
  236. def _title_keyword(statement, keyword: str | None):
  237. """简单关键词:仅模糊匹配标题(document_name)。"""
  238. if not keyword or not keyword.strip():
  239. return statement
  240. pattern = f"%{_escape_like(keyword)}%"
  241. return statement.where(Document.document_name.like(pattern, escape="\\"))
  242. def _security_levels(params: Mapping[str, str]) -> list[str] | None:
  243. """解析 ``securityLevels`` 逗号分隔多选(勾选项内 OR)。"""
  244. raw = params.get("securityLevels")
  245. if raw is None or not raw.strip():
  246. return None
  247. values = [item.strip() for item in raw.split(",") if item.strip()]
  248. if not values:
  249. return None
  250. for item in values:
  251. try:
  252. SecurityLevel(item)
  253. except ValueError as exc:
  254. raise InvalidArgumentError("securityLevels包含无效密级值") from exc
  255. if len(set(values)) != len(values):
  256. raise InvalidArgumentError("securityLevels不允许重复值")
  257. return values
  258. def _advanced_filters(statement, params: Mapping[str, str]):
  259. """高级检索三条件(正文关键词 / 密级多选 / 部门模糊),全部 AND 叠加。"""
  260. content_keyword = params.get("contentKeyword")
  261. if content_keyword and content_keyword.strip():
  262. pattern = f"%{_escape_like(content_keyword)}%"
  263. statement = statement.where(
  264. or_(
  265. Document.content_text.like(pattern, escape="\\"),
  266. Document.search_text.like(pattern, escape="\\"),
  267. )
  268. )
  269. levels = _security_levels(params)
  270. if levels:
  271. statement = statement.where(Document.security_level.in_(levels))
  272. organization_keyword = params.get("organizationKeyword")
  273. if organization_keyword and organization_keyword.strip():
  274. pattern = f"%{_escape_like(organization_keyword)}%"
  275. statement = statement.where(
  276. Document.organization_name.like(pattern, escape="\\")
  277. )
  278. return statement
  279. def _title_contains(document_name: str | None, keyword: str) -> bool:
  280. return keyword.lower() in (document_name or "").lower()
  281. def _child_title_hit_counts(
  282. context: AuthContext,
  283. main_ids: list[int],
  284. keyword: str,
  285. ) -> dict[int, list[int]]:
  286. """统计各主案下标题命中简单关键词的可见子案/附件数量。
  287. - 子案经 ``evaluate_plan_access`` 逐条校验,不可见的命中不计入;
  288. - 附件随挂载主案权限可见(主案本身已通过校验),直接计数;
  289. - 返回 ``{main_id: [子案命中数, 附件命中数]}``。
  290. """
  291. if not main_ids or not keyword.strip():
  292. return {}
  293. pattern = f"%{_escape_like(keyword)}%"
  294. counts: dict[int, list[int]] = {main_id: [0, 0] for main_id in main_ids}
  295. children = db.session.scalars(
  296. select(Document).where(
  297. Document.parent_document_id.in_(main_ids),
  298. Document.document_type == DocumentType.SUB_PLAN.value,
  299. Document.is_deleted.is_(False),
  300. Document.document_name.like(pattern, escape="\\"),
  301. )
  302. ).all()
  303. for child in children:
  304. if evaluate_plan_access(child, context).allowed:
  305. counts[child.parent_document_id][0] += 1
  306. bindings = db.session.execute(
  307. select(AttachmentBinding.main_document_id, Document.id)
  308. .join(Document, Document.id == AttachmentBinding.attachment_document_id)
  309. .where(
  310. AttachmentBinding.main_document_id.in_(main_ids),
  311. AttachmentBinding.is_deleted.is_(False),
  312. Document.document_type == DocumentType.ATTACHMENT.value,
  313. Document.is_deleted.is_(False),
  314. Document.document_name.like(pattern, escape="\\"),
  315. )
  316. ).all()
  317. for main_id, _ in bindings:
  318. counts[main_id][1] += 1
  319. return counts
  320. def _tags_filter(
  321. statement,
  322. tags_value: str | None,
  323. match_value: str | None,
  324. ):
  325. """按 ``tags`` JSON 数组精确匹配;``tagsMatch=any|all`` 决定 OR/AND 语义。"""
  326. if not tags_value or not tags_value.strip():
  327. return statement
  328. tags = [item.strip() for item in tags_value.split(",") if item.strip()]
  329. if not tags:
  330. return statement
  331. match = (match_value or "any").strip().lower()
  332. if match not in {"any", "all"}:
  333. raise InvalidArgumentError("tagsMatch只允许any或all")
  334. # 使用 JSON_CONTAINS 做数组元素的精确匹配;json.dumps 保证特殊字符安全转义。
  335. conditions = [func.json_contains(Document.tags, json.dumps(tag)) for tag in tags]
  336. combiner = and_ if match == "all" else or_
  337. return statement.where(combiner(*conditions))
  338. def _boolean(value: str | None, name: str, default: bool = False) -> bool:
  339. if value is None:
  340. return default
  341. if value not in {"true", "false"}:
  342. raise InvalidArgumentError(f"{name}必须是true或false")
  343. return value == "true"
  344. def _category_scope(category_id: int, include_descendants: bool) -> set[int]:
  345. categories = db.session.scalars(
  346. select(Category).where(
  347. Category.is_deleted.is_(False),
  348. Category.status == "ENABLED",
  349. )
  350. ).all()
  351. if not any(category.id == category_id for category in categories):
  352. raise ResourceNotFoundError("方案分类不存在或不可用")
  353. if not include_descendants:
  354. return {category_id}
  355. children: dict[int | None, list[int]] = {}
  356. for category in categories:
  357. children.setdefault(category.parent_id, []).append(category.id)
  358. result = {category_id}
  359. pending = [category_id]
  360. while pending:
  361. current = pending.pop()
  362. for child_id in children.get(current, []):
  363. if child_id not in result:
  364. result.add(child_id)
  365. pending.append(child_id)
  366. return result
  367. def list_documents(params: Mapping[str, str]) -> dict[str, object]:
  368. context = get_auth_context()
  369. page = _page(params)
  370. raw_types = params.get("documentType", "MAIN")
  371. document_types = [item.strip() for item in raw_types.split(",") if item.strip()]
  372. if (
  373. not document_types
  374. or any(item not in PLAN_TYPES for item in document_types)
  375. or len(set(document_types)) != len(document_types)
  376. ):
  377. raise InvalidArgumentError("documentType只允许MAIN、SUB_PLAN或二者组合")
  378. statement = select(Document).where(
  379. Document.is_deleted.is_(False),
  380. Document.document_type.in_(document_types),
  381. )
  382. include_descendants = _boolean(
  383. params.get("includeDescendants"), "includeDescendants"
  384. )
  385. category_id = params.get("categoryId")
  386. if category_id:
  387. parsed_category_id = parse_string_id(category_id, field="categoryId")
  388. statement = statement.where(
  389. Document.category_id.in_(
  390. _category_scope(parsed_category_id, include_descendants)
  391. )
  392. )
  393. aggregate = _boolean(params.get("aggregateHits"), "aggregateHits")
  394. if aggregate and document_types != ["MAIN"]:
  395. raise InvalidArgumentError("aggregateHits只允许在documentType=MAIN时使用")
  396. if not aggregate:
  397. statement = _title_keyword(statement, params.get("keyword"))
  398. statement = _advanced_filters(statement, params)
  399. statement = _tags_filter(
  400. statement, params.get("tags"), params.get("tagsMatch")
  401. )
  402. visibility_filter = _enum(
  403. params.get("visibilityType"), VisibilityType, "visibilityType"
  404. )
  405. for name, enum_type, column in (
  406. ("securityLevel", SecurityLevel, Document.security_level),
  407. ("status", DocumentStatus, Document.document_status),
  408. ):
  409. value = _enum(params.get(name), enum_type, name)
  410. if value:
  411. statement = statement.where(column == value)
  412. updated_from, updated_to = parse_updated_range(params)
  413. if updated_from:
  414. statement = statement.where(Document.updated_at >= updated_from)
  415. if updated_to:
  416. statement = statement.where(Document.updated_at <= updated_to)
  417. order, _ = _sort(params)
  418. documents = db.session.scalars(statement.order_by(order, Document.id.asc())).all()
  419. # 列表全量可见(需求3):无权限方案同样返回,allowedActions 为空集,
  420. # 前端据此禁用查看类按钮;预览/详情/下载接口仍独立拦截。
  421. listed: list[tuple[Document, PlanAccess]] = []
  422. for document in documents:
  423. access = evaluate_plan_access(document, context)
  424. if visibility_filter is not None:
  425. source_type = (
  426. access.source.visibility_type
  427. if access.source is not None
  428. else document.visibility_type
  429. )
  430. if source_type != visibility_filter:
  431. continue
  432. listed.append((document, access))
  433. total = len(listed)
  434. keyword = (params.get("keyword") or "").strip()
  435. hit_counts: dict[int, list[int]] = {}
  436. if aggregate:
  437. if keyword:
  438. # 子案/附件命中统计只覆盖有权限主案,避免借计数泄露无权限主案的挂载信息。
  439. hit_counts = _child_title_hit_counts(
  440. context, [document.id for document, access in listed if access.allowed], keyword
  441. )
  442. listed = [
  443. (document, access)
  444. for document, access in listed
  445. if _title_contains(document.document_name, keyword)
  446. or any(hit_counts.get(document.id))
  447. ]
  448. total = len(listed)
  449. selected = listed[page.offset : page.offset + page.page_size]
  450. items = [
  451. document_summary(
  452. document, context, access,
  453. keyword=params.get("contentKeyword") if access.allowed else None,
  454. )
  455. for document, access in selected
  456. ]
  457. if aggregate:
  458. for item, (document, access) in zip(items, selected, strict=True):
  459. counts = hit_counts.get(document.id, [0, 0]) if access.allowed else [0, 0]
  460. item["titleHit"] = not keyword or _title_contains(
  461. document.document_name, keyword
  462. )
  463. item["subHitCount"] = counts[0]
  464. item["attachmentHitCount"] = counts[1]
  465. return page_result(
  466. items,
  467. page=page.page,
  468. page_size=page.page_size,
  469. total=total,
  470. )
  471. def _active_plan(document_id: int) -> Document:
  472. document = db.session.scalar(
  473. select(Document).where(
  474. Document.id == document_id,
  475. Document.is_deleted.is_(False),
  476. Document.document_type.in_(PLAN_TYPES),
  477. )
  478. )
  479. if document is None:
  480. raise ResourceNotFoundError("方案文档不存在")
  481. return document
  482. def _record_view(document: Document) -> int:
  483. old_count = document.view_count
  484. document_id = document.id
  485. document_name = document.document_name
  486. target = (
  487. AuditTarget.ATTACHMENT
  488. if document.document_type == DocumentType.ATTACHMENT.value
  489. else AuditTarget.DOCUMENT
  490. )
  491. db.session.rollback()
  492. try:
  493. with transaction() as session:
  494. current = session.scalar(
  495. select(Document)
  496. .where(
  497. Document.id == document_id,
  498. Document.is_deleted.is_(False),
  499. )
  500. .with_for_update()
  501. )
  502. if current is None:
  503. raise ResourceNotFoundError("文档不存在")
  504. current.view_count += 1
  505. session.add(
  506. business_audit(
  507. action=AuditAction.VIEW_DOCUMENT,
  508. target=target,
  509. target_id=document_id,
  510. target_name=document_name,
  511. detail={"documentType": current.document_type},
  512. )
  513. )
  514. new_count = current.view_count
  515. return new_count
  516. except Exception:
  517. db.session.rollback()
  518. logger.exception("文档查看计数或审计写入失败:document_id=%s", document_id)
  519. return old_count
  520. def get_document(document_id: int) -> dict[str, object]:
  521. context = get_auth_context()
  522. document = _active_plan(document_id)
  523. access = _require_plan_access(document, context)
  524. result = document_detail(document, context, access)
  525. result["viewCount"] = _record_view(document)
  526. return result
  527. def list_sub_plans(
  528. main_document_id: int,
  529. params: Mapping[str, str],
  530. ) -> dict[str, object]:
  531. context = get_auth_context()
  532. main = db.session.scalar(
  533. select(Document).where(
  534. Document.id == main_document_id,
  535. Document.document_type == DocumentType.MAIN.value,
  536. Document.is_deleted.is_(False),
  537. )
  538. )
  539. if main is None:
  540. raise MainPlanNotFoundError()
  541. # 主案无权限时也返回子案列表(列表全量可见,与主案列表语义一致);
  542. # 子案权限继承自主案,allowedActions 自然为空集,内容由预览/详情接口拦截。
  543. evaluate_plan_access(main, context)
  544. page = _page(params)
  545. statement = select(Document).where(
  546. Document.parent_document_id == main.id,
  547. Document.document_type == DocumentType.SUB_PLAN.value,
  548. Document.is_deleted.is_(False),
  549. )
  550. statement = _title_keyword(statement, params.get("keyword"))
  551. statement = _advanced_filters(statement, params)
  552. status = _enum(params.get("status"), DocumentStatus, "status")
  553. if status:
  554. statement = statement.where(Document.document_status == status)
  555. updated_from, updated_to = parse_updated_range(params)
  556. if updated_from:
  557. statement = statement.where(Document.updated_at >= updated_from)
  558. if updated_to:
  559. statement = statement.where(Document.updated_at <= updated_to)
  560. order, _ = _sort(params)
  561. children = db.session.scalars(
  562. statement.order_by(order, Document.id.asc())
  563. ).all()
  564. listed: list[tuple[Document, PlanAccess]] = [
  565. (child, evaluate_plan_access(child, context)) for child in children
  566. ]
  567. total = len(listed)
  568. selected = listed[page.offset : page.offset + page.page_size]
  569. return page_result(
  570. [
  571. document_summary(
  572. child, context, access,
  573. keyword=params.get("contentKeyword") if access.allowed else None,
  574. )
  575. for child, access in selected
  576. ],
  577. page=page.page,
  578. page_size=page.page_size,
  579. total=total,
  580. )
  581. def list_main_plan_tags() -> dict[str, object]:
  582. """聚合当前用户可见的所有主案标签。
  583. - 全局视角:标签集合不随分类、关键词等其他筛选变化;
  584. - 权限:通过 ``evaluate_plan_access`` 在 Python 层逐条过滤,
  585. 与 ``list_documents`` 保持一致的可见性语义,避免泄露被
  586. ACL/密级隔离的主案标签;
  587. - 顺序:按 Unicode 升序,便于前端稳定渲染。
  588. """
  589. context = get_auth_context()
  590. statement = select(Document).where(
  591. Document.is_deleted.is_(False),
  592. Document.document_type == DocumentType.MAIN.value,
  593. )
  594. documents = db.session.scalars(statement).all()
  595. tags_set: set[str] = set()
  596. for document in documents:
  597. access = evaluate_plan_access(document, context)
  598. if not access.allowed:
  599. continue
  600. if document.tags:
  601. tags_set.update(document.tags)
  602. tags = sorted(tags_set)
  603. return {"items": tags, "total": len(tags)}
  604. __all__ = [
  605. "DOCUMENT_SORTS",
  606. "_advanced_filters",
  607. "_content_snippet",
  608. "_date",
  609. "_escape_like",
  610. "_enum",
  611. "_iso",
  612. "_page",
  613. "_record_view",
  614. "_sort",
  615. "_tags_filter",
  616. "_title_keyword",
  617. "document_detail",
  618. "document_summary",
  619. "get_document",
  620. "list_documents",
  621. "list_main_plan_tags",
  622. "list_sub_plans",
  623. "parse_string_id",
  624. ]