feat(freight-rpa): 系统连接只保留上传开关并增加 Crane 一次回查
上传页、按钮和成功判断改由连接器固定。Crane 分配中只排一次 10 分钟状态回查,手动刷新不改到期时间。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
95e7db0831
commit
3bb9938c05
33 files changed
+878
-374
No files matched your search
@@ -1995,6 +1995,22 @@ def _dsv_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""用登录地址的主机拼出平台固定上传页,不读取管理端保存的入口 URL。"""
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host:
|
||||
raise RuntimeError('upload login_url must be HTTPS')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}/main/portal/frame/WMSUpload2'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}/#/shipping-order-upload'
|
||||
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 发货通知行是否进入 Processing/Shipping Order Allocated。"""
|
||||
return (
|
||||
@@ -2004,6 +2020,15 @@ def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _crane_upload_result_is_allocating(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 是否已接收文件、仍在分配。这一态不是上传成功。"""
|
||||
return (
|
||||
bool(state.get('found'))
|
||||
and str(state.get('order_status') or '').strip().lower() == 'processing'
|
||||
and str(state.get('order_status_description') or '').strip().lower() == 'allocating the shipping order'
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_result(page: Any, filename: str) -> dict[str, Any]:
|
||||
"""轮询 DSV 上传结果页,不再使用 History 绿图标作为成功依据。
|
||||
|
||||
@@ -2056,12 +2081,19 @@ class _UploadResultUnknownError(RuntimeError):
|
||||
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
|
||||
class _UploadAcceptedAllocating(Exception):
|
||||
"""Crane 已接收文件,行状态仍是 Allocating。调用方回调 allocating,不视为失败。"""
|
||||
|
||||
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
|
||||
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
|
||||
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
|
||||
def __init__(self, pull_request_no: str):
|
||||
self.pull_request_no = pull_request_no
|
||||
super().__init__(pull_request_no)
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:页面路径、按钮和成功判断写在连接器里。
|
||||
|
||||
设计约束:系统连接只保存是否启用自动上传。Adapter 负责登录、打开固定上传页、
|
||||
选择 Excel、提交与结果判定。Worker 不再根据环境变量或后台选择器拼接页面动作。
|
||||
"""
|
||||
|
||||
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
|
||||
@@ -2089,10 +2121,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
"""选择 DSV 文件后强制点击 Process File,再读取结果页三项成功条件。"""
|
||||
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.goto(_upload_entry_url('dbs', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = 'input#file2'
|
||||
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
|
||||
# DSV 页面选择文件后只完成预览;必须点击真实二次确认按钮才会提交上传。
|
||||
submit_selector = 'button.btn.btn-primary.upload-button:has-text("Process File")'
|
||||
@@ -2105,9 +2136,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
|
||||
class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
|
||||
"""Crane 受控上传流程:login_url 登录后打开固定上传页,选择文件并读发货单行。
|
||||
|
||||
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
|
||||
Processing + Allocating the Shipping Order 表示已接收;只有 Shipping Order Allocated 才算成功。
|
||||
"""
|
||||
|
||||
# SweetAlert2 上传失败弹窗识别(受控 Adapter 内置,禁止开放到 upload_config):Crane 上传
|
||||
@@ -2133,18 +2164,25 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
)
|
||||
|
||||
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()
|
||||
"""选择 Crane 上传文件后读发货单行。分配中立即返回,不等到超时。"""
|
||||
_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(
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
page.locator('input[name="OrderFileUpload"]').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)
|
||||
result = self._resolve_result(page)
|
||||
if result.get('outcome') == 'allocating':
|
||||
raise _UploadAcceptedAllocating(self.file_path.stem)
|
||||
return result
|
||||
|
||||
def run_status_check(self, page: Any, *, login_url: str, pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录后只按 Pull Request # 读行,不选择、不提交文件。"""
|
||||
_ensure_crane_session(page, login_url)
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
found = self._wait_for_order_status(page, f'{pull_request_no}.xlsx', wait_seconds=20)
|
||||
if found and found.get('success_evidence'):
|
||||
return found
|
||||
return {'outcome': 'allocating', 'pull_request_no': pull_request_no}
|
||||
|
||||
def _require_result_fields(self) -> None:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
@@ -2242,83 +2280,22 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return None
|
||||
|
||||
def _resolve_result(self, page: Any) -> dict[str, Any]:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
"""读发货单行。已分配或分配中立即返回;明确弹窗拒绝则失败。"""
|
||||
filename = self.file_path.name
|
||||
# [STEP 1] Crane 页面成功反馈后仍需核对发货通知列表中的业务状态,
|
||||
# 只有 Processing + Shipping Order Allocated 才视为真正上传成功。
|
||||
status_result = self._wait_for_order_status(page, filename)
|
||||
# [STEP 1] 只有 Processing + Shipping Order Allocated 才是上传成功。
|
||||
# Processing + Allocating the Shipping Order 表示货代已接收,稍后回查。
|
||||
status_result = self._wait_for_order_status(page, filename, wait_seconds=30)
|
||||
if status_result:
|
||||
return status_result
|
||||
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
|
||||
# [STEP 2] 客户或仓库不存在等明确拒绝记失败。看不到行时不按后台选择器猜成功。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
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:
|
||||
# 判定期内可能出现失败弹窗(如 Customer/Warehouse 未找到);先读取并关闭,
|
||||
# 以真实原因上报失败;否则仍按“结果未知”转人工。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
raise _UploadResultUnknownError(
|
||||
f"无法判断上传是否成功/失败:{filename!r} 历史结果未确认({exc});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
) 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:
|
||||
# 上传失败时 Crane 会先弹错误窗而非成功提示;命中则读取原因、点 OK 关闭并上报失败。
|
||||
self._raise_if_crane_error(page)
|
||||
# 成功也可能以 SweetAlert2 成功弹窗反馈;优先于配置 result_selector 判定,避免配置错误误报 unknown。
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
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"无法判断上传是否成功/失败:{filename!r} 结果未确认(last_snippet={last_snippet!r});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
f"无法判断上传是否成功/失败:{filename!r} 未出现 Processing + Allocating 或 Shipping Order Allocated。"
|
||||
)
|
||||
|
||||
def _wait_for_order_status(self, page: Any, filename: str) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表,按上传单号核对 Processing/Shipping Order Allocated。"""
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
def _wait_for_order_status(self, page: Any, filename: str, *, wait_seconds: int = 30) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表。看到 Allocating 立刻返回,不等到 Allocated。"""
|
||||
result_selector = ''
|
||||
script = """
|
||||
({ filename, resultSelector }) => {
|
||||
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
|
||||
@@ -2338,15 +2315,18 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return { found: false, order_status: '', order_status_description: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
deadline = time.monotonic() + max(1, int(wait_seconds))
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(script, {'filename': filename, 'resultSelector': result_selector}) or {}
|
||||
if isinstance(state, dict):
|
||||
last_state = state
|
||||
if _crane_upload_result_is_allocating(state):
|
||||
return {'outcome': 'allocating', 'pull_request_no': Path(filename).stem}
|
||||
if _crane_upload_result_is_success(state):
|
||||
return {
|
||||
'outcome': 'allocated',
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_order_status_dom', selector='tr[id^="shipping-order-"]',
|
||||
@@ -2429,6 +2409,41 @@ def _upload_shipment_with_browser(
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _check_crane_allocation(upload_source: dict[str, Any], pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录 Crane,只按 Pull Request # 读取发货单行。"""
|
||||
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(Path('.'), reuse_session=False)
|
||||
adapter = CraneUploadAdapter(file_path=Path(f'{pull_request_no}.xlsx'), upload_config={})
|
||||
with _profile_credentials(upload_source):
|
||||
return adapter.run_status_check(page, login_url=login_url, pull_request_no=pull_request_no)
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
if not (failed and _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"):
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _post_allocating_callback(body: dict[str, Any], *, pull_request_no: str) -> None:
|
||||
"""回调 Crane 已接收、仍在分配。不带成功证据。"""
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": body.get("task_no"),
|
||||
"attempt_id": body.get("attempt_id"),
|
||||
"callback_id": body.get("callback_id"),
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"pull_request_no": pull_request_no,
|
||||
})
|
||||
|
||||
|
||||
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
@@ -2436,11 +2451,49 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
attempt_id = body.get("attempt_id")
|
||||
callback_id = str(body.get("callback_id") or "").strip()
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
status_check = str(body.get("mode") or "").strip() == "status_check"
|
||||
if not task_no:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if status_check and not mock:
|
||||
try:
|
||||
upload_source = {
|
||||
"connector_type": str(body.get("connector_type") or "").strip(),
|
||||
"login_url": str(body.get("login_url") or "").strip(),
|
||||
"credential_envelope": body.get("credential_envelope"),
|
||||
"upload_config_json": body.get("upload_config") or {"enabled": True},
|
||||
}
|
||||
pull_request_no = str(body.get("pull_request_no") or Path(file_path).stem).strip()
|
||||
raw = _check_crane_allocation(upload_source, pull_request_no)
|
||||
if raw.get("success_evidence"):
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "success",
|
||||
"success": True,
|
||||
"success_evidence": raw.get("success_evidence"),
|
||||
})
|
||||
else:
|
||||
_post_allocating_callback(body, pull_request_no=pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"error_message": str(exc)[:500],
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed after status check error")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
return
|
||||
|
||||
if not file_path or not Path(file_path).is_file():
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
@@ -2502,6 +2555,13 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
|
||||
except _UploadAcceptedAllocating as exc:
|
||||
try:
|
||||
_post_allocating_callback(body, pull_request_no=exc.pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] crane accepted {task_no} pull_request={exc.pull_request_no}; waiting for allocation")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
|
||||
Reference in new issue
Block a user