Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	backend/app/__init__.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-TW/admin.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-29 15:08:04 +08:00
commit 42d8b70250
300 files changed
+32072 -6411

No files matched your search

+10 -6
View File
@@ -17,21 +17,20 @@ def register_blueprints(app: Flask) -> None:
Args:
app: Flask 应用实例。
"""
# [STEP 1] 单体模块(Wave 3 前保持不变)
# [STEP 1] 域包入口(Blueprint 多在包 __init__ 或子模块)
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import auth_bp, user_bp
from app.api.integration import integration_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.internal import internal_jobs_bp
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.sso import sso_bp, sso_well_known_bp
from app.api.linked_services import linked_services_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
# [STEP 2] 其余域包与 Tool API
from app.api.kb import knowledge_base_bp
from app.api.schedule import schedule_admin_bp
from app.api.workspace import (
@@ -41,9 +40,14 @@ def register_blueprints(app: Flask) -> None:
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 (
agent_runtime_context_bp,
file_check_bp,
maintenance_tool_bp,
procurement_contract_bp,
shipping_notice_bp,
)
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
from app.api.contract_payment import contract_payment_bp
from app.api.order_delivery_reply import order_delivery_reply_bp
from app.api.in_transit_transfer import in_transit_transfer_bp
+5 -102
View File
@@ -1,107 +1,10 @@
"""
backend/app/api/agent_runtime_context_tools.py
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/agent_runtime_context.py)。
依赖:app.api.tools.agent_runtime_context。
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
"""
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
def _require_tool_auth() -> None:
"""
校验 agent_runtime_context Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
Raises:
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
UnauthorizedError: 缺少或传入错误鉴权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""
归一化 Tool API 错误码。
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
Args:
exc: 业务异常。
Returns:
Tool 侧错误码。
"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
return exc.code
@agent_runtime_context_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@agent_runtime_context_bp.before_request
def _verify_tool_access():
"""
对上下文解析 Tool 做统一 Header 鉴权。
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
"""
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
def parse_context_tool():
"""
解析 agent_runtime_context 的白名单字段。
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
不用于推进业务状态。
"""
payload = request.get_json(silent=True) or {}
return jsonify(
parse_agent_runtime_context(
payload.get("agent_runtime_context"),
payload.get("paths"),
)
)
__all__ = ['agent_runtime_context_bp']
@@ -1,5 +1,5 @@
"""
backend/app/api/agents.py
backend/app/api/agents/__init__.py
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
+2 -2
View File
@@ -2,7 +2,7 @@
api/chat/__init__.py
用途:聊天域 Blueprint 的统一入口。
依赖:chat 各职责路由模块、app.api.chat_turns。
依赖:chat 各职责路由模块、chat.turns。
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
"""
from __future__ import annotations
@@ -21,7 +21,7 @@ from .shared import ( # noqa: E402, F401
_merge_user_attachments_from_terminal_event,
_normalize_user_attachments,
)
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
from .turns import register_chat_turn_routes # noqa: E402
register_chat_turn_routes(chat_bp)
@@ -1,9 +1,9 @@
"""
backend/app/api/chat_turns.py
backend/app/api/chat/turns.py
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat 包注册到同一 Blueprint。
"""
from __future__ import annotations
@@ -1,10 +1,12 @@
"""
backend/app/api/contract_payment.py
backend/app/api/contract_payment/__init__.py
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
同步/扫描/周汇总发送仅 `role=admin`。
"""
@@ -28,16 +30,22 @@ from app.models import (
ContractPaymentContract,
ContractPaymentNode,
FileAsset,
Job,
)
from app.services.contract_payment.alert_service import build_weekly_alert_summary
from app.services.contract_payment.alert_service import build_weekly_alert_summary, describe_batch_failure, mark_payment_node_paid
from app.services.contract_payment.ledger_focus import (
LEDGER_FOCUS_VALUES,
apply_ledger_focus,
ledger_focus_counts,
)
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, normalize_purchase_order_no
from app.services.contract_payment.parse_service import unique_parse_issues
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
from app.services.file_assets.service import read_asset_bytes
from app.services.contract_payment.review_service import apply_manual_review
from app.services.contract_payment.sync_service import (
build_payment_plan,
build_payment_plan_from_bytes,
read_contract_attachment_bytes,
)
contract_payment_bp = Blueprint("contract_payment", __name__)
@@ -151,7 +159,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
"id": row.id,
"contract_no": row.contract_no,
"workflow_no": row.workflow_no,
"purchase_order_no": row.purchase_order_no,
"purchase_order_no": normalize_purchase_order_no(row.purchase_order_no) or None,
"company_name": row.company_name,
"erp_schema": erp_schema_for_company(row.company_name),
"supplier_name": row.supplier_name,
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
"currency": row.currency,
@@ -192,8 +202,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
"anchor_type": node.anchor_type,
"anchor_date": node.anchor_date.isoformat() if node.anchor_date else None,
"due_date": node.due_date.isoformat() if node.due_date else None,
# ERP apa_file 付款日期;已付款时展示,未付为空。
# 付款日期。paid_source=manual 表示人工标记,其余来自 ERP。
"paid_at": (node.evidence_json or {}).get("paid_at"),
"paid_source": (node.evidence_json or {}).get("paid_source"),
"status": node.status,
} for node in nodes],
"alerts": [{
@@ -354,7 +365,8 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
"""
下载合同详情中已归档的原文附件。
核心逻辑:附件必须同时属于请求中的合同和本地 FileAsset,避免通过附件 ID 越权读取其他合同原文。
核心逻辑:附件必须属于请求中的合同。本地 FileAsset 仍可读时直接返回;
若临时清理已删除对象,则按 OA/DMS 附件 ID 重新下载后再返回。
Args:
contract_id: 合同台账主键。
@@ -364,20 +376,19 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
受控下载的附件二进制流。
Raises:
NotFoundError: 合同、附件或其保存的文件资产不存在。
NotFoundError: 合同或附件不存在,或原文已被清理且无法从原系统重新下载。
"""
_require_contract_payment_access()
row = db.session.get(ContractPaymentContract, contract_id)
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
if not attachment or not attachment.file_asset_id:
raise NotFoundError("合同原文附件不存在")
asset = db.session.get(FileAsset, attachment.file_asset_id)
if not asset:
if not row or not attachment or not attachment.file_asset_id:
raise NotFoundError("合同原文附件不存在")
data = read_contract_attachment_bytes(row, attachment)
return send_file(
BytesIO(read_asset_bytes(asset)),
mimetype=attachment.mime_type or asset.mime_type or "application/octet-stream",
BytesIO(data),
mimetype=attachment.mime_type or "application/octet-stream",
as_attachment=True,
download_name=attachment.file_name or asset.original_filename,
download_name=attachment.file_name or "contract",
)
@@ -464,9 +475,55 @@ def enqueue_weekly_alert_send():
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
_CONTRACT_PAYMENT_JOB_TYPES = {
JobType.CONTRACT_PAYMENT_SYNC.value,
JobType.CONTRACT_PAYMENT_ALERT.value,
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY.value,
}
@contract_payment_bp.route("/jobs/<int:job_id>", methods=["GET"])
def get_contract_payment_job(job_id: int):
"""查询当前管理员提交的合同付款后台任务是否已经跑完。
核心逻辑:只返回本人创建的合同付款 Job,避免用任务号读到其它域的执行结果。
周汇总发送的 result 含 sent / failed,供页面在刷新批次列表前判断这次有没有真正发出。
Args:
job_id: jobs 表主键。
Returns:
标准成功 envelope,含 status、message 与 result。
Raises:
NotFoundError: 任务不存在,或不属于当前管理员的合同付款任务。
"""
user = _require_contract_payment_admin()
row = db.session.get(Job, job_id)
if (
row is None
or row.domain != "procurement_contract"
or row.job_type not in _CONTRACT_PAYMENT_JOB_TYPES
or row.created_by_id != user.id
):
raise NotFoundError("任务不存在")
return ok({
"id": row.id,
"status": row.status,
"message": row.message,
"result": row.result_json or {},
}, request_id=getattr(g, "request_id", None))
@contract_payment_bp.route("/alert-batches", methods=["GET"])
def list_alert_batches():
"""查询近期合同付款预警周汇总批次。"""
"""查询近期合同付款预警周汇总批次。
核心逻辑:按创建时间倒序最多返回 100 条。失败批次附带 failure_reasons,
供周汇总页点击图标展示;成功批次不返回原因,也不下发企微原始轨迹。
Returns:
标准成功 envelope,items 含批次摘要;失败项另含 failure_reasons。
"""
_require_contract_payment_access()
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
return ok({"items": [{
@@ -475,6 +532,11 @@ def list_alert_batches():
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
"created_at": row.created_at.isoformat(),
"failure_reasons": (
describe_batch_failure(row.wecom_trace_json, fallback=row.error_message)
if row.status == "failed"
else []
),
} for row in rows]}, request_id=getattr(g, "request_id", None))
@@ -519,8 +581,8 @@ def reparse_contract_attachment(contract_id: int):
"""
使用已归档的合同原文附件重新生成付款解析结果。
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;服务端只读取该合同
已保存的附件,优先盖章完成合同上传,覆盖付款节点、解析状态和问题列表,不调用 OA。
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;优先读取该合同
已保存的附件(盖章完成合同上传优先)。原文若已被临时清理删除,则按附件 ID 重新下载后再解析。
Args:
contract_id: 合同付款台账主键。
Returns:
@@ -543,12 +605,58 @@ def reparse_contract_attachment(contract_id: int):
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
attachment = min(attachments, key=_attachment_parse_priority)
asset = db.session.get(FileAsset, attachment.file_asset_id)
if not asset:
raise ValidationError("当前合同原文附件不存在,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=read_asset_bytes(asset))
data = read_contract_attachment_bytes(row, attachment)
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=data)
return ok({
"contract": _serialize_contract(row),
"parse_result": result,
"attachment_name": attachment.file_name,
}, request_id=getattr(g, "request_id", None))
@contract_payment_bp.route("/contracts/<int:contract_id>/manual-review", methods=["POST"])
def manual_review_contract(contract_id: int):
"""
保存待确认合同的人工复核,并在校验通过后放入合同台账。
核心逻辑:与单合同重解析一样,持有合同付款 Agent 的用户即可提交,不要求平台管理员。
服务层负责比例合计、金额核对和必填日期;本接口只转交请求体并返回更新后的合同。
Args:
contract_id: 合同付款台账主键。
Returns:
标准成功 envelope,含复核后的合同详情。
Raises:
NotFoundError: 合同不存在。
ValidationError: 采购单号、金额、比例或日期不满足进入台账的条件。
"""
user = _require_contract_payment_access()
data = request.get_json() or {}
row = apply_manual_review(contract_id, data, operator_id=getattr(user, "id", None))
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
def mark_contract_node_paid(contract_id: int, node_id: int):
"""
把未付的预付款或出货款手动标为已付。
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。只改这一阶段,并关闭尚未发送的预警。
Args:
contract_id: 合同台账主键。
node_id: 付款节点主键。
Returns:
标准成功 envelope,含更新后的合同详情。
Raises:
NotFoundError: 合同或节点不存在。
ValidationError: 阶段不能标记,或付款日期无效。
"""
user = _require_contract_payment_access()
data = request.get_json() or {}
row = mark_payment_node_paid(contract_id, node_id, data, operator_id=getattr(user, "id", None))
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
+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',
]
@@ -1,13 +1,19 @@
"""backend/app/api/in_transit_transfer.py
"""backend/app/api/in_transit_transfer/__init__.py
用途:在途仓自动调拨用户态 API(仓库管理人员)。
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
D18 废单不废行)。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from functools import wraps
from typing import Any
@@ -22,14 +28,24 @@ from app.services.in_transit_transfer.cancellation import cancel_run
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
from app.services.in_transit_transfer.execution_service import (
execute_precheck,
get_run,
serialize_run_result,
prepare_execution,
retrigger_document,
)
from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
from app.services.in_transit_transfer.matching_service import (
create_matching,
list_executable_items,
restore_matching,
)
from app.services.in_transit_transfer.retry_service import (
requery_items as retry_service_requery_items,
requery_items_by_ids,
retry_item,
)
from app.services.in_transit_transfer.manual_close_service import manual_close_item
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
from app.services.in_transit_transfer.serializers import (
DOCUMENT_STATUS_GROUPS,
serialize_executed_order,
serialize_item,
serialize_source,
serialize_summary,
@@ -69,15 +85,15 @@ def _ok(payload: Any, *, status: int = 200):
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
@in_transit_transfer_bp.route("/matchings", methods=["POST"])
@require_transfer_permission
def create_precheck_api():
"""创建或复用一次调拨预检(只读,不写 外部系统)。
def create_matching_api():
"""创建或复用一次调拨匹配(只读,不写 外部系统)。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
"receipt_date_from"/"receipt_date_to"(可选),
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
@@ -87,7 +103,7 @@ def create_precheck_api():
raise ValidationError("source_codes is required")
business_date = str(body.get("business_date") or business_date_now())
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
summary = create_matching(
source_codes=[str(item).strip() for item in source_codes],
business_date=business_date,
deps=deps,
@@ -98,11 +114,18 @@ def create_precheck_api():
return _ok(serialize_summary(summary), status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
@in_transit_transfer_bp.route("/items/executable", methods=["GET"])
@require_transfer_permission
def get_precheck_api(precheck_id: str):
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
restored = restore_precheck(precheck_id)
def executable_items_api():
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。"""
return _ok(list_executable_items())
@in_transit_transfer_bp.route("/matchings/<matching_id>", methods=["GET"])
@require_transfer_permission
def get_matching_api(matching_id: str):
"""恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。"""
restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies())
return _ok({
"summary": serialize_summary(restored["summary"]),
"items": [serialize_item(item) for item in restored["items"]],
@@ -110,41 +133,16 @@ def get_precheck_api(precheck_id: str):
})
@in_transit_transfer_bp.route("/prechecks/<precheck_id>/execute", methods=["POST"])
@in_transit_transfer_bp.route("/matchings/<matching_no>/items/requery", methods=["POST"])
@require_transfer_permission
def execute_precheck_api(precheck_id: str):
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
"""
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
if invoice_nos is not None and not isinstance(invoice_nos, list):
raise ValidationError("invoice_nos must be a list")
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
return _ok({
"run_no": outcome.run_no,
"status": outcome.status,
"result": serialize_run_result(outcome.result),
}, status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
@require_transfer_permission
def requery_items_api(precheck_no: str):
def requery_items_api(matching_no: str):
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
user = _require_user()
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_service_requery_items(
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
matching_no=matching_no, deps=deps, invoice_nos=invoice_nos,
actor_id=str(user.id) if user.id else None,
))
@@ -180,7 +178,7 @@ def download_source_receipt_files_api():
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
# 单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
@@ -220,7 +218,11 @@ def download_source_receipt_files_api():
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
@require_transfer_permission
def get_run_api(run_no: str):
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
"""恢复 Run 结果(页面刷新/会话恢复)。
返回体:result(单号聚合 + exceptions 既有口径)+ orders 调拨单清单
(D9 融合卡数据源:调拨单清单=进度=结果,轮询即恢复最新单态)。
"""
return _ok(get_run(run_no))
@@ -255,6 +257,300 @@ def manual_close_item_api(item_id: int):
return _ok(manual_close_item(item_id=item_id, reason=reason))
def _require_item_ids(body: Any) -> list[int]:
"""解析并校验批量操作的 item_ids(非空整数列表)。"""
raw = body.get("item_ids") if isinstance(body, dict) else None
if not isinstance(raw, list) or not raw:
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
try:
return [int(x) for x in raw]
except (TypeError, ValueError) as exc:
raise ValidationError("item_ids must be integers", code="TRANSFER.BATCH_ITEMS_REQUIRED") from exc
@in_transit_transfer_bp.route("/items/execute", methods=["POST"])
@require_transfer_permission
def execute_items_api():
"""按行提交执行(D8 异步:202 排队,单在提交时已组建,worker 逐单执行)。
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
响应:202 envelope,data 为 {"run_no", "status": "queued"}(纯库内毫秒级:
两道门禁(存在可执行 + 文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)+
建 queued Run + 五元组分组建单 + 一次入队);
门禁失败 400,error.details 携带对应 id 列表
(invalid_item_ids / changed_item_ids)。
进度与结果经 GET /runs/{run_no} 轮询恢复(融合卡数据源)。
"""
user = _require_user()
body = request.get_json(silent=True) or {}
item_ids = _require_item_ids(body)
deps = transfer_deps.get_transfer_dependencies()
outcome = prepare_execution(
item_ids=item_ids,
deps=deps,
actor_id=user.id,
request_id=getattr(g, "request_id", None),
)
return _ok({
"run_no": outcome.run_no,
"status": outcome.status,
}, status=202)
@in_transit_transfer_bp.route("/runs/<run_no>/documents/<doc_no>/retrigger", methods=["POST"])
@require_transfer_permission
def retrigger_document_api(run_no: str, doc_no: str):
"""人工重新触发 result_unknown 单(D11 唯一出口,禁止关闭重建)。
语义:复用本单 doc_no/submit_timestamp,只触发末步(D7②,幂等安全);
成功后单/行推进成功族并亮出原单号。人工动作,非自动重试。
响应:202 envelope,data 为 {"run_no", "doc_no", "status": "queued"};
非 result_unknown 单 → 400(TRANSFER.RETRIGGER_NOT_ALLOWED)。
"""
user = _require_user()
deps = transfer_deps.get_transfer_dependencies()
outcome = retrigger_document(
run_no=run_no,
doc_no=doc_no,
deps=deps,
actor_id=str(user.id) if user.id else None,
request_id=getattr(g, "request_id", None),
)
return _ok(outcome, status=202)
@in_transit_transfer_bp.route("/documents", methods=["GET"])
@require_transfer_permission
def list_documents_api():
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
Query:
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
page(默认 1);page_size(默认 20,上限 100)。
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
"""
from app import db
from app.models import TransferDocument, TransferInvoiceItem
from sqlalchemy import func
def _parse_date(name: str):
"""解析 YYYY-MM-DD 查询参数;空缺省返回 None,非法格式 400。"""
raw = (request.args.get(name) or "").strip()
if not raw:
return None
try:
return datetime.strptime(raw, "%Y-%m-%d").date()
except ValueError as exc:
raise ValidationError(f"{name} must be YYYY-MM-DD") from exc
def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。"""
raw = (request.args.get(name) or "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError as exc:
raise ValidationError(f"{name} must be an integer") from exc
value = max(minimum, value)
if maximum is not None:
value = min(maximum, value)
return value
# [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。
status_group = (request.args.get("status_group") or "").strip()
if status_group and status_group not in DOCUMENT_STATUS_GROUPS:
raise ValidationError(
f"status_group must be one of {sorted(DOCUMENT_STATUS_GROUPS)}",
)
date_from = _parse_date("date_from")
date_to = _parse_date("date_to")
page = _parse_int("page", 1, minimum=1)
page_size = _parse_int("page_size", 20, minimum=1, maximum=100)
# [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。
counts = dict(
db.session.query(TransferDocument.status, func.count())
.group_by(TransferDocument.status)
.all()
)
groups = {
group: sum(counts.get(status, 0) for status in statuses)
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
}
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
if status_group:
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
if date_from:
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
if date_to:
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
query = query.filter(TransferDocument.created_at < window_end)
total = query.count()
docs = (
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
# [STEP 4] items 批量查回(防 N+1),按 document_id 分组后逐单投影。
doc_ids = [doc.id for doc in docs]
items_by_doc: dict[int, list] = {}
if doc_ids:
rows = (
TransferInvoiceItem.query.filter(TransferInvoiceItem.document_id.in_(doc_ids))
.order_by(TransferInvoiceItem.id.asc())
.all()
)
for row in rows:
items_by_doc.setdefault(row.document_id, []).append(row)
return _ok({
"groups": groups,
"total": total,
"page": page,
"page_size": page_size,
"orders": [serialize_executed_order(doc, items_by_doc.get(doc.id, [])) for doc in docs],
})
@in_transit_transfer_bp.route("/documents/<doc_no>/close", methods=["POST"])
@require_transfer_permission
def close_document_api(doc_no: str):
"""人工关闭失败单(D18:语义=A 废单不废行;首页已执行区块/融合卡共用)。
门禁:仅 business_failed/technical_failed 可关;result_unknown → 400
(D11:结果未知单唯一出口=重新触发,禁止「关闭后重建」双单路径);
pending/executing → 400(在飞);原因必填;单不存在 404。
行为:doc.status='cancelled' + closed_reason=reason;单内 items 全部脱离
(document_id=NULL、status→ready_to_execute、清 result_code/result_message
——原路由漂移行由执行期既有守卫重新把关);审计事件(actor/reason/
前后状态/行数)。
效果:cancelled 不在部分唯一索引未完结集 → 组锁释放,同组可另开新单。
"""
from app import db
from app.models import TransferDocument, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
user = _require_user()
body = request.get_json(silent=True) or {}
reason = str(body.get("reason") or "").strip() if isinstance(body, dict) else ""
# [STEP 1] 原因必填(复用人工关闭既有错误码,查重不新增)。
if not reason:
raise ValidationError(
"document close reason is required",
code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
)
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
if doc is None:
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
# [STEP 2] 状态门禁:result_unknown 走 retrigger(D11);在飞/已完结单拒绝。
if doc.status == "result_unknown":
raise ValidationError(
"result_unknown order cannot be closed; use retrigger instead (D11)",
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
)
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
raise ValidationError(
f"order status {doc.status} is not closeable (in-flight or settled)",
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
)
# [STEP 3] D18 行脱离:单内 items 全部脱离单(document_id=NULL)回
# ready_to_execute(可重新勾选组建新单),行级结果清空。
before_status = doc.status
items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
for item in items:
item.document_id = None
item.status = ready_status
item.result_code = None
item.result_message = None
# [STEP 4] 单 cancelled + closed_reason 可视留档;组锁随之释放。
doc.status = "cancelled"
doc.closed_reason = reason
# [STEP 5] 审计事件(actor/reason/前后状态/行数)后提交。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_DOCUMENT_CLOSED",
aggregate_type="transfer_document",
aggregate_id=doc.doc_no,
run_no=doc.run.run_no if doc.run_id and doc.run else None,
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
before={"status": before_status},
after={"status": doc.status, "reason": reason, "item_count": len(items)},
))
db.session.commit()
return _ok({"doc_no": doc.doc_no, "status": doc.status, "released_items": len(items)})
@in_transit_transfer_bp.route("/documents/<doc_no>/retry", methods=["POST"])
@require_transfer_permission
def retry_document_api(doc_no: str):
"""调拨单级重试(失败单一键恢复主路径)。
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
"""
from app.services.in_transit_transfer.retry_service import retry_document
user = _require_user()
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_document(
doc_no=doc_no, deps=deps,
actor_id=user.id if user and user.id else None,
request_id=getattr(g, "request_id", None),
))
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
@require_transfer_permission
def batch_requery_items_api():
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
user = _require_user()
body = request.get_json(silent=True) or {}
item_ids = _require_item_ids(body)
deps = transfer_deps.get_transfer_dependencies()
return _ok(requery_items_by_ids(
item_ids=item_ids, deps=deps,
actor_id=str(user.id) if user.id else None,
request_id=getattr(g, "request_id", None),
))
@in_transit_transfer_bp.route("/items/batch-manual-close", methods=["POST"])
@require_transfer_permission
def batch_manual_close_items_api():
"""批量人工关闭异常项(原因必填,整批共用;单行隔离)。"""
user = _require_user()
body = request.get_json(silent=True) or {}
item_ids = _require_item_ids(body)
return _ok(manual_close_items(
item_ids=item_ids, reason=str(body.get("reason") or ""),
actor_id=str(user.id) if user.id else None,
request_id=getattr(g, "request_id", None),
))
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
@require_transfer_permission
def exceptions_excel_api(run_no: str):
@@ -301,8 +597,8 @@ def receipt_files_api(run_no: str):
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
precheck = run.prechecks[0] if run.prechecks else None
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {}
matching = run.matchings[0] if run.matchings else None
file_snapshot = matching.file_snapshot_json if matching and isinstance(matching.file_snapshot_json, dict) else {}
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
@@ -347,7 +643,7 @@ def receipt_files_api(run_no: str):
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
@require_transfer_permission
def erp_inventory_api(run_no: str):
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
"""下载本次匹配冻结的 外部系统 库存表(csv);记录访问审计。"""
import io
from app import db
@@ -403,7 +699,7 @@ def transfer_sources_api():
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
"""
from app.models import ShippingInventorySource
@@ -502,7 +798,7 @@ def backlog_summary_api():
def _serialize_backlog_item(item) -> dict[str, Any]:
"""待处理池项序列化。"""
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
return {
'item_id': item.item_id,
'source_code': item.source_code,
@@ -513,4 +809,12 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
'age_days': item.age_days,
'aging_level': item.aging_level,
'last_attempt_at': item.last_attempt_at,
'receipt_date': item.receipt_date,
'material_name': item.material_name,
'from_warehouse': item.from_warehouse,
'to_warehouse': item.to_warehouse,
'lot_no': item.lot_no,
'receipt_quantity': item.receipt_quantity,
'external_quantity': item.external_quantity,
'result_code': item.result_code,
}
@@ -1,5 +1,5 @@
"""
backend/app/api/integration.py
backend/app/api/integration/__init__.py
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
@@ -1,13 +1,20 @@
"""api/integration_connector.py
"""
backend/app/api/integration_connector/__init__.py
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto、
models.integration_connector.CONNECTOR_TYPES / DB_KINDS(白名单同源)。
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
客户端实例 connector_type ∈ rest/soap/database;database 时 db_kind 必填且 ∈
mysql/oracle/sqlserver/postgresql,非 database 强制置 NULL。
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
@@ -28,10 +35,12 @@ from app.core.errors import AppError, NotFoundError, ValidationError
from app.core.response import ok
from app.models import (
IntegrationBinding,
IntegrationCall,
IntegrationClientInstance,
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
from app.services.integration_connector.capability import list_capabilities
from app.services.integration_connector.credential_types import (
build_secret_dict,
@@ -40,12 +49,18 @@ from app.services.integration_connector.credential_types import (
visible_fields,
)
from app.services.integration_connector.gateway import get_capability_gateway
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
from app.services.integration_connector.security import (
CREDENTIAL_KEY_CONFIG_NAME,
_DB_SECRET_CODES,
resolve_credential,
)
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
integration_connector_bp = Blueprint('integration_connector', __name__)
VALID_CONNECTOR_TYPES = ('rest', 'soap')
# 与模型 CONNECTOR_TYPES / DB_KINDS 同源,禁止本地另维护一份白名单。
VALID_CONNECTOR_TYPES = CONNECTOR_TYPES
VALID_DB_KINDS = DB_KINDS
VALID_STATUSES = ('draft', 'published', 'retired')
VALID_SECRET_PROVIDERS = ('db', 'env')
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
@@ -70,6 +85,32 @@ def _require(value, field: str) -> None:
raise ValidationError(f'{field} is required', details={'field': field})
def _resolve_db_kind(connector_type: str, raw_db_kind) -> str | None:
"""按连接器类型解析 db_kind:database 必填且 ∈ VALID_DB_KINDS;其余强制 NULL。
Args:
connector_type: 已校验的连接器类型。
raw_db_kind: 请求体中的 db_kind(可为 None/空串)。
Returns:
合法库种字符串,或非 database 时的 None。
Raises:
ValidationError: database 缺省或未知库种(fail-closed,含历史别名 mssql)。
"""
if connector_type != 'database':
return None
kind = str(raw_db_kind or '').strip()
if not kind:
raise ValidationError('db_kind is required for database connector', details={'field': 'db_kind'})
if kind not in VALID_DB_KINDS:
raise ValidationError(
'invalid db_kind',
details={'field': 'db_kind', 'allowed': list(VALID_DB_KINDS)},
)
return kind
def _require_client(code: str) -> IntegrationClientInstance:
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
@@ -112,7 +153,8 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
400(fail-fast),不留给调用期 fail-closed。
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
client_instance_code 与首步接口的一致性检查。
"""
client = _require_client(str(client_code).strip())
iface = _require_interface(str(interface_code).strip())
@@ -129,16 +171,101 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
return client, iface
def _normalize_binding_steps(body: dict) -> list[dict]:
"""校验并归一化绑定 steps_json(非空数组;每步 interface 存在且客户端可用)。
核心逻辑:优先读 steps_json;缺省时用旧单步字段合成一元素数组(兼容窗)。
每步 interface_code 必须存在,其归属客户端必须存在(绑定的客户端实例族);
param_mapping_json 须为 dict。返回供落库的 [{interface_code, param_mapping_json}, ...]。
Args:
body: 创建/更新请求体。
Returns:
归一化后的步骤列表(至少一元素)。
Raises:
ValidationError: 空数组、步形状非法、接口不存在、映射非 dict。
"""
raw = body.get('steps_json')
if raw is None:
# 兼容窗:旧单步 API 字段 → 单元素 steps
iface_code = body.get('interface_definition_code')
if not iface_code:
raise ValidationError(
'steps_json is required',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json'},
)
raw = [{
'interface_code': iface_code,
'param_mapping_json': body.get('param_mapping_json') or {},
}]
if not isinstance(raw, list) or len(raw) == 0:
raise ValidationError(
'steps_json must be a non-empty array',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json'},
)
normalized: list[dict] = []
for idx, step in enumerate(raw):
if not isinstance(step, dict):
raise ValidationError(
'each step must be an object',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json', 'index': idx},
)
iface_code = step.get('interface_code') or step.get('interface_definition_code')
_require(iface_code, f'steps_json[{idx}].interface_code')
mapping = step.get('param_mapping_json', step.get('param_mapping', {}))
if mapping is None:
mapping = {}
if not isinstance(mapping, dict):
raise ValidationError(
'step param_mapping_json must be an object',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json', 'index': idx, 'key': 'param_mapping_json'},
)
iface = _require_interface(str(iface_code).strip())
# 客户端实例族:接口归属客户端必须存在(跨步可不同客户端,如 database+soap)。
_require_client(iface.client_instance_code)
normalized.append({
'interface_code': iface.code,
'param_mapping_json': mapping,
})
# 若请求仍带绑定级 client_instance_code,与首步接口做成对校验(防错配镜像列)。
binding_client = body.get('client_instance_code')
if binding_client is not None and str(binding_client).strip():
_validate_binding_pair(binding_client, normalized[0]['interface_code'])
return normalized
def _mirror_legacy_binding_columns(steps: list[dict]) -> tuple[str, str, dict]:
"""由归一化 steps 镜像旧 NOT NULL 列(首步);P2 删列前保持可写。
Returns:
(client_instance_code, interface_definition_code, param_mapping_json)
"""
first = steps[0]
iface = _require_interface(first['interface_code'])
return iface.client_instance_code, iface.code, dict(first.get('param_mapping_json') or {})
def _interface_transition(iface, action: str) -> None:
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
_apply_status_transition(iface, action, kind='interface')
def _serialize_client(client) -> dict:
"""客户端实例序列化(含 database 专列 db_kind;非 database 为 null)。"""
return {
'id': client.id, 'code': client.code, 'name': client.name,
'connector_type': client.connector_type, 'environment': client.environment,
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
'db_kind': client.db_kind,
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
'enabled': client.enabled,
}
@@ -156,9 +283,11 @@ def _serialize_interface(iface) -> dict:
def _serialize_binding(binding) -> dict:
"""绑定序列化:含 steps_json;旧单步列仍回显(P2 删前列镜像)。"""
return {
'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {},
'steps_json': binding.steps_json or [],
'param_mapping_json': binding.param_mapping_json or {},
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
@@ -276,6 +405,7 @@ def list_client_instances():
@integration_connector_bp.route('/client-instances', methods=['POST'])
@require_admin
def create_client_instance():
"""创建客户端实例;database 类型强制校验 db_kind 四库枚举,非 database 置 NULL。"""
body = request.get_json(silent=True) or {}
connector_type = str(body.get('connector_type') or '').strip()
_require(body.get('code'), 'code')
@@ -284,11 +414,13 @@ def create_client_instance():
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
db_kind = _resolve_db_kind(connector_type, body.get('db_kind'))
client = IntegrationClientInstance(
code=str(body['code']).strip(), name=str(body['name']).strip(),
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
endpoint=(str(body.get('endpoint') or '').strip() or None),
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
db_kind=db_kind,
config_json=body.get('config_json') or {},
credential_ref_code=body.get('credential_ref_code'),
enabled=bool(body.get('enabled', True)),
@@ -323,7 +455,10 @@ def delete_client_instance(code):
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
@require_admin
def update_client_instance(code):
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停/db_kind)。
database 类型必填合法 db_kind;切离 database 时强制清空 db_kind。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
@@ -348,6 +483,9 @@ def update_client_instance(code):
client.credential_ref_code = body.get('credential_ref_code')
if 'enabled' in body:
client.enabled = bool(body.get('enabled', True))
# 最终类型决定 db_kind:database 必填合法值;rest/soap 强制 NULL。
raw_kind = body['db_kind'] if 'db_kind' in body else client.db_kind
client.db_kind = _resolve_db_kind(connector_type, raw_kind)
from app import db
db.session.commit()
return ok(_serialize_client(client))
@@ -482,18 +620,22 @@ def list_bindings():
@integration_connector_bp.route('/bindings', methods=['POST'])
@require_admin
def create_binding():
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
"""
body = request.get_json(silent=True) or {}
_require(body.get('capability'), 'capability')
_require(body.get('client_instance_code'), 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code')
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
steps = _normalize_binding_steps(body)
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding = IntegrationBinding(
capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {},
param_mapping_json=body.get('param_mapping_json') or {},
client_instance_code=client.code,
interface_definition_code=iface.code,
steps_json=steps,
param_mapping_json=param_mapping,
client_instance_code=client_code,
interface_definition_code=iface_code,
mapping_version=int(body.get('mapping_version') or 1),
priority=int(body.get('priority') or 0),
environment=str(body.get('environment') or 'prod').strip(),
@@ -508,10 +650,14 @@ def create_binding():
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin
def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
[1] steps_json 与旧单步字段(interface_definition_code/param_mapping_json)同 PUT
属矛盾载荷 → 400(旧键会被静默忽略、部分生效无提示);
[2] 三把旧钥匙(interface_definition_code/param_mapping_json/client_instance_code)
任一出现在多步绑定 PUT → 400(兼容窗会合成单元素 steps 回写、静默销毁第 2..n 步);
[3] 单步绑定的旧字段 PUT 走兼容窗(换绑接口 / 仅更新首步映射);纯 steps_json PUT 不受限。
"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
@@ -523,23 +669,83 @@ def update_binding(binding_id):
binding.capability = body['capability']
if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {}
if 'param_mapping_json' in body:
binding.param_mapping_json = body.get('param_mapping_json') or {}
new_client_code = body.get('client_instance_code')
new_iface_code = body.get('interface_definition_code')
if new_client_code is not None:
_require(new_client_code, 'client_instance_code')
if new_iface_code is not None:
_require(new_iface_code, 'interface_definition_code')
if new_client_code is not None or new_iface_code is not None:
_validate_binding_pair(
new_client_code if new_client_code is not None else binding.client_instance_code,
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
if 'steps_json' in body:
# 评审 P2-2:矛盾载荷 fail-fast——steps_json 分支本会静默忽略旧单步键(部分生效无提示)。
# client_instance_code 不在矛盾集:它在 steps_json 分支仍被消费(首步成对校验)。
conflicts = sorted(
key for key in ('interface_definition_code', 'param_mapping_json') if key in body
)
if new_client_code is not None:
binding.client_instance_code = str(new_client_code).strip()
if new_iface_code is not None:
binding.interface_definition_code = str(new_iface_code).strip()
if conflicts:
raise ValidationError(
'steps_json PUT cannot carry legacy single-step fields; they would be silently ignored',
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
details={
'fields': conflicts,
'conflicting_with': 'steps_json',
'hint': 'submit the full ordered recipe via steps_json only',
},
)
merge_body = {
'steps_json': body['steps_json'],
'client_instance_code': body.get('client_instance_code'),
}
steps = _normalize_binding_steps(merge_body)
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding.steps_json = steps
binding.client_instance_code = client_code
binding.interface_definition_code = iface_code
binding.param_mapping_json = param_mapping
elif 'interface_definition_code' in body or 'client_instance_code' in body or 'param_mapping_json' in body:
# 评审 P1 守卫:三把旧钥匙(含 client_instance_code)任一出现在多步绑定 PUT,
# 都会经兼容窗用旧单步列合成单元素 steps 回写、静默销毁第 2..n 步 → fail-fast 400。
legacy_keys = sorted(
key for key in ('interface_definition_code', 'param_mapping_json', 'client_instance_code')
if key in body
)
if binding.steps_json and len(binding.steps_json) > 1:
raise ValidationError(
'legacy single-step fields cannot update a multi-step binding; use steps_json',
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
details={
'fields': legacy_keys,
'steps_count': len(binding.steps_json),
'hint': 'submit the full ordered recipe via steps_json',
},
)
# 兼容窗:旧单步字段 → 重写/局部更新 steps
if (
'param_mapping_json' in body
and 'interface_definition_code' not in body
and 'client_instance_code' not in body
and binding.steps_json
):
steps = [dict(s) if isinstance(s, dict) else s for s in binding.steps_json]
first = dict(steps[0])
first['param_mapping_json'] = body.get('param_mapping_json') or {}
steps[0] = first
steps = _normalize_binding_steps({
'steps_json': steps,
'client_instance_code': binding.client_instance_code,
})
else:
steps = _normalize_binding_steps({
'interface_definition_code': body.get(
'interface_definition_code', binding.interface_definition_code,
),
'client_instance_code': body.get(
'client_instance_code', binding.client_instance_code,
),
'param_mapping_json': body.get(
'param_mapping_json', binding.param_mapping_json or {},
),
})
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding.steps_json = steps
binding.client_instance_code = client_code
binding.interface_definition_code = iface_code
binding.param_mapping_json = param_mapping
if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None:
@@ -550,7 +756,6 @@ def update_binding(binding_id):
binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not None:
binding.effective_to = body['effective_to'] or None
from app import db
db.session.commit()
return ok(_serialize_binding(binding))
@@ -560,7 +765,7 @@ def update_binding(binding_id):
def _do_binding_lifecycle(binding_id: int, action: str):
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
(与 binding.resolve_binding 的调用期门禁同一语义)。
"""
@@ -569,17 +774,44 @@ def _do_binding_lifecycle(binding_id: int, action: str):
if binding is None:
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
if action == 'publish':
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
if client is None or iface is None or iface.status != 'published' or not client.enabled:
raw_steps = list(binding.steps_json or [])
if not raw_steps and binding.interface_definition_code:
raw_steps = [{
'interface_code': binding.interface_definition_code,
'param_mapping_json': binding.param_mapping_json or {},
}]
if not raw_steps:
raise ValidationError(
'binding target not ready: interface must be published and client instance enabled',
'binding target not ready: steps_json is empty',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
},
details={'steps_json': []},
)
for idx, step in enumerate(raw_steps):
if not isinstance(step, dict):
raise ValidationError(
'binding target not ready: invalid step',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={'index': idx},
)
iface_code = str(step.get('interface_code') or '').strip()
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
client = (
IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
if iface is not None else None
)
if client is None or iface is None or iface.status != 'published' or not client.enabled:
raise ValidationError(
'binding target not ready: each step interface must be published '
'and client instance enabled',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'index': idx,
'interface_code': iface_code,
'client_instance_code': getattr(iface, 'client_instance_code', None),
'iface_status': getattr(iface, 'status', None),
'client_enabled': getattr(client, 'enabled', None),
},
)
_apply_status_transition(binding, action, kind='binding')
db.session.commit()
return ok(_serialize_binding(binding))
@@ -718,8 +950,8 @@ def update_credential_reference(code):
def test_connection(code):
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
@@ -735,8 +967,12 @@ def test_connection(code):
'config_json': client.config_json or {},
'endpoint': client.endpoint,
'timeout_seconds': client.timeout_seconds,
'db_kind': client.db_kind,
}),
'credential': {},
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
# 有凭据引用时解析真实凭据(db 解密 / env 注入,与 engine 调用链同源),
# 无引用(匿名)为空 dict;解析失败 fail-closed 抛 CredentialUnresolvedError。
'credential': resolve_credential(client.credential_ref_code) if client.credential_ref_code else {},
}
probe = getattr(transport, 'probe', None)
if probe is not None:
@@ -747,3 +983,82 @@ def test_connection(code):
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
# ---- 集成调用日志查询 ----
@integration_connector_bp.route('/calls', methods=['GET'])
@require_admin
def list_integration_calls_api():
"""集成调用日志分页查询(能力无关通用口径)。
筛选:capability/interface_code/client_code/connector_type/status/
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
"""
from sqlalchemy import cast, String
args = request.args
query = IntegrationCall.query
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
value = (args.get(field) or '').strip()
if value:
query = query.filter(getattr(IntegrationCall, field) == value)
for json_field in ('interface_code', 'client_code', 'connector_type'):
value = (args.get(json_field) or '').strip()
if value:
query = query.filter(
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
keyword = (args.get('keyword') or '').strip()
if keyword:
query = query.filter(
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
date_from = (args.get('date_from') or '').strip()
if date_from:
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
date_to = (args.get('date_to') or '').strip()
if date_to:
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
page = max(int(args.get('page') or 1), 1)
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
total = query.count()
rows = (query.order_by(IntegrationCall.id.desc())
.offset((page - 1) * page_size).limit(page_size).all())
def _row(c: IntegrationCall) -> dict:
snap = c.binding_snapshot_json or {}
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
'capability': c.capability, 'operation_id': c.operation_id,
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
'business_ref': c.business_ref,
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
'connector_type': snap.get('connector_type'),
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
return ok({'total': total, 'page': page, 'page_size': page_size,
'items': [_row(c) for c in rows]})
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
@require_admin
def get_integration_call_api(call_id: int):
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
call = IntegrationCall.query.get(call_id)
if call is None:
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
'capability': call.capability, 'operation_id': call.operation_id,
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
'business_ref': call.business_ref,
'binding_snapshot_json': call.binding_snapshot_json or {},
'request_summary_json': call.request_summary_json or {},
'response_summary_json': call.response_summary_json or {},
'wire_json': call.wire_json}
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
.order_by(IntegrationCall.id.asc()).all())
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
return ok({'call': full, 'timeline': timeline})
+3 -1
View File
@@ -1,7 +1,9 @@
"""
backend/app/api/internal/__init__.py
用途:内部 job 回调/健康检查 Blueprint。
用途:内部 Job 回调 / 健康检查 Blueprint 包。
依赖:internal.jobs。
逻辑:register_blueprints 从本包导入 internal_jobs_bp,挂载 /api/internal/jobs。
"""
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
+218 -3
View File
@@ -1,8 +1,223 @@
"""
backend/app/api/internal/jobs.py
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
依赖:job_registry、schedule_contract、scheduler_service。
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
from __future__ import annotations
__all__ = ['internal_jobs_bp']
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
)
internal_jobs_bp = Blueprint('internal_jobs', __name__)
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
"""
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
Raises:
ValidationError: 非 platform_job 或 platform_api_path 不匹配
"""
if task.schedule_type != 'platform_job':
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
task_key = normalize_job_key(task.platform_api_path)
if task_key != job_key:
raise ValidationError(
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
f"does not match job key '{job_key}'"
)
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
"""
解析或创建 ScheduleTask / ScheduleRun。
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
run_no 查询限定 schedule_task_id,避免跨任务写入。
"""
schedule_task_id = data.get('schedule_task_id')
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
if task:
_assert_task_matches_job_key(task, job_key)
else:
task = (
ScheduleTask.query.filter(
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
)
.order_by(ScheduleTask.id.desc())
.first()
)
if not task:
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
run_no = str(data.get('run_no') or '').strip()
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
if not run:
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
if foreign and foreign.schedule_task_id != task.id:
raise ValidationError(
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
f"not {task.id}"
)
if not run:
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
return task, run
def _finalize_run(
run: ScheduleRun,
*,
total_count: int,
success_count: int,
failed_count: int,
skipped_count: int,
step_logs: list | None,
) -> None:
"""写入 run 汇总字段并 commit。"""
run.status = (
'success' if failed_count == 0
else 'failed' if success_count == 0
else 'partial_failed'
)
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.finished_at = datetime.utcnow()
if run.started_at and run.finished_at:
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
"""
执行已注册平台 Job。
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
key = normalize_job_key(name)
data = request.get_json(silent=True) or {}
if not get_platform_job(key):
raise NotFoundError(f"Unknown platform job: {name}")
task, run = _resolve_schedule_task_and_run(key, data)
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data,
)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=str(exc),
http_status=500,
details={
'traceback': traceback.format_exc(),
'summary': {
'total_count': 0,
'success_count': 0,
'failed_count': 0,
'skipped_count': 0,
},
},
)
if should_defer_schedule_run_finalization(task, step_logs):
apply_deferred_schedule_run_state(
run,
task,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
details=details,
errors=errors,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
'awaiting_rpa_callback': True,
})
if should_defer_receipt_schedule_run(task, step_logs):
apply_deferred_receipt_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count, 'success_count': success_count,
'failed_count': failed_count, 'skipped_count': skipped_count,
},
'details': details, 'errors': errors, 'step_logs': step_logs,
'awaiting_receipt_rpa_callback': True,
})
_finalize_run(
run,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
})
-223
View File
@@ -1,223 +0,0 @@
"""
backend/app/api/internal_jobs.py
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
依赖:job_registry、schedule_contract、scheduler_service。
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
from __future__ import annotations
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
)
internal_jobs_bp = Blueprint('internal_jobs', __name__)
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
"""
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
Raises:
ValidationError: 非 platform_job 或 platform_api_path 不匹配
"""
if task.schedule_type != 'platform_job':
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
task_key = normalize_job_key(task.platform_api_path)
if task_key != job_key:
raise ValidationError(
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
f"does not match job key '{job_key}'"
)
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
"""
解析或创建 ScheduleTask / ScheduleRun。
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
run_no 查询限定 schedule_task_id,避免跨任务写入。
"""
schedule_task_id = data.get('schedule_task_id')
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
if task:
_assert_task_matches_job_key(task, job_key)
else:
task = (
ScheduleTask.query.filter(
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
)
.order_by(ScheduleTask.id.desc())
.first()
)
if not task:
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
run_no = str(data.get('run_no') or '').strip()
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
if not run:
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
if foreign and foreign.schedule_task_id != task.id:
raise ValidationError(
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
f"not {task.id}"
)
if not run:
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
return task, run
def _finalize_run(
run: ScheduleRun,
*,
total_count: int,
success_count: int,
failed_count: int,
skipped_count: int,
step_logs: list | None,
) -> None:
"""写入 run 汇总字段并 commit。"""
run.status = (
'success' if failed_count == 0
else 'failed' if success_count == 0
else 'partial_failed'
)
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.finished_at = datetime.utcnow()
if run.started_at and run.finished_at:
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
"""
执行已注册平台 Job。
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
key = normalize_job_key(name)
data = request.get_json(silent=True) or {}
if not get_platform_job(key):
raise NotFoundError(f"Unknown platform job: {name}")
task, run = _resolve_schedule_task_and_run(key, data)
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data,
)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=str(exc),
http_status=500,
details={
'traceback': traceback.format_exc(),
'summary': {
'total_count': 0,
'success_count': 0,
'failed_count': 0,
'skipped_count': 0,
},
},
)
if should_defer_schedule_run_finalization(task, step_logs):
apply_deferred_schedule_run_state(
run,
task,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
details=details,
errors=errors,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
'awaiting_rpa_callback': True,
})
if should_defer_receipt_schedule_run(task, step_logs):
apply_deferred_receipt_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count, 'success_count': success_count,
'failed_count': failed_count, 'skipped_count': skipped_count,
},
'details': details, 'errors': errors, 'step_logs': step_logs,
'awaiting_receipt_rpa_callback': True,
})
_finalize_run(
run,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
})
@@ -1,5 +1,5 @@
"""
backend/app/api/linked_services.py
backend/app/api/linked_services/__init__.py
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
依赖:JWT current-user、linked_service_service。
@@ -1,5 +1,5 @@
"""
backend/app/api/maintenance.py
backend/app/api/maintenance/__init__.py
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
+5 -144
View File
@@ -1,149 +1,10 @@
"""
backend/app/api/maintenance_tools.py
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/maintenance.py)。
依赖:app.api.tools.maintenance。
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
"""
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from sqlalchemy import or_
from app import db
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import MaintenanceRecord
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.maintenance_chat_service import build_device_query_result
from app.services.maintenance_record_service import serialize_record
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
def _require_tool_auth() -> None:
"""
校验设备维保 Tool API 鉴权。
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
"""
configured = str(
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
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 == "VALIDATION.INVALID_PARAM":
return message or "invalid_request"
return exc.code
@maintenance_tool_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""Tool API 统一错误响应。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@maintenance_tool_bp.before_request
def _verify_tool_access():
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
return None
_require_tool_auth()
return None
def _payload() -> dict:
"""读取 JSON 请求体。"""
return request.get_json(silent=True) or {}
def _clean_text(value) -> str:
return str(value or "").strip()
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON。"""
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML。"""
import yaml
body = yaml.safe_dump(
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
allow_unicode=True,
sort_keys=False,
)
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
def query_device():
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
data = _payload()
keyword = _clean_text(data.get("keyword"))
if not keyword:
raise ValidationError("keyword is required")
include_records = bool(data.get("include_records", True))
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
return jsonify({"ok": True, **result})
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
def query_records():
"""按设备编号/名称和状态查询维修记录。"""
data = _payload()
keyword = _clean_text(data.get("keyword"))
if not keyword:
raise ValidationError("keyword is required")
status = _clean_text(data.get("status"))
limit = max(1, min(50, int(data.get("limit") or 10)))
query = db.session.query(MaintenanceRecord)
like = f"%{keyword}%"
query = query.filter(
or_(
MaintenanceRecord.device_code.ilike(like),
MaintenanceRecord.device_name.ilike(like),
)
)
if status:
query = query.filter(MaintenanceRecord.repair_status == status)
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
return jsonify({
"ok": True,
"matched": bool(rows),
"keyword": keyword,
"items": [serialize_record(item) for item in rows],
"totalReturned": len(rows),
})
__all__ = ['maintenance_tool_bp']
+5 -106
View File
@@ -1,111 +1,10 @@
"""
backend/app/api/procurement_contract_tools.py
Purpose: Chat/tool-facing procurement contract review APIs.
Dependencies: procurement_contract services, JWT current user, unified response envelope.
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/procurement_contract.py)。
依赖:app.api.tools.procurement_contract。
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
"""
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
from __future__ import annotations
import io
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.procurement_contract import review_service, template_service
procurement_contract_bp = Blueprint("procurement_contract", __name__)
def _require_user():
"""Return current authenticated user."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _optional_int(value, field: str) -> int | None:
"""Parse optional int payload fields with a ValidationError on bad input."""
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{field} must be integer") from exc
@procurement_contract_bp.route("/templates", methods=["GET"])
def list_enabled_templates():
"""List enabled templates for chat dropdown."""
_require_user()
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews", methods=["POST"])
def start_contract_review():
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
user = _require_user()
data = request.get_json() or {}
contract_asset_no = (data.get("contract_asset_no") or "").strip()
if not contract_asset_no:
raise ValidationError("contract_asset_no is required")
result = review_service.start_review(
user_id=user.id,
review_mode=str(data.get("review_mode") or "compare"),
contract_asset_no=contract_asset_no,
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
contract_type=(data.get("contract_type") or None),
supplier_name=(data.get("supplier_name") or None),
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
)
return ok(result, request_id=getattr(g, "request_id", None), status=202)
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
def get_contract_review(review_no: str):
"""Get a current user's review by review number."""
user = _require_user()
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
def download_my_contract_review_report(review_no: str):
"""Download current user's review report as txt or docx."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
else:
name, data = review_service.read_review_report_bytes(review_no=review_no)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
def download_my_annotated_contract(review_no: str):
"""Download current user's original PDF with anchored risk highlights."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews", methods=["GET"])
def list_my_contract_reviews():
"""List current user's recent procurement contract reviews."""
user = _require_user()
data = review_service.list_reviews(
user_id=user.id,
review_mode=request.args.get("review_mode") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
risk_level=request.args.get("risk_level") or None,
limit=_optional_int(request.args.get("limit"), "limit") or 20,
offset=_optional_int(request.args.get("offset"), "offset") or 0,
)
return ok(data, request_id=getattr(g, "request_id", None))
__all__ = ['procurement_contract_bp']
+8 -404
View File
@@ -1,409 +1,13 @@
"""
api/shipping_notice_tools.py
backend/app/api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
tool_api_url。
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/shipping_notice.py)。
依赖:app.api.tools.shipping_notice。
逻辑:保留 Blueprint 与 `_payload` 等测试符号;新代码请从 app.api.tools 导入。
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request, send_file
from app import db
from app.core.errors import (
AppError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
from app.api.tools.shipping_notice import ( # noqa: F401
_payload,
shipping_notice_bp,
)
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_task_by_ref,
resolve_task_export_download,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
def _require_tool_auth() -> None:
"""
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
"""
configured = str(
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
or current_app.config.get('INTEGRATION_API_KEY')
or ''
).strip()
if not configured:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
code='missing_auth',
)
bearer = str(request.headers.get('Authorization') or '').strip()
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
if configured in {token, integration_key}:
return
if not token and (not integration_key):
raise UnauthorizedError('missing_auth')
raise UnauthorizedError('invalid_auth')
def _tool_error_code(exc: AppError) -> str:
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
message = str(exc.message or '').strip()
if message in {'missing_auth', 'invalid_auth'}:
return message
if exc.code == 'AUTH.UNAUTHORIZED':
return 'invalid_auth'
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
return 'missing_auth'
return exc.code
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
if exc.details:
body['details'] = exc.details
return jsonify(body), exc.http_status
@shipping_notice_bp.before_request
def _verify_tool_access():
"""
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
"""
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
return None
_require_tool_auth()
return None
def _tool_api_base_url() -> str:
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
return resolve_tool_api_base_url()
def _dify_openapi_spec() -> dict:
return build_dify_openapi_spec(_tool_api_base_url())
def _payload() -> dict:
"""
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
"""
raw = request.get_json(silent=True) or {}
if not isinstance(raw, dict):
return {}
payload = dict(raw)
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
payload.pop(key, None)
return payload
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
from app.models import ShippingAuditEvent
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
db.session.add(ShippingAuditEvent(
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
))
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
def tool_create_task():
"""
创建单个发货任务。
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
def tool_create_temporary_inventory_session():
"""
创建对话上传库存候选会话。
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
"""
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
def tool_get_temporary_inventory_session():
"""
读取临时库存候选的脱敏分析结果。
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
"""
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
def tool_submit_temporary_inventory_mapping_suggestion():
"""
保存临时库存字段映射建议。
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
"""
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
def tool_confirm_temporary_inventory_use():
"""
确认本次对话临时库存文件的使用。
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
"""
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
def tool_update_notice_fields():
"""
修改发货通知单头字段。
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
"""
return jsonify(shipping_tools.update_notice_fields(_payload()))
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
def tool_update_notice_line():
"""
修改指定订单行。
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
"""
return jsonify(shipping_tools.update_notice_line(_payload()))
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
def tool_add_notice_line():
"""
新增订单行。
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
"""
return jsonify(shipping_tools.add_notice_line(_payload()))
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
def tool_remove_notice_line():
"""
删除订单行。
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_ensure_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_preparation',
))
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
def tool_auto_progress():
"""
自动推进任务。
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
def tool_match_inventory():
"""
执行库存匹配。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_match_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_matching',
))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
def tool_confirm_customer():
"""
确认任务所属标准客户(仅提交 customer_id)。
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
"""
return jsonify(shipping_tools.confirm_customer(_payload()))
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_generate_excel',
operator_id=payload.get('operator_id'),
resume_gate_code='artifact_generation',
))
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
def tool_get_task_status():
"""
查询任务状态。
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
"""
payload = _payload()
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
return jsonify(shipping_tools.get_task_status(payload))
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
"""
RPA Worker 心跳上报。
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
"""
payload = _payload()
try:
worker = record_rpa_worker_heartbeat(payload)
except ValueError as exc:
raise ValidationError(str(exc))
except ServiceUnavailableError:
raise
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
def rpa_receipt_batch_ready():
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
def rpa_inventory_batch_claimed():
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
def rpa_inventory_batch_progress():
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
return jsonify(report_inventory_batch_progress(_payload()))
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
def rpa_inventory_configuration_test_batch_ready():
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
def rpa_inventory_configuration_test_batch_progress():
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
def repair_task_inventory_attachment(task_no: str):
"""
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
"""
payload = _payload()
payload.setdefault("task_no", task_no)
payload.setdefault("task_id", task_no)
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
def rpa_inventory_repair():
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
payload = _payload()
payload['repair'] = True
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
def download_task_export(task_no: str):
"""下载任务已生成的出货 Excel。"""
task = get_task_by_ref(task_no)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
__all__ = ['shipping_notice_bp', '_payload']
@@ -1,6 +1,11 @@
"""
Speech transcription API — forwards audio to SiliconFlow ASR.
backend/app/api/speech/__init__.py
用途:语音转写 API,将音频转发至 SiliconFlow ASR。
依赖:app.core.auth.jwt、SpeechAsrService。
逻辑:register_blueprints 挂载 /api/speech;需登录后上传 audio/file。
"""
from flask import Blueprint, jsonify, request
from app.core.auth.jwt import get_current_user
@@ -1,5 +1,5 @@
"""
backend/app/api/sso.py
backend/app/api/sso/__init__.py
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
+13 -4
View File
@@ -1,11 +1,20 @@
"""
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:re-export shipping_notice、file_check、maintenance tools。
用途:Dify / Chatflow HTTP Tool API Blueprint 聚合。
依赖:tools 子模块(file_check、shipping_notice、maintenance、agent_runtime_context、procurement_contract)。
逻辑:register_blueprints 只从本包导入 Tool Blueprint;真实现已收口到本目录,根路径 *_tools.py 仅为兼容 shim。
"""
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
from app.api.tools.agent_runtime_context import agent_runtime_context_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.procurement_contract import procurement_contract_bp # noqa: F401
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp']
__all__ = [
'agent_runtime_context_bp',
'file_check_bp',
'maintenance_tool_bp',
'procurement_contract_bp',
'shipping_notice_bp',
]
@@ -0,0 +1,108 @@
"""
backend/app/api/tools/agent_runtime_context.py
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
逻辑:register_blueprints 从 api.tools 挂载;OpenAPI 文档接口放行;parse 工具复用
Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
def _require_tool_auth() -> None:
"""
校验 agent_runtime_context Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
Raises:
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
UnauthorizedError: 缺少或传入错误鉴权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""
归一化 Tool API 错误码。
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
Args:
exc: 业务异常。
Returns:
Tool 侧错误码。
"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
return exc.code
@agent_runtime_context_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@agent_runtime_context_bp.before_request
def _verify_tool_access():
"""
对上下文解析 Tool 做统一 Header 鉴权。
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
"""
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
def parse_context_tool():
"""
解析 agent_runtime_context 的白名单字段。
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
不用于推进业务状态。
"""
payload = request.get_json(silent=True) or {}
return jsonify(
parse_agent_runtime_context(
payload.get("agent_runtime_context"),
payload.get("paths"),
)
)
+652 -3
View File
@@ -1,8 +1,657 @@
"""
backend/app/api/tools/file_check.py
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace.file_check、services.file_check_tools、schedule.scheduler_service、jobs.enqueue。
逻辑:register_blueprints 从 api.tools 挂载;发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
"""
from app.api.file_check_tools import file_check_bp # noqa: F401
from __future__ import annotations
__all__ = ['file_check_bp']
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.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()))
+145 -4
View File
@@ -1,9 +1,150 @@
"""
backend/app/api/tools/maintenance.py
用途:设备维保 Tool API Blueprint re-export。
依赖:app.api.maintenance_tools。
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
逻辑:register_blueprints 从 api.tools 挂载;Dify 复杂问法调用本蓝图查询设备台账/维修记录;
明确查询仍由 chat 本地直答,写操作仍走 HXOPS 管理面板。
"""
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from sqlalchemy import or_
from app import db
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import MaintenanceRecord
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.maintenance_chat_service import build_device_query_result
from app.services.maintenance_record_service import serialize_record
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
def _require_tool_auth() -> None:
"""
校验设备维保 Tool API 鉴权。
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
"""
configured = str(
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
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 == "VALIDATION.INVALID_PARAM":
return message or "invalid_request"
return exc.code
@maintenance_tool_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""Tool API 统一错误响应。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@maintenance_tool_bp.before_request
def _verify_tool_access():
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
return None
_require_tool_auth()
return None
def _payload() -> dict:
"""读取 JSON 请求体。"""
return request.get_json(silent=True) or {}
def _clean_text(value) -> str:
return str(value or "").strip()
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON。"""
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML。"""
import yaml
body = yaml.safe_dump(
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
allow_unicode=True,
sort_keys=False,
)
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
def query_device():
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
data = _payload()
keyword = _clean_text(data.get("keyword"))
if not keyword:
raise ValidationError("keyword is required")
include_records = bool(data.get("include_records", True))
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
return jsonify({"ok": True, **result})
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
def query_records():
"""按设备编号/名称和状态查询维修记录。"""
data = _payload()
keyword = _clean_text(data.get("keyword"))
if not keyword:
raise ValidationError("keyword is required")
status = _clean_text(data.get("status"))
limit = max(1, min(50, int(data.get("limit") or 10)))
query = db.session.query(MaintenanceRecord)
like = f"%{keyword}%"
query = query.filter(
or_(
MaintenanceRecord.device_code.ilike(like),
MaintenanceRecord.device_name.ilike(like),
)
)
if status:
query = query.filter(MaintenanceRecord.repair_status == status)
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
return jsonify({
"ok": True,
"matched": bool(rows),
"keyword": keyword,
"items": [serialize_record(item) for item in rows],
"totalReturned": len(rows),
})
@@ -0,0 +1,111 @@
"""
backend/app/api/tools/procurement_contract.py
用途:采购合同审核面向 Chat/Tool 的 HTTP API。
依赖:procurement_contract services、JWT 当前用户、统一 response envelope。
逻辑:register_blueprints 从 api.tools 挂载;已登录用户可上传对照文件、发起审核、查本人历史并下载本人报告。
"""
from __future__ import annotations
import io
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.procurement_contract import review_service, template_service
procurement_contract_bp = Blueprint("procurement_contract", __name__)
def _require_user():
"""Return current authenticated user."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _optional_int(value, field: str) -> int | None:
"""Parse optional int payload fields with a ValidationError on bad input."""
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{field} must be integer") from exc
@procurement_contract_bp.route("/templates", methods=["GET"])
def list_enabled_templates():
"""List enabled templates for chat dropdown."""
_require_user()
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews", methods=["POST"])
def start_contract_review():
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
user = _require_user()
data = request.get_json() or {}
contract_asset_no = (data.get("contract_asset_no") or "").strip()
if not contract_asset_no:
raise ValidationError("contract_asset_no is required")
result = review_service.start_review(
user_id=user.id,
review_mode=str(data.get("review_mode") or "compare"),
contract_asset_no=contract_asset_no,
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
contract_type=(data.get("contract_type") or None),
supplier_name=(data.get("supplier_name") or None),
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
)
return ok(result, request_id=getattr(g, "request_id", None), status=202)
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
def get_contract_review(review_no: str):
"""Get a current user's review by review number."""
user = _require_user()
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
def download_my_contract_review_report(review_no: str):
"""Download current user's review report as txt or docx."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
else:
name, data = review_service.read_review_report_bytes(review_no=review_no)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
def download_my_annotated_contract(review_no: str):
"""Download current user's original PDF with anchored risk highlights."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews", methods=["GET"])
def list_my_contract_reviews():
"""List current user's recent procurement contract reviews."""
user = _require_user()
data = review_service.list_reviews(
user_id=user.id,
review_mode=request.args.get("review_mode") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
risk_level=request.args.get("risk_level") or None,
limit=_optional_int(request.args.get("limit"), "limit") or 20,
offset=_optional_int(request.args.get("offset"), "offset") or 0,
)
return ok(data, request_id=getattr(g, "request_id", None))
+403 -3
View File
@@ -1,8 +1,408 @@
"""
backend/app/api/tools/shipping_notice.py
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
"""
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
from __future__ import annotations
__all__ = ['shipping_notice_bp']
from flask import Blueprint, current_app, jsonify, request, send_file
from app import db
from app.core.errors import (
AppError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
)
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_task_by_ref,
resolve_task_export_download,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
def _require_tool_auth() -> None:
"""
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
"""
configured = str(
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
or current_app.config.get('INTEGRATION_API_KEY')
or ''
).strip()
if not configured:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
code='missing_auth',
)
bearer = str(request.headers.get('Authorization') or '').strip()
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
if configured in {token, integration_key}:
return
if not token and (not integration_key):
raise UnauthorizedError('missing_auth')
raise UnauthorizedError('invalid_auth')
def _tool_error_code(exc: AppError) -> str:
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
message = str(exc.message or '').strip()
if message in {'missing_auth', 'invalid_auth'}:
return message
if exc.code == 'AUTH.UNAUTHORIZED':
return 'invalid_auth'
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
return 'missing_auth'
return exc.code
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
if exc.details:
body['details'] = exc.details
return jsonify(body), exc.http_status
@shipping_notice_bp.before_request
def _verify_tool_access():
"""
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
"""
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
return None
_require_tool_auth()
return None
def _tool_api_base_url() -> str:
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
return resolve_tool_api_base_url()
def _dify_openapi_spec() -> dict:
return build_dify_openapi_spec(_tool_api_base_url())
def _payload() -> dict:
"""
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
"""
raw = request.get_json(silent=True) or {}
if not isinstance(raw, dict):
return {}
payload = dict(raw)
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
payload.pop(key, None)
return payload
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
from app.models import ShippingAuditEvent
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
db.session.add(ShippingAuditEvent(
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
))
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
def tool_create_task():
"""
创建单个发货任务。
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
def tool_create_temporary_inventory_session():
"""
创建对话上传库存候选会话。
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
"""
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
def tool_get_temporary_inventory_session():
"""
读取临时库存候选的脱敏分析结果。
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
"""
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
def tool_submit_temporary_inventory_mapping_suggestion():
"""
保存临时库存字段映射建议。
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
"""
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
def tool_confirm_temporary_inventory_use():
"""
确认本次对话临时库存文件的使用。
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
"""
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
def tool_update_notice_fields():
"""
修改发货通知单头字段。
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
"""
return jsonify(shipping_tools.update_notice_fields(_payload()))
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
def tool_update_notice_line():
"""
修改指定订单行。
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
"""
return jsonify(shipping_tools.update_notice_line(_payload()))
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
def tool_add_notice_line():
"""
新增订单行。
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
"""
return jsonify(shipping_tools.add_notice_line(_payload()))
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
def tool_remove_notice_line():
"""
删除订单行。
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_ensure_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_preparation',
))
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
def tool_auto_progress():
"""
自动推进任务。
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
def tool_match_inventory():
"""
执行库存匹配。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_match_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_matching',
))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
def tool_confirm_customer():
"""
确认任务所属标准客户(仅提交 customer_id)。
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
"""
return jsonify(shipping_tools.confirm_customer(_payload()))
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_generate_excel',
operator_id=payload.get('operator_id'),
resume_gate_code='artifact_generation',
))
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
def tool_get_task_status():
"""
查询任务状态。
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
"""
payload = _payload()
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
return jsonify(shipping_tools.get_task_status(payload))
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
"""
RPA Worker 心跳上报。
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
"""
payload = _payload()
try:
worker = record_rpa_worker_heartbeat(payload)
except ValueError as exc:
raise ValidationError(str(exc))
except ServiceUnavailableError:
raise
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
def rpa_receipt_batch_ready():
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
def rpa_inventory_batch_claimed():
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
def rpa_inventory_batch_progress():
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
return jsonify(report_inventory_batch_progress(_payload()))
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
def rpa_inventory_configuration_test_batch_ready():
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
def rpa_inventory_configuration_test_batch_progress():
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
def repair_task_inventory_attachment(task_no: str):
"""
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
"""
payload = _payload()
payload.setdefault("task_no", task_no)
payload.setdefault("task_id", task_no)
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
def rpa_inventory_repair():
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
payload = _payload()
payload['repair'] = True
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
def download_task_export(task_no: str):
"""下载任务已生成的出货 Excel。"""
task = get_task_by_ref(task_no)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@@ -1,5 +1,5 @@
"""
backend/app/api/training.py
backend/app/api/training/__init__.py
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
-18
View File
@@ -1,18 +0,0 @@
"""
backend/app/api/workspace_file_check.py
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
依赖:app.api.workspace.file_check。
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
"""
from app.api.workspace.file_check import (
serialize_current_step,
serialize_file_judgement,
workspace_file_check_bp,
)
__all__ = [
'serialize_current_step',
'serialize_file_judgement',
'workspace_file_check_bp',
]