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,923 @@
# -*- coding: utf-8 -*-
"""本地SQLite数据服务 - 替代feishu_service.py,无需飞书授权"""
import sqlite3
import os
import json
import shutil
from typing import Optional
DB_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "audit_data.db")
UPLOAD_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "uploads")
# 兼容性常量:表ID(与原 feishu_service.py 保持一致,用于 main.py 中的引用)
TABLE_PERSON = "tblutZwgApXAnKjI"
TABLE_CATEGORY = "tbl71MxxuidDoAUL"
TABLE_YEAR = "tblq8b8EOk1Yx17n"
TABLE_PROJECT = "tbldPHt7BEgMgfq9"
TABLE_STEP = "tblzyCwBmc1a8jF2"
TABLE_AUDIT_DOC = "tblAAld30nkXHRhF"
TABLE_ANALYSIS_RESULT = "tblWb9ZI2pgrGCo2"
# 表ID到SQLite表名的映射
_TABLE_ID_MAP = {
TABLE_PERSON: "persons",
TABLE_CATEGORY: "categories",
TABLE_YEAR: "years",
TABLE_PROJECT: "projects",
TABLE_STEP: "steps",
TABLE_AUDIT_DOC: "audit_docs",
TABLE_ANALYSIS_RESULT: "analysis_results",
"person": "persons",
"category": "categories",
"year": "years",
"project": "projects",
"step": "steps",
"audit_doc": "audit_docs",
"analysis_result": "analysis_results",
}
class TokenExpiredError(Exception):
"""保留兼容性,本地模式下不会触发"""
pass
def _get_conn():
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA foreign_keys = ON")
return conn
def _to_int_id(id_val):
"""将ID转换为整数"""
if id_val is None:
return None
try:
return int(id_val)
except (ValueError, TypeError):
return None
def _normalize_risk_level(risk_level: str) -> str:
"""将LLM返回的风险等级归一化"""
risk = str(risk_level).strip().lower()
if "高" in risk:
return "高"
elif "低" in risk:
return "低"
elif "无" in risk or "零" in risk:
return "无"
else:
return "中"
# ====== 人员表操作 ======
def list_persons() -> list[dict]:
conn = _get_conn()
rows = conn.execute("SELECT * FROM persons ORDER BY id").fetchall()
conn.close()
return [_person_row_to_dict(r) for r in rows]
def get_person(person_id) -> Optional[dict]:
pid = _to_int_id(person_id)
if pid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM persons WHERE id = ?", (pid,)).fetchone()
conn.close()
return _person_row_to_dict(row) if row else None
def create_person(name: str, dept: str, role: str, contact: str = "") -> dict:
conn = _get_conn()
c = conn.cursor()
c.execute("INSERT INTO persons (name, department, role, contact) VALUES (?, ?, ?, ?)",
(name, dept, role, contact))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_person(person_id, name: str = None, dept: str = None, role: str = None, contact: str = None) -> dict:
pid = _to_int_id(person_id)
fields = {}
if name is not None: fields["name"] = name
if dept is not None: fields["department"] = dept
if role is not None: fields["role"] = role
if contact is not None: fields["contact"] = contact
if fields and pid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE persons SET {sets} WHERE id = ?", list(fields.values()) + [pid])
conn.commit()
conn.close()
return {"record_id": str(pid)}
def _person_row_to_dict(row):
if row is None:
return None
return {
"id": str(row["id"]),
"姓名": row["name"],
"部门": row["department"],
"角色": row["role"],
"联系方式": row["contact"]
}
# ====== 项目大类表操作 ======
def list_categories() -> list[dict]:
conn = _get_conn()
rows = conn.execute("SELECT * FROM categories ORDER BY id").fetchall()
conn.close()
return [_category_row_to_dict(r, conn) for r in rows]
def get_category(category_id) -> Optional[dict]:
cid = _to_int_id(category_id)
if cid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM categories WHERE id = ?", (cid,)).fetchone()
conn.close()
return _category_row_to_dict(row, conn) if row else None
def create_category(name: str, description: str = "", status: str = "未开始", leader_id: str = "") -> dict:
lid = _to_int_id(leader_id) if leader_id else None
conn = _get_conn()
c = conn.cursor()
c.execute("INSERT INTO categories (name, description, status, leader_id) VALUES (?, ?, ?, ?)",
(name, description, status, lid))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_category(category_id, name: str = None, description: str = None, status: str = None, leader_id: str = None) -> dict:
cid = _to_int_id(category_id)
fields = {}
if name is not None: fields["name"] = name
if description is not None: fields["description"] = description
if status is not None: fields["status"] = status
if leader_id is not None:
fields["leader_id"] = _to_int_id(leader_id) if leader_id else None
if fields and cid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE categories SET {sets} WHERE id = ?", list(fields.values()) + [cid])
conn.commit()
conn.close()
return {"record_id": str(cid)}
def _category_row_to_dict(row, conn):
if row is None:
return None
leader_id = row["leader_id"]
return {
"id": str(row["id"]),
"大类名称": row["name"],
"大类描述": row["description"],
"大类状态": row["status"],
"大类负责人": [str(leader_id)] if leader_id else []
}
# ====== 年度表操作 ======
def list_years() -> list[dict]:
conn = _get_conn()
rows = conn.execute("SELECT * FROM years ORDER BY id").fetchall()
conn.close()
return [_year_row_to_dict(r) for r in rows]
def get_year(year_id) -> Optional[dict]:
yid = _to_int_id(year_id)
if yid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM years WHERE id = ?", (yid,)).fetchone()
conn.close()
return _year_row_to_dict(row) if row else None
def create_year(year: str, name: str, goal: str = "", budget: float = 0,
status: str = "未开始", category_id: str = "", leader_id: str = "") -> dict:
cid = _to_int_id(category_id) if category_id else None
lid = _to_int_id(leader_id) if leader_id else None
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO years (year, name, goal, budget, status, category_id, leader_id)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(year, name, goal, budget, status, cid, lid))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_year(year_id, year: str = None, name: str = None, goal: str = None, budget: float = None,
status: str = None, category_id: str = None, leader_id: str = None) -> dict:
yid = _to_int_id(year_id)
fields = {}
if year is not None: fields["year"] = year
if name is not None: fields["name"] = name
if goal is not None: fields["goal"] = goal
if budget is not None: fields["budget"] = budget
if status is not None: fields["status"] = status
if category_id is not None:
fields["category_id"] = _to_int_id(category_id) if category_id else None
if leader_id is not None:
fields["leader_id"] = _to_int_id(leader_id) if leader_id else None
if fields and yid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE years SET {sets} WHERE id = ?", list(fields.values()) + [yid])
conn.commit()
conn.close()
return {"record_id": str(yid)}
def _year_row_to_dict(row):
if row is None:
return None
cat_id = row["category_id"]
leader_id = row["leader_id"]
return {
"id": str(row["id"]),
"年度": row["year"],
"年度名称": row["name"],
"年度目标": row["goal"],
"年度预算": row["budget"],
"年度状态": row["status"],
"所属大类": [str(cat_id)] if cat_id else [],
"年度负责人": [str(leader_id)] if leader_id else []
}
# ====== 项目表操作 ======
def list_projects() -> list[dict]:
conn = _get_conn()
rows = conn.execute("SELECT * FROM projects ORDER BY id").fetchall()
result = []
for r in rows:
d = _project_row_to_dict(r)
# 获取项目成员
members = conn.execute("SELECT person_id FROM project_members WHERE project_id = ?", (r["id"],)).fetchall()
d["项目成员"] = [str(m["person_id"]) for m in members]
result.append(d)
conn.close()
return result
def get_project(project_id) -> Optional[dict]:
pid = _to_int_id(project_id)
if pid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM projects WHERE id = ?", (pid,)).fetchone()
if not row:
conn.close()
return None
d = _project_row_to_dict(row)
members = conn.execute("SELECT person_id FROM project_members WHERE project_id = ?", (pid,)).fetchall()
d["项目成员"] = [str(m["person_id"]) for m in members]
conn.close()
return d
def create_project(name: str, description: str = "", status: str = "未开始",
priority: str = "P2", start_date: str = "", end_date: str = "",
budget: float = 0, risks: str = "", leader_id: str = "",
member_ids: list = None, year_id: str = "", category_id: str = "") -> dict:
yid = _to_int_id(year_id) if year_id else None
cid = _to_int_id(category_id) if category_id else None
lid = _to_int_id(leader_id) if leader_id else None
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO projects (name, description, status, priority, budget, risks,
start_date, end_date, year_id, category_id, leader_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(name, description, status, priority, budget, risks,
start_date, end_date, yid, cid, lid))
new_id = c.lastrowid
# 插入项目成员
if member_ids:
for mid in member_ids:
mid_int = _to_int_id(mid)
if mid_int:
c.execute("INSERT OR IGNORE INTO project_members (project_id, person_id) VALUES (?, ?)",
(new_id, mid_int))
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_project(project_id, name: str = None, description: str = None, status: str = None,
priority: str = None, start_date: str = None, end_date: str = None,
budget: float = None, risks: str = None, leader_id: str = None,
year_id: str = None, category_id: str = None) -> dict:
pid = _to_int_id(project_id)
fields = {}
if name is not None: fields["name"] = name
if description is not None: fields["description"] = description
if status is not None: fields["status"] = status
if priority is not None: fields["priority"] = priority
if start_date is not None: fields["start_date"] = start_date
if end_date is not None: fields["end_date"] = end_date
if budget is not None: fields["budget"] = budget
if risks is not None: fields["risks"] = risks
if leader_id is not None:
fields["leader_id"] = _to_int_id(leader_id) if leader_id else None
if year_id is not None:
fields["year_id"] = _to_int_id(year_id) if year_id else None
if category_id is not None:
fields["category_id"] = _to_int_id(category_id) if category_id else None
if fields and pid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE projects SET {sets} WHERE id = ?", list(fields.values()) + [pid])
conn.commit()
conn.close()
return {"record_id": str(pid)}
def _project_row_to_dict(row):
if row is None:
return None
year_id = row["year_id"]
cat_id = row["category_id"]
leader_id = row["leader_id"]
return {
"id": str(row["id"]),
"项目名称": row["name"],
"项目描述": row["description"],
"项目状态": row["status"],
"优先级": row["priority"],
"项目预算": row["budget"],
"风险与问题": row["risks"],
"开始日期": row["start_date"],
"结束日期": row["end_date"],
"所属年度": [str(year_id)] if year_id else [],
"所属大类": [str(cat_id)] if cat_id else [],
"项目负责人": [str(leader_id)] if leader_id else [],
"项目成员": [] # 由调用方填充
}
# ====== 项目步骤表操作 ======
def list_steps() -> list[dict]:
conn = _get_conn()
rows = conn.execute("SELECT * FROM steps ORDER BY id").fetchall()
conn.close()
return [_step_row_to_dict(r) for r in rows]
def get_step(step_id) -> Optional[dict]:
sid = _to_int_id(step_id)
if sid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM steps WHERE id = ?", (sid,)).fetchone()
conn.close()
return _step_row_to_dict(row) if row else None
def create_step(name: str, status: str = "待开始", priority: str = "P2",
start_date: str = "", end_date: str = "", progress: float = 0,
deliverable: str = "", remark: str = "", leader_id: str = "",
project_id: str = "", prev_step_id: str = "") -> dict:
pid = _to_int_id(project_id) if project_id else None
lid = _to_int_id(leader_id) if leader_id else None
prev_id = _to_int_id(prev_step_id) if prev_step_id else None
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO steps (name, status, priority, progress, deliverable, remark,
start_date, end_date, project_id, leader_id, prev_step_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(name, status, priority, progress, deliverable, remark,
start_date, end_date, pid, lid, prev_id))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_step(step_id, name: str = None, status: str = None, priority: str = None,
start_date: str = None, end_date: str = None, progress: float = None,
deliverable: str = None, remark: str = None, leader_id: str = None,
project_id: str = None, prev_step_id: str = None) -> dict:
sid = _to_int_id(step_id)
fields = {}
if name is not None: fields["name"] = name
if status is not None: fields["status"] = status
if priority is not None: fields["priority"] = priority
if progress is not None: fields["progress"] = progress
if deliverable is not None: fields["deliverable"] = deliverable
if remark is not None: fields["remark"] = remark
if start_date is not None: fields["start_date"] = start_date
if end_date is not None: fields["end_date"] = end_date
if leader_id is not None:
fields["leader_id"] = _to_int_id(leader_id) if leader_id else None
if project_id is not None:
fields["project_id"] = _to_int_id(project_id) if project_id else None
if prev_step_id is not None:
fields["prev_step_id"] = _to_int_id(prev_step_id) if prev_step_id else None
if fields and sid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE steps SET {sets} WHERE id = ?", list(fields.values()) + [sid])
conn.commit()
conn.close()
return {"record_id": str(sid)}
def _step_row_to_dict(row):
if row is None:
return None
proj_id = row["project_id"]
leader_id = row["leader_id"]
prev_id = row["prev_step_id"]
return {
"id": str(row["id"]),
"步骤名称": row["name"],
"步骤状态": row["status"],
"优先级": row["priority"],
"进度": row["progress"],
"交付物": row["deliverable"],
"备注": row["remark"],
"开始日期": row["start_date"],
"结束日期": row["end_date"],
"所属项目": [str(proj_id)] if proj_id else [],
"步骤负责人": [str(leader_id)] if leader_id else [],
"前置依赖": [str(prev_id)] if prev_id else []
}
# ====== 审计资料表操作 ======
def list_audit_docs(project_id=None) -> list[dict]:
conn = _get_conn()
if project_id:
pid = _to_int_id(project_id)
rows = conn.execute("SELECT * FROM audit_docs WHERE project_id = ? ORDER BY id", (pid,)).fetchall()
else:
rows = conn.execute("SELECT * FROM audit_docs ORDER BY id").fetchall()
result = []
for r in rows:
d = _audit_doc_row_to_dict(r)
# 获取附件
atts = conn.execute("SELECT * FROM attachments WHERE doc_id = ?", (r["id"],)).fetchall()
d["附件"] = [{"file_token": str(a["id"]), "name": a["file_name"], "size": a["file_size"]} for a in atts]
result.append(d)
conn.close()
return result
def get_audit_doc(doc_id) -> Optional[dict]:
did = _to_int_id(doc_id)
if did is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM audit_docs WHERE id = ?", (did,)).fetchone()
if not row:
conn.close()
return None
d = _audit_doc_row_to_dict(row)
atts = conn.execute("SELECT * FROM attachments WHERE doc_id = ?", (did,)).fetchall()
d["附件"] = [{"file_token": str(a["id"]), "name": a["file_name"], "size": a["file_size"]} for a in atts]
conn.close()
return d
def create_audit_doc(title: str, doc_type: str, project_id: str, content: str = "",
step_id: str = "") -> dict:
pid = _to_int_id(project_id) if project_id else None
sid = _to_int_id(step_id) if step_id else None
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO audit_docs (title, doc_type, content, status, project_id, step_id)
VALUES (?, ?, ?, '待分析', ?, ?)""",
(title, doc_type, content, pid, sid))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def update_audit_doc(doc_id, title: str = None, doc_type: str = None,
content: str = None, project_id: str = None,
step_id: str = None) -> dict:
did = _to_int_id(doc_id)
fields = {}
if title is not None: fields["title"] = title
if doc_type is not None: fields["doc_type"] = doc_type
if content is not None: fields["content"] = content
if project_id is not None:
fields["project_id"] = _to_int_id(project_id) if project_id else None
if step_id is not None:
fields["step_id"] = _to_int_id(step_id) if step_id else None
# 修改后自动重置状态为「待分析」
if fields:
fields["status"] = "待分析"
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE audit_docs SET {sets} WHERE id = ?", list(fields.values()) + [did])
conn.commit()
conn.close()
return {"record_id": str(did)}
def update_doc_status(doc_id, status: str):
did = _to_int_id(doc_id)
if did is None:
return
conn = _get_conn()
conn.execute("UPDATE audit_docs SET status = ? WHERE id = ?", (status, did))
conn.commit()
conn.close()
def _audit_doc_row_to_dict(row):
if row is None:
return None
proj_id = row["project_id"]
step_id = row["step_id"]
return {
"id": str(row["id"]),
"资料标题": row["title"],
"资料类型": row["doc_type"],
"正文内容": row["content"],
"资料状态": row["status"],
"所属项目": [str(proj_id)] if proj_id else [],
"所属步骤": [str(step_id)] if step_id else [],
"附件": [] # 由调用方填充
}
# ====== 附件操作 ======
def upload_attachment(doc_id: str, file_path: str) -> dict:
"""将文件复制到uploads目录并记录到数据库"""
did = _to_int_id(doc_id)
if did is None:
raise Exception("无效的资料ID")
abs_path = os.path.abspath(file_path)
file_name = os.path.basename(abs_path)
# 复制到uploads目录
dest_path = os.path.join(UPLOAD_DIR, file_name)
# 如果同名文件已存在,加序号
if os.path.exists(dest_path):
base, ext = os.path.splitext(file_name)
i = 1
while os.path.exists(os.path.join(UPLOAD_DIR, f"{base}_{i}{ext}")):
i += 1
file_name = f"{base}_{i}{ext}"
dest_path = os.path.join(UPLOAD_DIR, file_name)
shutil.copy2(abs_path, dest_path)
file_size = os.path.getsize(dest_path)
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO attachments (doc_id, file_name, file_path, file_size)
VALUES (?, ?, ?, ?)""", (did, file_name, dest_path, file_size))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"id": new_id, "file_name": file_name, "file_size": file_size}
def download_attachment(doc_id: str, file_token: str, output_dir: str) -> str:
"""从本地uploads目录复制附件到指定目录"""
att_id = _to_int_id(file_token)
if att_id is None:
return ""
conn = _get_conn()
row = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
conn.close()
if not row:
return ""
src_path = row["file_path"]
file_name = row["file_name"]
# 兼容历史数据:数据库里可能残留其他机器的绝对路径(如 F:\...),
# 找不到时回退到本机 uploads 目录下的同名文件
if not src_path or not os.path.exists(src_path):
fallback = os.path.join(UPLOAD_DIR, file_name)
if os.path.exists(fallback):
src_path = fallback
if not src_path or not os.path.exists(src_path):
return ""
dest_path = os.path.join(output_dir, file_name)
shutil.copy2(src_path, dest_path)
return dest_path
def remove_attachment(doc_id: str, file_token: str) -> dict:
"""删除附件记录和本地文件"""
att_id = _to_int_id(file_token)
if att_id is None:
return {}
conn = _get_conn()
row = conn.execute("SELECT * FROM attachments WHERE id = ?", (att_id,)).fetchone()
if row:
# 删除本地文件(同样兼容历史数据中的其他机器绝对路径)
target = row["file_path"]
if not target or not os.path.exists(target):
fallback = os.path.join(UPLOAD_DIR, row["file_name"])
if os.path.exists(fallback):
target = fallback
if target and os.path.exists(target):
os.remove(target)
conn.execute("DELETE FROM attachments WHERE id = ?", (att_id,))
conn.commit()
conn.close()
return {"deleted": True}
# ====== 分析结果表操作 ======
def list_analysis_results(doc_id=None) -> list[dict]:
conn = _get_conn()
if doc_id:
did = _to_int_id(doc_id)
rows = conn.execute("SELECT * FROM analysis_results WHERE doc_id = ? ORDER BY id", (did,)).fetchall()
else:
rows = conn.execute("SELECT * FROM analysis_results ORDER BY id").fetchall()
conn.close()
return [_analysis_row_to_dict(r) for r in rows]
def get_analysis_result(result_id) -> Optional[dict]:
rid = _to_int_id(result_id)
if rid is None:
return None
conn = _get_conn()
row = conn.execute("SELECT * FROM analysis_results WHERE id = ?", (rid,)).fetchone()
conn.close()
return _analysis_row_to_dict(row) if row else None
def create_analysis_result(doc_id: str, analysis_type: str,
summary: str, risk_level: str,
findings: str, suggestions: str,
raw_output: str) -> dict:
did = _to_int_id(doc_id) if doc_id else None
normalized_risk = _normalize_risk_level(risk_level)
conn = _get_conn()
c = conn.cursor()
c.execute("""INSERT INTO analysis_results (doc_id, analysis_type, summary, risk_level,
findings, suggestions, raw_output)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(did, analysis_type, summary, normalized_risk, findings, suggestions, raw_output))
new_id = c.lastrowid
conn.commit()
conn.close()
return {"record_id": str(new_id)}
def delete_analysis_result(result_id) -> bool:
"""删除单条分析结果(不动审计资料)
若该资料无其它分析结果,回退资料状态为"待分析"
"""
rid = _to_int_id(result_id)
if rid is None:
return False
conn = _get_conn()
# 先取 doc_id(用于回退资料状态)
row = conn.execute("SELECT doc_id FROM analysis_results WHERE id = ?", (rid,)).fetchone()
if not row:
conn.close()
return False
doc_id = row["doc_id"]
# 删除这条记录
conn.execute("DELETE FROM analysis_results WHERE id = ?", (rid,))
conn.commit()
conn.close()
# 回退资料状态:该资料无其它分析结果时才回退
if doc_id:
conn = _get_conn()
remain = conn.execute("SELECT COUNT(*) FROM analysis_results WHERE doc_id = ?", (doc_id,)).fetchone()[0]
conn.close()
if remain == 0:
update_doc_status(doc_id, "待分析")
return True
def update_analysis_result(result_id, analysis_type: str = None,
summary: str = None, risk_level: str = None,
findings: str = None, suggestions: str = None,
raw_output: str = None) -> dict:
rid = _to_int_id(result_id)
fields = {}
if analysis_type is not None: fields["analysis_type"] = analysis_type
if summary is not None: fields["summary"] = summary
if risk_level is not None: fields["risk_level"] = _normalize_risk_level(risk_level)
if findings is not None: fields["findings"] = findings
if suggestions is not None: fields["suggestions"] = suggestions
if raw_output is not None: fields["raw_output"] = raw_output
if fields and rid:
sets = ", ".join(f"{k} = ?" for k in fields)
conn = _get_conn()
conn.execute(f"UPDATE analysis_results SET {sets} WHERE id = ?", list(fields.values()) + [rid])
conn.commit()
conn.close()
return {"record_id": str(rid)}
def _analysis_row_to_dict(row):
if row is None:
return None
doc_id = row["doc_id"]
return {
"id": str(row["id"]),
"分析类型": row["analysis_type"],
"分析摘要": row["summary"],
"风险等级": row["risk_level"],
"关键发现": row["findings"],
"改进建议": row["suggestions"],
"原始模型输出": row["raw_output"],
"关联资料": [str(doc_id)] if doc_id else []
}
def delete_audit_doc_with_cascade(doc_id) -> dict:
"""删除审计资料,并级联删除关联的分析结果"""
did = _to_int_id(doc_id)
if did is None:
return {"doc_id": doc_id, "deleted_results": []}
conn = _get_conn()
# 查找关联的分析结果
results = conn.execute("SELECT id FROM analysis_results WHERE doc_id = ?", (did,)).fetchall()
deleted_results = [str(r["id"]) for r in results]
# 删除分析结果
conn.execute("DELETE FROM analysis_results WHERE doc_id = ?", (did,))
# 删除附件记录
conn.execute("DELETE FROM attachments WHERE doc_id = ?", (did,))
# 删除审计资料
conn.execute("DELETE FROM audit_docs WHERE id = ?", (did,))
conn.commit()
conn.close()
return {"doc_id": str(did), "deleted_results": deleted_results}
# ====== 删除与关联检查 ======
def _delete_record(table_key: str, record_id) -> dict:
"""通用删除(支持表ID和表key)"""
rid = _to_int_id(record_id)
table = _TABLE_ID_MAP.get(table_key, table_key)
if rid is None:
return {"deleted": False}
conn = _get_conn()
conn.execute(f"DELETE FROM {table} WHERE id = ?", (rid,))
conn.commit()
conn.close()
return {"deleted": True}
def check_related_records(record_id: str, table_key: str) -> list[dict]:
"""检查指定记录是否被其他表引用"""
rid_str = str(record_id)
rid_int = _to_int_id(record_id)
related = []
conn = _get_conn()
if table_key == 'person':
for c in list_categories():
if rid_str in (c.get("大类负责人") or []):
related.append({"table": "项目大类表", "record": c.get("大类名称"), "field": "大类负责人"})
for y in list_years():
if rid_str in (y.get("年度负责人") or []):
related.append({"table": "年度表", "record": y.get("年度名称"), "field": "年度负责人"})
for p in list_projects():
if rid_str in (p.get("项目负责人") or []):
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "项目负责人"})
if rid_str in (p.get("项目成员") or []):
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "项目成员"})
for s in list_steps():
if rid_str in (s.get("步骤负责人") or []):
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "步骤负责人"})
elif table_key == 'category':
for y in list_years():
if rid_str in (y.get("所属大类") or []):
related.append({"table": "年度表", "record": y.get("年度名称"), "field": "所属大类"})
for p in list_projects():
if rid_str in (p.get("所属大类") or []):
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "所属大类"})
elif table_key == 'year':
for p in list_projects():
if rid_str in (p.get("所属年度") or []):
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "所属年度"})
elif table_key == 'project':
for d in list_audit_docs():
if rid_str in (d.get("所属项目") or []):
related.append({"table": "审计资料表", "record": d.get("资料标题"), "field": "所属项目"})
for s in list_steps():
if rid_str in (s.get("所属项目") or []):
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "所属项目"})
elif table_key == 'step':
for s in list_steps():
if str(s.get("id")) == rid_str:
continue
if rid_str in (s.get("前置依赖") or []):
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "前置依赖"})
elif table_key == 'audit_doc':
for r in list_analysis_results():
if rid_str in (r.get("关联资料") or []):
related.append({"table": "分析结果表", "record": r.get("分析摘要"), "field": "关联资料"})
conn.close()
return related
# ====== 通用辅助函数(保持兼容性) ======
def _list_table(table_key: str) -> list[dict]:
"""通用列表函数"""
funcs = {
'person': list_persons,
'category': list_categories,
'year': list_years,
'project': list_projects,
'step': list_steps,
'audit_doc': list_audit_docs,
'analysis_result': list_analysis_results
}
func = funcs.get(table_key, table_key)
if callable(func):
return func()
return []
def _get_record(table_key: str, record_id) -> Optional[dict]:
"""通用获取函数"""
funcs = {
'person': get_person,
'category': get_category,
'year': get_year,
'project': get_project,
'step': get_step,
'audit_doc': get_audit_doc,
'analysis_result': get_analysis_result
}
func = funcs.get(table_key, table_key)
if callable(func):
return func(record_id)
return None
def _simplify_value(val):
"""保持兼容性 - 直接返回值"""
return val
def attach_workflow_meta(docs):
"""给审计资料附加作业流程状态(来自同库 workflow_meta,数字化审计写入)。"""
if not docs:
return docs
ids = []
for d in docs:
try:
ids.append(int(d.get("id")))
except Exception:
pass
if not ids:
return docs
try:
conn = _get_conn()
rows = conn.execute(
"SELECT doc_id,category,subtype,status,author,reviewer,review_comment "
f"FROM workflow_meta WHERE doc_id IN ({','.join('?' * len(ids))})", ids).fetchall()
conn.close()
except Exception:
return docs
meta = {int(r["doc_id"]): dict(r) for r in rows}
for d in docs:
try:
m = meta.get(int(d.get("id")))
except Exception:
m = None
if m:
d["流程状态"] = m.get("status") or ""
d["作业类别"] = m.get("category") or ""
d["作业子类型"] = m.get("subtype") or ""
d["编制人"] = m.get("author") or ""
d["复核人"] = m.get("reviewer") or ""
d["复核意见"] = m.get("review_comment") or ""
return docs