feat(shipping-freight-auto-upload): 新增货代发货Excel连接级自动上传全链路功能

为提升货代上传的自动化程度,减少人工操作,本提交实现完整的连接级自动上传功能,包含以下变更:
- 新增数据库迁移与ShippingRpaProfile模型字段,存储连接级上传配置
- 完善RPA自动上传触发、回调与状态管理逻辑,支持三态结果与人工兜底
- 优化聊天界面任务卡片加载与按钮渲染,修复无文案幽灵按钮问题
This commit is contained in:
hugo committed 2026-08-27 12:44:12 +08:00
1 parent 06c18b3c7c
commit 434c04ed2d
30 files changed
+1574 -185

No files matched your search

+176 -65
View File
@@ -30,9 +30,8 @@ Optional:
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR
SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR
# 上传采用“用连接 login_url 登录 → 直接访问 upload_entry_url 上传页”;文件选择、提交动作与
# 结果判定由受控 DsvUploadAdapter / CraneUploadAdapter 固化,禁止后端注入任意脚本或 selector。
"""
from __future__ import annotations
@@ -1690,77 +1689,186 @@ def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str,
)
class _UploadResultUnknownError(RuntimeError):
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
class _BaseUploadAdapter:
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
"""
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
self.file_path = file_path
self.config = upload_config or {}
def _timeout_ms(self) -> int:
try:
seconds = int(self.config.get('timeout_seconds') or 120)
except (TypeError, ValueError):
seconds = 120
return max(1, seconds) * 1000
def _require(self, *fields: str) -> None:
missing = [field for field in fields if not str(self.config.get(field) or '').strip()]
if missing:
raise RuntimeError(f"upload config missing required field(s): {', '.join(missing)}")
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
raise NotImplementedError
class DsvUploadAdapter(_BaseUploadAdapter):
"""DSV 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → History 绿色判定。"""
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
self._require('entry_url', 'file_input_selector')
_ensure_dsv_session(page, login_url)
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
submit_selector = str(self.config.get('submit_selector') or '').strip()
if not submit_selector:
raise RuntimeError('DSV click_submit upload requires submit_selector')
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
try:
return _wait_for_dsv_upload_history_receipt(page, self.file_path.name)
except RuntimeError as exc:
# 文件已选择/可能已提交但未取得可核验成功证据 → unknown,转人工。
raise _UploadResultUnknownError(str(exc)) from exc
class CraneUploadAdapter(_BaseUploadAdapter):
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
"""
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
self._require('entry_url', 'file_input_selector', 'submit_mode')
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
self._require('submit_selector')
self._require_result_fields()
_ensure_crane_session(page, login_url)
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
page.locator(str(self.config['file_input_selector'])).first.set_input_files(
str(self.file_path), timeout=self._timeout_ms(),
)
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
page.locator(str(self.config['submit_selector'])).first.click(timeout=self._timeout_ms())
return self._resolve_result(page)
def _require_result_fields(self) -> None:
result_mode = str(self.config.get('result_mode') or '').strip()
if result_mode == 'page_notice':
if not str(self.config.get('result_selector') or '').strip() or not self.config.get('success_texts'):
raise RuntimeError('Crane page_notice upload requires result_selector and success_texts')
elif result_mode == 'history_record' and not str(self.config.get('result_selector') or '').strip():
raise RuntimeError('Crane history_record upload requires result_selector')
else:
raise RuntimeError('Crane upload requires a supported result_mode')
def _resolve_result(self, page: Any) -> dict[str, Any]:
result_mode = str(self.config.get('result_mode') or '').strip()
filename = self.file_path.name
if result_mode == 'history_record':
result_selector = str(self.config.get('result_selector') or '').strip()
try:
loc = page.locator(result_selector).first
loc.wait_for(state='visible', timeout=self._timeout_ms())
except Exception as exc:
raise _UploadResultUnknownError(
f"Crane upload history not confirmed for {filename!r}: {exc}"
) from exc
try:
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
except Exception:
reference = ''
return {
'reference': reference,
'success_evidence': _capture_success_page_evidence(
page, kind='crane_history_record', selector=result_selector,
filename=filename, reference=reference or None,
),
}
# page_notice:要求 result_selector 可见且内容命中任一 success_texts。
result_selector = str(self.config.get('result_selector') or '').strip()
success_texts = [str(t).strip() for t in (self.config.get('success_texts') or []) if str(t).strip()]
deadline = time.monotonic() + (self._timeout_ms() / 1000)
last_snippet = ''
while time.monotonic() < deadline:
try:
loc = page.locator(result_selector).first
if loc.count() > 0 and loc.is_visible():
snippet = str(loc.text_content(timeout=1000) or '').strip()
last_snippet = snippet
if any(text in snippet for text in success_texts):
return {
'reference': '',
'success_evidence': _capture_success_page_evidence(
page, kind='crane_page_notice', selector=result_selector,
filename=filename, reference=None,
),
}
except Exception:
pass
time.sleep(1)
raise _UploadResultUnknownError(
f"Crane upload page notice not confirmed for {filename!r}; last_snippet={last_snippet!r}"
)
def _upload_shipment_with_browser(
file_path: Path, *, connector_type: str = "", dsv_entry_url: str = ""
file_path: Path, *, connector_type: str = "", upload_source: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
在受控配置下执行货代 Excel 上传,并以页面成功证据作为回调成功前提。
在受控 Adapter 下执行货代 Excel 上传,并以可核验证据作为回调成功前提。
触发条件:仅当 Worker 非 mock、上传与最终提交两个开关均为 true,且 URL、文件
控件、提交控件和成功标识均已配置时执行。未满足任何条件时抛异常并回调失败,绝不
猜测站点、选择器或提交按钮。
触发条件:连接 upload_config.enabled=true(代表管理员已审核该连接的上传行为),且 Worker 上传与
最终提交两项开关均为 true。未满足/未审核时抛异常并回调失败/未知,绝不猜测站点、选择器或
提交按钮,也不允许后台配置注入任意脚本或浏览器动作。
Args:
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
connector_type: 业务连接类型(dbs / crane),决定使用哪个受控 Adapter。
upload_source: 该连接上传快照(含 login_url / credential_envelope / upload_config_json)。
Returns:
dict: reference(可空)与 success_evidence(DSV 绿 DOM 或通用 success 选择器)。
dict: reference(可空)与 success_evidence。
"""
upload_source = upload_source or {}
upload_config = upload_source.get('upload_config_json')
if not isinstance(upload_config, dict) or not upload_config.get('enabled'):
raise RuntimeError(
"upload RPA is not enabled for this connection; enable it in '系统连接' after validation"
)
if not _upload_worker_enabled():
raise RuntimeError("upload RPA is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
raise RuntimeError("upload RPA worker is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
if not _upload_submit_confirmed():
raise RuntimeError("upload RPA submit is not confirmed; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run")
normalized_connector = _worker_connector_type({"connector_type": connector_type}) if connector_type else ""
upload_url = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL")
file_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR")
submit_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR")
success_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR")
if normalized_connector == "crane_footprint":
raise RuntimeError("CRANE upload RPA is not implemented because its upload path is unverified")
if normalized_connector == "dsv360":
dsv_entry_url = dsv_entry_url or _env("SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL")
if not dsv_entry_url:
raise RuntimeError("DSV upload RPA requires a reviewed DSV upload entry URL")
# DSV WMS Upload Tool 已在真实页面确认 Browse 与 Process File 的 DOM。
file_selector = file_selector or "#file2"
submit_selector = submit_selector or 'button.upload-button:has-text("Process File")'
elif not upload_url:
raise RuntimeError("upload RPA configuration requires a reviewed upload URL")
if not all((file_selector, submit_selector)) or (
normalized_connector != "dsv360" and not success_selector
):
raise RuntimeError("upload RPA configuration requires file, submit and success selectors")
business = str(connector_type or '').strip().lower()
if business not in {'dbs', 'crane'} and connector_type:
business = {'dsv360': 'dbs', 'crane_footprint': 'crane'}.get(
_worker_connector_type({"connector_type": connector_type}), business,
)
if business == 'dbs':
adapter = DsvUploadAdapter(file_path=file_path, upload_config=upload_config)
elif business == 'crane':
adapter = CraneUploadAdapter(file_path=file_path, upload_config=upload_config)
else:
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
login_url = str(upload_source.get('login_url') or '').strip()
playwright = context = runtime_profile_dir = None
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
if normalized_connector == "dsv360":
_navigate_dsv_to_upload_tool(page, dsv_entry_url)
else:
page.goto(upload_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
file_input = page.locator(file_selector).first
file_input.set_input_files(str(file_path), timeout=_browser_timeout_ms())
submit = page.locator(submit_selector).first
submit.click(timeout=_browser_timeout_ms())
if normalized_connector == "dsv360":
return _wait_for_dsv_upload_history_receipt(page, file_path.name)
page.locator(success_selector).first.wait_for(state="visible", timeout=_browser_timeout_ms())
receipt_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR")
reference = ''
if receipt_selector:
receipt = page.locator(receipt_selector).first
reference = str(receipt.text_content(timeout=_browser_timeout_ms()) or "").strip()
return {
"reference": reference,
"success_evidence": _capture_success_page_evidence(
page,
kind="configured_success_selector",
selector=success_selector,
filename=file_path.name,
reference=reference or None,
),
}
with _profile_credentials(upload_source):
return adapter.run(page, login_url=login_url)
except Exception:
failed = True
raise
@@ -1795,6 +1903,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "failed",
"success": False,
"error_message": f"queue file missing: {file_path or '<empty>'}",
})
@@ -1826,15 +1935,15 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
},
}
else:
connector_type = str(body.get("inventory_connector_type") or "").strip()
dsv_entry_url = str(body.get("inventory_entry_url") or "").strip()
# 兼容旧 trigger;新 trigger 才携带站点路由信息并进入专用 Driver。
raw = (
_upload_shipment_with_browser(
Path(file_path), connector_type=connector_type, dsv_entry_url=dsv_entry_url
)
if connector_type
else _upload_shipment_with_browser(Path(file_path))
connector_type = str(body.get("connector_type") or "").strip()
upload_source = {
"connector_type": connector_type,
"login_url": str(body.get("login_url") or "").strip(),
"credential_envelope": body.get("credential_envelope"),
"upload_config_json": body.get("upload_config"),
}
raw = _upload_shipment_with_browser(
Path(file_path), connector_type=connector_type, upload_source=upload_source,
)
upload_result = raw if isinstance(raw, dict) else {"reference": str(raw or ''), "success_evidence": None}
ref = str(upload_result.get("reference") or "").strip()
@@ -1842,6 +1951,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "success",
"success": True,
"freight_ref_no": ref or None,
"success_evidence": upload_result.get("success_evidence"),
@@ -1854,6 +1964,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "unknown" if isinstance(exc, _UploadResultUnknownError) else "failed",
"success": False,
"error_message": str(exc)[:500],
})