Files
guwangtu b91954df4a
CI / check (push) Failing after 15m48s
chore: initial open-source baseline v1.0.0
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
2026-12-05 15:44:53 +00:00

1567 lines
53 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""风险管理项目 - FastAPI 后端服务"""
import os
import json
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Depends
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
from config import HOST, PORT, BACKUP_DIR
from database import init_db, get_db
from services import risk_service
from services import import_service
from services import feishu_service
from services.feishu_service import TokenExpiredError
app = FastAPI(title="医院风险管理项目")
app.mount("/static", StaticFiles(directory=str(Path(__file__).parent)), name="static")
# 允许通过 /static 访问的文件类型(防止 risk_data.db、源码等被直接下载)
_SAFE_STATIC_SUFFIXES = {
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
".css", ".js", ".woff", ".woff2", ".ttf",
}
@app.middleware("http")
async def _block_unsafe_static(request, call_next):
"""/static 只放行图片/样式/脚本,避免 risk_data.db、*.py 等被下载"""
if request.url.path.startswith("/static/"):
suffix = os.path.splitext(request.url.path)[1].lower()
if suffix not in _SAFE_STATIC_SUFFIXES:
return JSONResponse(status_code=404, content={"detail": "Not Found"})
return await call_next(request)
# ====== 登录会话(Cookie + HMAC 签名,四套系统共享) ======
import auth_guard as auth
@app.middleware("http")
async def _auth_middleware(request, call_next):
resp = auth.guard(request)
if resp is not None:
return resp
return await call_next(request)
# ====== 全局异常处理 ======
@app.exception_handler(TokenExpiredError)
async def token_expired_handler(request, exc):
return JSONResponse(status_code=401, content={"detail": "token_expired", "message": str(exc)})
# ====== 页面路由 ======
@app.get("/", response_class=HTMLResponse)
async def index():
"""主页"""
index_path = os.path.join(os.path.dirname(__file__), "templates", "index.html")
with open(index_path, "r", encoding="utf-8") as f:
content = f.read()
return HTMLResponse(content=content, headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
})
# ====== 健康检查 ======
@app.get("/api/health")
async def health():
return {"status": "ok"}
@app.get("/api/system-info")
async def system_info():
"""系统信息(大模型配置实时读取,不写死)"""
from config import get_llm_config
llm = get_llm_config()
return {
"llm": {
"model": llm["model"],
"base_url": llm["base_url"],
"api_key_set": bool(llm["api_key"]),
},
"port": PORT,
}
# ====== 飞书连接状态检查 ======
@app.get("/api/feishu/status")
async def feishu_status():
"""检查飞书连接状态 - 通过实际调用飞书API来检测"""
try:
# 尝试调用飞书多维表格API来检测连接状态
# 如果 token 过期,feishu_service._run_lark 会抛出 TokenExpiredError
from services.feishu_service import _run_lark, TokenExpiredError
from config import SURVEY_BASE_TOKEN
# 调用一个轻量的飞书命令:列出多维表格中的表
result = _run_lark(["base", "+table-list", "--base-token", SURVEY_BASE_TOKEN])
# 如果调用成功,说明飞书连接正常
return {"connected": True, "message": "飞书已连接"}
except TokenExpiredError as e:
return {"connected": False, "message": "飞书授权已过期,请在TRAE中重新授权飞书插件"}
except Exception as e:
err_msg = str(e)
if 'token' in err_msg.lower() or 'unauthorized' in err_msg.lower() or 'not authorized' in err_msg.lower():
return {"connected": False, "message": "飞书授权已过期,请在TRAE中重新授权飞书插件"}
return {"connected": False, "message": f"飞书连接异常: {err_msg}"}
# ====== 年度版本管理 ======
@app.get("/api/versions")
async def get_versions():
"""获取年度版本列表"""
try:
return {"versions": risk_service.list_versions()}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/versions")
async def create_version(
year: int = Form(...),
version_name: str = Form(""),
description: str = Form("")
):
"""创建年度版本"""
try:
return risk_service.create_version(year, version_name, description)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/versions/{version_id}")
async def delete_version(version_id: int):
"""删除年度版本"""
try:
return risk_service.delete_version(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/versions/copy")
async def copy_version(
source_version_id: int = Form(...),
new_year: int = Form(...),
new_version_name: str = Form(""),
description: str = Form("")
):
"""从已有版本复制风险清单到新年度"""
try:
result = risk_service.copy_version(source_version_id, new_year, new_version_name, description)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== Excel 导入 ======
@app.post("/api/import/{year}")
async def import_from_excel(
year: int,
version_name: str = Form(""),
description: str = Form(""),
overwrite: bool = Form(False)
):
"""从 Excel 导入风险清单(同年已有数据时需传 overwrite=True 确认覆盖)"""
try:
result = import_service.import_risk_list_from_excel(year, version_name, description, overwrite)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== Excel 导出 ======
@app.post("/api/export/{version_id}")
async def export_to_excel(version_id: int):
"""导出风险清单到 Excel 文件"""
try:
from config import BACKUP_DIR
os.makedirs(BACKUP_DIR, exist_ok=True)
filename = f"风险清单导出_{version_id}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = risk_service.export_to_excel(version_id, output_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/export/download/{filename}")
async def download_export(filename: str):
"""下载导出的文件"""
from config import BACKUP_DIR
file_path = os.path.join(BACKUP_DIR, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="文件不存在")
return FileResponse(file_path, filename=filename)
# ====== 风险点管理 ======
@app.get("/api/risks/{version_id}")
async def get_risks(
version_id: int,
department: str = None,
risk_type: str = None,
is_economic: str = None,
risk_level: str = None,
keyword: str = None,
page: int = 1,
page_size: int = 50
):
"""获取风险点列表"""
try:
return risk_service.list_risk_items(
version_id, department, risk_type, is_economic, risk_level,
keyword, page, page_size
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/risks/item/{item_id}")
async def get_risk_item(item_id: int):
"""获取单个风险点"""
try:
item = risk_service.get_risk_item(item_id)
if not item:
raise HTTPException(status_code=404, detail="风险点不存在")
return {"item": item}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/risks")
async def create_risk_item(
version_id: int = Form(...),
risk_code: str = Form(...),
department: str = Form(...),
risk_no: str = Form(...),
risk_desc: str = Form(...),
is_economic: str = Form("否"),
in_responsibility: str = Form("是"),
has_regulation: str = Form("是"),
probability_score: float = Form(1),
impact_score: float = Form(1),
framework: str = Form(""),
risk_type: str = Form("运营"),
control_flow_no: str = Form(""),
target_category: str = Form(""),
target_content: str = Form(""),
coso_erm_category: str = Form(""),
indicator: str = Form(""),
formula: str = Form(""),
formula_attr: str = Form("调查获取"),
low_risk_threshold: str = Form("0.95"),
mid_risk_threshold: str = Form("0.85"),
high_risk_threshold: str = Form("0.75")
):
"""创建风险点"""
try:
data = {
"version_id": version_id, "risk_code": risk_code,
"department": department, "risk_no": risk_no,
"risk_desc": risk_desc, "is_economic": is_economic,
"in_responsibility": in_responsibility,
"has_regulation": has_regulation,
"probability_score": probability_score,
"impact_score": impact_score,
"framework": framework, "risk_type": risk_type,
"control_flow_no": control_flow_no,
"target_category": target_category,
"target_content": target_content,
"coso_erm_category": coso_erm_category,
"indicator": indicator, "formula": formula,
"formula_attr": formula_attr,
"low_risk_threshold": low_risk_threshold,
"mid_risk_threshold": mid_risk_threshold,
"high_risk_threshold": high_risk_threshold
}
return risk_service.create_risk_item(data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/risks/{item_id}")
async def update_risk_item(item_id: int, data: dict):
"""更新风险点"""
try:
return risk_service.update_risk_item(item_id, data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/risks/{item_id}")
async def delete_risk_item(item_id: int):
"""删除风险点"""
try:
return risk_service.delete_risk_item(item_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 风险点唯一值 ======
@app.get("/api/unique-points/config")
async def get_unique_points_config():
"""获取业务层面与层面代码映射配置"""
from config import BUSINESS_LEVELS
return {"business_levels": BUSINESS_LEVELS}
@app.get("/api/unique-points")
async def get_unique_points(
business_level: str = None,
business_framework: str = None,
level_code: str = None,
keyword: str = None,
page: int = 1,
page_size: int = 50
):
"""获取风险点唯一值列表"""
try:
return risk_service.list_unique_points(business_level, business_framework, level_code, keyword, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/unique-points/next-number/{level_code}")
async def get_next_risk_number(level_code: str):
"""获取指定层面代码的下一个风险数字编号"""
try:
return risk_service.get_next_risk_number(level_code)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/unique-points/item/{risk_no}")
async def get_unique_point(risk_no: str):
"""获取单个风险点唯一值"""
try:
item = risk_service.get_unique_point(risk_no)
if not item:
raise HTTPException(status_code=404, detail="风险点不存在")
return {"item": item}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/unique-points")
async def create_unique_point(data: dict):
"""新增风险点唯一值"""
try:
result = risk_service.create_unique_point(data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/unique-points/{risk_no}")
async def update_unique_point(risk_no: str, data: dict):
"""更新风险点唯一值"""
try:
return risk_service.update_unique_point(risk_no, data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/unique-points/{risk_no}")
async def delete_unique_point(risk_no: str):
"""删除风险点唯一值"""
try:
return risk_service.delete_unique_point(risk_no)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/unique-points/import")
async def import_unique_points():
"""从Excel导入风险点唯一值"""
try:
result = risk_service.import_unique_points_from_excel()
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 业务架构与风险编号筛选 ======
@app.get("/api/frameworks")
async def get_frameworks():
"""获取所有不重复的业务架构(来源:风险点唯一值表)"""
try:
return {"frameworks": risk_service.list_frameworks()}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/unique-points/by-framework/{framework}")
async def get_unique_points_by_framework(framework: str):
"""根据业务架构筛选风险点唯一值"""
try:
items = risk_service.list_unique_points_by_framework(framework)
return {"items": items, "count": len(items)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 科室表 ======
@app.get("/api/dept-table")
async def list_dept_table(keyword: str = None):
"""获取科室表列表"""
try:
return {"items": risk_service.list_departments(keyword)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/dept-table")
async def create_dept_table(data: dict):
"""新增科室"""
try:
return risk_service.create_department(data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/dept-table/{dept_id}")
async def update_dept_table(dept_id: int, data: dict):
"""更新科室"""
try:
return risk_service.update_department(dept_id, data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/dept-table/{dept_id}")
async def delete_dept_table(dept_id: int):
"""删除科室"""
try:
return risk_service.delete_department(dept_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 目标分类表 ======
@app.get("/api/target-cat-table")
async def list_target_cat_table(keyword: str = None):
"""获取目标分类表列表"""
try:
return {"items": risk_service.list_target_categories(keyword)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/target-cat-table")
async def create_target_cat_table(data: dict):
"""新增目标分类"""
try:
return risk_service.create_target_category(data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/target-cat-table/{cat_id}")
async def update_target_cat_table(cat_id: int, data: dict):
"""更新目标分类"""
try:
return risk_service.update_target_category(cat_id, data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/target-cat-table/{cat_id}")
async def delete_target_cat_table(cat_id: int):
"""删除目标分类"""
try:
return risk_service.delete_target_category(cat_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== COSO-ERM目标类别表 ======
@app.get("/api/coso-table")
async def list_coso_table(keyword: str = None):
"""获取COSO-ERM目标类别表列表"""
try:
return {"items": risk_service.list_coso_erm_categories(keyword)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/coso-table")
async def create_coso_table(data: dict):
"""新增COSO-ERM目标类别"""
try:
return risk_service.create_coso_erm_category(data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/coso-table/{coso_id}")
async def update_coso_table(coso_id: int, data: dict):
"""更新COSO-ERM目标类别"""
try:
return risk_service.update_coso_erm_category(coso_id, data)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/coso-table/{coso_id}")
async def delete_coso_table(coso_id: int):
"""删除COSO-ERM目标类别"""
try:
return risk_service.delete_coso_erm_category(coso_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 统计信息 ======
@app.get("/api/statistics/{version_id}")
async def get_statistics(version_id: int):
"""获取统计信息"""
try:
return risk_service.get_statistics(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/departments/{version_id}")
async def get_departments(version_id: int):
"""获取科室列表"""
try:
return {"departments": risk_service.get_departments(version_id)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 调查表管理(按科室+选择题格式+审核流程) ======
@app.get("/api/survey/summary/{version_id}")
async def get_survey_summary(version_id: int):
"""获取某年度调查表整体概览"""
try:
return feishu_service.get_survey_summary(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/survey/tasks/{version_id}")
async def get_survey_tasks(version_id: int):
"""获取某年度下所有调查任务(按科室分组)"""
try:
return {"tasks": feishu_service.list_survey_tasks(version_id)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/create-all/{version_id}")
async def create_all_survey_tasks(version_id: int):
"""为当前年度所有有风险点的科室批量创建调查任务"""
try:
return feishu_service.create_all_survey_tasks(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks")
async def create_survey_task(data: dict):
"""为指定科室创建调查任务"""
try:
result = feishu_service.create_survey_task(data["version_id"], data["department"])
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/survey/tasks/{task_id}")
async def delete_survey_task(task_id: int):
"""删除调查任务(级联删除响应)"""
try:
return feishu_service.delete_survey_task(task_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/survey/tasks/{task_id}/status")
async def update_survey_task_status(task_id: int, data: dict):
"""更新调查任务状态"""
try:
return feishu_service.update_survey_task_status(task_id, data.get("status", ""))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/{task_id}/export")
async def export_dept_survey(task_id: int):
"""导出某科室的调查表到Excel(选择题格式)"""
try:
from config import BACKUP_DIR
os.makedirs(BACKUP_DIR, exist_ok=True)
task = feishu_service.get_survey_task(task_id)
if not task:
raise HTTPException(status_code=404, detail="调查任务不存在")
filename = f"调查表_{task['department']}_{task_id}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = feishu_service.export_dept_survey_excel(task["version_id"], task["department"], output_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/survey/download/{filename}")
async def download_survey(filename: str):
"""下载调查表文件"""
from config import BACKUP_DIR
file_path = os.path.join(BACKUP_DIR, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="文件不存在")
return FileResponse(file_path, filename=filename)
@app.post("/api/survey/export-responses/{version_id}")
async def export_all_responses(version_id: int):
"""导出某年度所有科室的调查原始数据到Excel"""
try:
from config import BACKUP_DIR
import time
os.makedirs(BACKUP_DIR, exist_ok=True)
version = risk_service.get_version(version_id)
if not version:
raise HTTPException(status_code=404, detail="版本不存在")
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"调查原始数据_{version['year']}年度_{timestamp}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = feishu_service.export_all_survey_responses(version_id, output_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/{task_id}/import")
async def import_survey_responses(task_id: int, file: UploadFile = File(...)):
"""导入调查结果(选择题格式解析+去重)"""
try:
from config import BACKUP_DIR
os.makedirs(BACKUP_DIR, exist_ok=True)
file_path = os.path.join(BACKUP_DIR, f"survey_response_{task_id}_{file.filename}")
with open(file_path, "wb") as f:
content = await file.read()
f.write(content)
result = feishu_service.import_survey_responses(task_id, file_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/survey/tasks/{task_id}/responses")
async def get_survey_responses(task_id: int, status: str = None):
"""获取调查结果列表,可按状态筛选"""
try:
return {"responses": feishu_service.list_survey_responses(task_id, status)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/survey/responses/{response_id}")
async def update_survey_response(response_id: int, data: dict):
"""编辑修改单条调查结果(审核时可直接修改数据)"""
try:
result = feishu_service.update_survey_response(response_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/responses/{response_id}/audit")
async def audit_survey_response(response_id: int, data: dict):
"""审核单条调查结果"""
try:
return feishu_service.audit_response(response_id, data.get("action", ""), data.get("audit_remark", ""))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/{task_id}/batch-audit")
async def batch_audit_survey(task_id: int, data: dict):
"""批量审核"""
try:
return feishu_service.batch_audit(task_id, data.get("action", ""), data.get("audit_remark", ""))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/{task_id}/import-approved")
async def import_approved_to_local(task_id: int):
"""将审核通过的调查结果导入本地(年度覆盖)"""
try:
result = feishu_service.import_approved_to_local(task_id)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/tasks/{task_id}/revoke-import")
async def revoke_import(task_id: int):
"""撤销入库:删除已导入的数据,恢复为可编辑状态"""
try:
result = feishu_service.revoke_import(task_id)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/survey/review-status/{version_id}")
async def check_review_status(version_id: int):
"""检查某年度所有科室和风险点的调查数据是否全部审核通过
用于判断是否可以进入风险分析环节。
"""
try:
return feishu_service.check_review_complete(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 飞书多维表格联动 ======
@app.get("/api/survey/feishu/url")
async def get_feishu_url():
"""获取飞书多维表格分享链接"""
try:
return feishu_service.get_feishu_survey_url()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/feishu/push/{version_id}")
async def push_to_feishu(version_id: int, data: dict = None):
"""将风险清单数据推送到飞书多维表格"""
try:
department = data.get("department") if data else None
result = feishu_service.push_to_feishu(version_id, department)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except TokenExpiredError:
raise
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/survey/feishu/pull/{version_id}")
async def pull_from_feishu(version_id: int, data: dict = None):
"""从飞书多维表格拉取调查结果"""
try:
department = data.get("department") if data else None
result = feishu_service.pull_from_feishu(version_id, department)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except TokenExpiredError:
raise
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 备份 ======
@app.post("/api/backup")
async def backup_database():
"""备份数据库"""
try:
import shutil
from config import DB_PATH, BACKUP_DIR
os.makedirs(BACKUP_DIR, exist_ok=True)
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(BACKUP_DIR, f"risk_data_backup_{timestamp}.db")
shutil.copy2(DB_PATH, backup_path)
return {"message": "备份成功", "path": backup_path}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== AI风险智能分析 ======
@app.post("/api/ai-risk/analyze")
async def analyze_material(file: UploadFile = File(...)):
"""上传材料并进行AI风险分析"""
try:
from config import BACKUP_DIR
import services.ai_risk_service as ai_service
os.makedirs(BACKUP_DIR, exist_ok=True)
# 保存上传文件
file_path = os.path.join(BACKUP_DIR, f"ai_analysis_{file.filename}")
with open(file_path, "wb") as f:
content = await file.read()
f.write(content)
# 提取文本
text = ai_service._extract_text_from_file(file_path, file.filename)
if not text or len(text.strip()) < 50:
raise HTTPException(status_code=400, detail="无法从文件中提取足够的文本内容,请确认文件格式正确")
# 调用大模型分析
ai_risks = ai_service.analyze_material_with_llm(text)
if not ai_risks:
raise HTTPException(status_code=400, detail="AI未能从材料中识别出风险点")
# 与现有风险点对比
compared = ai_service.compare_with_existing(ai_risks)
# 保存新风险为待审核
save_result = ai_service.save_candidates(compared, file.filename, f"AI识别出{len(ai_risks)}个风险点")
return {
"total_identified": len(ai_risks),
"new_risks": save_result["saved"],
"existing_matches": save_result["skipped"],
"candidates": compared,
"source_file": file.filename
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/ai-risk/candidates")
async def get_candidates(status: str = None, page: int = 1, page_size: int = 50):
"""获取AI风险候选列表"""
try:
import services.ai_risk_service as ai_service
return ai_service.list_candidates(status, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/ai-risk/candidates/{candidate_id}/approve")
async def approve_candidate(candidate_id: int, data: dict):
"""审核通过AI风险候选"""
try:
import services.ai_risk_service as ai_service
result = ai_service.approve_candidate(candidate_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/ai-risk/candidates/{candidate_id}/reject")
async def reject_candidate(candidate_id: int, data: dict):
"""审核退回AI风险候选"""
try:
import services.ai_risk_service as ai_service
result = ai_service.reject_candidate(candidate_id, data.get("audit_remark", ""))
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/ai-risk/candidates/{candidate_id}")
async def update_candidate(candidate_id: int, data: dict):
"""编辑AI风险候选"""
try:
import services.ai_risk_service as ai_service
result = ai_service.update_candidate(candidate_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 检查风险数据管理 ======
@app.post("/api/inspection/analyze")
async def analyze_inspection_report(
file: UploadFile = File(...),
year: int = Form(...),
report_name: str = Form(""),
report_date: str = Form("")
):
"""上传检查报告并进行AI分析"""
try:
from config import BACKUP_DIR
import services.inspection_service as svc
os.makedirs(BACKUP_DIR, exist_ok=True)
file_path = os.path.join(BACKUP_DIR, f"inspection_{file.filename}")
with open(file_path, "wb") as f:
content = await file.read()
f.write(content)
result = svc.analyze_inspection_report(file_path, file.filename, year, report_name, report_date)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/inspection/reports/{year}")
async def get_inspection_reports(year: int):
"""获取某年度检查报告列表"""
try:
import services.inspection_service as svc
return {"reports": svc.list_reports(year)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/inspection/data/{year}")
async def get_inspection_data(
year: int,
report_id: int = None,
keyword: str = None,
page: int = 1,
page_size: int = 50
):
"""获取检查风险数据列表"""
try:
import services.inspection_service as svc
return svc.list_risk_data(year, report_id, keyword, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/inspection/candidates/{report_id}")
async def get_inspection_candidates(report_id: int, status: str = None):
"""获取某报告的候选风险点列表"""
try:
import services.inspection_service as svc
return svc.list_candidates(report_id, status)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/inspection/candidates/{candidate_id}/approve")
async def approve_inspection_candidate(candidate_id: int, data: dict):
"""审核通过候选风险点"""
try:
import services.inspection_service as svc
result = svc.approve_candidate(candidate_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/inspection/candidates/batch-approve/{report_id}")
async def batch_approve_candidates(report_id: int, data: dict = None):
"""批量审核通过"""
try:
import services.inspection_service as svc
data_list = data.get("candidates", []) if data else None
return svc.approve_all_candidates(report_id, data_list)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/inspection/candidates/{candidate_id}/reject")
async def reject_inspection_candidate(candidate_id: int, data: dict):
"""审核退回候选风险点"""
try:
import services.inspection_service as svc
result = svc.reject_candidate(candidate_id, data.get("audit_remark", ""))
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/inspection/candidates/{candidate_id}")
async def update_inspection_candidate(candidate_id: int, data: dict):
"""编辑候选记录"""
try:
import services.inspection_service as svc
result = svc.update_candidate(candidate_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/inspection/candidates/{candidate_id}/duplicate")
async def duplicate_inspection_candidate(candidate_id: int, data: dict):
"""复制候选风险点记录(可指定不同科室)"""
try:
import services.inspection_service as svc
result = svc.duplicate_candidate(candidate_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/inspection/data/{data_id}")
async def update_inspection_data(data_id: int, data: dict):
"""修改已入库的检查风险数据"""
try:
import services.inspection_service as svc
result = svc.update_risk_data(data_id, data)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/inspection/data/{data_id}")
async def delete_inspection_data(data_id: int):
"""删除单条检查风险数据"""
try:
import services.inspection_service as svc
result = svc.delete_risk_data(data_id)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/inspection/reports/{report_id}")
async def delete_inspection_report(report_id: int):
"""按报告ID批量删除数据"""
try:
import services.inspection_service as svc
result = svc.batch_delete_by_report(report_id)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/inspection/batch/{batch_no}")
async def delete_inspection_by_batch(batch_no: str):
"""按批次编号批量删除数据"""
try:
import services.inspection_service as svc
result = svc.batch_delete_by_batch_no(batch_no)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/inspection/statistics/{year}")
async def get_inspection_statistics(year: int):
"""获取某年度检查风险数据统计"""
try:
import services.inspection_service as svc
return svc.get_statistics(year)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 风险数据分析 ======
@app.post("/api/analysis/calculate/{version_id}")
async def calculate_analysis(version_id: int):
"""执行风险评分计算(基于调查数据+客观指标)"""
try:
import services.analysis_service as svc
result = svc.calculate_version_scores(version_id)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/overview/{version_id}")
async def get_analysis_overview(version_id: int):
"""获取分析概览(等级分布+评分统计)"""
try:
import services.analysis_service as svc
return svc.get_analysis_overview(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/scores/{version_id}")
async def get_analysis_scores(
version_id: int,
department: str = None,
risk_level: str = None,
risk_type: str = None,
keyword: str = None,
page: int = 1,
page_size: int = 50
):
"""获取风险评分明细列表"""
try:
import services.analysis_service as svc
return svc.get_scored_items(version_id, department, risk_level, risk_type, keyword, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/by-dimension/{version_id}/{dimension}")
async def get_analysis_by_dimension(version_id: int, dimension: str):
"""按维度聚合分析(department/framework/risk_type/is_economic)"""
try:
import services.analysis_service as svc
return {"items": svc.get_analysis_by_dimension(version_id, dimension)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/top-risks/{version_id}")
async def get_top_risks(version_id: int, limit: int = 10):
"""获取Top N高风险点"""
try:
import services.analysis_service as svc
return {"items": svc.get_top_risks(version_id, limit)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/detail/{risk_item_id}")
async def get_risk_analysis_detail(risk_item_id: int):
"""获取单个风险点的详细分析"""
try:
import services.analysis_service as svc
result = svc.get_risk_detail(risk_item_id)
if "error" in result:
raise HTTPException(status_code=404, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/cross/{version_id}")
async def get_cross_analysis(version_id: int):
"""交叉分析:科室 x 风险等级 矩阵"""
try:
import services.analysis_service as svc
return svc.get_cross_analysis(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/impact-comparison/{version_id}")
async def get_impact_comparison(version_id: int):
"""对比调查表主观影响程度与风险清单影响程度"""
try:
import services.analysis_service as svc
return svc.get_impact_comparison(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/departments/{version_id}")
async def get_analysis_departments(version_id: int):
"""获取有评分数据的科室列表"""
try:
import services.analysis_service as svc
return {"departments": svc.get_departments_with_scores(version_id)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analysis/export/{version_id}")
async def export_analysis_report(version_id: int):
"""导出风险分析报告到Excel"""
try:
from config import BACKUP_DIR
import services.analysis_service as svc
import time
os.makedirs(BACKUP_DIR, exist_ok=True)
version = risk_service.get_version(version_id)
if not version:
raise HTTPException(status_code=404, detail="版本不存在")
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"风险分析报告_{version['year']}年度_{timestamp}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = svc.export_analysis_report(version_id, output_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 检查风险数据分析 ======
@app.post("/api/analysis/inspection/calculate/{year}")
async def calculate_inspection_analysis(year: int):
"""执行检查数据风险评分计算"""
try:
import services.analysis_service as svc
result = svc.calculate_inspection_scores(year)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/inspection/overview/{year}")
async def get_inspection_analysis_overview(year: int):
"""获取检查数据分析概览"""
try:
import services.analysis_service as svc
return svc.get_inspection_overview(year)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/inspection/scores/{year}")
async def get_inspection_analysis_scores(
year: int,
department: str = None,
risk_level: str = None,
keyword: str = None,
page: int = 1,
page_size: int = 50
):
"""获取检查数据评分明细列表"""
try:
import services.analysis_service as svc
return svc.get_inspection_scores(year, department, risk_level, keyword, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/inspection/by-dimension/{year}/{dimension}")
async def get_inspection_analysis_by_dimension(year: int, dimension: str):
"""按维度聚合检查数据分析"""
try:
import services.analysis_service as svc
return {"items": svc.get_inspection_by_dimension(year, dimension)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/inspection/top-risks/{year}")
async def get_inspection_top_risks(year: int, limit: int = 10):
"""获取检查数据 Top N 高风险点"""
try:
import services.analysis_service as svc
return {"items": svc.get_inspection_top_risks(year, limit)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/inspection/departments/{year}")
async def get_inspection_analysis_departments(year: int):
"""获取检查数据涉及的科室列表"""
try:
import services.analysis_service as svc
return {"departments": svc.get_inspection_departments(year)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analysis/inspection/export/{year}")
async def export_inspection_analysis_report(year: int):
"""导出检查风险分析报告到Excel"""
try:
from config import BACKUP_DIR
import services.analysis_service as svc
import time
os.makedirs(BACKUP_DIR, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"检查风险分析报告_{year}年度_{timestamp}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = svc.export_inspection_report(year, output_path)
if "error" in result:
raise HTTPException(status_code=400, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 合并风险数据分析 ======
@app.post("/api/analysis/merge/execute/{version_id}")
async def execute_merge(version_id: int):
"""执行数据合并(调查数据 + 检查数据)"""
try:
import services.merge_service as svc
result = svc.merge_data(version_id)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/list/{version_id}")
async def get_merged_list(
version_id: int,
department: str = None,
merge_status: str = None,
page: int = 1,
page_size: int = 20
):
"""获取合并数据列表"""
try:
import services.merge_service as svc
return svc.list_merged_data(version_id, department, merge_status, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/duplicates/{version_id}")
async def get_merge_duplicates(version_id: int):
"""获取重复组列表"""
try:
import services.merge_service as svc
return {"groups": svc.list_duplicates(version_id)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analysis/merge/select/{record_id}")
async def select_merge_record(record_id: int):
"""选用重复组中的某条数据"""
try:
import services.merge_service as svc
result = svc.select_duplicate(record_id)
if not result.get("success"):
raise HTTPException(status_code=400, detail=result.get("message", "选用失败"))
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/api/analysis/merge/update/{record_id}")
async def update_merge_record(record_id: int, data: dict):
"""修改选用的合并数据"""
try:
import services.merge_service as svc
result = svc.update_merged_record(record_id, data)
if not result.get("success"):
raise HTTPException(status_code=400, detail=result.get("message", "修改失败"))
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analysis/merge/calculate/{version_id}")
async def calculate_merge_scores(version_id: int):
"""计算合并数据评分"""
try:
import services.merge_service as svc
result = svc.calculate_merged_scores(version_id)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/overview/{version_id}")
async def get_merge_overview(version_id: int):
"""获取合并数据概览"""
try:
import services.merge_service as svc
return svc.get_merged_overview(version_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/scores/{version_id}")
async def get_merge_scores(
version_id: int,
department: str = None,
risk_level: str = None,
keyword: str = None,
page: int = 1,
page_size: int = 20
):
"""获取合并数据评分明细"""
try:
import services.merge_service as svc
return svc.get_merged_scores(version_id, department, risk_level, keyword, page, page_size)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/by-dimension/{version_id}/{dimension}")
async def get_merge_by_dimension(version_id: int, dimension: str):
"""按维度聚合合并数据分析"""
try:
import services.merge_service as svc
return svc.get_merged_by_dimension(version_id, dimension)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/top-risks/{version_id}")
async def get_merge_top_risks(version_id: int, limit: int = 10):
"""获取合并数据 Top N 高风险点"""
try:
import services.merge_service as svc
return svc.get_merged_top_risks(version_id, limit)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/merge/inspection-source/{record_id}")
async def get_inspection_source_records(record_id: int):
"""查询合并记录对应的原始检查数据明细"""
try:
import services.merge_service as svc
result = svc.get_inspection_source_records(record_id)
if "error" in result:
raise HTTPException(status_code=404, detail=result["error"])
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analysis/merge/export/{version_id}")
async def export_merge_report(version_id: int):
"""导出合并分析报告到Excel"""
try:
from config import BACKUP_DIR
import services.merge_service as svc
import time
os.makedirs(BACKUP_DIR, exist_ok=True)
version = risk_service.get_version(version_id)
if not version:
raise HTTPException(status_code=404, detail="版本不存在")
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"合并分析报告_{version['year']}年度_{timestamp}.xlsx"
output_path = os.path.join(BACKUP_DIR, filename)
result = svc.export_merged_report(version_id, output_path)
if not result.get("success"):
raise HTTPException(status_code=400, detail="导出失败")
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ====== 启动 ======
if __name__ == "__main__":
init_db()
print(f"风险管理项目启动中...")
print(f"打开浏览器访问: http://localhost:{PORT}")
uvicorn.run(app, host=HOST, port=PORT)