Files
audit-platform/审计项目管理平台/services/feishu_service.py
T
guwangtu b91954df4a
CI / check (push) Failing after 15m48s
chore: initial open-source baseline v1.0.0
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
2026-12-05 15:44:53 +00:00

828 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""飞书多维表格服务 - 通过 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