refactor: refactor of backend

This commit is contained in:
sophie committed 2026-09-28 14:52:28 +08:00
1 parent d4cb8c5def
commit 14e5af0c9c
55 files changed
+2251 -1805

No files matched your search

+22 -651
View File
@@ -1,657 +1,28 @@
"""
backend/app/api/file_check_tools.py
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/file_check.py)。
依赖:app.api.tools.file_check。
逻辑:保留 Blueprint 与测试 monkeypatch 常用符号;新代码请从 app.api.tools 导入。
"""
from __future__ import annotations
import threading
import time
from io import BytesIO
from datetime import datetime
from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text
from app import db
from app.api.workspace_file_check import serialize_file_judgement
from app.jobs import JobType, enqueue
from app.core.errors import (
AppError,
ConflictError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
from app.api.tools.file_check import ( # noqa: F401
_RUN_START_LOCK,
_build_excel_download_url,
_precheck_no_data,
enqueue,
file_check_bp,
get_schedule_sql_config_by_task_id,
_build_srm_conn_str,
_fetch_records,
)
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
try:
import pyodbc # type: ignore
except Exception: # pragma: no cover
pyodbc = None
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_TASK_LOCK_KEY_BASE = 8700000000
def _download_token_secret() -> str:
"""
Excel 下载 JWT 签名密钥。
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
"""
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
def _decode_download_token(token: str | None) -> dict | None:
normalized = str(token or "").strip()
if not normalized:
return None
try:
import jwt
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
return payload if isinstance(payload, dict) else None
except Exception as exc:
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
return None
def _require_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
"""
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
if request.path.endswith("/excel"):
query_token = str(request.args.get("token") or "").strip()
if query_token:
if _decode_download_token(query_token):
return
raise UnauthorizedError("invalid_auth")
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
from app.services.integration_tool_auth import require_integration_tool_auth
require_integration_tool_auth()
def _tool_error_code(exc: AppError) -> str:
message = str(exc.message or "").strip()
if message in {
"missing_auth",
"invalid_auth",
"task_not_found",
"run_not_found",
"excel_not_ready",
"kb_sync_failed",
"query_required",
"kb_not_configured",
"kb_group_not_found",
"kb_dataset_not_bound",
"dify_retrieve_failed",
}:
return message
if exc.code == "data_source_unavailable":
return "data_source_unavailable"
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
if exc.code == "RESOURCE.NOT_FOUND":
return message or "run_not_found"
if exc.code == "VALIDATION.INVALID_PARAM":
return message or "invalid_request"
if exc.code == "RESOURCE.CONFLICT":
return message or "conflict"
return exc.code
@file_check_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
status = exc.http_status
return jsonify({
"ok": False,
"error_code": _tool_error_code(exc),
"message": exc.message,
}), status
def _public_base_url() -> str:
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
return resolve_hxops_user_facing_base_url()
def _acquire_task_start_lock(task_id: int) -> None:
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
bind = db.session.get_bind()
if bind.dialect.name != "postgresql":
return
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
def _build_excel_download_url(run: ScheduleRun) -> str:
import jwt
payload = {
"scope": "file_check_excel",
"run_id": run.id,
"exp": int(time.time()) + 600,
}
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
@file_check_bp.before_request
def _verify_tool_access():
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
def _serialize_tool_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
return {
"run_id": payload["id"],
"run_no": payload["run_no"],
"task_id": payload["schedule_task_id"],
"task_name": payload.get("schedule_name"),
"status": payload["status"],
"total_count": payload["total_count"],
"success_count": payload["success_count"],
"failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"],
"judgement": serialize_file_judgement(payload),
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"),
"error_message": payload.get("error_message"),
"excel": {
"file_name": payload.get("excel_file_name"),
"file_size": payload.get("excel_file_size"),
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
},
"knowledge_base": {
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
"sync_status": payload.get("kb_sync_status"),
"group_id": payload.get("kb_group_id"),
"document_id": payload.get("kb_document_id"),
"document_version_id": payload.get("kb_document_version_id"),
"sync_job_id": payload.get("kb_sync_job_id"),
"error_message": payload.get("kb_sync_error"),
},
}
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
data = data or {}
raw_task_id = task_id if task_id is not None else data.get("task_id")
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
raise ValidationError("task_id_required")
try:
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
except (TypeError, ValueError):
raise ValidationError("task_id_invalid")
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
if not task:
task_no = str(data.get("task_no") or "").strip()
if task_no:
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
if not task:
raise NotFoundError("task_not_found")
return task
@file_check_bp.route("/tools/tasks", methods=["GET"])
def list_file_check_tasks():
"""
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
"""
raw_task_id = request.args.get("task_id", type=int)
if raw_task_id is None:
raise ValidationError("task_id_required")
task = _resolve_check_task(task_id=raw_task_id)
latest = (
ScheduleRun.query.filter_by(schedule_task_id=task.id)
.order_by(ScheduleRun.id.desc())
.first()
)
tasks = [{
"task_id": task.id,
"task_no": task.schedule_no,
"name": task.name,
"enabled": bool(task.enabled),
"last_status": latest.status if latest else None,
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
}]
return jsonify({"ok": True, "tasks": tasks})
def _normalize_bind_payload(data: dict | None) -> dict:
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
payload = dict(data or {})
session_id = str(payload.get("hxops_session_id") or "").strip()
if session_id:
return payload
conversation_id = str(payload.get("conversation_id") or "").strip()
if not conversation_id:
return payload
from app.models import ChatSession
session = ChatSession.query.filter_by(session_id=conversation_id).first()
if session:
payload["hxops_session_id"] = conversation_id
return payload
def _prepare_bind_payload(data: dict | None) -> dict:
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
payload = _normalize_bind_payload(data)
inferred = infer_bind_context_for_run_request(payload)
if inferred:
payload = {**payload, **inferred}
return payload
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
from app.services.file_check_tools.chat_tool_run_binding import (
_has_ambiguous_pending_turns,
bind_schedule_run,
)
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
turn_id = str(data.get("hxops_turn_id") or "").strip()
session_id = str(data.get("hxops_session_id") or "").strip() or None
user_message = str(data.get("user_message") or "").strip() or None
bound = bind_schedule_run(
schedule_run_id=int(run.id),
turn_id=turn_id or None,
session_id=session_id,
user_message=user_message,
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
bind_source='tool_start',
)
ambiguous = _has_ambiguous_pending_turns(
session_id=session_id,
user_message=user_message,
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
)
if bound or (not ambiguous and (turn_id or session_id)):
merge_chat_log_bind_context(run, data)
if bound and turn_id:
attach_run_to_turn(turn_id, int(run.id))
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
"""
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
"""
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
turn_id = str(data.get("hxops_turn_id") or "").strip()
session_id = str(data.get("conversation_id") or "").strip() or None
user_message = str(data.get("user_message") or "").strip() or None
if not turn_id:
return
bound = bind_schedule_run(
schedule_run_id=int(run.id),
turn_id=turn_id,
session_id=session_id,
user_message=user_message,
schedule_task_id=int(run.schedule_task_id),
bind_source="tool_query_latest",
)
if bound:
attach_run_to_turn(turn_id, int(run.id))
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
"""
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
Args:
task: 当前检核任务。
run: 已持久化并绑定当前对话的成功空批次。
Returns:
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
"""
return {
"ok": False,
"error_code": "no_data_to_check",
"message": "目前没有资料需要检核",
"run": _serialize_tool_run(run),
"task": {
"task_id": task.id,
"task_name": task.name,
},
}
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
"""
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
"""
current_app.logger.warning(
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
task.id,
exc,
exc_info=True,
)
raise ServiceUnavailableError(
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
code="data_source_unavailable",
) from exc
def _precheck_no_data(task: ScheduleTask) -> dict | None:
"""
启动前预检当前任务是否存在待检资料。
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
"""
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
return None
cfg = get_schedule_sql_config_by_task_id(task.id)
if not cfg or not str(cfg.fetch_sql or "").strip():
return None
try:
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, cfg.fetch_sql)
except RuntimeError as exc:
_raise_data_source_unavailable(task, exc)
except Exception as exc:
if pyodbc is not None and isinstance(exc, pyodbc.Error):
_raise_data_source_unavailable(task, exc)
raise
if rows:
return None
return {
"ok": False,
"error_code": "no_data_to_check",
"message": "目前没有资料需要检核",
}
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
"""
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
Args:
task: 已解析的文件检核任务。
data: Tool 请求及对话绑定上下文。
Returns:
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
"""
finished_at = datetime.utcnow()
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type="dify_chatflow",
started_at=finished_at,
finished_at=finished_at,
duration_ms=0,
status="success",
total_count=0,
success_count=0,
failed_count=0,
skipped_count=0,
api_request_json={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
},
response_summary_json={"errors": [], "no_data": True},
)
db.session.add(run)
db.session.commit()
_record_run_bind(run, data)
db.session.commit()
return run
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
Body 关键字段(立账凭证检核):
mode: incremental | force_all | single
invoice_no: mode=single 时发票号
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
"""
perf_started = time.perf_counter()
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
lock_started = time.perf_counter()
with _RUN_START_LOCK:
_acquire_task_start_lock(task.id)
existing = (
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
.order_by(ScheduleRun.id.desc())
.first()
)
if existing:
_record_run_bind(existing, data)
db.session.commit()
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
existing.id,
)
return jsonify({
"ok": False,
"error_code": "check_running",
"message": "该检核任务正在执行中,请稍后查询结果",
"run": _serialize_tool_run(existing),
})
no_data_response = _precheck_no_data(task)
if no_data_response:
run = _create_no_data_run(task, data)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
task.id,
run.id,
)
return jsonify(_build_no_data_response(task, run))
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
run_options = {}
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
if mode in {"incremental", "force_all", "single"}:
run_options["mode"] = mode
invoice_no = data.get("invoice_no")
if invoice_no is None or not str(invoice_no).strip():
invoice_no = raw_options.get("invoice_no")
if invoice_no is not None and str(invoice_no).strip():
run_options["invoice_no"] = str(invoice_no).strip()
api_request_json = {
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
}
if run_options:
api_request_json["run_options"] = run_options
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type="dify_chatflow",
started_at=datetime.utcnow(),
status="running",
api_request_json=api_request_json,
)
db.session.add(run)
db.session.commit()
_record_run_bind(run, data)
db.session.commit()
run_id = run.id
task_id = task.id
enqueue(
JobType.FILE_CHECK_RUN,
{"task_id": task_id, "schedule_run_id": run_id},
domain="file_check",
business_ref=str(run_id),
message="等待执行文件检核",
)
db.session.refresh(run)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
run_id,
)
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
def get_file_check_run(run_id: int):
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@file_check_bp.route("/tools/runs", methods=["GET"])
def list_file_check_runs():
raw_task_id = request.args.get("task_id", type=int)
raw_limit = request.args.get("limit", default=20, type=int)
limit = max(1, min(int(raw_limit or 20), 100))
if raw_task_id is not None:
task = _resolve_check_task(task_id=raw_task_id)
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
else:
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
runs = [_serialize_tool_run(row) for row in rows]
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_file_check_run_excel(run_id: int):
token_payload = _decode_download_token(request.args.get("token"))
if token_payload:
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
raise UnauthorizedError("Unauthorized")
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not run.excel_file_data:
raise ConflictError("excel_not_ready")
filename = run.excel_file_name or f"{run.run_no}.xlsx"
return send_file(
BytesIO(run.excel_file_data),
as_attachment=True,
download_name=filename,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_file_check_run(task_id: int):
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
task = _resolve_check_task(task_id=task_id)
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
if not run:
raise NotFoundError("run_not_found")
_bind_queried_run_to_turn(run, {
"hxops_turn_id": request.args.get("hxops_turn_id"),
"conversation_id": request.args.get("conversation_id"),
"user_message": request.args.get("user_message"),
})
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@file_check_bp.route("/tools/history/search", methods=["POST"])
def search_file_check_history():
"""
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
"""
data = request.get_json(silent=True) or {}
raw_task_id = data.get("task_id")
try:
task_id = int(raw_task_id)
except (TypeError, ValueError):
raise ValidationError("task_id_invalid")
if task_id <= 0:
raise ValidationError("task_id_invalid")
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
result = run_history_search(
task_id=task_id,
query=str(data.get("query") or ""),
top_k=data.get("top_k"),
score_threshold=data.get("score_threshold"),
)
return jsonify({"ok": True, **result})
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
def file_check_openapi_spec():
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
__all__ = [
'file_check_bp',
'enqueue',
'_precheck_no_data',
'_build_excel_download_url',
'_RUN_START_LOCK',
'get_schedule_sql_config_by_task_id',
'_build_srm_conn_str',
'_fetch_records',
]