chore: initial open-source baseline v1.0.0
CI / check (push) Failing after 15m48s

Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
This commit is contained in:
guwangtu committed 2026-12-05 15:44:53 +00:00
commit b91954df4a
106 files changed
+43359

No files matched your search

@@ -0,0 +1,959 @@
"""检查风险数据管理服务 - 上传检查报告→AI分析→语义比对→审核→入库"""
import os
import json
import sqlite3
import time
from config import DB_PATH, BUSINESS_LEVELS, get_llm_config
def _get_conn():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
def _extract_text_from_file(file_path: str, filename: str) -> str:
"""从上传的文件中提取文本内容"""
ext = os.path.splitext(filename)[1].lower()
if ext in ('.txt',):
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
return f.read()
if ext in ('.doc', '.docx'):
try:
from docx import Document
doc = Document(file_path)
return '\n'.join([p.text for p in doc.paragraphs if p.text.strip()])
except ImportError:
import subprocess
try:
result = subprocess.run(['antiword', file_path], capture_output=True, text=True, timeout=30)
return result.stdout
except:
return ""
if ext == '.pdf':
try:
import PyPDF2
text = []
with open(file_path, 'rb') as f:
reader = PyPDF2.PdfReader(f)
for page in reader.pages:
text.append(page.extract_text() or '')
return '\n'.join(text)
except ImportError:
try:
import pdf_tools
return pdf_tools.extract_text(file_path)
except Exception:
return ""
if ext in ('.xls', '.xlsx'):
try:
import openpyxl
wb = openpyxl.load_workbook(file_path, data_only=True)
text = []
for ws in wb.worksheets:
for row in ws.iter_rows(values_only=True):
row_text = ' '.join([str(c) for c in row if c is not None])
if row_text.strip():
text.append(row_text)
return '\n'.join(text)
except:
return ""
return ""
def _generate_batch_no(conn, year: int) -> str:
"""生成批次编号:INS-{year}-{序号}"""
cursor = conn.cursor()
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_reports WHERE year = ?", (year,)
)
count = cursor.fetchone()["c"]
return f"INS-{year}-{count + 1:03d}"
def _correct_choice_by_amount(is_economic, survey_choice, occurrence_amount):
"""根据经济类风险的累计金额自动校正选项"""
if is_economic != '是':
return survey_choice
if occurrence_amount is None or occurrence_amount <= 0:
return 'A'
if occurrence_amount < 100000:
return 'B'
elif occurrence_amount < 500000:
return 'C'
elif occurrence_amount < 1000000:
return 'D'
elif occurrence_amount < 5000000:
return 'E'
else:
return 'F'
def analyze_inspection_report(file_path: str, filename: str, year: int,
report_name: str = "", report_date: str = "") -> dict:
"""分析检查报告,提取风险点并与现有风险点唯一值进行语义比对
流程:
1. 提取文本
2. 调用大模型识别风险点(含经济/非经济、发生次数、金额等)
3. 与 risk_unique_points 语义比对
4. 创建检查报告记录
5. 保存候选记录(新风险标记 is_new=1)
"""
# 提取文本
text = _extract_text_from_file(file_path, filename)
if not text or len(text.strip()) < 50:
return {"error": "无法从文件中提取足够的文本内容,请确认文件格式正确"}
# 调用大模型分析
ai_risks = _analyze_report_with_llm(text)
if not ai_risks:
return {"error": "AI未能从报告中识别出风险点"}
# 与现有风险点语义比对
compared = _compare_with_existing_risks(ai_risks)
# 创建检查报告记录
conn = _get_conn()
cursor = conn.cursor()
batch_no = _generate_batch_no(conn, year)
if not report_name:
report_name = os.path.splitext(filename)[0]
if not report_date:
report_date = time.strftime("%Y-%m-%d")
new_count = sum(1 for c in compared if c["is_new"])
existing_count = len(compared) - new_count
cursor.execute("""
INSERT INTO inspection_reports
(year, report_name, report_date, batch_no, source_file,
total_identified, new_risks, existing_matches, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, '分析完成')
""", (year, report_name, report_date, batch_no, filename,
len(ai_risks), new_count, existing_count))
report_id = cursor.lastrowid
# 保存候选记录
saved_new = 0
saved_existing = 0
for c in compared:
cursor.execute("""
INSERT INTO inspection_risk_candidates
(report_id, year, risk_no, risk_desc, department, is_economic,
survey_choice, occurrence_count, occurrence_amount, remark,
is_new, matched_risk_no, match_reason, ai_analysis, source_material, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '待审核')
""", (
report_id, year,
c.get("matched_risk_no", "") if not c["is_new"] else "",
_get_unique_desc_for_candidate(cursor, c),
c.get("department", ""),
c.get("is_economic", "否"),
_correct_choice_by_amount(c.get("is_economic", "否"), c.get("survey_choice", ""), c.get("occurrence_amount", 0)),
c.get("occurrence_count", 0),
c.get("occurrence_amount", 0),
_get_remark_for_candidate(cursor, c),
1 if c["is_new"] else 0,
c.get("matched_risk_no", ""),
c.get("match_reason", ""),
f"AI从报告中识别出风险点",
filename
))
if c["is_new"]:
saved_new += 1
else:
saved_existing += 1
conn.commit()
conn.close()
return {
"report_id": report_id,
"batch_no": batch_no,
"report_name": report_name,
"report_date": report_date,
"total_identified": len(ai_risks),
"new_risks": saved_new,
"existing_matches": saved_existing,
"candidates": compared
}
def _analyze_report_with_llm(text: str) -> list:
"""调用大模型分析检查报告,提取风险点及其详细信息
与 ai_risk_service 不同,这里需要提取:
- 风险描述
- 是否经济类
- 选项(非经济类A-E,经济类A-F)
- 发生次数
- 累计金额
- 备注(风险事件具体内容)
- 所属科室
"""
from openai import OpenAI
text_content = text[:15000]
prompt = f"""你是一位专业的医院风险管理专家。请仔细阅读以下检查/审计报告,从中识别出所有与医院风险管理相关的风险点。
## 重要要求:
1. 从报告中提取所有可识别的风险点
2. 判断每个风险点属于"经济类"还是"非经济类"
3. 对于非经济类风险点,请根据报告内容判断其严重程度选项:
- A: 无事件(未发生风险事件)
- B: 轻微(有隐患但未造成影响)
- C: 一般(造成一定影响)
- D: 较严重(造成较大影响)
- E: 严重(造成严重影响)
4. 对于经济类风险点,请根据报告中提到的涉及金额(单位:元)判断其严重程度选项:
- A: 无事件(金额为0)
- B: 10万元以下(金额大于0且小于100000元,即0 < 金额 < 100000)
- C: 10-50万元(金额在100000元至500000元之间,即100000 ≤ 金额 < 500000)
- D: 50-100万元(金额在500000元至1000000元之间,即500000 ≤ 金额 < 1000000)
- E: 100-500万元(金额在1000000元至5000000元之间,即1000000 ≤ 金额 < 5000000)
- F: 500万元以上(金额大于等于5000000元,即金额 ≥ 5000000)
重要:occurrence_amount字段的单位是元,请务必根据实际金额(元)选择正确的选项!
例如:金额547219.6元 = 54.7万元,应选D(50-100万元);金额66256.3元 = 6.6万元,应选B(10万元以下)
5. 如果报告中提到了具体的次数或金额,请如实填写(金额单位为元)
6. 如果报告中没有明确提到次数或金额,对于非经济类B-E选项填发生次数1,经济类B-F选项填累计金额0
## 字段填写说明(非常重要):
### risk_desc 字段:
填写风险点的简要描述,用一句话概括风险类型,不要包含具体案例细节。
例如:"采购变更活动未经审批" 或 "资产验收入库不及时"
### remark 字段(最重要!):
填写风险事件的**完整详细叙述**,必须是一段连贯的、包含所有关键要素的文字,不能简单罗列要点。
**必须包含以下要素(如报告中提到):**
- 涉及的具体单位/供应商/科室名称
- 涉及的具体金额(精确到分,如66256.30元)
- 具体的违规事实和行为描述(做了什么、怎么做的)
- 未履行的程序或未签的协议(如未履行审批程序、未签订补充协议)
- 违反的法律法规或制度名称及具体条款
- 造成的后果或潜在风险
**示例1:**
与崇川区华信机电经营部签订的五金电器采购合同存在大量合同外增项采购,累计金额66256.30元,未履行合同变更及增补审批程序,未签订补充协议,采取多次小额分散采购方式规避监管,违反《政府采购法》第四十九条
**示例2:**
与南通天星信息科技有限公司签订的合同存在严重合同外增项采购,累计547219.6元,占合同内付款金额252351.81元的216.8%,以'代购'名义扩大采购标的、按补税后价格结算,实质构成背离中标合同标的和价款的隐性协议,违反《招标投标法》第四十六条及实施条例第五十七条
**示例3:**
与南通力兰高科技发展有限公司签订的签到一体机采购合同约定4台总价28800元,实际入库8台,超合同数量收货且未签订补充协议、未履行变更审批,财务科未核验合同、签收、入库、付款一致性,超合同总价支付57600元,违反《政府采购法》第四十九条
**注意:remark必须是一段完整的叙述文字,不要分段、不要用编号列表、不要重复相同信息。**
## 报告内容:
{text_content}
## 输出格式(严格JSON数组):
```json
[
{{
"risk_desc": "风险点的简要描述(一句话概括)",
"is_economic": "否",
"survey_choice": "C",
"occurrence_count": 1,
"occurrence_amount": 0,
"remark": "风险事件的完整详细叙述(包含单位名称、金额、违规事实、违反法规等)",
"department": "相关科室名称"
}}
]
```
请只输出JSON数组,不要输出其他内容。"""
llm_cfg = get_llm_config()
client = OpenAI(api_key=llm_cfg["api_key"], base_url=llm_cfg["base_url"])
response = client.chat.completions.create(
model=llm_cfg["model"],
messages=[
{"role": "system", "content": "你是专业的医院风险管理专家,擅长从检查报告和审计报告中识别风险点并评估其严重程度。"},
{"role": "user", "content": prompt}
],
temperature=0.3,
)
result_text = response.choices[0].message.content.strip()
if '```json' in result_text:
start = result_text.index('```json') + 7
end = result_text.rindex('```')
result_text = result_text[start:end].strip()
elif '```' in result_text:
start = result_text.index('```') + 3
end = result_text.rindex('```')
result_text = result_text[start:end].strip()
risks = json.loads(result_text)
return risks
def _compare_with_existing_risks(ai_risks: list) -> list:
"""将AI提取的风险点与现有风险点唯一值进行语义比对
使用大模型进行语义级别的判断,只要含义一致或接近就认为是已存在的风险。
只有真正全新的风险才认为是新风险。
"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT risk_no, risk_desc FROM risk_unique_points")
existing_points = [dict(r) for r in cursor.fetchall()]
conn.close()
if not existing_points:
results = []
for ar in ai_risks:
results.append({
**ar,
"is_new": True,
"matched_risk_no": "",
"match_reason": "现有清单为空,全部为新风险"
})
return results
existing_lines = []
for ep in existing_points:
desc = (ep["risk_desc"] or "")[:120]
existing_lines.append(f"[{ep['risk_no']}] {desc}")
existing_text = '\n'.join(existing_lines)
ai_lines = []
for i, ar in enumerate(ai_risks):
ai_lines.append(f"风险点{i+1}: {ar.get('risk_desc', '')}")
ai_text = '\n'.join(ai_lines)
from openai import OpenAI
prompt = f"""你是一位专业的医院风险管理专家。请对以下两组风险点进行**语义层面**的对比分析。
## 现有风险点清单(已编号):
{existing_text}
## AI新识别的风险点:
{ai_text}
## 判断标准(非常重要):
1. **语义对比**,而非文字匹配。即使表述不同,只要风险事件含义一致或接近,就认为已存在。
2. 例如:"未按规定进行政府采购"和"采购流程缺乏合规审查"含义接近,应判定为已存在。
3. 只有真正全新的、现有清单中没有任何接近含义的风险点,才认为是新风险。
4. 宁可多判为"已存在",也不要漏判。如果不确定,倾向于匹配最接近的现有风险点。
## 输出格式(严格JSON数组):
```json
[
{{
"index": 1,
"is_new": false,
"matched_risk_no": "A10",
"match_reason": "语义匹配原因简述"
}}
]
```
字段说明:
- index: AI风险点序号(从1开始)
- is_new: true=新风险点,false=已存在
- matched_risk_no: 匹配的现有风险点编号(is_new为true时为空字符串)
- match_reason: 判定原因简述
请只输出JSON数组,不要输出其他内容。"""
llm_cfg = get_llm_config()
client = OpenAI(api_key=llm_cfg["api_key"], base_url=llm_cfg["base_url"])
response = client.chat.completions.create(
model=llm_cfg["model"],
messages=[
{"role": "system", "content": "你是专业的医院风险管理专家,擅长语义分析和风险点对比。你的判断准确、严谨。"},
{"role": "user", "content": prompt}
],
temperature=0.1,
)
result_text = response.choices[0].message.content.strip()
if '```json' in result_text:
start = result_text.index('```json') + 7
end = result_text.rindex('```')
result_text = result_text[start:end].strip()
elif '```' in result_text:
start = result_text.index('```') + 3
end = result_text.rindex('```')
result_text = result_text[start:end].strip()
llm_results = json.loads(result_text)
results = []
for i, ar in enumerate(ai_risks):
llm_match = None
for lr in llm_results:
if lr.get("index") == i + 1:
llm_match = lr
break
is_new = llm_match.get("is_new", True) if llm_match else True
matched_risk_no = llm_match.get("matched_risk_no", "") if llm_match else ""
match_reason = llm_match.get("match_reason", "") if llm_match else ""
results.append({
**ar,
"is_new": is_new,
"matched_risk_no": matched_risk_no,
"match_reason": match_reason
})
return results
# ====== 查询 ======
def list_reports(year: int) -> list:
"""获取某年度的检查报告列表"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM inspection_reports WHERE year = ? ORDER BY created_at DESC",
(year,)
)
rows = cursor.fetchall()
# 为每个报告附加数据条数
result = []
for r in rows:
item = dict(r)
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_data WHERE report_id = ?",
(item["id"],)
)
item["data_count"] = cursor.fetchone()["c"]
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_candidates WHERE report_id = ? AND status = '待审核'",
(item["id"],)
)
item["pending_count"] = cursor.fetchone()["c"]
result.append(item)
conn.close()
return result
def list_risk_data(year: int, report_id: int = None, keyword: str = None,
page: int = 1, page_size: int = 50) -> dict:
"""获取检查风险数据列表"""
conn = _get_conn()
cursor = conn.cursor()
where = "WHERE year = ?"
params = [year]
if report_id:
where += " AND report_id = ?"
params.append(report_id)
if keyword:
where += " AND (risk_desc LIKE ? OR risk_no LIKE ? OR department LIKE ? OR remark LIKE ?)"
params.extend([f"%{keyword}%"] * 4)
cursor.execute(f"SELECT COUNT(*) as total FROM inspection_risk_data {where}", params)
total = cursor.fetchone()["total"]
offset = (page - 1) * page_size
cursor.execute(
f"SELECT * FROM inspection_risk_data {where} ORDER BY is_economic DESC, risk_no ASC LIMIT ? OFFSET ?",
params + [page_size, offset]
)
rows = cursor.fetchall()
conn.close()
return {
"items": [dict(r) for r in rows],
"total": total,
"page": page,
"page_size": page_size,
"total_pages": (total + page_size - 1) // page_size
}
def list_candidates(report_id: int, status: str = None) -> dict:
"""获取某报告的候选风险点列表
新风险排在最前面
"""
conn = _get_conn()
cursor = conn.cursor()
where = "WHERE report_id = ?"
params = [report_id]
if status:
where += " AND status = ?"
params.append(status)
# 新风险(is_new=1)排在前面,待审核排前面
cursor.execute(
f"SELECT * FROM inspection_risk_candidates {where} ORDER BY is_new DESC, status ASC, id ASC",
params
)
rows = cursor.fetchall()
conn.close()
return {"items": [dict(r) for r in rows]}
# ====== 审核与入库 ======
def approve_candidate(candidate_id: int, data: dict) -> dict:
"""审核通过候选风险点,保存到 inspection_risk_data 表
如果是新风险(is_new=1),需要先将其添加到 risk_unique_points 表,
然后用新的 risk_no 保存到 inspection_risk_data。
"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_candidates WHERE id = ?", (candidate_id,))
candidate = cursor.fetchone()
if not candidate:
conn.close()
return {"error": "候选记录不存在"}
candidate = dict(candidate)
if candidate["status"] != "待审核":
conn.close()
return {"error": f"该记录状态为「{candidate['status']}」,无法审核"}
risk_no = candidate["risk_no"]
# 如果是新风险,先添加到 risk_unique_points
if candidate["is_new"] == 1:
risk_desc = data.get("risk_desc") or candidate["risk_desc"]
business_level = data.get("business_level", "")
business_framework = data.get("business_framework", "")
# 反查层面代码
level_code = ""
for code, info in BUSINESS_LEVELS.items():
if info["name"] == business_level:
level_code = code
break
if not level_code:
# 如果没有指定业务层面,使用默认值
level_code = "A"
business_level = BUSINESS_LEVELS["A"]["name"]
business_framework = BUSINESS_LEVELS["A"]["frameworks"][0]
# 获取下一个风险编号
cursor.execute(
"SELECT MAX(risk_number) as max_num FROM risk_unique_points WHERE level_code = ?",
(level_code,)
)
row = cursor.fetchone()
max_num = row["max_num"] if row and row["max_num"] else 0
next_num = max_num + 1
risk_no = f"{level_code}{next_num}"
# 插入到 risk_unique_points
cursor.execute("""
INSERT INTO risk_unique_points
(risk_no, risk_desc, business_level, business_framework, level_code, risk_number)
VALUES (?, ?, ?, ?, ?, ?)
""", (risk_no, risk_desc, business_level, business_framework, level_code, next_num))
# 使用用户可能修改的值
final_risk_desc = data.get("risk_desc") or candidate["risk_desc"]
final_department = data.get("department", candidate["department"])
final_is_economic = data.get("is_economic", candidate["is_economic"])
final_survey_choice = data.get("survey_choice", candidate["survey_choice"])
final_occurrence_count = data.get("occurrence_count", candidate["occurrence_count"])
final_occurrence_amount = data.get("occurrence_amount", candidate["occurrence_amount"])
final_remark = data.get("remark", candidate["remark"])
# 保存到 inspection_risk_data
cursor.execute("""
INSERT INTO inspection_risk_data
(year, report_id, risk_no, risk_desc, department, is_economic,
survey_choice, occurrence_count, occurrence_amount, remark,
batch_no, report_name, report_date, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '已入库')
""", (
candidate["year"], candidate["report_id"], risk_no,
final_risk_desc, final_department, final_is_economic,
final_survey_choice, final_occurrence_count, final_occurrence_amount,
final_remark,
_get_report_batch_no(cursor, candidate["report_id"]),
_get_report_name(cursor, candidate["report_id"]),
_get_report_date(cursor, candidate["report_id"])
))
# 更新候选记录状态
cursor.execute("""
UPDATE inspection_risk_candidates
SET status = '已通过', risk_no = ?
WHERE id = ?
""", (risk_no, candidate_id))
conn.commit()
conn.close()
return {"risk_no": risk_no, "candidate_id": candidate_id, "status": "已通过"}
def approve_all_candidates(report_id: int, data_list: list = None) -> dict:
"""批量审核通过所有待审核候选(使用候选原始数据)"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM inspection_risk_candidates WHERE report_id = ? AND status = '待审核'",
(report_id,)
)
candidates = [dict(r) for r in cursor.fetchall()]
conn.close()
approved = 0
errors = []
for c in candidates:
# 查找用户修改的数据
modified = None
if data_list:
for d in data_list:
if d.get("candidate_id") == c["id"]:
modified = d
break
result = approve_candidate(c["id"], modified or {})
if "error" in result:
errors.append({"candidate_id": c["id"], "error": result["error"]})
else:
approved += 1
return {"approved": approved, "errors": errors}
def reject_candidate(candidate_id: int, audit_remark: str = "") -> dict:
"""审核退回候选风险点"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_candidates WHERE id = ?", (candidate_id,))
candidate = cursor.fetchone()
if not candidate:
conn.close()
return {"error": "候选记录不存在"}
if candidate["status"] != "待审核":
conn.close()
return {"error": f"该记录状态为「{candidate['status']}」,无法操作"}
cursor.execute("""
UPDATE inspection_risk_candidates
SET status = '已退回'
WHERE id = ?
""", (candidate_id,))
conn.commit()
conn.close()
return {"candidate_id": candidate_id, "status": "已退回"}
def update_candidate(candidate_id: int, data: dict) -> dict:
"""编辑候选记录(审核前可修改)"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_candidates WHERE id = ?", (candidate_id,))
candidate = cursor.fetchone()
if not candidate:
conn.close()
return {"error": "候选记录不存在"}
updates = []
values = []
for field in ["risk_desc", "department", "is_economic", "survey_choice",
"occurrence_count", "occurrence_amount", "remark"]:
if field in data:
updates.append(f"{field} = ?")
values.append(data[field])
if updates:
values.append(candidate_id)
cursor.execute(
f"UPDATE inspection_risk_candidates SET {', '.join(updates)} WHERE id = ?",
values
)
conn.commit()
conn.close()
return {"candidate_id": candidate_id, "status": "已更新"}
def duplicate_candidate(candidate_id: int, data: dict) -> dict:
"""复制候选风险点记录,可指定不同科室
用于同一条风险需要归属到多个科室的场景。
新记录状态为「待审核」,保留原记录的所有其他字段。
"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_candidates WHERE id = ?", (candidate_id,))
candidate = cursor.fetchone()
if not candidate:
conn.close()
return {"error": "候选记录不存在"}
c = dict(candidate)
# 使用传入的值覆盖(如果有),否则保持原值
new_department = data.get("department", c.get("department", ""))
new_risk_desc = data.get("risk_desc", c.get("risk_desc", ""))
new_survey_choice = data.get("survey_choice", c.get("survey_choice", ""))
new_occurrence_count = data.get("occurrence_count", c.get("occurrence_count", 0))
new_occurrence_amount = data.get("occurrence_amount", c.get("occurrence_amount", 0))
new_remark = data.get("remark", c.get("remark", ""))
cursor.execute("""
INSERT INTO inspection_risk_candidates
(report_id, year, risk_no, risk_desc, department, is_economic,
survey_choice, occurrence_count, occurrence_amount, remark,
is_new, matched_risk_no, match_reason, ai_analysis, source_material, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '待审核')
""", (
c["report_id"], c.get("year", ""),
c.get("risk_no", ""),
new_risk_desc,
new_department,
c.get("is_economic", "否"),
new_survey_choice,
new_occurrence_count,
new_occurrence_amount,
new_remark,
c.get("is_new", 0),
c.get("matched_risk_no", ""),
c.get("match_reason", ""),
c.get("ai_analysis", ""),
c.get("source_material", ""),
))
new_id = cursor.lastrowid
conn.commit()
conn.close()
return {"candidate_id": new_id, "status": "已复制", "department": new_department}
# ====== 数据管理 ======
def update_risk_data(data_id: int, data: dict) -> dict:
"""修改已入库的检查风险数据"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_data WHERE id = ?", (data_id,))
row = cursor.fetchone()
if not row:
conn.close()
return {"error": "数据不存在"}
updates = []
values = []
for field in ["risk_no", "risk_desc", "department", "is_economic",
"survey_choice", "occurrence_count", "occurrence_amount", "remark"]:
if field in data:
updates.append(f"{field} = ?")
values.append(data[field])
if updates:
updates.append("updated_at = CURRENT_TIMESTAMP")
values.append(data_id)
cursor.execute(
f"UPDATE inspection_risk_data SET {', '.join(updates)} WHERE id = ?",
values
)
conn.commit()
conn.close()
return {"data_id": data_id, "status": "已更新"}
def delete_risk_data(data_id: int) -> dict:
"""删除单条检查风险数据"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inspection_risk_data WHERE id = ?", (data_id,))
row = cursor.fetchone()
if not row:
conn.close()
return {"error": "数据不存在"}
cursor.execute("DELETE FROM inspection_risk_data WHERE id = ?", (data_id,))
conn.commit()
conn.close()
return {"data_id": data_id, "status": "已删除"}
def batch_delete_by_report(report_id: int) -> dict:
"""按报告ID批量删除数据"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT report_name, batch_no FROM inspection_reports WHERE id = ?", (report_id,))
report = cursor.fetchone()
if not report:
conn.close()
return {"error": "报告不存在"}
# 删除风险数据
cursor.execute("DELETE FROM inspection_risk_data WHERE report_id = ?", (report_id,))
deleted_data = cursor.rowcount
# 删除候选记录
cursor.execute("DELETE FROM inspection_risk_candidates WHERE report_id = ?", (report_id,))
deleted_candidates = cursor.rowcount
# 删除报告记录
cursor.execute("DELETE FROM inspection_reports WHERE id = ?", (report_id,))
conn.commit()
conn.close()
return {
"report_id": report_id,
"report_name": report["report_name"],
"deleted_data": deleted_data,
"deleted_candidates": deleted_candidates,
"status": "已删除"
}
def batch_delete_by_batch_no(batch_no: str) -> dict:
"""按批次编号批量删除数据"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute("SELECT id, report_name FROM inspection_reports WHERE batch_no = ?", (batch_no,))
reports = cursor.fetchall()
if not reports:
conn.close()
return {"error": f"未找到批次编号 {batch_no} 对应的报告"}
total_data = 0
total_candidates = 0
report_names = []
for report in reports:
rid = report["id"]
report_names.append(report["report_name"])
cursor.execute("DELETE FROM inspection_risk_data WHERE report_id = ?", (rid,))
total_data += cursor.rowcount
cursor.execute("DELETE FROM inspection_risk_candidates WHERE report_id = ?", (rid,))
total_candidates += cursor.rowcount
cursor.execute("DELETE FROM inspection_reports WHERE id = ?", (rid,))
conn.commit()
conn.close()
return {
"batch_no": batch_no,
"report_names": report_names,
"deleted_data": total_data,
"deleted_candidates": total_candidates,
"status": "已删除"
}
def get_statistics(year: int) -> dict:
"""获取某年度检查风险数据统计"""
conn = _get_conn()
cursor = conn.cursor()
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_reports WHERE year = ?", (year,)
)
report_count = cursor.fetchone()["c"]
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_data WHERE year = ?", (year,)
)
data_count = cursor.fetchone()["c"]
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_data WHERE year = ? AND is_economic = '是'",
(year,)
)
economic_count = cursor.fetchone()["c"]
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_data WHERE year = ? AND is_economic = '否'",
(year,)
)
non_economic_count = cursor.fetchone()["c"]
cursor.execute(
"SELECT COUNT(*) as c FROM inspection_risk_candidates WHERE year = ? AND status = '待审核'",
(year,)
)
pending_count = cursor.fetchone()["c"]
conn.close()
return {
"report_count": report_count,
"data_count": data_count,
"economic_count": economic_count,
"non_economic_count": non_economic_count,
"pending_count": pending_count
}
# ====== 辅助函数 ======
def _get_report_batch_no(cursor, report_id: int) -> str:
cursor.execute("SELECT batch_no FROM inspection_reports WHERE id = ?", (report_id,))
row = cursor.fetchone()
return row["batch_no"] if row else ""
def _get_report_name(cursor, report_id: int) -> str:
cursor.execute("SELECT report_name FROM inspection_reports WHERE id = ?", (report_id,))
row = cursor.fetchone()
return row["report_name"] if row else ""
def _get_report_date(cursor, report_id: int) -> str:
cursor.execute("SELECT report_date FROM inspection_reports WHERE id = ?", (report_id,))
row = cursor.fetchone()
return row["report_date"] if row else ""
def _get_unique_desc_for_candidate(cursor, candidate):
"""对于已存在的风险,返回风险点唯一值的标准描述;新风险返回原描述"""
if not candidate.get('is_new') and candidate.get('matched_risk_no'):
cursor.execute(
'SELECT risk_desc FROM risk_unique_points WHERE risk_no = ?',
(candidate['matched_risk_no'],)
)
row = cursor.fetchone()
if row:
return row['risk_desc']
return candidate.get('risk_desc', '')
def _get_remark_for_candidate(cursor, candidate):
"""返回AI提取的风险事件详细叙述(remark字段)
无论新风险还是已存在风险,都直接使用AI生成的remark作为备注内容。
AI的remark已经包含了完整的详细叙述(单位名称、金额、违规事实、违反法规等),
不再与risk_desc拼接,避免内容冗余。
"""
return candidate.get('remark', '')