chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

+122 -43
View File
@@ -19,6 +19,7 @@ Optional:
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=false
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
@@ -446,6 +447,22 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
_move_trigger(trigger_path, failed_dir, "callback failed")
def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profile_dir: Path | None) -> None:
"""在正常完成或 Ctrl+C 中断后依序释放批量 RPA 浏览器资源。"""
try:
if context is not None:
context.close()
except BaseException as exc:
print(f"[browser] context close interrupted: {exc}", file=sys.stderr)
try:
if playwright is not None:
playwright.stop()
except BaseException as exc:
print(f"[browser] playwright stop interrupted: {exc}", file=sys.stderr)
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
_INVENTORY_V2_REQUIRED_FIELDS = (
"schema_version", "callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id",
@@ -530,36 +547,48 @@ def _validate_inventory_excel(path: Path) -> None:
Raises:
RuntimeError: 文件过小、非 Excel 或缺少库存报表关键表头。
"""
size = path.stat().st_size
if size < _INVENTORY_EXCEL_MIN_BYTES:
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
started_at = time.monotonic()
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError("openpyxl required to validate inventory Excel") from exc
size = path.stat().st_size
if size < _INVENTORY_EXCEL_MIN_BYTES:
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception as exc:
raise RuntimeError(f"downloaded file is not valid Excel: {exc}") from exc
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError("openpyxl required to validate inventory Excel") from exc
try:
worksheet = workbook.active
if worksheet is None:
raise RuntimeError("downloaded file is not valid Excel: missing active sheet")
preview_lines: list[str] = []
for row in worksheet.iter_rows(max_row=6, values_only=True):
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
if cells:
preview_lines.append(" | ".join(cells).lower())
haystack = "\n".join(preview_lines)
title = str(worksheet.title or "").lower().replace("_", "")
if not any(marker in haystack for marker in _INVENTORY_EXCEL_HEADER_MARKERS):
if "inventory" not in title and "onhand" not in title:
raise RuntimeError("downloaded file is not valid Excel: missing inventory report headers")
finally:
workbook.close()
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception as exc:
raise RuntimeError(f"downloaded file is not valid Excel: {exc}") from exc
try:
worksheet = workbook.active
if worksheet is None:
raise RuntimeError("downloaded file is not valid Excel: missing active sheet")
preview_lines: list[str] = []
for row in worksheet.iter_rows(max_row=6, values_only=True):
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
if cells:
preview_lines.append(" | ".join(cells).lower())
haystack = "\n".join(preview_lines)
title = str(worksheet.title or "").lower().replace("_", "")
if not any(marker in haystack for marker in _INVENTORY_EXCEL_HEADER_MARKERS):
if "inventory" not in title and "onhand" not in title:
raise RuntimeError("downloaded file is not valid Excel: missing inventory report headers")
finally:
workbook.close()
except Exception:
print(
"[inventory-artifact] stage=excel_structure_validation status=error "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
)
raise
print(
"[inventory-artifact] stage=excel_structure_validation status=end "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
)
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
@@ -586,7 +615,12 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic
source_code = str(source.get("source_code") or "UNKNOWN")
warehouse_id = str(source.get("warehouse_id") or "WH")
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
save_started_at = time.monotonic()
download.save_as(str(dest))
print(
"[inventory-artifact] stage=download_save status=end "
f"elapsedMs={int((time.monotonic() - save_started_at) * 1000)} path={dest.name!r}"
)
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
_validate_inventory_excel(dest)
return dest
@@ -798,26 +832,64 @@ def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: d
)
def _open_browser(download_dir: Path):
def _dsv_session_reuse_enabled() -> bool:
"""返回是否显式允许 DSV 库存导出复用受控浏览器会话。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "false").lower() == "true"
def _dsv_session_profile_dir() -> Path:
"""返回 DSV 专用持久 profile;该目录不得与其他货代任务共用。"""
return _browser_profile_root() / "dsv360_session"
def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
"""
判断关闭浏览器后是否可删除本次 profile。
核心逻辑:仅显式开启的 DSV 固定会话目录需要跨任务保留;其余目录都是
`_open_browser` 创建的一次性运行目录,应由调用方清理。
Args:
profile_dir: 已传给 Playwright persistent context 的 profile 目录。
Returns:
bool: 为 True 时调用方可安全删除该目录。
"""
return profile_dir.resolve() != _dsv_session_profile_dir().resolve()
def _open_browser(download_dir: Path, *, reuse_dsv_session: bool = False):
"""
打开用于库存 RPA 导出的浏览器上下文。
核心逻辑:无论正式执行还是测试执行,都基于 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`
创建一次性的运行时 profile 子目录,再交给 Playwright 的 persistent context。
这样既能保留 Chrome/Edge 可执行文件与下载目录配置,又能避免复用任何已有登录态。
核心逻辑:默认创建一次性的运行时 profile 子目录。仅当调用方明确为 DSV
库存导出请求会话复用,且 `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=true` 时,
才使用独立的固定 `dsv360_session` 目录;其他货代任务绝不复用该会话。
Args:
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
reuse_dsv_session: 仅 DSV 库存调用可传 True;环境开关关闭时仍使用临时目录。
Returns:
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
为本次执行独占的临时 profile 目录,调用方负责在关闭浏览器后清理。
为本次执行使用的 profile 目录。调用方必须用
`_should_cleanup_browser_profile` 决定是否清理。
"""
sync_playwright, _timeout = _require_playwright()
playwright = sync_playwright().start()
profile_root = _browser_profile_root()
profile_root.mkdir(parents=True, exist_ok=True)
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
use_reused_dsv_session = reuse_dsv_session and _dsv_session_reuse_enabled()
runtime_profile_dir = (
_dsv_session_profile_dir()
if use_reused_dsv_session
else Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
)
runtime_profile_dir.mkdir(parents=True, exist_ok=True)
print(
"[browser] profile_mode="
f"{'dsv_session_reuse' if use_reused_dsv_session else 'temporary'}"
)
headless = _env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true"
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL")
executable_path = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH")
@@ -868,7 +940,10 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
keep_open_on_error = _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
playwright, context, page, runtime_profile_dir = _open_browser(
drop_dir,
reuse_dsv_session=connector_type == "dsv360",
)
with _profile_credentials(source):
if connector_type == "dsv360":
download = _download_dsv360_inventory(page, trigger, source)
@@ -889,7 +964,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
context.close()
if playwright is not None:
playwright.stop()
if runtime_profile_dir is not None:
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
@@ -1025,17 +1100,23 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if not isinstance(source, dict):
identity_errors.append(f"inventory_sources[{index}]")
continue
# Crane 的 Warehouse 由导出 Excel 中 reservation_id + part_number 解析,
# trigger 阶段不存在固定预期库位;其余来源仍必须绑定预期库位。
requires_expected_warehouse = str(
source.get("worker_connector_type") or source.get("connector_type") or ""
).strip().lower() not in {"crane", "crane_footprint"}
identity_errors.extend(
f"inventory_sources[{index}].{key}"
for key in _INVENTORY_V2_REQUIRED_FIELDS
if key not in {"schema_version", "task_no", "callback_id"}
and (key != "expected_warehouse_id" or requires_expected_warehouse)
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"callback_id": body.get("callback_id"),
"batch_run_no": run_no or None,
"business_status": "rejected",
"status": "rejected",
@@ -1108,7 +1189,10 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
entry_url = str((site_sources[0] or {}).get("entry_url") or (site_sources[0] or {}).get("login_url") or "").strip()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
playwright, context, page, runtime_profile_dir = _open_browser(
drop_dir,
reuse_dsv_session=site == "dsv360",
)
if site not in {"dsv360", "crane_footprint"}:
raise RuntimeError(f"unsupported connector_type: {site}")
export_fn = _export_dsv_inventory_source if site == "dsv360" else _export_crane_inventory_source
@@ -1147,12 +1231,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
for source in site_sources:
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
finally:
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)
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
# v2 业务结果必须原样保留逐源身份,后端据此绑定 SourceAttempt;
# Worker 不生成新身份,只从已校验的 trigger source 复制。