seed_showcase.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. """幂等补充业务展示分类、方案、附件、挂载和权限。"""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. from flask import Flask, current_app
  5. from sqlalchemy import func, select
  6. from dms import init_dms
  7. from dms.common.enums import (
  8. AttachmentType,
  9. CategoryType,
  10. DocumentStatus,
  11. DocumentType,
  12. EnabledStatus,
  13. SecurityLevel,
  14. SubjectType,
  15. VisibilityType,
  16. )
  17. from dms.extensions import db
  18. from dms.models import (
  19. AttachmentBinding,
  20. Category,
  21. Document,
  22. Organization,
  23. Permission,
  24. User,
  25. )
  26. from dms.seed_documents import _binding, _document, _permission, _required
  27. from dms.storage.paths import ensure_storage_directories
  28. def _category(
  29. *,
  30. code: str,
  31. name: str,
  32. category_type: CategoryType,
  33. sort_no: int,
  34. parent: Category | None = None,
  35. ) -> tuple[Category, bool]:
  36. existing = db.session.scalar(
  37. select(Category).where(Category.category_code == code)
  38. )
  39. if existing is not None:
  40. if existing.is_deleted or existing.status != EnabledStatus.ENABLED.value:
  41. raise RuntimeError(f"展示分类{code}已存在但不可用")
  42. return existing, False
  43. category_path = (
  44. f"{parent.category_path.rstrip('/')}/{name}"
  45. if parent is not None
  46. else f"/{name}"
  47. )
  48. category = Category(
  49. category_code=code,
  50. category_name=name,
  51. category_type=category_type.value,
  52. parent_id=parent.id if parent is not None else None,
  53. category_path=category_path,
  54. sort_no=sort_no,
  55. document_count=0,
  56. status=EnabledStatus.ENABLED.value,
  57. )
  58. db.session.add(category)
  59. db.session.flush()
  60. return category, True
  61. def _refresh_counts(categories: list[Category], mains: list[Document]) -> None:
  62. for main in mains:
  63. main.child_count = db.session.scalar(
  64. select(func.count(Document.id)).where(
  65. Document.parent_document_id == main.id,
  66. Document.document_type == DocumentType.SUB_PLAN.value,
  67. Document.is_deleted.is_(False),
  68. )
  69. ) or 0
  70. main.attachment_count = db.session.scalar(
  71. select(func.count(AttachmentBinding.id)).where(
  72. AttachmentBinding.main_document_id == main.id,
  73. AttachmentBinding.is_deleted.is_(False),
  74. )
  75. ) or 0
  76. for category in categories:
  77. category.document_count = db.session.scalar(
  78. select(func.count(Document.id)).where(
  79. Document.category_id == category.id,
  80. Document.document_type.in_(
  81. [DocumentType.MAIN.value, DocumentType.SUB_PLAN.value]
  82. ),
  83. Document.is_deleted.is_(False),
  84. )
  85. ) or 0
  86. def seed_showcase() -> tuple[int, int, int, int, int]:
  87. root = ensure_storage_directories(current_app.config["DMS_STORAGE_ROOT"])
  88. actor = _required(
  89. User,
  90. User.username == "admin",
  91. User.is_deleted.is_(False),
  92. description="有效admin用户",
  93. )
  94. ordinary_user = _required(
  95. User,
  96. User.username == "user",
  97. User.is_deleted.is_(False),
  98. description="有效user用户",
  99. )
  100. ops = _required(
  101. Organization,
  102. Organization.org_code == "ORG_OPS",
  103. Organization.is_deleted.is_(False),
  104. description="ORG_OPS组织",
  105. )
  106. comms = _required(
  107. Organization,
  108. Organization.org_code == "ORG_COMMS",
  109. Organization.is_deleted.is_(False),
  110. description="ORG_COMMS组织",
  111. )
  112. category_specs = (
  113. ("DEMO_EMERGENCY", "应急预案体系", CategoryType.SCENE, 10, None),
  114. ("DEMO_NATURAL", "自然灾害应急", CategoryType.STYLE, 10, "DEMO_EMERGENCY"),
  115. ("DEMO_PUBLIC", "公共安全保障", CategoryType.STYLE, 20, "DEMO_EMERGENCY"),
  116. ("DEMO_SUPPORT", "保障资源体系", CategoryType.SCENE, 20, None),
  117. ("DEMO_COMMS", "通信保障", CategoryType.SITUATION, 10, "DEMO_SUPPORT"),
  118. ("DEMO_MATERIAL", "物资保障", CategoryType.SITUATION, 20, "DEMO_SUPPORT"),
  119. ("DEMO_RULES", "制度与模板", CategoryType.SCENE, 30, None),
  120. ("DEMO_STANDARD", "工作规范", CategoryType.OTHER, 10, "DEMO_RULES"),
  121. ("DEMO_TEMPLATE", "表单模板", CategoryType.OTHER, 20, "DEMO_RULES"),
  122. )
  123. categories: dict[str, Category] = {}
  124. created_categories = 0
  125. for code, name, category_type, sort_no, parent_code in category_specs:
  126. category, created = _category(
  127. code=code,
  128. name=name,
  129. category_type=category_type,
  130. sort_no=sort_no,
  131. parent=categories.get(parent_code) if parent_code else None,
  132. )
  133. categories[code] = category
  134. created_categories += int(created)
  135. new_files: list[Path] = []
  136. created_documents = 0
  137. existing_documents = 0
  138. created_bindings = 0
  139. created_permissions = 0
  140. try:
  141. main_specs = (
  142. (
  143. "防汛抗旱专项应急预案",
  144. "面向汛情、城市内涝和旱情的监测预警、响应处置与恢复重建方案。",
  145. "DEMO_NATURAL",
  146. SecurityLevel.INTERNAL,
  147. VisibilityType.CUSTOM,
  148. ["防汛", "抗旱", "应急响应"],
  149. ("监测预警子方案", "人员转移安置子方案", "抢险救援子方案"),
  150. ),
  151. (
  152. "重大活动通信保障方案",
  153. "保障重大活动期间指挥链路、无线通信和应急通信资源连续可用。",
  154. "DEMO_COMMS",
  155. SecurityLevel.SECRET,
  156. VisibilityType.CUSTOM,
  157. ["通信", "重大活动", "链路保障"],
  158. ("核心网络保障子方案", "应急通信车调度子方案"),
  159. ),
  160. (
  161. "应急物资储备与调拨方案",
  162. "规范应急物资储备布局、库存盘点、需求汇总和跨区域调拨流程。",
  163. "DEMO_MATERIAL",
  164. SecurityLevel.INTERNAL,
  165. VisibilityType.CUSTOM,
  166. ["物资", "储备", "调拨"],
  167. ("仓储盘点子方案", "跨区域调拨子方案"),
  168. ),
  169. (
  170. "大型活动现场安全保障方案",
  171. "覆盖人员疏导、重点区域管控、突发事件处置和多部门协同。",
  172. "DEMO_PUBLIC",
  173. SecurityLevel.INTERNAL,
  174. VisibilityType.ALL_AUTHENTICATED,
  175. ["现场安全", "活动保障", "协同处置"],
  176. ("人员疏导子方案", "重点区域管控子方案"),
  177. ),
  178. )
  179. mains: list[Document] = []
  180. for name, summary, category_code, security, visibility, tags, children in main_specs:
  181. main, created, failed = _document(
  182. root=root,
  183. name=name,
  184. summary=summary,
  185. document_type=DocumentType.MAIN,
  186. status=DocumentStatus.PUBLISHED,
  187. security=security,
  188. visibility=visibility,
  189. category=categories[category_code],
  190. actor=actor,
  191. tags=tags,
  192. new_files=new_files,
  193. )
  194. if failed or main is None:
  195. raise RuntimeError(f"同名展示主案已逻辑删除:{name}")
  196. created_documents += int(created)
  197. existing_documents += int(not created)
  198. mains.append(main)
  199. for child_name in children:
  200. child, child_created, child_failed = _document(
  201. root=root,
  202. name=child_name,
  203. summary=f"《{name}》配套的{child_name},明确任务分工、实施步骤和保障要求。",
  204. document_type=DocumentType.SUB_PLAN,
  205. status=DocumentStatus.PUBLISHED,
  206. security=security,
  207. visibility=visibility,
  208. category=categories[category_code],
  209. actor=actor,
  210. tags=["子方案", *tags[:2]],
  211. new_files=new_files,
  212. parent=main,
  213. root_document=main,
  214. )
  215. if child_failed or child is None:
  216. raise RuntimeError(f"同名展示子方案已逻辑删除:{child_name}")
  217. created_documents += int(child_created)
  218. existing_documents += int(not child_created)
  219. attachment_specs = (
  220. ("防汛应急响应流程图", "防汛响应等级、指挥关系和处置流程示意。", AttachmentType.DIAGRAM),
  221. ("应急物资需求统计表", "应急物资需求、库存和缺口统计模板。", AttachmentType.TABLE),
  222. ("现场处置工作规范", "现场警戒、人员疏导和信息报送工作规范。", AttachmentType.WORK_STANDARD),
  223. ("应急通讯录模板", "应急联系人、值班电话和协同单位通讯录模板。", AttachmentType.TABLE),
  224. ("跨部门协同处置流程", "跨部门会商、指令下达和反馈闭环流程。", AttachmentType.DIAGRAM),
  225. )
  226. attachments: list[Document] = []
  227. for name, summary, attachment_type in attachment_specs:
  228. attachment, created, failed = _document(
  229. root=root,
  230. name=name,
  231. summary=summary,
  232. document_type=DocumentType.ATTACHMENT,
  233. status=DocumentStatus.PUBLISHED,
  234. security=SecurityLevel.PUBLIC,
  235. visibility=VisibilityType.ALL_AUTHENTICATED,
  236. category=None,
  237. actor=actor,
  238. tags=["共享附件", "业务模板"],
  239. new_files=new_files,
  240. attachment_type=attachment_type,
  241. )
  242. if failed or attachment is None:
  243. raise RuntimeError(f"同名展示附件已逻辑删除:{name}")
  244. created_documents += int(created)
  245. existing_documents += int(not created)
  246. attachments.append(attachment)
  247. permission_specs = (
  248. (mains[0], SubjectType.ORG, ops.id, ops.org_name),
  249. (mains[1], SubjectType.ORG, comms.id, comms.org_name),
  250. (mains[2], SubjectType.ORG, ops.id, ops.org_name),
  251. (mains[2], SubjectType.USER, ordinary_user.id, ordinary_user.real_name),
  252. )
  253. for main, subject_type, subject_id, subject_name in permission_specs:
  254. existing_permission = db.session.scalar(
  255. select(Permission.id).where(
  256. Permission.document_id == main.id,
  257. Permission.subject_type == subject_type.value,
  258. Permission.subject_id == subject_id,
  259. )
  260. )
  261. _permission(
  262. main,
  263. subject_type=subject_type,
  264. subject_id=subject_id,
  265. subject_name=subject_name,
  266. actor_id=actor.id,
  267. )
  268. created_permissions += int(existing_permission is None)
  269. binding_specs = (
  270. (mains[0], attachments[0], 10),
  271. (mains[0], attachments[1], 20),
  272. (mains[0], attachments[4], 30),
  273. (mains[1], attachments[3], 10),
  274. (mains[1], attachments[4], 20),
  275. (mains[2], attachments[1], 10),
  276. (mains[2], attachments[3], 20),
  277. (mains[3], attachments[2], 10),
  278. (mains[3], attachments[4], 20),
  279. )
  280. for main, attachment, sort_no in binding_specs:
  281. existing_binding = db.session.scalar(
  282. select(AttachmentBinding.id).where(
  283. AttachmentBinding.main_document_id == main.id,
  284. AttachmentBinding.attachment_document_id == attachment.id,
  285. )
  286. )
  287. _binding(
  288. main,
  289. attachment,
  290. sort_no=sort_no,
  291. actor_id=actor.id,
  292. )
  293. created_bindings += int(existing_binding is None)
  294. _refresh_counts(list(categories.values()), mains)
  295. db.session.commit()
  296. except Exception:
  297. db.session.rollback()
  298. for path in new_files:
  299. path.unlink(missing_ok=True)
  300. raise
  301. return (
  302. created_categories,
  303. created_documents,
  304. existing_documents,
  305. created_bindings,
  306. created_permissions,
  307. )
  308. def main() -> None:
  309. app = Flask("dms-seed-showcase")
  310. init_dms(app)
  311. with app.app_context():
  312. result = seed_showcase()
  313. print(
  314. "业务展示数据初始化完成:"
  315. f"新增分类{result[0]}个,新增文档{result[1]}个,"
  316. f"已有文档{result[2]}个,新增挂载{result[3]}条,"
  317. f"新增权限{result[4]}条。"
  318. )
  319. if __name__ == "__main__":
  320. main()