feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程

清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
hugo committed 2026-08-20 20:23:10 +08:00
1 parent 260465b72d
commit 1b6483a4ea
466 files changed
+32115 -33796

No files matched your search

+12
View File
@@ -2,6 +2,18 @@
Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 脚本在 Windows 货代终端上运行(或由本 PoC worker 在开发环境模拟)。
## 收料 RPA(独立 Worker)
收料使用 `freight_receipt_rpa_worker.py` 与 `start_receipt_rpa_worker.ps1`,仅消费 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR`,仅写 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR`,只回调 `/api/shipping-notice/rpa/receipt-batch-ready`。它可以与库存 Worker 同时运行,但四类目录(trigger、drop、browser profile、日志)绝不能共享。
启动示例:
```powershell
.\scripts\rpa\start_receipt_rpa_worker.ps1 -Environment test -ApiBase "http://<backend>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
收料 Worker 在同一排程内按 Profile 登录一次后串行处理单元;DBS 每个 Warehouse 导出一个文件且不传报表日期,Crane 无论 Profile 登录地址保存为门户首页还是其他页面,都会强制进入 `#/inbound-details-query`,不填写 Warehouse 或查询条件,直接使用页面默认条件生成/等待唯一 Description 对应的 `Inbound Details` 文件。不要把收料 trigger 手工复制到库存目录或反向复制。
## 先看这里:文档阅读路径
请按实际场景只走一条路径,不要把“首次部署”和“部署后日常运维”重复执行:
+6 -4
View File
@@ -285,9 +285,7 @@ def _fill_crane_report_parameters(
browser_timeout_ms: int,
select_or_fill: Callable[..., None],
) -> None:
"""
按 source.parameters 填充可选报表参数(Owner/Project);Warehouse 已废弃不再填写。
"""
"""按 source.parameters 填充可选报表参数(Owner/Project);Warehouse 已废弃不再填写。"""
parameters = source.get("parameters")
if isinstance(parameters, list) and parameters:
label_map = {
@@ -854,6 +852,11 @@ def _resolve_scheduled_report_file_name(
解析 Scheduled Reports 目标文件名(Name 列)。
核心逻辑:此为 Crane Driver 模板策略,只读环境变量与默认值,不允许连接或库存源配置覆盖。
"""
# 业务单元可声明固定的目标报表名;例如收料必须精确匹配 Inbound Details。
# 库存路径未声明时,仍只使用原有环境变量与默认名,保持库存 Worker 行为不变。
source_value = str((source or {}).get('scheduled_report_name') or '').strip()
if source_value:
return source_value
env_value = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_NAME", _CRANE_SCHEDULED_REPORT_NAME_DEFAULT) or "").strip()
return env_value or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT
@@ -1113,7 +1116,6 @@ def export_crane_inventory_report(
browser_timeout_ms=browser_timeout_ms,
select_or_fill=select_or_fill,
)
if download_mode == "file_download":
_click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms)
export_selector = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_EXPORT_SELECTOR")
@@ -0,0 +1,42 @@
"""Crane 收料报表导出适配器。"""
from __future__ import annotations
from typing import Any, Callable
from urllib.parse import urlsplit, urlunsplit
import crane_report_export
import crane_session
def _inbound_details_entry_url(login_url: str) -> str:
"""将复用的 Crane Profile 登录地址固定到收料 Inbound Details 路由。"""
parsed = urlsplit(str(login_url or '').strip())
if not parsed.scheme or not parsed.netloc:
raise RuntimeError('Crane receipt unit requires an absolute login_url')
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, '/inbound-details-query'))
def export_receipt_report(
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
) -> Any:
"""创建并下载唯一 Description 对应的 Crane Inbound Details 文件,禁止按最新历史文件选择。"""
report_path = dict(unit.get('report_path_json') or {})
if str(report_path.get('report_name') or '').strip() != 'Inbound Details':
raise RuntimeError('Crane receipt report must be Inbound Details')
entry_url = _inbound_details_entry_url(str(unit.get('login_url') or '').strip())
if first_in_profile:
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
crane_session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
crane_session.wait_for_crane_app_ready(page, entry_url, env=env, browser_timeout_ms=browser_timeout_ms)
# 旧 Crane driver 的 Scheduled Reports 匹配名来自 source;收料固定为
# Inbound Details,不能沿用库存的 OnHandDetails.xlsx 默认值。
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Inbound Details',
}
return crane_report_export.export_crane_inventory_report(
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
browser_timeout_ms=browser_timeout_ms, select_or_fill=select_or_fill, click_text=click_text,
)
+27
View File
@@ -0,0 +1,27 @@
"""DBS 收料报表导出适配器。"""
from __future__ import annotations
from typing import Any
import dsv_report_export
def export_receipt_report(page: Any, unit: dict[str, Any], *, entry_url: str, first_in_profile: bool) -> Any:
"""在既有 DBS 登录态内执行收料路径、Warehouse 与受控非日期条件。"""
source = {
'entry_url': entry_url,
'report_path_json': dict(unit.get('report_path_json') or {}),
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
}
warehouse_id = str(unit.get('warehouse_id') or '').strip()
if not warehouse_id:
raise RuntimeError('DBS receipt unit requires warehouse_id')
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
if first_in_profile:
dsv_report_export.ensure_dsv_session(page, entry_url)
return dsv_report_export.export_dsv_inventory_source(page, {'action': 'receipt_export_batch'}, source)
+228
View File
@@ -0,0 +1,228 @@
"""独立货代收料 RPA Worker:仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import time
import urllib.request
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
_RPA_DIR = Path(__file__).resolve().parent
if str(_RPA_DIR) not in __import__('sys').path:
__import__('sys').path.insert(0, str(_RPA_DIR))
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
import freight_receipt_crane_export # noqa: E402
import freight_receipt_dbs_export # noqa: E402
def _backend_dir() -> Path:
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
return Path(__file__).resolve().parents[2] / 'backend'
def _require_dir(variable: str) -> Path:
"""读取 receipt 专用目录;不回退至库存共享路径。"""
value = env(variable)
if not value:
raise SystemExit(f'Missing env: {variable}')
path = Path(value)
if not path.is_absolute():
path = (_backend_dir() / value).resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元结果,认证密钥从进程 Secret 注入。"""
key = env('SHIPPING_NOTICE_TOOL_API_KEY') or env('INTEGRATION_API_KEY')
if not key:
raise RuntimeError('Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY')
base = env('HXOPS_API_BASE', 'http://127.0.0.1:5052').rstrip('/')
request = urllib.request.Request(
f'{base}/api/shipping-notice/rpa/receipt-batch-ready',
data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), method='POST',
headers={'Content-Type': 'application/json', 'X-Integration-Key': key},
)
with urllib.request.urlopen(request, timeout=30) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError(f'receipt callback failed: HTTP {response.status}')
@contextmanager
def _profile_credentials(unit: dict[str, Any]):
"""在单个 Profile 分组内临时解密凭据并清理环境,绝不输出明文。"""
envelope = unit.get('credential_envelope') or {}
username_ciphertext = str(envelope.get('username_ciphertext') or '').strip()
password_ciphertext = str(envelope.get('password_ciphertext') or '').strip()
if not username_ciphertext and not password_ciphertext:
yield
return
if not username_ciphertext or not password_ciphertext:
raise RuntimeError('RPA Profile credentials are incomplete')
key = env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
if not key:
raise RuntimeError('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is required')
try:
fernet = Fernet(key.encode('ascii'))
username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8')
password = fernet.decrypt(password_ciphertext.encode('ascii')).decode('utf-8')
except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc
connector = str(unit.get('connector_type') or '').lower()
names = ('SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD')
before = {name: os.environ.get(name) for name in names}
os.environ[names[0]], os.environ[names[1]] = username, password
try:
yield
finally:
for name, old_value in before.items():
if old_value is None:
os.environ.pop(name, None)
else:
os.environ[name] = old_value
def _open_browser(download_dir: Path):
"""为一个 receipt Profile 分组创建临时浏览器上下文,组内登录一次、串行导出。"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError('Playwright is required for real receipt RPA') from exc
profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR')
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
channel = env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL')
if channel:
options['channel'] = channel
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options)
page = context.pages[0] if context.pages else context.new_page()
page.set_default_timeout(browser_timeout_ms())
return playwright, context, page, runtime_profile
def _save_download(download: Any, drop_dir: Path, unit: dict[str, Any]) -> Path:
"""保存本单元下载文件到 receipt drop 并计算 callback 需要的身份。"""
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
if suffix != '.xlsx':
raise RuntimeError('receipt report download must be xlsx')
safe_callback = ''.join(ch for ch in str(unit['callback_id']) if ch.isalnum() or ch in {'-', '_'})
target = drop_dir / f'receipt_{safe_callback}_{datetime.utcnow():%Y%m%d%H%M%S}.xlsx'
download.save_as(str(target))
if target.stat().st_size <= 0:
raise RuntimeError('receipt report download is empty')
return target
def _validate_unit(unit: dict[str, Any]) -> None:
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
if not str(unit.get(key) or '').strip():
raise RuntimeError(f'receipt unit missing {key}')
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
raise RuntimeError('unsupported receipt connector_type')
parameters = list(unit.get('query_parameters_json') or [])
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
raise RuntimeError('receipt date filtering is forbidden')
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。"""
units = body.get('units')
if body.get('schema_version') != 'shipping_receipt_rpa.v1' or body.get('action') != 'receipt_export_batch' or not isinstance(units, list) or not units:
raise RuntimeError('invalid receipt trigger contract')
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
for item in units:
if not isinstance(item, dict):
raise RuntimeError('receipt unit must be object')
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items():
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true'
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(drop_dir)
playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]):
for index, unit in enumerate(group):
try:
if mock:
from openpyxl import Workbook
mock_path = drop_dir / f"receipt_{unit['callback_id'].replace(':', '_')}.xlsx"
workbook = Workbook(); workbook.active.append(['Receipt RPA mock']); workbook.save(mock_path); workbook.close()
output = mock_path
else:
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
if index:
page = context.new_page(); page.set_default_timeout(browser_timeout_ms())
download = freight_receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
else:
download = freight_receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
output = _save_download(download, drop_dir, unit)
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
except Exception as exc:
_report_failure(unit, exc)
finally:
playwright, context, _page, profile_dir = resources
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if profile_dir is not None:
shutil.rmtree(profile_dir, ignore_errors=True)
def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_dir: Path) -> None:
"""原子领取一个 receipt trigger;成功归档 processed,callback 异常归档 failed。"""
claimed_dir = path.parent / 'processing'
claimed_dir.mkdir(parents=True, exist_ok=True)
claimed = claimed_dir / path.name
try:
path.replace(claimed)
except OSError:
return
try:
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
processed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(processed_dir / claimed.name)
except Exception:
failed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(failed_dir / claimed.name)
raise
def main() -> None:
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
processed_dir, failed_dir = trigger_dir / 'processed', trigger_dir / 'failed'
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
while True:
for path in sorted(trigger_dir.glob('*.json')):
try:
_claim_and_process(path, drop_dir, processed_dir, failed_dir)
except Exception as exc:
print(f'[receipt-trigger] failed {path.name}: {exc}')
time.sleep(poll)
if __name__ == '__main__':
main()
+21 -1
View File
@@ -1114,6 +1114,26 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
)
if identity_errors:
try:
# 即使 trigger 身份不完整,也保留每个 source 已携带的身份片段;
# 后端据此将可定位的 Attempt/Gate 立即收口,不能等轮询超时。
rejected_results = [
{
**{
key: source.get(key)
for key in (
"callback_id", "task_no", "source_code", "attempt_no",
"source_run_no", "lease_token", "candidate_set_id",
"execution_id", "gate_id", "expected_warehouse_id",
)
},
"status": "failed",
"success": False,
"error_code": "trigger_identity_invalid",
"error_message": "RPA trigger identity is invalid.",
}
for source in sources
if isinstance(source, dict)
]
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": body.get("callback_id"),
@@ -1122,7 +1142,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": list(dict.fromkeys(identity_errors)),
"results": [],
"results": rejected_results,
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
+57
View File
@@ -0,0 +1,57 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树启动独立货代收料 RPA Worker。
.DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
但二者不共享 trigger、drop、browser profile 或日志目录。
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
[Parameter(Mandatory = $true)][string]$ApiBase,
[Parameter(Mandatory = $true)][string]$WorkerRoot,
[Parameter(Mandatory = $true)][string]$SecretFile,
[string]$PythonExe = 'python.exe',
[switch]$Mock,
[switch]$Headless
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" }
$workerScript = Join-Path $WorkerRoot 'scripts\rpa\freight_receipt_rpa_worker.py'
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
$secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
}
$dataRoot = Join-Path $WorkerRoot 'data\freight_receipt_rpa'
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = 'msedge'
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR = Join-Path $dataRoot 'browser_profile'
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot"
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
}