feat(agent): 立账凭证检核

(cherry picked from commit f9e2fb5efc1ec7bf4f6e52e08dd3591b4e77edd9)
This commit is contained in:
sophie committed 2026-08-06 10:05:46 +08:00
1 parent 9bcbf9d211
commit f615e56bb9
70 files changed
+4968 -108

No files matched your search

+4 -1
View File
@@ -39,8 +39,9 @@ def register_blueprints(app: Flask) -> None:
workspace_file_check_bp,
workspace_schedule_bp,
workspace_shipping_notice_bp,
workspace_voucher_check_bp,
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
@@ -57,10 +58,12 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_voucher_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
+38 -27
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/file_check_tools.py
用途:文件检核 Chatflow 显式 HTTP Tool API。
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
"""
from __future__ import annotations
@@ -74,7 +74,7 @@ def _require_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
"""
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
if request.path.endswith("/excel"):
@@ -84,26 +84,10 @@ def _require_tool_auth() -> None:
return
raise UnauthorizedError("invalid_auth")
# [STEP 2] Dify / RPA 服务端调用
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
from app.services.integration_tool_auth import require_integration_tool_auth
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
require_integration_tool_auth()
def _tool_error_code(exc: AppError) -> str:
@@ -382,7 +366,17 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
"""
立即执行检核;任务 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)
@@ -428,16 +422,33 @@ def run_file_check():
)
return jsonify(no_data_response)
# [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={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
},
api_request_json=api_request_json,
)
db.session.add(run)
db.session.commit()
+3 -2
View File
@@ -2,10 +2,11 @@
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。
"""
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
from app.api.tools.file_check import file_check_bp # noqa: F401
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401
__all__ = ['shipping_notice_bp', 'file_check_bp']
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp']
+105
View File
@@ -0,0 +1,105 @@
"""
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/<int:task_id>/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/<int:run_id>/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/<path:invoice_no>/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)
+3 -1
View File
@@ -1,7 +1,7 @@
"""
backend/app/api/workspace/__init__.py
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、voucher_check、announcements)。
依赖:workspace 各子模块 blueprint。
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
"""
@@ -9,10 +9,12 @@ from app.api.workspace.announcements import workspace_announcements_bp
from app.api.workspace.file_check import workspace_file_check_bp
from app.api.workspace.schedule import workspace_schedule_bp
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
from app.api.workspace.voucher_check import workspace_voucher_check_bp
__all__ = [
'workspace_announcements_bp',
'workspace_file_check_bp',
'workspace_schedule_bp',
'workspace_shipping_notice_bp',
'workspace_voucher_check_bp',
]
+58 -1
View File
@@ -57,6 +57,31 @@ def serialize_current_step(payload: dict) -> dict | None:
return None
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
def serialize_progress_metrics(payload: dict) -> list[dict] | None:
"""
序列化领域自定义进度指标(如立账凭证检核的齐全/缺资料)。
核心逻辑:读取 response_summary_json.progress_metrics;非法则返回 None 以回退旧八格。
"""
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
metrics = response_summary.get('progress_metrics')
if not isinstance(metrics, list) or not metrics:
return None
out: list[dict] = []
for item in metrics:
if not isinstance(item, dict):
continue
key = str(item.get('key') or '').strip()
if not key:
continue
out.append({
'key': key,
'label_key': str(item.get('label_key') or ''),
'label': str(item.get('label') or ''),
'value': int(item.get('value') or 0),
})
return out or None
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get('total_count') or 0)
@@ -66,7 +91,39 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
processed = success + failed + skipped
percent = int(round(processed / total * 100)) if total > 0 else 0
percent = max(0, min(percent, 100))
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, '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': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'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')}}
return {
'run_id': payload['id'],
'run_no': payload['run_no'],
'task_id': payload['schedule_task_id'],
'title': payload.get('schedule_name') or '',
'status': payload['status'],
'total_count': total,
'processed_count': processed,
'success_count': success,
'failed_count': failed,
'skipped_count': skipped,
'judgement': serialize_file_judgement(payload),
'progress_metrics': serialize_progress_metrics(payload),
'current_step': serialize_current_step(payload),
'progress_percent': percent,
'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': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None,
},
'knowledge_base': {
'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'),
},
}
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
def workspace_file_check_run_for_log():
@@ -0,0 +1,70 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
"""
from __future__ import annotations
from flask import Blueprint, request
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.core.response import ok
from app.services.voucher_check import query_service
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
def _require_user():
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤。
"""
_require_user()
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 ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
def workspace_voucher_states():
"""
按月份、状态、发票号筛选最新状态。
"""
_require_user()
data = query_service.list_states(
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
status=request.args.get("status"),
invoice_no=request.args.get("invoice_no"),
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 ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states/<path:invoice_no>", methods=["GET"])
def workspace_voucher_state_detail(invoice_no: str):
"""查看单票最近状态和历史批次快照。"""
_require_user()
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 ok(data)