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

+147 -20
View File
@@ -506,6 +506,125 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
assert response.status_code == 403
# ---------------------------------------------------------------------------
# Task 4:retry-rpa 对 parse_failed 先本地重解析(成功 200+ready / 仍失败 ok=False;
# 两条路径均不触发 RPA、不返回 202/fetching)
# ---------------------------------------------------------------------------
def _seed_parse_failed_receipt_file(source_code: str):
"""造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。
与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数:
来源须在全局 app 夹具种子中(DSV360_AWSDU);文件 created_at 取默认当前 UTC
(当日业务日窗口内 → 可用门禁命中),返回该文件供测试断言。
"""
import hashlib
from datetime import datetime
from uuid import uuid4
from app.models import (
ShippingInventorySource,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
)
source = ShippingInventorySource.query.filter_by(source_code=source_code).one()
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id,
callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success",
config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=f"shipping/receipt/retry-{unit.id}.xlsx",
original_filename="retry.xlsx", file_size=16,
sha256=hashlib.sha256(b"retry workbook").hexdigest(),
parse_failed_at=datetime.utcnow(),
parse_error_code="TRANSFER_FILE_SCHEMA_INVALID", parse_error_message="schema",
)
db.session.add(report)
db.session.commit()
return report
def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_headers, monkeypatch):
"""parse_failed 且有可用文件 → retry 先本地重解析(sync),不触发 RPA(200 非 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回
# ready(请求会话内重查后清除并 commit,保证端点再解析可见)。
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.source_file_status import clear_receipt_parse_failure
called["sync"] += 1
file = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code))
.first()
)
if file is not None:
clear_receipt_parse_failure(report=file)
db.session.commit()
return True
monkeypatch.setattr(
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
# 断言意图:重解析成功返回 200(非 202/fetching),payload 恰为四键契约,
# 且 RPA 触发 0 次(本地重解析不落 RPA 单元)。
assert response.status_code == 200
body = response.get_json()["data"]
assert body == {
"source_code": "DSV360_AWSDU", "ok": True,
"file_status": "ready", "reparsed": True,
}
assert called["sync"] == 1
assert called["rpa"] == 0
def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_headers, monkeypatch):
"""sync 返回 True 但投影仍 parse_failed → ok=False(不触发 RPA、不回 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报
# 失败(ok=False + parse_failed),由用户感知仍不可用。
called["sync"] += 1
return True
monkeypatch.setattr(
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
# 断言意图:仍失败也返回 200(业务结果在 ok 字段),RPA 0 次不兜底重抓。
assert response.status_code == 200
body = response.get_json()["data"]
assert body == {
"source_code": "DSV360_AWSDU", "ok": False,
"file_status": "parse_failed", "reparsed": True,
}
assert called["sync"] == 1
assert called["rpa"] == 0
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
@@ -755,15 +874,17 @@ def test_run_projection_returns_order_list_with_multi_status(
data = run.get_json()["data"]
orders = data["orders"]
assert len(orders) == 3
# 断言意图:单序稳定(created_at/id 升序 = 组建单的组键升序:收料日期升序)。
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源,
# 收料日期升序,与建单的组键序一致)。
assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
by_status = {t["status"]: t for t in orders}
assert set(by_status) == {"success", "business_failed", "result_unknown"}
success = by_status["success"]
# 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含六键
# (含 reason:框线图失败行原因展示契约,控制器裁决扩充,T13-3)。
# 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含七键
# (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图
# 失败行原因展示契约,控制器裁决扩充,T13-3)。
assert set(success.keys()) == {
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
"status", "erp_document_no", "error_message", "lines",
@@ -777,6 +898,7 @@ def test_run_projection_returns_order_list_with_multi_status(
# 断言意图:行数量为 6 位小数字符串(D14 快照口径),unit 原值透传非空;
# 成功行 reason 为 None(键恒出现)。
assert success["lines"] == [{
"invoice_no": "HOM-A",
"material_no": "MAT-001", "material_name": "物料MAT-001", "lot_no": "LOT-10",
"quantity": "500.000000", "unit": "EA", "reason": None,
}]
@@ -784,8 +906,9 @@ def test_run_projection_returns_order_list_with_multi_status(
failed = by_status["business_failed"]
assert failed["erp_document_no"] is None
# 断言意图:单据级 error_message 恒 null(T11 裁决契约:失败/未知原因只在
# 行级 reason 与 run exceptions 透出,单据级不落原因文本)。
# 行级 reason 与 orders 卡片透出,单据级不落原因文本)。
assert failed["error_message"] is None
assert failed["lines"][0]["invoice_no"] == "HOX-B"
assert failed["lines"][0]["quantity"] == "700.000000"
# 断言意图:失败行 reason=行级 result_message(框线图「原因」展示数据源)。
assert failed["lines"][0]["reason"] == "rejected by external system"
@@ -800,10 +923,9 @@ def test_run_projection_returns_order_list_with_multi_status(
# 断言意图:未知行 reason 回落 error_code(result_message 为空时引擎已写入)。
assert unknown["lines"][0]["reason"] == "EXTERNAL_TIMEOUT_AFTER_COMMIT"
# 断言意图:exceptions 既有口径不变——成功族行不进异常清单,失败/未知行逐行进。
exceptions = data["result"]["exceptions"]
assert len(exceptions) == 2
assert {exc["reason"] for exc in exceptions} == {"business_failed", "result_unknown"}
# 断言意图:[2026-09-29 口径收窄] exceptions 仅收未建单阻断行——失败/未知行
# 已建单,不再进异常清单(原因/动作由 orders 卡片承载)。
assert data["result"]["exceptions"] == []
# 断言意图:external_documents 既有口径不变——仅成功单聚合出单据视图。
assert len(data["result"]["external_documents"]) == 1
@@ -973,9 +1095,10 @@ def test_list_documents_group_counts_always_full(app, transfer_db, client, admin
assert data["total"] == 7 # cancelled 不进列表
assert data["page"] == 1
assert data["page_size"] == 20
# 断言意图:列表 created_at 倒序(无筛选=全部未关闭单)。
# 断言意图:列表按 收料日期→数据源→库位 升序(2026-09-29 统一口径;本组
# 造数同日同源,按拨入库位字典序升序)。
assert [t["doc_no"] for t in data["orders"]] == [
"D-UNK-1", "D-EXEC-2", "D-EXEC-1", "D-FAIL-2", "D-FAIL-1", "D-SUC-2", "D-SUC-1",
"D-EXEC-1", "D-EXEC-2", "D-FAIL-1", "D-FAIL-2", "D-SUC-1", "D-SUC-2", "D-UNK-1",
]
# 过滤 failed:groups 计数不变(恒全量),列表仅失败族。
@@ -1030,7 +1153,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm
def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs_matching):
"""分页:默认 page_size=20;created_at 倒序;page/page_size 翻页取片;上限 100。"""
"""分页:默认 page_size=20;收料日期→数据源→库位升序;page/page_size 翻页取片;上限 100。"""
from datetime import datetime, timedelta
with app.app_context():
@@ -1045,22 +1168,23 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs
first_page = client.get(f"{API_PREFIX}/documents?status_group=failed", headers=admin_headers).get_json()["data"]
assert first_page["total"] == 25
assert len(first_page["orders"]) == 20
# 断言意图:列表 created_at 倒序——第一页含最新的 24~5 号单。
assert first_page["orders"][0]["doc_no"] == "D-PG-24"
assert first_page["orders"][-1]["doc_no"] == "D-PG-05"
# 断言意图:列表升序(2026-09-29 统一口径;本组造数同日同源,按拨入库位
# 字典序 = doc_no 序)——第一页含最早的 00~19 号单。
assert first_page["orders"][0]["doc_no"] == "D-PG-00"
assert first_page["orders"][-1]["doc_no"] == "D-PG-19"
second_page = client.get(
f"{API_PREFIX}/documents?status_group=failed&page=2", headers=admin_headers,
).get_json()["data"]
assert len(second_page["orders"]) == 5
assert second_page["orders"][0]["doc_no"] == "D-PG-04"
assert second_page["orders"][0]["doc_no"] == "D-PG-20"
sized = client.get(
f"{API_PREFIX}/documents?status_group=failed&page=2&page_size=10", headers=admin_headers,
).get_json()["data"]
assert sized["page"] == 2
assert sized["page_size"] == 10
assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(14, 4, -1)]
assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(10, 20)]
# page_size 上限 100:超限收口到 100(防大页拖库)。
capped = client.get(
@@ -1070,26 +1194,29 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs
def test_list_documents_date_range_filters_list_only(app, transfer_db, client, admin_headers, docs_matching):
"""时间范围仅作用 orders 列表(groups 恒全量);历史单(30 天前失败单)计入且可查出。"""
"""时间范围(收料日期口径,2026-09-29 切换)仅作用 orders 列表(groups 恒全量);
历史收料日期的失败单计入且可查出。"""
from datetime import datetime, timedelta
with app.app_context():
now = datetime(2026, 9, 24, 10, 0, 0)
_seed_document(transfer_db, docs_matching, "D-OLD-1", "2026-08-06 09:00:00", "business_failed",
group={"receipt_date": "2026-08-25"},
created_at=now - timedelta(days=30))
_seed_document(transfer_db, docs_matching, "D-NEW-1", "2026-08-06 10:00:00", "business_failed",
group={"receipt_date": "2026-09-23"},
created_at=now - timedelta(days=1))
transfer_db.session.commit()
unfiltered = client.get(f"{API_PREFIX}/documents", headers=admin_headers).get_json()["data"]
# 断言意图:历史失败单(30 天前)计入分组计数且默认列表可查(created_at 倒序在前)。
# 断言意图:历史收料日期失败单计入分组计数且默认列表可查(收料日期升序在前)。
assert unfiltered["groups"]["failed"] == 2
assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-NEW-1", "D-OLD-1"]
assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-OLD-1", "D-NEW-1"]
ranged = client.get(
f"{API_PREFIX}/documents?date_from=2026-09-20&date_to=2026-09-30", headers=admin_headers,
).get_json()["data"]
# 断言意图:时间窗只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。
# 断言意图:时间窗按收料日期只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。
assert [t["doc_no"] for t in ranged["orders"]] == ["D-NEW-1"]
assert ranged["groups"]["failed"] == 2