feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力
This commit is contained in:
1 parent
d62f5107b2
commit
93777fd6df
63 files changed
+9707
-1491
No files matched your search
@@ -27,6 +27,11 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
|
||||
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
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1166,6 +1171,197 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
|
||||
def _upload_worker_enabled() -> bool:
|
||||
"""返回上传浏览器自动化开关;默认关闭,避免仅部署 Worker 就提交货代文件。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false").lower() == "true"
|
||||
|
||||
|
||||
def _upload_submit_confirmed() -> bool:
|
||||
"""返回真实提交二次确认开关;页面填文件与最终提交必须显式分开授权。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "false").lower() == "true"
|
||||
|
||||
|
||||
def _click_dsv_upload_tool_entry(page: Any, *, section: str | None = None) -> bool:
|
||||
"""点击已确认的 DSV Upload Tool 入口;返回是否已打开 WMS 上传页。"""
|
||||
section_selector = (
|
||||
f":has-text({json.dumps(section)})" if section else ""
|
||||
)
|
||||
selectors = (
|
||||
f"{section_selector} a:has-text('Upload Tool')" if section else "",
|
||||
f"{section_selector} button:has-text('Upload Tool')" if section else "",
|
||||
"a:has-text('Upload Tool')" if not section else "",
|
||||
"button:has-text('Upload Tool')" if not section else "",
|
||||
"[role='link']:has-text('Upload Tool')" if not section else "",
|
||||
)
|
||||
for selector in (item for item in selectors if item):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
locator.wait_for(state="visible", timeout=3_000)
|
||||
locator.click(timeout=3_000)
|
||||
page.get_by_text("WMS Upload Tool", exact=False).first.wait_for(
|
||||
state="visible", timeout=_browser_timeout_ms()
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _navigate_dsv_to_upload_tool(page: Any, entry_url: str) -> None:
|
||||
"""
|
||||
复用 DSV 登录态进入 WMS Upload Tool,优先首页入口,再退回 Apps 菜单。
|
||||
|
||||
Args:
|
||||
page: 已由 Worker 创建的 Playwright 页面。
|
||||
entry_url: 已审核的 DSV Portal 入口,不允许用代码猜测站点地址。
|
||||
|
||||
Raises:
|
||||
RuntimeError: Portal 未提供截图已确认的任一 Upload Tool 入口时抛出。
|
||||
"""
|
||||
_ensure_dsv_session(page, entry_url)
|
||||
if _click_dsv_upload_tool_entry(page, section="My Applications"):
|
||||
return
|
||||
|
||||
for selector in (
|
||||
"nav a:has-text('Apps')",
|
||||
"a.nav-link:has-text('Apps')",
|
||||
"[role='button']:has-text('Apps')",
|
||||
):
|
||||
try:
|
||||
apps = page.locator(selector).first
|
||||
apps.wait_for(state="visible", timeout=3_000)
|
||||
apps.click(timeout=3_000, force=True)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if _click_dsv_upload_tool_entry(page):
|
||||
return
|
||||
raise RuntimeError("DSV WMS Upload Tool was not found via My Applications or Apps")
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> str:
|
||||
"""仅以 DSV History 的同名绿色行和 Reference # 确认上传受理。"""
|
||||
try:
|
||||
page.get_by_text("History", exact=True).first.click(timeout=_browser_timeout_ms())
|
||||
except Exception as exc:
|
||||
raise RuntimeError("DSV Upload History tab was not available") from exc
|
||||
|
||||
receipt_script = """
|
||||
({ filename }) => {
|
||||
const clean = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
|
||||
for (const table of document.querySelectorAll('table')) {
|
||||
const headers = Array.from(table.querySelectorAll('thead th')).map((node) => clean(node.textContent));
|
||||
const filenameIndex = headers.findIndex((value) => value.toLowerCase() === 'filename');
|
||||
const referenceIndex = headers.findIndex((value) => value.toLowerCase() === 'reference #');
|
||||
if (filenameIndex < 0 || referenceIndex < 0) continue;
|
||||
for (const row of table.querySelectorAll('tbody tr')) {
|
||||
const cells = Array.from(row.querySelectorAll(':scope > td'));
|
||||
if (clean(cells[filenameIndex]?.textContent) !== filename) continue;
|
||||
return {
|
||||
found: true,
|
||||
succeeded: Boolean(row.querySelector('em.fa.fa-circle.success-color.status-icon')),
|
||||
reference: clean(cells[referenceIndex]?.textContent),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { found: false, succeeded: false, reference: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (_browser_timeout_ms() / 1000)
|
||||
last_state: dict[str, Any] = {"found": False, "succeeded": False, "reference": ""}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(receipt_script, {"filename": filename}) or {}
|
||||
last_state = state if isinstance(state, dict) else last_state
|
||||
except Exception:
|
||||
last_state = {"found": False, "succeeded": False, "reference": ""}
|
||||
reference = str(last_state.get("reference") or "").strip()
|
||||
if bool(last_state.get("succeeded")) and reference:
|
||||
return reference
|
||||
time.sleep(1)
|
||||
raise RuntimeError(
|
||||
"DSV upload History did not confirm a green success status and Reference # "
|
||||
f"for {filename!r}; last_state={last_state}"
|
||||
)
|
||||
|
||||
|
||||
def _upload_shipment_with_browser(
|
||||
file_path: Path, *, connector_type: str = "", dsv_entry_url: str = ""
|
||||
) -> str | None:
|
||||
"""
|
||||
在受控配置下执行货代 Excel 上传,并以页面成功证据作为回调成功前提。
|
||||
|
||||
触发条件:仅当 Worker 非 mock、上传与最终提交两个开关均为 true,且 URL、文件
|
||||
控件、提交控件和成功标识均已配置时执行。未满足任何条件时抛异常并回调失败,绝不
|
||||
猜测站点、选择器或提交按钮。
|
||||
|
||||
Args:
|
||||
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
|
||||
|
||||
Returns:
|
||||
可选货代回执号;页面未配置回执选择器时返回 None。
|
||||
"""
|
||||
if not _upload_worker_enabled():
|
||||
raise RuntimeError("upload RPA 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")
|
||||
|
||||
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")
|
||||
if not receipt_selector:
|
||||
return None
|
||||
receipt = page.locator(receipt_selector).first
|
||||
return str(receipt.text_content(timeout=_browser_timeout_ms()) or "").strip() or None
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
if failed and _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true":
|
||||
print("[browser] keeping browser open after upload error because SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true")
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
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 _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()
|
||||
@@ -1178,26 +1374,34 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
return
|
||||
|
||||
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if not mock:
|
||||
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
|
||||
return
|
||||
|
||||
if file_path and not Path(file_path).is_file():
|
||||
if not file_path or not Path(file_path).is_file():
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"success": False,
|
||||
"error_message": f"queue file missing: {file_path}",
|
||||
"error_message": f"queue file missing: {file_path or '<empty>'}",
|
||||
})
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
return
|
||||
|
||||
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
|
||||
try:
|
||||
if mock:
|
||||
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
|
||||
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。
|
||||
ref = (
|
||||
_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))
|
||||
)
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
@@ -1206,9 +1410,19 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
"freight_ref_no": ref,
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] mock upload done for {task_no} ref={ref}")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"success": False,
|
||||
"error_message": str(exc)[:500],
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed after upload failure")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
|
||||
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
Reference in new issue
Block a user