feat(file-check): 增加文件检核 Excel 下载链接解析与展示功能
This commit is contained in:
1 parent
5e7e5a8717
commit
f21216f81e
21 files changed
+885
-125
No files matched your search
@@ -56,8 +56,10 @@ MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
|
||||
|
||||
|
||||
@@ -58,8 +58,10 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
# SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
|
||||
|
||||
+3
-1
@@ -80,8 +80,10 @@ WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
|
||||
@@ -1002,7 +1002,7 @@ def get_chat_messages():
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
|
||||
@@ -27,13 +27,19 @@ from app.core.errors import (
|
||||
)
|
||||
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
|
||||
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, run_task_now
|
||||
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"}
|
||||
@@ -41,13 +47,13 @@ _RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
).strip()
|
||||
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:
|
||||
@@ -57,7 +63,7 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
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)
|
||||
@@ -65,6 +71,20 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
"""
|
||||
# [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 服务端调用
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
@@ -77,13 +97,11 @@ def _require_tool_auth() -> None:
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
||||
return
|
||||
if not token and not integration_key:
|
||||
if not api_token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
@@ -104,6 +122,8 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
"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():
|
||||
@@ -128,7 +148,8 @@ def _handle_tool_app_error(exc: AppError):
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
@@ -148,7 +169,7 @@ def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@@ -309,12 +330,30 @@ def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
@@ -323,12 +362,19 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
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()
|
||||
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
|
||||
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
|
||||
@@ -119,9 +119,12 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
|
||||
@@ -134,6 +134,98 @@ class DifyService:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _merge_stream_answer_text(
|
||||
streamed_text: str,
|
||||
terminal_answer: str | None,
|
||||
*,
|
||||
replace_answer: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
合并流式增量文本与终态 answer,避免 Dify 结束事件重复携带整段正文导致落库翻倍。
|
||||
核心逻辑:与前端 useChat.ts 终态事件去重策略保持一致。
|
||||
|
||||
Args:
|
||||
streamed_text: message 事件累积的增量文本。
|
||||
terminal_answer: message_end / workflow_finished 携带的 answer。
|
||||
replace_answer: 为 True 时仅使用终态 answer。
|
||||
|
||||
Returns:
|
||||
去重后的最终正文。
|
||||
"""
|
||||
current_content = str(streamed_text or '')
|
||||
terminal = str(terminal_answer or '')
|
||||
|
||||
if replace_answer and terminal.strip():
|
||||
return terminal.strip()
|
||||
if not terminal:
|
||||
return current_content.strip()
|
||||
if not current_content.strip():
|
||||
return terminal.strip()
|
||||
|
||||
current_stripped = current_content.strip()
|
||||
terminal_stripped = terminal.strip()
|
||||
if (
|
||||
terminal_stripped
|
||||
and current_stripped
|
||||
and len(terminal_stripped) >= len(current_stripped)
|
||||
and current_stripped in terminal_stripped
|
||||
):
|
||||
return terminal_stripped
|
||||
if terminal_stripped and current_stripped and terminal_stripped in current_stripped:
|
||||
return current_stripped
|
||||
return (current_content + terminal).strip()
|
||||
|
||||
@staticmethod
|
||||
def _build_final_answer_text(
|
||||
*,
|
||||
streamed_parts: list[str],
|
||||
data: dict,
|
||||
event_name: str,
|
||||
) -> str:
|
||||
"""
|
||||
根据流式片段与终态事件组装最终落库 answer。
|
||||
核心逻辑:先走 _merge_stream_answer_text 去重;workflow_finished 无 answer 时回退 outputs。
|
||||
"""
|
||||
streamed_text = ''.join(streamed_parts)
|
||||
terminal = str(data.get('answer') or '') if data.get('answer') else ''
|
||||
answer_text = DifyService._merge_stream_answer_text(
|
||||
streamed_text,
|
||||
terminal or None,
|
||||
replace_answer=bool(data.get('replace_answer')),
|
||||
)
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
|
||||
@staticmethod
|
||||
def _dedupe_exact_doubled_text(text: str) -> str:
|
||||
"""
|
||||
修复历史落库时将同一段正文原样拼接两次的记录。
|
||||
核心逻辑:仅当整段文本可被均分为两段完全相同子串时才裁剪。
|
||||
"""
|
||||
normalized = str(text or '')
|
||||
stripped = normalized.strip()
|
||||
if len(stripped) < 2:
|
||||
return normalized
|
||||
half = len(stripped) // 2
|
||||
if len(stripped) % 2 == 0 and stripped[:half] == stripped[half:]:
|
||||
return stripped[:half]
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not isinstance(data, dict):
|
||||
@@ -896,25 +988,11 @@ class DifyService:
|
||||
return result
|
||||
|
||||
def build_final_answer_text(data: dict, event_name: str) -> str:
|
||||
answer_text = ''.join(full_answer).strip()
|
||||
if data.get('answer'):
|
||||
answer_text = (answer_text + str(data.get('answer') or '')).strip()
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
return DifyService._build_final_answer_text(
|
||||
streamed_parts=full_answer,
|
||||
data=data,
|
||||
event_name=event_name,
|
||||
)
|
||||
|
||||
|
||||
max_retries = 3
|
||||
|
||||
@@ -108,6 +108,9 @@
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/DataSourceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -533,7 +536,8 @@
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
"example": 12,
|
||||
"description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
|
||||
},
|
||||
"trigger_source": {
|
||||
"type": "string",
|
||||
@@ -561,7 +565,7 @@
|
||||
"required": [
|
||||
"task_id"
|
||||
],
|
||||
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
@@ -887,6 +891,21 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"DataSourceUnavailable": {
|
||||
"description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "data_source_unavailable",
|
||||
"message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,42 @@
|
||||
"""
|
||||
backend/app/services/hxops_tool_api.py
|
||||
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
|
||||
|
||||
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
|
||||
依赖:Flask current_app / request。
|
||||
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
|
||||
|
||||
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
|
||||
cfg = config
|
||||
if cfg is None and current_app:
|
||||
cfg = current_app.config
|
||||
cfg = cfg or {}
|
||||
def _resolve_config(config: dict | None = None) -> dict:
|
||||
"""读取 Flask config 或空 dict。"""
|
||||
if config is not None:
|
||||
return config
|
||||
if current_app:
|
||||
return current_app.config
|
||||
return {}
|
||||
|
||||
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
|
||||
configured = str(cfg.get(key) or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""
|
||||
返回 Dify / RPA 等服务端调用 Tool API 时使用的根地址(无尾斜杠)。
|
||||
|
||||
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
|
||||
|
||||
Args:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
|
||||
|
||||
Returns:
|
||||
无尾斜杠的根地址,如 http://192.168.100.192:8890。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
|
||||
configured = str(cfg.get("HXOPS_TOOLS_API_BASE") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
@@ -25,3 +44,26 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
|
||||
return host or ""
|
||||
|
||||
|
||||
def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
|
||||
"""
|
||||
返回浏览器侧可访问的根地址,用于 Excel 签名下载等用户可见链接。
|
||||
|
||||
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
|
||||
|
||||
Args:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
|
||||
Returns:
|
||||
无尾斜杠的根地址,如 https://ai.example.com。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
|
||||
for key in ("HXOPS_PUBLIC_BASE_URL", "WECOM_PUBLIC_BASE_URL"):
|
||||
configured = str(cfg.get(key) or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
|
||||
@@ -271,3 +271,40 @@ def test_file_check_evaluate_exception_includes_error_type(monkeypatch):
|
||||
assert payload["error_type"] == "http_403"
|
||||
assert payload["retryable"] is False
|
||||
assert payload["poll_used"] is False
|
||||
|
||||
|
||||
def test_merge_stream_answer_text_replaces_when_terminal_contains_streamed():
|
||||
streamed = "检核完成,共处理 3 个文件,全部成功。"
|
||||
terminal = streamed
|
||||
merged = DifyService._merge_stream_answer_text(streamed, terminal)
|
||||
assert merged == streamed
|
||||
assert merged != streamed + terminal
|
||||
|
||||
|
||||
def test_merge_stream_answer_text_honors_replace_answer_flag():
|
||||
streamed = "partial"
|
||||
terminal = "final answer"
|
||||
merged = DifyService._merge_stream_answer_text(streamed, terminal, replace_answer=True)
|
||||
assert merged == "final answer"
|
||||
|
||||
|
||||
def test_merge_stream_answer_text_appends_non_overlapping_suffix():
|
||||
merged = DifyService._merge_stream_answer_text("Hello", " world")
|
||||
assert merged == "Hello world"
|
||||
|
||||
|
||||
def test_build_final_answer_text_dedupes_message_end_payload():
|
||||
streamed_parts = ["检核", "完成。"]
|
||||
data = {"answer": "检核完成。"}
|
||||
result = DifyService._build_final_answer_text(
|
||||
streamed_parts=streamed_parts,
|
||||
data=data,
|
||||
event_name="message_end",
|
||||
)
|
||||
assert result == "检核完成。"
|
||||
|
||||
|
||||
def test_dedupe_exact_doubled_text_fixes_historical_records():
|
||||
doubled = "检核完成,共处理 3 个文件。" * 2
|
||||
assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。"
|
||||
assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer"
|
||||
@@ -503,6 +503,14 @@ def test_file_check_tool_requires_task_id(app, client):
|
||||
assert res.status_code == 400
|
||||
assert res.get_json()['error_code'] == 'task_id_required'
|
||||
|
||||
res_null = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': None},
|
||||
)
|
||||
assert res_null.status_code == 400
|
||||
assert res_null.get_json()['error_code'] == 'task_id_required'
|
||||
|
||||
|
||||
def test_file_check_tool_rejects_invalid_task_id(app, client):
|
||||
with app.app_context():
|
||||
@@ -517,6 +525,77 @@ def test_file_check_tool_rejects_invalid_task_id(app, client):
|
||||
assert res.get_json()['error_code'] == 'task_id_invalid'
|
||||
|
||||
|
||||
def test_file_check_tool_precheck_data_source_unavailable_on_runtime_error(app, client, monkeypatch):
|
||||
"""预检连接串构建失败时返回 503 data_source_unavailable,而非 500。"""
|
||||
class _SqlConfig:
|
||||
fetch_sql = 'SELECT 1'
|
||||
data_source = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
|
||||
lambda _task_id: _SqlConfig(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.api.file_check_tools._build_srm_conn_str',
|
||||
lambda: (_ for _ in ()).throw(RuntimeError('SRM_SQLSERVER_HOST is not configured')),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task_id = _mk_check_task(admin.id).id
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
|
||||
)
|
||||
assert res.status_code == 503
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'data_source_unavailable'
|
||||
assert '数据源不可用' in data['message']
|
||||
|
||||
|
||||
def test_file_check_tool_precheck_data_source_unavailable_on_pyodbc_error(app, client, monkeypatch):
|
||||
"""预检 ODBC 连接失败时返回 503 data_source_unavailable。"""
|
||||
pyodbc = pytest.importorskip('pyodbc')
|
||||
|
||||
class _SqlConfig:
|
||||
fetch_sql = 'SELECT 1'
|
||||
data_source = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
|
||||
lambda _task_id: _SqlConfig(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.api.file_check_tools._build_srm_conn_str',
|
||||
lambda: 'DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=test;UID=u;PWD=p',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.api.file_check_tools._fetch_records',
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(pyodbc.InterfaceError('IM002', 'driver not found')),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task_id = _mk_check_task(admin.id).id
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
|
||||
)
|
||||
assert res.status_code == 503
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'data_source_unavailable'
|
||||
|
||||
|
||||
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
|
||||
class _Thread:
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -921,6 +1000,94 @@ def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
|
||||
assert res.get_json()['run'] is None
|
||||
|
||||
|
||||
def test_file_check_tool_excel_download_uses_user_facing_base_url(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
app.config['HXOPS_TOOLS_API_BASE'] = 'http://192.168.100.230:8890'
|
||||
app.config['HXOPS_PUBLIC_BASE_URL'] = 'http://ai.well-trust.com:8890'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-EXCEL-DOMAIN',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='manual',
|
||||
excel_file_name='result.xlsx',
|
||||
excel_file_data=b'xlsx-bytes',
|
||||
excel_file_size=10,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
|
||||
download_url = query_res.get_json()['run']['excel']['download_url']
|
||||
assert download_url.startswith('http://ai.well-trust.com:8890/api/file-check/tools/runs/')
|
||||
assert '192.168.100.230' not in download_url
|
||||
|
||||
|
||||
def test_file_check_tool_excel_download_works_without_tool_api_key(app, client):
|
||||
"""浏览器 Excel 下载仅依赖 JWT,不应要求 INTEGRATION_API_KEY 已配置。"""
|
||||
with app.app_context():
|
||||
app.config['FILE_CHECK_TOOL_API_KEY'] = ''
|
||||
app.config['INTEGRATION_API_KEY'] = ''
|
||||
app.config['SECRET_KEY'] = 'download-signing-secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-EXCEL-NO-KEY',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='manual',
|
||||
excel_file_name='result.xlsx',
|
||||
excel_file_data=b'xlsx-bytes',
|
||||
excel_file_size=10,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
query_res = client.get(f'/api/file-check/tools/runs/{run_id}')
|
||||
assert query_res.status_code == 503
|
||||
|
||||
with app.app_context():
|
||||
run = db.session.get(ScheduleRun, run_id)
|
||||
from app.api.file_check_tools import _build_excel_download_url
|
||||
|
||||
download_url = _build_excel_download_url(run)
|
||||
download_path = download_url[download_url.index('/api/file-check'):]
|
||||
|
||||
res = client.get(download_path)
|
||||
assert res.status_code == 200
|
||||
assert res.data == b'xlsx-bytes'
|
||||
|
||||
|
||||
def test_file_check_tool_excel_download_invalid_token_returns_invalid_auth(app, client):
|
||||
with app.app_context():
|
||||
app.config['SECRET_KEY'] = 'download-signing-secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-EXCEL-BAD-TOKEN',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='manual',
|
||||
excel_file_name='result.xlsx',
|
||||
excel_file_data=b'xlsx-bytes',
|
||||
excel_file_size=10,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
res = client.get(f'/api/file-check/tools/runs/{run_id}/excel?token=not-a-valid-token')
|
||||
assert res.status_code == 401
|
||||
assert res.get_json()['error_code'] == 'invalid_auth'
|
||||
|
||||
|
||||
def test_file_check_tool_excel_download_uses_signed_token(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -69,9 +70,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
|
||||
|
||||
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
|
||||
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件。"""
|
||||
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
log_path = tmp_path / "logs" / "worker.log"
|
||||
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
|
||||
original_stdout = sys.stdout
|
||||
@@ -91,10 +93,16 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
|
||||
assert resolved == log_path
|
||||
assert "hello stdout" in captured.out
|
||||
assert "hello stderr" in captured.err
|
||||
assert timestamp_pattern.search(captured.out)
|
||||
assert timestamp_pattern.search(captured.err)
|
||||
text = log_path.read_text(encoding="utf-8")
|
||||
assert "[logging] tee enabled" in text
|
||||
assert "hello stdout" in text
|
||||
assert "hello stderr" in text
|
||||
# 断言:每行非空日志均带 YYYY-MM-DD HH:MM:SS 前缀,便于长批次排障。
|
||||
for line in text.splitlines():
|
||||
if line.strip():
|
||||
assert timestamp_pattern.match(line)
|
||||
|
||||
|
||||
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
|
||||
|
||||
@@ -122,6 +122,11 @@ def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows
|
||||
|
||||
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False
|
||||
frame.evaluate.assert_called_once()
|
||||
probe_js = frame.evaluate.call_args.args[0]
|
||||
assert "#Report_table" in probe_js
|
||||
assert "ReportViewerMain_ctl08" in probe_js
|
||||
assert "directBodyRows" in probe_js
|
||||
assert "isWarehouseCodeOnly" in probe_js
|
||||
|
||||
|
||||
def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch):
|
||||
@@ -133,6 +138,8 @@ def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monk
|
||||
|
||||
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True
|
||||
frame.evaluate.assert_called_once()
|
||||
probe_js = frame.evaluate.call_args.args[0]
|
||||
assert "isInventoryDetailRow" in probe_js
|
||||
|
||||
|
||||
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
|
||||
|
||||
@@ -901,8 +901,8 @@ flask db current # 应包含 e2f3a4b5c6d7
|
||||
| 1 | Start(`用户输入`)**删除** `task_id`、`hxops_turn_id` 等 HXOPS 业务变量 |
|
||||
| 2 | Start **新增/保留** `agent_runtime_context`(Paragraph / Long Text);`query` 继续绑定 `sys.query` |
|
||||
| 3 | Start 与 LLM 之间 **新增** [§3.1A Code:解析运行态上下文](#31a-code解析运行态上下文) |
|
||||
| 4 | 原引用 `用户输入.task_id` 的节点改为 `解析运行态上下文.task_id` |
|
||||
| 5 | RUN_FILE_CHECK(§3.8)入参绑定 `解析运行态上下文.task_id` 与 `解析运行态上下文.hxops_turn_id` |
|
||||
| 4 | 原引用 `用户输入.task_id` 的 **Tool** 节点改为 `解析运行态上下文.task_id_int`(Number);**LLM / Code** 改为 `解析运行态上下文.task_id`(String) |
|
||||
| 5 | RUN_FILE_CHECK(§3.8)入参:`task_id` → `解析运行态上下文.task_id_int`;`hxops_turn_id` → `解析运行态上下文.hxops_turn_id` |
|
||||
| 6 | (可选)导入 `docs/openapi/agent_runtime_context_tools.dify.json`,用 Tool `parse_agent_runtime_context` 替代 Code 节点 |
|
||||
| 7 | Dify 直连调试时,Start 的 `agent_runtime_context` 手工填含 `refs` 的 JSON(见 §3.1A 示例) |
|
||||
|
||||
@@ -1209,10 +1209,22 @@ Layer 2 — 成功出口 → Code(仅 HTTP 200 且 JSON 已到)
|
||||
| --- | --- |
|
||||
| **String** | 文本、JSON 字符串(`run_json` / `runs_json`)、ID、错误码 |
|
||||
| **Boolean** | `ok`、各类是否判断 |
|
||||
| **Number** | `confidence`(意图识别) |
|
||||
| **Number** | `confidence`(意图识别)、`task_id_int`(检核任务 ID 整数,**Tool API 专用**) |
|
||||
| **Secret** | 历史 HTTP 方案曾在 Start 使用 `hxops_tool_api_token`;**当前 Tool 方案由 OpenAPI 工具 Credential 托管,Start 勿配** |
|
||||
| **Array[Object]** | Tool 节点 `json` 出参;历史检索 Tool 响应(§3.25) |
|
||||
|
||||
#### 3.0.0 `task_id` 类型约定(最终版,勿混用)
|
||||
|
||||
| 层级 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **HXOPS 后端**(`ScheduleTask.id`、`bound_schedule_task_id`、`chat_tool_runs.schedule_task_id`) | **integer** | 数据库与 API 内部一律整型 |
|
||||
| **OpenAPI Tool API**(`run_file_check`、`get_latest_file_check_run`、`list_file_check_runs`、`search_file_check_history` 等) | **integer** | `docs/openapi/file_check_tools_openapi.json` 中 `task_id` 均为 `integer` |
|
||||
| **Dify `解析运行态上下文` 出参** | `task_id_int` · **Number**;`task_id` · String | Tool 节点 Integer 参数 **只绑 `task_id_int`**;LLM Prompt / Code 文本逻辑用 `task_id` 字符串 |
|
||||
| **Dify `提取查询参数` 出参** | 同上 | 查询分支 Tool 绑 `提取查询参数.task_id_int` |
|
||||
| **Dify Start / 意图识别** | **勿用** | 不在 Start 配顶层 `task_id`;`意图识别.task_id` 常为空,禁止绑 Tool |
|
||||
|
||||
> `agent_runtime_context.refs.schedule_task_id` 在 JSON 中可能是字符串 `"3"` 或数字 `3`,§3.1A Code 负责归一化为 `task_id_int=3`。
|
||||
|
||||
#### 3.0.1 Code 节点入参 / 出参总表
|
||||
|
||||
**Tool 响应解析共用 helper**(各 Code 节点可复制到 `main` 上方):
|
||||
@@ -1241,7 +1253,7 @@ def _load_tool_json(tool_json, tool_text):
|
||||
| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) |
|
||||
| --- | --- | --- |
|
||||
| `解析启动检核响应` | `tool_json` · **Array[Object]** 或 **Object** · 是 · `Tool:启动检核.json`;`tool_text` · **String** · 否 · 同上 `.text` | `ok` · **Boolean**;`error_code` / `message` / `run_id` / `run_no` / `run_status` / `task_name` / `started_at` · **String** |
|
||||
| `提取查询参数` | `user_query` / `intent_run_id` / `intent_task_id` / `task_id` · **String** · `user_query` 与 `task_id` 是,其余否 · 见 §3.14 | `query_mode` · **String** · `by_run_id`/`latest_by_task`/`all_runs`/`missing`;`run_id` / `task_id` · **String** |
|
||||
| `提取查询参数` | `user_query` / `intent_run_id` / `intent_task_id` / `task_id` · **String** · `user_query` 与 `task_id` 是,其余否 · 见 §3.14 | `query_mode` · **String**;`run_id` / `task_id` · **String**;`task_id_int` · **Number**(Tool 绑此字段) |
|
||||
| `解析指定检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询指定检核.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` · **String**;`run_json` · **String** |
|
||||
| `解析最近检核查询响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询最近检核.json` / `.text` | 同上 |
|
||||
| `解析所有检核批次响应` | `tool_json` / `tool_text` · 是/否 · `Tool:查询所有检核批次.json` / `.text` | `ok` · **Boolean**;`error_code` / `message` / `runs_json` / `count` · **String** |
|
||||
@@ -1284,7 +1296,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
|
||||
|
||||
| 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) |
|
||||
| --- | --- | --- |
|
||||
| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `解析运行态上下文.task_id`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** |
|
||||
| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `解析运行态上下文.task_id_int`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** |
|
||||
| `解析历史检索响应` | `tool_json` · **Object** · 是 · `检索历史检核报告.json`;`tool_text` · **String** · 否 | `count` · **Number**;`segments_text` · **String** |
|
||||
| `生成历史报告回答` | Prompt · `用户输入.query`;`解析历史检索响应.segments_text` | `text` · **String** |
|
||||
|
||||
@@ -1352,7 +1364,8 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
|
||||
|
||||
| 输出名 | Dify 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `task_id` | String | 检核任务 ID(`ScheduleTask.id`),供下游 Tool / LLM 复用 |
|
||||
| `task_id` | String | 检核任务 ID 字符串,供 LLM Prompt / Code 节点复用 |
|
||||
| `task_id_int` | **Number** | 与 `task_id` 同值整数;**所有 OpenAPI Tool 的 Integer task_id 参数绑此字段** |
|
||||
| `schedule_task_id` | String | 与 `task_id` 相同,显式命名便于对照平台协议 |
|
||||
| `hxops_turn_id` | String | 本轮对话唯一标识;RUN_FILE_CHECK **必须**回传 |
|
||||
|
||||
@@ -1374,11 +1387,20 @@ def main(agent_runtime_context: str) -> dict:
|
||||
pass
|
||||
|
||||
refs = ctx.get("refs") if isinstance(ctx.get("refs"), dict) else {}
|
||||
schedule_task_id = str(refs.get("schedule_task_id") or "").strip()
|
||||
raw_task_id = refs.get("schedule_task_id")
|
||||
schedule_task_id = str(raw_task_id or "").strip()
|
||||
hxops_turn_id = str(refs.get("hxops_turn_id") or "").strip()
|
||||
|
||||
task_id_int = None
|
||||
try:
|
||||
if raw_task_id is not None and str(raw_task_id).strip() != "":
|
||||
task_id_int = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
task_id_int = None
|
||||
|
||||
return {
|
||||
"task_id": schedule_task_id,
|
||||
"task_id_int": task_id_int,
|
||||
"schedule_task_id": schedule_task_id,
|
||||
"hxops_turn_id": hxops_turn_id,
|
||||
}
|
||||
@@ -1389,7 +1411,7 @@ def main(agent_runtime_context: str) -> dict:
|
||||
- 导入 `docs/openapi/agent_runtime_context_tools.dify.json`
|
||||
- 节点名建议 `Tool 解析运行态上下文`;调用 `parse_agent_runtime_context`
|
||||
- 推荐 paths:`refs.schedule_task_id`、`refs.hxops_turn_id`、`platform.session_id`
|
||||
- 将 Tool 输出映射为与本节相同的 `task_id` / `hxops_turn_id` 变量名,供 §3.8 使用
|
||||
- 将 Tool 输出映射为与本节相同的 `task_id` / `task_id_int` / `hxops_turn_id` 变量名,供 §3.8 使用
|
||||
|
||||
---
|
||||
|
||||
@@ -1518,7 +1540,7 @@ def main(agent_runtime_context: str) -> dict:
|
||||
错误类型:{{#检索历史检核报告.error_type#}}
|
||||
错误信息:{{#检索历史检核报告.error_message#}}
|
||||
|
||||
常见原因:Tool 鉴权失败(401)、检核任务/批次不存在(404)、参数非法(400)、HXOPS 或 Dify 检索服务不可用(503)、网络超时。
|
||||
常见原因:Tool 鉴权失败(401)、检核任务/批次不存在(404)、参数非法(400)、检核数据源不可用(503 / data_source_unavailable)、HXOPS 或 Dify 检索服务不可用(503)、网络超时。
|
||||
|
||||
若为历史查询,请确认排程已启用 kb_sync 且知识库 Dataset 已绑定;若为发起/查询检核,请确认 Agent 已配置 schedule_task_id。
|
||||
```
|
||||
@@ -1547,7 +1569,7 @@ def main(agent_runtime_context: str) -> dict:
|
||||
|
||||
| 参数 | 类型 | 绑定 / 固定值 |
|
||||
| --- | --- | --- |
|
||||
| `task_id` | Number | `解析运行态上下文.task_id` |
|
||||
| `task_id` | **Number** | `解析运行态上下文.task_id_int`(**勿绑** `task_id` 字符串或 `意图识别.task_id`) |
|
||||
| `hxops_turn_id` | String | `解析运行态上下文.hxops_turn_id` |
|
||||
| `trigger_source` | String | 固定 `dify_chatflow` |
|
||||
| `conversation_id` | String | `sys.conversation_id`(系统变量) |
|
||||
@@ -1560,7 +1582,7 @@ def main(agent_runtime_context: str) -> dict:
|
||||
|
||||
```json
|
||||
{
|
||||
"task_id": "<解析运行态上下文.task_id>",
|
||||
"task_id": "<解析运行态上下文.task_id_int>",
|
||||
"hxops_turn_id": "<解析运行态上下文.hxops_turn_id>",
|
||||
"conversation_id": "{{#sys.conversation_id#}}",
|
||||
"trigger_source": "dify_chatflow",
|
||||
@@ -1855,13 +1877,33 @@ def main(tool_json, tool_text: str = "") -> dict:
|
||||
| --- | --- | --- |
|
||||
| `query_mode` | String | `by_run_id` / `latest_by_task` / `all_runs` / `missing` |
|
||||
| `run_id` | String | 检核批次 ID;非 by_run_id 时为 `""` |
|
||||
| `task_id` | String | 检核任务 ID |
|
||||
| `task_id` | String | 检核任务 ID 字符串,供 IF / LLM |
|
||||
| `task_id_int` | **Number** | 检核任务 ID 整数;§3.17 / §3.17A Tool 绑此字段 |
|
||||
|
||||
**完整 Python 代码**
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
|
||||
def _to_task_id_int(tid: str):
|
||||
"""将 task_id 字符串转为整数;非法或空时返回 None(Dify Number 出参可为 null)。"""
|
||||
normalized = str(tid or "").strip()
|
||||
if not normalized.isdigit():
|
||||
return None
|
||||
return int(normalized)
|
||||
|
||||
|
||||
def _pack_query_result(query_mode: str, run_id: str = "", task_id: str = "") -> dict:
|
||||
tid = str(task_id or "").strip()
|
||||
return {
|
||||
"query_mode": query_mode,
|
||||
"run_id": str(run_id or "").strip(),
|
||||
"task_id": tid,
|
||||
"task_id_int": _to_task_id_int(tid),
|
||||
}
|
||||
|
||||
|
||||
def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
|
||||
q = str(user_query or "")
|
||||
run_id = str(intent_run_id or "").strip()
|
||||
@@ -1869,7 +1911,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
|
||||
all_keywords = ["所有", "全部", "全量", "列表", "历史记录", "执行记录", "所有文件检核结果", "全部文件检核结果", "all"]
|
||||
if any(k in q for k in all_keywords):
|
||||
tid = str(intent_task_id or task_id or "").strip()
|
||||
return {"query_mode": "all_runs", "run_id": "", "task_id": tid}
|
||||
return _pack_query_result("all_runs", task_id=tid)
|
||||
|
||||
if not run_id:
|
||||
m = re.search(r'(?:批次\s*ID|run[_\s-]*id|run_id)\s*[::]?\s*(\d+)', q, re.I)
|
||||
@@ -1881,19 +1923,19 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
|
||||
run_id = m.group(1)
|
||||
|
||||
if run_id:
|
||||
return {"query_mode": "by_run_id", "run_id": run_id, "task_id": ""}
|
||||
return _pack_query_result("by_run_id", run_id=run_id)
|
||||
|
||||
latest_keywords = ["最新", "最近", "上一次", "上次", "latest"]
|
||||
if any(k in q for k in latest_keywords):
|
||||
tid = str(intent_task_id or task_id or "").strip()
|
||||
if tid:
|
||||
return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid}
|
||||
return _pack_query_result("latest_by_task", task_id=tid)
|
||||
|
||||
tid = str(intent_task_id or task_id or "").strip()
|
||||
if tid:
|
||||
return {"query_mode": "latest_by_task", "run_id": "", "task_id": tid}
|
||||
return _pack_query_result("latest_by_task", task_id=tid)
|
||||
|
||||
return {"query_mode": "missing", "run_id": "", "task_id": ""}
|
||||
return _pack_query_result("missing")
|
||||
```
|
||||
|
||||
**下游**:→ [§3.15 IF:查询方式](#315-if查询方式)
|
||||
@@ -1941,7 +1983,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
|
||||
|
||||
| 参数 | 类型 | 绑定 |
|
||||
| --- | --- | --- |
|
||||
| `task_id` | Number | `提取查询参数.task_id` |
|
||||
| `task_id` | Number | `提取查询参数.task_id_int` |
|
||||
|
||||
**下游**:→ [§3.18.2 Code:解析最近检核查询响应](#318-code解析检核查询响应两个节点)
|
||||
|
||||
@@ -1957,7 +1999,7 @@ def main(user_query, intent_run_id, intent_task_id, task_id) -> dict:
|
||||
|
||||
| 参数 | 类型 | 绑定 / 固定值 |
|
||||
| --- | --- | --- |
|
||||
| `task_id` | Number | `提取查询参数.task_id` |
|
||||
| `task_id` | Number | `提取查询参数.task_id_int` |
|
||||
| `limit` | Number | 固定 `50` |
|
||||
|
||||
**下游**:→ [§3.18.3 Code:解析所有检核批次响应](#3183-code解析所有检核批次响应)
|
||||
@@ -2322,7 +2364,7 @@ def main(tool_json, tool_text) -> dict:
|
||||
| 配置项 | 绑定 |
|
||||
| --- | --- |
|
||||
| 工具 | OpenAPI 自定义工具 `search_file_check_history` |
|
||||
| `task_id` | `{{#解析运行态上下文.task_id#}}` |
|
||||
| `task_id` | `{{#解析运行态上下文.task_id_int#}}` |
|
||||
| `query` | `{{#用户输入.query#}}` |
|
||||
| `top_k`(可选) | 默认 5,可不填 |
|
||||
| 异常处理 | **Fail Branch** → §3.7 |
|
||||
@@ -2511,6 +2553,7 @@ def main(tool_json: dict, tool_text: str) -> dict:
|
||||
| `kb_not_configured` | 400 | 排程未启用 kb_sync 或未绑 kb_group | Tool 异常分支 → §3.7 |
|
||||
| `kb_dataset_not_bound` | 400 | 知识库分组未绑定 dify_dataset_id | Tool 异常分支 → §3.7 |
|
||||
| `dify_retrieve_failed` | 503 | Dify 检索 API 失败或未配置 | Tool 异常分支 → §3.7 |
|
||||
| `data_source_unavailable` | 503 | 启动检核预检时 ODBC/SQL Server 连接失败或 SRM 未配置 | Tool 异常分支 → §3.7(RUN_FILE_CHECK) |
|
||||
| `check_running` | 200 | 检核进行中(body,非 HTTP 失败) | Tool **成功出口** → [§3.9](#39-code解析启动检核响应) → [§3.10](#310-if启动业务分支) → §3.12 |
|
||||
| `excel_not_ready` | 409 | 报告未生成 | 查询分支 LLM 说明时提及 |
|
||||
| `invalid_response` | — | Tool HTTP 成功但 Code 无法解析 JSON | [§3.24](#324-answer错误兜底启动检核-body)(启动)或历史 LLM 兜底 |
|
||||
@@ -2607,11 +2650,13 @@ limit 20;
|
||||
| 指定/最近查询共用一个 Code | 分支汇入变量来源混乱 | 复制为两个 Code 节点 |
|
||||
| 历史报告改走 Knowledge Retrieval | 无法按 task_id 动态选 Dataset | 历史走 §3.25 Tool API |
|
||||
| OpenAPI Server URL 错误 | 工具调用超时 / 404 | 确认与 `HXOPS_TOOLS_API_BASE` 一致 |
|
||||
| RUN_FILE_CHECK 绑定 `意图识别.task_id` 或 `task_id` 字符串 | 解析节点有 `task_id_int:3`,Tool 入参却是 `null` | Tool 的 Integer `task_id` **只绑** `解析运行态上下文.task_id_int`(或 `提取查询参数.task_id_int`) |
|
||||
| RUN_FILE_CHECK 仍显示 `task_no` | 入参含废弃字段 `task_no:null` | 重新 URL 导入 OpenAPI(§1.4),删除 `task_no` 绑定 |
|
||||
|
||||
### E.3 迁移后画布检查
|
||||
|
||||
- [ ] Start **仅**含 `agent_runtime_context`(及 `query`);无顶层 `task_id` / `hxops_turn_id`
|
||||
- [ ] 存在 §3.1A `解析运行态上下文` 节点,且 RUN_FILE_CHECK 绑定其 `task_id` / `hxops_turn_id`
|
||||
- [ ] 存在 §3.1A `解析运行态上下文` 节点,且 **所有 Tool** 的 Integer `task_id` 绑 `task_id_int`(RUN_FILE_CHECK / 历史检索绑 `解析运行态上下文.task_id_int`;查询分支绑 `提取查询参数.task_id_int`)
|
||||
- [ ] 不存在调用 `/api/file-check/tools/*` 的 HTTP Request 节点
|
||||
- [ ] 不存在手写 `Authorization` Header
|
||||
- [ ] Start 无 Tool API token / base URL
|
||||
|
||||
@@ -292,9 +292,8 @@ $env:FREIGHT_RPA_LOG_BACKUP_COUNT = "5"
|
||||
$env:FREIGHT_RPA_DSV_USERNAME = "请替换为DSV账号"
|
||||
$env:FREIGHT_RPA_DSV_PASSWORD = "请替换为DSV密码"
|
||||
|
||||
# 如需 Crane:
|
||||
# $env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号"
|
||||
# $env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码"
|
||||
$env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号"
|
||||
$env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码"
|
||||
```
|
||||
|
||||
正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://127.0.0.1:5052",
|
||||
"url": "http://192.168.100.192:8890",
|
||||
"description": "HXOPS_TOOLS_API_BASE"
|
||||
}
|
||||
],
|
||||
@@ -108,6 +108,9 @@
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/DataSourceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -533,7 +536,8 @@
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
"example": 12,
|
||||
"description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
|
||||
},
|
||||
"trigger_source": {
|
||||
"type": "string",
|
||||
@@ -561,7 +565,7 @@
|
||||
"required": [
|
||||
"task_id"
|
||||
],
|
||||
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
|
||||
@@ -6,10 +6,16 @@
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { marked } from 'marked';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
downloadFileCheckExcelByRunId,
|
||||
parseFileCheckExcelRunId,
|
||||
rewriteFileCheckExcelLinksForDisplay,
|
||||
} from '../utils/fileCheckExcelDownload';
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
@@ -330,6 +336,8 @@ function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
}
|
||||
|
||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const message = useMessage();
|
||||
|
||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'shipping-parse-review') return false;
|
||||
@@ -416,6 +424,15 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
void ctx.openPreview(preview);
|
||||
return;
|
||||
}
|
||||
const fileCheckRunId = parseFileCheckExcelRunId(rawHref);
|
||||
if (fileCheckRunId) {
|
||||
event.preventDefault();
|
||||
void downloadFileCheckExcelByRunId(fileCheckRunId).catch((error: unknown) => {
|
||||
const text = error instanceof Error ? error.message : '下载 Excel 失败';
|
||||
message.error(text);
|
||||
});
|
||||
return;
|
||||
}
|
||||
ctx.handleLeaveMarkdownClick(event);
|
||||
};
|
||||
|
||||
@@ -428,7 +445,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const renderMarkdown = (text: string) => {
|
||||
if (!text) return '';
|
||||
const extracted = safeExtractInlineDownloadFiles(text);
|
||||
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
|
||||
const displayText = rewriteFileCheckExcelLinksForDisplay(
|
||||
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
|
||||
);
|
||||
try {
|
||||
const rendered = marked.parse(displayText);
|
||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
parseFileCheckExcelRunId,
|
||||
rewriteFileCheckExcelLinksForDisplay,
|
||||
} from './fileCheckExcelDownload';
|
||||
|
||||
describe('fileCheckExcelDownload', () => {
|
||||
it('parses tool api excel link with token', () => {
|
||||
expect(parseFileCheckExcelRunId(
|
||||
'http://192.168.100.230:8890/api/file-check/tools/runs/187/excel?token=abc',
|
||||
)).toBe(187);
|
||||
});
|
||||
|
||||
it('parses workspace excel link', () => {
|
||||
expect(parseFileCheckExcelRunId('/api/workspace/file-check/runs/42/excel')).toBe(42);
|
||||
});
|
||||
|
||||
it('rewrites tool api links to workspace paths for display', () => {
|
||||
const input = '下载:[链接](http://ai.example.com/api/file-check/tools/runs/9/excel?token=xyz)';
|
||||
expect(rewriteFileCheckExcelLinksForDisplay(input)).toBe(
|
||||
'下载:[链接](/api/workspace/file-check/runs/9/excel)',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* features/chat/utils/fileCheckExcelDownload.ts
|
||||
* 用途:解析文件检核 Excel 下载链接,并通过 Workspace 会话鉴权下载(不依赖短期 JWT)。
|
||||
* 依赖:getAuthHeaders。
|
||||
* 逻辑:ChatMessageBubble 点击 Dify 返回的 Tool API 链接时,改走 workspace 下载接口以支持历史对话。
|
||||
*/
|
||||
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
const FILE_CHECK_TOOL_EXCEL_PATH_RE = /\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?.*)?$/i;
|
||||
const FILE_CHECK_WORKSPACE_EXCEL_PATH_RE = /\/api\/workspace\/file-check\/runs\/(\d+)\/excel(?:\?.*)?$/i;
|
||||
|
||||
/**
|
||||
* 从 Tool API 或 Workspace 下载链中解析检核批次 ID。
|
||||
* @param href - 原始链接(可为绝对或相对路径)。
|
||||
* @returns 批次 ID;无法解析时返回 null。
|
||||
*/
|
||||
export function parseFileCheckExcelRunId(href: string): number | null {
|
||||
const normalized = String(href || '').trim();
|
||||
if (!normalized) return null;
|
||||
|
||||
let pathname = normalized;
|
||||
try {
|
||||
if (/^https?:\/\//i.test(normalized)) {
|
||||
pathname = new URL(normalized).pathname;
|
||||
} else {
|
||||
pathname = normalized.split('?')[0] || normalized;
|
||||
}
|
||||
} catch {
|
||||
pathname = normalized.split('?')[0] || normalized;
|
||||
}
|
||||
|
||||
const match = pathname.match(FILE_CHECK_TOOL_EXCEL_PATH_RE)
|
||||
|| pathname.match(FILE_CHECK_WORKSPACE_EXCEL_PATH_RE);
|
||||
if (!match?.[1]) return null;
|
||||
|
||||
const runId = Number(match[1]);
|
||||
return Number.isFinite(runId) && runId > 0 ? runId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Dify Tool API 的 Excel 下载链改写为 Workspace 相对路径,供 Markdown 展示。
|
||||
* @param text - 原始聊天文本。
|
||||
* @returns 改写后的文本。
|
||||
*/
|
||||
export function rewriteFileCheckExcelLinksForDisplay(text: string): string {
|
||||
const source = String(text || '');
|
||||
if (!source) return '';
|
||||
|
||||
return source
|
||||
.replace(
|
||||
/https?:\/\/[^\s)\]]+\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
|
||||
'/api/workspace/file-check/runs/$1/excel',
|
||||
)
|
||||
.replace(
|
||||
/\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
|
||||
'/api/workspace/file-check/runs/$1/excel',
|
||||
);
|
||||
}
|
||||
|
||||
const parseDownloadFilename = (disposition: string | null, fallback: string) => {
|
||||
const value = disposition || '';
|
||||
const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
|
||||
const raw = utf8Match?.[1] || value.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
|
||||
try {
|
||||
return decodeURIComponent(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 通过 Workspace 接口下载检核 Excel(使用登录态,不依赖 Tool API 短期 token)。
|
||||
* @param runId - 检核批次 ID。
|
||||
* @param fallbackName - 默认文件名。
|
||||
*/
|
||||
export async function downloadFileCheckExcelByRunId(
|
||||
runId: number,
|
||||
fallbackName = `file-check-run-${runId}.xlsx`,
|
||||
): Promise<void> {
|
||||
const url = `/api/workspace/file-check/runs/${encodeURIComponent(String(runId))}/excel`;
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
const message = typeof body?.message === 'string'
|
||||
? body.message
|
||||
: typeof body?.error?.message === 'string'
|
||||
? body.error.message
|
||||
: `下载失败:${res.status}`;
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const filename = parseDownloadFilename(
|
||||
res.headers.get('content-disposition'),
|
||||
fallbackName,
|
||||
);
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -661,47 +661,167 @@ def _wait_dsv_report_ready(page: Any, *, timeout_ms: int) -> None:
|
||||
_wait_for_dsv_report_result_ready(page, timeout_ms)
|
||||
|
||||
|
||||
_DSV_INVENTORY_DATA_ROWS_PROBE_JS = """
|
||||
() => {
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
|
||||
const PARAMETER_ROOT_SELECTORS = [
|
||||
'#ReportViewerMain_ctl08',
|
||||
'#ParameterTable_ReportViewerMain_ctl08',
|
||||
'#ParametersGridReportViewerMain_ctl08',
|
||||
'[id$="_divDropDown"]',
|
||||
].join(', ');
|
||||
|
||||
const REPORT_ROOT_SELECTORS = [
|
||||
'#Report_table',
|
||||
'span#Report_table',
|
||||
'#VisibleReportContentReportViewerMain_ctl13',
|
||||
'#ReportViewerMain_ctl13_ReportArea',
|
||||
'#ReportViewerMain_ctl13',
|
||||
].join(', ');
|
||||
|
||||
const isInsideParameterArea = (node) => {
|
||||
if (!node || !node.closest) return false;
|
||||
return !!node.closest(PARAMETER_ROOT_SELECTORS);
|
||||
};
|
||||
|
||||
const directBodyRows = (table) => {
|
||||
const tbodies = Array.from(table.tBodies || []);
|
||||
const rows = [];
|
||||
for (const tbody of tbodies) {
|
||||
if (tbody.parentElement !== table) continue;
|
||||
rows.push(...Array.from(tbody.children).filter((node) => node.tagName === 'TR'));
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
const isHiddenRow = (row) => {
|
||||
const heightAttr = String(row.getAttribute('height') || '').trim().toLowerCase();
|
||||
if (heightAttr === '0' || heightAttr === '0px') return true;
|
||||
try {
|
||||
const style = window.getComputedStyle(row);
|
||||
if (style.display === 'none' || style.visibility === 'hidden') return true;
|
||||
if (row.offsetHeight === 0 && parseFloat(style.height || '0') === 0) return true;
|
||||
} catch (_err) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const isInventoryHeaderRow = (row) => {
|
||||
const line = normalize(row.innerText || '');
|
||||
return (
|
||||
line.includes('Supplier ID') &&
|
||||
line.includes('AWS Sku') &&
|
||||
(line.includes('Qty Available') || /\\bQty\\b/.test(line))
|
||||
);
|
||||
};
|
||||
|
||||
const isReportMetadataRow = (row) => {
|
||||
const line = normalize(row.innerText || '');
|
||||
if (!line) return true;
|
||||
if (/created\\s+.+(by|rsviewer)/i.test(line)) return true;
|
||||
if (/rsviewer\\s+v\\d/i.test(line)) return true;
|
||||
if (/^aws on hand inventory by location$/i.test(line)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const isWarehouseCodeOnly = (texts) => {
|
||||
if (!texts.length) return true;
|
||||
return texts.every((value) => /^BYAWS[A-Z0-9]+$/i.test(value));
|
||||
};
|
||||
|
||||
const isInventoryDetailRow = (row) => {
|
||||
if (isHiddenRow(row) || isInventoryHeaderRow(row) || isReportMetadataRow(row)) {
|
||||
return false;
|
||||
}
|
||||
const cells = Array.from(row.querySelectorAll(':scope > td, :scope > th'));
|
||||
if (!cells.length) return false;
|
||||
const texts = cells.map((cell) => normalize(cell.innerText || '')).filter(Boolean);
|
||||
if (!texts.length || isWarehouseCodeOnly(texts)) return false;
|
||||
|
||||
const hasAwsSku = texts.some((value) => /^B0[A-Z0-9]{8,}$/i.test(value));
|
||||
const hasSupplierId = texts.some((value) => /^\\d{6,}$/.test(value.replace(/,/g, '')));
|
||||
const hasQtyLike = texts.some((value) => /^-?\\d+(\\.\\d+)?$/.test(value.replace(/,/g, '')));
|
||||
const hasMeaningfulSku = texts.some(
|
||||
(value) =>
|
||||
/^[A-Z0-9][A-Z0-9._-]{3,}$/i.test(value) &&
|
||||
!/^(supplier|location|carton|pallet|uom|owner|putawayzone|warehouse)$/i.test(value) &&
|
||||
!/^BYAWS[A-Z0-9]+$/i.test(value),
|
||||
);
|
||||
|
||||
return hasAwsSku || (hasSupplierId && hasQtyLike) || (hasMeaningfulSku && hasQtyLike);
|
||||
};
|
||||
|
||||
const tableHasInventoryDetailRows = (table) => {
|
||||
if (isInsideParameterArea(table)) return false;
|
||||
const text = normalize(table.innerText || '');
|
||||
const isInventoryTable =
|
||||
text.includes('Supplier ID') &&
|
||||
text.includes('AWS Sku') &&
|
||||
(text.includes('Qty Available') || /\\bQty\\b/.test(text));
|
||||
if (!isInventoryTable) return false;
|
||||
|
||||
const rows = directBodyRows(table).filter((row) => !isHiddenRow(row));
|
||||
const headerIdx = rows.findIndex(isInventoryHeaderRow);
|
||||
if (headerIdx >= 0) {
|
||||
return rows.slice(headerIdx + 1).some(isInventoryDetailRow);
|
||||
}
|
||||
return rows.some(isInventoryDetailRow);
|
||||
};
|
||||
|
||||
const collectCandidateTables = () => {
|
||||
const seen = new Set();
|
||||
const tables = [];
|
||||
const push = (table) => {
|
||||
if (!table || seen.has(table) || isInsideParameterArea(table)) return;
|
||||
seen.add(table);
|
||||
tables.push(table);
|
||||
};
|
||||
|
||||
document
|
||||
.querySelectorAll('#Report_table table, span#Report_table > table')
|
||||
.forEach(push);
|
||||
|
||||
if (tables.length > 0) return tables;
|
||||
|
||||
for (const root of document.querySelectorAll(REPORT_ROOT_SELECTORS)) {
|
||||
if (isInsideParameterArea(root)) continue;
|
||||
root.querySelectorAll('table').forEach((table) => {
|
||||
if (isInsideParameterArea(table)) return;
|
||||
const text = normalize(table.innerText || '');
|
||||
if (
|
||||
text.includes('Supplier ID') &&
|
||||
text.includes('AWS Sku') &&
|
||||
(text.includes('Qty Available') || /\\bQty\\b/.test(text))
|
||||
) {
|
||||
push(table);
|
||||
}
|
||||
});
|
||||
}
|
||||
return tables;
|
||||
};
|
||||
|
||||
return collectCandidateTables().some(tableHasInventoryDetailRows);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _dsv_report_has_inventory_data_rows(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV 库存报表结果页是否存在真实库存明细行。
|
||||
|
||||
核心逻辑:只检查包含库存表头的 SSRS 明细表,不统计整页 `tr`。
|
||||
当前报表无数据时该表通常只有 3 行;有数据时第 4 行开始出现明细行。
|
||||
核心逻辑:仅扫描 SSRS 结果区(`#Report_table` / `#ReportViewerMain_ctl13`),
|
||||
排除参数区 `#ReportViewerMain_ctl08` 及其下拉表格;只统计目标 table 的直接
|
||||
`tbody > tr`;忽略 `height=0`、列头行与 rsviewer 元数据行;明细行须含 AWS Sku
|
||||
或 Supplier ID + Qty 组合,避免 PutawayZone 的 BBU/DAMAGE 被误判为库存。
|
||||
"""
|
||||
selected = _find_dsv_report_result_frame(page)
|
||||
if selected is None:
|
||||
return False
|
||||
_frame_index, frame, _state = selected
|
||||
try:
|
||||
return bool(
|
||||
frame.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
const tables = Array.from(document.querySelectorAll('table'));
|
||||
for (const table of tables) {
|
||||
const text = normalize(table.innerText);
|
||||
const isInventoryTable =
|
||||
text.includes('Supplier ID') &&
|
||||
text.includes('AWS Sku') &&
|
||||
text.includes('Qty Available');
|
||||
if (!isInventoryTable) continue;
|
||||
|
||||
const rows = Array.from(table.querySelectorAll('tbody > tr'));
|
||||
if (rows.length <= 3) return false;
|
||||
|
||||
const dataRows = rows.slice(3).filter((row) => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
const line = normalize(cells.map((cell) => cell.innerText || '').join(' '));
|
||||
return line.length > 0;
|
||||
});
|
||||
return dataRows.length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
"""
|
||||
)
|
||||
)
|
||||
return bool(frame.evaluate(_DSV_INVENTORY_DATA_ROWS_PROBE_JS))
|
||||
except Exception as exc:
|
||||
print(f"[dsv-report] inventory data row probe failed: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
@@ -39,7 +39,7 @@ import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, TextIO
|
||||
|
||||
@@ -126,26 +126,55 @@ def _env(name: str, default: str = "") -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _log_line_timestamp() -> str:
|
||||
"""
|
||||
生成 worker 日志行首时间戳(本地时区)。
|
||||
|
||||
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
|
||||
|
||||
Returns:
|
||||
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
|
||||
"""
|
||||
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
class _TeeStream:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
文件 flush 采用行级同步,RPA 异常退出时尽量保留最后几行排障信息。
|
||||
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
|
||||
保留最后几行排障信息。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
self._pending = ""
|
||||
self.encoding = getattr(console, "encoding", "utf-8")
|
||||
|
||||
def _emit_line(self, line: str, *, newline: bool) -> None:
|
||||
"""将单行(可含时间戳前缀)写入控制台与日志文件。"""
|
||||
if line:
|
||||
stamped = f"{_log_line_timestamp()} {line}"
|
||||
self._console.write(stamped)
|
||||
self._log_file.write(stamped)
|
||||
if newline:
|
||||
self._console.write("\n")
|
||||
self._log_file.write("\n")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._console.write(text)
|
||||
written = self._log_file.write(text)
|
||||
self._pending += text
|
||||
while "\n" in self._pending:
|
||||
line, self._pending = self._pending.split("\n", 1)
|
||||
self._emit_line(line, newline=True)
|
||||
self.flush()
|
||||
return written
|
||||
return len(text)
|
||||
|
||||
def flush(self) -> None:
|
||||
if self._pending:
|
||||
self._emit_line(self._pending, newline=False)
|
||||
self._pending = ""
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
@@ -158,7 +187,8 @@ def _configure_file_logging() -> Path | None:
|
||||
按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,便于排查登录、下载、回调失败。
|
||||
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
|
||||
登录、下载、回调失败与长批次耗时。
|
||||
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
|
||||
Reference in new issue
Block a user