CI / check (push) Failing after 15m48s
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
184 lines
6.9 KiB
Python
184 lines
6.9 KiB
Python
"""Excel 风险清单导入服务"""
|
||
|
||
import os
|
||
import sqlite3
|
||
from config import DB_PATH, RISK_LIST_EXCEL
|
||
|
||
|
||
def check_year_exists(year: int) -> dict:
|
||
"""检查指定年度是否已有风险清单
|
||
|
||
Returns:
|
||
{"exists": bool, "version_id": int, "item_count": int, "version_name": str}
|
||
"""
|
||
conn = sqlite3.connect(DB_PATH)
|
||
conn.row_factory = sqlite3.Row
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT * FROM risk_versions WHERE year = ?", (year,))
|
||
row = cursor.fetchone()
|
||
if row:
|
||
cursor.execute("SELECT COUNT(*) as c FROM risk_items WHERE version_id = ?", (row["id"],))
|
||
count = cursor.fetchone()["c"]
|
||
conn.close()
|
||
return {"exists": True, "version_id": row["id"], "item_count": count, "version_name": row["version_name"]}
|
||
conn.close()
|
||
return {"exists": False, "version_id": None, "item_count": 0, "version_name": ""}
|
||
|
||
|
||
def import_risk_list_from_excel(year: int, version_name: str = "", description: str = "",
|
||
overwrite: bool = False) -> dict:
|
||
"""从 Excel 文件导入风险清单到数据库
|
||
|
||
Args:
|
||
year: 年度(如 2026)
|
||
version_name: 版本名称(为空则自动生成)
|
||
description: 版本描述
|
||
overwrite: 同年度已有数据时是否覆盖(默认False,需前端确认后传True)
|
||
|
||
Returns:
|
||
导入结果统计。如果同年已有数据且 overwrite=False,返回 {"need_confirm": True, ...}
|
||
"""
|
||
if not os.path.exists(RISK_LIST_EXCEL):
|
||
return {"error": f"风险清单文件不存在: {RISK_LIST_EXCEL}"}
|
||
|
||
# 检查同年度是否已有数据
|
||
existing = check_year_exists(year)
|
||
if existing["exists"] and not overwrite:
|
||
return {
|
||
"need_confirm": True,
|
||
"year": year,
|
||
"existing_version": existing["version_name"],
|
||
"existing_count": existing["item_count"],
|
||
"message": f"{year}年度已有风险清单「{existing['version_name']}」({existing['item_count']}条风险点),是否覆盖?"
|
||
}
|
||
|
||
import openpyxl
|
||
wb = openpyxl.load_workbook(RISK_LIST_EXCEL, data_only=True)
|
||
ws = wb["基础表"]
|
||
|
||
conn = sqlite3.connect(DB_PATH)
|
||
conn.row_factory = sqlite3.Row
|
||
conn.execute("PRAGMA foreign_keys = ON")
|
||
cursor = conn.cursor()
|
||
|
||
# 如果已有版本则更新,否则创建
|
||
if existing["exists"]:
|
||
version_id = existing["version_id"]
|
||
if not version_name:
|
||
version_name = existing["version_name"]
|
||
cursor.execute(
|
||
"UPDATE risk_versions SET version_name = ?, description = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||
(version_name, description, "已导入", version_id)
|
||
)
|
||
else:
|
||
if not version_name:
|
||
version_name = f"{year}年度风险清单"
|
||
cursor.execute(
|
||
"INSERT INTO risk_versions (year, version_name, description, status) VALUES (?, ?, ?, ?)",
|
||
(year, version_name, description, "已导入")
|
||
)
|
||
conn.commit()
|
||
version_id = cursor.lastrowid
|
||
|
||
# 清除该版本的所有风险点(覆盖导入)
|
||
cursor.execute("DELETE FROM risk_items WHERE version_id = ?", (version_id,))
|
||
|
||
# 读取数据行(从第3行开始,第1行是标题,第2行是表头)
|
||
imported = 0
|
||
skipped = 0
|
||
for row_data in ws.iter_rows(min_row=3, max_row=ws.max_row, values_only=True):
|
||
if not row_data or not row_data[0]:
|
||
skipped += 1
|
||
continue
|
||
|
||
risk_code = str(row_data[0]).strip() if row_data[0] else ""
|
||
if not risk_code:
|
||
skipped += 1
|
||
continue
|
||
|
||
department = str(row_data[1]).strip() if row_data[1] else ""
|
||
risk_no = str(row_data[2]).strip() if row_data[2] else ""
|
||
risk_desc = str(row_data[3]).strip() if row_data[3] else ""
|
||
|
||
if not risk_desc:
|
||
skipped += 1
|
||
continue
|
||
|
||
# 安全地提取各字段
|
||
def _safe_str(val, default=""):
|
||
if val is None:
|
||
return default
|
||
return str(val).strip()
|
||
|
||
def _safe_float(val, default=1):
|
||
if val is None:
|
||
return default
|
||
try:
|
||
return float(val)
|
||
except (ValueError, TypeError):
|
||
return default
|
||
|
||
try:
|
||
cursor.execute("""
|
||
INSERT INTO risk_items (
|
||
version_id, risk_code, department, risk_no, risk_desc,
|
||
is_economic, in_responsibility, has_regulation,
|
||
probability_score, impact_score, risk_total_score,
|
||
framework, risk_level, risk_type, control_flow_no,
|
||
target_category, target_content, coso_erm_category,
|
||
indicator, formula, formula_attr,
|
||
low_risk_threshold, mid_risk_threshold, high_risk_threshold
|
||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
""", (
|
||
version_id, risk_code, department, risk_no, risk_desc,
|
||
_safe_str(row_data[4], "否"),
|
||
_safe_str(row_data[5], "是"),
|
||
_safe_str(row_data[6], "是"),
|
||
_safe_float(row_data[7]),
|
||
_safe_float(row_data[8]),
|
||
_safe_float(row_data[9]),
|
||
_safe_str(row_data[10]),
|
||
_safe_str(row_data[11], "低风险"),
|
||
_safe_str(row_data[12], "运营"),
|
||
_safe_str(row_data[13]),
|
||
_safe_str(row_data[14]),
|
||
_safe_str(row_data[15]),
|
||
_safe_str(row_data[16]),
|
||
_safe_str(row_data[17]),
|
||
_safe_str(row_data[18]),
|
||
_safe_str(row_data[19], "调查获取"),
|
||
_safe_str(row_data[20], "0.95"),
|
||
_safe_str(row_data[21], "0.85"),
|
||
_safe_str(row_data[22], "0.75"),
|
||
))
|
||
imported += 1
|
||
except Exception as e:
|
||
print(f"导入失败 {risk_code}: {e}")
|
||
skipped += 1
|
||
continue
|
||
|
||
conn.commit()
|
||
|
||
# 统计经济类/非经济类
|
||
cursor.execute("SELECT COUNT(*) as c FROM risk_items WHERE version_id = ? AND is_economic = '是'", (version_id,))
|
||
economic_count = cursor.fetchone()["c"]
|
||
cursor.execute("SELECT COUNT(*) as c FROM risk_items WHERE version_id = ? AND is_economic = '否'", (version_id,))
|
||
non_economic_count = cursor.fetchone()["c"]
|
||
|
||
# 统计科室数
|
||
cursor.execute("SELECT COUNT(DISTINCT department) as c FROM risk_items WHERE version_id = ?", (version_id,))
|
||
dept_count = cursor.fetchone()["c"]
|
||
|
||
conn.close()
|
||
|
||
return {
|
||
"version_id": version_id,
|
||
"year": year,
|
||
"version_name": version_name,
|
||
"imported": imported,
|
||
"skipped": skipped,
|
||
"economic_count": economic_count,
|
||
"non_economic_count": non_economic_count,
|
||
"department_count": dept_count
|
||
}
|