seed_showcase.py 12 KB

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