From b91954df4a5e3325415946a0fe742214459be64d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=8D=97=E9=80=9A=E4=B8=80=E6=AC=A1=E5=85=83=E7=A7=91?=
=?UTF-8?q?=E6=8A=80=E6=9C=89=E9=99=90=E5=85=AC=E5=8F=B8?=
Date: Sat, 5 Dec 2026 15:44:53 +0000
Subject: [PATCH] chore: initial open-source baseline v1.0.0
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: 南通一次元科技有限公司
---
.gitea/workflows/ci.yml | 16 +
.gitignore | 22 +
CHANGELOG.md | 13 +
CODE_OF_CONDUCT.md | 24 +
CONTRIBUTING.md | 67 +
LICENSE | 202 +
NOTICE | 33 +
README.md | 92 +
SECURITY.md | 34 +
SHA256SUMS | 104 +
TRADEMARK.md | 26 +
deploy/.dockerignore | 6 +
deploy/.env.example | 5 +
deploy/Dockerfile | 31 +
deploy/docker-compose.yml | 97 +
deploy/requirements.txt | 11 +
deploy/冒烟测试.py | 137 +
deploy/同步公共模块.py | 67 +
deploy/同步统一主题.py | 88 +
deploy/生成演示数据.py | 307 +
deploy/自检.py | 257 +
docs/Git仓库初始化指南.md | 60 +
docs/合成演示数据说明.md | 34 +
docs/平台建设与协作方案.md | 69 +
docs/开源合规清单.md | 53 +
docs/离线发布与升级指南.md | 76 +
shared/auth_guard.py | 553 ++
shared/embed_theme.css | 32 +
shared/pdf_tools.py | 133 +
合同审核管理平台/auth_guard.py | 553 ++
合同审核管理平台/chart.umd.min.js | 1 +
合同审核管理平台/contract_service.py | 701 ++
合同审核管理平台/index.html | 1229 ++++
合同审核管理平台/pdf_tools.py | 133 +
合同审核管理平台/portal_server.py | 227 +
合同审核管理平台/requirements.txt | 10 +
合同审核管理平台/启动合同审核.bat | 34 +
审计项目管理平台/auth_guard.py | 553 ++
审计项目管理平台/check_att.py | 30 +
审计项目管理平台/config.py | 39 +
审计项目管理平台/main.py | 1842 +++++
审计项目管理平台/pdf_tools.py | 133 +
审计项目管理平台/requirements.txt | 7 +
审计项目管理平台/services/__init__.py | 1 +
.../services/attachment_parser.py | 192 +
审计项目管理平台/services/feishu_service.py | 828 +++
审计项目管理平台/services/llm_service.py | 477 ++
审计项目管理平台/services/local_service.py | 923 +++
.../services/local_wiki_service.py | 111 +
.../services/web_search_service.py | 122 +
审计项目管理平台/services/wiki_service.py | 127 +
审计项目管理平台/start_audit_server.py | 20 +
审计项目管理平台/sync_wiki_content.py | 269 +
审计项目管理平台/templates/index.html | 3980 +++++++++++
审计项目管理平台/启动审计系统.bat | 50 +
综合管理平台/auth_guard.py | 553 ++
综合管理平台/chart.umd.min.js | 1 +
综合管理平台/digital_audit.css | 162 +
综合管理平台/digital_audit.html | 124 +
综合管理平台/digital_audit_service.py | 1834 +++++
综合管理平台/extract_service.py | 426 ++
综合管理平台/js/boot.js | 11 +
综合管理平台/js/core.js | 193 +
综合管理平台/js/dashboard.js | 62 +
综合管理平台/js/data.js | 152 +
综合管理平台/js/extract.js | 100 +
综合管理平台/js/parse.js | 159 +
综合管理平台/js/rectification.js | 266 +
综合管理平台/js/rules.js | 121 +
综合管理平台/js/tasks.js | 100 +
综合管理平台/js/workflow.js | 115 +
综合管理平台/knowledge.html | 1231 ++++
综合管理平台/knowledge_service.py | 794 +++
综合管理平台/make_icon.py | 0
综合管理平台/operator_context.py | 21 +
综合管理平台/parse_task_service.py | 276 +
综合管理平台/pdf_tools.py | 133 +
综合管理平台/policy_news_cache.json | 96 +
综合管理平台/portal.html | 1513 +++++
综合管理平台/portal_icon.ico | Bin 0 -> 132292 bytes
综合管理平台/portal_server.py | 1774 +++++
综合管理平台/rectification_service.py | 594 ++
综合管理平台/requirements.txt | 10 +
综合管理平台/settings.html | 426 ++
综合管理平台/shell.html | 477 ++
综合管理平台/workflow_service.py | 369 +
综合管理平台/write_bat.py | 92 +
综合管理平台/启动平台.bat | 70 +
风险管理项目/auth_guard.py | 553 ++
风险管理项目/chart.umd.min.js | 1 +
风险管理项目/config.py | 92 +
风险管理项目/database.py | 462 ++
风险管理项目/main.py | 1566 +++++
风险管理项目/pdf_tools.py | 133 +
风险管理项目/requirements.txt | 10 +
风险管理项目/services/__init__.py | 1 +
风险管理项目/services/ai_risk_service.py | 498 ++
风险管理项目/services/analysis_service.py | 1544 +++++
风险管理项目/services/feishu_service.py | 1714 +++++
风险管理项目/services/import_service.py | 183 +
风险管理项目/services/inspection_service.py | 959 +++
风险管理项目/services/merge_service.py | 1303 ++++
风险管理项目/services/risk_service.py | 897 +++
风险管理项目/templates/index.html | 5908 +++++++++++++++++
风险管理项目/启动服务.bat | 34 +
风险管理项目/静默启动.vbs | 5 +
106 files changed, 43359 insertions(+)
create mode 100644 .gitea/workflows/ci.yml
create mode 100644 .gitignore
create mode 100644 CHANGELOG.md
create mode 100644 CODE_OF_CONDUCT.md
create mode 100644 CONTRIBUTING.md
create mode 100644 LICENSE
create mode 100644 NOTICE
create mode 100644 README.md
create mode 100644 SECURITY.md
create mode 100644 SHA256SUMS
create mode 100644 TRADEMARK.md
create mode 100644 deploy/.dockerignore
create mode 100644 deploy/.env.example
create mode 100644 deploy/Dockerfile
create mode 100644 deploy/docker-compose.yml
create mode 100644 deploy/requirements.txt
create mode 100644 deploy/冒烟测试.py
create mode 100644 deploy/同步公共模块.py
create mode 100644 deploy/同步统一主题.py
create mode 100644 deploy/生成演示数据.py
create mode 100644 deploy/自检.py
create mode 100644 docs/Git仓库初始化指南.md
create mode 100644 docs/合成演示数据说明.md
create mode 100644 docs/平台建设与协作方案.md
create mode 100644 docs/开源合规清单.md
create mode 100644 docs/离线发布与升级指南.md
create mode 100644 shared/auth_guard.py
create mode 100644 shared/embed_theme.css
create mode 100644 shared/pdf_tools.py
create mode 100644 合同审核管理平台/auth_guard.py
create mode 100644 合同审核管理平台/chart.umd.min.js
create mode 100644 合同审核管理平台/contract_service.py
create mode 100644 合同审核管理平台/index.html
create mode 100644 合同审核管理平台/pdf_tools.py
create mode 100644 合同审核管理平台/portal_server.py
create mode 100644 合同审核管理平台/requirements.txt
create mode 100644 合同审核管理平台/启动合同审核.bat
create mode 100644 审计项目管理平台/auth_guard.py
create mode 100644 审计项目管理平台/check_att.py
create mode 100644 审计项目管理平台/config.py
create mode 100644 审计项目管理平台/main.py
create mode 100644 审计项目管理平台/pdf_tools.py
create mode 100644 审计项目管理平台/requirements.txt
create mode 100644 审计项目管理平台/services/__init__.py
create mode 100644 审计项目管理平台/services/attachment_parser.py
create mode 100644 审计项目管理平台/services/feishu_service.py
create mode 100644 审计项目管理平台/services/llm_service.py
create mode 100644 审计项目管理平台/services/local_service.py
create mode 100644 审计项目管理平台/services/local_wiki_service.py
create mode 100644 审计项目管理平台/services/web_search_service.py
create mode 100644 审计项目管理平台/services/wiki_service.py
create mode 100644 审计项目管理平台/start_audit_server.py
create mode 100644 审计项目管理平台/sync_wiki_content.py
create mode 100644 审计项目管理平台/templates/index.html
create mode 100644 审计项目管理平台/启动审计系统.bat
create mode 100644 综合管理平台/auth_guard.py
create mode 100644 综合管理平台/chart.umd.min.js
create mode 100644 综合管理平台/digital_audit.css
create mode 100644 综合管理平台/digital_audit.html
create mode 100644 综合管理平台/digital_audit_service.py
create mode 100644 综合管理平台/extract_service.py
create mode 100644 综合管理平台/js/boot.js
create mode 100644 综合管理平台/js/core.js
create mode 100644 综合管理平台/js/dashboard.js
create mode 100644 综合管理平台/js/data.js
create mode 100644 综合管理平台/js/extract.js
create mode 100644 综合管理平台/js/parse.js
create mode 100644 综合管理平台/js/rectification.js
create mode 100644 综合管理平台/js/rules.js
create mode 100644 综合管理平台/js/tasks.js
create mode 100644 综合管理平台/js/workflow.js
create mode 100644 综合管理平台/knowledge.html
create mode 100644 综合管理平台/knowledge_service.py
create mode 100644 综合管理平台/make_icon.py
create mode 100644 综合管理平台/operator_context.py
create mode 100644 综合管理平台/parse_task_service.py
create mode 100644 综合管理平台/pdf_tools.py
create mode 100644 综合管理平台/policy_news_cache.json
create mode 100644 综合管理平台/portal.html
create mode 100644 综合管理平台/portal_icon.ico
create mode 100644 综合管理平台/portal_server.py
create mode 100644 综合管理平台/rectification_service.py
create mode 100644 综合管理平台/requirements.txt
create mode 100644 综合管理平台/settings.html
create mode 100644 综合管理平台/shell.html
create mode 100644 综合管理平台/workflow_service.py
create mode 100644 综合管理平台/write_bat.py
create mode 100644 综合管理平台/启动平台.bat
create mode 100644 风险管理项目/auth_guard.py
create mode 100644 风险管理项目/chart.umd.min.js
create mode 100644 风险管理项目/config.py
create mode 100644 风险管理项目/database.py
create mode 100644 风险管理项目/main.py
create mode 100644 风险管理项目/pdf_tools.py
create mode 100644 风险管理项目/requirements.txt
create mode 100644 风险管理项目/services/__init__.py
create mode 100644 风险管理项目/services/ai_risk_service.py
create mode 100644 风险管理项目/services/analysis_service.py
create mode 100644 风险管理项目/services/feishu_service.py
create mode 100644 风险管理项目/services/import_service.py
create mode 100644 风险管理项目/services/inspection_service.py
create mode 100644 风险管理项目/services/merge_service.py
create mode 100644 风险管理项目/services/risk_service.py
create mode 100644 风险管理项目/templates/index.html
create mode 100644 风险管理项目/启动服务.bat
create mode 100644 风险管理项目/静默启动.vbs
diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml
new file mode 100644
index 0000000..740588c
--- /dev/null
+++ b/.gitea/workflows/ci.yml
@@ -0,0 +1,16 @@
+name: CI
+on:
+ push:
+ pull_request:
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Install dependencies
+ run: pip install -r deploy/requirements.txt
+ - name: Self check
+ run: python deploy/自检.py
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..421059d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,22 @@
+__pycache__/
+*.py[cod]
+.venv/
+venv/
+env/
+*.db
+*.db-wal
+*.db-shm
+uploads/
+合同/
+报告/
+backups/
+settings.json
+.auth_override.json
+.env
+*.log
+*.pyc
+dist/
+build/
+node_modules/
+.DS_Store
+Thumbs.db
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..8ac878c
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,13 @@
+# 更新日志
+
+## v1.0.0(首个开源基线,待发布)
+
+- 统一门户、数字化审计驾驶舱、待办中心、全局搜索
+- 审计项目、资料、分析、报告
+- 智能解析工厂:文档解析、OCR 批量任务、合同要素抽取、单据信息提取
+- 规则引擎:高级规则、模拟运行、发布审批、任务调度
+- 审计作业:底稿、取证、报告
+- 整改闭环:派发、反馈、审核、初验六必问、专项评估、批量导入导出、整改地图与报表
+- 风险管理、合同审核、知识库
+- 用户、角色、权限、真实操作人留痕
+- 冒烟测试、数据库索引、部署自动备份与离线升级基础
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..1406280
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,24 @@
+# 行为准则
+
+本项目采用 Contributor Covenant 的精神,适用于 Issue、PR、讨论和线下协作。
+
+## 我们期望
+
+- 尊重不同医院、不同岗位、不同技术背景的参与者
+- 对事不对人,讨论技术方案而非攻击个人
+- 保护患者隐私和医院数据,不索取、不传播真实业务数据
+- 接受建设性批评,也愿意修正自己的错误
+- 不利用项目身份冒充官方或误导医院
+
+## 不可接受
+
+- 人身攻击、歧视、骚扰、威胁
+- 发布他人隐私或医院敏感数据
+- 恶意提交后门、数据外传代码或破坏性改动
+- 冒充官方版本、官方人员或认证实施商
+- 其他违反法律法规或行业规范的行为
+
+## 处理
+
+维护方有权删除不当内容、拒绝贡献或暂停参与者权限。
+严重事件可通过维护方联系渠道私下报告。
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..b53a5b6
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,67 @@
+# 贡献指南
+
+感谢参与医院智能审计管理平台。我们欢迎代码、文档、规则、报表模板和缺陷报告。
+
+## 一、提交前
+
+1. 先搜索 Issue / PR,避免重复。
+2. 大功能请先提 Issue 说明场景和方案,避免大改后被拒。
+3. 不要提交任何医院真实数据、患者信息、合同原文、数据库、上传文件或密钥。
+4. 代码需通过现有测试与自检:
+ - `python deploy/自检.py`
+ - `python deploy/冒烟测试.py --url http://127.0.0.1:8080`
+5. 前端改动请确认 4 个服务页面无报错。
+
+## 二、DCO(开发者原创声明)
+
+本项目使用 DCO 1.1。每次提交需签名:
+
+```bash
+git commit -s -m "fix: 修复整改工单超期统计"
+```
+
+提交信息中包含:
+```text
+Signed-off-by: 你的名字 <你的邮箱>
+```
+
+即表示你确认有权提交该代码,并同意按本项目许可证授权。
+
+## 三、分支与提交
+
+- 分支:`feature/xxx`、`fix/xxx`、`docs/xxx`
+- 提交信息建议使用:`feat:`、`fix:`、`docs:`、`refactor:`、`test:`、`chore:`
+- 一个 PR 只做一件事,避免超大 PR
+- 修改数据库结构必须附带迁移脚本与回滚说明
+
+## 四、代码规范
+
+- Python:保持现有 FastAPI 风格,函数职责单一,不硬编码医院路径/密钥
+- 前端:使用现有设计变量,不引入与项目风格冲突的框架
+- 公共模块唯一来源为 `shared/`,不要单独修改各项目下的副本
+- 新增配置项必须写入 `.env.example` 并说明默认值
+
+## 五、离线贡献(医院内网)
+
+医院无法访问公网时,可通过离线补丁包贡献:
+
+```bash
+# 在本地仓库导出相对官方基线的补丁
+git format-patch upstream/main --stdout > hospital-improvement.patch
+
+# 或导出 git bundle
+git bundle create hospital-improvement.bundle upstream/main..HEAD
+```
+
+将补丁/bundle 与变更说明一起交给维护方,由维护方导入评审。
+不要在补丁中包含数据库、上传文件、合同、报告或患者数据。
+
+## 六、评审与合并
+
+- 维护者会检查:功能合理性、兼容性、测试、许可证、数据安全
+- 涉及核心行为的改动可能需要 RFC 讨论
+- 合并后进入下一个版本;重要贡献会在 CHANGELOG 中署名
+
+## 七、行为准则
+
+请阅读 `CODE_OF_CONDUCT.md`。
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..162b2bc
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,33 @@
+医院智能审计管理平台
+Copyright 2026 南通一次元科技有限公司
+
+本产品包含或依赖以下第三方组件。各组件的版权归其各自作者所有,
+使用时请遵守对应许可证。正式发布前请以实际安装版本为准补齐版本号与许可证全文。
+
+一、Python 依赖
+- FastAPI(MIT)
+- Uvicorn(BSD-3-Clause)
+- Starlette(BSD-3-Clause)
+- Pydantic(MIT)
+- python-multipart(Apache-2.0)
+- python-docx(MIT)
+- openpyxl(MIT)
+- PyPDF2(BSD-3-Clause)
+- openai(Apache-2.0)
+- pypdfium2(Apache-2.0,PDF 渲染)
+- pytesseract(MIT,OCR 可选)
+- Pillow(HPND,图像处理)
+
+二、系统组件(由部署环境提供,不随源码包分发)
+- Tesseract OCR(Apache-2.0)
+- LibreOffice(MPL-2.0)
+- Noto CJK 字体(SIL Open Font License 1.1)
+- SQLite(Public Domain)
+
+三、前端组件
+- Chart.js(MIT,文件:chart.umd.min.js)
+
+说明:
+原 PyMuPDF 依赖已移除,PDF 文本提取使用 PyPDF2(BSD-3-Clause),
+页面渲染使用 pypdfium2(Apache-2.0,内置 PDFium BSD-3-Clause),
+以保持与 Apache-2.0 发布兼容。详见 docs/开源合规清单.md。
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b6335e1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,92 @@
+# 医院智能审计管理平台
+
+> 面向医院审计科的开源审计业务平台,覆盖审计项目、资料解析、规则引擎、审计作业、整改闭环与报表分析。
+
+- 维护方:南通一次元科技有限公司
+- 当前版本:v1.0.0(首个开源基线,版本号可按实际发布调整)
+- 许可证:Apache License 2.0(发布前请先阅读 `docs/开源合规清单.md`)
+
+## 功能概览
+
+| 模块 | 能力 |
+|------|------|
+| 统一门户 | 统一登录、模块导航、全局搜索、待办中心、服务状态 |
+| 审计项目管理 | 年度计划、项目、步骤、资料、分析结果、报告 |
+| 智能解析工厂 | 文档解析、OCR 批量任务、合同要素抽取、单据信息提取 |
+| 规则引擎 | 关键词/正则/相似度/时间逻辑/数值范围/跨文档勾稽/计算校验;模拟运行、发布审批、定时调度 |
+| 审计作业 | 审计底稿、取证单、报告全流程 |
+| 整改闭环 | 工单派发、反馈、审核、初验六必问、专项评估、批量导入导出、整改地图与报表 |
+| 风险管理 | 风险清单、风险评估、检查风险数据 |
+| 合同审核 | 合同上传、AI 审核、审核报告 |
+| 知识库 | 分类、文档、采集与检索 |
+| 系统设置 | 用户、角色、权限、大模型配置 |
+
+## 技术栈
+
+- Python 3.12 + FastAPI + Uvicorn
+- SQLite(单机部署,数据随医院内网保存)
+- 原生 HTML / CSS / JavaScript
+- Docker Compose 部署
+- Tesseract OCR(扫描件识别,可选)
+- LibreOffice(旧版 Office 格式转换,可选)
+
+## 目录结构
+
+```
+├── 综合管理平台/ 门户、数字化审计、知识库、用户权限
+├── 审计项目管理平台/ 审计项目、资料、分析、报告
+├── 风险管理项目/ 风险清单、评估、检查风险
+├── 合同审核管理平台/ 合同上传、AI 审核、报告
+├── shared/ 公共模块与统一主题(唯一来源)
+├── deploy/ 构建与部署脚本
+├── docs/ 文档
+├── LICENSE
+├── NOTICE
+└── CONTRIBUTING.md
+```
+
+## 本地运行
+
+1. 准备 Python 3.12 环境。
+2. 在 `综合管理平台/`、`审计项目管理平台/`、`风险管理项目/`、`合同审核管理平台/` 分别安装依赖:
+ `pip install -r requirements.txt`
+3. 分别启动四个服务(默认端口 8080 / 8000 / 8001 / 8090)。
+4. 浏览器访问 `http://127.0.0.1:8080/`。
+
+本地默认不启用登录;生产环境必须通过 `.env` 配置 `AUTH_USER`、`AUTH_PASSWORD`、`SESSION_SECRET`。
+
+## Docker 部署
+
+参考 `docs/离线发布与升级指南.md`,或使用仓库内的 `deploy/Dockerfile` 与 `deploy/docker-compose.yml`。
+
+医院内网离线部署请阅读 `docs/离线发布与升级指南.md`。本仓库暂未附带演示数据库,首次运行会初始化空库。
+
+## 数据与安全
+
+- 本仓库**不包含**任何医院真实数据、数据库、合同原文、审核报告、上传文件或密钥。
+- 请勿在 Issue、PR、截图中提交患者信息、合同原文或医院内部数据。
+- 安全漏洞请按 `SECURITY.md` 私下报告,不要公开提交 Issue。
+
+## 定制与二次开发
+
+- 优先通过配置、规则、报表模板和插件扩展,不要直接修改核心代码。
+- 医院可 fork 后自行修改;修改版必须遵守 `TRADEMARK.md`,不得冒充官方版本。
+- 欢迎通过 Pull Request 或离线补丁包(git bundle / patch)提交改进。
+
+## 贡献
+
+请阅读 `CONTRIBUTING.md`。
+
+## 进一步阅读
+
+- 平台建设与协作方案:`docs/平台建设与协作方案.md`
+- 离线发布与升级:`docs/离线发布与升级指南.md`
+- Git 仓库初始化:`docs/Git仓库初始化指南.md`
+- 开源合规清单:`docs/开源合规清单.md`
+- 合成演示数据:`docs/合成演示数据说明.md`提交代码需签署 DCO(`git commit -s`)。
+
+## 许可证
+
+除非另有说明,本项目代码采用 Apache License 2.0,详见 `LICENSE` 与 `NOTICE`。
+
+> PDF 解析已切换到 PyPDF2(BSD)与 pypdfium2(Apache-2.0),不再依赖 PyMuPDF;发布前仍建议按 `docs/开源合规清单.md` 做一次第三方许可证复核。
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..0c5200c
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,34 @@
+# 安全策略
+
+## 支持版本
+
+| 版本 | 支持状态 |
+|------|----------|
+| 1.x | 安全修复 |
+
+旧版本请先升级到受支持版本。
+
+## 报告漏洞
+
+请**不要**通过公开 Issue 报告安全漏洞。
+
+请通过维护方公布的安全联系渠道私下报告,并尽量包含:
+
+- 影响版本
+- 复现步骤
+- 影响范围(是否可读取/修改数据、是否可绕过登录等)
+- 修复建议(如有)
+
+> 安全联系邮箱:待维护方在正式发布前填写。
+
+## 处理流程
+
+1. 维护方确认收到并评估影响
+2. 修复并在受支持版本发布补丁
+3. 视情况发布安全公告
+4. 在修复发布后致谢报告者(如报告者同意)
+
+## 禁止事项
+
+- 不要在报告中附带真实患者数据、合同原文或医院内部数据
+- 不要对生产环境进行未授权测试
diff --git a/SHA256SUMS b/SHA256SUMS
new file mode 100644
index 0000000..f661df8
--- /dev/null
+++ b/SHA256SUMS
@@ -0,0 +1,104 @@
+af93a653cb58d2686550db1ab18dba96cae86b297a1c32b21f9ea808516df3b8 .gitignore
+f0fbe9bfd5c7a93c0ae6618fa45a87676068425a4719269db7f6d2a813ada2f1 CHANGELOG.md
+439d955a86637a6b026b06a6a929364bd052df6ac927c72479e6ad4a2e7efd4b CODE_OF_CONDUCT.md
+694a4966bfdc61b3d1c54266f36555b35db4164902573fefe4055bec47232b93 CONTRIBUTING.md
+8382ca6e3b7d98e375cbc6e1af802d3d03ba960afdcd685a10357db28f1673a1 deploy/.dockerignore
+d57294e50d0dea951378299c4cf9c543606f3b0e8afb6e1df0f3da23158882a9 deploy/.env.example
+02928bb6ffbd50deff58035e78649f1a63c57b25b28be599827ad7696a709e3a deploy/docker-compose.yml
+60dad02408ef2e9398634a8e813686502758dd6d969036187d84a1ab2b982013 deploy/Dockerfile
+7d0666926db89157779d24794e01b1f7f4439347e1ed01fbf48b30cc9291afa5 deploy/requirements.txt
+56852d0917810543f55d4fb09200487eb573adc9fd8a765ef30b8eb1c872dd3b deploy/冒烟测试.py
+87a35eb3a91c18bd0c47178903401785d604f782684a1c26433ea6ceb5d74f9c deploy/同步公共模块.py
+57a7f8492a9f3c1d2e292c59308e63c89b3d448b526756d12cbc255139f9720b deploy/同步统一主题.py
+1edf80d0ebe323061ea89ba8f35abc45dcd2908a9d0de73fab5eeb5fd44ae0d9 deploy/生成演示数据.py
+8f0c6daa430497af31d1c4a347641df931c34b55717034aa797a839402024710 deploy/自检.py
+a13b39d104277a41b3940d19328138d07f7906fc211b1ae86012199bf3d184cd docs/Git仓库初始化指南.md
+e9618150cb9f86754d7724bbd8d6fcac330e7a9561f35592223f71b66e27d4df docs/合成演示数据说明.md
+924a0dbe2a683943f5ded7a31e539891ee992d486c6ef94e315e169d67a0a74c docs/平台建设与协作方案.md
+efb5d4cc5a2e3e6e187c14d9845dbc9a629847c04f7f026d783aa153a1e70f55 docs/开源合规清单.md
+91e03af6629271e0c14ade6ded2e0cb814f2382b567b208c2a3c969b0fc89e30 docs/离线发布与升级指南.md
+cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
+bb9f1e4ad9d7b88f4cd8b83e2ec149744631a94334948d9106c075f3313e4eca NOTICE
+377dc475b6709537963d86274f9e979d9ca778d61878b48cbe8d52dbd814eec3 README.md
+2fa1eb1ea37c62ee3c6e2b7e113654e6ba77a23b742bd7d64bae081349631e5a SECURITY.md
+e3f99dd6f109e422f5e8606167e1889c586e9f5505bded6b35371699e34fef54 shared/auth_guard.py
+ab718191b5ba0c78328c49926b3d91ee5f7cb9c1dcfe47ed91634a992bf4cfed shared/embed_theme.css
+091eeaf53989638005f86295bd9b85f361884c46352e6dac68c76269cd005cf5 shared/pdf_tools.py
+d86cb3ec38545af95b415c1d74b0d1a6d4d970307c0aeac00c1103f38ce80daf TRADEMARK.md
+e3f99dd6f109e422f5e8606167e1889c586e9f5505bded6b35371699e34fef54 合同审核管理平台/auth_guard.py
+e9b0f875106021fb3d58120ad8ebdd3e7d32135a4452fd8918c72ac6475f2bd3 合同审核管理平台/chart.umd.min.js
+03f6827c86e1dffff1b2d1e190afe1b56462751f974fc8bdf8efca2fbc8459fc 合同审核管理平台/contract_service.py
+bd8293d3a70cfca681c36f881ce39735b0da202902bedde1256da75b25c3a576 合同审核管理平台/index.html
+091eeaf53989638005f86295bd9b85f361884c46352e6dac68c76269cd005cf5 合同审核管理平台/pdf_tools.py
+d79309b693265e78606bfdb57388f1dd19ca6e3092d16f8216a5133ffad53752 合同审核管理平台/portal_server.py
+2b98dde283539393d37e49f8c19fcfe15dd1e732c77eaadb5bb631853f121dcf 合同审核管理平台/requirements.txt
+a609267279b86556a41c6f9822171f6be028188e55574ab205538ea25f15cb0c 合同审核管理平台/启动合同审核.bat
+e3f99dd6f109e422f5e8606167e1889c586e9f5505bded6b35371699e34fef54 审计项目管理平台/auth_guard.py
+1139ace4df8f2c08a612e5a81b3e3a5510072460632c7fa02ed50734c0ac0315 审计项目管理平台/check_att.py
+4433b88cd793045202094cbad55ccc61095afae71c46fc4e9a1152859d6a109b 审计项目管理平台/config.py
+6fafb770c558ef74e6f9c810956df0ec2726535fbac240a15ca4f9ed7c6350a5 审计项目管理平台/main.py
+091eeaf53989638005f86295bd9b85f361884c46352e6dac68c76269cd005cf5 审计项目管理平台/pdf_tools.py
+9b5a7dd1a1549df1568a68135f156ffca9bd09c509e19aecffad7386b6a9d491 审计项目管理平台/requirements.txt
+c69d0ace5465422aa4390808a314325fcb220a08f4094265b6713504c84e81f1 审计项目管理平台/services/__init__.py
+84ee38f3b435ce771eebe9ba165d4e14123e1ed965ce7b39a211a4f32a6714fc 审计项目管理平台/services/attachment_parser.py
+460500a9c4c80b1c1972255f25047f71ac52f662991096fa26ba0156d1b089ec 审计项目管理平台/services/feishu_service.py
+e40dcae31a85e69c126d0d04cf3018768895e0121a154ced794e29d35fa07d17 审计项目管理平台/services/llm_service.py
+91e682dd2c01678241525b2a8f9ffe89853d1fd28e0496fee9e7527a242ca151 审计项目管理平台/services/local_service.py
+b9c78f5f4e1b0dc6e6d736bcddaf0e455172bf7a8cc63957934042949721026d 审计项目管理平台/services/local_wiki_service.py
+6a3a36b088672591fb16cbf8a8c9d48aacf1cf36d79cf4933ef03ab43e9a95a9 审计项目管理平台/services/web_search_service.py
+721f85e61891b423dd723834cbfd30b61b0bfc38c1d734909b81d93b6e6c2e3b 审计项目管理平台/services/wiki_service.py
+65ee23ba29e861a65231111c07e2e008189705b5db5d159f24d215237d542a82 审计项目管理平台/start_audit_server.py
+a187ce03135b3469a03f37cbb9c0473db66da383e857b282895fb6a7039cc3a3 审计项目管理平台/sync_wiki_content.py
+aaed320fee68b79441c9b405bdbf2f323e4f2bfda9f2d7ce6ffe6665f1496bfd 审计项目管理平台/templates/index.html
+0378d4b184be2de1df4d0db8326f92a3e74864bcc5ac6e6ca41a93d7eb06d1ed 审计项目管理平台/启动审计系统.bat
+e3f99dd6f109e422f5e8606167e1889c586e9f5505bded6b35371699e34fef54 综合管理平台/auth_guard.py
+e9b0f875106021fb3d58120ad8ebdd3e7d32135a4452fd8918c72ac6475f2bd3 综合管理平台/chart.umd.min.js
+ac585dfbc05ada0a6f6cedbea33f39b0979c09df5d3ffc420cd740de2938dafa 综合管理平台/digital_audit.css
+b3f4ba9ba3717f4422ad5deb3572e0f16d598974bf657c0e64a25d986c9e02f1 综合管理平台/digital_audit.html
+ab922341fb6dcc03be9d3dec23b703bbddaeef1a955f04987725b3c46175e59f 综合管理平台/digital_audit_service.py
+d0eeb3f1ddc4e81914e0c1b2bd9409c2669a1cd59832ad6f6983c61bf9c4acfd 综合管理平台/extract_service.py
+5e8b249a6e4674eb6486a7077902318b84ec1ac93f7beda0763f7c603d41b8f7 综合管理平台/js/boot.js
+a2cb6485684db60c688b4713f0caf3fe51aab785f60a187d8f6335083ad96a44 综合管理平台/js/core.js
+fd811b6ca424333362ce32d1940b665b19b051791bf9b3c81304a6024428c85f 综合管理平台/js/dashboard.js
+059c2e1a6bda29deb2b568455ff589f5704bba2c30c2d5dedc80fc986187658f 综合管理平台/js/data.js
+a690fa55c807683d7b9175e40521157669bb60eac341278ebcda20e366795f39 综合管理平台/js/extract.js
+ab3130ed8da5d4255adc822e03c33235edf6d954e547c39be0cb821ca4b52e59 综合管理平台/js/parse.js
+5b4c66086b1382ed8d4bae087a13525410232a2e56349de4b38021d82d502733 综合管理平台/js/rectification.js
+2b50e74c8a4e570a0158a90e084dfcb19f235d87f76af2a511a6b9caea5731fc 综合管理平台/js/rules.js
+74955c53c09df06a03481f9aec8e84df5a44003d4cb1de5ab5815c6599923804 综合管理平台/js/tasks.js
+cf35245a65ea507200571dcc3c37c7a51b1c59d98904fd527075aa54f9f2c466 综合管理平台/js/workflow.js
+5788295d44a9b88e8efba299c5108f85f244b5af9cbecf3eae4e15e0c28a12b1 综合管理平台/knowledge.html
+3e276c046662859edf795504e9adc35c0d99604ec56940b29549acde03b63006 综合管理平台/knowledge_service.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 综合管理平台/make_icon.py
+efa6a1fa771f0ecd57b99f23f6013d77170730b955b5c61d31c2e1835ebdd73d 综合管理平台/operator_context.py
+6e193eb9ddc071fbd1d37f032b28d75fa9c3eec683547d5b005ab5c1d2e01940 综合管理平台/parse_task_service.py
+091eeaf53989638005f86295bd9b85f361884c46352e6dac68c76269cd005cf5 综合管理平台/pdf_tools.py
+e4ab4db2d855d2498da5a001a6c2c014372d4663aa28b41fe73e15f4b8e00760 综合管理平台/policy_news_cache.json
+cc538ae17c46c7c9a0668d883fb27f93cfa6e8ff465965dc8028af047553bec8 综合管理平台/portal.html
+dfe9db9e53a5a3bcbcc242394e7b170e864d430a541afb9aa24f17f93af511a5 综合管理平台/portal_icon.ico
+7ed6ac752e6ffa848de8c0e76e4343e6fdba8a50724d3490be825d3862d60837 综合管理平台/portal_server.py
+ff251619d7cbf4b29d51cb5537e4c831bfc60c59772aebca48c2f852ead22493 综合管理平台/rectification_service.py
+2b98dde283539393d37e49f8c19fcfe15dd1e732c77eaadb5bb631853f121dcf 综合管理平台/requirements.txt
+1935711070bc261224f8f6c05da9f1a28ad996f0b1bccd70351d1cba9bd84358 综合管理平台/settings.html
+04f67298a9489c438d48213ed3a7f304d9190a5b490221f57de2b19a014de0bb 综合管理平台/shell.html
+34134068bd9e0a006ccd3375c9edd975edeba22a6c7ae5e163db07b8903606ba 综合管理平台/workflow_service.py
+085246aab8005d1e99ea850397a5ab99c9491af6cb6523348d9fa7217d94c330 综合管理平台/write_bat.py
+8543cb29ee32e2f147485def9e50b5615587d7feff661eda1f07169bea61341c 综合管理平台/启动平台.bat
+e3f99dd6f109e422f5e8606167e1889c586e9f5505bded6b35371699e34fef54 风险管理项目/auth_guard.py
+e9b0f875106021fb3d58120ad8ebdd3e7d32135a4452fd8918c72ac6475f2bd3 风险管理项目/chart.umd.min.js
+547f6882d45337933b6cb3cb01325f02afea5f68e40298ca6c42fd5d8ec6e800 风险管理项目/config.py
+b4fdda2a289ac5c8309fd314ead70fddbc7c366ac45dce2a4840b17c5b311168 风险管理项目/database.py
+6a2e30c075df1556eb49221e80f00b12b1b212ca323a140c9e5726aada202210 风险管理项目/main.py
+091eeaf53989638005f86295bd9b85f361884c46352e6dac68c76269cd005cf5 风险管理项目/pdf_tools.py
+2b98dde283539393d37e49f8c19fcfe15dd1e732c77eaadb5bb631853f121dcf 风险管理项目/requirements.txt
+66aa27fccc1e39fae0cf407d52d2e1f6253776b1865ce2b17442686d3d14ea06 风险管理项目/services/__init__.py
+7dc8a616bbbce92dd40bc7bb1ade4688bdd377d1a095b7f28d80d79c43aa5768 风险管理项目/services/ai_risk_service.py
+a44c225ac98e194422d9451c6a508b914a289f1c02420e6e044b206fd67093db 风险管理项目/services/analysis_service.py
+1ad8b66f37220568b6c6bdce94a335665cb25ba2e33416084916183b2e70493f 风险管理项目/services/feishu_service.py
+87f2900112ca4f34a7b366eac1a95705b51325cb6782d338161d5f4436593433 风险管理项目/services/import_service.py
+6f579f501ce50075c9a285c6c3363db8958ebef9f7e30e96cb1348275b50710b 风险管理项目/services/inspection_service.py
+2f589fb97cd50e7ecbb0cb19f85bfee4c6721d990b8d82786da5c393e787a282 风险管理项目/services/merge_service.py
+9a3539879587c1abae11febfc2985ac939755aeb1bfc028a43b7d98314785872 风险管理项目/services/risk_service.py
+5e422fba4558ef56cdfb2e119560d679b8ac652cf0b7ab411659486805824dbc 风险管理项目/templates/index.html
+679cff4f217cb504981300bcc0d37619fb1302ec509a0f9e20f3d57f19eee88c 风险管理项目/启动服务.bat
+3989d8b14e85eec63d3d44a1331db57c366204e407ddda8f0f6cbdacaa64f2be 风险管理项目/静默启动.vbs
diff --git a/TRADEMARK.md b/TRADEMARK.md
new file mode 100644
index 0000000..62e6b48
--- /dev/null
+++ b/TRADEMARK.md
@@ -0,0 +1,26 @@
+# 商标与品牌使用政策
+
+“医院智能审计管理平台”名称、Logo 及相关标识归南通一次元科技有限公司所有。
+
+## 允许
+
+- 在事实性描述中说明“基于医院智能审计管理平台修改”
+- 在文档、论文、案例中引用项目名称
+- 通过官方兼容性认证的版本使用“官方兼容”标识(需书面授权)
+
+## 不允许
+
+- 修改版继续使用官方名称、Logo 冒充官方版本
+- 使用官方名称注册公司、产品、域名、公众号,造成混淆
+- 暗示获得官方认证、官方支持而未获书面授权
+- 将修改版作为“官方原版”向医院销售
+
+## 修改版命名建议
+
+`医院智能审计管理平台(XX医院定制版)` 或独立产品名,并在显著位置注明:
+
+> 本版本基于医院智能审计管理平台修改,非官方发行版。
+
+## 认证与授权
+
+如需使用官方名称、Logo 或“官方兼容”标识,请联系维护方申请书面授权。
diff --git a/deploy/.dockerignore b/deploy/.dockerignore
new file mode 100644
index 0000000..3fd9150
--- /dev/null
+++ b/deploy/.dockerignore
@@ -0,0 +1,6 @@
+# 构建上下文不需要代码和数据(运行时通过 volume 挂载)
+app/
+# 文档与打包脚本不需要进镜像
+部署说明.md
+打包.py
+.env
diff --git a/deploy/.env.example b/deploy/.env.example
new file mode 100644
index 0000000..9d7bb63
--- /dev/null
+++ b/deploy/.env.example
@@ -0,0 +1,5 @@
+# 登录账号密码(必填;留空则首次启动生成随机管理员密码并打印在容器日志中)
+AUTH_USER=
+AUTH_PASSWORD=
+# 登录会话 Cookie 的签名密钥(必填;四个服务必须一致,建议随机 32 位以上)
+SESSION_SECRET=
diff --git a/deploy/Dockerfile b/deploy/Dockerfile
new file mode 100644
index 0000000..19ea50f
--- /dev/null
+++ b/deploy/Dockerfile
@@ -0,0 +1,31 @@
+# 医院审计科综合管理系统 - 运行时镜像
+# 说明:代码与数据不打进镜像,由 docker-compose 通过 ./app 目录挂载,
+# 这样更新文件、备份数据都直接在宿主机上完成。
+
+FROM python:3.12-slim
+
+ARG PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
+
+ENV PYTHONUNBUFFERED=1 \
+ PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUTF8=1 \
+ LANG=C.UTF-8 \
+ LC_ALL=C.UTF-8 \
+ TZ=Asia/Shanghai \
+ PIP_INDEX_URL=${PIP_INDEX_URL}
+
+# 安装 OCR 组件(扫描件 PDF 识别),apt 使用阿里云镜像源加速
+RUN sed -i 's|http://deb.debian.org|http://mirrors.aliyun.com|g; s|http://security.debian.org|http://mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources \
+ && apt-get update \
+ && apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-chi-sim \
+ libreoffice-writer libreoffice-calc libreoffice-impress fonts-noto-cjk \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+
+COPY requirements.txt /tmp/requirements.txt
+RUN pip install --no-cache-dir -r /tmp/requirements.txt \
+ && rm -f /tmp/requirements.txt
+
+# 实际启动命令由 docker-compose.yml 中每个服务的 command 指定
+CMD ["python", "--version"]
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
new file mode 100644
index 0000000..1336c9a
--- /dev/null
+++ b/deploy/docker-compose.yml
@@ -0,0 +1,97 @@
+# 医院审计科综合管理系统 - Docker Compose 编排
+# 四个服务共用同一镜像,代码与数据统一放在 ./app 目录下挂载到容器的 /app
+#
+# 端口:门户 8080 / 审计 8000 / 风险 8001 / 合同 8090
+# 启动:docker compose up -d --build
+# 停止:docker compose down
+# 日志:docker compose logs -f
+
+x-common: &common
+ image: hospital-audit-suite:1.0
+ restart: unless-stopped
+ volumes:
+ - ./app:/app
+ environment:
+ TZ: Asia/Shanghai
+ # 登录账号密码(在 .env 文件中配置)
+ AUTH_USER: ${AUTH_USER:?请在 .env 中设置 AUTH_USER}
+ AUTH_PASSWORD: ${AUTH_PASSWORD:?请在 .env 中设置 AUTH_PASSWORD}
+ # Cookie 会话签名密钥(四个服务必须一致)
+ SESSION_SECRET: ${SESSION_SECRET:?请在 .env 中设置 SESSION_SECRET}
+
+services:
+ # ===== 审计项目管理平台 :8000 =====
+ audit:
+ <<: *common
+ build:
+ context: .
+ dockerfile: Dockerfile
+ container_name: audit-suite-audit
+ working_dir: /app/审计项目管理平台
+ command: ["python", "start_audit_server.py"]
+ ports:
+ - "8000:8000"
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/api/health', timeout=3)"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 20s
+
+ # ===== 风险管理项目 :8001 =====
+ risk:
+ <<: *common
+ container_name: audit-suite-risk
+ working_dir: /app/风险管理项目
+ command: ["python", "main.py"]
+ ports:
+ - "8001:8001"
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8001/api/health', timeout=3)"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 20s
+
+ # ===== 合同审核管理平台 :8090 =====
+ contract:
+ <<: *common
+ container_name: audit-suite-contract
+ working_dir: /app/合同审核管理平台
+ command: ["python", "portal_server.py"]
+ ports:
+ - "8090:8090"
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8090/api/health', timeout=3)"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 20s
+
+ # ===== 综合管理平台(门户) :8080 =====
+ portal:
+ <<: *common
+ container_name: audit-suite-portal
+ working_dir: /app/综合管理平台
+ command: ["python", "portal_server.py"]
+ ports:
+ - "8080:8080"
+ environment:
+ TZ: Asia/Shanghai
+ AUTH_USER: ${AUTH_USER:?请在 .env 中设置 AUTH_USER}
+ AUTH_PASSWORD: ${AUTH_PASSWORD:?请在 .env 中设置 AUTH_PASSWORD}
+ SESSION_SECRET: ${SESSION_SECRET:?请在 .env 中设置 SESSION_SECRET}
+ # 容器内用服务名互相访问,门户的健康检查依赖这三个地址
+ AUDIT_URL: http://audit:8000
+ RISK_URL: http://risk:8001
+ CONTRACT_URL: http://contract:8090
+ depends_on:
+ - audit
+ - risk
+ - contract
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=3)"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 20s
diff --git a/deploy/requirements.txt b/deploy/requirements.txt
new file mode 100644
index 0000000..e8eed05
--- /dev/null
+++ b/deploy/requirements.txt
@@ -0,0 +1,11 @@
+fastapi==0.143.3
+uvicorn[standard]==0.54.0
+python-multipart==0.0.32
+python-docx==1.2.0
+pypdfium2==5.15.2
+Pillow
+openai==3.33.0
+openpyxl==3.1.5
+PyPDF2==3.0.1
+pytesseract==0.3.13
+mammoth==1.8.0
diff --git a/deploy/冒烟测试.py b/deploy/冒烟测试.py
new file mode 100644
index 0000000..855f901
--- /dev/null
+++ b/deploy/冒烟测试.py
@@ -0,0 +1,137 @@
+# -*- coding: utf-8 -*-
+"""审计管理平台冒烟测试。
+
+用法:
+ python deploy/冒烟测试.py
+ python deploy/冒烟测试.py --url http://your-server:8080 --user shenji --password '***'
+
+检查:登录(可选)、核心页面、核心接口、静态资源。返回码 0 表示全部通过。
+"""
+import argparse
+import json
+import sys
+
+try:
+ sys.stdout.reconfigure(encoding="utf-8")
+except Exception:
+ pass
+import urllib.error
+import urllib.parse
+import urllib.request
+import http.cookiejar
+
+
+PAGES = [
+ ("统一入口", "/"),
+ ("数字化审计", "/digital-audit"),
+ ("知识库", "/knowledge"),
+ ("系统设置", "/settings"),
+ ("旧门户", "/portal"),
+]
+
+APIS = [
+ ("健康检查", "/api/health"),
+ ("当前用户", "/api/me"),
+ ("平台状态", "/api/platform/status"),
+ ("驾驶舱", "/api/da/overview"),
+ ("待办中心", "/api/da/todo"),
+ ("规则库", "/api/da/rules"),
+ ("审计任务", "/api/da/tasks"),
+ ("整改统计", "/api/da/rectifications/stats"),
+ ("整改报表", "/api/da/rectifications/report?dimension=dept"),
+ ("整改组织分布", "/api/da/rectifications/map"),
+ ("OCR 任务", "/api/da/ocr/tasks"),
+ ("要素抽取任务", "/api/da/extract/tasks"),
+ ("审计作业统计", "/api/da/workflow/stats"),
+ ("解析记录", "/api/da/parsed"),
+ ("数据资源", "/api/da/datasources"),
+ ("分析模型", "/api/da/models"),
+]
+
+STATIC = [
+ ("数字化审计 core.js", "/static/js/core.js"),
+ ("数字化审计 boot.js", "/static/js/boot.js"),
+ ("数字化审计 CSS", "/static/digital_audit.css"),
+]
+
+
+def build_opener():
+ cj = http.cookiejar.CookieJar()
+ return urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
+
+
+def login(opener, base, user, password):
+ data = urllib.parse.urlencode({"username": user, "password": password, "next": "/"}).encode()
+ req = urllib.request.Request(base + "/api/login", data=data, method="POST")
+ try:
+ resp = opener.open(req, timeout=15)
+ return resp.status in (200, 303)
+ except urllib.error.HTTPError as e:
+ return e.code in (200, 303)
+
+
+def check(opener, url, expect_json=False):
+ try:
+ resp = opener.open(urllib.request.Request(url), timeout=20)
+ body = resp.read()
+ if resp.status != 200:
+ return False, f"HTTP {resp.status}"
+ if expect_json:
+ try:
+ json.loads(body.decode("utf-8"))
+ except Exception:
+ return False, "返回不是合法 JSON"
+ return True, f"200 / {len(body)} bytes"
+ except urllib.error.HTTPError as e:
+ return False, f"HTTP {e.code}"
+ except Exception as e:
+ return False, str(e)[:80]
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--url", default="http://127.0.0.1:8080")
+ parser.add_argument("--user", default="")
+ parser.add_argument("--password", default="")
+ args = parser.parse_args()
+ base = args.url.rstrip("/")
+ opener = build_opener()
+ failures = []
+
+ if args.user:
+ ok = login(opener, base, args.user, args.password)
+ print(("[OK]" if ok else "[FAIL]") + " 登录")
+ if not ok:
+ failures.append("登录")
+
+ print("\n== 页面 ==")
+ for name, path in PAGES:
+ ok, detail = check(opener, base + path)
+ print(("[OK]" if ok else "[FAIL]") + f" {name}: {detail}")
+ if not ok:
+ failures.append(name)
+
+ print("\n== 接口 ==")
+ for name, path in APIS:
+ ok, detail = check(opener, base + path, expect_json=True)
+ print(("[OK]" if ok else "[FAIL]") + f" {name}: {detail}")
+ if not ok:
+ failures.append(name)
+
+ print("\n== 静态资源 ==")
+ for name, path in STATIC:
+ ok, detail = check(opener, base + path)
+ print(("[OK]" if ok else "[FAIL]") + f" {name}: {detail}")
+ if not ok:
+ failures.append(name)
+
+ print("\n" + "=" * 40)
+ if failures:
+ print(f"冒烟测试失败 {len(failures)} 项:{'、'.join(failures)}")
+ return 1
+ print("冒烟测试全部通过")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/deploy/同步公共模块.py b/deploy/同步公共模块.py
new file mode 100644
index 0000000..e8e6e53
--- /dev/null
+++ b/deploy/同步公共模块.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+"""公共模块同步工具
+
+当前平台由四个独立 FastAPI 服务组成,公共模块统一放在 shared/ 目录维护,
+再同步到四个项目目录,避免出现“四份代码不一致”。
+
+用法:
+ python deploy/同步公共模块.py # 同步 shared/ 到四个项目
+ python deploy/同步公共模块.py --check # 只检查是否一致,不写入
+"""
+import argparse
+import hashlib
+import shutil
+import sys
+from pathlib import Path
+
+WORKSPACE = Path(__file__).resolve().parent.parent
+PROJECTS = ["综合管理平台", "审计项目管理平台", "风险管理项目", "合同审核管理平台"]
+SHARED_MODULES = ["auth_guard.py", "pdf_tools.py"]
+
+
+def md5(path: Path) -> str:
+ return hashlib.md5(path.read_bytes()).hexdigest()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--check", action="store_true", help="只检查不写入")
+ args = parser.parse_args()
+
+ shared_dir = WORKSPACE / "shared"
+ problems = 0
+ for module in SHARED_MODULES:
+ src = shared_dir / module
+ if not src.exists():
+ print(f"[错误] 缺少公共模块:shared/{module}")
+ problems += 1
+ continue
+ src_hash = md5(src)
+ for project in PROJECTS:
+ dst = WORKSPACE / project / module
+ if not dst.exists():
+ if args.check:
+ print(f"[缺失] {project}/{module}")
+ problems += 1
+ else:
+ shutil.copy2(src, dst)
+ print(f"[已创建] {project}/{module}")
+ continue
+ if md5(dst) == src_hash:
+ print(f"[一致] {project}/{module}")
+ continue
+ if args.check:
+ print(f"[不一致] {project}/{module}")
+ problems += 1
+ else:
+ shutil.copy2(src, dst)
+ print(f"[已同步] {project}/{module}")
+ if problems:
+ print(f"\n检查完成:发现 {problems} 处问题")
+ return 1
+ print("\n检查完成:公共模块全部一致")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/deploy/同步统一主题.py b/deploy/同步统一主题.py
new file mode 100644
index 0000000..717a548
--- /dev/null
+++ b/deploy/同步统一主题.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+"""统一嵌入主题同步工具
+
+把 shared/embed_theme.css 注入到各业务页面,替换原有的
+', re.S)
+SCRIPT_MARKER = 'id="platform-embed-script"'
+
+
+def build_block(extra: str) -> str:
+ theme = THEME_FILE.read_text(encoding="utf-8")
+ if extra:
+ theme += "\n/* 页面补充样式 */\n" + extra + "\n"
+ return '"
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--check", action="store_true")
+ args = parser.parse_args()
+
+ if not THEME_FILE.exists():
+ print("缺少 shared/embed_theme.css")
+ return 1
+ problems = 0
+ for rel, extra in PAGE_EXTRAS.items():
+ path = WORKSPACE / rel
+ if not path.exists():
+ print(f"[缺失] {rel}")
+ problems += 1
+ continue
+ raw = path.read_bytes()
+ bom = raw.startswith(b"\xef\xbb\xbf")
+ text = raw.decode("utf-8-sig")
+ if SCRIPT_MARKER not in text:
+ print(f"[缺少嵌入脚本] {rel}")
+ problems += 1
+ new_block = build_block(extra)
+ if STYLE_RE.search(text):
+ new_text = STYLE_RE.sub(lambda m: new_block, text, count=1)
+ else:
+ idx = text.rfind("
+
+
+")
+ if idx < 0:
+ print(f"[无法定位] {rel}")
+ problems += 1
+ continue
+ new_text = text[:idx] + new_block + "\n" + text[idx:]
+ if new_text == text:
+ print(f"[已是最新] {rel}")
+ continue
+ if args.check:
+ print(f"[需要更新] {rel}")
+ problems += 1
+ else:
+ path.write_bytes(new_text.encode("utf-8-sig" if bom else "utf-8"))
+ print(f"[已同步] {rel}")
+ if problems:
+ print(f"\n完成:发现 {problems} 处需要处理")
+ return 1
+ print("\n完成:统一嵌入主题全部一致")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/deploy/生成演示数据.py b/deploy/生成演示数据.py
new file mode 100644
index 0000000..513953e
--- /dev/null
+++ b/deploy/生成演示数据.py
@@ -0,0 +1,307 @@
+# -*- coding: utf-8 -*-
+"""生成合成演示数据包(C 阶段)。
+
+从现有数据库复制 schema,清空全部业务数据后写入虚构数据并 VACUUM,
+生成:
+ dist/医院智能审计管理平台-v1.0.0-demo-data.zip
+
+演示数据全部为虚构内容,不包含任何真实医院、患者、合同或人员信息。
+"""
+import argparse
+import hashlib
+import shutil
+import sqlite3
+import sys
+import tempfile
+import zipfile
+from pathlib import Path
+
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+WORKSPACE = Path(__file__).resolve().parent.parent
+DBS = {
+ "审计项目管理平台": WORKSPACE / "审计项目管理平台" / "audit_data.db",
+ "风险管理项目": WORKSPACE / "风险管理项目" / "risk_data.db",
+ "合同审核管理平台": WORKSPACE / "合同审核管理平台" / "contract.db",
+ "综合管理平台": WORKSPACE / "综合管理平台" / "digital_audit.db",
+}
+KEEP_TABLES = {
+ "综合管理平台": {"da_rules", "da_rule_categories", "da_models", "da_workflows"},
+}
+NOW = "2026-12-05 09:00:00"
+
+
+def backup_copy(src: Path, dst: Path):
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ with sqlite3.connect(str(src), timeout=15) as s, sqlite3.connect(str(dst), timeout=15) as d:
+ s.backup(d)
+
+
+def wipe(conn, keep_tables):
+ tables = [r[0] for r in conn.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
+ for t in tables:
+ if t in keep_tables:
+ continue
+ conn.execute(f'DELETE FROM "{t}"')
+ try:
+ conn.execute("DELETE FROM sqlite_sequence")
+ except sqlite3.Error:
+ pass
+ conn.commit()
+
+
+def insert(conn, table, **data):
+ cols = ",".join(data.keys())
+ marks = ",".join("?" for _ in data)
+ cur = conn.execute(f'INSERT INTO "{table}" ({cols}) VALUES ({marks})', tuple(data.values()))
+ return cur.lastrowid
+
+
+def seed_audit(conn):
+ cat1 = insert(conn, "categories", name="财务审计", description="演示分类", status="启用", created_at=NOW)
+ cat2 = insert(conn, "categories", name="采购审计", description="演示分类", status="启用", created_at=NOW)
+ p1 = insert(conn, "persons", name="张演示", department="审计科", role="审计员", contact="", created_at=NOW)
+ p2 = insert(conn, "persons", name="李示例", department="审计科", role="主审", contact="", created_at=NOW)
+ y1 = insert(conn, "years", year=2026, name="2026 年度审计计划(演示)", goal="演示数据",
+ budget=0, status="进行中", category_id=cat1, leader_id=p2, created_at=NOW)
+ projs = []
+ for i, (name, cat, status, leader) in enumerate([
+ ("示例市第一人民医院 2026 年度财务收支审计(演示)", cat1, "实施中", p2),
+ ("示例市第一人民医院 2026 年度采购专项审计(演示)", cat2, "进行中", p1),
+ ("示例医疗集团 2026 年度合同管理审计(演示)", cat1, "报告阶段", p2),
+ ], start=1):
+ pid = insert(conn, "projects", name=name, description="虚构的演示项目,仅用于功能体验。",
+ status=status, priority="P1", budget=0, risks="", start_date="2026-01-01T00:00:00.000+08:00",
+ end_date="2026-12-31T00:00:00.000+08:00", year_id=y1, category_id=cat,
+ leader_id=leader, created_at=NOW)
+ projs.append(pid)
+ insert(conn, "project_members", project_id=pid, person_id=leader)
+ s1 = insert(conn, "steps", name=name.split("(")[0] + " + 审前调查", status="已完成", priority="P1",
+ progress=100, deliverable="审前调查报告", remark="", start_date="2026-01-01T00:00:00.000+08:00",
+ end_date="2026-02-01T00:00:00.000+08:00", project_id=pid, leader_id=leader, created_at=NOW)
+ s2 = insert(conn, "steps", name=name.split("(")[0] + " + 现场实施", status="进行中", priority="P1",
+ progress=60, deliverable="审计工作底稿", remark="", start_date="2026-02-01T00:00:00.000+08:00",
+ end_date="2026-06-01T00:00:00.000+08:00", project_id=pid, leader_id=leader,
+ prev_step_id=s1, created_at=NOW)
+ docs = [
+ ("审计实施方案(演示)", "方案", "本方案为演示数据:审计目标、范围、重点、时间安排和人员分工。", "已完成", s2),
+ ("财务管理制度(演示)", "制度", "示例医院财务管理制度:预算、收支、采购、资产等内容均为虚构。", "已完成", s1),
+ ("采购合同样本(演示)", "合同", "示例采购合同:甲方向乙方采购医疗设备,合同金额为演示金额。", "已完成", s2),
+ ]
+ doc_ids = []
+ for title, dtype, content, status, step in docs:
+ doc_ids.append(insert(conn, "audit_docs", title=title, doc_type=dtype, content=content,
+ status=status, project_id=pid, step_id=step, created_at=NOW))
+ insert(conn, "analysis_results", doc_id=doc_ids[0], analysis_type="风险识别",
+ summary="演示分析结果:方案缺少后续跟踪安排,建议补充整改复查节点。",
+ risk_level="中", findings="1. 演示问题一;2. 演示问题二。",
+ suggestions="1. 补充整改复查;2. 明确责任人和时限。", raw_output="{}", created_at=NOW)
+ insert(conn, "analysis_results", doc_id=doc_ids[2], analysis_type="合同风险",
+ summary="演示分析结果:合同缺少验收条款,建议补充验收标准和付款节点。",
+ risk_level="高", findings="1. 缺少验收标准;2. 付款节点不明确。",
+ suggestions="补充验收条款和付款条件。", raw_output="{}", created_at=NOW)
+ space = insert(conn, "knowledge_spaces", space_id="demo-space-001", name="审计制度与模板(演示)", description="演示知识库",
+ space_type="内部", visibility="公开", created_at=NOW)
+ for title, content in [
+ ("内部审计工作制度(演示)", "这是虚构的演示制度文本,用于展示知识库阅读与检索。"),
+ ("审计报告模板(演示)", "演示模板:标题、背景、审计发现、整改建议、附件。"),
+ ("整改台账填写说明(演示)", "演示说明:问题描述、责任部门、整改期限、反馈、验收。"),
+ ]:
+ insert(conn, "knowledge_docs", space_id=space, space_name="审计制度与模板(演示)", title=title,
+ content=content, obj_type="docx", has_child=0, created_at=NOW)
+ insert(conn, "collection_items", url="https://example.com/demo-policy", title="演示政策文章",
+ content="演示采集内容,不代表任何真实政策。", source_name="示例来源", source_type="web",
+ category="政策法规", status="待整理", created_at=NOW, updated_at=NOW)
+ conn.commit()
+
+
+def seed_risk(conn):
+ depts = ["财务科", "采购管理科", "医学装备科"]
+ for i, d in enumerate(depts, 1):
+ insert(conn, "departments", dept_code=f"D{i:02d}", dept_name=d, created_at=NOW, updated_at=NOW)
+ for code, name in [("C1", "合规目标"), ("C2", "运营目标")]:
+ insert(conn, "coso_erm_categories", coso_code=code, coso_name=name, created_at=NOW, updated_at=NOW)
+ for code, name in [("T1", "收入管理"), ("T2", "采购管理")]:
+ insert(conn, "target_categories", cat_code=code, cat_name=name, created_at=NOW, updated_at=NOW)
+ ver = insert(conn, "risk_versions", year=2026, version_name="2026 演示风险库", description="虚构演示数据",
+ status="启用", created_at=NOW, updated_at=NOW)
+ risks = [
+ ("R-DEMO-001", "财务科", "采购付款未按合同约定节点执行,存在提前付款风险。", "高风险", "采购管理"),
+ ("R-DEMO-002", "采购管理科", "供应商准入资料不完整,未定期复核资质。", "中风险", "采购管理"),
+ ("R-DEMO-003", "医学装备科", "设备验收记录缺失,可能导致资产账实不符。", "中风险", "资产管理"),
+ ("R-DEMO-004", "财务科", "合同台账与财务付款记录未定期核对。", "高风险", "合同管理"),
+ ("R-DEMO-005", "采购管理科", "单一来源采购缺少论证材料。", "低风险", "采购管理"),
+ ]
+ item_ids = []
+ for i, (code, dept, desc, level, framework) in enumerate(risks, 1):
+ item_ids.append(insert(conn, "risk_items", version_id=ver, risk_code=f"{dept}/{code}",
+ department=dept, risk_no=code, risk_desc=desc, is_economic="是",
+ in_responsibility="是", has_regulation="是", probability_score=1,
+ impact_score=1, risk_total_score=1, framework=framework, risk_level=level,
+ risk_type="经济", target_category="运营", target_content=framework,
+ coso_erm_category="合规目标", created_at=NOW, updated_at=NOW))
+ insert(conn, "risk_assessments", risk_item_id=item_ids[-1], version_id=ver,
+ subjective_score=0.7, objective_score=0.7, combined_score=0.7,
+ final_risk_level=level, assessment_detail="演示评估", assessed_at=NOW)
+ insert(conn, "risk_unique_points", risk_no=code, risk_desc=desc, business_level="院级",
+ business_framework=framework, level_code=code, risk_number=i, created_at=NOW, updated_at=NOW)
+ report = insert(conn, "inspection_reports", year=2026, report_name="2026 年度检查报告(演示)",
+ report_date="2026-11-01", batch_no="DEMO-2026-001", total_identified=len(risks),
+ new_risks=len(risks), existing_matches=0, status="已完成", created_at=NOW)
+ for i, (code, dept, desc, level, framework) in enumerate(risks, 1):
+ insert(conn, "inspection_risk_data", year=2026, report_id=report, risk_no=code,
+ risk_desc=desc, department=dept, is_economic="是", survey_choice="B",
+ occurrence_count=i, occurrence_amount=10000 * i, remark="演示检查发现",
+ batch_no="DEMO-2026-001", report_name="2026 年度检查报告(演示)",
+ report_date="2026-11-01", status="已入库", created_at=NOW, updated_at=NOW,
+ subjective_score=0.7, combined_score=0.7, final_risk_level=level,
+ assessment_detail="演示评估")
+ insert(conn, "inspection_aggregated", year=2026, risk_no=code, risk_desc=desc, department=dept,
+ is_economic="是", occurrence_count=i, occurrence_amount=10000 * i,
+ final_risk_level=level, aggregated_at=NOW, subjective_score=0.7, combined_score=0.7)
+ conn.commit()
+
+
+def seed_contract(conn):
+ rows = [
+ ("医疗设备采购合同(演示).docx", "reviewed", "采购合同", "高",
+ "合同缺少验收标准和付款节点,建议补充。"),
+ ("信息系统运维服务合同(演示).docx", "reviewed", "服务合同", "中",
+ "服务范围描述较笼统,建议明确响应时限。"),
+ ("办公用品采购合同(演示).docx", "pending", "采购合同", "",
+ "演示数据,尚未审核。"),
+ ]
+ for i, (name, status, ctype, level, summary) in enumerate(rows, 1):
+ issues = "[]"
+ if level:
+ issues = ('[{"dimension":"演示维度","severity":"%s",'
+ '"description":"演示问题:条款描述不完整,仅用于功能演示。"}]' % level)
+ insert(conn, "contracts", name=name, file_path="", upload_date=NOW, status=status,
+ contract_type=ctype, risk_level=level, issues=issues, rectifications=None,
+ report_path="", summary=summary, reviewed_at=NOW if status == "reviewed" else None,
+ updated_at=NOW)
+ conn.commit()
+
+
+def seed_digital(conn):
+ # 清空任务/整改/日志/解析等演示数据;规则/分类/模型/流程保留
+ for table in ("da_rectifications", "da_rect_history", "da_tasks", "da_task_hits", "da_parsed_docs",
+ "da_ocr_tasks", "da_ocr_files", "da_extract_tasks", "da_extract_files",
+ "da_extract_results", "da_logs"):
+ conn.execute(f'DELETE FROM "{table}"')
+ conn.commit()
+ rects = [
+ ("DEMO-001", "采购合同缺少验收条款", "采购管理科", "高", "待派发", 30,
+ "补充验收标准、验收流程和付款节点。", "总院区", "张演示"),
+ ("DEMO-002", "设备验收记录不完整", "医学装备科", "中", "整改中", 15,
+ "补齐设备验收单,建立设备台账复核机制。", "东院区", "李示例"),
+ ("DEMO-003", "合同台账未定期核对", "财务科", "高", "已办结", -10,
+ "建立月度合同台账与付款记录核对机制。", "总院区", "王演示"),
+ ]
+ for i, (no, issue, dept, level, status, days, requirement, branch, owner) in enumerate(rects, 1):
+ rid = insert(conn, "da_rectifications", work_no=no, issue=issue, dept=dept, owner=owner,
+ level=level, priority=level, status=status, progress=100 if status == "已办结" else (50 if status == "整改中" else 0),
+ deadline="2026-12-31", requirement=requirement, branch=branch,
+ created_at=NOW, updated_at=NOW)
+ insert(conn, "da_rect_history", rect_id=rid, action="创建工单", from_status="", to_status="待派发",
+ comment="演示数据", operator="演示管理员", created_at=NOW)
+ if status != "待派发":
+ insert(conn, "da_rect_history", rect_id=rid, action="派发", from_status="待派发", to_status="整改中",
+ comment="演示派发", operator="演示管理员", created_at=NOW)
+ if status == "已办结":
+ insert(conn, "da_rect_history", rect_id=rid, action="评估到位", from_status="待评估", to_status="已办结",
+ comment="演示办结", operator="演示管理员", created_at=NOW)
+ task = insert(conn, "da_tasks", name="演示审计任务", task_type="综合审计", project_id=None,
+ project_name="示例市第一人民医院 2026 年度财务收支审计(演示)", rule_ids="[]",
+ status="已完成", progress=100, doc_total=6, hit_total=3, mode="正式运行",
+ created_at=NOW, finished_at=NOW, schedule_type="立即", run_count=1)
+ for i in range(1, 4):
+ insert(conn, "da_task_hits", task_id=task, rule_id=None, rule_name=f"演示规则 {i}",
+ risk_level="中" if i < 3 else "高", doc_id=None, doc_title="演示资料",
+ hit_type="keyword_exists", snippet="演示疑点片段", description="演示疑点:请结合真实业务复核。",
+ created_at=NOW)
+ insert(conn, "da_parsed_docs", filename="演示制度.txt", file_type="txt", mode="文本读取", status="已完成",
+ pages=1, char_count=60, preview="演示制度内容", content="这是虚构的演示制度文本,仅用于展示解析结果。",
+ created_at=NOW)
+ insert(conn, "da_logs", action="演示初始化", detail="已导入合成演示数据", operator="演示管理员", created_at=NOW)
+ conn.commit()
+
+
+SEEDS = {"审计项目管理平台": seed_audit, "风险管理项目": seed_risk,
+ "合同审核管理平台": seed_contract, "综合管理平台": seed_digital}
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--version", default="1.0.0")
+ parser.add_argument("--out", default=str(WORKSPACE / "dist"))
+ args = parser.parse_args()
+ outdir = Path(args.out)
+ outdir.mkdir(parents=True, exist_ok=True)
+ stage = Path(tempfile.mkdtemp(prefix="demo_stage_"))
+ demo_root = stage / f"医院智能审计管理平台-v{args.version}-demo-data"
+ demo_root.mkdir(parents=True)
+
+ for project, src in DBS.items():
+ if not src.exists():
+ print(f"[跳过] 缺少数据库:{src}")
+ continue
+ dst = demo_root / project / src.name
+ backup_copy(src, dst)
+ conn = sqlite3.connect(str(dst))
+ try:
+ wipe(conn, KEEP_TABLES.get(project, set()))
+ SEEDS[project](conn)
+ conn.execute("VACUUM")
+ ok = conn.execute("PRAGMA integrity_check").fetchone()[0]
+ if ok != "ok":
+ raise SystemExit(f"{project} 演示库校验失败:{ok}")
+ finally:
+ conn.close()
+ print(f"[生成] {project}/{src.name} {dst.stat().st_size/1024:.0f} KB")
+
+ readme = """# 医院智能审计管理平台 · 合成演示数据
+
+本目录内所有数据均为**虚构数据**,不包含任何真实医院、患者、合同或人员信息。
+
+## 导入方式
+
+1. 先备份现有数据库(生产环境务必先备份)。
+2. 停止服务。
+3. 把以下文件复制到对应目录(覆盖同名文件):
+ - `审计项目管理平台/audit_data.db`
+ - `风险管理项目/risk_data.db`
+ - `合同审核管理平台/contract.db`
+ - `综合管理平台/digital_audit.db`
+4. 启动服务。
+5. 首次启动后如提示用户库为空,按安装文档设置管理员账号。
+
+注意:仅建议在演示/测试环境导入,不要覆盖生产数据。
+"""
+ (demo_root / "README.md").write_text(readme, encoding="utf-8")
+
+ manifest = []
+ for p in sorted(demo_root.rglob("*")):
+ if p.is_file():
+ manifest.append(f"{hashlib.sha256(p.read_bytes()).hexdigest()} {p.relative_to(demo_root).as_posix()}")
+ (demo_root / "SHA256SUMS").write_text("\n".join(manifest) + "\n", encoding="utf-8")
+
+ zip_path = outdir / f"医院智能审计管理平台-v{args.version}-demo-data.zip"
+ if zip_path.exists():
+ zip_path.unlink()
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
+ for p in sorted(demo_root.rglob("*")):
+ if p.is_file():
+ zf.write(p, p.relative_to(demo_root.parent).as_posix())
+ digest = hashlib.sha256(zip_path.read_bytes()).hexdigest()
+ (outdir / "SHA256SUMS-demo.txt").write_text(f"{digest} {zip_path.name}\n", encoding="utf-8")
+ shutil.rmtree(stage, ignore_errors=True)
+ print(f"已生成:{zip_path}")
+ print(f"SHA256:{digest}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/deploy/自检.py b/deploy/自检.py
new file mode 100644
index 0000000..16b2dc2
--- /dev/null
+++ b/deploy/自检.py
@@ -0,0 +1,257 @@
+# -*- coding: utf-8 -*-
+"""项目自检脚本:部署前/提交前统一检查,避免把低级错误带到线上。
+
+检查项:
+1. 四个项目 + shared 的 Python 文件语法编译
+2. 公共模块(auth_guard.py)是否与 shared 一致
+3. 关键 HTML 页面是否包含统一嵌入样式、统一入口 shell.html 是否存在
+4. 前端内联 JS 语法检查(需要本机 node;没有则跳过并提示)
+5. 数据库文件是否存在、是否可打开
+6. 可选:--url 检查线上健康接口和统一入口
+
+用法:
+ python deploy/自检.py
+ python deploy/自检.py --url http://your-server
+"""
+import argparse
+import hashlib
+import os
+import re
+import shutil
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import urllib.request
+from pathlib import Path
+
+WORKSPACE = Path(__file__).resolve().parent.parent
+PROJECTS = ["综合管理平台", "审计项目管理平台", "风险管理项目", "合同审核管理平台"]
+EMBED_PAGES = [
+ "审计项目管理平台/templates/index.html",
+ "风险管理项目/templates/index.html",
+ "合同审核管理平台/index.html",
+ "综合管理平台/knowledge.html",
+ "综合管理平台/settings.html",
+ "综合管理平台/digital_audit.html",
+]
+DATABASES = [
+ "审计项目管理平台/audit_data.db",
+ "风险管理项目/risk_data.db",
+ "合同审核管理平台/contract.db",
+]
+SKIP_DIRS = {".venv", "__pycache__", "backups", "node_modules", ".git"}
+
+failures = []
+warnings = []
+
+
+def fail(msg):
+ failures.append(msg)
+ print(f" [失败] {msg}")
+
+
+def warn(msg):
+ warnings.append(msg)
+ print(f" [提示] {msg}")
+
+
+def ok(msg):
+ print(f" [通过] {msg}")
+
+
+def check_python_syntax():
+ print("\n1. Python 语法检查")
+ count = 0
+ targets = list(WORKSPACE.glob("shared/*.py"))
+ for project in PROJECTS:
+ for path in (WORKSPACE / project).rglob("*.py"):
+ if SKIP_DIRS.intersection(path.parts):
+ continue
+ targets.append(path)
+ for path in targets:
+ try:
+ raw = path.read_bytes()
+ source = None
+ for enc in ("utf-8-sig", "utf-8", "gbk", "gb18030"):
+ try:
+ source = raw.decode(enc)
+ break
+ except Exception:
+ continue
+ if source is None:
+ warn(f"{path.relative_to(WORKSPACE)} 编码无法识别,跳过")
+ continue
+ compile(source, str(path), "exec")
+ count += 1
+ except SyntaxError as e:
+ fail(f"{path.relative_to(WORKSPACE)} 语法错误:{e}")
+ ok(f"{count} 个 Python 文件编译通过")
+
+
+def check_public_modules():
+ print("\n2. 公共模块一致性")
+ src = WORKSPACE / "shared" / "auth_guard.py"
+ if not src.exists():
+ fail("缺少 shared/auth_guard.py")
+ return
+ src_hash = hashlib.md5(src.read_bytes()).hexdigest()
+ for project in PROJECTS:
+ dst = WORKSPACE / project / "auth_guard.py"
+ if not dst.exists():
+ fail(f"{project}/auth_guard.py 缺失")
+ elif hashlib.md5(dst.read_bytes()).hexdigest() != src_hash:
+ fail(f"{project}/auth_guard.py 与 shared 不一致(执行 deploy/同步公共模块.py 修复)")
+ else:
+ ok(f"{project}/auth_guard.py 一致")
+
+
+def check_pages():
+ print("\n3. 统一入口与嵌入页面")
+ shell = WORKSPACE / "综合管理平台" / "shell.html"
+ if shell.exists():
+ ok("统一入口 shell.html 存在")
+ else:
+ fail("缺少综合管理平台/shell.html")
+ for rel in EMBED_PAGES:
+ path = WORKSPACE / rel
+ if not path.exists():
+ fail(f"缺少页面:{rel}")
+ continue
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ if "platform-embed-style" not in text:
+ fail(f"{rel} 缺少统一嵌入样式(platform-embed-style)")
+ elif "shared/embed_theme.css" not in text:
+ fail(f"{rel} 嵌入样式不是统一主题来源(执行 deploy/同步统一主题.py)")
+ elif "portalTopBack" not in text:
+ warn(f"{rel} 未看到返回门户隐藏规则")
+ else:
+ ok(f"{rel} 统一嵌入主题正常")
+
+
+def node_path():
+ for name in ("node", "node.exe"):
+ path = shutil.which(name)
+ if path:
+ return path
+ return None
+
+
+def check_js():
+ print("\n4. 前端 JS 语法")
+ node = node_path()
+ if not node:
+ warn("未找到 node,跳过 JS 语法检查")
+ return
+ temp = Path(tempfile.gettempdir()) / "_platform_js_check.js"
+ checked = 0
+ for rel in EMBED_PAGES + ["综合管理平台/shell.html"]:
+ path = WORKSPACE / rel
+ if not path.exists():
+ continue
+ html = path.read_text(encoding="utf-8", errors="ignore")
+ for block in re.findall(r"", html, re.S):
+ if not block.strip():
+ continue
+ temp.write_text(block, encoding="utf-8")
+ r = subprocess.run([node, "--check", str(temp)], capture_output=True, text=True)
+ if r.returncode != 0:
+ fail(f"{rel} 内联 JS 语法错误:{r.stderr.strip()[:200]}")
+ checked += 1
+ ok(f"检查 {checked} 个内联脚本块")
+
+
+def check_static_assets():
+ print("\n4.1 静态资源(数字化审计拆分后)")
+ html_path = WORKSPACE / "综合管理平台" / "digital_audit.html"
+ css_path = WORKSPACE / "综合管理平台" / "digital_audit.css"
+ js_dir = WORKSPACE / "综合管理平台" / "js"
+ for path in (css_path, html_path):
+ if not path.exists():
+ fail(f"缺少静态资源:{path.relative_to(WORKSPACE)}")
+ else:
+ ok(f"{path.relative_to(WORKSPACE)} 存在")
+ if not js_dir.is_dir():
+ fail("缺少静态资源目录:综合管理平台/js")
+ return
+ text = html_path.read_text(encoding="utf-8", errors="ignore")
+ if "/static/digital_audit.css" not in text:
+ fail("digital_audit.html 未引用 /static/digital_audit.css")
+ modules = sorted(js_dir.glob("*.js"))
+ if not modules:
+ fail("综合管理平台/js 下没有前端模块")
+ return
+ for m in modules:
+ if f"/static/js/{m.name}" not in text:
+ fail(f"digital_audit.html 未引用前端模块 {m.name}")
+ if "/static/digital_audit.js" in text:
+ fail("digital_audit.html 仍引用已拆分旧文件 digital_audit.js")
+ node = node_path()
+ checked = 0
+ if node:
+ for m in modules:
+ r = subprocess.run([node, "--check", str(m)], capture_output=True, text=True)
+ if r.returncode != 0:
+ fail(f"{m.name} 语法错误:{r.stderr.strip()[:200]}")
+ else:
+ checked += 1
+ ok(f"{checked} 个前端模块语法通过")
+
+
+def check_databases():
+ print("\n5. 数据库文件")
+ for rel in DATABASES:
+ path = WORKSPACE / rel
+ if not path.exists():
+ warn(f"{rel} 不存在(本地可能未下载数据,不影响代码自检)")
+ continue
+ try:
+ conn = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)
+ tables = conn.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table'").fetchone()[0]
+ conn.close()
+ ok(f"{rel} 可打开,{tables} 张表")
+ except Exception as e:
+ fail(f"{rel} 无法打开:{e}")
+
+
+def check_url(base):
+ print(f"\n6. 线上检查:{base}")
+ paths = ["/api/health", "/api/health/audit", "/api/health/risk", "/api/health/contract"]
+ for p in paths:
+ try:
+ with urllib.request.urlopen(base.rstrip("/") + p, timeout=8) as resp:
+ if resp.status == 200:
+ ok(f"{p} 200")
+ else:
+ fail(f"{p} 返回 {resp.status}")
+ except Exception as e:
+ fail(f"{p} 无法访问:{e}")
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--url", help="可选:线上服务根地址,如 http://your-server:8080")
+ args = parser.parse_args()
+
+ print("=" * 60)
+ print("审计管理平台 · 项目自检")
+ print("=" * 60)
+ check_python_syntax()
+ check_public_modules()
+ check_pages()
+ check_js()
+ check_static_assets()
+ check_databases()
+ if args.url:
+ check_url(args.url)
+
+ print("\n" + "=" * 60)
+ if failures:
+ print(f"自检失败:{len(failures)} 项错误,{len(warnings)} 项提示")
+ return 1
+ print(f"自检通过:0 项错误,{len(warnings)} 项提示")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/docs/Git仓库初始化指南.md b/docs/Git仓库初始化指南.md
new file mode 100644
index 0000000..c96a288
--- /dev/null
+++ b/docs/Git仓库初始化指南.md
@@ -0,0 +1,60 @@
+# Git 仓库初始化指南
+
+当前项目还没有 Git 仓库。建议先在内部建仓,再发布到 Gitea/GitHub/Gitee。
+
+## 一、生成干净源码包
+
+```powershell
+python deploy/准备开源源码包.py --version 1.0.0
+```
+
+产物:
+
+- `dist/医院智能审计管理平台-v1.0.0-src.zip`
+- `dist/SHA256SUMS.txt`
+
+脚本会自动扫描服务器 IP、固定口令、私钥、API Key、数据库/上传文件,发现则中止。
+
+## 二、初始化为 Git 仓库
+
+解压源码包后,在仓库根目录执行:
+
+```bash
+git init -b main
+git config user.name "你的名字"
+git config user.email "你的邮箱"
+git add .
+git commit -s -m "chore: initial open-source baseline v1.0.0"
+```
+
+> `-s` 会加入 DCO 签名,表示你确认有权提交这些代码。
+
+## 三、推送到 Gitea/Forgejo
+
+```bash
+git remote add origin http://your-git-server/upstream/audit-platform.git
+git push -u origin main
+git tag -a v1.0.0 -m "v1.0.0"
+git push origin v1.0.0
+```
+
+建议组织:
+
+```
+upstream/audit-platform 官方基线(受保护分支 main)
+hospitals/<医院名>/audit-platform 医院 fork
+```
+
+## 四、保护与 CI
+
+- `main` 分支保护:禁止直接 push,必须 PR + 评审 + CI
+- CI 必跑:`python deploy/自检.py`、`python deploy/冒烟测试.py`
+- 发布 tag 必须签名(GPG/SSH)
+- 开启依赖漏洞扫描与 secrets 扫描
+
+## 五、发布前
+
+1. 完成 `docs/开源合规清单.md`(PyMuPDF 必须处理)
+2. 确认仓库无真实医院数据与密钥
+3. 生成 SBOM 与 SHA256
+4. 准备首个 release 说明
diff --git a/docs/合成演示数据说明.md b/docs/合成演示数据说明.md
new file mode 100644
index 0000000..4f150d8
--- /dev/null
+++ b/docs/合成演示数据说明.md
@@ -0,0 +1,34 @@
+# 合成演示数据说明
+
+演示数据包:
+
+- `dist/医院智能审计管理平台-v1.0.0-demo-data.zip`
+
+内容为虚构数据,不包含真实医院、患者、合同或人员信息。
+
+## 包含的数据库
+
+- `审计项目管理平台/audit_data.db`
+- `风险管理项目/risk_data.db`
+- `合同审核管理平台/contract.db`
+- `综合管理平台/digital_audit.db`
+
+演示数据包含:3 个虚构审计项目、9 份审计资料、6 条分析结果、5 条风险点、5 条检查风险、
+3 份合同、3 个整改工单、1 个审计任务及疑点、知识库文档等。
+
+## 导入方式
+
+1. 备份现有数据库。
+2. 停止服务。
+3. 将演示包内数据库复制到对应项目目录,覆盖同名文件。
+4. 启动服务。
+
+仅建议在演示/测试环境导入,不要覆盖生产数据。
+
+## 重新生成
+
+```powershell
+python deploy/生成演示数据.py
+```
+
+生成脚本会读取当前数据库 schema,清空业务数据后写入虚构数据,并执行 VACUUM 与完整性检查。
diff --git a/docs/平台建设与协作方案.md b/docs/平台建设与协作方案.md
new file mode 100644
index 0000000..66fc5fc
--- /dev/null
+++ b/docs/平台建设与协作方案.md
@@ -0,0 +1,69 @@
+# 平台建设与协作方案(草案)
+
+## 一、定位
+
+不是“医院版 GitHub”,而是:
+
+> 医院智能审计管理平台的官方基线 + 医院分支治理 + 改进回流平台
+
+## 二、许可证与商业模型
+
+- 核心代码:Apache License 2.0(PyMuPDF 已替换为 PyPDF2 + pypdfium2,见 `开源合规清单.md`)
+- 商标:保留“医院智能审计管理平台”名称与 Logo,修改版必须注明非官方
+- 贡献:DCO(`git commit -s`);如未来做商业双许可,再评估 CLA
+- 收入:实施部署、数据迁移、接口对接、等保/信创、年度升级保障、认证实施商、Open Core 高级模块
+- 不靠卖源码收费,靠“可运行、可升级、可合规”收费
+
+## 三、平台架构
+
+```
+品牌门户(FastAPI)
+ ├─ 官方版本 / 下载 / 更新日志
+ ├─ 医院空间:fork、版本、升级状态、对比官方
+ ├─ 改进集市:被采纳的补丁/插件
+ ├─ 兼容性矩阵:版本 ↔ schema ↔ 插件
+ └─ 安全公告 / 支持
+ │ OAuth / API
+Gitea / Forgejo(代码托管 + PR + CI)
+ ├─ upstream/audit-platform
+ └─ hospitals/医院A、医院B...
+ │
+CI Runner(测试、构建镜像、离线升级包、签名、SBOM)
+```
+
+## 四、离线协作流程(关键)
+
+1. 官方发布源码包 + 镜像 tar + 离线升级包(含迁移脚本、校验和、回滚说明)
+2. 医院本地 Git 管理定制,尽量只改配置/插件/模板
+3. 医院导出补丁或 git bundle,通过 U 盘/邮件/网盘交给维护方
+4. 平台导入补丁 → 自动对比 → CI → 评审 → 合并进官方
+5. 医院可随时回到官方基线,配置单独迁移
+
+## 五、扩展点优先级
+
+1. 规则插件(规则引擎已具备基础)
+2. 报表/底稿模板
+3. 数据源连接器(HIS/HRP/财务)
+4. 认证对接(LDAP/AD/院内 SSO)
+5. 主题/Logo/首页
+6. 审批流节点
+
+每个插件需要 manifest:适用版本、依赖、作者、许可证。
+
+## 六、90 天路线
+
+| 阶段 | 目标 |
+|------|------|
+| 第 1-2 周 | 开源就绪:许可证、NOTICE、README、CI、干净源码包、演示数据 |
+| 第 3-4 周 | 数据库迁移版本化、`auditctl` 升级/回滚、离线升级包 |
+| 第 5-6 周 | Gitea + 门户 MVP:官方版本、医院空间、改进集市 |
+| 第 7-8 周 | 2-3 家医院试点 fork → 补丁 → 官方合并 → 升级闭环 |
+| 第 9-12 周 | 插件规范、插件市场、认证实施商、安全公告 |
+
+## 七、风险
+
+- 医院改散 → 配置/插件优先 + LTS + 兼容矩阵 + 升级工具
+- 支持量爆炸 → 只支持官方基线和认证插件;非标改造转认证实施商
+- 医院不愿贡献 → 荣誉榜、联合署名、官方认证、改进奖励
+- 数据泄露 → 平台不收患者数据;合成演示数据;提交前扫描
+- 安全漏洞 → 私下披露、签名发布、依赖扫描
diff --git a/docs/开源合规清单.md b/docs/开源合规清单.md
new file mode 100644
index 0000000..9f88191
--- /dev/null
+++ b/docs/开源合规清单.md
@@ -0,0 +1,53 @@
+# 开源合规清单(发布前必须完成)
+
+> 本文档不是法律意见。正式对外发布前,请由律师/法务复核许可证、CLA/DCO、商标与出口管制事项。
+
+## 一、PyMuPDF 许可证问题(已处理)
+
+原实现依赖 PyMuPDF(AGPL-3.0 或商业许可),与 Apache-2.0 发布存在冲突。
+
+现已替换为:
+
+- 文本提取:PyPDF2(BSD-3-Clause)
+- PDF 页面渲染:pypdfium2(Apache-2.0,内置 PDFium BSD-3-Clause)
+- 图像处理:Pillow(HPND)
+
+替换后需回归验证:OCR 预览、扫描件 OCR、合同/知识库 PDF 解析、页面预览。
+
+发布前仍需确认 `requirements.txt` 与镜像中不再包含 PyMuPDF。
+
+## 二、其他第三方组件
+
+| 组件 | 许可证 | 处理建议 |
+|------|--------|----------|
+| FastAPI / Pydantic / python-docx / openpyxl / Chart.js | MIT | 保留版权声明 |
+| Uvicorn / Starlette / PyPDF2 | BSD-3-Clause | 保留版权声明 |
+| python-multipart / openai | Apache-2.0 | 保留 NOTICE |
+| Tesseract OCR | Apache-2.0 | 作为独立系统组件,部署时安装 |
+| LibreOffice | MPL-2.0 | 作为独立进程调用,保留许可证说明 |
+| Noto CJK 字体 | OFL-1.1 | 保留字体许可证 |
+| Pillow / pytesseract | HPND / MIT | 如实际使用需列入 NOTICE |
+
+## 三、发布前检查项
+
+- [ ] 仓库无 `*.db`、`uploads/`、`合同/`、`报告/`、`.env`、`settings.json`、`.auth_override.json`
+- [ ] 无真实医院名称、患者信息、合同金额、人员姓名
+- [ ] 无服务器 IP、SSH 密钥、API Key、密码
+- [ ] `LICENSE`、`NOTICE`、第三方许可证齐全
+- [ ] 生成 SBOM(软件物料清单)
+- [ ] 确定 DCO 或 CLA 方案
+- [x] 确认 requirements/镜像中无 PyMuPDF(已验证:fitz=False, pypdfium2=True)
+- [ ] 商标政策已发布
+- [ ] 安全披露渠道已填写
+- [ ] 演示数据为合成数据
+- [ ] 离线升级包带校验和/签名
+- [ ] 出口管制/密码合规自查(如涉及加密通信)
+
+## 四、建议发布流程
+
+1. 法务审核许可证与依赖
+2. 代码扫描(secrets、真实数据、硬编码 IP)
+3. 在内部 Git 仓库打 tag(如 `v1.0.0`)
+4. 生成干净源码包 + SHA256 + SBOM
+5. 发布到 Gitea/GitHub/Gitee 镜像
+6. 同步发布离线升级包与安装文档
diff --git a/docs/离线发布与升级指南.md b/docs/离线发布与升级指南.md
new file mode 100644
index 0000000..0be1523
--- /dev/null
+++ b/docs/离线发布与升级指南.md
@@ -0,0 +1,76 @@
+# 离线发布与升级指南(医院内网)
+
+医院大多为内网离线环境,平台应按“在线发布 + 离线交付 + 补丁交换”设计。
+
+## 一、发布物
+
+每次发版提供:
+
+1. **干净源码包**:不含数据库、上传文件、合同、报告、密钥
+2. **Docker 镜像包**:`docker save` 生成的 tar,可在内网导入
+3. **离线升级包**:
+ - 新版本代码
+ - 数据库迁移脚本
+ - 配置模板变更说明
+ - 回滚脚本
+ - `SHA256SUMS` 与签名
+ - 升级说明(前置检查、备份、步骤、验证)
+4. **兼容性矩阵**:官方版本 ↔ 数据库 schema ↔ 插件版本
+
+## 二、版本策略
+
+- 语义化版本:`MAJOR.MINOR.PATCH`
+- 每年至少一个 LTS 版本,医院可锁定 LTS
+- 补丁版本只修缺陷和安全问题,不改变数据结构
+
+## 三、医院升级流程
+
+1. 备份数据库与上传文件
+2. 校验升级包 SHA256/签名
+3. 停止服务
+4. 应用代码与迁移脚本
+5. 启动并执行健康检查
+6. 验证核心功能(登录、项目、资料、规则、整改)
+7. 失败则按回滚脚本恢复
+
+升级工具建议实现为 `auditctl`:
+
+```bash
+auditctl upgrade --check # 检查版本与兼容性
+auditctl upgrade --backup # 备份数据库与文件
+auditctl upgrade --apply # 应用升级包
+auditctl upgrade --rollback # 回滚
+```
+
+## 四、医院定制与补丁回流
+
+### 医院侧
+
+- 以官方 tag 为 upstream,本地 Git 管理定制
+- 定制尽量放在配置、插件、模板目录,避免改核心
+- 需要贡献时导出补丁:
+
+```bash
+git format-patch upstream/main --stdout > hospital-improvement.patch
+# 或
+git bundle create hospital-improvement.bundle upstream/main..HEAD
+```
+
+### 平台侧
+
+- 导入补丁/bundle,自动创建分支与对比
+- 检查是否包含数据/密钥/医院敏感信息
+- 通过 CI 后进入评审
+- 通用改进合并进官方;医院专属改动保留在私有分支
+
+## 五、回退到官方版本
+
+- 保留官方镜像 tag 与数据库备份
+- 提供 `auditctl reset --official vX.Y.Z`(需先备份)
+- 配置与插件单独迁移,避免覆盖医院配置
+
+## 六、数据安全
+
+- 平台只接收代码、补丁、脱敏日志
+- 禁止上传患者数据、合同原文、报告、数据库
+- 离线包不带任何真实数据
diff --git a/shared/auth_guard.py b/shared/auth_guard.py
new file mode 100644
index 0000000..4ed609a
--- /dev/null
+++ b/shared/auth_guard.py
@@ -0,0 +1,553 @@
+# -*- coding: utf-8 -*-
+"""四套系统共享的登录会话校验(Cookie + HMAC 签名)
+
+设计:
+- 登录页在综合门户(8080 端口)的 /login
+- 登录成功后写一个 HMAC 签名的 Cookie(作用域是主机,浏览器对同一 IP 的不同端口共享)
+- 审计(8000)/风险(8001)/合同(8090) 校验同一个 Cookie,所以登录一次即可访问四个系统
+- 同时保留 HTTP Basic 兼容,便于脚本和系统内部调用(如门户代理合同接口)
+"""
+
+import os
+import base64
+import hashlib
+import hmac
+import json
+import time
+import secrets
+import sqlite3
+import datetime
+from urllib.parse import quote, urlparse
+
+from fastapi.responses import JSONResponse, RedirectResponse
+
+AUTH_USER = os.getenv("AUTH_USER", "")
+AUTH_PASSWORD = os.getenv("AUTH_PASSWORD", "")
+SESSION_SECRET = os.getenv("SESSION_SECRET", "")
+
+SESSION_COOKIE = "audit_session"
+SESSION_MAX_AGE = 12 * 3600 # 12 小时
+
+MAX_FAILS = 10
+FAIL_WINDOW_SECONDS = 600
+
+# 门户登录地址(默认按访问的 Host 推导,指向 8080 端口)
+PORTAL_LOGIN_URL = os.getenv("PORTAL_LOGIN_URL", "")
+
+ENABLED = bool(AUTH_USER and AUTH_PASSWORD and SESSION_SECRET)
+
+_FAILS = {}
+
+
+def _b64e(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _b64d(text: str) -> bytes:
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
+
+
+def _make_token(claims: dict) -> str:
+ payload = json.dumps(
+ {"u": claims.get("username", ""), "d": claims.get("display_name", ""),
+ "r": claims.get("role", ""), "p": claims.get("permissions", []),
+ "exp": int(time.time()) + SESSION_MAX_AGE},
+ separators=(",", ":"),
+ ).encode("utf-8")
+ sig = hmac.new(SESSION_SECRET.encode("utf-8"), payload, hashlib.sha256).digest()
+ return _b64e(payload) + "." + _b64e(sig)
+
+
+def session_token(username: str) -> str:
+ """兼容旧调用:仅带用户名的会话令牌。"""
+ return _make_token({"username": username})
+
+
+def session_token_for(claims: dict) -> str:
+ """带角色/权限的会话令牌。"""
+ return _make_token(claims or {})
+
+
+def session_claims(token: str):
+ if not token or token.count(".") != 1:
+ return None
+ p64, s64 = token.split(".", 1)
+ try:
+ payload = _b64d(p64)
+ sig = _b64d(s64)
+ except Exception:
+ return None
+ expected = hmac.new(SESSION_SECRET.encode("utf-8"), payload, hashlib.sha256).digest()
+ if not hmac.compare_digest(sig, expected):
+ return None
+ try:
+ data = json.loads(payload)
+ except Exception:
+ return None
+ if int(data.get("exp", 0)) < time.time():
+ return None
+ return data
+
+
+def session_user(token: str):
+ data = session_claims(token)
+ return data.get("u") if data else None
+
+
+def has_permission(claims, key: str) -> bool:
+ if not claims:
+ return False
+ perms = claims.get("p") or claims.get("permissions") or []
+ if isinstance(perms, str):
+ try:
+ perms = json.loads(perms)
+ except Exception:
+ perms = [perms]
+ return "*" in perms or key in perms
+
+
+# ===== 密码覆盖文件(在系统设置里修改密码后写入,四套系统共享) =====
+AUTH_OVERRIDE_FILE = os.getenv(
+ "AUTH_OVERRIDE_FILE",
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".auth_override.json"),
+)
+_OVERRIDE_CACHE = {"mtime": None, "data": None}
+
+
+def _load_override():
+ try:
+ st = os.stat(AUTH_OVERRIDE_FILE)
+ except Exception:
+ return None
+ if _OVERRIDE_CACHE["mtime"] == st.st_mtime:
+ return _OVERRIDE_CACHE["data"]
+ try:
+ with open(AUTH_OVERRIDE_FILE, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ except Exception:
+ return None
+ _OVERRIDE_CACHE["mtime"] = st.st_mtime
+ _OVERRIDE_CACHE["data"] = data
+ return data
+
+
+# ===== 多用户 / 角色权限(users.db 四套系统共享,唯一用户库) =====
+USERS_DB = os.getenv(
+ "USERS_DB",
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "综合管理平台", "users.db"),
+)
+
+DEFAULT_ROLES = [
+ ("admin", "系统管理员", ["*"]),
+ ("auditor", "审计人员", ["home", "digital", "audit", "risk", "knowledge"]),
+ ("contract", "合同管理员", ["home", "contract", "knowledge"]),
+ ("viewer", "只读用户", ["home", "knowledge"]),
+]
+
+
+def _now():
+ return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+
+def _users_conn(create=False):
+ if not create and not os.path.exists(USERS_DB):
+ return None
+ if create:
+ os.makedirs(os.path.dirname(USERS_DB), exist_ok=True)
+ conn = sqlite3.connect(USERS_DB, timeout=10)
+ conn.row_factory = sqlite3.Row
+ if create:
+ conn.executescript("""
+ CREATE TABLE IF NOT EXISTS roles (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ code TEXT UNIQUE, name TEXT, permissions TEXT, created_at TEXT
+ );
+ CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT UNIQUE, display_name TEXT,
+ password_hash TEXT, salt TEXT, role_id INTEGER, role_code TEXT,
+ status TEXT DEFAULT '启用', created_at TEXT, last_login TEXT
+ );
+ """)
+ conn.commit()
+ return conn
+
+
+def _hash_password(password, salt_hex=None):
+ salt = bytes.fromhex(salt_hex) if salt_hex else secrets.token_bytes(16)
+ digest = hashlib.pbkdf2_hmac("sha256", (password or "").encode("utf-8"), salt, 200000)
+ return salt.hex(), digest.hex()
+
+
+def _verify_password(password, salt_hex, expected_hash):
+ try:
+ salt = bytes.fromhex(salt_hex)
+ digest = hashlib.pbkdf2_hmac("sha256", (password or "").encode("utf-8"), salt, 200000)
+ return hmac.compare_digest(digest.hex(), expected_hash)
+ except Exception:
+ return False
+
+
+def _fallback_claims(username):
+ """环境变量 / 密码覆盖文件登录成功后,默认按系统管理员处理。"""
+ return {
+ "username": username,
+ "display_name": username,
+ "role": "系统管理员",
+ "role_code": "admin",
+ "permissions": ["*"],
+ "source": "env",
+ }
+
+
+def authenticate(username: str, password: str):
+ """统一认证:先查 users.db,再回退到环境变量/密码覆盖文件。返回 claims 或 None。"""
+ username = (username or "").strip()
+ if not username:
+ return None
+ # 1) users.db 多用户
+ try:
+ conn = _users_conn()
+ if conn:
+ row = conn.execute("""
+ SELECT u.*, r.code role_code, r.name role_name, r.permissions role_permissions
+ FROM users u LEFT JOIN roles r ON u.role_id = r.id
+ WHERE u.username = ? AND u.status = '启用'
+ """, (username,)).fetchone()
+ if row and _verify_password(password, row["salt"], row["password_hash"]):
+ try:
+ perms = json.loads(row["role_permissions"] or "[]")
+ except Exception:
+ perms = []
+ conn.execute("UPDATE users SET last_login=? WHERE id=?", (_now(), row["id"]))
+ conn.commit()
+ conn.close()
+ return {
+ "username": row["username"],
+ "display_name": row["display_name"] or row["username"],
+ "role": row["role_name"] or "未授权",
+ "role_code": row["role_code"] or "",
+ "permissions": perms,
+ "source": "db",
+ }
+ conn.close()
+ except Exception:
+ pass
+ # 2) 兼容原有单账号环境变量 / 密码覆盖文件
+ if _check_static(username, password):
+ return _fallback_claims(username)
+ return None
+
+
+def _check_static(username, password) -> bool:
+ override = _load_override()
+ if override and override.get("username") and override.get("salt") and override.get("password_hash"):
+ if not secrets.compare_digest(username or "", override["username"]):
+ return False
+ return _verify_password(password, override["salt"], override["password_hash"])
+ return secrets.compare_digest(username or "", AUTH_USER) and secrets.compare_digest(
+ password or "", AUTH_PASSWORD
+ )
+
+
+def ensure_seed_users():
+ """首次部署时初始化角色,并按环境变量/覆盖文件创建管理员账号。"""
+ conn = _users_conn(create=True)
+ if conn is None:
+ return {"ok": False, "error": "无法创建用户库"}
+ for code, name, perms in DEFAULT_ROLES:
+ exists = conn.execute("SELECT 1 FROM roles WHERE code=?", (code,)).fetchone()
+ if not exists:
+ conn.execute("INSERT INTO roles(code,name,permissions,created_at) VALUES (?,?,?,?)",
+ (code, name, json.dumps(perms, ensure_ascii=False), _now()))
+ admin_role = conn.execute("SELECT id FROM roles WHERE code='admin'").fetchone()
+ admin_role_id = admin_role["id"] if admin_role else None
+ user_count = conn.execute("SELECT COUNT(*) c FROM users").fetchone()["c"]
+ if user_count == 0:
+ override = _load_override()
+ if override and override.get("username") and override.get("salt") and override.get("password_hash"):
+ username = override["username"]
+ salt, pwd_hash = override["salt"], override["password_hash"]
+ elif AUTH_USER and AUTH_PASSWORD:
+ username = AUTH_USER
+ salt, pwd_hash = _hash_password(AUTH_PASSWORD)
+ else:
+ # 未配置 AUTH_USER/AUTH_PASSWORD 时,不再内置固定口令;
+ # 生成随机初始密码并打印一次,要求部署者立即修改。
+ username = "admin"
+ generated = secrets.token_urlsafe(12)
+ salt, pwd_hash = _hash_password(generated)
+ print(f"[初始化] 未配置 AUTH_USER/AUTH_PASSWORD,已创建管理员 admin,"
+ f"初始密码:{generated}(请立即修改并配置 .env)", flush=True)
+ conn.execute("""INSERT INTO users(username,display_name,password_hash,salt,role_id,role_code,
+ status,created_at) VALUES (?,?,?,?,?,?,?,?)""",
+ (username, "系统管理员", pwd_hash, salt, admin_role_id, "admin", "启用", _now()))
+ conn.commit()
+ conn.close()
+ return {"ok": True, "db": USERS_DB}
+
+
+def list_roles():
+ conn = _users_conn()
+ if not conn:
+ ensure_seed_users()
+ conn = _users_conn()
+ rows = [dict(r) for r in conn.execute("SELECT * FROM roles ORDER BY id").fetchall()]
+ conn.close()
+ for r in rows:
+ try:
+ r["permissions"] = json.loads(r.get("permissions") or "[]")
+ except Exception:
+ r["permissions"] = []
+ return rows
+
+
+def list_users():
+ conn = _users_conn()
+ if not conn:
+ ensure_seed_users()
+ conn = _users_conn()
+ rows = conn.execute("""
+ SELECT u.id,u.username,u.display_name,u.role_id,u.role_code,u.status,u.created_at,u.last_login,
+ r.name role_name
+ FROM users u LEFT JOIN roles r ON u.role_id=r.id ORDER BY u.id
+ """).fetchall()
+ conn.close()
+ return [dict(r) for r in rows]
+
+
+def save_user(data):
+ """创建/更新用户;password 为空则不改密码。"""
+ conn = _users_conn(create=True)
+ username = (data.get("username") or "").strip()
+ if not username:
+ raise ValueError("用户名不能为空")
+ role_id = data.get("role_id")
+ role = conn.execute("SELECT * FROM roles WHERE id=?", (role_id,)).fetchone() if role_id else None
+ role_code = role["code"] if role else data.get("role_code", "viewer")
+ if not role:
+ role = conn.execute("SELECT * FROM roles WHERE code=?", (role_code,)).fetchone()
+ role_id = role["id"] if role else None
+ now = _now()
+ uid = data.get("id")
+ password = data.get("password") or ""
+ if uid:
+ if password:
+ salt, pwd_hash = _hash_password(password)
+ conn.execute("""UPDATE users SET display_name=?,role_id=?,role_code=?,status=?,
+ password_hash=?,salt=? WHERE id=?""",
+ (data.get("display_name", ""), role_id, role_code,
+ data.get("status", "启用"), pwd_hash, salt, uid))
+ else:
+ conn.execute("UPDATE users SET display_name=?,role_id=?,role_code=?,status=? WHERE id=?",
+ (data.get("display_name", ""), role_id, role_code,
+ data.get("status", "启用"), uid))
+ conn.commit()
+ conn.close()
+ return uid
+ if not password:
+ raise ValueError("新建用户必须设置密码")
+ salt, pwd_hash = _hash_password(password)
+ cur = conn.execute("""INSERT INTO users(username,display_name,password_hash,salt,role_id,role_code,
+ status,created_at) VALUES (?,?,?,?,?,?,?,?)""",
+ (username, data.get("display_name") or username, pwd_hash, salt,
+ role_id, role_code, data.get("status", "启用"), now))
+ conn.commit()
+ uid = cur.lastrowid
+ conn.close()
+ return uid
+
+
+def delete_user(uid):
+ conn = _users_conn()
+ if not conn:
+ return False
+ row = conn.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
+ if not row:
+ conn.close()
+ return False
+ if row["role_code"] == "admin":
+ admins = conn.execute("SELECT COUNT(*) c FROM users WHERE role_code='admin' AND status='启用'").fetchone()["c"]
+ if admins <= 1:
+ conn.close()
+ raise ValueError("不能删除最后一个系统管理员")
+ conn.execute("DELETE FROM users WHERE id=?", (uid,))
+ conn.commit()
+ conn.close()
+ return True
+
+
+def reset_user_password(uid, password):
+ if not password:
+ raise ValueError("密码不能为空")
+ conn = _users_conn()
+ if not conn:
+ return False
+ salt, pwd_hash = _hash_password(password)
+ conn.execute("UPDATE users SET password_hash=?,salt=? WHERE id=?", (pwd_hash, salt, uid))
+ conn.commit()
+ affected = conn.total_changes
+ conn.close()
+ return affected > 0
+
+
+def check_credentials(username: str, password: str) -> bool:
+ return authenticate(username, password) is not None
+
+
+def basic_ok(request) -> bool:
+ header = request.headers.get("authorization", "")
+ if not header.lower().startswith("basic "):
+ return False
+ try:
+ decoded = base64.b64decode(header[6:]).decode("utf-8")
+ except Exception:
+ return False
+ user, _, password = decoded.partition(":")
+ return check_credentials(user, password)
+
+
+def login_url(request) -> str:
+ if PORTAL_LOGIN_URL:
+ return PORTAL_LOGIN_URL
+ host = (request.headers.get("host") or "").split(":")[0] or "localhost"
+ return f"http://{host}:8080/login"
+
+
+def client_ip(request) -> str:
+ return request.client.host if request.client else "unknown"
+
+
+def login_fail_count(ip: str) -> int:
+ now = time.time()
+ fails = [t for t in _FAILS.get(ip, []) if now - t < FAIL_WINDOW_SECONDS]
+ _FAILS[ip] = fails
+ return len(fails)
+
+
+def record_fail(ip: str) -> None:
+ _FAILS.setdefault(ip, []).append(time.time())
+
+
+def clear_fails(ip: str) -> None:
+ _FAILS.pop(ip, None)
+
+
+def safe_next(next_url: str, request) -> str:
+ """只允许跳回本站地址,避免开放重定向"""
+ if not next_url:
+ return "/"
+ if next_url.startswith("/") and not next_url.startswith("//"):
+ return next_url
+ try:
+ parsed = urlparse(next_url)
+ host = (request.headers.get("host") or "").split(":")[0]
+ if parsed.scheme == "http" and parsed.hostname == host:
+ return next_url
+ except Exception:
+ pass
+ return "/"
+
+
+def guard(request, extra_exempt=()):
+ """未登录时返回响应;已登录/免登录返回 None"""
+ if not ENABLED:
+ return None
+
+ path = request.url.path
+ if path.startswith("/api/health"):
+ return None
+ for prefix in extra_exempt:
+ if path == prefix or path.startswith(prefix):
+ return None
+
+ if session_user(request.cookies.get(SESSION_COOKIE)):
+ return None
+ if basic_ok(request):
+ return None
+
+ if path.startswith("/api/"):
+ return JSONResponse(
+ status_code=401,
+ content={"detail": "未登录", "login": login_url(request)},
+ )
+
+ target = login_url(request) + "?next=" + quote(str(request.url), safe="")
+ return RedirectResponse(target, status_code=302)
+
+
+LOGIN_HTML = """
+
+
+
+
+
登录 · XX大学附属医院审计管理平台
+
+
+
+