Merge branch 'hugo-auto-transfer' into dev

# Conflicts:
#	backend/app/api/shipping_notice_tools.py
This commit is contained in:
hugo committed 2026-09-30 00:34:28 +08:00
commit 6cf71679b7
143 files changed
+10145 -2132

No files matched your search

@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_configuration_test.py
用途:编排库存站点测试导出、RPA 回调文件分析和自动启用判定。
用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。
逻辑:管理端发起批量/单站测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不自动启用站点、不关联订单任务。
"""
from __future__ import annotations
@@ -347,9 +347,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
'confirmed_profile_checksum': source.parsing_profile.checksum,
}
run.completed_at = datetime.utcnow()
# 空库存同样证明当前配置可查询;全部必要条件满足时自动投入正式运行。
from app.services.admin.shipping_inventory_service import activate_source_if_ready
activate_source_if_ready(source, actor_id=run.created_by)
db.session.commit()
return _payload(run)
if status != 'success':
@@ -401,7 +398,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
), None)
run.analysis_id = analysis.id; run.status = 'completed'
if current_profile_candidate is not None:
# 当前绑定的方案已验证时,测试应直接成为站点启用证据,无需管理员重复确认相同方案。
# 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。
run.stage = 'current_profile_verified'
run.result_json = {
'analysis': serialize_analysis(analysis),
@@ -410,9 +407,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
'current_profile_verified': True,
'profile_match_level': current_profile_candidate.get('level'),
}
# 当前绑定解析已由本次文件验证,无需管理员重复确认或手动启用。
from app.services.admin.shipping_inventory_service import activate_source_if_ready
activate_source_if_ready(source, actor_id=run.created_by)
else:
run.stage = 'ready_for_confirmation'
run.result_json = {'analysis': serialize_analysis(analysis)}
@@ -62,7 +62,11 @@ _WAREHOUSE_ID_HEADER_ALIASES = {
def inventory_snapshot_ttl_hours() -> int:
"""库存快照 TTL(小时);默认 24。"""
"""库存快照 TTL(小时);默认 24。
唯一权威来源为全局配置 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS;
不读取站点字段 snapshot_ttl_seconds(该字段已退出管理端配置面)。
"""
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS", 24)
try:
return max(int(raw), 1)
@@ -147,9 +147,17 @@ class PerSourcePrepareResult:
def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str:
"""构造 per-source 三元组唯一 run_no:PSR-<task_no>-<SOURCE>-<attempt_no>-<uuid8>。"""
suffix = uuid.uuid4().hex[:8].upper()
return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.task_no}-{attempt.source_code}-A{attempt.attempt_no}-{suffix}'
"""
构造 per-source 唯一 run_no:PSR-<attempt_id>(dumb ID)。
[设计] 编号只承担唯一标识与回调回显匹配,不嵌入业务语义——task_no/source_code/
attempt_no 已是 Attempt 行的结构化列,嵌入只会让长度被最长的语义段绑架
(2026-09-27:65 字符组合超 varchar(64) 致门禁 Attempt 终态失败;迁移
we9f0a1b2c3d 已加宽到 128,兜底旧格式与外部变化)。Worker 侧将该编号当作
不透明标签透传(文件命名/回调回显),不做解析,缩短对 Worker 零影响。
PSR- 前缀保留,用于与 legacy T-xxx 全局 run_no 家族区分。
"""
return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.id}'
def _latest_attempt(
@@ -649,7 +657,7 @@ def per_source_callback_handler(
# [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态
consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess)
# Run no format: PSR-<task>-<SOURCE>-A<N>-<uuid> → 排序按 attempt_no 前缀即可
# 迟到判断按 attempt_no 数值比较(run_no 自身为 PSR-<attempt_id>,不含序号语义)
try:
current_attempt_no = int(attempt.attempt_no)
except (TypeError, ValueError):
@@ -1,7 +1,7 @@
"""收料报表企微通知的管理员重发通道。
用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送
textcard 汇总 + 全部收料文件(scheduler_service._notify_schedule_run_wecom,
textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom,
与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的
强制重发能力(POST /receipt-report-files/<id>/resend),不触发 RPA。
依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。
@@ -1,13 +1,15 @@
"""收料 RPA callback 的原样归档服务。
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线);
每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)、
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.receipt_callback_bridge(惰性导入)、
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
success 分支再触发调拨证据同步(sync_and_commit_for_callback);两座桥都是记账
不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data);
有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步;
两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
"""
from __future__ import annotations
@@ -85,19 +87,36 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
status = str(payload.get('status') or '').strip().lower()
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
if status in {'empty', 'no_data'}:
unit.status = 'empty'; unit.error_code = None; unit.error_message = None; unit.finished_at = datetime.utcnow()
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
unit.status = 'empty'
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
before=before, after={'status': 'empty', 'callback_id': unit.callback_id},
metadata={'callback_status': status},
before=before,
after={
'status': 'empty',
'callback_id': unit.callback_id,
'error_code': unit.error_code,
'error_message': unit.error_message,
},
metadata={'callback_status': status, 'skip_reason': unit.error_code},
)
db.session.commit()
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
_advance_transfer_source_job(
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
)
from app.services.schedule.freight_receipt_rpa_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
@@ -111,9 +130,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
)
db.session.commit()
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
from app.services.schedule.freight_receipt_rpa_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
return {'unit_run_id': unit.id, 'status': 'failed'}
data = _read_receipt_callback_file(str(payload.get('file_path') or ''))
@@ -147,9 +170,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
)
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
from app.services.schedule.freight_receipt_rpa_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
@@ -1,4 +1,11 @@
"""独立收料 RPA trigger 的目录和载荷构造服务。"""
"""
backend/app/services/shipping_notice/receipt_rpa.py
用途:独立收料 RPA trigger 的目录解析与批量载荷原子写入。
依赖:Flask current_app 配置 FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR。
逻辑:freight_receipt_rpa_job / receipt_trigger_service 调用写 trigger;
Worker 仅消费 shipping_receipt_rpa.v1,绝不回落到库存 trigger 目录。
"""
from __future__ import annotations
@@ -18,35 +25,6 @@ def receipt_trigger_dir() -> Path | None:
return Path(value) if value else None
def receipt_warehouse_values(config: Any) -> list[str]:
"""从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。
Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单);
排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。
"""
values: list[str] = []
for item in (config.query_parameters_json or []):
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
continue
for raw in (item.get('values') or []):
cleaned = str(raw or '').strip()
if cleaned and cleaned not in values:
values.append(cleaned)
return values
def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]:
"""构建单个执行单元的受控条件:剥离 Warehouse 条件。
Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件,
快照里保留用户维护的 Warehouse 条件会与之重复冲突。
"""
return [
dict(item) for item in (config.query_parameters_json or [])
if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse')
]
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
trigger_dir = receipt_trigger_dir()
@@ -1,10 +1,11 @@
"""
services/shipping_notice/rpa_worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)。
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload trigger 前强制就绪检查;
AUTO_UPLOAD 开启时由 create_app 与履约链调用货代上传就绪校验(Worker/凭据/共享目录/环境隔离)。
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
shipping_notice.receipt_rpa(收料 trigger 目录)。
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。
"""
from __future__ import annotations
@@ -32,6 +33,9 @@ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
@@ -354,10 +358,15 @@ def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str
return None, "shared_sentinel_unreadable"
def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]:
def _verify_shared_trigger_mount(
trigger_dir: Path | None, *, require_sentinel: bool = True,
) -> tuple[bool, list[str]]:
"""
校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。
核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
Args:
trigger_dir: 共享 trigger 目录。
require_sentinel: 为 True 时在 test/prod 或配置了 scope 时校验哨兵。
"""
reasons: list[str] = []
if trigger_dir is None:
@@ -368,7 +377,7 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s
return False, ["trigger_dir_not_accessible"]
expected_scope = shared_scope_id()
if _shared_mount_check_required():
if require_sentinel and _shared_mount_check_required():
sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
if sentinel_reason:
reasons.append(sentinel_reason)
@@ -391,6 +400,27 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s
return not reasons, reasons
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自收料 Worker。
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
return True
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
expected = receipt_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual:
return False
try:
return Path(actual).resolve() == expected.resolve()
except OSError:
return False
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
expected_scope = shared_scope_id()
if not expected_scope:
@@ -472,14 +502,18 @@ def _check_rpa_worker_ready_for_capability(
trigger_dir: Path | None,
required_capability: str,
extra_reasons: list[str] | None = None,
worker_predicate: Any | None = None,
require_sentinel: bool = True,
) -> RpaWorkerReadiness:
"""
通用 Worker 就绪检查:心跳存储、共享挂载、能力声明与环境隔离。
Args:
trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力。
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(收料为 False)。
Returns:
RpaWorkerReadiness。
@@ -496,7 +530,9 @@ def _check_rpa_worker_ready_for_capability(
if _heartbeat_redis_required() and _redis_client() is None:
reasons.append("heartbeat_storage_unavailable")
_mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
_mount_ok, mount_reasons = _verify_shared_trigger_mount(
trigger_dir, require_sentinel=require_sentinel,
)
reasons.extend(mount_reasons)
backend_env = resolve_backend_rpa_environment()
@@ -505,6 +541,8 @@ def _check_rpa_worker_ready_for_capability(
workers, storage_read_failed = list_rpa_worker_heartbeats()
if storage_read_failed:
reasons.append("heartbeat_storage_unavailable")
if worker_predicate is not None:
workers = [worker for worker in workers if worker_predicate(worker)]
eligible_workers: list[dict[str, Any]] = []
enriched_workers: list[dict[str, Any]] = []
@@ -590,6 +628,60 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
)
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
"""
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=receipt_trigger_dir(),
required_capability=RECEIPT_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker,
require_sentinel=True,
)
def assert_receipt_rpa_worker_ready() -> None:
"""
写收料 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_receipt_rpa。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
result = check_receipt_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
if 'heartbeat_storage_unavailable' in result.reasons:
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
logger.warning(
'[rpa-heartbeat] receipt readiness blocked code=%s reasons=%s detail=%s',
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
'reasons': result.reasons,
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(receipt_trigger_dir() or ''),
},
)
def _freight_upload_config_reasons() -> list[str]:
"""
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
@@ -749,11 +841,25 @@ def assert_inventory_rpa_worker_ready() -> None:
)
def serialize_rpa_worker_status() -> dict[str, Any]:
"""管理端展示:在线 worker 列表与库存/货代上传就绪摘要(含详细 reasons)。"""
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
"""
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
Args:
scope: inventory(默认)或 receipt。
"""
from app.services.shipping_notice.rpa import upload_trigger_dir
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
normalized = str(scope or "inventory").strip().lower()
if normalized == "receipt":
readiness = check_receipt_rpa_worker_ready()
trigger_path = str(receipt_trigger_dir() or "")
else:
readiness = check_inventory_rpa_worker_ready()
trigger_path = str(inventory_trigger_dir() or "")
normalized = "inventory"
readiness = check_inventory_rpa_worker_ready()
freight_readiness = check_freight_upload_rpa_ready()
ttl_seconds = _heartbeat_ttl_seconds()
workers = []
@@ -777,6 +883,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]:
"ineligible_reasons": worker.get("ineligible_reasons") or [],
})
return {
"scope": normalized,
"ready": readiness.ready,
"message": readiness.message,
"detail_message": readiness.detail_message,
@@ -785,7 +892,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]:
"backend_environment": resolve_backend_rpa_environment(),
"shared_scope_id": shared_scope_id(),
"shared_sentinel_name": shared_sentinel_name(),
"trigger_dir": str(inventory_trigger_dir() or ""),
"trigger_dir": trigger_path,
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,