Files
hugo 8102a1fe44 feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层
- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建
- 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步
- 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定
- backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中
- 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态
- 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist
- 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
2026-10-16 19:43:49 +08:00

324 lines
16 KiB
Python
Raw Permalink 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.
"""在途调拨测试的可控外部系统替身:FakeCapabilityClient / FakeRPA / FakeWeCom / FakeClock。
用途:让 L0/L1 测试在不接触真实 RPA、外部系统、企业微信的前提下覆盖全部业务分支,
并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。
依赖:标准库(dataclasses / decimal / zoneinfo)、capability_client(域类型)。
逻辑:FakeCapabilityClient 以 (料号, 拨出库位, 拨出批号) 三元组维护账面库存;
query_stock 一次返回组内全部命中行;create_transfer 为单据级签名(与 T9 真实
CapabilityClient 一致:operation_id + TransferOrder + final_only),按注入的
scenario 返回已分类的 TransferWriteResult(success / duplicate_success /
business_failed / technical_failed / result_unknown)。场景解析顺序:
write_scenarios_by_doc[单号] → write_scenarios[单内行溯源 Invoice] →
write_scenario 全局;final_only 仅记录进 call log(fake 不模拟 ERP 内部
幂等细节,重触发命中已存在单证 → duplicate_success + 原单号)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from typing import Any
from zoneinfo import ZoneInfo
from app.services.in_transit_transfer.capability_client import (
ExternalQueryTimeoutError,
StockQueryResult,
StockRow,
TransferWriteResult,
)
class FakeClock:
"""固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。"""
def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None:
self.now_value = datetime.fromisoformat(iso)
def now(self) -> datetime:
"""返回当前固定时刻(带 Asia/Shanghai 时区)。"""
return self.now_value
def advance(self, *, seconds: int = 0, days: int = 0) -> None:
"""按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。"""
self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
if seconds:
self.now_value = self.now_value + timedelta(seconds=seconds)
if days:
self.now_value = self.now_value + timedelta(days=days)
@dataclass(frozen=True)
class ExternalCallRecord:
"""FakeCapabilityClient 单次调用的事实记录;测试断言优先读取该记录。"""
operation_id: str
external_org: str
call_seq: int
returned_status: str
method: str
# 查询调用:记录目标元组;写调用(单据级):单头字段 + 完整行集 + final_only。
targets: tuple[tuple[str, str, str], ...] = ()
invoice_no: str = ""
document_no: str | None = None
doc_no: str = ""
submit_timestamp: str = ""
doc_date: str = ""
posting_date: str = ""
final_only: bool = False
on_nonfinal_success: bool = False
lines: tuple[dict, ...] = ()
class FakeCapabilityClient:
"""可注入账面库存与响应场景的外部系统客户端替身;每次调用写入 call log。"""
def __init__(self) -> None:
self.inventory: dict[tuple[str, str, str], Decimal] = {}
# ERP 库存行单位(img09)按三元组维护;与真实 ERP 契约一致默认恒非空(EA),
# 需要「ERP 未给单位」场景时显式 seed unit=""。
self.stock_units: dict[tuple[str, str, str], str] = {}
self.documents: dict[str, str] = {}
self.verified_posted: dict[str, bool] = {}
self.query_scenario: str = "normal"
self.write_scenario: str = "success"
# 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。
self.write_scenarios: dict[str, str] = {}
# 按单号覆盖写场景(Key=doc_no,T10 单据级执行主键);优先级最高。
self.write_scenarios_by_doc: dict[str, str] = {}
self.call_log: list[ExternalCallRecord] = []
self._seq = 0
# -- 控制注入 ----------------------------------------------------------
def seed_stock(self, material_no: str, warehouse_code: str, lot_no: str,
quantity: str | int | Decimal, *, unit: str = "EA") -> None:
"""设置指定 (料号, 仓库, 批号) 的账面库存与 ERP 单位(键=查询契约三元组)。
unit 模拟 ERP img09 库存单位(调拨行交易单位唯一来源);默认 "EA" 对应
ERP「img09 恒非空」契约;显式传空串可构造「ERP 未给单位」场景。
"""
key = (str(material_no).strip(), str(warehouse_code).strip(), str(lot_no).strip())
self.inventory[key] = Decimal(str(quantity))
self.stock_units[key] = str(unit)
def clear_stock(self) -> None:
"""清空全部账面库存(模拟 外部系统 库存被移走/未上账)。"""
self.inventory.clear()
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
"""预置某 Invoice 已存在的单据(幂等重复场景)。"""
self.documents[str(invoice_no).strip()] = document_no
self.verified_posted[str(invoice_no).strip()] = posted
def set_query_scenario(self, scenario: str) -> None:
"""normal | inventory_not_found | timeout | error。"""
self.query_scenario = scenario
def set_write_scenario(self, scenario: str) -> None:
"""success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。"""
self.write_scenario = scenario
# -- 外部系域能力 ----------------------------------------------------------
def query_stock(self, *, operation_id: str, external_org: str,
targets: list) -> StockQueryResult:
"""按组织批量返回库存行;timeout/error 场景按客户端语义抛错。"""
self._seq += 1
target_keys = [
(str(t.material_no).strip(), str(t.warehouse_code).strip(), str(t.lot_no).strip())
for t in targets
]
if self.query_scenario == "timeout":
raise ExternalQueryTimeoutError(f"query timeout operation_id={operation_id}")
if self.query_scenario == "error":
self.call_log.append(ExternalCallRecord(
operation_id, external_org, self._seq, "error", "query_stock",
targets=tuple(target_keys),
))
raise RuntimeError("binding not found for capability query_inventory")
rows: list[StockRow] = []
# 同键多目标去重(真实 ERP 每料号+批号仅一行账面;重复目标不重复计行,
# 否则 lookup 的同键累加会放大库存)。
for key in dict.fromkeys(target_keys):
if self.query_scenario == "inventory_not_found":
continue
if key in self.inventory:
rows.append(StockRow(
material_no=key[0], warehouse_code=key[1], lot_no=key[2],
quantity=self.inventory[key],
stock_unit=self.stock_units.get(key, "EA"),
))
self.call_log.append(ExternalCallRecord(
operation_id, external_org, self._seq,
"success" if rows else "inventory_not_found", "query_stock",
targets=tuple(target_keys),
))
return StockQueryResult(rows=tuple(rows))
def create_transfer(self, *, operation_id: str, order, final_only: bool = False,
on_nonfinal_success=None, business_ref: str | None = None) -> TransferWriteResult:
"""单据级原子建单/审核/过账(签名与 T9 真实 CapabilityClient 一致)。
business_ref(2026-09-27 调用日志 Task 4):随真实客户端签名同步新增的可选
业务锚点参,替身仅接受不消费(调用日志断言走真实网关,见
tests/services/integration_connector/test_engine.py)。
按注入场景返回已分类结果并记录调用(call log 携带单头字段 + 完整行集 +
final_only + on_nonfinal_success 携带标记,供 D7②/D14/R7 断言)。场景解析
顺序:write_scenarios_by_doc[doc_no] → write_scenarios[行溯源 invoice_no] →
write_scenario;单号或行溯源 Invoice 命中已存在单证时走重复路径:
已过账 → duplicate_success + 原单号(ERP 重触发回带原单号的域内表达);
未证实过账 → duplicate_unverified(收敛为 result_unknown,禁自动重试)。
R7 语义:非 timeout_before_commit 场景(stage 成功)在返回前回调一次
on_nonfinal_success(模拟引擎「stage 成功、submit 之前」时序);该场景
或 final_only=True 不回调。
"""
self._seq += 1
doc_key = str(order.doc_no).strip()
invoice_keys = []
for line in order.lines:
for inv in str(line.get("invoice_no") or "").split(","):
inv = inv.strip()
if inv and inv not in invoice_keys:
invoice_keys.append(inv)
lines = tuple(dict(line) for line in order.lines)
def _record(status: str, document_no: str | None = None) -> None:
"""记录一次单据级写调用(单头 + 行集 + final_only/on_nonfinal_success 留痕)。"""
self.call_log.append(ExternalCallRecord(
operation_id=operation_id, external_org=order.external_org,
call_seq=self._seq, returned_status=status, method="create_transfer",
invoice_no=invoice_keys[0] if invoice_keys else "",
document_no=document_no, doc_no=doc_key,
submit_timestamp=order.submit_timestamp, doc_date=order.doc_date,
posting_date=order.posting_date, final_only=final_only,
on_nonfinal_success=on_nonfinal_success is not None, lines=lines,
))
def _fire_stage_callback() -> None:
"""模拟引擎时序:stage 成功后、submit 前触发一次非末步成功回调。"""
if on_nonfinal_success is not None and not final_only and scenario != "timeout_before_commit":
on_nonfinal_success(None, 0)
# [场景解析] 单号 → 行溯源 Invoice → 全局。
scenario = self.write_scenarios_by_doc.get(doc_key)
if scenario is None:
scenario = next((self.write_scenarios[k] for k in invoice_keys if k in self.write_scenarios), None)
scenario = scenario or self.write_scenario
if scenario == "timeout_before_commit":
# 可证明未落单 → 明确技术失败(不产生单据);stage 未成功 → 不触发回调。
_record("timeout_before_commit")
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
# [R7 时序模拟] 自此处起 stage 已成功:先触发回调(断点标记),再走 submit/返回。
_fire_stage_callback()
if scenario == "timeout_after_commit":
# 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。
document_no = self.documents.setdefault(doc_key, f"TRF-{self._seq:05d}")
self.verified_posted[doc_key] = True
_record("timeout_after_commit", document_no)
return TransferWriteResult(
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
document_no=document_no,
)
if scenario == "business_failed":
_record("business_failed")
return TransferWriteResult(
status="business_failed", error_code="EXTERNAL_BUSINESS_REJECT",
error_message="rejected by external system",
)
# [重复路径] 单号或行溯源 Invoice 命中已存在单证(幂等重触发场景)。
existing = self.documents.get(doc_key)
existing_key = doc_key
if existing is None:
for inv in invoice_keys:
if inv in self.documents:
existing = self.documents[inv]
existing_key = inv
break
if existing is not None:
posted = self.verified_posted.get(existing_key, False)
status = "duplicate_success" if posted else "duplicate_unverified"
_record(status, existing)
return TransferWriteResult(
status=status, document_no=existing, verified_posted=posted,
error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED",
)
document_no = f"TRF-{self._seq:05d}"
self.documents[doc_key] = document_no
self.verified_posted[doc_key] = True
for inv in invoice_keys:
self.documents.setdefault(inv, document_no)
self.verified_posted.setdefault(inv, True)
_record("success", document_no)
return TransferWriteResult(status="success", document_no=document_no, verified_posted=True)
# -- 断言辅助 ----------------------------------------------------------
@property
def query_calls(self) -> int:
"""库存查询(query_stock)调用次数计数器(零外部调用断言用)。"""
return sum(1 for record in self.call_log if record.method == "query_stock")
def calls(self, *, invoice_no: str | None = None) -> list[ExternalCallRecord]:
"""按 Invoice 过滤调用记录(默认返回全部;查询调用 invoice_no 为空串)。"""
if invoice_no is None:
return list(self.call_log)
return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()]
def write_calls(self) -> list[ExternalCallRecord]:
"""仅返回 create_transfer 调用记录(写副作用断言)。"""
return [record for record in self.call_log if record.method == "create_transfer"]
class FakeRPA:
"""可独立按来源注入失败/延迟的收料 RPA 替身。"""
def __init__(self) -> None:
self.triggered: list[dict[str, Any]] = []
self.fail_on: set[str] = set()
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次来源收料抓取并记录。"""
self.triggered.append({
"source_code": source_code,
"business_date": business_date,
"reason": reason,
})
if source_code in self.fail_on:
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
return {"ok": True, "callback_id": f"inbound:{source_code}:{business_date}"}
class FakeWeCom:
"""企业微信通知替身;记录投递事实,可注入附件失败。"""
def __init__(self) -> None:
self.deliveries: list[dict[str, Any]] = []
self.attach_fail = False
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""发送一次汇总通知;附件失败时返回 failed 但不抛异常。"""
if self.attach_fail and excel_path:
record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
self.deliveries.append(record)
return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path}
self.deliveries.append(record)
return {"status": "success"}
@dataclass
class FakeAuditSink:
"""审计落点替身;记录 before/after、Diff、Hash 与关联上下文。"""
events: list[dict[str, Any]] = field(default_factory=list)
def append(self, event: dict[str, Any]) -> None:
"""追加一条审计事件 dict。"""
self.events.append(event)
def utc_now_iso() -> str:
"""返回当前 UTC 时间的 ISO 字符串(测试断言用)。"""
return datetime.now(timezone.utc).isoformat()