Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
This commit is contained in:
commit
b91954df4a
106 files changed
+43359
No files matched your search
@@ -0,0 +1 @@
|
||||
# 医院审计管理系统 - 服务层
|
||||
@@ -0,0 +1,192 @@
|
||||
"""附件内容提取服务 - 从上传的文件中提取文本内容供分析"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def extract_text_from_file(file_path: str) -> str:
|
||||
"""根据文件类型提取文本内容
|
||||
|
||||
Args:
|
||||
file_path: 本地文件路径
|
||||
|
||||
Returns:
|
||||
提取的文本内容,失败返回空字符串
|
||||
"""
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
return ""
|
||||
|
||||
ext = Path(file_path).suffix.lower()
|
||||
|
||||
if ext == '.txt':
|
||||
return _extract_txt(file_path)
|
||||
elif ext in ['.docx', '.doc']:
|
||||
return _extract_docx(file_path)
|
||||
elif ext == '.pdf':
|
||||
return _extract_pdf(file_path)
|
||||
elif ext in ['.xlsx', '.xls']:
|
||||
return _extract_excel(file_path)
|
||||
elif ext in ['.csv']:
|
||||
return _extract_csv(file_path)
|
||||
else:
|
||||
return f"【无法解析的文件格式:{ext},请将内容复制到正文】"
|
||||
|
||||
|
||||
def _extract_txt(file_path: str) -> str:
|
||||
"""提取 TXT 文件内容"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
return f.read()
|
||||
except UnicodeDecodeError:
|
||||
try:
|
||||
with open(file_path, 'r', encoding='gbk') as f:
|
||||
return f.read()
|
||||
except Exception:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_docx(file_path: str) -> str:
|
||||
"""提取 Word 文档内容"""
|
||||
try:
|
||||
from docx import Document
|
||||
doc = Document(file_path)
|
||||
paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
|
||||
return '\n'.join(paragraphs)
|
||||
except ImportError:
|
||||
return "【需要安装 python-docx 库以解析 Word 文档】"
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_pdf(file_path: str) -> str:
|
||||
"""提取 PDF 文件内容"""
|
||||
try:
|
||||
# 尝试使用 PyPDF2
|
||||
try:
|
||||
from PyPDF2 import PdfReader
|
||||
reader = PdfReader(file_path)
|
||||
texts = []
|
||||
for page in reader.pages:
|
||||
text = page.extract_text()
|
||||
if text:
|
||||
texts.append(text)
|
||||
return '\n'.join(texts)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# 尝试使用 pdfplumber
|
||||
try:
|
||||
import pdfplumber
|
||||
texts = []
|
||||
with pdfplumber.open(file_path) as pdf:
|
||||
for page in pdf.pages:
|
||||
text = page.extract_text()
|
||||
if text:
|
||||
texts.append(text)
|
||||
return '\n'.join(texts)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
return "【需要安装 PyPDF2 或 pdfplumber 库以解析 PDF 文件】"
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_excel(file_path: str) -> str:
|
||||
"""提取 Excel 文件内容"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(file_path, data_only=True)
|
||||
texts = []
|
||||
for sheet in wb.worksheets:
|
||||
texts.append(f"【工作表:{sheet.title}】")
|
||||
for row in sheet.iter_rows(values_only=True):
|
||||
row_text = ' | '.join(str(cell) for cell in row if cell is not None)
|
||||
if row_text.strip():
|
||||
texts.append(row_text)
|
||||
return '\n'.join(texts)
|
||||
except ImportError:
|
||||
return "【需要安装 openpyxl 库以解析 Excel 文件】"
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_csv(file_path: str) -> str:
|
||||
"""提取 CSV 文件内容"""
|
||||
try:
|
||||
import csv
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
reader = csv.reader(f)
|
||||
texts = []
|
||||
for row in reader:
|
||||
texts.append(' | '.join(row))
|
||||
return '\n'.join(texts)
|
||||
except UnicodeDecodeError:
|
||||
try:
|
||||
with open(file_path, 'r', encoding='gbk') as f:
|
||||
reader = csv.reader(f)
|
||||
texts = []
|
||||
for row in reader:
|
||||
texts.append(' | '.join(row))
|
||||
return '\n'.join(texts)
|
||||
except Exception:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def extract_from_doc_attachments(doc: dict, download_func) -> str:
|
||||
"""从审计资料记录的附件中提取内容
|
||||
|
||||
Args:
|
||||
doc: 审计资料记录字典(包含"附件"字段)
|
||||
download_func: 下载附件的函数,签名 download_func(doc_id, file_token, output_dir) -> file_path
|
||||
|
||||
Returns:
|
||||
提取的文本内容
|
||||
"""
|
||||
att_field = doc.get("附件")
|
||||
if not att_field:
|
||||
return ""
|
||||
|
||||
# 解析附件字段
|
||||
attachments = []
|
||||
if isinstance(att_field, list):
|
||||
for a in att_field:
|
||||
if isinstance(a, dict):
|
||||
attachments.append(a)
|
||||
elif isinstance(a, str):
|
||||
attachments.append({"name": a, "file_token": "", "size": 0})
|
||||
elif isinstance(att_field, str):
|
||||
attachments.append({"name": att_field, "file_token": "", "size": 0})
|
||||
|
||||
if not attachments:
|
||||
return ""
|
||||
|
||||
all_texts = []
|
||||
|
||||
for att in attachments:
|
||||
file_token = att.get("file_token", "")
|
||||
name = att.get("name", "未知文件")
|
||||
if not file_token:
|
||||
continue
|
||||
|
||||
try:
|
||||
# 下载附件
|
||||
from config import UPLOAD_DIR
|
||||
download_dir = os.path.join(UPLOAD_DIR, "downloads")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
saved_path = download_func(doc["id"], file_token, download_dir)
|
||||
|
||||
if saved_path and os.path.exists(saved_path):
|
||||
# 提取文本
|
||||
text = extract_text_from_file(saved_path)
|
||||
if text:
|
||||
all_texts.append(f"### 附件:{name}\n{text}")
|
||||
except Exception as e:
|
||||
print(f"提取附件 {name} 内容失败: {e}")
|
||||
continue
|
||||
|
||||
return "\n\n---\n\n".join(all_texts) if all_texts else ""
|
||||
@@ -0,0 +1,828 @@
|
||||
"""飞书多维表格服务 - 通过 lark-cli 操作 Base"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
from typing import Optional
|
||||
from config import (BASE_TOKEN, TABLE_PERSON, TABLE_CATEGORY, TABLE_YEAR,
|
||||
TABLE_PROJECT, TABLE_STEP, TABLE_AUDIT_DOC, TABLE_ANALYSIS_RESULT, UPLOAD_DIR)
|
||||
|
||||
|
||||
class TokenExpiredError(Exception):
|
||||
"""飞书 Token 过期异常"""
|
||||
pass
|
||||
|
||||
|
||||
def _run_lark(args: list[str], cwd: str = None) -> dict:
|
||||
"""执行 lark-cli 命令并返回 JSON 结果"""
|
||||
# lark-cli.exe 完整路径(由 trae-remote-official 插件提供)
|
||||
lark_cli = r"C:\Users\qinyi\.trae-cn\plugins\trae-remote-official\lark\1.0.3\bin\lark-cli.exe"
|
||||
if not os.path.exists(lark_cli):
|
||||
# 兜底:尝试 PATH 中的 lark-cli
|
||||
lark_cli = "lark-cli"
|
||||
cmd = [lark_cli] + args + ["--as", "user", "--format", "json"]
|
||||
result = subprocess.run(cmd, capture_output=True, encoding='utf-8', timeout=60, cwd=cwd)
|
||||
if result.returncode != 0:
|
||||
err = json.loads(result.stderr) if result.stderr else {"error": result.stderr}
|
||||
err_obj = err.get('error') or {}
|
||||
msg = err_obj.get('message', str(err)) if isinstance(err_obj, dict) else str(err)
|
||||
msg_lower = msg.lower()
|
||||
# 检测 token 过期或未授权,抛出专用异常便于上层识别
|
||||
if ('token expire' in msg_lower or 'token expired' in msg_lower
|
||||
or 'unauthorized' in msg_lower or 'not configured' in msg_lower
|
||||
or 'no token' in msg_lower or 'not authorized' in msg_lower
|
||||
or 'permission denied' in msg_lower or 'invalid token' in msg_lower):
|
||||
raise TokenExpiredError(f"飞书授权已过期或未配置,请在 TRAE 中重新授权飞书插件")
|
||||
raise Exception(f"lark-cli 调用失败: {msg}")
|
||||
if not result.stdout:
|
||||
raise Exception(f"lark-cli 返回空输出 (returncode={result.returncode}, stderr={result.stderr[:200] if result.stderr else 'none'})")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
# ====== 项目表操作 ======
|
||||
|
||||
def list_projects() -> list[dict]:
|
||||
"""获取项目列表"""
|
||||
data = _run_lark(["base", "+record-list",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_PROJECT])
|
||||
records = []
|
||||
field_names = data["data"]["fields"]
|
||||
for i, row in enumerate(data["data"]["data"]):
|
||||
record = {"id": data["data"]["record_id_list"][i]}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def get_project(project_id: str) -> Optional[dict]:
|
||||
"""获取单个项目"""
|
||||
data = _run_lark(["base", "+record-get",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_PROJECT,
|
||||
"--record-id", project_id])
|
||||
records = data["data"]["data"]
|
||||
if not records:
|
||||
return None
|
||||
field_names = data["data"]["fields"]
|
||||
row = records[0]
|
||||
record = {"id": project_id}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
return record
|
||||
|
||||
|
||||
# ====== 审计资料表操作 ======
|
||||
|
||||
def list_audit_docs(project_id: Optional[str] = None) -> list[dict]:
|
||||
"""获取审计资料列表,可按项目筛选"""
|
||||
data = _run_lark(["base", "+record-list",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC])
|
||||
records = []
|
||||
field_names = data["data"]["fields"]
|
||||
for i, row in enumerate(data["data"]["data"]):
|
||||
record = {"id": data["data"]["record_id_list"][i]}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def get_audit_doc(doc_id: str) -> Optional[dict]:
|
||||
"""获取单个审计资料详情"""
|
||||
data = _run_lark(["base", "+record-get",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id])
|
||||
records = data["data"]["data"]
|
||||
if not records:
|
||||
return None
|
||||
field_names = data["data"]["fields"]
|
||||
row = records[0]
|
||||
record = {"id": doc_id}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
return record
|
||||
|
||||
|
||||
def create_audit_doc(title: str, doc_type: str, project_id: str, content: str = "",
|
||||
step_id: str = "") -> dict:
|
||||
"""创建审计资料记录,返回包含 record_id 的简化结构"""
|
||||
fields = {
|
||||
"资料标题": title,
|
||||
"资料类型": doc_type,
|
||||
"所属项目": [{"id": project_id}],
|
||||
"正文内容": content,
|
||||
"资料状态": "待分析"
|
||||
}
|
||||
if step_id:
|
||||
fields["所属步骤"] = [{"id": step_id}]
|
||||
data = _run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--json", json.dumps(fields, ensure_ascii=False)])
|
||||
raw = data.get("data", {})
|
||||
record_ids = raw.get("record", {}).get("record_id_list", [])
|
||||
return {"record_id": record_ids[0] if record_ids else ""}
|
||||
|
||||
|
||||
def update_doc_status(doc_id: str, status: str):
|
||||
"""更新资料状态"""
|
||||
from config import TABLE_AUDIT_DOC
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--json", json.dumps({
|
||||
"资料状态": status
|
||||
}, ensure_ascii=False)])
|
||||
|
||||
|
||||
def update_audit_doc(doc_id: str, title: str = None, doc_type: str = None,
|
||||
content: str = None, project_id: str = None,
|
||||
step_id: str = None) -> dict:
|
||||
"""更新审计资料记录,并自动重置状态为待分析"""
|
||||
# 第一步:更新文本字段(关联字段需单独更新才能生效)
|
||||
text_fields = {}
|
||||
if title is not None:
|
||||
text_fields["资料标题"] = title
|
||||
if doc_type is not None:
|
||||
text_fields["资料类型"] = doc_type
|
||||
if content is not None:
|
||||
text_fields["正文内容"] = content
|
||||
# 修改后自动重置状态为「待分析」,以便重新分析
|
||||
text_fields["资料状态"] = "待分析"
|
||||
|
||||
if text_fields:
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--json", json.dumps(text_fields, ensure_ascii=False)])
|
||||
|
||||
# 第二步:单独更新关联字段(所属项目)
|
||||
if project_id is not None:
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--json", json.dumps({"所属项目": [{"id": project_id}]}, ensure_ascii=False)])
|
||||
|
||||
# 第三步:单独更新关联字段(所属步骤)
|
||||
if step_id is not None:
|
||||
step_fields = {"所属步骤": [{"id": step_id}] if step_id else []}
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--json", json.dumps(step_fields, ensure_ascii=False)])
|
||||
|
||||
return {"record_id": doc_id}
|
||||
|
||||
|
||||
def upload_attachment(doc_id: str, file_path: str) -> dict:
|
||||
"""上传文件附件到审计资料记录"""
|
||||
abs_path = os.path.abspath(file_path)
|
||||
upload_dir = os.path.dirname(abs_path)
|
||||
file_name = os.path.basename(abs_path)
|
||||
data = _run_lark(["base", "+record-upload-attachment",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--field-id", "附件",
|
||||
"--file", file_name],
|
||||
cwd=upload_dir)
|
||||
return data["data"]
|
||||
|
||||
|
||||
def download_attachment(doc_id: str, file_token: str, output_dir: str) -> str:
|
||||
"""下载审计资料附件到指定目录,返回保存的文件路径"""
|
||||
# lark-cli 要求 --output 为相对路径,需通过 cwd 切换到目标目录
|
||||
data = _run_lark(["base", "+record-download-attachment",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--file-token", file_token,
|
||||
"--output", ".",
|
||||
"--overwrite"],
|
||||
cwd=output_dir)
|
||||
# lark-cli 返回下载结果中包含文件名
|
||||
result = data.get("data", {})
|
||||
# 尝试从返回数据中提取文件路径/文件名
|
||||
file_name = result.get("file_name") or result.get("name") or ""
|
||||
if not file_name:
|
||||
# 如果返回数据中有 files 列表
|
||||
files = result.get("files", [])
|
||||
if files and isinstance(files[0], dict):
|
||||
file_name = files[0].get("name", "") or files[0].get("file_name", "")
|
||||
elif files and isinstance(files[0], str):
|
||||
file_name = files[0]
|
||||
if file_name:
|
||||
return os.path.join(output_dir, file_name)
|
||||
return ""
|
||||
|
||||
|
||||
def remove_attachment(doc_id: str, file_token: str) -> dict:
|
||||
"""删除审计资料记录中的指定附件
|
||||
|
||||
Args:
|
||||
doc_id: 审计资料记录ID
|
||||
file_token: 要删除的附件file_token
|
||||
"""
|
||||
data = _run_lark(["base", "+record-remove-attachment",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--field-id", "附件",
|
||||
"--file-token", file_token,
|
||||
"--yes"])
|
||||
return data.get("data", {})
|
||||
|
||||
|
||||
# ====== 分析结果表操作 ======
|
||||
|
||||
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 create_analysis_result(doc_id: str, analysis_type: str,
|
||||
summary: str, risk_level: str,
|
||||
findings: str, suggestions: str,
|
||||
raw_output: str) -> dict:
|
||||
"""创建分析结果记录,并建立与审计资料的双向关联"""
|
||||
# 归一化风险等级为预定义选项:高/中/低/无
|
||||
normalized_risk = _normalize_risk_level(risk_level)
|
||||
|
||||
# 第一步:先创建分析结果记录(不含关联字段)
|
||||
data = _run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_ANALYSIS_RESULT,
|
||||
"--json", json.dumps({
|
||||
"分析类型": analysis_type,
|
||||
"分析摘要": summary,
|
||||
"风险等级": normalized_risk,
|
||||
"关键发现": findings,
|
||||
"改进建议": suggestions,
|
||||
"原始模型输出": raw_output
|
||||
}, ensure_ascii=False)])
|
||||
raw = data.get("data", {})
|
||||
record_ids = raw.get("record", {}).get("record_id_list", [])
|
||||
result_id = record_ids[0] if record_ids else ""
|
||||
|
||||
# 第二步:用 --record-id 更新关联资料字段(link 字段在创建时可能不生效)
|
||||
if result_id and doc_id:
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_ANALYSIS_RESULT,
|
||||
"--record-id", result_id,
|
||||
"--json", json.dumps({
|
||||
"关联资料": [{"id": doc_id}]
|
||||
}, ensure_ascii=False)])
|
||||
|
||||
# 第三步:更新审计资料表的"分析结果"反向关联字段
|
||||
if doc_id:
|
||||
try:
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_AUDIT_DOC,
|
||||
"--record-id", doc_id,
|
||||
"--json", json.dumps({
|
||||
"分析结果": [{"id": result_id}]
|
||||
}, ensure_ascii=False)])
|
||||
except Exception:
|
||||
pass # 反向关联失败不影响主流程
|
||||
|
||||
return {"record_id": result_id}
|
||||
|
||||
|
||||
def list_analysis_results(doc_id: Optional[str] = None) -> list[dict]:
|
||||
"""获取分析结果列表"""
|
||||
data = _run_lark(["base", "+record-list",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_ANALYSIS_RESULT])
|
||||
records = []
|
||||
field_names = data["data"]["fields"]
|
||||
for i, row in enumerate(data["data"]["data"]):
|
||||
record = {"id": data["data"]["record_id_list"][i]}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def get_analysis_result(result_id: str) -> Optional[dict]:
|
||||
"""获取单个分析结果"""
|
||||
data = _run_lark(["base", "+record-get",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_ANALYSIS_RESULT,
|
||||
"--record-id", result_id])
|
||||
records = data["data"]["data"]
|
||||
if not records:
|
||||
return None
|
||||
field_names = data["data"]["fields"]
|
||||
row = records[0]
|
||||
record = {"id": result_id}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
return record
|
||||
|
||||
|
||||
def delete_analysis_result(result_id: str) -> bool:
|
||||
"""删除单条分析结果(不动关联的审计资料)
|
||||
|
||||
删除后将资料的"资料状态"回退为"待分析"(如果该资料没有其它分析结果)。
|
||||
"""
|
||||
# 先取这条分析结果关联的资料ID,用于后续回退状态
|
||||
target = None
|
||||
for r in list_analysis_results():
|
||||
if r.get("id") == result_id:
|
||||
target = r
|
||||
break
|
||||
if not target:
|
||||
return False
|
||||
doc_refs = target.get("关联资料") or []
|
||||
|
||||
# 删除分析结果记录
|
||||
_delete_record(TABLE_ANALYSIS_RESULT, result_id)
|
||||
|
||||
# 回退资料状态:只在该资料没有其它分析结果时才回退
|
||||
for doc_id in doc_refs:
|
||||
if not isinstance(doc_id, str) or not doc_id:
|
||||
continue
|
||||
still_has = any(
|
||||
(r.get("id") != result_id) and (doc_id in (r.get("关联资料") or []))
|
||||
for r in list_analysis_results()
|
||||
)
|
||||
if not still_has:
|
||||
try:
|
||||
update_doc_status(doc_id, "待分析")
|
||||
except Exception:
|
||||
pass # 状态回退失败不影响删除主流程
|
||||
return True
|
||||
|
||||
|
||||
def update_analysis_result(result_id: str, analysis_type: str = None,
|
||||
summary: str = None, risk_level: str = None,
|
||||
findings: str = None, suggestions: str = None,
|
||||
raw_output: str = None) -> dict:
|
||||
"""更新分析结果记录"""
|
||||
fields = {}
|
||||
if analysis_type is not None:
|
||||
fields["分析类型"] = analysis_type
|
||||
if summary is not None:
|
||||
fields["分析摘要"] = summary
|
||||
if risk_level is not None:
|
||||
fields["风险等级"] = _normalize_risk_level(risk_level)
|
||||
if findings is not None:
|
||||
fields["关键发现"] = findings
|
||||
if suggestions is not None:
|
||||
fields["改进建议"] = suggestions
|
||||
if raw_output is not None:
|
||||
fields["原始模型输出"] = raw_output
|
||||
|
||||
if not fields:
|
||||
return {"record_id": result_id}
|
||||
|
||||
data = _run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", TABLE_ANALYSIS_RESULT,
|
||||
"--record-id", result_id,
|
||||
"--json", json.dumps(fields, ensure_ascii=False)])
|
||||
raw = data.get("data", {})
|
||||
record_ids = raw.get("record", {}).get("record_id_list", [])
|
||||
return {"record_id": record_ids[0] if record_ids else result_id}
|
||||
|
||||
|
||||
def delete_audit_doc_with_cascade(doc_id: str) -> dict:
|
||||
"""删除审计资料,并级联删除关联的分析结果记录"""
|
||||
deleted_results = []
|
||||
|
||||
# 1. 查找并删除关联的分析结果
|
||||
for r in list_analysis_results():
|
||||
refs = r.get("关联资料") or []
|
||||
if doc_id in refs:
|
||||
try:
|
||||
_delete_record(TABLE_ANALYSIS_RESULT, r["id"])
|
||||
deleted_results.append(r["id"])
|
||||
except Exception:
|
||||
pass # 单条删除失败不影响主流程
|
||||
|
||||
# 2. 删除审计资料本身
|
||||
_delete_record(TABLE_AUDIT_DOC, doc_id)
|
||||
|
||||
return {"doc_id": doc_id, "deleted_results": deleted_results}
|
||||
|
||||
|
||||
# ====== 通用辅助函数 ======
|
||||
|
||||
def _list_table(table_id: str) -> list[dict]:
|
||||
"""通用:获取指定表的所有记录"""
|
||||
data = _run_lark(["base", "+record-list",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", table_id])
|
||||
records = []
|
||||
field_names = data["data"]["fields"]
|
||||
for i, row in enumerate(data["data"]["data"]):
|
||||
record = {"id": data["data"]["record_id_list"][i]}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def _get_record(table_id: str, record_id: str) -> Optional[dict]:
|
||||
"""通用:获取指定表的单个记录"""
|
||||
data = _run_lark(["base", "+record-get",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", table_id,
|
||||
"--record-id", record_id])
|
||||
records = data["data"]["data"]
|
||||
if not records:
|
||||
return None
|
||||
field_names = data["data"]["fields"]
|
||||
row = records[0]
|
||||
record = {"id": record_id}
|
||||
for j, val in enumerate(row):
|
||||
field_name = field_names[j]
|
||||
record[field_name] = _simplify_value(val)
|
||||
return record
|
||||
|
||||
|
||||
def _create_record(table_id: str, fields: dict) -> dict:
|
||||
"""通用:创建记录并返回 record_id"""
|
||||
data = _run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", table_id,
|
||||
"--json", json.dumps(fields, ensure_ascii=False)])
|
||||
raw = data.get("data", {})
|
||||
record_ids = raw.get("record", {}).get("record_id_list", [])
|
||||
return {"record_id": record_ids[0] if record_ids else ""}
|
||||
|
||||
|
||||
def _update_record(table_id: str, record_id: str, fields: dict) -> dict:
|
||||
"""通用:更新记录"""
|
||||
_run_lark(["base", "+record-upsert",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", table_id,
|
||||
"--record-id", record_id,
|
||||
"--json", json.dumps(fields, ensure_ascii=False)])
|
||||
return {"record_id": record_id}
|
||||
|
||||
|
||||
# ====== 人员表操作 ======
|
||||
|
||||
def list_persons() -> list[dict]:
|
||||
"""获取人员列表"""
|
||||
return _list_table(TABLE_PERSON)
|
||||
|
||||
|
||||
def get_person(person_id: str) -> Optional[dict]:
|
||||
"""获取单个人员"""
|
||||
return _get_record(TABLE_PERSON, person_id)
|
||||
|
||||
|
||||
def create_person(name: str, dept: str, role: str, contact: str = "") -> dict:
|
||||
"""创建人员记录"""
|
||||
return _create_record(TABLE_PERSON, {
|
||||
"姓名": name,
|
||||
"部门": dept,
|
||||
"角色": role,
|
||||
"联系方式": contact
|
||||
})
|
||||
|
||||
|
||||
def update_person(person_id: str, name: str = None, dept: str = None, role: str = None, contact: str = None) -> dict:
|
||||
"""更新人员记录"""
|
||||
fields = {}
|
||||
if name is not None: fields["姓名"] = name
|
||||
if dept is not None: fields["部门"] = dept
|
||||
if role is not None: fields["角色"] = role
|
||||
if contact is not None: fields["联系方式"] = contact
|
||||
return _update_record(TABLE_PERSON, person_id, fields)
|
||||
|
||||
|
||||
# ====== 项目大类表操作 ======
|
||||
|
||||
def list_categories() -> list[dict]:
|
||||
"""获取项目大类列表"""
|
||||
return _list_table(TABLE_CATEGORY)
|
||||
|
||||
|
||||
def get_category(category_id: str) -> Optional[dict]:
|
||||
"""获取单个项目大类"""
|
||||
return _get_record(TABLE_CATEGORY, category_id)
|
||||
|
||||
|
||||
def create_category(name: str, description: str = "", status: str = "未开始", leader_id: str = "") -> dict:
|
||||
"""创建项目大类记录"""
|
||||
fields = {"大类名称": name, "大类描述": description, "大类状态": status}
|
||||
if leader_id:
|
||||
fields["大类负责人"] = [{"id": leader_id}]
|
||||
return _create_record(TABLE_CATEGORY, fields)
|
||||
|
||||
|
||||
def update_category(category_id: str, name: str = None, description: str = None, status: str = None, leader_id: str = None) -> dict:
|
||||
"""更新项目大类记录"""
|
||||
fields = {}
|
||||
if name is not None: fields["大类名称"] = name
|
||||
if description is not None: fields["大类描述"] = description
|
||||
if status is not None: fields["大类状态"] = status
|
||||
if leader_id is not None:
|
||||
fields["大类负责人"] = [{"id": leader_id}] if leader_id else []
|
||||
return _update_record(TABLE_CATEGORY, category_id, fields)
|
||||
|
||||
|
||||
# ====== 年度表操作 ======
|
||||
|
||||
def list_years() -> list[dict]:
|
||||
"""获取年度列表"""
|
||||
return _list_table(TABLE_YEAR)
|
||||
|
||||
|
||||
def get_year(year_id: str) -> Optional[dict]:
|
||||
"""获取单个年度"""
|
||||
return _get_record(TABLE_YEAR, year_id)
|
||||
|
||||
|
||||
def create_year(year: str, name: str, goal: str = "", budget: float = 0,
|
||||
status: str = "未开始", category_id: str = "", leader_id: str = "") -> dict:
|
||||
"""创建年度记录"""
|
||||
fields = {
|
||||
"年度": year,
|
||||
"年度名称": name,
|
||||
"年度目标": goal,
|
||||
"年度预算": budget,
|
||||
"年度状态": status
|
||||
}
|
||||
if category_id:
|
||||
fields["所属大类"] = [{"id": category_id}]
|
||||
if leader_id:
|
||||
fields["年度负责人"] = [{"id": leader_id}]
|
||||
return _create_record(TABLE_YEAR, fields)
|
||||
|
||||
|
||||
def update_year(year_id: str, year: str = None, name: str = None, goal: str = None, budget: float = None,
|
||||
status: str = None, category_id: str = None, leader_id: str = None) -> dict:
|
||||
"""更新年度记录"""
|
||||
fields = {}
|
||||
if year is not None: fields["年度"] = year
|
||||
if name is not None: fields["年度名称"] = name
|
||||
if goal is not None: fields["年度目标"] = goal
|
||||
if budget is not None: fields["年度预算"] = budget
|
||||
if status is not None: fields["年度状态"] = status
|
||||
if category_id is not None:
|
||||
fields["所属大类"] = [{"id": category_id}] if category_id else []
|
||||
if leader_id is not None:
|
||||
fields["年度负责人"] = [{"id": leader_id}] if leader_id else []
|
||||
return _update_record(TABLE_YEAR, year_id, fields)
|
||||
|
||||
|
||||
# ====== 项目表操作(补充 create) ======
|
||||
|
||||
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:
|
||||
"""创建项目记录"""
|
||||
fields = {
|
||||
"项目名称": name,
|
||||
"项目描述": description,
|
||||
"项目状态": status,
|
||||
"优先级": priority,
|
||||
"风险与问题": risks
|
||||
}
|
||||
if start_date:
|
||||
fields["开始日期"] = start_date
|
||||
if end_date:
|
||||
fields["结束日期"] = end_date
|
||||
if budget:
|
||||
fields["项目预算"] = budget
|
||||
if leader_id:
|
||||
fields["项目负责人"] = [{"id": leader_id}]
|
||||
if member_ids:
|
||||
fields["项目成员"] = [{"id": mid} for mid in member_ids]
|
||||
if year_id:
|
||||
fields["所属年度"] = [{"id": year_id}]
|
||||
if category_id:
|
||||
fields["所属大类"] = [{"id": category_id}]
|
||||
return _create_record(TABLE_PROJECT, fields)
|
||||
|
||||
|
||||
def update_project(project_id: str, 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:
|
||||
"""更新项目记录"""
|
||||
fields = {}
|
||||
if name is not None: fields["项目名称"] = name
|
||||
if description is not None: fields["项目描述"] = description
|
||||
if status is not None: fields["项目状态"] = status
|
||||
if priority is not None: fields["优先级"] = priority
|
||||
if start_date is not None:
|
||||
fields["开始日期"] = start_date
|
||||
if end_date is not None:
|
||||
fields["结束日期"] = end_date
|
||||
if budget is not None: fields["项目预算"] = budget
|
||||
if risks is not None: fields["风险与问题"] = risks
|
||||
if leader_id is not None:
|
||||
fields["项目负责人"] = [{"id": leader_id}] if leader_id else []
|
||||
if year_id is not None:
|
||||
fields["所属年度"] = [{"id": year_id}] if year_id else []
|
||||
if category_id is not None:
|
||||
fields["所属大类"] = [{"id": category_id}] if category_id else []
|
||||
return _update_record(TABLE_PROJECT, project_id, fields)
|
||||
|
||||
|
||||
# ====== 项目步骤表操作 ======
|
||||
|
||||
def list_steps() -> list[dict]:
|
||||
"""获取项目步骤列表"""
|
||||
return _list_table(TABLE_STEP)
|
||||
|
||||
|
||||
def get_step(step_id: str) -> Optional[dict]:
|
||||
"""获取单个项目步骤"""
|
||||
return _get_record(TABLE_STEP, step_id)
|
||||
|
||||
|
||||
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:
|
||||
"""创建项目步骤记录"""
|
||||
fields = {
|
||||
"步骤名称": name,
|
||||
"步骤状态": status,
|
||||
"优先级": priority,
|
||||
"进度": progress,
|
||||
"交付物": deliverable,
|
||||
"备注": remark
|
||||
}
|
||||
if start_date:
|
||||
fields["开始日期"] = start_date
|
||||
if end_date:
|
||||
fields["结束日期"] = end_date
|
||||
if leader_id:
|
||||
fields["步骤负责人"] = [{"id": leader_id}]
|
||||
if project_id:
|
||||
fields["所属项目"] = [{"id": project_id}]
|
||||
if prev_step_id:
|
||||
fields["前置依赖"] = [{"id": prev_step_id}]
|
||||
return _create_record(TABLE_STEP, fields)
|
||||
|
||||
|
||||
def update_step(step_id: str, 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:
|
||||
"""更新项目步骤记录"""
|
||||
fields = {}
|
||||
if name is not None: fields["步骤名称"] = name
|
||||
if status is not None: fields["步骤状态"] = status
|
||||
if priority is not None: fields["优先级"] = priority
|
||||
if progress is not None: fields["进度"] = progress
|
||||
if deliverable is not None: fields["交付物"] = deliverable
|
||||
if remark is not None: fields["备注"] = remark
|
||||
if start_date is not None:
|
||||
fields["开始日期"] = start_date
|
||||
if end_date is not None:
|
||||
fields["结束日期"] = end_date
|
||||
if leader_id is not None:
|
||||
fields["步骤负责人"] = [{"id": leader_id}] if leader_id else []
|
||||
if project_id is not None:
|
||||
fields["所属项目"] = [{"id": project_id}] if project_id else []
|
||||
if prev_step_id is not None:
|
||||
fields["前置依赖"] = [{"id": prev_step_id}] if prev_step_id else []
|
||||
return _update_record(TABLE_STEP, step_id, fields)
|
||||
|
||||
|
||||
# ====== 删除与关联检查 ======
|
||||
|
||||
def _delete_record(table_id: str, record_id: str) -> dict:
|
||||
"""通用:删除记录"""
|
||||
data = _run_lark(["base", "+record-delete",
|
||||
"--base-token", BASE_TOKEN,
|
||||
"--table-id", table_id,
|
||||
"--record-id", record_id,
|
||||
"--yes"])
|
||||
return data.get("data", {})
|
||||
|
||||
|
||||
def check_related_records(record_id: str, table_key: str) -> list[dict]:
|
||||
"""检查指定记录是否被其他表引用,返回关联信息列表"""
|
||||
related = []
|
||||
|
||||
if table_key == 'person':
|
||||
# 检查项目大类表
|
||||
for c in list_categories():
|
||||
refs = c.get("大类负责人") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目大类表", "record": c.get("大类名称"), "field": "大类负责人"})
|
||||
# 检查年度表
|
||||
for y in list_years():
|
||||
refs = y.get("年度负责人") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "年度表", "record": y.get("年度名称"), "field": "年度负责人"})
|
||||
# 检查项目表
|
||||
for p in list_projects():
|
||||
refs = p.get("项目负责人") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "项目负责人"})
|
||||
refs = p.get("项目成员") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "项目成员"})
|
||||
# 检查项目步骤表
|
||||
for s in list_steps():
|
||||
refs = s.get("步骤负责人") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "步骤负责人"})
|
||||
|
||||
elif table_key == 'category':
|
||||
# 检查年度表
|
||||
for y in list_years():
|
||||
refs = y.get("所属大类") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "年度表", "record": y.get("年度名称"), "field": "所属大类"})
|
||||
# 检查项目表
|
||||
for p in list_projects():
|
||||
refs = p.get("所属大类") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "所属大类"})
|
||||
|
||||
elif table_key == 'year':
|
||||
# 检查项目表
|
||||
for p in list_projects():
|
||||
refs = p.get("所属年度") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目表", "record": p.get("项目名称"), "field": "所属年度"})
|
||||
|
||||
elif table_key == 'project':
|
||||
# 检查审计资料表
|
||||
for d in list_audit_docs():
|
||||
refs = d.get("所属项目") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "审计资料表", "record": d.get("资料标题"), "field": "所属项目"})
|
||||
# 检查项目步骤表
|
||||
for s in list_steps():
|
||||
refs = s.get("所属项目") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "所属项目"})
|
||||
|
||||
elif table_key == 'step':
|
||||
# 检查项目步骤表(前置依赖)
|
||||
for s in list_steps():
|
||||
if s.get("id") == record_id:
|
||||
continue
|
||||
refs = s.get("前置依赖") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "项目步骤表", "record": s.get("步骤名称"), "field": "前置依赖"})
|
||||
|
||||
elif table_key == 'audit_doc':
|
||||
# 检查分析结果表
|
||||
for r in list_analysis_results():
|
||||
refs = r.get("关联资料") or []
|
||||
if record_id in refs:
|
||||
related.append({"table": "分析结果表", "record": r.get("分析摘要"), "field": "关联资料"})
|
||||
|
||||
return related
|
||||
|
||||
|
||||
# ====== 工具函数 ======
|
||||
|
||||
def _simplify_value(val):
|
||||
"""简化 CellValue 为可读格式"""
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, list):
|
||||
# 单选字段返回形如 ["xxx"]
|
||||
if len(val) == 1 and isinstance(val[0], str):
|
||||
return val[0]
|
||||
# 关联字段返回形如 [{"id": "xxx"}]
|
||||
if all(isinstance(v, dict) and "id" in v and "file_token" not in v for v in val):
|
||||
return [v["id"] for v in val]
|
||||
# 人员字段返回显示名
|
||||
if all(isinstance(v, dict) and "name" in v and "file_token" not in v for v in val):
|
||||
return [v["name"] for v in val]
|
||||
# 附件字段返回形如 [{"file_token": "xxx", "name": "xxx", "size": 123}]
|
||||
if all(isinstance(v, dict) and "file_token" in v for v in val):
|
||||
return [{"file_token": v.get("file_token", ""), "name": v.get("name", ""), "size": v.get("size", 0)} for v in val]
|
||||
return val
|
||||
return val
|
||||
@@ -0,0 +1,477 @@
|
||||
"""大模型分析服务"""
|
||||
|
||||
import json
|
||||
from openai import OpenAI
|
||||
from config import LLM_API_KEY, LLM_BASE_URL, LLM_MODEL
|
||||
|
||||
|
||||
# ====== 审计分析 Prompt 模板 ======
|
||||
|
||||
AUDIT_PROMPT_TEMPLATE = """你是一名经验丰富的医院内部审计专家。请对以下审计资料进行全面分析,并严格按照 JSON 格式输出结果。
|
||||
|
||||
{user_guidance_section}
|
||||
|
||||
## 审计资料
|
||||
{content}
|
||||
|
||||
{knowledge_section}
|
||||
|
||||
## 分析要求
|
||||
1. 识别资料中的关键风险点
|
||||
2. 判断合规性状况{compliance_hint}
|
||||
3. 给出可操作的改进建议
|
||||
4. 评估整体风险等级
|
||||
5. {reference_hint}
|
||||
|
||||
## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记)
|
||||
{{
|
||||
"analysis_type": "风险识别",
|
||||
"summary": "200字以内的核心分析摘要",
|
||||
"risk_level": "高/中/低/无",
|
||||
"findings": "逐条列出关键发现,每条用数字编号",
|
||||
"suggestions": "逐条列出改进建议,每条用数字编号",
|
||||
"references": "引用了知识库中的哪些制度/规范(如有),逐条列出;无则返回空字符串"
|
||||
}}
|
||||
"""
|
||||
|
||||
KNOWLEDGE_PROMPT_HINT = """
|
||||
## 知识库参考材料
|
||||
以下是与你本次审计相关的制度、规范和指南。请在分析时参考这些材料,并在"references"字段中注明引用了哪些制度条款。
|
||||
|
||||
{knowledge_content}
|
||||
"""
|
||||
|
||||
|
||||
def _get_client() -> OpenAI:
|
||||
"""获取 OpenAI 客户端"""
|
||||
return OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL)
|
||||
|
||||
|
||||
def analyze_audit_content(content: str, knowledge_context: str = "", user_guidance: str = "") -> dict:
|
||||
"""调用大模型分析审计资料内容
|
||||
|
||||
Args:
|
||||
content: 审计资料正文内容
|
||||
knowledge_context: 知识库参考材料文本(可选),为空则不引用知识库
|
||||
user_guidance: 用户自定义指导文本(可选),如只分析某张表、指定输出风格等
|
||||
"""
|
||||
if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here":
|
||||
return {
|
||||
"analysis_type": "风险识别",
|
||||
"summary": "【模拟分析】请先在 config.py 中配置 LLM_API_KEY 以启用真实分析。",
|
||||
"risk_level": "中",
|
||||
"findings": "1. 这是模拟分析结果,非真实大模型输出\n2. 请在 config.py 中配置 LLM_API_KEY 和 LLM_BASE_URL",
|
||||
"suggestions": "1. 配置大模型 API Key\n2. 重启服务后重试分析",
|
||||
"references": ""
|
||||
}
|
||||
|
||||
# 构建知识库提示部分
|
||||
if knowledge_context:
|
||||
knowledge_section = KNOWLEDGE_PROMPT_HINT.format(knowledge_content=knowledge_context)
|
||||
compliance_hint = "(对照知识库参考材料中的制度条款,逐条核对合规性)"
|
||||
reference_hint = "在 references 字段中注明分析时引用了知识库中的哪些制度、规范或指南"
|
||||
else:
|
||||
knowledge_section = ""
|
||||
compliance_hint = ""
|
||||
reference_hint = "如无知识库参考材料,references 字段返回空字符串"
|
||||
|
||||
# 构建用户指导段(如果用户提供了指导文本)
|
||||
# 放在分析要求之后、输出格式之前,优先级最高
|
||||
if user_guidance and user_guidance.strip():
|
||||
user_guidance_section = (
|
||||
"## ⚠️ 本次分析的特别指导(最高优先级,必须先读再分析)\n"
|
||||
"以下是用户对本次分析提出的特别要求。你必须主动、积极地按这些要求调整分析方向和输出风格,"
|
||||
"而不是消极地说明哪些做不到:\n\n"
|
||||
+ user_guidance.strip()
|
||||
+ "\n\n"
|
||||
"执行原则(必须严格遵守):\n"
|
||||
"1. 如指导指定了分析范围(如某张工作表/某个字段/某段时间),就只分析该范围内的数据,严禁引用该范围以外的任何数据\n"
|
||||
"2. 如指导指定了风险类型(如单价异常/供应商集中度),就把该类风险作为分析重点\n"
|
||||
"3. 如指导指定了输出风格(如简短要点/表格/编号/散文),就严格按该风格输出\n"
|
||||
"4. 即便下方审计资料中包含其它工作表/其它范围的数据,也一律不得在 findings、summary、suggestions 中引用或提及\n"
|
||||
"5. 如用户指导与上述分析要求冲突,以本指导为准\n"
|
||||
"6. 不要在输出中说明'因用户要求只分析XX所以无法分析YY',而是直接按用户要求产出分析结果"
|
||||
)
|
||||
else:
|
||||
user_guidance_section = ""
|
||||
user_guidance_section = ""
|
||||
|
||||
prompt = AUDIT_PROMPT_TEMPLATE.format(
|
||||
content=content,
|
||||
knowledge_section=knowledge_section,
|
||||
user_guidance_section=user_guidance_section,
|
||||
compliance_hint=compliance_hint,
|
||||
reference_hint=reference_hint
|
||||
)
|
||||
|
||||
# === 临时调试日志(排查用户指导被忽略问题)===
|
||||
try:
|
||||
import os as _os, datetime as _dt
|
||||
_log = _os.path.join(_os.path.dirname(__file__), "..", "_debug_prompt.log")
|
||||
with open(_log, "a", encoding="utf-8") as _f:
|
||||
_f.write("\n" + "="*70 + "\n")
|
||||
_f.write(f"[{_dt.datetime.now().isoformat()}]\n")
|
||||
_f.write(f"user_guidance 原文: [{user_guidance!r}]\n")
|
||||
_f.write(f"user_guidance_section 构建: [{user_guidance_section!r}]\n")
|
||||
_f.write(f"knowledge_context 长度: {len(knowledge_context)}\n")
|
||||
_f.write(f"content 长度: {len(content)}\n")
|
||||
_f.write(f"content 前200字: {content[:200]}\n")
|
||||
_f.write("---- 完整 prompt ----\n")
|
||||
_f.write(prompt + "\n")
|
||||
except Exception as _e:
|
||||
print(f"调试日志写入失败: {_e}")
|
||||
# === 调试日志结束 ===
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一个专业的医院内部审计分析助手,始终以 JSON 格式返回分析结果。分析时应严格对照制度条款,给出有依据的结论。"},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
temperature=0.3,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
result_text = response.choices[0].message.content
|
||||
result = json.loads(result_text)
|
||||
|
||||
def _ensure_str(val):
|
||||
"""确保值为字符串(数组用换行连接)"""
|
||||
if isinstance(val, list):
|
||||
return "\n".join(str(v) for v in val)
|
||||
return str(val) if val is not None else ""
|
||||
|
||||
# 确保字段完整
|
||||
return {
|
||||
"analysis_type": result.get("analysis_type", "风险识别"),
|
||||
"summary": result.get("summary", ""),
|
||||
"risk_level": result.get("risk_level", "中"),
|
||||
"findings": _ensure_str(result.get("findings", "")),
|
||||
"suggestions": _ensure_str(result.get("suggestions", "")),
|
||||
"references": _ensure_str(result.get("references", "")),
|
||||
"raw_output": result_text
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"analysis_type": "风险识别",
|
||||
"summary": f"分析调用失败: {str(e)}",
|
||||
"risk_level": "中",
|
||||
"findings": f"调用大模型 API 时发生错误: {str(e)}",
|
||||
"suggestions": "检查 API Key 和网络连接后重试",
|
||||
"references": "",
|
||||
"raw_output": f"Error: {str(e)}"
|
||||
}
|
||||
|
||||
|
||||
# ====== 审计报告生成 ======
|
||||
|
||||
AUDIT_REPORT_PROMPT_TEMPLATE = """你是一名资深的医院内部审计专家,擅长撰写审计报告。请根据以下信息,撰写一份详尽、专业、规范的审计报告。
|
||||
|
||||
## 审计项目信息
|
||||
- 步骤名称:{step_name}
|
||||
- 所属项目:{project_name}
|
||||
- 所属年度:{year_name}
|
||||
- 项目大类:{category_name}
|
||||
|
||||
## 审计资料及分析结果
|
||||
{docs_and_results}
|
||||
|
||||
## 报告要求
|
||||
{report_desc}
|
||||
|
||||
## 知识库参考材料(医院内部制度、规范)
|
||||
{knowledge_content}
|
||||
|
||||
## 网络补充资料(行业最佳实践、法规要求)
|
||||
{web_content}
|
||||
|
||||
## 报告生成要求
|
||||
1. 报告必须基于审计资料和大模型分析结果,客观反映审计发现
|
||||
2. 报告应结合知识库中的内部制度要求和网络补充的外部法规/最佳实践
|
||||
3. 报告应结构清晰、逻辑严密,结论有据可依
|
||||
4. 报告应包含审计发现、风险评估、整改建议等核心内容
|
||||
|
||||
## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记)
|
||||
{{
|
||||
"title": "审计报告标题",
|
||||
"content": "完整的审计报告正文,使用 Markdown 格式,包含以下章节:\\n\\n## 一、审计概况\\n(审计依据、审计范围、审计时间等)\\n## 二、审计基本情况\\n(被审计事项的基本情况描述)\\n## 三、审计发现\\n(逐条列明发现的问题,引用审计资料和分析结果)\\n## 四、风险评估与定性\\n(对发现的问题进行风险评级和定性分析)\\n## 五、审计结论\\n(综合评价和审计意见)\\n## 六、整改建议\\n(逐条列出可操作的整改建议)\\n## 七、附录\\n(引用的审计资料清单、分析依据等)\\n\\n每个章节内容详实,不少于200字。",
|
||||
"references": "报告编制时参考的制度、法规和资料来源,逐条列出"
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def generate_audit_report(
|
||||
step_name: str, project_name: str, year_name: str, category_name: str,
|
||||
docs_and_results: str, report_desc: str,
|
||||
knowledge_content: str, web_content: str
|
||||
) -> dict:
|
||||
"""调用大模型生成审计报告
|
||||
|
||||
Args:
|
||||
step_name: 步骤名称
|
||||
project_name: 项目名称
|
||||
year_name: 年度
|
||||
category_name: 大类名称
|
||||
docs_and_results: 审计资料和分析结果汇总文本
|
||||
report_desc: 报告要求和格式描述
|
||||
knowledge_content: 知识库参考材料文本
|
||||
web_content: 网络补充材料文本
|
||||
"""
|
||||
if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here":
|
||||
return {
|
||||
"title": "【模拟报告】请先配置 LLM_API_KEY",
|
||||
"content": "请先在 config.py 中配置 LLM_API_KEY 以启用真实报告生成。",
|
||||
"references": ""
|
||||
}
|
||||
|
||||
prompt = AUDIT_REPORT_PROMPT_TEMPLATE.format(
|
||||
step_name=step_name or "未指定",
|
||||
project_name=project_name or "未指定",
|
||||
year_name=year_name or "未指定",
|
||||
category_name=category_name or "未指定",
|
||||
docs_and_results=docs_and_results or "(无审计资料和分析结果)",
|
||||
report_desc=report_desc or "(无特殊要求,按标准审计报告格式编写)",
|
||||
knowledge_content=knowledge_content or "(未选择知识库,无内部制度参考材料)",
|
||||
web_content=web_content or "(无网络补充材料)"
|
||||
)
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一名资深的医院内部审计专家,擅长撰写审计报告。报告应客观、详尽、规范,始终以 JSON 格式返回结果。"},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
temperature=0.4,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
result_text = response.choices[0].message.content
|
||||
result = json.loads(result_text)
|
||||
|
||||
def _ensure_str(val):
|
||||
if isinstance(val, list):
|
||||
return "\n".join(str(v) for v in val)
|
||||
return str(val) if val is not None else ""
|
||||
|
||||
return {
|
||||
"title": result.get("title", "审计报告"),
|
||||
"content": _ensure_str(result.get("content", "")),
|
||||
"references": _ensure_str(result.get("references", "")),
|
||||
"raw_output": result_text
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"title": "报告生成失败",
|
||||
"content": f"调用大模型 API 时发生错误: {str(e)}",
|
||||
"references": "",
|
||||
"raw_output": f"Error: {str(e)}"
|
||||
}
|
||||
|
||||
|
||||
# ====== 综合分析整合 Prompt ======
|
||||
|
||||
MERGE_PROMPT_TEMPLATE = """你是一名经验丰富的医院内部审计专家。现在有两份针对同一份审计资料的分析结果,一份是基于资料本身的直接分析,另一份是引用了知识库制度后的分析。请将两者的结果整合为一份更全面、更权威的综合分析报告。
|
||||
|
||||
## 审计资料
|
||||
{content}
|
||||
|
||||
## 直接分析结果(未引用知识库)
|
||||
- 分析摘要:{plain_summary}
|
||||
- 风险等级:{plain_risk}
|
||||
- 关键发现:
|
||||
{plain_findings}
|
||||
- 改进建议:
|
||||
{plain_suggestions}
|
||||
|
||||
## 引用知识库分析结果
|
||||
- 分析摘要:{wiki_summary}
|
||||
- 风险等级:{wiki_risk}
|
||||
- 关键发现:
|
||||
{wiki_findings}
|
||||
- 改进建议:
|
||||
{wiki_suggestions}
|
||||
- 引用制度依据:
|
||||
{wiki_references}
|
||||
|
||||
## 整合要求
|
||||
1. 合并两次分析的关键发现,去重并补充遗漏项
|
||||
2. 综合两次的风险等级评估,给出最终等级(取较高者或说明理由)
|
||||
3. 整合改进建议,确保可操作性和制度合规性
|
||||
4. 保留知识库引用的制度依据
|
||||
5. 摘要应概括两次分析的核心结论
|
||||
|
||||
## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记)
|
||||
{{
|
||||
"analysis_type": "综合分析",
|
||||
"summary": "200字以内的综合分析摘要",
|
||||
"risk_level": "高/中/低/无",
|
||||
"findings": "逐条列出整合后的关键发现,每条用数字编号",
|
||||
"suggestions": "逐条列出整合后的改进建议,每条用数字编号",
|
||||
"references": "引用了知识库中的哪些制度/规范,逐条列出;无则返回空字符串"
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def merge_analyses(content: str, plain_result: dict, wiki_result: dict) -> dict:
|
||||
"""将直接分析结果和引用知识库分析结果整合为一份综合分析
|
||||
|
||||
Args:
|
||||
content: 原始审计资料内容
|
||||
plain_result: 直接分析结果(不含知识库)
|
||||
wiki_result: 引用知识库的分析结果
|
||||
"""
|
||||
if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here":
|
||||
return {
|
||||
"analysis_type": "综合分析",
|
||||
"summary": "【模拟分析】请先配置 LLM_API_KEY 以启用真实分析。",
|
||||
"risk_level": "中",
|
||||
"findings": "1. 模拟综合分析结果",
|
||||
"suggestions": "1. 配置大模型 API Key",
|
||||
"references": "",
|
||||
"raw_output": ""
|
||||
}
|
||||
|
||||
prompt = MERGE_PROMPT_TEMPLATE.format(
|
||||
content=content[:3000], # 截断避免 token 超限
|
||||
plain_summary=plain_result.get("summary", ""),
|
||||
plain_risk=plain_result.get("risk_level", ""),
|
||||
plain_findings=plain_result.get("findings", ""),
|
||||
plain_suggestions=plain_result.get("suggestions", ""),
|
||||
wiki_summary=wiki_result.get("summary", ""),
|
||||
wiki_risk=wiki_result.get("risk_level", ""),
|
||||
wiki_findings=wiki_result.get("findings", ""),
|
||||
wiki_suggestions=wiki_result.get("suggestions", ""),
|
||||
wiki_references=wiki_result.get("references", "")
|
||||
)
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一个专业的医院内部审计分析助手,擅长整合多份分析报告,输出全面且不重复的结论。始终以 JSON 格式返回结果。"},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
temperature=0.3,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
result_text = response.choices[0].message.content
|
||||
result = json.loads(result_text)
|
||||
|
||||
def _ensure_str(val):
|
||||
if isinstance(val, list):
|
||||
return "\n".join(str(v) for v in val)
|
||||
return str(val) if val is not None else ""
|
||||
|
||||
return {
|
||||
"analysis_type": result.get("analysis_type", "综合分析"),
|
||||
"summary": result.get("summary", ""),
|
||||
"risk_level": result.get("risk_level", "中"),
|
||||
"findings": _ensure_str(result.get("findings", "")),
|
||||
"suggestions": _ensure_str(result.get("suggestions", "")),
|
||||
"references": _ensure_str(result.get("references", "")),
|
||||
"raw_output": result_text
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"analysis_type": "综合分析",
|
||||
"summary": f"整合分析失败: {str(e)}",
|
||||
"risk_level": "中",
|
||||
"findings": f"调用大模型 API 时发生错误: {str(e)}",
|
||||
"suggestions": "检查 API Key 和网络连接后重试",
|
||||
"references": "",
|
||||
"raw_output": f"Error: {str(e)}"
|
||||
}
|
||||
|
||||
|
||||
# ====== 审计实施方案生成 ======
|
||||
|
||||
AUDIT_PLAN_PROMPT_TEMPLATE = """你是一名资深的医院内部审计专家,擅长制定审计实施方案。请根据以下信息,制定一份详尽、专业、可操作的审计实施方案。
|
||||
|
||||
## 审计项目描述
|
||||
{project_desc}
|
||||
|
||||
## 知识库参考材料(医院内部制度、规范)
|
||||
{knowledge_content}
|
||||
|
||||
## 网络补充资料(行业最佳实践、法规要求)
|
||||
{web_content}
|
||||
|
||||
## 方案生成要求
|
||||
1. 方案必须结合知识库中的内部制度要求和网络补充的外部法规/最佳实践
|
||||
2. 方案应具有可操作性,明确审计范围、审计重点、审计方法
|
||||
3. 方案应包含时间安排和人员分工建议
|
||||
4. 方案应识别重点风险领域和关键控制点
|
||||
|
||||
## 输出格式(必须返回纯 JSON,不要包含 Markdown 代码块标记)
|
||||
{{
|
||||
"title": "审计实施方案标题",
|
||||
"content": "完整的审计实施方案正文,使用 Markdown 格式,包含以下章节:\\n\\n## 一、审计目的\\n## 二、审计范围\\n## 三、审计依据\\n## 四、审计重点和关键控制点\\n## 五、审计方法\\n## 六、审计时间安排\\n## 七、人员分工\\n## 八、审计风险及应对措施\\n## 九、审计质量保障措施\\n\\n每个章节内容详实,不少于200字。",
|
||||
"references": "方案编制时参考的制度、法规和资料来源,逐条列出"
|
||||
}}
|
||||
"""
|
||||
|
||||
|
||||
def generate_audit_plan(project_desc: str, knowledge_content: str, web_content: str) -> dict:
|
||||
"""调用大模型生成审计实施方案
|
||||
|
||||
Args:
|
||||
project_desc: 审计项目描述
|
||||
knowledge_content: 知识库参考材料文本
|
||||
web_content: 网络补充材料文本
|
||||
"""
|
||||
if not LLM_API_KEY or LLM_API_KEY == "sk-your-api-key-here":
|
||||
return {
|
||||
"title": "【模拟方案】请先配置 LLM_API_KEY",
|
||||
"content": "请先在 config.py 中配置 LLM_API_KEY 以启用真实方案生成。",
|
||||
"references": ""
|
||||
}
|
||||
|
||||
prompt = AUDIT_PLAN_PROMPT_TEMPLATE.format(
|
||||
project_desc=project_desc,
|
||||
knowledge_content=knowledge_content or "(未选择知识库,无内部制度参考材料)",
|
||||
web_content=web_content or "(无网络补充材料)"
|
||||
)
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
response = client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一名资深的医院内部审计专家,擅长制定审计实施方案。方案应详尽、专业、具有可操作性,始终以 JSON 格式返回结果。"},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
temperature=0.4,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
result_text = response.choices[0].message.content
|
||||
result = json.loads(result_text)
|
||||
|
||||
def _ensure_str(val):
|
||||
if isinstance(val, list):
|
||||
return "\n".join(str(v) for v in val)
|
||||
return str(val) if val is not None else ""
|
||||
|
||||
return {
|
||||
"title": result.get("title", "审计实施方案"),
|
||||
"content": _ensure_str(result.get("content", "")),
|
||||
"references": _ensure_str(result.get("references", "")),
|
||||
"raw_output": result_text
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"title": "方案生成失败",
|
||||
"content": f"调用大模型 API 时发生错误: {str(e)}",
|
||||
"references": "",
|
||||
"raw_output": f"Error: {str(e)}"
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,111 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""本地知识库服务 - 从SQLite读取知识库文档内容,无需飞书授权"""
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
DB_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "audit_data.db")
|
||||
|
||||
# 单篇文档内容最大长度(字符)
|
||||
MAX_DOC_CONTENT_LEN = 8000
|
||||
# 知识库上下文总最大长度(字符)
|
||||
MAX_CONTEXT_TOTAL_LEN = 50000
|
||||
|
||||
|
||||
def _get_conn():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def list_spaces() -> list[dict]:
|
||||
"""列出所有知识空间"""
|
||||
conn = _get_conn()
|
||||
rows = conn.execute("SELECT * FROM knowledge_spaces ORDER BY id").fetchall()
|
||||
conn.close()
|
||||
return [{
|
||||
"space_id": r["space_id"],
|
||||
"name": r["name"],
|
||||
"description": r["description"],
|
||||
"space_type": r["space_type"],
|
||||
"visibility": r["visibility"]
|
||||
} for r in rows]
|
||||
|
||||
|
||||
def list_nodes(space_id: str, parent_token: str = "") -> list[dict]:
|
||||
"""列出知识空间下的节点"""
|
||||
conn = _get_conn()
|
||||
if parent_token:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_docs WHERE space_id = ? AND parent_node_token = ? ORDER BY id",
|
||||
(space_id, parent_token)
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_docs WHERE space_id = ? ORDER BY id",
|
||||
(space_id,)
|
||||
).fetchall()
|
||||
conn.close()
|
||||
return [{
|
||||
"node_token": r["node_token"],
|
||||
"obj_token": r["node_token"], # 使用node_token作为obj_token
|
||||
"obj_type": r["obj_type"],
|
||||
"title": r["title"],
|
||||
"has_child": bool(r["has_child"]),
|
||||
"parent_node_token": r["parent_node_token"],
|
||||
"space_id": r["space_id"]
|
||||
} for r in rows]
|
||||
|
||||
|
||||
def fetch_doc_content(obj_token: str) -> str:
|
||||
"""从本地数据库获取文档内容"""
|
||||
conn = _get_conn()
|
||||
row = conn.execute("SELECT content FROM knowledge_docs WHERE node_token = ?", (obj_token,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return ""
|
||||
content = row["content"] or ""
|
||||
if len(content) > MAX_DOC_CONTENT_LEN:
|
||||
content = content[:MAX_DOC_CONTENT_LEN] + "\n...(内容过长已截断)"
|
||||
return content
|
||||
|
||||
|
||||
def build_knowledge_context(space_ids: list[str]) -> str:
|
||||
"""根据选中的知识空间ID列表,构建知识库上下文文本供大模型引用"""
|
||||
if not space_ids:
|
||||
return ""
|
||||
|
||||
conn = _get_conn()
|
||||
all_docs = []
|
||||
total_len = 0
|
||||
|
||||
for space_id in space_ids:
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM knowledge_docs WHERE space_id = ? AND obj_type = 'docx' AND content != '' ORDER BY id",
|
||||
(space_id,)
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
if total_len >= MAX_CONTEXT_TOTAL_LEN:
|
||||
break
|
||||
title = r["title"] or "未命名"
|
||||
content = r["content"] or ""
|
||||
if len(content.strip()) > 20: # 过滤掉太短的模板内容
|
||||
doc_text = f"### {title}\n{content}"
|
||||
remaining = MAX_CONTEXT_TOTAL_LEN - total_len
|
||||
if len(doc_text) > remaining:
|
||||
doc_text = doc_text[:remaining] + "\n...(内容已截断)"
|
||||
all_docs.append(doc_text)
|
||||
total_len += len(doc_text)
|
||||
except Exception:
|
||||
continue
|
||||
if total_len >= MAX_CONTEXT_TOTAL_LEN:
|
||||
break
|
||||
|
||||
conn.close()
|
||||
|
||||
if not all_docs:
|
||||
return ""
|
||||
|
||||
context = "## 知识库参考材料\n以下是与本次审计相关的制度、规范和指南,请在分析时参考引用:\n\n"
|
||||
context += "\n\n---\n\n".join(all_docs)
|
||||
return context
|
||||
@@ -0,0 +1,122 @@
|
||||
"""网络搜索服务 - 从互联网获取审计相关补充材料"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
|
||||
|
||||
def search_web(query: str, max_results: int = 5) -> list[dict]:
|
||||
"""使用 DuckDuckGo 搜索获取相关网页摘要
|
||||
|
||||
Args:
|
||||
query: 搜索关键词
|
||||
max_results: 最大返回结果数
|
||||
|
||||
Returns:
|
||||
包含 title, url, snippet 的结果列表
|
||||
"""
|
||||
results = []
|
||||
try:
|
||||
# 使用 DuckDuckGo Instant Answer API(无需 API Key)
|
||||
encoded_query = urllib.parse.quote(query)
|
||||
url = f"https://api.duckduckgo.com/?q={encoded_query}&format=json&no_html=1&skip_disambig=1"
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
# 提取摘要
|
||||
abstract = data.get("Abstract", "")
|
||||
abstract_source = data.get("AbstractSource", "")
|
||||
abstract_url = data.get("AbstractURL", "")
|
||||
heading = data.get("Heading", "")
|
||||
|
||||
if abstract:
|
||||
results.append({
|
||||
"title": heading or abstract_source or "搜索结果",
|
||||
"url": abstract_url or "",
|
||||
"snippet": abstract[:500]
|
||||
})
|
||||
|
||||
# 提取相关主题
|
||||
for topic in data.get("RelatedTopics", [])[:max_results]:
|
||||
if isinstance(topic, dict) and topic.get("Text"):
|
||||
results.append({
|
||||
"title": topic.get("Text", "")[:80],
|
||||
"url": topic.get("FirstURL", ""),
|
||||
"snippet": topic.get("Text", "")[:300]
|
||||
})
|
||||
if len(results) >= max_results:
|
||||
break
|
||||
|
||||
except Exception:
|
||||
pass # 网络搜索失败不影响主流程
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def fetch_url_content(url: str, max_length: int = 2000) -> str:
|
||||
"""获取网页文本内容(简单提取)
|
||||
|
||||
Args:
|
||||
url: 网页 URL
|
||||
max_length: 最大返回字符数
|
||||
"""
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
raw = resp.read().decode("utf-8", errors="ignore")
|
||||
|
||||
# 简单提取文本:去掉 HTML 标签
|
||||
import re
|
||||
# 移除 script 和 style
|
||||
raw = re.sub(r'<script[^>]*>.*?</script>', '', raw, flags=re.DOTALL | re.IGNORECASE)
|
||||
raw = re.sub(r'<style[^>]*>.*?</style>', '', raw, flags=re.DOTALL | re.IGNORECASE)
|
||||
# 移除所有 HTML 标签
|
||||
text = re.sub(r'<[^>]+>', ' ', raw)
|
||||
# 清理多余空白
|
||||
text = re.sub(r'\s+', ' ', text).strip()
|
||||
|
||||
if len(text) > max_length:
|
||||
text = text[:max_length] + "...(内容已截断)"
|
||||
return text
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def build_web_context(query: str) -> str:
|
||||
"""根据查询关键词搜索网络并构建补充材料文本
|
||||
|
||||
Args:
|
||||
query: 搜索关键词(通常包含审计相关主题)
|
||||
|
||||
Returns:
|
||||
格式化的网络补充材料文本
|
||||
"""
|
||||
results = search_web(query, max_results=5)
|
||||
if not results:
|
||||
return ""
|
||||
|
||||
sections = []
|
||||
for i, r in enumerate(results, 1):
|
||||
title = r.get("title", "")
|
||||
snippet = r.get("snippet", "")
|
||||
url = r.get("url", "")
|
||||
|
||||
# 尝试获取更详细的内容
|
||||
detail = ""
|
||||
if url:
|
||||
detail = fetch_url_content(url, max_length=1500)
|
||||
|
||||
section = f"### 资料{i}:{title}\n"
|
||||
section += f"摘要:{snippet}\n"
|
||||
if detail:
|
||||
section += f"详细内容:{detail}\n"
|
||||
if url:
|
||||
section += f"来源:{url}\n"
|
||||
sections.append(section)
|
||||
|
||||
context = "## 网络补充材料\n以下是从互联网搜索获取的相关法规、最佳实践和参考资料:\n\n"
|
||||
context += "\n\n---\n\n".join(sections)
|
||||
return context
|
||||
@@ -0,0 +1,127 @@
|
||||
"""飞书知识库服务 - 读取知识空间文档内容供大模型分析引用"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
|
||||
# lark-cli 完整路径
|
||||
LARK_CLI = r"C:\Users\qinyi\.trae-cn\plugins\trae-remote-official\lark\1.0.3\bin\lark-cli.exe"
|
||||
if not os.path.exists(LARK_CLI):
|
||||
LARK_CLI = "lark-cli"
|
||||
|
||||
# 单篇文档内容最大长度(字符),避免 token 超限
|
||||
MAX_DOC_CONTENT_LEN = 8000
|
||||
# 知识库上下文总最大长度(字符)
|
||||
MAX_CONTEXT_TOTAL_LEN = 50000
|
||||
|
||||
|
||||
def _run_lark(args: list[str], cwd: str = None) -> dict:
|
||||
"""执行 lark-cli 命令并返回 JSON 结果"""
|
||||
cmd = [LARK_CLI] + args + ["--as", "user", "--format", "json"]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, cwd=cwd)
|
||||
if result.returncode != 0:
|
||||
err = json.loads(result.stderr) if result.stderr else {"error": result.stderr}
|
||||
msg = err.get('error', {}).get('message', str(err))
|
||||
raise Exception(f"lark-cli 调用失败: {msg}")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def list_spaces() -> list[dict]:
|
||||
"""列出所有可访问的知识空间"""
|
||||
data = _run_lark(["wiki", "+space-list"])
|
||||
spaces = []
|
||||
for s in data.get("data", {}).get("spaces", []):
|
||||
spaces.append({
|
||||
"space_id": s.get("space_id", ""),
|
||||
"name": s.get("name", ""),
|
||||
"description": s.get("description", ""),
|
||||
"space_type": s.get("space_type", ""),
|
||||
"visibility": s.get("visibility", "")
|
||||
})
|
||||
return spaces
|
||||
|
||||
|
||||
def list_nodes(space_id: str, parent_token: str = "") -> list[dict]:
|
||||
"""列出知识空间下的节点(支持递归获取子节点)"""
|
||||
args = ["wiki", "+node-list", "--space-id", space_id]
|
||||
if parent_token:
|
||||
args.append("--parent-node-token")
|
||||
args.append(parent_token)
|
||||
data = _run_lark(args)
|
||||
nodes = []
|
||||
for n in data.get("data", {}).get("nodes", []):
|
||||
node = {
|
||||
"node_token": n.get("node_token", ""),
|
||||
"obj_token": n.get("obj_token", ""),
|
||||
"obj_type": n.get("obj_type", ""),
|
||||
"title": n.get("title", ""),
|
||||
"has_child": n.get("has_child", False),
|
||||
"parent_node_token": n.get("parent_node_token", ""),
|
||||
"space_id": space_id
|
||||
}
|
||||
nodes.append(node)
|
||||
# 递归获取子节点
|
||||
if node["has_child"]:
|
||||
try:
|
||||
children = list_nodes(space_id, node["node_token"])
|
||||
nodes.extend(children)
|
||||
except Exception:
|
||||
pass # 子节点获取失败不影响主流程
|
||||
return nodes
|
||||
|
||||
|
||||
def fetch_doc_content(obj_token: str) -> str:
|
||||
"""获取飞书文档内容(markdown格式)"""
|
||||
try:
|
||||
data = _run_lark([
|
||||
"docs", "+fetch",
|
||||
"--doc", obj_token,
|
||||
"--doc-format", "markdown",
|
||||
"--scope", "full"
|
||||
])
|
||||
content = data.get("data", {}).get("document", {}).get("content", "")
|
||||
if len(content) > MAX_DOC_CONTENT_LEN:
|
||||
content = content[:MAX_DOC_CONTENT_LEN] + "\n...(内容过长已截断)"
|
||||
return content
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def build_knowledge_context(space_ids: list[str]) -> str:
|
||||
"""根据选中的知识空间ID列表,构建知识库上下文文本供大模型引用"""
|
||||
if not space_ids:
|
||||
return ""
|
||||
|
||||
all_docs = []
|
||||
total_len = 0
|
||||
|
||||
for space_id in space_ids:
|
||||
try:
|
||||
nodes = list_nodes(space_id)
|
||||
for node in nodes:
|
||||
if total_len >= MAX_CONTEXT_TOTAL_LEN:
|
||||
break
|
||||
# 只读取 docx 类型的文档
|
||||
if node.get("obj_type") != "docx":
|
||||
continue
|
||||
title = node.get("title", "未命名")
|
||||
content = fetch_doc_content(node["obj_token"])
|
||||
if content and len(content.strip()) > 20: # 过滤掉太短的模板内容
|
||||
doc_text = f"### {title}\n{content}"
|
||||
remaining = MAX_CONTEXT_TOTAL_LEN - total_len
|
||||
if len(doc_text) > remaining:
|
||||
doc_text = doc_text[:remaining] + "\n...(内容已截断)"
|
||||
all_docs.append(doc_text)
|
||||
total_len += len(doc_text)
|
||||
except Exception:
|
||||
continue
|
||||
if total_len >= MAX_CONTEXT_TOTAL_LEN:
|
||||
break
|
||||
|
||||
if not all_docs:
|
||||
return ""
|
||||
|
||||
context = "## 知识库参考材料\n以下是与本次审计相关的制度、规范和指南,请在分析时参考引用:\n\n"
|
||||
context += "\n\n---\n\n".join(all_docs)
|
||||
return context
|
||||
Reference in new issue
Block a user