Files
audit-platform/风险管理项目/services/analysis_service.py
T
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

1545 lines
53 KiB
Python
Raw 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.
"""风险数据分析服务
对调查表数据进行多维度分析,包括:
1. 主观风险评分(基于调查表选项)
2. 客观风险评分(基于指标计算)
3. 综合风险评分与等级判定
4. 多维度统计聚合(科室/架构/类型/等级)
5. 分析报告导出
"""
import sqlite3
import os
from config import DB_PATH, BACKUP_DIR
def _get_conn():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
# ====== 评分配置 ======
# 选项 → 主观影响程度映射(1~5,用于与风险清单影响程度对比)
# 非经济类选项(A=无影响, B=轻度, C=中度, D=重度, E=毁灭性)
NON_ECONOMIC_CHOICE_IMPACT = {
"A": 1, "B": 2, "C": 3, "D": 4, "E": 5,
}
# 经济类选项(A=没发生, B=1次, C=2次, D=3次, E=4次, F=5次及以上)
ECONOMIC_CHOICE_IMPACT = {
"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 5,
}
# 风险等级阈值(基于风险评分 1~25)
# 风险评分<9为低风险;9~16为中风险;>16为高风险
HIGH_RISK_THRESHOLD = 16 # >16 为高风险
MID_RISK_THRESHOLD = 9 # >=9 为中风险,<9 为低风险
def _calc_probability_coefficient(occurrence_count: int) -> int:
"""根据发生次数计算可能性系数(1~5)
发生次数为0,可能性系数=1
发生次数为1,可能性系数=2
发生次数为2,可能性系数=3
发生次数为3,可能性系数=4
发生次数≥4,可能性系数=5
"""
count = int(occurrence_count or 0)
if count <= 0:
return 1
elif count == 1:
return 2
elif count == 2:
return 3
elif count == 3:
return 4
else:
return 5
def _calc_impact_degree(is_economic: str, impact_score: float,
occurrence_amount: float = 0) -> int:
"""计算影响程度(1~5)
非经济类:取风险清单中的影响程度系数(risk_items.impact_score)
经济类:根据发生金额大小确定
>50万 → 5
10万~50万(含) → 4
3万~10万(含) → 3
5000~3万(含) → 2
<5000 → 1
"""
if is_economic == "是":
amount = float(occurrence_amount or 0)
if amount > 500000:
return 5
elif amount > 100000:
return 4
elif amount > 30000:
return 3
elif amount >= 5000:
return 2
else:
return 1
else:
# 非经济类:取风险清单的影响程度,确保在1~5范围内
score = int(impact_score or 1)
return max(1, min(5, score))
def _choice_to_subjective_impact(is_economic: str, choice: str) -> int:
"""将调查选项转换为主观影响程度(1~5),用于与风险清单对比"""
if not choice:
return 0
choice = choice.strip().upper()
if is_economic == "是":
return ECONOMIC_CHOICE_IMPACT.get(choice, 0)
else:
return NON_ECONOMIC_CHOICE_IMPACT.get(choice, 0)
def _risk_score_to_level(risk_score: int, impact_degree: int,
occurrence_count: int) -> str:
"""根据风险评分和特殊情况确定风险等级
规则:
- 风险评分<9为低风险
- 风险评分>16为高风险
- 其他为中风险
- 特殊情况(优先判断):
- 发生次数=0 → 低风险
- 影响程度=5且发生≥1次 → 高风险
- 影响程度=4且发生1次 → 中风险
"""
count = int(occurrence_count or 0)
# 特殊情况优先判断
if count == 0:
return "低风险"
if impact_degree == 5 and count >= 1:
return "高风险"
if impact_degree == 4 and count == 1:
return "中风险"
# 常规判断
if risk_score > 16:
return "高风险"
elif risk_score >= 9:
return "中风险"
else:
return "低风险"
# ====== 核心计算 ======
def calculate_version_scores(version_id: int) -> dict:
"""计算某年度所有风险点的风险评分
新评分规则:
- 风险评分 = 可能性系数 * 影响程度(1~25)
- 可能性系数:根据发生次数计算(0->1, 1->2, 2->3, 3->4, >=4->5)
- 影响程度:
- 非经济类:取风险清单中的 impact_score(1~5)
- 经济类:根据发生金额范围确定(<5000->1, 5000~3万->2, 3万~10万->3, 10万~50万->4, >50万->5)
- 风险等级:<9 低风险, 9~16 中风险, >16 高风险
- 特殊情况:发生0次->低风险;影响=5且发生>=1->高风险;影响=4且发生1次->中风险
字段映射(risk_assessments 表):
- subjective_score -> 可能性系数(1~5)
- objective_score -> 影响程度(1~5)
- combined_score -> 风险评分(1~25)
"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM risk_versions WHERE id = ?", (version_id,))
version = cursor.fetchone()
if not version:
conn.close()
return {"error": "版本不存在"}
cursor.execute("SELECT * FROM risk_items WHERE version_id = ? ORDER BY department, risk_no", (version_id,))
risk_items = [dict(r) for r in cursor.fetchall()]
if not risk_items:
conn.close()
return {"error": "该版本没有风险点数据"}
# 获取已导入调查响应(按 risk_item_id 去重,优先「已导入」)
cursor.execute("""
SELECT r.* FROM survey_responses r
JOIN survey_tasks t ON r.task_id = t.id
WHERE t.version_id = ? AND r.status IN ('已导入', '审核通过')
ORDER BY r.risk_item_id
""", (version_id,))
all_responses = [dict(r) for r in cursor.fetchall()]
responses_by_item = {}
for resp in all_responses:
item_id = resp["risk_item_id"]
if item_id not in responses_by_item:
responses_by_item[item_id] = resp
elif resp["status"] == "已导入" and responses_by_item[item_id]["status"] != "已导入":
responses_by_item[item_id] = resp
cursor.execute("DELETE FROM risk_assessments WHERE version_id = ?", (version_id,))
calculated = 0
has_survey = 0
no_survey = 0
high_count = 0
mid_count = 0
low_count = 0
for item in risk_items:
item_id = item["id"]
survey = responses_by_item.get(item_id)
is_economic = item.get("is_economic", "否")
impact_score_from_list = item.get("impact_score", 1) or 1
occurrence_count = 0
occurrence_amount = 0.0
survey_choice = ""
detail_parts = []
if survey:
has_survey += 1
occurrence_count = survey.get("occurrence_count", 0) or 0
occurrence_amount = float(survey.get("occurrence_amount", 0) or 0)
survey_choice = survey.get("survey_choice", "") or ""
detail_parts.append(f"调查数据: 选项={survey_choice}, 发生次数={occurrence_count}, 发生金额={occurrence_amount:.2f}")
else:
no_survey += 1
detail_parts.append("无调查数据,发生次数按0处理")
# 可能性系数
prob_coef = _calc_probability_coefficient(occurrence_count)
detail_parts.append(f"可能性系数: {prob_coef}(发生次数={occurrence_count})")
# 影响程度
impact_degree = _calc_impact_degree(is_economic, impact_score_from_list, occurrence_amount)
if is_economic == "是":
detail_parts.append(f"影响程度: {impact_degree}(经济类,金额={occurrence_amount:.2f})")
else:
detail_parts.append(f"影响程度: {impact_degree}(非经济类,风险清单impact_score={impact_score_from_list})")
# 风险评分 = 可能性 * 影响
risk_score = prob_coef * impact_degree
detail_parts.append(f"风险评分: {prob_coef} x {impact_degree} = {risk_score}")
# 调查主观影响程度(用于对比,非评分依据)
if survey_choice:
subjective_impact = _choice_to_subjective_impact(is_economic, survey_choice)
detail_parts.append(f"调查主观影响程度: {subjective_impact}(选项{survey_choice})")
# 风险等级(含特殊情况)
final_level = _risk_score_to_level(risk_score, impact_degree, occurrence_count)
detail_parts.append(f"风险等级: {final_level}")
if final_level == "高风险":
high_count += 1
elif final_level == "中风险":
mid_count += 1
else:
low_count += 1
cursor.execute("""
INSERT INTO risk_assessments
(risk_item_id, version_id, subjective_score, objective_score,
combined_score, final_risk_level, assessment_detail, assessed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
""", (item_id, version_id, prob_coef, impact_degree,
risk_score, final_level, "\n".join(detail_parts)))
calculated += 1
conn.commit()
conn.close()
return {
"version_id": version_id,
"total_items": len(risk_items),
"calculated": calculated,
"has_survey": has_survey,
"no_survey_data": no_survey,
"level_distribution": {
"高风险": high_count,
"中风险": mid_count,
"低风险": low_count
}
}
def get_impact_comparison(version_id: int) -> dict:
"""对比调查表主观影响程度与风险清单影响程度
仅用于展示参考,判断填表人对风险的认知是否到位。
"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT r.id as response_id, r.risk_item_id, r.risk_no, r.risk_desc,
r.department, r.is_economic, r.survey_choice,
r.occurrence_count, r.occurrence_amount, r.respondent,
i.impact_score as risk_list_impact,
i.probability_score, i.risk_type, i.framework
FROM survey_responses r
JOIN survey_tasks t ON r.task_id = t.id
JOIN risk_items i ON r.risk_item_id = i.id
WHERE t.version_id = ? AND r.status IN ('已导入', '审核通过')
ORDER BY r.department, r.risk_no
""", (version_id,))
rows = [dict(r) for r in cursor.fetchall()]
items = []
match_count = 0
diff_count = 0
for r in rows:
is_economic = r.get("is_economic", "否")
choice = r.get("survey_choice", "") or ""
list_impact = int(r.get("risk_list_impact", 1) or 1)
survey_impact = _choice_to_subjective_impact(is_economic, choice)
if is_economic == "是":
amount = float(r.get("occurrence_amount", 0) or 0)
actual_impact = _calc_impact_degree("是", list_impact, amount)
impact_source = f"金额{amount:.2f}元"
else:
actual_impact = list_impact
impact_source = "风险清单"
is_match = survey_impact == actual_impact
if is_match:
match_count += 1
else:
diff_count += 1
items.append({
"response_id": r["response_id"],
"risk_no": r.get("risk_no", ""),
"risk_desc": r.get("risk_desc", ""),
"department": r.get("department", ""),
"is_economic": is_economic,
"survey_choice": choice,
"survey_impact": survey_impact,
"risk_list_impact": list_impact,
"actual_impact": actual_impact,
"impact_source": impact_source,
"is_match": is_match,
"occurrence_count": r.get("occurrence_count", 0),
"occurrence_amount": r.get("occurrence_amount", 0),
"respondent": r.get("respondent", ""),
"risk_type": r.get("risk_type", ""),
"framework": r.get("framework", ""),
})
conn.close()
return {
"version_id": version_id,
"total": len(items),
"match_count": match_count,
"diff_count": diff_count,
"items": items
}
# ====== 查询接口 ======
def get_analysis_overview(version_id: int) -> dict:
"""获取分析概览:评分统计 + 等级分布"""
conn = _get_conn()
cursor = conn.cursor()
# 检查是否已计算
cursor.execute("SELECT COUNT(*) as c FROM risk_assessments WHERE version_id = ?", (version_id,))
assessed_count = cursor.fetchone()["c"]
cursor.execute("SELECT COUNT(*) as c FROM risk_items WHERE version_id = ?", (version_id,))
total_items = cursor.fetchone()["c"]
if assessed_count == 0:
conn.close()
return {
"version_id": version_id,
"calculated": False,
"total_items": total_items,
"assessed_items": 0
}
# 等级分布
cursor.execute("""
SELECT final_risk_level, COUNT(*) as count
FROM risk_assessments WHERE version_id = ?
GROUP BY final_risk_level
""", (version_id,))
level_dist = {r["final_risk_level"]: r["count"] for r in cursor.fetchall()}
# 评分统计(subjective_score=可能性系数, objective_score=影响程度, combined_score=风险评分)
cursor.execute("""
SELECT
AVG(combined_score) as avg_combined,
AVG(subjective_score) as avg_probability,
AVG(objective_score) as avg_impact,
MAX(combined_score) as max_combined,
MIN(combined_score) as min_combined
FROM risk_assessments WHERE version_id = ?
""", (version_id,))
stats = cursor.fetchone()
conn.close()
return {
"version_id": version_id,
"calculated": True,
"total_items": total_items,
"assessed_items": assessed_count,
"level_distribution": {
"高风险": level_dist.get("高风险", 0),
"中风险": level_dist.get("中风险", 0),
"低风险": level_dist.get("低风险", 0)
},
"score_stats": {
"avg_combined": round(stats["avg_combined"] or 0, 2),
"avg_probability": round(stats["avg_probability"] or 0, 2),
"avg_impact": round(stats["avg_impact"] or 0, 2),
"max_combined": round(stats["max_combined"] or 0, 2),
"min_combined": round(stats["min_combined"] or 0, 2)
}
}
def get_scored_items(version_id: int, department: str = None,
risk_level: str = None, risk_type: str = None,
keyword: str = None, page: int = 1,
page_size: int = 50) -> dict:
"""获取风险评分明细列表(关联风险点+评估结果)"""
conn = _get_conn()
cursor = conn.cursor()
where = "WHERE a.version_id = ?"
params = [version_id]
if department:
where += " AND i.department = ?"
params.append(department)
if risk_level:
where += " AND a.final_risk_level = ?"
params.append(risk_level)
if risk_type:
where += " AND i.risk_type = ?"
params.append(risk_type)
if keyword:
where += " AND (i.risk_desc LIKE ? OR i.risk_no LIKE ? OR i.risk_code LIKE ?)"
params.extend([f"%{keyword}%", f"%{keyword}%", f"%{keyword}%"])
cursor.execute(f"""
SELECT COUNT(*) as total
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
{where}
""", params)
total = cursor.fetchone()["total"]
offset = (page - 1) * page_size
cursor.execute(f"""
SELECT a.*, i.risk_code, i.department, i.risk_no, i.risk_desc,
i.is_economic, i.risk_type, i.framework, i.risk_level as inherent_level,
i.probability_score, i.impact_score, i.risk_total_score,
i.indicator, i.formula, i.formula_attr,
i.low_risk_threshold, i.mid_risk_threshold, i.high_risk_threshold,
i.target_category, i.coso_erm_category
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
{where}
ORDER BY a.combined_score DESC, i.department, i.risk_no
LIMIT ? OFFSET ?
""", params + [page_size, offset])
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return {
"items": rows,
"total": total,
"page": page,
"page_size": page_size,
"total_pages": (total + page_size - 1) // page_size
}
def get_analysis_by_dimension(version_id: int, dimension: str) -> list[dict]:
"""按维度聚合分析(department/framework/risk_type/is_economic)"""
conn = _get_conn()
cursor = conn.cursor()
dim_map = {
"department": "i.department",
"framework": "i.framework",
"risk_type": "i.risk_type",
"is_economic": "i.is_economic",
}
dim_field = dim_map.get(dimension, "i.department")
cursor.execute(f"""
SELECT
{dim_field} as dimension,
COUNT(*) as total,
SUM(CASE WHEN a.final_risk_level = '高风险' THEN 1 ELSE 0 END) as high_count,
SUM(CASE WHEN a.final_risk_level = '中风险' THEN 1 ELSE 0 END) as mid_count,
SUM(CASE WHEN a.final_risk_level = '低风险' THEN 1 ELSE 0 END) as low_count,
ROUND(AVG(a.combined_score), 2) as avg_score,
ROUND(AVG(a.subjective_score), 2) as avg_probability,
ROUND(AVG(a.objective_score), 2) as avg_impact,
ROUND(MAX(a.combined_score), 2) as max_score
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
WHERE a.version_id = ? AND {dim_field} != ''
GROUP BY {dim_field}
ORDER BY avg_score DESC
""", (version_id,))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def get_top_risks(version_id: int, limit: int = 10) -> list[dict]:
"""获取 Top N 高风险点"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT a.combined_score, a.subjective_score, a.objective_score,
a.final_risk_level, a.assessment_detail, a.risk_item_id,
i.risk_code, i.department, i.risk_no, i.risk_desc,
i.is_economic, i.risk_type, i.framework,
i.probability_score, i.impact_score
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
WHERE a.version_id = ?
ORDER BY a.combined_score DESC
LIMIT ?
""", (version_id, limit))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def get_risk_detail(risk_item_id: int) -> dict:
"""获取单个风险点的详细分析(含调查响应+评估结果)"""
conn = _get_conn()
cursor = conn.cursor()
# 风险点信息
cursor.execute("SELECT * FROM risk_items WHERE id = ?", (risk_item_id,))
item = cursor.fetchone()
if not item:
conn.close()
return {"error": "风险点不存在"}
item = dict(item)
# 评估结果
cursor.execute("SELECT * FROM risk_assessments WHERE risk_item_id = ?", (risk_item_id,))
assessment = cursor.fetchone()
assessment = dict(assessment) if assessment else None
# 调查响应
cursor.execute("""
SELECT r.*, t.department as task_dept
FROM survey_responses r
JOIN survey_tasks t ON r.task_id = t.id
WHERE r.risk_item_id = ? AND r.status IN ('已导入', '审核通过')
ORDER BY r.status DESC
""", (risk_item_id,))
responses = [dict(r) for r in cursor.fetchall()]
# 客观指标
cursor.execute("SELECT * FROM objective_results WHERE risk_item_id = ?", (risk_item_id,))
objective = cursor.fetchone()
objective = dict(objective) if objective else None
conn.close()
return {
"risk_item": item,
"assessment": assessment,
"survey_responses": responses,
"objective_result": objective
}
def get_departments_with_scores(version_id: int) -> list[str]:
"""获取有评分数据的科室列表"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT DISTINCT i.department FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
WHERE a.version_id = ? AND i.department != ''
ORDER BY i.department
""", (version_id,))
rows = [r["department"] for r in cursor.fetchall()]
conn.close()
return rows
def get_cross_analysis(version_id: int) -> dict:
"""交叉分析:科室 × 风险等级 矩阵"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT i.department,
a.final_risk_level,
COUNT(*) as count,
ROUND(AVG(a.combined_score), 2) as avg_score
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
WHERE a.version_id = ? AND i.department != ''
GROUP BY i.department, a.final_risk_level
ORDER BY i.department
""", (version_id,))
rows = [dict(r) for r in cursor.fetchall()]
# 构建矩阵
departments = sorted(set(r["department"] for r in rows))
levels = ["高风险", "中风险", "低风险"]
matrix = {}
for dept in departments:
matrix[dept] = {level: {"count": 0, "avg_score": 0} for level in levels}
for r in rows:
if r["department"] == dept:
level = r["final_risk_level"]
if level in matrix[dept]:
matrix[dept][level] = {"count": r["count"], "avg_score": r["avg_score"]}
conn.close()
return {
"departments": departments,
"levels": levels,
"matrix": matrix
}
# ====== 导出 ======
def export_analysis_report(version_id: int, output_path: str) -> dict:
"""导出完整风险分析报告到 Excel(多Sheet)"""
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM risk_versions WHERE id = ?", (version_id,))
version = cursor.fetchone()
if not version:
conn.close()
return {"error": "版本不存在"}
# 获取所有评分数据
cursor.execute("""
SELECT a.*, i.risk_code, i.department, i.risk_no, i.risk_desc,
i.is_economic, i.risk_type, i.framework, i.risk_level as inherent_level,
i.probability_score, i.impact_score, i.risk_total_score,
i.indicator, i.formula, i.formula_attr,
i.low_risk_threshold, i.mid_risk_threshold, i.high_risk_threshold,
i.target_category, i.coso_erm_category, i.control_flow_no
FROM risk_assessments a
JOIN risk_items i ON a.risk_item_id = i.id
WHERE a.version_id = ?
ORDER BY a.combined_score DESC, i.department, i.risk_no
""", (version_id,))
items = [dict(r) for r in cursor.fetchall()]
if not items:
conn.close()
return {"error": "没有分析数据,请先执行风险评分计算"}
conn.close()
wb = openpyxl.Workbook()
# 样式
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, size=11, color="FFFFFF")
title_font = Font(bold=True, size=14, color="333333")
thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin')
)
high_fill = PatternFill(start_color="FEE2E2", end_color="FEE2E2", fill_type="solid")
mid_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
low_fill = PatternFill(start_color="D1FAE5", end_color="D1FAE5", fill_type="solid")
critical_fill = PatternFill(start_color="FECACA", end_color="FECACA", fill_type="solid")
def _apply_level_fill(cell, level):
if level == "高风险":
cell.fill = high_fill
elif level == "中风险":
cell.fill = mid_fill
elif level == "低风险":
cell.fill = low_fill
elif level == "极高风险":
cell.fill = critical_fill
# ====== Sheet1: 评分汇总 ======
ws1 = wb.active
ws1.title = "风险评分汇总"
ws1.cell(row=1, column=1, value=f"{version['year']}年度风险分析报告").font = title_font
headers = [
"排名", "科室", "风险编号", "风险描述", "风险类型", "经济类",
"业务架构", "固有等级", "可能性", "影响程度", "固有评分",
"主观评分", "客观评分", "综合评分", "最终等级", "评估详情"
]
for col, h in enumerate(headers, 1):
cell = ws1.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, item in enumerate(items, 1):
row = idx + 3
vals = [
idx,
item.get("department", ""),
item.get("risk_no", ""),
item.get("risk_desc", ""),
item.get("risk_type", ""),
item.get("is_economic", ""),
item.get("framework", ""),
item.get("inherent_level", ""),
item.get("probability_score", 0),
item.get("impact_score", 0),
item.get("risk_total_score", 0),
round(item.get("subjective_score", 0), 4),
round(item.get("objective_score", 0), 4),
round(item.get("combined_score", 0), 4),
item.get("final_risk_level", ""),
item.get("assessment_detail", "")
]
for col, val in enumerate(vals, 1):
cell = ws1.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
if col == 15:
_apply_level_fill(cell, val)
col_widths = [6, 16, 10, 50, 10, 8, 16, 10, 8, 8, 8, 10, 10, 10, 10, 60]
for i, w in enumerate(col_widths, 1):
ws1.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet2: 科室维度统计 ======
ws2 = wb.create_sheet("科室维度统计")
ws2.cell(row=1, column=1, value="按科室统计").font = title_font
dept_stats = get_analysis_by_dimension(version_id, "department")
dept_headers = ["科室", "风险总数", "极高风险", "高风险", "中风险", "低风险", "平均评分", "平均主观", "平均客观", "最高分"]
for col, h in enumerate(dept_headers, 1):
cell = ws2.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, d in enumerate(dept_stats, 1):
row = idx + 3
vals = [
d["dimension"], d["total"], d["critical_count"], d["high_count"],
d["mid_count"], d["low_count"],
d["avg_score"], d["avg_subjective"], d["avg_objective"], d["max_score"]
]
for col, val in enumerate(vals, 1):
cell = ws2.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
for i, w in enumerate([16, 10, 10, 10, 10, 10, 10, 10, 10, 10], 1):
ws2.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet3: 架构维度统计 ======
ws3 = wb.create_sheet("架构维度统计")
ws3.cell(row=1, column=1, value="按业务架构统计").font = title_font
fw_stats = get_analysis_by_dimension(version_id, "framework")
for col, h in enumerate(dept_headers, 1):
h2 = h.replace("科室", "业务架构") if col == 1 else h
cell = ws3.cell(row=3, column=col, value=h2)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, d in enumerate(fw_stats, 1):
row = idx + 3
vals = [
d["dimension"], d["total"], d["critical_count"], d["high_count"],
d["mid_count"], d["low_count"],
d["avg_score"], d["avg_subjective"], d["avg_objective"], d["max_score"]
]
for col, val in enumerate(vals, 1):
cell = ws3.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
for i, w in enumerate([16, 10, 10, 10, 10, 10, 10, 10, 10, 10], 1):
ws3.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet4: Top10 高风险 ======
ws4 = wb.create_sheet("Top10高风险")
ws4.cell(row=1, column=1, value="综合评分最高的10个风险点").font = title_font
top_items = items[:10]
top_headers = ["排名", "科室", "风险编号", "风险描述", "综合评分", "主观评分", "客观评分", "最终等级"]
for col, h in enumerate(top_headers, 1):
cell = ws4.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, item in enumerate(top_items, 1):
row = idx + 3
vals = [
idx, item.get("department", ""), item.get("risk_no", ""),
item.get("risk_desc", ""),
round(item.get("combined_score", 0), 4),
round(item.get("subjective_score", 0), 4),
round(item.get("objective_score", 0), 4),
item.get("final_risk_level", "")
]
for col, val in enumerate(vals, 1):
cell = ws4.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
if col == 8:
_apply_level_fill(cell, val)
for i, w in enumerate([6, 16, 10, 50, 10, 10, 10, 10], 1):
ws4.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
wb.save(output_path)
return {
"file_path": output_path,
"total_items": len(items),
"year": version["year"],
"sheets": ["风险评分汇总", "科室维度统计", "架构维度统计", "Top10高风险"]
}
# ====== 检查风险数据分析 ======
# ====== 检查数据汇总(按风险点分组汇总后分析) ======
def aggregate_inspection_data(year):
"""将检查风险数据按 (department, risk_no) 分组汇总
汇总规则:
- occurrence_count: 求和
- occurrence_amount: 求和
- survey_choice: 取风险最高的选项(A<B<C<D<E<F)
- remark: 合并所有备注(去重,用 | 分隔)
- source_reports: 合并所有报告名称(去重,用逗号分隔)
- risk_desc: 取最长的描述
- is_economic: 取第一条记录的值
Returns:
汇总结果统计
"""
conn = _get_conn()
cursor = conn.cursor()
# 查询原始检查数据
cursor.execute("""
SELECT * FROM inspection_risk_data
WHERE year = ? AND status = '已入库'
ORDER BY department, risk_no, id
""", (year,))
rows = [dict(r) for r in cursor.fetchall()]
if not rows:
conn.close()
return {"error": "没有找到已入库的检查风险数据", "year": year, "aggregated": 0}
# 按 (department, risk_no) 分组
groups = {}
for row in rows:
key = (row.get("department", ""), row.get("risk_no", ""))
if key not in groups:
groups[key] = []
groups[key].append(row)
# 清除旧的汇总数据
cursor.execute("DELETE FROM inspection_aggregated WHERE year = ?", (year,))
# 选项风险排序(越大越高风险)
choice_order = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6}
aggregated_count = 0
multi_source_count = 0
for (dept, risk_no), recs in groups.items():
if len(recs) > 1:
multi_source_count += 1
# 汇总各字段
total_count = sum(r.get("occurrence_count", 0) or 0 for r in recs)
total_amount = sum(r.get("occurrence_amount", 0) or 0 for r in recs)
# 取风险最高的选项
best_choice = ""
best_score = 0
for r in recs:
ch = r.get("survey_choice", "") or ""
if ch and choice_order.get(ch, 0) > best_score:
best_score = choice_order.get(ch, 0)
best_choice = ch
# 合并备注(去重)
remarks = []
for r in recs:
rm = r.get("remark", "") or ""
if rm and rm not in remarks:
remarks.append(rm)
# 合并报告名称(去重)
reports = []
for r in recs:
rp = r.get("report_name", "") or ""
if rp and rp not in reports:
reports.append(rp)
# 取最长描述
risk_desc = max((r.get("risk_desc", "") or "" for r in recs), key=len)
# 取第一条的 is_economic
is_economic = recs[0].get("is_economic", "否")
# 原始记录ID列表
source_ids = ",".join(str(r["id"]) for r in recs)
cursor.execute("""
INSERT INTO inspection_aggregated
(year, risk_no, risk_desc, department, is_economic,
survey_choice, occurrence_count, occurrence_amount,
remark, source_reports, source_record_count, source_record_ids)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
year, risk_no, risk_desc, dept, is_economic,
best_choice, total_count, total_amount,
" | ".join(remarks) if remarks else "",
", ".join(reports) if reports else "",
len(recs), source_ids
))
aggregated_count += 1
conn.commit()
conn.close()
return {
"year": year,
"original_count": len(rows),
"aggregated_count": aggregated_count,
"multi_source_groups": multi_source_count,
"merged_records": len(rows) - aggregated_count
}
def _ensure_inspection_columns(cursor):
"""确保 inspection_risk_data 表包含评分相关字段,缺失则自动添加
检查数据表原生不含评分字段,需要先 ALTER TABLE ADD COLUMN。
"""
cursor.execute("PRAGMA table_info(inspection_risk_data)")
existing = {row[1] for row in cursor.fetchall()}
needed = {
"subjective_score": "REAL",
"combined_score": "REAL",
"final_risk_level": "TEXT",
"assessment_detail": "TEXT",
}
for col, col_type in needed.items():
if col not in existing:
cursor.execute(
f"ALTER TABLE inspection_risk_data ADD COLUMN {col} {col_type}"
)
def _ensure_inspection_agg_score_columns(cursor):
"""确保 inspection_aggregated 表包含评分相关字段,缺失则自动添加
汇总表原生不含评分字段(objective_score 等),
需要先 ALTER TABLE ADD COLUMN,否则查询会报 no such column。
"""
cursor.execute("PRAGMA table_info(inspection_aggregated)")
existing = {row[1] for row in cursor.fetchall()}
needed = {
"subjective_score": "REAL DEFAULT 0",
"objective_score": "REAL DEFAULT 0",
"combined_score": "REAL DEFAULT 0",
"final_risk_level": "TEXT",
"assessment_detail": "TEXT",
}
for col, col_type in needed.items():
if col not in existing:
cursor.execute(
f"ALTER TABLE inspection_aggregated ADD COLUMN {col} {col_type}"
)
def calculate_inspection_scores(year):
"""计算检查数据评分(基于汇总后数据,使用新评分规则)
新评分规则:
- 风险评分 = 可能性系数 * 影响程度(1~25)
- 可能性系数:根据发生次数计算(0->1, 1->2, 2->3, 3->4, >=4->5)
- 影响程度:非经济类取风险清单impact_score,经济类取金额范围
- 风险等级:<9低, 9~16中, >16高,含特殊情况
字段映射(inspection_aggregated 表):
- subjective_score -> 可能性系数(1~5)
- objective_score -> 影响程度(1~5)
- combined_score -> 风险评分(1~25)
"""
# 先执行汇总
agg_result = aggregate_inspection_data(year)
if "error" in agg_result:
return agg_result
conn = _get_conn()
cursor = conn.cursor()
# 确保汇总表有评分相关列
_ensure_inspection_agg_score_columns(cursor)
# 获取该年份对应的版本ID(用于查找风险清单)
cursor.execute("SELECT id FROM risk_versions WHERE year = ?", (year,))
version_row = cursor.fetchone()
version_id = version_row[0] if version_row else None
# 预加载风险清单的 impact_score(按 risk_no 索引)
impact_by_risk_no = {}
if version_id:
cursor.execute("SELECT risk_no, impact_score FROM risk_items WHERE version_id = ?", (version_id,))
for r in cursor.fetchall():
impact_by_risk_no[r["risk_no"]] = r["impact_score"]
# 从汇总表读取数据
cursor.execute("""
SELECT * FROM inspection_aggregated
WHERE year = ?
ORDER BY department, risk_no
""", (year,))
rows = [dict(r) for r in cursor.fetchall()]
if not rows:
conn.close()
return {"error": "汇总后无数据", "year": year, "calculated": 0}
calculated = 0
has_choice = 0
no_choice = 0
high_count = 0
mid_count = 0
low_count = 0
for row in rows:
rid = row["id"]
is_economic = row.get("is_economic", "否")
risk_no = row.get("risk_no", "")
occurrence_count = row.get("occurrence_count", 0) or 0
occurrence_amount = float(row.get("occurrence_amount", 0) or 0)
source_count = row.get("source_record_count", 1) or 1
choice = row.get("survey_choice", "") or ""
# 从风险清单获取影响程度
impact_score_from_list = impact_by_risk_no.get(risk_no, 1) or 1
detail_parts = []
detail_parts.append(f"汇总自 {source_count} 条原始记录")
detail_parts.append(f"发生次数: {occurrence_count}, 发生金额: {occurrence_amount:.2f}")
# 可能性系数
prob_coef = _calc_probability_coefficient(occurrence_count)
detail_parts.append(f"可能性系数: {prob_coef}(发生次数={occurrence_count})")
# 影响程度
impact_degree = _calc_impact_degree(is_economic, impact_score_from_list, occurrence_amount)
if is_economic == "是":
detail_parts.append(f"影响程度: {impact_degree}(经济类,金额={occurrence_amount:.2f})")
else:
detail_parts.append(f"影响程度: {impact_degree}(非经济类,风险清单impact_score={impact_score_from_list})")
# 风险评分
risk_score = prob_coef * impact_degree
detail_parts.append(f"风险评分: {prob_coef} x {impact_degree} = {risk_score}")
# 调查选项主观影响(仅记录,用于对比)
if choice:
subjective_impact = _choice_to_subjective_impact(is_economic, choice)
detail_parts.append(f"调查选项({choice})主观影响: {subjective_impact}")
has_choice += 1
else:
no_choice += 1
# 风险等级
final_level = _risk_score_to_level(risk_score, impact_degree, occurrence_count)
detail_parts.append(f"风险等级: {final_level}")
if final_level == "高风险":
high_count += 1
elif final_level == "中风险":
mid_count += 1
else:
low_count += 1
cursor.execute("""
UPDATE inspection_aggregated
SET subjective_score = ?,
objective_score = ?,
combined_score = ?,
final_risk_level = ?,
assessment_detail = ?
WHERE id = ?
""", (prob_coef, impact_degree, risk_score, final_level,
"\n".join(detail_parts), rid))
calculated += 1
conn.commit()
conn.close()
return {
"year": year,
"total_items": len(rows),
"calculated": calculated,
"has_choice": has_choice,
"no_choice": no_choice,
"aggregated_from": agg_result.get("original_count", 0),
"multi_source_groups": agg_result.get("multi_source_groups", 0),
"level_distribution": {
"高风险": high_count,
"中风险": mid_count,
"低风险": low_count
}
}
def get_inspection_overview(year):
"""检查数据评分概览(基于汇总后数据):总数、等级分布、平均评分"""
conn = _get_conn()
cursor = conn.cursor()
# 确保汇总表有评分相关列
_ensure_inspection_agg_score_columns(cursor)
cursor.execute("""
SELECT COUNT(*) as total FROM inspection_aggregated
WHERE year = ?
""", (year,))
total = cursor.fetchone()["total"]
if total == 0:
conn.close()
return {
"year": year,
"calculated": False,
"total_items": 0,
"assessed_items": 0
}
# 已评分数量
cursor.execute("""
SELECT COUNT(*) as c FROM inspection_aggregated
WHERE year = ?
AND final_risk_level IS NOT NULL
AND final_risk_level != ''
""", (year,))
assessed = cursor.fetchone()["c"]
# 等级分布
cursor.execute("""
SELECT final_risk_level, COUNT(*) as count
FROM inspection_aggregated
WHERE year = ?
AND final_risk_level IS NOT NULL
AND final_risk_level != ''
GROUP BY final_risk_level
""", (year,))
level_dist = {r["final_risk_level"]: r["count"] for r in cursor.fetchall()}
# 评分统计(subjective_score=可能性系数, objective_score=影响程度, combined_score=风险评分)
cursor.execute("""
SELECT
AVG(combined_score) as avg_combined,
AVG(subjective_score) as avg_probability,
AVG(objective_score) as avg_impact,
MAX(combined_score) as max_combined,
MIN(combined_score) as min_combined
FROM inspection_aggregated
WHERE year = ?
AND combined_score IS NOT NULL
AND combined_score > 0
""", (year,))
stats = cursor.fetchone()
# 原始记录数
cursor.execute("""
SELECT COALESCE(SUM(source_record_count), 0) as orig_count
FROM inspection_aggregated
WHERE year = ?
""", (year,))
orig_count = cursor.fetchone()["orig_count"]
conn.close()
return {
"year": year,
"calculated": assessed > 0,
"total_items": total,
"assessed_items": assessed,
"original_records": orig_count,
"level_distribution": {
"高风险": level_dist.get("高风险", 0),
"中风险": level_dist.get("中风险", 0),
"低风险": level_dist.get("低风险", 0)
},
"score_stats": {
"avg_combined": round(stats["avg_combined"] or 0, 2),
"avg_probability": round(stats["avg_probability"] or 0, 2),
"avg_impact": round(stats["avg_impact"] or 0, 2),
"max_combined": round(stats["max_combined"] or 0, 2),
"min_combined": round(stats["min_combined"] or 0, 2)
}
}
def get_inspection_scores(year, department=None, risk_level=None,
keyword=None, page=1, page_size=50):
"""检查数据评分明细(基于汇总后数据)"""
conn = _get_conn()
cursor = conn.cursor()
# 确保汇总表有评分相关列
_ensure_inspection_agg_score_columns(cursor)
where = "WHERE d.year = ?"
params = [year]
if department:
where += " AND d.department = ?"
params.append(department)
if risk_level:
where += " AND d.final_risk_level = ?"
params.append(risk_level)
if keyword:
where += " AND (d.risk_desc LIKE ? OR d.risk_no LIKE ?)"
params.extend([f"%{keyword}%", f"%{keyword}%"])
cursor.execute(f"""
SELECT COUNT(*) as total
FROM inspection_aggregated d
{where}
""", params)
total = cursor.fetchone()["total"]
offset = (page - 1) * page_size
cursor.execute(f"""
SELECT d.*
FROM inspection_aggregated d
{where}
ORDER BY d.combined_score DESC, d.department, d.risk_no
LIMIT ? OFFSET ?
""", params + [page_size, offset])
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return {
"items": rows,
"total": total,
"page": page,
"page_size": page_size,
"total_pages": (total + page_size - 1) // page_size
}
def get_inspection_by_dimension(year, dimension):
"""按维度聚合检查数据分析(基于汇总后数据)
可用维度:is_economic / department / source_reports
"""
conn = _get_conn()
cursor = conn.cursor()
# 确保汇总表有评分相关列
_ensure_inspection_agg_score_columns(cursor)
dim_map = {
"is_economic": "d.is_economic",
"department": "d.department",
"source_reports": "d.source_reports",
"report_name": "d.source_reports",
}
dim_field = dim_map.get(dimension, "d.department")
cursor.execute(f"""
SELECT
{dim_field} as dimension,
COUNT(*) as total,
SUM(CASE WHEN d.final_risk_level = '高风险' THEN 1 ELSE 0 END) as high_count,
SUM(CASE WHEN d.final_risk_level = '中风险' THEN 1 ELSE 0 END) as mid_count,
SUM(CASE WHEN d.final_risk_level = '低风险' THEN 1 ELSE 0 END) as low_count,
ROUND(AVG(d.combined_score), 2) as avg_score,
ROUND(AVG(d.subjective_score), 2) as avg_probability,
ROUND(AVG(d.objective_score), 2) as avg_impact,
ROUND(MAX(d.combined_score), 2) as max_score
FROM inspection_aggregated d
WHERE d.year = ?
AND d.final_risk_level IS NOT NULL
AND d.final_risk_level != ''
AND {dim_field} IS NOT NULL
AND {dim_field} != ''
GROUP BY {dim_field}
ORDER BY avg_score DESC
""", (year,))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def get_inspection_top_risks(year, limit=10):
"""获取检查数据 Top N 高风险点(基于汇总后数据)"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT *
FROM inspection_aggregated
WHERE year = ?
AND final_risk_level IS NOT NULL
AND final_risk_level != ''
ORDER BY combined_score DESC
LIMIT ?
""", (year, limit))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def get_inspection_departments(year):
"""获取检查数据中涉及的科室列表(基于汇总后数据)"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT DISTINCT d.department FROM inspection_aggregated d
WHERE d.year = ?
AND d.department IS NOT NULL AND d.department != ''
ORDER BY d.department
""", (year,))
rows = [r["department"] for r in cursor.fetchall()]
conn.close()
return rows
def export_inspection_report(year, output_path):
"""导出检查风险数据分析报告到 Excel(多Sheet)"""
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT *
FROM inspection_aggregated
WHERE year = ?
AND final_risk_level IS NOT NULL
AND final_risk_level != ''
ORDER BY combined_score DESC, department, risk_no
""", (year,))
items = [dict(r) for r in cursor.fetchall()]
if not items:
conn.close()
return {"error": "没有检查分析数据,请先执行风险评分计算"}
conn.close()
wb = openpyxl.Workbook()
# 样式
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, size=11, color="FFFFFF")
title_font = Font(bold=True, size=14, color="333333")
thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin')
)
high_fill = PatternFill(start_color="FEE2E2", end_color="FEE2E2", fill_type="solid")
mid_fill = PatternFill(start_color="FEF3C7", end_color="FEF3C7", fill_type="solid")
low_fill = PatternFill(start_color="D1FAE5", end_color="D1FAE5", fill_type="solid")
def _apply_level_fill(cell, level):
if level == "高风险":
cell.fill = high_fill
elif level == "中风险":
cell.fill = mid_fill
elif level == "低风险":
cell.fill = low_fill
# ====== Sheet1: 检查风险评分汇总 ======
ws1 = wb.active
ws1.title = "检查风险评分汇总"
ws1.cell(row=1, column=1, value=f"{year}年度检查风险分析报告").font = title_font
headers = [
"排名", "科室", "风险编号", "风险描述", "经济类",
"报告名称", "发生次数", "发生金额",
"主观评分", "综合评分", "最终等级", "评估详情"
]
for col, h in enumerate(headers, 1):
cell = ws1.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, item in enumerate(items, 1):
row = idx + 3
vals = [
idx,
item.get("department", ""),
item.get("risk_no", ""),
item.get("risk_desc", ""),
item.get("is_economic", ""),
item.get("report_name", ""),
item.get("occurrence_count", 0),
item.get("occurrence_amount", 0),
round(item.get("subjective_score", 0), 4),
round(item.get("combined_score", 0), 4),
item.get("final_risk_level", ""),
item.get("assessment_detail", "")
]
for col, val in enumerate(vals, 1):
cell = ws1.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
if col == 11:
_apply_level_fill(cell, val)
col_widths = [6, 16, 10, 50, 8, 24, 10, 14, 10, 10, 10, 60]
for i, w in enumerate(col_widths, 1):
ws1.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet2: 科室维度统计 ======
ws2 = wb.create_sheet("科室维度统计")
ws2.cell(row=1, column=1, value="按科室统计").font = title_font
dept_stats = get_inspection_by_dimension(year, "department")
dept_headers = ["科室", "风险总数", "高风险", "中风险", "低风险",
"平均评分", "平均主观", "最高分"]
for col, h in enumerate(dept_headers, 1):
cell = ws2.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, d in enumerate(dept_stats, 1):
row = idx + 3
vals = [
d["dimension"], d["total"], d["high_count"],
d["mid_count"], d["low_count"],
d["avg_score"], d["avg_subjective"], d["max_score"]
]
for col, val in enumerate(vals, 1):
cell = ws2.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
for i, w in enumerate([16, 10, 10, 10, 10, 10, 10, 10], 1):
ws2.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet3: 报告维度统计 ======
ws3 = wb.create_sheet("报告维度统计")
ws3.cell(row=1, column=1, value="按检查报告统计").font = title_font
report_stats = get_inspection_by_dimension(year, "report_name")
for col, h in enumerate(dept_headers, 1):
h2 = h.replace("科室", "报告") if col == 1 else h
cell = ws3.cell(row=3, column=col, value=h2)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, d in enumerate(report_stats, 1):
row = idx + 3
vals = [
d["dimension"], d["total"], d["high_count"],
d["mid_count"], d["low_count"],
d["avg_score"], d["avg_subjective"], d["max_score"]
]
for col, val in enumerate(vals, 1):
cell = ws3.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
for i, w in enumerate([24, 10, 10, 10, 10, 10, 10, 10], 1):
ws3.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
# ====== Sheet4: Top10高风险 ======
ws4 = wb.create_sheet("Top10高风险")
ws4.cell(row=1, column=1, value="综合评分最高的10个检查风险点").font = title_font
top_items = items[:10]
top_headers = ["排名", "科室", "风险编号", "风险描述", "报告名称",
"综合评分", "主观评分", "最终等级"]
for col, h in enumerate(top_headers, 1):
cell = ws4.cell(row=3, column=col, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
cell.border = thin_border
for idx, item in enumerate(top_items, 1):
row = idx + 3
vals = [
idx, item.get("department", ""), item.get("risk_no", ""),
item.get("risk_desc", ""), item.get("report_name", ""),
round(item.get("combined_score", 0), 4),
round(item.get("subjective_score", 0), 4),
item.get("final_risk_level", "")
]
for col, val in enumerate(vals, 1):
cell = ws4.cell(row=row, column=col, value=val)
cell.border = thin_border
cell.font = Font(size=10)
if col == 8:
_apply_level_fill(cell, val)
for i, w in enumerate([6, 16, 10, 50, 24, 10, 10, 10], 1):
ws4.column_dimensions[openpyxl.utils.get_column_letter(i)].width = w
wb.save(output_path)
return {
"file_path": output_path,
"total_items": len(items),
"year": year,
"sheets": ["检查风险评分汇总", "科室维度统计", "报告维度统计", "Top10高风险"]
}