feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误

- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
This commit is contained in:
hugo committed 2026-09-30 00:20:06 +08:00
1 parent 993e581135
commit abf3d48927
144 files changed
+10161 -2132

No files matched your search

@@ -1,4 +1,11 @@
"""Crane 收料报表导出适配器。"""
"""
scripts/freight_rpa/receipt/receipt_crane_export.py
用途:Crane 收料报表导出适配器——固定 Inbound Details,委托共享 crane_report_export。
依赖:crane_report_export、crane_session。
逻辑:receipt_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
driver 在 Playwright 未返回 Download 时做目录兜底。
"""
from __future__ import annotations
@@ -36,7 +43,12 @@ 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 文件,禁止按最新历史文件选择。"""
"""
创建并下载唯一 Description 对应的 Crane Inbound Details 文件。
核心逻辑:固定 scheduled_report_name=Inbound Details;把 unit.__download_dir
写入 source,供共享 crane_report_export 目录兜底(对齐库存)。
"""
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')
@@ -50,6 +62,8 @@ def export_receipt_report(
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Inbound Details',
# 与库存/DBS 同构:供 crane_report_export 在 Playwright 未返回 Download 时目录兜底。
'__download_dir': str(unit.get('__download_dir') or ''),
}
return crane_report_export.export_crane_inventory_report(
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
@@ -1,4 +1,14 @@
"""DBS 收料报表导出适配器。"""
"""
scripts/freight_rpa/receipt/receipt_dbs_export.py
用途:DBS 收料报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
依赖:connectors/dsv/dsv_report_export。
逻辑:receipt_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
source 写入 __export_kind__=receipt,共享驱动用 Receipt Detail 就绪/行探针。
query_parameters 原样下发;仅当 unit.warehouse_id 有值时追加单值 Warehouse
(兼容旧 trigger);空条件表示使用页面默认,不强制 Warehouse。
"""
from __future__ import annotations
@@ -22,21 +32,68 @@ 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 = {
def build_receipt_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
"""
将收料 unit 组装为共享 dsv_report_export 可消费的 source。
核心逻辑:report_path_json → navigation(驱动只读 navigation/query);
parameters 取自 query_parameters_json;有 warehouse_id 时追加单值 Warehouse。
Args:
unit: 收料 trigger 单元(含 report_path_json / query_parameters_json 等)。
entry_url: 该 Profile 分组的登录入口 URL。
Returns:
与库存 trigger source 同构的 dict,可供 prepare_dsv_batch_export_step 与导出使用。
"""
report_path = dict(unit.get('report_path_json') or {})
source: dict[str, Any] = {
'entry_url': entry_url,
'report_path_json': dict(unit.get('report_path_json') or {}),
'report_path_json': report_path,
# 与库存 trigger 同构:Source.report_path_json → navigation,供菜单导航使用。
'navigation': report_path,
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
# 显式标记收料导出:共享 dsv_report_export 用 Receipt Detail 就绪/行探针,不用库存字段。
'__export_kind__': 'receipt',
}
# 兼容旧 trigger:仅当排程曾写入 warehouse_id 时追加,避免与参数里已有 Warehouse 双写需由旧载荷保证互斥。
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)
if warehouse_id:
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
return source
def export_receipt_report(
page: Any,
unit: dict[str, Any],
*,
entry_url: str,
skip_navigation: bool = False,
) -> Any:
"""
在既有 DBS 登录态内执行收料路径与受控非日期条件。
核心逻辑:组装 source 后委托 export_dsv_inventory_source;会话登录与参数页复用
由 Worker 侧 prepare_dsv_batch_export_step 完成。skip_navigation=True 时跳过菜单导航,
直接在已就绪的参数页填参导出(同导航批内复用)。
Args:
page: 当前 Playwright Page(批内复用同一 tab,禁止每源 new_page)。
unit: 收料 trigger 单元。
entry_url: 登录入口 URL。
skip_navigation: 为 True 时跳过报表菜单导航(参数页已由 prepare 就绪)。
Returns:
Playwright Download 对象。
"""
source = build_receipt_dsv_source(unit, entry_url=entry_url)
return dsv_report_export.export_dsv_inventory_source(
page,
{'action': 'receipt_export_batch'},
source,
skip_navigation=skip_navigation,
)
@@ -0,0 +1,106 @@
"""
scripts/freight_rpa/receipt/receipt_excel_empty.py
用途:收料 Excel「有表头无明细」判空(真相源,对齐库存 Excel 判空)。
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
逻辑:receipt_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail)
不得当成表头,否则真表头会被误判为明细导致假 success。
"""
from __future__ import annotations
from pathlib import Path
class NoReceiptDataError(RuntimeError):
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
def _normalize_row_joined(row: tuple | list) -> str:
"""
将一行单元格规范为小写比较串。
核心逻辑:换行压成空格(SSRS 表头常为 External\\nASN #),去空白后用 | 拼接。
"""
parts: list[str] = []
for cell in row:
if cell is None:
continue
text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip()
if text:
parts.append(text.lower())
return ' | '.join(parts)
def is_receipt_excel_header_row(joined: str) -> bool:
"""
判断是否为收料列标题行(非报表标题行)。
核心逻辑:要求 External ASN / WMS Receipt / Supplier ID+AWS Sku 等组合特征;
单独含 receipt(如「AWS Receipt Detail」)不得命中。
"""
if not joined:
return False
if 'external asn' in joined and (
'wms receipt' in joined
or 'aws sku' in joined
or 'supplier id' in joined
or 'supplier' in joined
):
return True
if 'warehouse' in joined and 'external asn' in joined:
return True
if 'supplier id' in joined and 'aws sku' in joined:
return True
return False
def receipt_excel_has_detail_rows(path: Path) -> bool | None:
"""
判断收料 Excel 列标题之后是否有明细行。
核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None
(不强制 empty,由结构校验兜底)。
Returns:
True: 有明细;False: 有表头无明细;None: 未识别表头形态。
"""
try:
from openpyxl import load_workbook
except ImportError:
return None
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception:
return None
try:
worksheet = workbook.active
if worksheet is None:
return None
header_idx: int | None = None
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
joined = _normalize_row_joined(row or ())
if not joined:
continue
if header_idx is None:
if is_receipt_excel_header_row(joined):
header_idx = idx
continue
if idx > header_idx:
return True
if header_idx is None:
return None
return False
finally:
workbook.close()
def enforce_receipt_excel_not_empty(path: Path) -> None:
"""
有表头无明细时记为无收料(NoReceiptDataError → empty / no_receipt_data)。
Raises:
NoReceiptDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
"""
if receipt_excel_has_detail_rows(path) is False:
raise NoReceiptDataError('no_receipt_data')
+534 -44
View File
@@ -1,4 +1,13 @@
"""独立货代收料 RPA Worker:仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。"""
"""
scripts/freight_rpa/receipt/receipt_rpa_worker.py
用途:独立货代收料 RPA Worker——仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
receipt_excel_empty、receipt_dbs_export、receipt_crane_export、connectors/dsv/dsv_report_export。
逻辑:排程写入 receipt trigger → 本进程领取并按 connector/profile 分组串行导出 →
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
"""
from __future__ import annotations
@@ -33,12 +42,35 @@ if _RPA_ROOT is not None:
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
import rpa_heartbeat # noqa: E402
import worker_logging # noqa: E402
import worker_disk_cleanup # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
import dsv_report_export # noqa: E402
import receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
from receipt_excel_empty import ( # noqa: E402
NoReceiptDataError,
enforce_receipt_excel_not_empty as _enforce_receipt_excel_not_empty,
)
_EXPORT_UNIT_MAX_ATTEMPTS = 2
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
_RECEIPT_EXCEL_MIN_BYTES = 512
# 结构校验可用较宽标记;「有表头无明细」判空见 receipt_excel_empty(禁止用单字 receipt 当表头)。
_RECEIPT_EXCEL_HEADER_MARKERS = (
'receipt',
'inbound',
'asn',
'po number',
'po #',
'supplier id',
'aws sku',
'sku',
'quantity',
'received',
)
def _backend_dir() -> Path:
@@ -66,20 +98,61 @@ def _require_dir(variable: str) -> Path:
return path
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元结果,认证密钥从进程 Secret 注入。"""
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
"""向 HXOPS 收料 RPA API 上报;认证密钥从进程 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',
f'{base}{path}',
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:
with urllib.request.urlopen(request, timeout=timeout) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError(f'receipt callback failed: HTTP {response.status}')
raise RuntimeError(f'receipt rpa callback failed: HTTP {response.status} path={path}')
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元终态结果。"""
_post_rpa('/api/shipping-notice/rpa/receipt-batch-ready', payload)
def _mark_unit_processing(unit: dict[str, Any]) -> None:
"""开始导出前标记 processing;失败不影响导出主链路。"""
try:
_post_rpa(
'/api/shipping-notice/rpa/receipt-unit-progress',
{
'schema_version': 'shipping_receipt_rpa.v1',
'callback_id': unit.get('callback_id'),
'status': 'processing',
},
)
except Exception as exc:
print(f'[receipt-unit] processing progress failed: {exc}', file=_sys.stderr)
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
"""每完成一笔导出回传累计进度(对齐库存 inventory-batch-progress)。"""
schedule_run_id = body.get('schedule_run_id')
if schedule_run_id is None:
return
try:
_post_rpa(
'/api/shipping-notice/rpa/receipt-batch-progress',
{
'schema_version': 'shipping_receipt_rpa.v1',
'schedule_run_id': schedule_run_id,
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
'success_count': int(counts.get('success') or 0),
'skipped_count': int(counts.get('empty') or 0),
'failed_count': int(counts.get('failed') or 0),
},
)
except Exception as exc:
print(f'[receipt-batch] progress callback failed: {exc}', file=_sys.stderr)
@contextmanager
@@ -116,25 +189,73 @@ def _profile_credentials(unit: dict[str, Any]):
os.environ[name] = old_value
def _open_browser(download_dir: Path, reuse_session: bool = False):
def _session_reuse_enabled() -> bool:
"""
收料是否复用持久浏览器 Profile。
核心逻辑:对齐库存——未设置或空值时默认开启;仅显式 false 时关闭。
"""
raw = env('FREIGHT_RPA_WORKER_SESSION_REUSE')
if raw is None or str(raw).strip() == '':
return True
return str(raw).strip().strip("\"'").lower() == 'true'
def _sanitize_profile_dir_segment(value: str) -> str:
"""将 connector / profile_code 收成可作目录名的安全片段。"""
text = str(value or '').strip()
cleaned = ''.join(ch if (ch.isalnum() or ch in '-_') else '_' for ch in text)
return (cleaned[:96] or 'default')
def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
"""
按 connector + RPA Profile 隔离的持久收料会话目录。
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
命名空间分离,避免串 Cookie);禁止所有收料源共用单一 receipt_session。
"""
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
code = _sanitize_profile_dir_segment(profile_code)
return profile_root / f'{connector}__{code}_session'
def _open_browser(
download_dir: Path,
*,
reuse_session: bool = False,
connector_type: str = '',
profile_code: str = '',
):
"""为一个 receipt Profile 分组创建浏览器上下文,组内登录一次、串行导出。
reuse_session=False(默认):一次性临时 Profile(receipt_* 前缀),批次结束即删,隔离最干净。
reuse_session=True:持久会话 Profile(receipt_session),跨批次复用登录态,适用于同日重跑/重试;
持久目录命中磁盘清理的 *_session 豁免规则,不会被孤儿清理删除。
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
否则一次性临时 Profile(receipt_* 前缀),批次结束即删。
"""
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('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
if reuse_session:
runtime_profile = profile_root / 'receipt_session'
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
if use_reused:
runtime_profile = _session_profile_dir(connector_type, profile_code)
runtime_profile.mkdir(parents=True, exist_ok=True)
profile_mode = 'session_reuse'
else:
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
profile_mode = 'temporary'
print(
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
f'profile={profile_code or "-"} dir={runtime_profile.name!r}'
)
playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
options: dict[str, Any] = {
'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true',
'accept_downloads': True,
'downloads_path': str(download_dir),
}
channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
if channel:
options['channel'] = channel
@@ -144,19 +265,183 @@ def _open_browser(download_dir: Path, reuse_session: bool = False):
return playwright, context, page, runtime_profile
def _save_download(download: Any, drop_dir: Path, unit: dict[str, Any]) -> Path:
"""保存本单元下载文件到 receipt drop 并计算 callback 需要的身份。"""
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
"""
在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
核心逻辑:对齐库存 Worker——新开空白页并关闭旧页;Cookie 仍在 context 内,
仅用于会话准备失败后的一次完整登录重试,禁止作为常态「每源新开空白页」。
Args:
context: 已建立登录态的 Playwright browser context。
current_page: 上一站页面;关闭以避免报表 iframe / 下载菜单残留。
Returns:
可重新进入收料报表的空白页面。
"""
next_page = context.new_page()
next_page.set_default_timeout(browser_timeout_ms())
if current_page is not None:
try:
current_page.close()
except Exception as exc:
print(f'[receipt-batch] close previous page failed: {exc}', file=_sys.stderr)
return next_page
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
"""
导出前拍摄下载目录已有文件名,供目录兜底识别「本次新文件」。
核心逻辑:仅收集普通文件名;目录不可读时返回空集合(对齐库存)。
"""
try:
return {path.name for path in drop_dir.iterdir() if path.is_file()}
except OSError:
return set()
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
"""判断是否为 Playwright 页面/上下文已关闭导致的落盘失败。"""
message = str(exc).lower()
return 'has been closed' in message or 'target closed' in message or 'targetclosed' in message
def _persist_download_to_dest(
download: Any,
dest: Path,
*,
drop_dir: Path,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> None:
"""
将 Playwright Download 落到规范路径;浏览器已关闭时走 downloads_path 目录兜底。
核心逻辑:对齐库存 `_persist_download_to_dest`——先 save_as,TargetClosed
再按 baseline 等待稳定新文件后搬迁。
"""
try:
download.save_as(str(dest))
return
except Exception as exc:
if not _is_playwright_target_closed_error(exc):
raise
print(
f'[receipt-artifact] stage=download_save status=fallback '
f'reason=browser_closed path={dest.name!r}',
file=_sys.stderr,
)
artifact = _wait_for_new_download_file(
download_dir=drop_dir,
baseline_names=set(baseline_names or ()),
timeout_seconds=fallback_timeout_seconds,
)
if artifact is None:
raise
artifact.save_as(str(dest))
def _receipt_download_name(
batch_run_no: str,
source_code: str,
warehouse_id: str | None,
*,
suffix: str = '.xlsx',
) -> str:
"""
收料落盘文件名,对齐库存 `_batch_download_name`。
核心逻辑:`receipt_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
不写入 callback_id(关联仍靠 callback JSON)。
Args:
batch_run_no: trigger 顶层批次号。
source_code: 库存源编码(辨识用)。
warehouse_id: 可选仓码;空则 NA。
suffix: 扩展名,默认 .xlsx。
Returns:
安全化后的文件名(不含目录)。
"""
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'receipt'
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
return f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
def _save_download(
download: Any,
drop_dir: Path,
unit: dict[str, Any],
*,
batch_run_no: str,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> Path:
"""
保存本单元下载文件到 receipt drop;必要时在浏览器关闭后走目录兜底。
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
"""
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))
target = drop_dir / _receipt_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
suffix=suffix,
)
_persist_download_to_dest(
download,
target,
drop_dir=drop_dir,
baseline_names=baseline_names,
fallback_timeout_seconds=fallback_timeout_seconds,
)
if target.stat().st_size <= 0:
raise RuntimeError('receipt report download is empty')
return target
def _validate_receipt_excel(path: Path) -> None:
"""
校验收料 Excel 可打开且具备报表基本结构。
核心逻辑:对齐库存 `_validate_inventory_excel`——拒过小/HTML 伪装文件;
前几行或 sheet 标题须含收料报表特征,避免错误页当 success 归档。
"""
size = path.stat().st_size
if size < _RECEIPT_EXCEL_MIN_BYTES:
raise RuntimeError(f'downloaded receipt Excel is too small ({size} bytes)')
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError('openpyxl required to validate receipt Excel') from exc
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 _RECEIPT_EXCEL_HEADER_MARKERS):
if 'receipt' not in title and 'inbound' not in title:
raise RuntimeError('downloaded file is not valid Excel: missing receipt report headers')
finally:
workbook.close()
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'):
@@ -175,58 +460,263 @@ def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
_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 _report_empty(unit: dict[str, Any], exc: NoReceiptDataError) -> None:
"""无业务明细的合法结果:回调 empty + no_receipt_data(后端 finalize 计 skipped)。"""
print(f'[receipt-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
_post_callback({
'schema_version': 'shipping_receipt_rpa.v1',
'callback_id': unit.get('callback_id'),
'status': 'empty',
'error_code': 'no_receipt_data',
'error_message': str(exc)[:2000] or 'no_receipt_data',
})
def _is_login_session_error(exc: BaseException) -> bool:
"""登录/会话类偶发异常可干净页重试;凭据校验类不重试。"""
message = str(exc).lower()
login_related = any(token in message for token in ('login', 'session', 'oauth'))
credential_mismatch = any(token in message for token in ('invalid', 'verification'))
return login_related and not credential_mismatch
def _export_unit_download(
*,
connector: str,
unit: dict[str, Any],
group: list[dict[str, Any]],
index: int,
login_url: str,
page: Any,
context: Any,
drop_dir: Path,
) -> tuple[Any, Any]:
"""
导出单个收料单元的 Playwright Download;必要时干净页重试会话。
Returns:
(download, page):download 为 Playwright Download;page 可能已切换为干净页。
"""
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
source = receipt_dbs_export.build_receipt_dsv_source(unit, entry_url=login_url)
previous_unit = group[index - 1] if index > 0 else None
previous_source = (
receipt_dbs_export.build_receipt_dsv_source(previous_unit, entry_url=login_url)
if previous_unit is not None else None
)
skip_navigation = False
try:
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, previous_source, source, index=index,
)
)
except Exception as exc:
if not _is_login_session_error(exc):
raise
print(
f'[receipt-batch] dbs session prepare failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, None, source, index=0,
)
)
download = receipt_dbs_export.export_receipt_report(
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
)
return download, page
first_in_profile = index == 0
try:
download = 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=first_in_profile,
)
return download, page
except Exception as exc:
# Crane 无 DBS 式 prepare 步骤:导出期登录/会话失败时干净页 + 强制首源登录重试一次。
if not _is_login_session_error(exc):
raise
print(
f'[receipt-batch] crane session failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
download = 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=True,
)
return download, page
def _write_mock_receipt_excel(path: Path) -> None:
"""Mock 模式写出带表头+一行明细的合法收料 Excel,便于走校验与 success 回调。"""
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = 'ReceiptDetail'
sheet.append(['ASN', 'PO Number', 'AWS Sku', 'Quantity Received'])
sheet.append(['ASN-MOCK-1', 'PO-1', 'SKU-1', 1])
workbook.save(path)
workbook.close()
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
"""落盘成功后上报 receipt-batch-ready(归档);调用方须放在导出重试之外。"""
_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(),
})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。"""
"""
按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
``receipt-batch-progress``(管理端实时笔数),再调 ``receipt-batch-ready`` 归档;
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
"""
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')
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'receipt').strip() or 'receipt'
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():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
for (connector, profile_code, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={profile_code} units={len(group)}')
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
reuse_session = env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false').lower() == 'true'
reuse_session = _session_reuse_enabled()
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(drop_dir, reuse_session=reuse_session)
resources = _open_browser(
drop_dir,
reuse_session=reuse_session,
connector_type=connector,
profile_code=profile_code,
)
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 = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
_mark_unit_processing(unit)
output: Path | None = None
terminal: tuple[str, BaseException] | None = None
# [RETRY] 仅导出/落盘/校验;ready 回调禁止进入本循环。
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
try:
if mock:
mock_path = drop_dir / _receipt_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
)
_write_mock_receipt_excel(mock_path)
output = mock_path
else:
download = 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)
baseline_names = _download_dir_baseline_names(drop_dir)
download, page = _export_unit_download(
connector=connector,
unit=unit,
group=group,
index=index,
login_url=login_url,
page=page,
context=context,
drop_dir=drop_dir,
)
output = _save_download(
download, drop_dir, unit, batch_run_no=batch_run_no,
baseline_names=baseline_names,
)
_validate_receipt_excel(output)
_enforce_receipt_excel_not_empty(output)
break
except NoReceiptDataError as exc:
terminal = ('empty', exc)
output = None
break
except Exception as exc:
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
print(
f'[receipt-batch] export failed {unit.get("source_code")} '
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
file=_sys.stderr,
)
time.sleep(_EXPORT_UNIT_RETRY_WAIT_SECONDS)
continue
terminal = ('failed', exc)
output = None
# [STEP] 导出循环外:轻量 progress + 终态回调(对齐库存 progress / 批末 ready)
if terminal is not None and terminal[0] == 'empty':
try:
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[receipt-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['empty'] += 1
_emit_batch_progress(body, progress_counts)
continue
if terminal is not None and terminal[0] == 'failed':
try:
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[receipt-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['failed'] += 1
_emit_batch_progress(body, progress_counts)
continue
if output is None:
continue
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
progress_counts['success'] += 1
_emit_batch_progress(body, progress_counts)
try:
_post_unit_ready(unit, output)
except Exception as callback_exc:
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
f'[receipt-unit] ready callback failed source={unit.get("source_code")} '
f'file={output.name}: {callback_exc}',
file=_sys.stderr,
)
_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()
# 会话复用模式保留 receipt_session 持久目录(命中清理豁免),仅一次性模式即删。
if profile_dir is not None and not reuse_session:
# 会话复用模式保留 {connector}__{profile}_session;一次性临时目录批次后删除。
if profile_dir is not None and not (reuse_session and _session_reuse_enabled()):
shutil.rmtree(profile_dir, ignore_errors=True)
@@ -5,7 +5,8 @@
.DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
根(各自在其中创建隔离的一次性子目录)。
根(各自按 connector+profile 隔离会话目录)。
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
@@ -15,7 +16,9 @@ param(
[string]$PythonExe = 'python.exe',
[switch]$Mock,
[switch]$Headless,
# 可选跨批次会话复用:持久 receipt_session Profile(同日重跑/重试免登录);默认一次性临时 Profile。
# 默认开启收料会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
[switch]$NoSessionReuse,
# 兼容旧文档:显式开启复用(现在默认已开启)。
[switch]$SessionReuse
)
@@ -35,8 +38,12 @@ $secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
}
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}(data 即 SMB 共享 hxops-rpa-*-data 的根,代码包 scripts 不进共享)。
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
if ($SessionReuse -and $NoSessionReuse) {
Write-Warning '同时指定 -SessionReuse 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
}
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
@@ -44,7 +51,7 @@ $processVars = [ordered]@{
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $(if ($SessionReuse) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'receipt\logs\worker.log'
@@ -55,7 +62,7 @@ $processVars = [ordered]@{
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop'
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile(各自在其中创建隔离的一次性子目录)。
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
# 本机磁盘保留:与库存 Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/receipt_* Profile)。
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
@@ -64,7 +71,7 @@ $processVars = [ordered]@{
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot"
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot sessionReuse=$sessionReuse"
& $PythonExe $workerScript
exit $LASTEXITCODE
}