Files
syops/scripts/rpa/receipt/receipt_rpa_worker.py
T
hugo 12521489c6 refactor(rpa): 重构 scripts/rpa 目录结构与命名
按 common/connectors/inventory/receipt 分层并重命名

- common/: rpa_common, rpa_heartbeat, download_artifact_fallback,
  new_rpa_worker_secret
- connectors/dsv|crane/: 登录网站连接器,库存与收料共用
- inventory/: inventory_rpa_worker, run_inventory_batch_trigger,
  start_inventory_worker, register_inventory_worker_tasks
- receipt/: receipt_rpa_worker, receipt_crane/dbs_export,
  start_receipt_worker

保留裸 import + sys.path 引导;修正懒加载路径;
按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks;
同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。

(cherry picked from commit f3050164d0)
2026-08-28 17:23:39 +08:00

242 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""独立货代收料 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
import sys as _sys
from pathlib import Path as _Path
_RPA_ROOT = next(
(_c for _c in _Path(__file__).resolve().parents
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
if _dir not in _sys.path:
_sys.path.insert(0, _dir)
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
import receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
def _backend_dir() -> Path:
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
return _RPA_ROOT.parents[1] / '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_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 = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
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)
_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, SystemExit):
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
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()