feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

+4 -1
View File
@@ -293,7 +293,7 @@ def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
() => {{
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const nodes = Array.from(document.querySelectorAll(
'#report-mega-legacy a, .mega-dropdown-menu a, .dropdown-menu a, [role="menuitem"], .dropdown-item'
'#report-mega-legacy a, #report-mega-legacy button, #report-mega-legacy [role="menuitem"], #report-mega-legacy [data-program], #report-mega-legacy [data-report], #report-mega-legacy .dropdown-item, #report-mega-legacy .menu-item, #report-mega-legacy div, #report-mega-legacy span, .mega-dropdown-menu a, .mega-dropdown-menu button, .mega-dropdown-menu [role="menuitem"], .mega-dropdown-menu [data-program], .mega-dropdown-menu [data-report], .mega-dropdown-menu .dropdown-item, .mega-dropdown-menu .menu-item, .mega-dropdown-menu div, .mega-dropdown-menu span, .dropdown-menu a, .dropdown-menu button, .dropdown-menu [role="menuitem"], .dropdown-menu [data-program], .dropdown-menu [data-report], .dropdown-menu .dropdown-item, .dropdown-menu .menu-item, .dropdown-menu div, .dropdown-menu span'
));
const visible = nodes
.filter((node) => {{
@@ -307,6 +307,9 @@ def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
text: textOf(node),
className: node.className || '',
ariaExpanded: node.getAttribute('aria-expanded') || '',
tagName: node.tagName || '',
dataProgram: node.getAttribute('data-program') || '',
dataReport: node.getAttribute('data-report') || '',
x: Math.round(rect.x),
y: Math.round(rect.y),
}};
+26 -3
View File
@@ -181,6 +181,14 @@ def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000)
return True
except Exception:
pass
# DSV 的部分 Program(例如 Salt Lake City/AWSSL)由自定义 div/span 渲染,
# 不一定带 dropdown-item、a 或 role=menuitem;精确文本定位可命中其嵌套节点。
try:
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
if page.locator(container).get_by_text(text, exact=True).first.is_visible(timeout=timeout_ms):
return True
except Exception:
pass
probe = _collect_dsv_menu_probe(page, text)
for item in probe.get("matchedItems") or []:
item_text = str((item or {}).get("text") or "").strip().lower()
@@ -219,7 +227,9 @@ def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
deadline = time.monotonic() + 30
started_at = time.monotonic()
while time.monotonic() < deadline:
for selector in (
locator_candidates = [
(page.locator(selector).first, selector)
for selector in (
f"#report-mega-legacy a.dropdown-item:has-text({text_literal})",
f".mega-dropdown-menu a.dropdown-item:has-text({text_literal})",
f".dropdown-menu a.dropdown-item:has-text({text_literal})",
@@ -229,12 +239,25 @@ def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
f"#report-mega-legacy a:has-text({text_literal})",
f".mega-dropdown-menu a:has-text({text_literal})",
f".dropdown-menu a:has-text({text_literal})",
):
)
]
# 兼容自定义菜单节点及嵌套 span 文本(AWSSL 使用该类结构)。
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
try:
locator_candidates.append(
(page.locator(container).get_by_text(text, exact=True).first, f"{container} >> text={text!r}")
)
except Exception:
pass
for locator, selector in locator_candidates:
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=2_000)
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
try:
try:
locator.scroll_into_view_if_needed(timeout=1_000)
except Exception:
pass
if action == "hover":
locator.hover(timeout=1_500)
time.sleep(0.2)
+113 -9
View File
@@ -446,6 +446,25 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
_move_trigger(trigger_path, failed_dir, "callback failed")
_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",
"expected_warehouse_id",
)
def _inventory_v2_identity_errors(body: dict[str, Any]) -> list[str]:
"""校验库存 RPA v2 Trigger 身份;缺失字段时禁止启动外部库存操作。"""
missing = []
for key in _INVENTORY_V2_REQUIRED_FIELDS:
value = body.get(key)
if value is None or (isinstance(value, str) and not value.strip()):
missing.append(key)
if body.get("schema_version") != "shipping_inventory_rpa.v2":
missing.append("schema_version")
return list(dict.fromkeys(missing))
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
@@ -995,6 +1014,38 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if not isinstance(sources, list) or not sources:
trigger_path.unlink(missing_ok=True)
return
identity_errors = []
if body.get("schema_version") != "shipping_inventory_rpa.v2":
identity_errors.append("schema_version")
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
identity_errors.append("callback_id")
if body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()):
identity_errors.append("task_no")
for index, source in enumerate(sources):
if not isinstance(source, dict):
identity_errors.append(f"inventory_sources[{index}]")
continue
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 (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,
"batch_run_no": run_no or None,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": list(dict.fromkeys(identity_errors)),
"results": [],
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
@@ -1103,6 +1154,30 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
# v2 业务结果必须原样保留逐源身份,后端据此绑定 SourceAttempt;
# Worker 不生成新身份,只从已校验的 trigger source 复制。
source_identity_by_key = {
(
str(source.get("source_code") or "").strip().upper(),
str(source.get("expected_warehouse_id") or source.get("warehouse_id") or "").strip().upper(),
): source
for source in sources
if isinstance(source, dict)
}
for result in results:
source = source_identity_by_key.get((
str(result.get("source_code") or "").strip().upper(),
str(result.get("warehouse_id") or result.get("expected_warehouse_id") or "").strip().upper(),
))
if not source:
continue
for key in (
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id",
):
if key in source:
result[key] = source.get(key)
try:
batch_summary = _summarize_inventory_batch_results(results)
trigger_type = str(body.get("trigger_type") or "").strip()
@@ -1125,6 +1200,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
else:
callback_path = "/api/shipping-notice/rpa/inventory-batch-ready"
callback_payload = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"status": batch_summary["status"],
"success": batch_summary["success"],
@@ -1163,36 +1241,62 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
identity_errors = _inventory_v2_identity_errors({**body, "task_no": task_no})
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"task_no": task_no,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": identity_errors,
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
# 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。
identity = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": str(body.get("callback_id") or "").strip(),
"task_no": task_no,
"source_code": str(body.get("source_code") or ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else "") or "").strip().upper(),
"source_run_no": str(body.get("source_run_no") or "").strip(),
"run_no": str(body.get("source_run_no") or "").strip(),
"attempt_no": body.get("attempt_no") or body.get("attempt"),
"lease_token": str(body.get("lease_token") or "").strip(),
"candidate_set_id": body.get("candidate_set_id"),
"execution_id": body.get("execution_id"),
"gate_id": body.get("gate_id"),
"expected_warehouse_id": body.get("expected_warehouse_id"),
}
try:
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
**identity,
"status": "success",
"success": True,
"file_path": str(out_file),
"file_sha256": hashlib.sha256(out_file.read_bytes()).hexdigest(),
"rpa_mode": mode,
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
except NoInventoryDataError as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
**identity,
"status": "skipped",
"success": False,
"skipped": True,
"skip_reason": "no_inventory_data",
"message": str(exc),
"rpa_mode": mode,
"source_code": (
(body.get("rpa_inventory_source") or {}).get("source_code")
if isinstance(body.get("rpa_inventory_source"), dict)
else None
),
})
if trigger_path.exists():
trigger_path.unlink(missing_ok=True)
@@ -1202,7 +1306,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
**identity,
"status": "failed",
"success": False,
"skipped": False,
+120
View File
@@ -0,0 +1,120 @@
[CmdletBinding()]
param(
[string]$DatabaseUrl = "",
[int]$KbConcurrency = 1,
[int]$ShippingConcurrency = 1,
[switch]$SkipMigrate
)
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$backendDir = Join-Path $repoRoot "backend"
$frontendDir = Join-Path $repoRoot "frontend"
$venvPython = Join-Path $backendDir "venv\Scripts\python.exe"
if (-not (Test-Path $venvPython)) { throw "Backend virtualenv not found: $venvPython" }
if (-not (Test-Path $frontendDir)) { throw "Frontend directory not found: $frontendDir" }
function Import-DotEnv {
param([string]$Path)
if (-not (Test-Path $Path)) { return }
foreach ($line in Get-Content $Path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') { continue }
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")))) {
$value = $value.Substring(1, $value.Length - 2)
}
Set-Item "env:$name" $value
}
}
}
function Stop-HxopsProcess {
param([string]$Pattern)
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -and $_.CommandLine -match $Pattern } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
}
function Stop-Port {
param([int]$Port)
Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique |
ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue }
}
Import-DotEnv (Join-Path $repoRoot ".env.shared")
Import-DotEnv (Join-Path $repoRoot ".env.dev")
Import-DotEnv (Join-Path $repoRoot ".env.local")
if (-not [string]::IsNullOrWhiteSpace($DatabaseUrl)) { $env:DATABASE_URL = $DatabaseUrl }
Write-Host "[cleanup] stopping HXOPS processes and ports..." -ForegroundColor Yellow
Stop-HxopsProcess 'run\.py|worker_kb\.py|worker_shipping\.py|worker_shipping_notice\.py|worker_scheduler\.py'
Stop-Port 5052
Stop-Port 8881
Start-Sleep -Milliseconds 800
if (-not $SkipMigrate) {
$env:FLASK_APP = "run.py"
$env:FLASK_ENV = "development"
$env:ENV_NAME = "dev"
Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan
Push-Location $backendDir
try { & $venvPython -m flask db upgrade } finally { Pop-Location }
if ($LASTEXITCODE -ne 0) { throw "Database migration failed with exit code $LASTEXITCODE" }
}
$jobs = @()
$jobs += Start-Job -Name "hxops-backend" -ScriptBlock {
param($dir, $python, $db)
if ($db) { $env:DATABASE_URL = $db }
Set-Location $dir
& $python .\run.py 2>&1
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL)
$jobs += Start-Job -Name "hxops-frontend" -ScriptBlock {
param($dir)
Set-Location $dir
npm run dev 2>&1
} -ArgumentList @($frontendDir)
$jobs += Start-Job -Name "hxops-kb-worker" -ScriptBlock {
param($dir, $python, $db, $concurrency)
if ($db) { $env:DATABASE_URL = $db }
$env:ENV_NAME = "dev"
$env:KB_WORKER_CONCURRENCY = "$concurrency"
Set-Location $dir
& $python .\worker_kb.py 2>&1
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $KbConcurrency)
$jobs += Start-Job -Name "hxops-shipping-worker" -ScriptBlock {
param($dir, $python, $db, $concurrency)
if ($db) { $env:DATABASE_URL = $db }
$env:ENV_NAME = "dev"
$env:SHIPPING_NOTICE_WORKER_CONCURRENCY = "$concurrency"
Set-Location $dir
& $python .\worker_shipping.py 2>&1
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $ShippingConcurrency)
Write-Host "[startup] backend, frontend, kb-worker and shipping-worker are running in this IDE terminal." -ForegroundColor Green
Write-Host "[startup] Press Ctrl+C to stop all services." -ForegroundColor DarkGray
try {
while ($true) {
foreach ($job in $jobs) {
Receive-Job -Job $job -ErrorAction SilentlyContinue | ForEach-Object {
Write-Host "[$($job.Name)] $_"
}
if ($job.State -in @("Failed", "Stopped", "Completed")) {
Write-Warning "[$($job.Name)] state: $($job.State)"
}
}
Start-Sleep -Milliseconds 500
}
}
finally {
$jobs | Stop-Job -ErrorAction SilentlyContinue
$jobs | Remove-Job -Force -ErrorAction SilentlyContinue
Stop-HxopsProcess 'run\.py|worker_kb\.py|worker_shipping\.py|worker_shipping_notice\.py|worker_scheduler\.py'
Stop-Port 5052
Stop-Port 8881
}
+57
View File
@@ -0,0 +1,57 @@
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$backendDir = Join-Path $repoRoot "backend"
$python = Join-Path $backendDir "venv\Scripts\python.exe"
function Import-DotEnv {
param([string]$Path)
if (-not (Test-Path $Path)) { return }
foreach ($line in Get-Content $Path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') { continue }
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")))) {
$value = $value.Substring(1, $value.Length - 2)
}
Set-Item "env:$name" $value
}
}
}
function Stop-HxopsProcess {
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -and $_.CommandLine -match 'run\.py|worker_kb\.py|worker_shipping\.py|worker_shipping_notice\.py|worker_scheduler\.py' } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
}
function Stop-Port {
param([int]$Port)
Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique |
ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue }
}
if (-not (Test-Path $python)) { throw "Backend virtualenv not found: $python" }
Import-DotEnv (Join-Path $repoRoot ".env.shared")
Import-DotEnv (Join-Path $repoRoot ".env.dev")
Import-DotEnv (Join-Path $repoRoot ".env.local")
Write-Host "[cleanup] stopping HXOPS processes and ports..." -ForegroundColor Yellow
Stop-HxopsProcess
Stop-Port 5052
Stop-Port 8881
Start-Sleep -Milliseconds 800
$env:FLASK_APP = "run.py"
$env:FLASK_ENV = "development"
$env:ENV_NAME = "dev"
Push-Location $backendDir
try {
Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan
& $python -m flask db upgrade
if ($LASTEXITCODE -ne 0) { throw "Database migration failed with exit code $LASTEXITCODE" }
} finally {
Pop-Location
}
Write-Host "[prepare] completed" -ForegroundColor Green