feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力
This commit is contained in:
1 parent
d62f5107b2
commit
93777fd6df
63 files changed
+9707
-1491
No files matched your search
@@ -26,6 +26,14 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` | 真实上传浏览器自动化总开关,默认 `false` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT` | 最终提交二次确认,默认 `false` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL` | 非 DSV 站点的已审核上传页面 URL(仅由受控环境变量注入) |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` | DSV Portal 入口;Worker 复用登录态,优先 `My Applications > Upload Tool`,再退回 `Apps > Upload Tool` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR` | 文件输入框 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` | 提交按钮 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR` | 成功状态 CSS selector;未出现不得回调成功 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR` | 可选的货代回执号 CSS selector |
|
||||
| `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | 与后端 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 一致;Worker 在 **inventory_triggers** 目录写哨兵 `.hxops_rpa_shared_mount` |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
|
||||
@@ -38,6 +46,19 @@ Windows test/prod 部署脚本:`scripts/rpa/set_rpa_worker_env.ps1`(详见 `
|
||||
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。历史 `FREIGHT_RPA_*`、`SHIPPING_RPA_*`
|
||||
仅在迁移期兼容读取,不得用于新部署。
|
||||
|
||||
### DSV WMS Upload Tool
|
||||
|
||||
已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和
|
||||
`History` 查询入口。`Browse` 的真实 DOM 是 `<input id="file2" type="file">`,因此
|
||||
DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR`
|
||||
覆盖。选择文件后出现的真实提交控件为 `<button class="btn btn-primary upload-button">`
|
||||
(文案 `Process File`),DSV Worker 默认使用
|
||||
`button.upload-button:has-text("Process File")`,亦可通过
|
||||
`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` 覆盖。DSV 成功不依赖 toast:Worker
|
||||
切换到 `History`,仅在同名文件行同时存在绿色
|
||||
`em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #` 时回调成功,Reference
|
||||
作为货代回执号。CRANE 上传路径尚未确认,Worker 会显式失败,绝不会误用 DSV 页面。
|
||||
|
||||
## 部署、启动与停止手册
|
||||
|
||||
本节说明库存 RPA 测试导出的三种运行方式:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -90,6 +90,9 @@ $Vars = [ordered]@{
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR" = Join-Path $DataRoot "inventory_drop"
|
||||
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR" = Join-Path $DataRoot "upload_triggers"
|
||||
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR" = Join-Path $DataRoot "upload_queue"
|
||||
# 上传站点配置通过受控环境变量单独注入;部署脚本永远不默认开启浏览器提交。
|
||||
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED" = "false"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT" = "false"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR" = Join-Path $DataRoot "browser_profile"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_LOG_FILE" = Join-Path $DataRoot "logs\worker.log"
|
||||
"SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES" = "10485760"
|
||||
|
||||
Reference in new issue
Block a user