""" backend/app/api/tools/voucher_check.py 用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。 依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。 逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。 """ from __future__ import annotations from flask import Blueprint, jsonify, request from app.core.errors import AppError from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE from app.services.integration_tool_auth import require_integration_tool_auth from app.services.voucher_check import query_service from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__) @voucher_check_tools_bp.before_request def _verify_tool_access(): """openapi.json 免鉴权,其余端点校验 Tool API Key。""" if request.path.endswith("/openapi.json"): return None require_integration_tool_auth() return None def _tool_error(exc: AppError): """将 AppError 映射为 Tool 非 envelope 错误体。""" code = str(exc.code or "").lower().replace(".", "_") message = str(exc.message or "").strip() # 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支 if message in {"missing_auth", "invalid_auth"}: code = message return jsonify({ "ok": False, "error_code": code, "message": message or code, "details": exc.details or {}, }), exc.http_status @voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"]) def voucher_check_openapi_spec(): """ 返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。 【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。 """ return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) @voucher_check_tools_bp.route("/tools/tasks//missing", methods=["GET"]) def tool_list_missing(task_id: int): """ 查询当前月或指定月缺资料票。 【AI 触发时机】:用户说「查询缺资料发票」时调用。 """ try: data = query_service.list_missing_states( task_id=task_id, scope_code=str(request.args.get("scope_code") or "HXJM"), period=request.args.get("period"), limit=request.args.get("limit", default=200, type=int) or 200, ) return jsonify({"ok": True, **data}) except AppError as exc: return _tool_error(exc) @voucher_check_tools_bp.route("/tools/runs//items", methods=["GET"]) def tool_list_run_items(run_id: int): """ 查询批次明细,可按 result 过滤。 【AI 触发时机】:用户查询某批次结果明细时调用。 """ try: data = query_service.list_run_items( run_id=run_id, result=request.args.get("result"), page=request.args.get("page", default=1, type=int) or 1, page_size=request.args.get("page_size", default=50, type=int) or 50, ) return jsonify({"ok": True, **data}) except AppError as exc: return _tool_error(exc) @voucher_check_tools_bp.route("/tools/invoices//latest", methods=["GET"]) def tool_invoice_latest(invoice_no: str): """ 查询指定发票最新状态。 【AI 触发时机】:用户询问某张发票检核结论时调用。 """ try: data = query_service.get_invoice_latest( invoice_no=invoice_no, scope_code=str(request.args.get("scope_code") or "HXJM"), period=request.args.get("period"), ) return jsonify({"ok": True, **data}) except AppError as exc: return _tool_error(exc)