Merge branch 'dev' into departmental-structure
This commit is contained in:
commit
ec47e012a7
310 files changed
+31263
-6681
No files matched your search
@@ -122,7 +122,8 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
|
||||
data = body["data"]
|
||||
assert data["matching_id"].startswith("MTG-")
|
||||
assert data["matching_hash"].startswith("sha256:")
|
||||
assert data["estimated_external_write_count"] == 2
|
||||
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||
assert data["estimated_external_write_count"] == 1
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
@@ -625,6 +626,41 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h
|
||||
assert called["rpa"] == 0
|
||||
|
||||
|
||||
def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers):
|
||||
"""空 source_codes → 400(批量端点参数卡控)。"""
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, json={"source_codes": []},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch):
|
||||
"""批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。"""
|
||||
captured: dict = {}
|
||||
|
||||
def fake_batch(*, source_codes, business_date, reason):
|
||||
captured.update(source_codes=source_codes, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": True, "triggered": True, "trigger_path": "/tmp/trigger.json",
|
||||
"results": [{"source_code": code, "ok": True} for code in source_codes],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch,
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers,
|
||||
json={"source_codes": ["DSV360_AWSDU", "DSV360_AWSSG"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()["data"]
|
||||
# [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。
|
||||
assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||
assert captured["reason"] == "transfer_retry_receipt"
|
||||
assert body["ok"] is True and body["triggered"] is True
|
||||
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
|
||||
@@ -64,3 +64,29 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
|
||||
assert outcome.run_no == "RUN-20260928-XYZ789"
|
||||
assert outcome.run_status == "success"
|
||||
assert outcome.errors == []
|
||||
|
||||
|
||||
def test_passes_receipt_date_range_to_matching(monkeypatch):
|
||||
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return _summary(0)
|
||||
|
||||
monkeypatch.setattr(at, "create_matching", _fake_create)
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
|
||||
)
|
||||
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
|
||||
assert captured["receipt_date_from"] == "2026-09-01"
|
||||
assert captured["receipt_date_to"] == "2026-09-05"
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
)
|
||||
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
@@ -85,7 +85,8 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
assert event.data["message_type"] == "transfer-match"
|
||||
payload = event.data["payload"]
|
||||
assert payload["kind"] == "match"
|
||||
assert payload["summary"]["estimated_external_write_count"] == 2
|
||||
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||
assert payload["summary"]["estimated_external_write_count"] == 1
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
@@ -57,7 +57,9 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
assert summary.counts.blocked_count == 0
|
||||
assert summary.status == "ready_to_execute"
|
||||
assert summary.matching_hash.startswith("sha256:")
|
||||
assert summary.estimated_external_write_count == 3
|
||||
# [2026-10-12 单据数口径修正] 3 行可执行按执行建单五元组去重:DBS 两行
|
||||
# 同(org,source,date,from,to)合并 1 张 + CRANE 1 行 1 张 = 2(原口径=行数 3)。
|
||||
assert summary.estimated_external_write_count == 2
|
||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
||||
@@ -66,6 +68,61 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
|
||||
|
||||
def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
|
||||
|
||||
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
|
||||
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
|
||||
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
|
||||
"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
|
||||
assert result.summary.estimated_external_write_count == 1
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["HOM-001"].external_org == "HX-CN01"
|
||||
assert items["HOX-002"].external_org == "HX-CN01"
|
||||
|
||||
|
||||
def test_estimated_document_count_splits_by_receipt_date():
|
||||
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
|
||||
|
||||
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
|
||||
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
|
||||
"""
|
||||
deps, erp, _ = _deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_no": "REC-20260806-009",
|
||||
"file_version": "v9",
|
||||
"checksum": "e" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
})
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
assert result.summary.estimated_external_write_count == 2
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
|
||||
@@ -75,10 +75,22 @@ def test_invalid_quantity_rejected():
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
||||
|
||||
|
||||
def test_zero_quantity_rejected():
|
||||
"""0 数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
def test_zero_quantity_stamped_row_skipped():
|
||||
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
assert parsed == []
|
||||
|
||||
|
||||
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
|
||||
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
|
||||
receipt_date="2026-10-01 14:37:43"),
|
||||
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
|
||||
]
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
assert [row.row_no for row in parsed] == [789]
|
||||
assert parsed[0].invoice_no == "INV-002"
|
||||
|
||||
|
||||
def test_negative_quantity_rejected():
|
||||
@@ -121,3 +133,19 @@ def test_error_carries_row_details():
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
||||
details = excinfo.value.details
|
||||
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
||||
|
||||
|
||||
def test_schema_error_message_carries_row_details():
|
||||
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=5, invoice_no=""),
|
||||
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
|
||||
]
|
||||
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
|
||||
# 明细同时保留在 details.rows 供管理端展示。
|
||||
text = str(exc_info.value) or (exc_info.value.message or "")
|
||||
assert "row 5" in text and "missing_invoice_no" in text
|
||||
detail_rows = (exc_info.value.details or {}).get("rows") or []
|
||||
assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows
|
||||
@@ -1,11 +1,13 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
||||
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
|
||||
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
|
||||
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
|
||||
parse_failed 先本地重解析不触发 RPA)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +15,10 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import (
|
||||
trigger_receipt_rpa,
|
||||
trigger_receipt_rpa_batch,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -170,3 +175,157 @@ def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
|
||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
|
||||
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def second_receipt_source(app):
|
||||
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
|
||||
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
|
||||
|
||||
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
profile = ShippingRpaProfile(
|
||||
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
|
||||
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
|
||||
rpa_profile=profile,
|
||||
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add_all([profile, source])
|
||||
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[],
|
||||
)
|
||||
db.session.add(config)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
calls: list = []
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
reason='transfer_retry_receipt', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
|
||||
assert len(calls) == 1
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'awaiting_rpa'}
|
||||
assert all(row.schedule_run_id is None for row in rows)
|
||||
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
|
||||
captured: dict = {}
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
captured['units'] = units
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 来源级隔离:坏源不炸整批,trigger 只含有效源;结果逐源如实分层。
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
|
||||
by_code = {item['source_code']: item for item in outcome['results']}
|
||||
assert by_code['DSV360_AWSDU']['ok'] is True
|
||||
assert by_code['DSV360_NOPE']['ok'] is False
|
||||
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
|
||||
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'failed'}
|
||||
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
|
||||
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
|
||||
statuses = {
|
||||
'DSV360_AWSDU': [
|
||||
{'file_status': 'parse_failed', 'file_sha256': 'abc'},
|
||||
{'file_status': 'ready', 'file_sha256': 'abc'},
|
||||
],
|
||||
}
|
||||
|
||||
def fake_resolve(*, source_code):
|
||||
# [断言意图] 解析失败分层:首次投影 parse_failed 触发本地重解析,
|
||||
# sync 后再查投影回 ready——该来源不得进入 batch trigger。
|
||||
queue = statuses.get(source_code)
|
||||
if queue and len(queue) > 1:
|
||||
return queue.pop(0)
|
||||
return queue[0] if queue else {'file_status': 'none'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.in_transit_transfer.source_file_status.resolve_source_file_status', fake_resolve,
|
||||
)
|
||||
synced: list = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback',
|
||||
lambda *, source_code, business_date, now: synced.append(source_code) or True,
|
||||
)
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
raise AssertionError('reparsed source must not be triggered via RPA')
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
|
||||
assert synced == ['DSV360_AWSDU']
|
||||
assert outcome['ok'] is True and outcome['triggered'] is False
|
||||
assert outcome['results'] == [{
|
||||
'source_code': 'DSV360_AWSDU', 'ok': True, 'reparsed': True, 'file_status': 'ready',
|
||||
}]
|
||||
@@ -29,7 +29,9 @@ def test_transfer_job_registered_with_schedule_defaults():
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history"} <= keys
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
|
||||
|
||||
@@ -123,17 +125,8 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
class _FakeSender:
|
||||
"""记录实例化的发送器替身(断言 handler 接线,不发真实消息)。"""
|
||||
|
||||
instantiated = 0
|
||||
|
||||
def __init__(self):
|
||||
type(self).instantiated += 1
|
||||
|
||||
|
||||
def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
||||
"""配了通知人:构造 sender、置领域自管标记、recipients 透传。"""
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
@@ -147,28 +140,32 @@ def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
class _FakeSenderInner:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
||||
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]})
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recipients"] == ["7"]
|
||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
||||
assert captured["recover_history"] is True
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert results == []
|
||||
assert any("no executable items" in w for w in warnings)
|
||||
|
||||
|
||||
def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
||||
"""未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。"""
|
||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||
from datetime import date
|
||||
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
@@ -178,43 +175,91 @@ def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
|
||||
assert captured["business_date"] == "2026-10-12"
|
||||
assert captured["receipt_date_from"] == "2026-10-08"
|
||||
assert captured["receipt_date_to"] == "2026-10-10"
|
||||
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
assert results == []
|
||||
assert any("收料日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("收料日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
assert captured["sender"] is None
|
||||
assert captured["recipients"] == []
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results and results[0]["run_no"] == "TR-1"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。"""
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
class _FakeSenderInner:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
||||
|
||||
task = ScheduleTask(job_params={"notify_user_ids": ["7"]})
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:sender 已构造并透传;硬失败不抑制框架完成卡。
|
||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
||||
assert captured["recipients"] == ["7"]
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
@@ -207,3 +207,14 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
clear_receipt_parse_failure(report=report)
|
||||
db.session.commit()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
|
||||
|
||||
|
||||
def test_empty_unit_is_no_data(app, receipt_unit_run):
|
||||
"""空数据单元(抓取成功、当日无收料记录)→ no_data,不得与抓取失败混淆。"""
|
||||
from app import db
|
||||
|
||||
receipt_unit_run.status = 'empty'
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'no_data'
|
||||
assert status['has_ready_file'] is False
|
||||
@@ -135,33 +135,6 @@ def test_casdoor_config_repr_does_not_expose_secret(app):
|
||||
assert 'top-secret-value' not in repr(config)
|
||||
|
||||
|
||||
def test_casdoor_server_endpoints_follow_base_url_when_issuer_uses_expired_https():
|
||||
"""公网 HTTPS 证书不可用时,换票和 userinfo 改走 CASDOOR_BASE_URL,浏览器授权地址保持原域名。"""
|
||||
http = FakeHttp()
|
||||
http.get = lambda url, **kwargs: FakeResponse({
|
||||
'issuer': 'https://auth.example.com',
|
||||
'authorization_endpoint': 'https://auth.example.com/login/oauth/authorize',
|
||||
'token_endpoint': 'https://auth.example.com/api/login/oauth/access_token',
|
||||
'userinfo_endpoint': 'https://auth.example.com/api/userinfo',
|
||||
'jwks_uri': 'https://auth.example.com/.well-known/jwks',
|
||||
}) if url.endswith('/.well-known/openid-configuration') else FakeResponse({})
|
||||
client = CasdoorClient(CasdoorConfig(
|
||||
base_url='http://192.168.100.230:8870',
|
||||
client_id='peer-client',
|
||||
client_secret='peer-secret',
|
||||
issuer='https://auth.example.com',
|
||||
), http_session=http)
|
||||
metadata = client.oidc_metadata()
|
||||
# 后端换票不能再访问过期证书上的 HTTPS 域名。
|
||||
assert metadata['token_endpoint'] == 'http://192.168.100.230:8870/api/login/oauth/access_token'
|
||||
assert metadata['userinfo_endpoint'] == 'http://192.168.100.230:8870/api/userinfo'
|
||||
assert metadata['jwks_uri'] == 'http://192.168.100.230:8870/.well-known/jwks'
|
||||
# 浏览器授权仍使用 discovery 原地址。
|
||||
assert metadata['authorization_endpoint'] == 'https://auth.example.com/login/oauth/authorize'
|
||||
client.password_login('alice', 'user-password')
|
||||
assert http.posts[0][0] == 'http://192.168.100.230:8870/api/login/oauth/access_token'
|
||||
|
||||
|
||||
def test_casdoor_password_client_request_is_framework_independent():
|
||||
"""公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。"""
|
||||
http = FakeHttp()
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付;增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -443,6 +443,38 @@ def test_conflicting_shipment_percentages_report_duplicate_once():
|
||||
assert not any(node["node_type"] == "shipment" for node in result["nodes"])
|
||||
|
||||
|
||||
def test_vat_rate_beside_deposit_schedule_is_not_prepayment_percentage():
|
||||
"""关键断言:完成日期「收到定金后135天」后的含13%增值税不算预付款,结算条款的定金30%仍保留。"""
|
||||
result = parse_contract_text(
|
||||
"设备定作合同 收到定金后 135天 合计(人民币大写)壹佰伍拾伍万元整(含13%增值税) "
|
||||
"四、结算方式及期限:甲方支付乙方定金:¥465,000.00元(总价款的30%),"
|
||||
"甲方支付乙方发货款:¥930,000.00元(总价款的60%),"
|
||||
"验收款(总价款的10%)¥155,000.00元。"
|
||||
"设备总价款(含税):1550000.00元"
|
||||
)
|
||||
|
||||
percentages = {node["node_type"]: node["percentage"] for node in result["nodes"]}
|
||||
assert percentages["prepayment"] == "30"
|
||||
assert percentages["shipment"] == "60"
|
||||
assert percentages["acceptance"] == "10"
|
||||
assert "warranty" not in percentages
|
||||
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||||
assert "付款阶段比例无法识别:质保款" in result["issues"]
|
||||
|
||||
|
||||
def test_tax_rate_in_same_clause_does_not_hide_payment_percentage():
|
||||
"""关键断言:同一句里先写含13%增值税、再写总价款30%时,预付款取30%,不取税率。"""
|
||||
result = parse_contract_text(
|
||||
"采购协议 合同号:HT-2026-006;合同总价:100,000元;"
|
||||
"定金(含13%增值税)为总价款的30%;出货款40%;验收款20%;质保款10%;交货期:2026年09月01日。"
|
||||
)
|
||||
|
||||
assert result["status"] == "parsed"
|
||||
prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment")
|
||||
assert prepayment["percentage"] == "30"
|
||||
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||||
|
||||
|
||||
def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch):
|
||||
"""关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。"""
|
||||
app.config.update(
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
"""
|
||||
tests/test_customer_resolution_rebind.py
|
||||
|
||||
用途:确认客户改绑(customer_resolution_service.rebind_confirmed_customer)契约测试。
|
||||
依赖:内存数据库、客户识别结果服务、order_freeze_service(真实冻结链)、
|
||||
order_edit_window_service(编辑窗 header 谓词)、ShippingExportArtifact。
|
||||
逻辑:已确认订单在产生发货通知/Excel 之前允许直接修改确认客户;改绑同步刷新冻结快照客户,
|
||||
并保持 evidence_json / identity_rule_set_checksum 非空冻结契约;Excel 已产生 / 活动
|
||||
Gate Attempt / 同客户 / 未知或停用客户 / 未确认识别结果均 fail-closed 且零副作用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import project_review_case_customer_resolution
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
freeze_order_snapshot,
|
||||
)
|
||||
from tests.conftest import parse_api_error
|
||||
|
||||
|
||||
def _build_confirmed_frozen_order(*, suffix: str) -> dict:
|
||||
"""构造已确认客户 + 已冻结快照 + 未产生 Excel 的正式订单(编辑窗 header 可编辑)。"""
|
||||
user = User(username=f'rebind-user-{suffix}', email=f'rebind-user-{suffix}@example.test', password_hash='x')
|
||||
old_customer = ShippingCustomer(standard_name='原确认客户', short_code='OLD', status='active')
|
||||
new_customer = ShippingCustomer(standard_name='新确认客户', short_code='NEWC', status='active')
|
||||
inactive_customer = ShippingCustomer(standard_name='停用客户', short_code='OFF', status='inactive')
|
||||
task = ShippingOrderTask(task_no=f'OT-REBIND-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7)
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Rebind frozen order')
|
||||
db.session.add_all([user, old_customer, new_customer, inactive_customer, task, schema])
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
definitions = []
|
||||
fields: dict[str, ShippingOrderField] = {}
|
||||
for code in [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]:
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
field = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one()
|
||||
fields[code] = field
|
||||
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': field.value_type, 'enabled': True})
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='rebind-test',
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {
|
||||
'customer_po_number': 'PO-REBIND', 'customer_code': 'C-001', 'customer_name': 'Customer',
|
||||
'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'),
|
||||
'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS',
|
||||
}
|
||||
for code, field in fields.items():
|
||||
value = values.get(code)
|
||||
decision = _make_decision(extraction, line, field, code, value)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(_make_field_value(extraction, line, field, decision, value))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-REBIND-{suffix}', asset_id=1, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-REBIND-{suffix}', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key=f'rebind-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.candidate_id = candidate.id
|
||||
task.user_id = int(user.id)
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': old_customer.short_code}],
|
||||
candidate_matches_json=[
|
||||
{'customer_id': old_customer.id, 'score': 100},
|
||||
{'customer_id': new_customer.id, 'score': 90},
|
||||
],
|
||||
resolution_context_json={'rule_set': {'checksum': 'f' * 64}},
|
||||
identity_rule_set_checksum='f' * 64, top_customer_id=old_customer.id, top_score=100,
|
||||
confirmed_customer_id=old_customer.id, confirmation_method='manual', confirmed_by_id=user.id,
|
||||
)
|
||||
notice = ShippingNotice(task_no=f'SN-REBIND-{suffix}', order_task_id=task.id)
|
||||
db.session.add_all([resolution, notice])
|
||||
db.session.flush()
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
db.session.commit()
|
||||
return {
|
||||
'user': user, 'task': task, 'notice': notice, 'resolution': resolution,
|
||||
'old_customer': old_customer, 'new_customer': new_customer, 'inactive_customer': inactive_customer,
|
||||
'snapshot': snapshot, 'schema_version_id': int(version.id),
|
||||
}
|
||||
|
||||
|
||||
def _make_decision(extraction, line, field, code, value):
|
||||
"""构造单头/行字段裁决行(与既有快照测试同构)。"""
|
||||
from app.models import ShippingOrderFieldDecision
|
||||
return ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id,
|
||||
field_id=field.id, decision_status='accepted',
|
||||
resolved_value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
supporting_observation_ids_json=[],
|
||||
)
|
||||
|
||||
|
||||
def _make_field_value(extraction, line, field, decision, value):
|
||||
"""构造字段值投影行(Decimal 保留精度,料号/预约号保留前导零)。"""
|
||||
from app.models import ShippingOrderFieldValue
|
||||
return ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None if field.scope == 'header' else line.id,
|
||||
field_id=field.id, decision_id=decision.id,
|
||||
value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
value_text=str(value) if isinstance(value, str) else None,
|
||||
value_decimal=value if isinstance(value, Decimal) else None,
|
||||
)
|
||||
|
||||
|
||||
def _attach_ready_export_artifact(notice: ShippingNotice) -> None:
|
||||
"""给通知挂一个 ready 导出产物(Excel 已产生,header 编辑窗关闭)。"""
|
||||
from app.models import ShippingOrderSchema as Schema
|
||||
from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction
|
||||
|
||||
template = _template_row()
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = Schema(schema_code='REBIND_SCHEMA', display_name='Rebind schema')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingExportArtifact(
|
||||
task_id=int(notice.id), artifact_no=f'ART-REBIND-{notice.task_no}', template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='d' * 64,
|
||||
file_path='rebind.xlsx', file_name='rebind.xlsx', file_checksum='e' * 64,
|
||||
file_size=1, status='ready',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
_TEMPLATE_CACHE: dict = {}
|
||||
|
||||
|
||||
def _template_row():
|
||||
"""复用同进程内已建模板,避免不同用例重复建模板造成噪音。
|
||||
|
||||
缓存需自愈:每测试独立 create_all/drop_all,缓存 id 在新 DB 中可能不存在
|
||||
(该脆弱组合即 Task 1 评审预警项),取不到时重建并刷新缓存。
|
||||
"""
|
||||
from app.models import ShippingExcelTemplate
|
||||
cached_id = _TEMPLATE_CACHE.get('id')
|
||||
if cached_id is not None:
|
||||
template = db.session.get(ShippingExcelTemplate, int(cached_id))
|
||||
if template is not None:
|
||||
return template
|
||||
_TEMPLATE_CACHE.pop('id', None)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='REBIND_TPL', display_name='Rebind template', version=1, status='published',
|
||||
storage_bucket='test', storage_key='rebind-tpl.xlsx', original_filename='rebind-tpl.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
db.session.add(template)
|
||||
db.session.flush()
|
||||
_TEMPLATE_CACHE['id'] = int(template.id)
|
||||
return template
|
||||
|
||||
|
||||
def _resolution_of(task: ShippingOrderTask) -> ShippingCustomerShadowResolution:
|
||||
"""按 OT 的候选反查唯一识别结果行。"""
|
||||
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(task.candidate_id)).one()
|
||||
|
||||
|
||||
def _attach_confirmed_revision(fx: dict, *, suffix: str):
|
||||
"""构造建单确认修订,把冻结任务挂到真实复核 Case 上(审计 review_case_no 反查依赖)。"""
|
||||
from app.models import ShippingOrderReviewConfirmedRevision
|
||||
|
||||
_user, case = _seed_review_case(suffix=suffix)
|
||||
db.session.add(ShippingOrderReviewConfirmedRevision(
|
||||
case_id=int(case.id), task_id=int(fx['task'].id), draft_version=1,
|
||||
schema_version_id=int(fx['schema_version_id']),
|
||||
idempotency_key=f'IDEM-REBIND-{suffix}',
|
||||
confirmed_by_id=int(fx['user'].id),
|
||||
))
|
||||
# 生产确认路径会把任务挂上 Case;改绑投影经 confirmed_task_id 反查确认结果。
|
||||
case.confirmed_task_id = int(fx['task'].id)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
|
||||
def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(app):
|
||||
"""改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='happy')
|
||||
# Case 反查夹具的 suffix 必须大写(intake_no 查找统一 upper 归一)。
|
||||
case = _attach_confirmed_revision(fx, suffix='HAPPY-CASE')
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
|
||||
actor_id=int(fx['user'].id), expected_order_data_version=7, reason='选错客户',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
snapshot = result['snapshot']
|
||||
# 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。
|
||||
assert resolution.confirmed_customer_id == int(fx['new_customer'].id)
|
||||
assert snapshot.customer_id == int(fx['new_customer'].id)
|
||||
assert snapshot.customer_short_code_snapshot == str(fx['new_customer'].short_code)
|
||||
rebind_record = next(
|
||||
item for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
)
|
||||
assert rebind_record['rebind']['previous_customer_id'] == int(fx['old_customer'].id)
|
||||
assert rebind_record['rebind']['new_customer_id'] == int(fx['new_customer'].id)
|
||||
assert rebind_record['rebind']['actor_id'] == int(fx['user'].id)
|
||||
assert rebind_record['rebind']['reason'] == '选错客户'
|
||||
assert resolution.identity_rule_set_checksum == 'f' * 64 # 冻结契约:保持非空
|
||||
# 原始识别证据保留(rebind 记录是追加,不是覆盖)。
|
||||
assert resolution.evidence_json[0]['definition_code'] == 'test_customer'
|
||||
# 快照唯一约束(uq task_id):一个任务一份快照,改绑是原地刷新而非新行。
|
||||
assert int(snapshot.id) == int(fx['snapshot'].id)
|
||||
assert fx['task'].order_snapshot_id == snapshot.id
|
||||
# 审计事件:before/after 携带原/新确认客户与原因;挂 review_case_no 供 Case 时间线查询。
|
||||
event = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_customer_rebound', aggregate_id=str(fx['task'].task_no),
|
||||
).one()
|
||||
assert event.before_snapshot_json['previous_value'] == int(fx['old_customer'].id)
|
||||
assert event.after_snapshot_json['new_value'] == int(fx['new_customer'].id)
|
||||
assert event.reason == '选错客户'
|
||||
assert event.actor_type == 'user'
|
||||
assert event.review_case_no == str(case.case_no)
|
||||
# 改绑后投影以确认结果+客户主数据为权威展示:名字/简称/改绑谓词直供工作台。
|
||||
projection = project_review_case_customer_resolution(case=case)
|
||||
assert projection['standard_name'] == str(fx['new_customer'].standard_name)
|
||||
assert projection['short_code'] == str(fx['new_customer'].short_code)
|
||||
assert projection['customer_id'] == int(fx['new_customer'].id)
|
||||
assert projection['rebind_allowed'] is True
|
||||
|
||||
|
||||
def test_task_ui_state_emits_edit_window_gate_for_workbench(app):
|
||||
"""工作台 payload 必须下发 edit_window(D10 门控数据源,防合并再次丢失)。
|
||||
|
||||
回归背景:前端波次出单工具条的显示条件读 ui_state.edit_window.header,
|
||||
后端曾把该字段丢失,导致 Excel 已产生仍显示「生成发货通知和 Excel」工具条。
|
||||
"""
|
||||
fx = _build_confirmed_frozen_order(suffix='ew')
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
ui = build_task_ui_state(fx['notice'], include_stage_context=True)
|
||||
# 断言意图:Excel 未产生时 header=True(出单工具条显示)。
|
||||
assert ui['edit_window']['header'] is True
|
||||
|
||||
_attach_ready_export_artifact(fx['notice'])
|
||||
ui_after = build_task_ui_state(fx['notice'], include_stage_context=True)
|
||||
# 断言意图:Excel 已产生时 header=False(出单工具条隐藏——用户报告的缺陷)。
|
||||
assert ui_after['edit_window']['header'] is False
|
||||
# OT 身份构建必须与通知身份同判(editable_scope 身份归一):用户场景即按 OT 加载详情。
|
||||
ui_by_ot = build_task_ui_state(fx['task'], include_stage_context=True)
|
||||
assert ui_by_ot['edit_window']['header'] is False
|
||||
|
||||
|
||||
def test_rebind_rejects_when_export_artifact_exists(app):
|
||||
"""已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='excel')
|
||||
_attach_ready_export_artifact(fx['notice'])
|
||||
case = _attach_confirmed_revision(fx, suffix='EXCEL-CASE')
|
||||
# 断言意图:Excel 已产生时投影谓词 fail-closed(前端「修改客户」按钮禁用的数据源)。
|
||||
assert project_review_case_customer_resolution(case=case)['rebind_allowed'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
# 断言意图:A 管控 fail-closed;错误码可前端定位(details 区分 Excel / 活动 Attempt)。
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
|
||||
assert exc.value.details['excel_exists'] is True
|
||||
assert exc.value.details['active_attempt'] is False
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_when_active_gate_attempt_exists(app, monkeypatch):
|
||||
"""存在活动 Gate Attempt(库存 RPA / 匹配处理中)时改绑必须 409。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt',
|
||||
lambda n: True,
|
||||
)
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='busy')
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
|
||||
assert exc.value.details['excel_exists'] is False
|
||||
assert exc.value.details['active_attempt'] is True
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_same_customer_and_unknown_customer(app):
|
||||
"""同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='guards')
|
||||
|
||||
with pytest.raises(ConflictError) as same:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['old_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert same.value.code == 'SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER'
|
||||
|
||||
with pytest.raises(NotFoundError) as unknown:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=999999, actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert unknown.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND'
|
||||
|
||||
with pytest.raises(ConflictError) as inactive:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['inactive_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert inactive.value.code == 'SHIPPING.CUSTOMER_INACTIVE'
|
||||
|
||||
# 断言意图:拒绝路径零副作用(确认结果与快照均不被触碰)。
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
assert fx['task'].order_snapshot_id == fx['snapshot'].id
|
||||
|
||||
|
||||
def test_rebind_requires_confirmed_resolution(app):
|
||||
"""识别结果未确认(或缺失)时改绑必须 409,提示走既有识别确认流程。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='unconfirmed')
|
||||
resolution = _resolution_of(fx['task'])
|
||||
resolution.status = 'unique_candidate'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_RESOLUTION_REQUIRED'
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_stale_version_without_side_effects(app):
|
||||
"""[断言] 客户端版本比较在守卫阶段执行:版本不一致必须 409 且零副作用(不写确认结果/审计/快照)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='stale')
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=6,
|
||||
)
|
||||
|
||||
# 断言意图:乐观锁在写前拒绝;details 呈现 expected/actual 供前端提示刷新。
|
||||
assert exc.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
|
||||
assert exc.value.details == {'expected': 6, 'actual': 7}
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
assert fx['task'].order_snapshot_id == fx['snapshot'].id
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='review_customer_rebound').count() == 0
|
||||
|
||||
|
||||
def test_rebind_requires_operator_for_internal_call(app):
|
||||
"""[断言] 缺少执行人的内部调用按参数错误拒绝(独立于编辑窗 A 管控语义)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='no-actor')
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
|
||||
actor_id=None, expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED'
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API 路由层(POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_review_case(*, suffix: str):
|
||||
"""构造属主用户与其复核 Case(未建正式 OT,够验证路由守卫)。"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix=suffix)
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
return user, case
|
||||
|
||||
|
||||
def _auth_headers(user) -> dict:
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
return {'Authorization': f'Bearer {issue_local_access_token(user)}'}
|
||||
|
||||
|
||||
def test_rebind_api_requires_customer_id(app):
|
||||
"""[断言] 缺少 customer_id 的请求体被 400 拦截,错误码可前端定位。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-BODY')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user), json={},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 400
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED'
|
||||
|
||||
|
||||
def test_rebind_api_requires_expected_version(app):
|
||||
"""[断言] 缺少 expected_order_data_version 的请求体被 400 拦截(乐观锁必填)。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-VER')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user), json={'customer_id': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 400
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED'
|
||||
assert error['details']['field'] == 'expected_order_data_version'
|
||||
|
||||
|
||||
def test_rebind_api_rejects_case_outside_ownership(app):
|
||||
"""[断言] 非属主访问他人 Case 必须按不存在拒绝(404),不泄露存在性。"""
|
||||
with app.app_context():
|
||||
owner, case = _seed_review_case(suffix='API-OWNER')
|
||||
# agent_code 全局唯一,非属主用户须使用独立 agent_code。
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
outsider, _a, _s, _i, _d = _seed_run_input(suffix='API-OUTSIDER', agent_code='shipping_notice_rebind')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(outsider),
|
||||
json={'customer_id': 1, 'expected_order_data_version': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 404
|
||||
assert error['code'] == 'SHIPPING.REVIEW_CASE_NOT_FOUND'
|
||||
assert owner is not None
|
||||
|
||||
|
||||
def test_rebind_api_requires_formal_order_task(app):
|
||||
"""[断言] Case 尚未确认建单(无正式 OT)时改绑必须 409。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-NOOT')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user),
|
||||
json={'customer_id': 1, 'expected_order_data_version': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 409
|
||||
assert error['code'] == 'SHIPPING.FORMAL_OT_REQUIRED'
|
||||
@@ -78,6 +78,38 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||
|
||||
|
||||
def test_friendly_workflow_failure_message_identifies_knowledge_retrieval_failure():
|
||||
"""知识检索节点失败应说明是知识库,而不是笼统的查询失败。"""
|
||||
message = DifyService._friendly_workflow_failure_message(
|
||||
'Node knowledge-retrieval run failed: dataset not found',
|
||||
agent_name='研发培训',
|
||||
)
|
||||
assert message == '研发培训的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。'
|
||||
|
||||
|
||||
def test_friendly_stream_request_failure_message_distinguishes_timeout():
|
||||
"""连接 Dify 读超时应提示等待超时,且不带异常原文。"""
|
||||
import requests
|
||||
|
||||
message = DifyService._friendly_stream_request_failure_message(
|
||||
requests.exceptions.ReadTimeout('read timed out'),
|
||||
agent_name='研发培训',
|
||||
)
|
||||
assert message == '研发培训等待 AI 服务响应超时,请稍后重试。'
|
||||
assert 'read timed out' not in message
|
||||
|
||||
|
||||
def test_present_stream_error_message_keeps_rerank_authorization_copy():
|
||||
"""流内 error 事件里的重排 403 应沿用授权失败文案。"""
|
||||
message = DifyService._present_stream_error_message(
|
||||
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||
400,
|
||||
'研发培训',
|
||||
)
|
||||
assert '知识检索重排服务授权失败' in message
|
||||
assert 'https://api.example' not in message
|
||||
|
||||
|
||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
|
||||
@@ -448,3 +448,167 @@ def test_fill_multi_value_js_uses_entry_text_not_bare_text():
|
||||
# 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。
|
||||
assert "desiredValues.includes(text" not in source
|
||||
assert "normalize(text)" not in source or "entryText" in source
|
||||
|
||||
|
||||
class _RecordingFrame:
|
||||
"""脚本化 frame:evaluate 返回预置结果或抛预置异常,并记录收到的 label。"""
|
||||
|
||||
def __init__(self, result=None, error: Exception | None = None):
|
||||
self._result = result
|
||||
self._error = error
|
||||
self.calls: list[str] = []
|
||||
|
||||
def evaluate(self, script: str, label: str):
|
||||
self.calls.append(label)
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._result
|
||||
|
||||
|
||||
class _RecordingPage:
|
||||
def __init__(self, frames):
|
||||
self.frames = frames
|
||||
|
||||
|
||||
_STRUCTURAL_CONTROLS = {
|
||||
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||
}
|
||||
|
||||
|
||||
def test_structural_resolver_hit_returns_controls_and_trims_label():
|
||||
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
|
||||
module = _load_module()
|
||||
early = _RecordingFrame(result=None)
|
||||
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([early, hit])
|
||||
|
||||
got = module.resolve_parameter_controls_structural(page, " Owner ")
|
||||
|
||||
assert got == _STRUCTURAL_CONTROLS
|
||||
assert hit.calls == ["Owner"]
|
||||
|
||||
|
||||
def test_structural_resolver_all_frames_miss_or_error_returns_none():
|
||||
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
|
||||
module = _load_module()
|
||||
page = _RecordingPage([
|
||||
_RecordingFrame(result=None),
|
||||
_RecordingFrame(error=RuntimeError("execution context destroyed")),
|
||||
_RecordingFrame(result=None),
|
||||
])
|
||||
assert module.resolve_parameter_controls_structural(page, "Owner") is None
|
||||
|
||||
|
||||
def test_structural_resolver_empty_label_short_circuits():
|
||||
"""空标签短路:不打扰任何 frame。"""
|
||||
module = _load_module()
|
||||
frame = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([frame])
|
||||
assert module.resolve_parameter_controls_structural(page, " ") is None
|
||||
assert frame.calls == []
|
||||
|
||||
|
||||
def test_structural_resolver_none_page_returns_none():
|
||||
"""无页面上下文(纯函数调用):直接返回 None。"""
|
||||
module = _load_module()
|
||||
assert module.resolve_parameter_controls_structural(None, "Owner") is None
|
||||
|
||||
|
||||
def test_fill_multi_select_template_miss_falls_back_to_structural(monkeypatch):
|
||||
"""接线:报表模板未命中 Owner 时,落到结构性解析并把三件套传入 multi_value 填充。
|
||||
|
||||
[断言意图] 2026-10-08 事故回归:Owner@Receipt Detail@AWSRTM 未登记 ctl15 模板时,
|
||||
不得静默失败弃填(导致全货主巨报表渲染超时),必须结构性解析后正常填充。
|
||||
"""
|
||||
module = _load_module()
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||
captured.update(config_override)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "resolve_parameter_controls", lambda *a, **k: {})
|
||||
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([probe])
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Owner", ["CRTM-0000000100"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert captured == {"control": "multi_value", **_STRUCTURAL_CONTROLS}
|
||||
assert probe.calls == ["Owner"]
|
||||
|
||||
|
||||
def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch):
|
||||
"""优先级:结构性解析优先(ctl 编号随渲染漂移,注册表 ctl 条目只作回退)。
|
||||
|
||||
[断言意图] 结构性命中时使用结构性三件套、注册表回退不被消费;
|
||||
结构性未命中时才回退注册表控件。
|
||||
"""
|
||||
module = _load_module()
|
||||
registry_controls = {
|
||||
"text": "#ReportViewerMain_ctl08_ctl29_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl29_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown",
|
||||
}
|
||||
resolve_calls: list[tuple] = []
|
||||
monkeypatch.setattr(
|
||||
module, "resolve_parameter_controls",
|
||||
lambda *a, **k: (resolve_calls.append(a), dict(registry_controls))[1],
|
||||
)
|
||||
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([probe])
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||
captured.update(config_override)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Warehouse", ["RTM"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert captured.get("text") == _STRUCTURAL_CONTROLS["text"] # 结构性解析优先生效
|
||||
assert resolve_calls == [] # 结构性命中:注册表回退未被消费
|
||||
|
||||
# 结构性未命中 → 回退注册表控件
|
||||
probed = _RecordingFrame(result=None)
|
||||
page = _RecordingPage([probed])
|
||||
captured.clear()
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Warehouse", ["RTM"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
assert ok is True
|
||||
assert captured.get("text") == registry_controls["text"] # 回退到注册表
|
||||
assert probed.calls == ["Warehouse"]
|
||||
|
||||
|
||||
def test_multi_value_already_set_set_equality_not_substring():
|
||||
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
|
||||
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
|
||||
module = _load_module()
|
||||
all_owners_csv = ",".join(f"CRTM-0000000{n:03d}" for n in range(5, 449))
|
||||
|
||||
# [断言意图] 目标值是全选 CSV 的"子串"但非"全集"——不得判已设置(旧 bug 行为)。
|
||||
assert module._multi_value_already_set(all_owners_csv, ["CRTM-0000000100"]) is False
|
||||
# 完全相等的选中集合才允许跳过。
|
||||
assert module._multi_value_already_set("CRTM-0000000100", ["CRTM-0000000100"]) is True
|
||||
assert module._multi_value_already_set("CRTM-0000000100, CRTM-0000000101",
|
||||
["CRTM-0000000101", "CRTM-0000000100"]) is True
|
||||
# 边界:空当前值/空目标不判已设置;大小写与空白不敏感。
|
||||
assert module._multi_value_already_set("", ["CRTM-0000000100"]) is False
|
||||
assert module._multi_value_already_set(all_owners_csv, []) is False
|
||||
assert module._multi_value_already_set(" crtm-0000000100 ", ["CRTM-0000000100"]) is True
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
tests/test_equipment_acceptance_alert_notice.py
|
||||
|
||||
用途:锁定设备验收企微汇总文案和 Excel 列。
|
||||
依赖:alert_notice、openpyxl。
|
||||
逻辑:不连数据库,不发企业微信。卡片只写张数。工作簿含申请人,不写主送。
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_notice import (
|
||||
NOTICE_HEADERS,
|
||||
build_notice_workbook,
|
||||
summary_message,
|
||||
)
|
||||
|
||||
|
||||
def test_summary_counts_rounds_without_listing_orders():
|
||||
"""第一行写已逾期张数。正文不出现验收单号,也不写主送。"""
|
||||
text = summary_message([
|
||||
{"threshold_days": 30},
|
||||
{"threshold_days": 30},
|
||||
{"threshold_days": 37},
|
||||
])
|
||||
assert text == "共 3 张验收单已逾期。\n超过 30 天 2 张,超过 37 天 1 张。\n明细见下一条文件。"
|
||||
assert "主送" not in text
|
||||
assert "20260210" not in text
|
||||
|
||||
|
||||
def test_workbook_includes_applicant_and_identity():
|
||||
"""Excel 列与原型一致。通知身份保留角色名,停留天数为空时写横线。"""
|
||||
data = build_notice_workbook([{
|
||||
"acceptance_no": "20260210000001",
|
||||
"purchase_order_no": "1111",
|
||||
"applicant": "孙浩",
|
||||
"threshold_days": 30,
|
||||
"dwell_days": None,
|
||||
"node_name": "使用部门担当",
|
||||
"handlers": "吴敏",
|
||||
"identity": "直接主管",
|
||||
}])
|
||||
sheet = load_workbook(BytesIO(data)).active
|
||||
assert [cell.value for cell in sheet[1]] == list(NOTICE_HEADERS)
|
||||
assert [cell.value for cell in sheet[2]] == [
|
||||
"20260210000001",
|
||||
"1111",
|
||||
"孙浩",
|
||||
"超过 30 天",
|
||||
"—",
|
||||
"使用部门担当",
|
||||
"吴敏",
|
||||
"直接主管",
|
||||
]
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_alert_plan.py
|
||||
|
||||
用途:设备验收四档跨档和收件人组装的纯函数测试。
|
||||
依赖:alert_plan。不连接数据库,不访问 OA,不发企业微信。
|
||||
逻辑:超过阈值才进档。解析失败留在原角色上,不改发给别人。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_plan import (
|
||||
assemble_tier,
|
||||
due_tiers,
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
)
|
||||
|
||||
_DAYS = (30, 37, 44, 51)
|
||||
|
||||
|
||||
def test_due_tiers_use_strictly_greater_than_threshold():
|
||||
"""刚好等于 30 天还不发。超过 51 天才四档都到。"""
|
||||
assert due_tiers(None, _DAYS) == []
|
||||
assert due_tiers(30, _DAYS) == []
|
||||
assert due_tiers(31, _DAYS) == [1]
|
||||
assert due_tiers(51, _DAYS) == [1, 2, 3]
|
||||
assert due_tiers(52, _DAYS) == [1, 2, 3, 4]
|
||||
assert due_tiers(52, _DAYS, max_tier=3) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_tier_one_keeps_missing_supervisor_as_failure():
|
||||
"""直接主管缺失时整档仍可发给处理人和采购担当,不把申请人改成主送。"""
|
||||
handler = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
oa_employee_id=11,
|
||||
)
|
||||
supervisor = make_person(slot="cc", label="直接主管", name="吴敏", error="吴敏没有直接主管")
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name="赵琴",
|
||||
job_num="20001",
|
||||
user=SimpleNamespace(id=8, wecom_userid="wx-buyer", real_name="赵琴"),
|
||||
missing_job_error="没有申请人工号",
|
||||
)
|
||||
draft = assemble_tier(tier=1, threshold_days=30, to_people=[handler], cc_people=[supervisor, applicant])
|
||||
assert draft["status"] == "pending"
|
||||
assert draft["to_text"] == "吴敏"
|
||||
assert draft["cc_text"] == "赵琴"
|
||||
assert "吴敏没有直接主管" in draft["error_message"]
|
||||
assert all(item["label"] != "采购担当" or item["slot"] == "cc" for item in draft["recipients"])
|
||||
|
||||
|
||||
def test_duplicate_person_stays_only_on_the_primary_list():
|
||||
"""同一个人既是主送又是抄送时只留主送。"""
|
||||
person = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
)
|
||||
copied = dict(person)
|
||||
copied["slot"] = "cc"
|
||||
copied["label"] = "直接主管"
|
||||
draft = assemble_tier(tier=1, threshold_days=30, to_people=[person], cc_people=[copied])
|
||||
assert draft["to_text"] == "吴敏"
|
||||
assert draft["cc_text"] is None
|
||||
assert len(draft["recipients"]) == 1
|
||||
|
||||
|
||||
def test_unbound_wecom_and_missing_role_stay_failed():
|
||||
"""没绑企微、没选 COO 都记失败,不写死姓名。"""
|
||||
unbound = resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name="吴敏",
|
||||
job_num="10086",
|
||||
user=SimpleNamespace(id=7, wecom_userid="", real_name="吴敏"),
|
||||
missing_job_error="吴敏没有工号",
|
||||
)
|
||||
assert unbound["error"] == "未绑定企业微信"
|
||||
missing = resolve_configured_user(slot="to", label="COO", user=None, missing_error="未配置COO")
|
||||
draft = assemble_tier(tier=3, threshold_days=44, to_people=[missing], cc_people=[unbound])
|
||||
assert draft["status"] == "failed"
|
||||
assert draft["to_text"] is None
|
||||
assert "未配置COO" in draft["error_message"]
|
||||
assert "未绑定企业微信" in draft["error_message"]
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
tests/test_equipment_acceptance_config.py
|
||||
|
||||
用途:锁定设备验收预警四档天数和第 4 轮开关的保存前校验。
|
||||
依赖:config_service.validate_reminder_days、parse_round_4_enabled、ValidationError。
|
||||
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。第 4 轮缺省关闭。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.equipment_acceptance.config_service import parse_round_4_enabled, validate_reminder_days
|
||||
|
||||
|
||||
def test_default_reminder_days_pass():
|
||||
"""冻结默认值可以保存。"""
|
||||
assert validate_reminder_days([30, 37, 44, 51]) == (30, 37, 44, 51)
|
||||
|
||||
|
||||
def test_days_must_increase():
|
||||
"""后一档不大于前一档时拒绝,避免两档在同一天触发。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_reminder_days([30, 30, 44, 51])
|
||||
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
|
||||
|
||||
|
||||
def test_days_reject_bool_and_wrong_length():
|
||||
"""布尔值在 Python 里也是 int,不能当成 1 天;档数必须是四档。"""
|
||||
with pytest.raises(ValidationError):
|
||||
validate_reminder_days([True, 37, 44, 51])
|
||||
with pytest.raises(ValidationError):
|
||||
validate_reminder_days([30, 37, 44])
|
||||
|
||||
|
||||
def test_round_4_defaults_off_and_rejects_non_bool():
|
||||
"""未传开关时按关闭处理。数字 1 不能当成启用,避免误通知总经理。"""
|
||||
assert parse_round_4_enabled(None) is False
|
||||
assert parse_round_4_enabled(False) is False
|
||||
assert parse_round_4_enabled(True) is True
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_round_4_enabled(1)
|
||||
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
|
||||
@@ -0,0 +1,257 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_snapshot.py
|
||||
|
||||
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
EXCLUDED,
|
||||
NOT_STARTED,
|
||||
STOPPED_ARCHIVED,
|
||||
STOPPED_CANNOT_ACCEPT,
|
||||
STOPPED_FORCE_FINISHED,
|
||||
STOPPED_RETURNED,
|
||||
STOPPED_REVOKED,
|
||||
STOPPED_VOIDED,
|
||||
WATCHING,
|
||||
can_accept_from_oa,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import group_acceptance_rows
|
||||
|
||||
|
||||
def test_oa_yes_no_is_flipped_before_storage():
|
||||
"""OA 0 是、1 否。验收空值保持空;退回空值收成否。其他值不猜测。"""
|
||||
assert can_accept_from_oa(0) == 1
|
||||
assert can_accept_from_oa(1) == 0
|
||||
assert can_accept_from_oa(None) is None
|
||||
assert can_accept_from_oa(2) == 2
|
||||
assert is_returned_from_oa(0) == 1
|
||||
assert is_returned_from_oa(1) == 0
|
||||
assert is_returned_from_oa(None) == 0
|
||||
assert is_returned_from_oa(2) == 2
|
||||
|
||||
|
||||
def test_returned_yes_stops_even_while_approving():
|
||||
"""is_returned=1 是退回,审批中也停表。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=1, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == STOPPED_RETURNED
|
||||
|
||||
|
||||
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||
stopped = classify_monitor_status(
|
||||
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
excluded = classify_monitor_status(
|
||||
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||
assert excluded == EXCLUDED
|
||||
|
||||
|
||||
def test_not_returned_and_can_accept_watches():
|
||||
"""未退回且可以验收、审批中、已有计时起点时继续计时。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == WATCHING
|
||||
|
||||
|
||||
def test_terminal_flow_status_stops():
|
||||
"""3/4/5 分别停表。7、8、99、-99 都是撤销,没有计时起点也不再提醒。"""
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=3, timer_started=True) == STOPPED_ARCHIVED
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=4, timer_started=True) == STOPPED_FORCE_FINISHED
|
||||
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=5, timer_started=True) == STOPPED_VOIDED
|
||||
for flow_status in (7, 8, 99, -99):
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=True
|
||||
) == STOPPED_REVOKED
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=False
|
||||
) == STOPPED_REVOKED
|
||||
|
||||
|
||||
def test_missing_timer_is_not_started_when_no_stop_reason():
|
||||
"""没有计时起点且没有停表原因时是未开始。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=1, timer_started=False
|
||||
)
|
||||
assert status == NOT_STARTED
|
||||
|
||||
|
||||
def test_unknown_returned_is_excluded():
|
||||
"""0、1 以外的退回值既不判退回也不当未退回。"""
|
||||
status = classify_monitor_status(
|
||||
can_accept=1, is_returned=2, flow_status=1, timer_started=True
|
||||
)
|
||||
assert status == EXCLUDED
|
||||
|
||||
|
||||
def test_dwell_days_freeze_on_archive_date():
|
||||
"""归档后的天数截止到归档日,不随同步日继续增加。"""
|
||||
days = dwell_days(
|
||||
timer_started_at=datetime(2026, 9, 1, 8, 0, 0),
|
||||
flow_status=3,
|
||||
finished_at=datetime(2026, 9, 11, 18, 0, 0),
|
||||
as_of=date(2026, 10, 8),
|
||||
)
|
||||
assert days == 10
|
||||
|
||||
|
||||
def test_dwell_days_use_sync_date_while_watching():
|
||||
"""计时中按同步日减起点的自然日。"""
|
||||
days = dwell_days(
|
||||
timer_started_at=date(2026, 10, 1),
|
||||
flow_status=1,
|
||||
finished_at=None,
|
||||
as_of=date(2026, 10, 8),
|
||||
)
|
||||
assert days == 7
|
||||
|
||||
|
||||
def test_group_splits_requests_and_dedupes_operators():
|
||||
"""不同 requestid 各成一张单。同一节点同一人只留一行,即使源行带了不同的 isremark。没有 requestid 的行跳过。"""
|
||||
drafts, skipped = group_acceptance_rows(
|
||||
[
|
||||
{
|
||||
"ysddh": "YS-1",
|
||||
"cgdh": "CG-1",
|
||||
"htbh": "HT-1",
|
||||
"sbsyrjssj": "2026-10-01 09:00:00",
|
||||
"sfkyzcys": 0,
|
||||
"ycsm": " 到货规格与请购不符 ",
|
||||
"sfzfth": None,
|
||||
"requestid": 10,
|
||||
"flowstatus": 3,
|
||||
"nodeid": 1,
|
||||
"nodename": "旧节点",
|
||||
"userid": 7,
|
||||
"isremark": 2,
|
||||
},
|
||||
{
|
||||
"ysddh": "YS-2",
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 8,
|
||||
"isremark": 0,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 9,
|
||||
"isremark": 2,
|
||||
},
|
||||
{
|
||||
"requestid": 20,
|
||||
"flowstatus": 1,
|
||||
"nodeid": 2,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 8,
|
||||
"isremark": 9,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{"ysddh": "NO-REQUEST"},
|
||||
]
|
||||
)
|
||||
assert skipped == 1
|
||||
by_request = {draft.request_id: draft for draft in drafts}
|
||||
assert set(by_request) == {10, 20}
|
||||
assert by_request[10].acceptance_no == "YS-1"
|
||||
assert by_request[10].contract_no == "HT-1"
|
||||
assert by_request[10].can_accept == 1
|
||||
assert by_request[10].cannot_accept_note == "到货规格与请购不符"
|
||||
assert by_request[10].is_returned == 0
|
||||
assert by_request[10].flow_status_raw == 3
|
||||
current = by_request[20]
|
||||
assert current.request_match_count == 1
|
||||
assert current.flow_status_raw == 1
|
||||
assert [node.node_name for node in current.nodes] == ["使用部门担当"]
|
||||
assert sorted(item.user_id for item in current.operators) == [8, 9]
|
||||
assert not hasattr(current.operators[0], "isremark")
|
||||
|
||||
|
||||
def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
||||
"""实例同时有字典库时用 weaver_wfc / weaver_wfp,SQL 不查询 isremark。"""
|
||||
catalogs = resolve_catalogs({"ecology10", "eteams", "weaver_wfc", "weaver_wfp"})
|
||||
sql = build_acceptance_sql(catalogs)
|
||||
assert catalogs.request == "weaver_wfc"
|
||||
assert catalogs.node == "weaver_wfp"
|
||||
assert "[weaver_wfc].[dbo].[wfc_operate]" in sql
|
||||
assert "[weaver_wfp].[dbo].[wfp_node]" in sql
|
||||
assert "isremark" not in sql.lower()
|
||||
assert "ycsm" in sql
|
||||
assert "workflow_requestbase" not in sql
|
||||
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||
assert "lcbh" not in sql
|
||||
assert "htbh1" not in sql
|
||||
assert "ysrq" not in sql
|
||||
assert "requestmark" not in sql
|
||||
assert "operateround" not in sql.lower()
|
||||
assert "optgroupid" not in sql.lower()
|
||||
assert "batch_number" not in sql.lower()
|
||||
assert "operate_log_id" not in sql.lower()
|
||||
|
||||
|
||||
def test_sql_falls_back_when_dictionary_catalog_is_absent():
|
||||
"""看不到 weaver_wfc 时,流程表改用 ecology10。人员库缺失则失败。"""
|
||||
catalogs = resolve_catalogs({"ecology10", "eteams"})
|
||||
assert catalogs.request == "ecology10"
|
||||
assert catalogs.node == "ecology10"
|
||||
with pytest.raises(ValueError):
|
||||
resolve_catalogs({"ecology10"})
|
||||
|
||||
|
||||
def test_sql_rejects_unsafe_catalog_override():
|
||||
"""库名覆盖值不能带分号或空格。"""
|
||||
with pytest.raises(ValueError):
|
||||
resolve_catalogs({"ecology10", "eteams"}, request="weaver_wfc;drop")
|
||||
|
||||
|
||||
def test_send_record_payload_keeps_written_names():
|
||||
"""发送记录接口用写入时的单号和主送抄送,不回读当前岗位。"""
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
|
||||
from app.services.equipment_acceptance.send_record_service import send_record_payload
|
||||
|
||||
row = EquipmentAcceptanceSendRecord(
|
||||
id=3,
|
||||
order_id=9,
|
||||
acceptance_no="YS-1",
|
||||
purchase_order_no="CG-1",
|
||||
tier=2,
|
||||
threshold_days=37,
|
||||
to_text="经副理甲",
|
||||
cc_text="COO、采购经副理",
|
||||
status="sent",
|
||||
sent_at=datetime(2026, 10, 9, 10, 0, 0),
|
||||
error_message=None,
|
||||
created_at=datetime(2026, 10, 9, 9, 0, 0),
|
||||
)
|
||||
payload = send_record_payload(row)
|
||||
assert payload["acceptance_no"] == "YS-1"
|
||||
assert payload["to_text"] == "经副理甲"
|
||||
assert payload["cc_text"] == "COO、采购经副理"
|
||||
assert payload["threshold_days"] == 37
|
||||
assert payload["status"] == "sent"
|
||||
assert payload["sent_at"]
|
||||
@@ -266,3 +266,49 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
assert saved.status == 'empty'
|
||||
assert saved.error_code == 'no_receipt_data'
|
||||
assert saved.error_message == 'no_receipt_data'
|
||||
|
||||
|
||||
def test_receipt_progress_routes_are_registered(app):
|
||||
"""回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。
|
||||
|
||||
2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、
|
||||
在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。
|
||||
"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key'
|
||||
client = app.test_client()
|
||||
headers = {'X-Integration-Key': 'test-tool-key'}
|
||||
for path, payload in (
|
||||
('/api/shipping-notice/rpa/receipt-unit-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}),
|
||||
('/api/shipping-notice/rpa/receipt-batch-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}),
|
||||
):
|
||||
# [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层
|
||||
# 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。
|
||||
resp = client.post(path, json=payload, headers=headers)
|
||||
assert resp.status_code == 200, (path, resp.status_code, resp.get_json())
|
||||
assert resp.get_json()['data']['updated'] is False
|
||||
|
||||
|
||||
def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
|
||||
"""跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
|
||||
with app.app_context():
|
||||
drop_root = tmp_path / 'receipt-drop'
|
||||
drop_root.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root)
|
||||
target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
target.write_bytes(b'receipt-bytes')
|
||||
|
||||
# [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都
|
||||
# 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。
|
||||
assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||
assert _read_receipt_callback_file(
|
||||
r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
) == b'receipt-bytes'
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'x')
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
@@ -132,20 +132,68 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
# [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。
|
||||
# [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。
|
||||
assert outcome == {'finalized': True, 'status': 'success'}
|
||||
assert len(textcards) == 1
|
||||
assert '原始收料包:已随本通知发送' in textcards[0][1]
|
||||
assert len(media_uploads) == 1
|
||||
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip')
|
||||
assert file_sends == ['media-1']
|
||||
assert len(media_uploads) == 2
|
||||
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx')
|
||||
assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip')
|
||||
assert file_sends == ['media-1', 'media-2']
|
||||
assert run.wecom_notified is True
|
||||
assert run.response_summary_json.get('raw_receipt_zip_available') is True
|
||||
|
||||
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
|
||||
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
assert len(textcards) == 1 and len(file_sends) == 1
|
||||
assert len(textcards) == 1 and len(file_sends) == 2
|
||||
|
||||
|
||||
def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。"""
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
|
||||
unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
|
||||
unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
|
||||
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
|
||||
db.session.commit()
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
# [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。
|
||||
assert outcome == {'finalized': True, 'status': 'partial_failed'}
|
||||
assert run.excel_file_data
|
||||
assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx')
|
||||
assert run.response_summary_json['excel_export_status'] == 'ok'
|
||||
assert run.response_summary_json['excel_failed'] is False
|
||||
|
||||
# [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。
|
||||
workbook = load_workbook(BytesIO(run.excel_file_data))
|
||||
sheet = workbook.active
|
||||
header = [cell.value for cell in sheet[1]]
|
||||
assert header[:2] == ['收料源', '仓库']
|
||||
rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)}
|
||||
assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success'
|
||||
assert rows['DSV360_AWSCV'][4] == 'skipped'
|
||||
assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout'
|
||||
|
||||
|
||||
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
|
||||
|
||||
@@ -1909,8 +1909,10 @@ def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypat
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
# 2026-09-20 页面改版后 #lanNavSel 既是标签读取点也是下拉开关(先于旧 #kc_locale 点击),
|
||||
# 因此点击它须置 opened,模拟“点开语言菜单”。
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("label")
|
||||
return _FakeLocator("toggle")
|
||||
if selector == "#kc_locale":
|
||||
return _FakeLocator("toggle")
|
||||
if "中文简体" in selector:
|
||||
@@ -2123,6 +2125,292 @@ def test_wait_for_dsv_login_method_page_skips_human_check_when_not_detected(monk
|
||||
assert human_check_calls["value"] == 0
|
||||
|
||||
|
||||
def test_is_dsv_password_upgrade_redirect_accepts_auth_dsv_com_resume():
|
||||
"""auth.dsv.com 的 resume/authorization.ping 也必须识别为密码升级提示地址。
|
||||
|
||||
[2026-10-12 回归] PingFederate resume 链迁移至 auth.dsv.com 后,旧的单域硬编码
|
||||
返回 False,导致升级提示检测不到、登录卡死在“使用密码升级登录!”页不点「也许以后」。
|
||||
"""
|
||||
_load_freight_rpa_worker()
|
||||
import dsv_auth
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||
|
||||
assert dsv_auth._is_dsv_password_upgrade_redirect(_FakePage()) is True
|
||||
|
||||
|
||||
def test_is_dsv_oauth_handshake_and_ping_urls_accept_auth_dsv_com():
|
||||
"""OAuth 握手 / authorization.ping 判定须覆盖 auth.dsv.com 双认证域。"""
|
||||
_load_freight_rpa_worker()
|
||||
import dsv_auth
|
||||
|
||||
assert dsv_auth.is_dsv_oauth_handshake_url(
|
||||
"https://auth.dsv.com/as/mock/as/authorization.oauth2"
|
||||
) is True
|
||||
assert dsv_auth.is_dsv_auth_ping_url(
|
||||
"https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||
) is True
|
||||
assert dsv_auth.is_dsv_oauth_handshake_url("https://s360.dbschenker.com/main") is False
|
||||
assert dsv_auth.is_dsv_auth_ping_url("https://s360.dbschenker.com/main") is False
|
||||
|
||||
|
||||
def test_looks_like_dsv_identifier_chooser_matches_strong_markers_only():
|
||||
"""「选择登录方法」标题命中且无密码框 → 已记住标识页;用户名页不得误判。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.body = body
|
||||
self.first = self
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self.body
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def count(self) -> int:
|
||||
return 0
|
||||
|
||||
class _FakeFrame:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.body = body
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator(self.body)
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.frames = [_FakeFrame(body)]
|
||||
|
||||
chooser_body = (
|
||||
"欢迎\nhtcus@hoo-thai.com\n选择登录方法\n通行密钥\n使用此设备登录。\n"
|
||||
"移动应用程序 (iPhone 11)\n密码\n输入您的密码并登录。\n取消"
|
||||
)
|
||||
assert worker._looks_like_dsv_identifier_chooser(_FakePage(chooser_body)) is True
|
||||
|
||||
username_body = "电子邮件或SIMS ID或手机号\n继续\n忘记密码"
|
||||
assert worker._looks_like_dsv_identifier_chooser(_FakePage(username_body)) is False
|
||||
|
||||
|
||||
def test_has_dsv_password_upgrade_prompt_on_auth_dsv_com_upgrade_page():
|
||||
"""升级提示检测在 auth.dsv.com resume 页必须生效,否则不点「也许以后」直接卡死。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
upgrade_body = "使用密码升级登录!\n从密码和电子邮件中解脱出来。\n也许以后\n立即启用"
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return upgrade_body
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
|
||||
|
||||
|
||||
def test_maybe_auto_login_dsv_chooser_first_skips_username_and_completes(monkeypatch):
|
||||
"""已记住标识:方法选择页预检命中 → 跳过用户名等待/继续点击,直进密码阶段完成登录。
|
||||
|
||||
[2026-10-12 回归] 首版实现 chooser 分支漏初始化 user_filled,命中即抛
|
||||
UnboundLocalError 导致整源失败;且选择页判定在用户名等待超时后才做,每源白等约 2 分钟。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
g = worker._maybe_auto_login_dsv.__globals__
|
||||
state = {
|
||||
"continue_clicked": False,
|
||||
"purge_called": False,
|
||||
"password_method_clicked": False,
|
||||
"submitted": False,
|
||||
"home_ready": False,
|
||||
"find_password_calls": 0,
|
||||
}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def fill(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
password_locator = _FakeLocator()
|
||||
|
||||
def fake_find_password(page, timeout_ms: int = 250):
|
||||
state["find_password_calls"] += 1
|
||||
return password_locator if state["find_password_calls"] >= 2 else None
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||
frames: list = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setitem(
|
||||
g, "_env",
|
||||
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||
)
|
||||
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: True)
|
||||
monkeypatch.setitem(g, "_click_dsv_continue", lambda page, locator: state.__setitem__("continue_clicked", True))
|
||||
monkeypatch.setitem(
|
||||
g, "_retry_dsv_login_with_purged_cookies", lambda page, username: state.__setitem__("purge_called", True)
|
||||
)
|
||||
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||
monkeypatch.setitem(g, "_fill_dsv_password_page_fields", lambda page, username, password: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_login_method_page", lambda page, timeout_ms=None: True)
|
||||
monkeypatch.setitem(
|
||||
g, "_click_dsv_password_method",
|
||||
lambda page: (state.__setitem__("password_method_clicked", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
g, "_submit_dsv_password_form",
|
||||
lambda page: (state.__setitem__("submitted", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||
monkeypatch.setitem(
|
||||
g, "_wait_for_dsv_home_ready_after_login",
|
||||
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
ticks["value"] += 0.25
|
||||
return ticks["value"]
|
||||
|
||||
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||
|
||||
worker._maybe_auto_login_dsv(_FakePage())
|
||||
|
||||
assert state["continue_clicked"] is False, "chooser-first 不得点击继续按钮"
|
||||
assert state["purge_called"] is False, "chooser-first 不得触发 Cookie 清空兜底"
|
||||
assert state["password_method_clicked"] is True
|
||||
assert state["submitted"] is True
|
||||
assert state["home_ready"] is True
|
||||
|
||||
|
||||
def test_maybe_auto_login_dsv_generic_fill_reaches_continue_without_unbound(monkeypatch):
|
||||
"""无用户名选择器时走通用填装:username_locator=None 传给继续点击,不得抛 UnboundLocalError。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
g = worker._maybe_auto_login_dsv.__globals__
|
||||
state = {
|
||||
"continue_args": None,
|
||||
"submitted": False,
|
||||
"home_ready": False,
|
||||
"find_password_calls": 0,
|
||||
}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def fill(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
password_locator = _FakeLocator()
|
||||
|
||||
def fake_find_password(page, timeout_ms: int = 250):
|
||||
state["find_password_calls"] += 1
|
||||
return password_locator
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||
frames: list = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setitem(
|
||||
g, "_env",
|
||||
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||
)
|
||||
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: False)
|
||||
monkeypatch.setitem(g, "_fill_first_visible_text_input", lambda page, username: True)
|
||||
|
||||
def fake_click_continue(page, locator):
|
||||
state["continue_args"] = locator
|
||||
return True
|
||||
|
||||
monkeypatch.setitem(g, "_click_dsv_continue", fake_click_continue)
|
||||
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||
monkeypatch.setitem(
|
||||
g, "_submit_dsv_password_form",
|
||||
lambda page: (state.__setitem__("submitted", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||
monkeypatch.setitem(
|
||||
g, "_wait_for_dsv_home_ready_after_login",
|
||||
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
ticks["value"] += 0.25
|
||||
return ticks["value"]
|
||||
|
||||
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||
|
||||
worker._maybe_auto_login_dsv(_FakePage())
|
||||
|
||||
assert state["continue_args"] is None, "通用填装路径 username_locator 应显式为 None"
|
||||
assert state["submitted"] is True
|
||||
assert state["home_ready"] is True
|
||||
|
||||
|
||||
def test_find_dsv_password_locator_returns_visible_locator():
|
||||
"""密码方式切换轮询应走轻量密码框探测,而不是长时间通用等待。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -29,6 +29,7 @@ _RPA_MODULE_PATHS = {
|
||||
"dsv_auth": "connectors/dsv/dsv_auth.py",
|
||||
"dsv_session": "connectors/dsv/dsv_session.py",
|
||||
"dsv_debug": "connectors/dsv/dsv_debug.py",
|
||||
"dsv_report_parameters": "connectors/dsv/dsv_report_parameters.py",
|
||||
}
|
||||
|
||||
|
||||
@@ -449,6 +450,7 @@ def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
|
||||
worker._navigate_dsv_to_report_form(
|
||||
page,
|
||||
@@ -581,6 +583,7 @@ def test_navigate_dsv_to_report_form_retries_once_with_home_reset(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||
@@ -608,6 +611,7 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
chain = MagicMock()
|
||||
@@ -630,6 +634,177 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
||||
assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list)
|
||||
|
||||
|
||||
def _fake_dsv_page_with_frames(*frames):
|
||||
page = MagicMock()
|
||||
page.frames = list(frames)
|
||||
return page
|
||||
|
||||
|
||||
def _fake_dsv_frame(url: str, body: str):
|
||||
frame = MagicMock()
|
||||
frame.url = url
|
||||
frame.locator.return_value.inner_text.return_value = body
|
||||
return frame
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_passes_for_expected_program():
|
||||
"""SSRS viewer 标题含 program_label 时应判定打开了目标报表,直接放行。"""
|
||||
worker = _load_dsv_report_export()
|
||||
viewer = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/S360Reports/SSRS/f26275b5?token=x&isLegacy=true",
|
||||
"On Hand Inventory By Location AWS > Moerdijk > AWSRTM favorite_border",
|
||||
)
|
||||
page = _fake_dsv_page_with_frames(viewer)
|
||||
|
||||
worker._assert_dsv_report_viewer_identity(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||
timeout_ms=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_raises_on_wrong_program():
|
||||
"""viewer 载入 Bison 3lv(AWS > Bison > AWSBI)时应报身份不匹配。
|
||||
|
||||
2026-10-09 AWSRTM 事故回归:portal 顶层 Recent Reports 文本同样含 AWSRTM,
|
||||
门禁只认 /s360reports/ssrs/ viewer frame,顶层的 AWSRTM 字样不得误判为匹配。
|
||||
"""
|
||||
worker = _load_dsv_report_export()
|
||||
portal = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/main/portal/frame/reports/x",
|
||||
"RECENT REPORTS On Hand Inventory By Location (Moerdijk > AWSRTM)",
|
||||
)
|
||||
viewer = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/S360Reports/SSRS/d40ada0a?token=x&isLegacy=true",
|
||||
"On Hand Inventory By Location 3lv AWS > Bison > AWSBI favorite_border",
|
||||
)
|
||||
page = _fake_dsv_page_with_frames(portal, viewer)
|
||||
|
||||
import pytest
|
||||
|
||||
with pytest.raises(RuntimeError, match="identity mismatch"):
|
||||
worker._assert_dsv_report_viewer_identity(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||
timeout_ms=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_skips_without_program_label():
|
||||
"""配置缺 program_label 时应跳过身份校验(保持旧行为,不因无身份信息而失败)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = _fake_dsv_page_with_frames()
|
||||
|
||||
worker._assert_dsv_report_viewer_identity(page, {"navigation": {"report_name": "X"}}, timeout_ms=1000)
|
||||
|
||||
|
||||
def test_navigate_dsv_to_report_form_resets_home_when_viewer_identity_mismatch(monkeypatch):
|
||||
"""viewer 载错报表(身份不匹配)时应整页 reset 后重导一次(2026-10-09 AWSRTM 串报修复)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
|
||||
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
identity = MagicMock(side_effect=[RuntimeError("identity mismatch"), None])
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", identity)
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||
|
||||
source = {
|
||||
"entry_url": "https://s360.dbschenker.com/main/portal",
|
||||
"navigation": {
|
||||
"program_group": "Moerdijk",
|
||||
"program_label": "AWSRTM",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
},
|
||||
}
|
||||
assert worker._navigate_dsv_to_report_form(page, source) == "On Hand Inventory by Location"
|
||||
assert identity.call_count == 2
|
||||
reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal")
|
||||
|
||||
|
||||
def test_fill_dsv_filter_returns_false_when_all_paths_fail(monkeypatch):
|
||||
"""配置了值但 multi_value/select/脚本/fill 全部失败时应返回 False(FILL-FAIL-FAST 契约)。"""
|
||||
params = _load_rpa_module("dsv_report_parameters")
|
||||
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||
monkeypatch.setattr(params, "_probe_report_parameter_controls", lambda page: {})
|
||||
|
||||
result = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
assert result is False
|
||||
|
||||
|
||||
def test_fill_dsv_filter_returns_true_on_success_and_legitimate_skip(monkeypatch):
|
||||
"""填充成功或合法跳过(值为空)应返回 True,不得被包装层误判为失败。"""
|
||||
params = _load_rpa_module("dsv_report_parameters")
|
||||
# JDA 模板下 Warehouse 是 multi_value 控件:mock 主路径成功即可验证 True 契约。
|
||||
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||
|
||||
filled = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
skipped = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
None,
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
assert filled is True
|
||||
assert skipped is True
|
||||
|
||||
|
||||
def test_fill_dsv_filter_wrapper_raises_on_fill_failure(monkeypatch):
|
||||
"""包装层在 fill 返回 False 时必须抛错中止本源(2026-10-09 静默吞掉曾连环误报)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
fake_module = MagicMock()
|
||||
fake_module.fill_dsv_filter_if_needed.return_value = False
|
||||
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||
|
||||
import pytest
|
||||
|
||||
with pytest.raises(RuntimeError, match="fill failed"):
|
||||
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||
|
||||
|
||||
def test_fill_dsv_filter_wrapper_silent_on_fill_success(monkeypatch):
|
||||
"""fill 返回 True(已填充/合法跳过)时包装层不得抛错。"""
|
||||
worker = _load_dsv_report_export()
|
||||
fake_module = MagicMock()
|
||||
fake_module.fill_dsv_filter_if_needed.return_value = True
|
||||
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||
|
||||
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||
|
||||
|
||||
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
||||
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
|
||||
worker = _load_dsv_report_export()
|
||||
@@ -696,6 +871,7 @@ def test_navigate_dsv_to_report_form_clicks_program_group_before_program_label(m
|
||||
lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
|
||||
source = {
|
||||
"navigation": {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
tests/test_inventory_source_gate_notice_task.py
|
||||
|
||||
用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。
|
||||
依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。
|
||||
逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿
|
||||
order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id
|
||||
字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被
|
||||
「库存源尚未确定」静默拦截(无事件、无 attempt 记录)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _make_frozen_task_with_notice(task_no: str):
|
||||
"""构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
input_fingerprint=f'fp-{task_no}',
|
||||
routing_rule_version_json={},
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='CRANE',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
part_number='PN-1',
|
||||
reservation_id='3000092917',
|
||||
source_codes_json=['CRANE'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = int(candidate_set.id)
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no=f'SN-{task_no}',
|
||||
order_task_id=int(task.id),
|
||||
business_no=f'USZ{task_no[-6:]}',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return task, notice
|
||||
|
||||
|
||||
def _patch_source_lookup(monkeypatch):
|
||||
"""注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
|
||||
def _source(code):
|
||||
if str(code).upper() != 'CRANE':
|
||||
return None
|
||||
return {
|
||||
'source_code': 'CRANE',
|
||||
'display_name': 'Crane FootPrint',
|
||||
'connector_type': 'crane',
|
||||
'warehouse_resolution_mode': 'inventory_match',
|
||||
'fixed_warehouse_id': None,
|
||||
'enabled': True,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
|
||||
|
||||
|
||||
def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch):
|
||||
"""门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
|
||||
task, notice = _make_frozen_task_with_notice('OT-NOTICE-GATE-OK')
|
||||
# 断言意图:OT 与其 Notice 的稳定性判定一致(历史缺陷:Notice 恒 False)
|
||||
assert is_inventory_source_stable(task) is True
|
||||
assert is_inventory_source_stable(notice) is True
|
||||
# 断言意图:库存身份(RPA 网点/仓库)对两者一致,且能解析到源
|
||||
identity_ot = task_inventory_identity(task)
|
||||
identity_notice = task_inventory_identity(notice)
|
||||
assert identity_ot == identity_notice
|
||||
assert identity_notice['inventory_source_code'] == 'CRANE'
|
||||
|
||||
|
||||
def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch):
|
||||
"""Notice 缺 OT 绑定时保持 fail-closed(不得误判稳定)。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no='SN-ORPHAN-NOTICE',
|
||||
business_no='USZORPH01',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(orphan)
|
||||
db.session.flush()
|
||||
# 断言意图:无法归一到 OT 的 Notice 保持 fail-closed
|
||||
assert is_inventory_source_stable(orphan) is False
|
||||
@@ -1,15 +1,17 @@
|
||||
"""
|
||||
tests/test_line_inventory_match_persistence.py
|
||||
|
||||
用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。
|
||||
依赖:pytest、line_inventory_match_persistence。
|
||||
逻辑:纯单元;不写库。
|
||||
用途:锁定 disposition → match_result 映射、not_found/invalid_key 语义,
|
||||
及行级匹配事实落库契约(含料号兜底总量 part_available_qty)。
|
||||
依赖:pytest、line_inventory_match_persistence、app 夹具(persist 用例)。
|
||||
逻辑:映射用例纯单元;persist 用例写库(内存测试库),不触外部集成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
map_disposition_to_match_codes,
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
|
||||
|
||||
@@ -54,3 +56,222 @@ def test_ok_and_shortage_are_matched_ready():
|
||||
assert map_disposition_to_match_codes(
|
||||
disposition='shortage', part_number='A', reservation_id='B',
|
||||
) == ('matched', 'ready')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# persist_line_inventory_match_facts 落库契约(依赖 app 夹具,写内存测试库)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_snapshot_task(task_no: str):
|
||||
"""
|
||||
构造含两行冻结快照的 OT 任务,供 persist 落库测试复用。
|
||||
|
||||
核心逻辑:持久化按 order_snapshot_id → ShippingOrderSnapshot.lines 的 line_no
|
||||
解析 snapshot_line_id;第 1 行料号/预约号齐全,第 2 行缺料号
|
||||
(对齐匹配器「缺料号行不下发 part_available_qty 键」的真实产出,见
|
||||
test_shipping_stp_phase4_line_inventory_match.py 的兜底总量用例)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
|
||||
|
||||
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=1,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
rule_versions_json={},
|
||||
source_manifest_json={},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
lines = [
|
||||
{'line_no': 1, 'part_number': 'PN-1', 'reservation_id': '3000092917', 'qty': 8},
|
||||
{'line_no': 2, 'part_number': None, 'reservation_id': '3000092918', 'qty': 1},
|
||||
]
|
||||
for position, line in enumerate(lines):
|
||||
db.session.add(
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=position,
|
||||
line_no=line['line_no'],
|
||||
part_number=line['part_number'],
|
||||
reservation_id=line['reservation_id'],
|
||||
qty=line['qty'],
|
||||
field_values_json={},
|
||||
)
|
||||
)
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _not_found_result(*, part_available_qty, line_index: int = 0) -> dict:
|
||||
"""
|
||||
构造 not_found 行结果桩。
|
||||
|
||||
核心逻辑:part_available_qty 传 None 时**不下发该键**(而非显式 None),
|
||||
对齐匹配器对 conflict/缺料号行「无键即无兜底」的契约;持久化必须按
|
||||
无键 → NULL 处理。
|
||||
"""
|
||||
result = {
|
||||
'line_index': line_index,
|
||||
'disposition': 'not_found',
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'required_qty': 8.0,
|
||||
'available_qty': 0.0,
|
||||
}
|
||||
if part_available_qty is not None:
|
||||
result['part_available_qty'] = part_available_qty
|
||||
return result
|
||||
|
||||
|
||||
def test_persist_writes_part_available_qty_for_not_found_line(app):
|
||||
"""预约不匹配行的料号兜底总量必须随匹配事实落库。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-PART-AVAILABLE-NEW')
|
||||
match_payload = {
|
||||
'line_results': [
|
||||
_not_found_result(part_available_qty=8.0),
|
||||
_not_found_result(part_available_qty=None, line_index=1),
|
||||
],
|
||||
'resolutions': [],
|
||||
}
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=match_payload,
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
# 断言意图:兜底总量字符串化落列
|
||||
assert str(rows[0].part_available_qty) == '8.0'
|
||||
# 断言意图:无键/None 时必须落 NULL 而非 'None'
|
||||
assert rows[1].part_available_qty is None
|
||||
|
||||
|
||||
def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||
"""同快照幂等更新时,料号兜底总量必须以最新匹配结果为准。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-PART-AVAILABLE-UPDATE')
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=8.0)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=13.0)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
# 断言意图:更新分支同样把新兜底总量字符串化落列
|
||||
assert str(rows[0].part_available_qty) == '13.0'
|
||||
# 断言意图:更新时键缺失 → 回写 NULL,不得残留旧值或 'None'
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=None)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
assert rows[0].part_available_qty is None
|
||||
# 断言意图:同快照幂等更新,始终只有一条 current 事实
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 行级文件归因契约(多源池:锚点文件 ≠ 命中文件)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int:
|
||||
"""构造最小可用库存快照文件,返回主键。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
file_row = ShippingInventoryFile(
|
||||
inventory_file_no=file_no,
|
||||
storage_path=f'/tmp/{file_no}.xlsx',
|
||||
source_code='DSV360_TEST',
|
||||
warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id,
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
share_mode='warehouse_pool',
|
||||
)
|
||||
db.session.add(file_row)
|
||||
db.session.flush()
|
||||
return int(file_row.id)
|
||||
|
||||
|
||||
def _ok_result(*, line_index: int = 0, inventory_file_no: str | None = None) -> dict:
|
||||
"""构造命中库存的行结果桩;inventory_file_no 模拟匹配器回填的命中文件身份。"""
|
||||
result = {
|
||||
'line_index': line_index,
|
||||
'disposition': 'ok',
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'required_qty': 8.0,
|
||||
'available_qty': 8.0,
|
||||
}
|
||||
if inventory_file_no is not None:
|
||||
result['inventory_file_no'] = inventory_file_no
|
||||
return result
|
||||
|
||||
|
||||
def test_persist_attributes_line_to_hit_file_not_anchor(app):
|
||||
"""多源池下行命中 B 文件时,inventory_snapshot_id 必须归因 B,而非任务锚点 A。
|
||||
|
||||
历史缺陷:持久化把任务级锚点文件 ID 盖到所有行,Excel 仓库列因此写成
|
||||
锚点仓(AWSCV 单写成 CMH01)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
task = _make_snapshot_task('OT-LINE-FILE-ATTR')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01')
|
||||
hit_id = _make_inventory_file(app, 'SIF-TEST-HIT', 'AWSCV')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_ok_result(inventory_file_no='SIF-TEST-HIT')],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:行事实挂到命中文件,而不是任务级锚点文件
|
||||
assert rows[0].inventory_snapshot_id == hit_id
|
||||
assert rows[0].matched_file_no == 'SIF-TEST-HIT'
|
||||
# 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源)
|
||||
hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id)
|
||||
assert hit_file.warehouse_id == 'AWSCV'
|
||||
|
||||
|
||||
def test_persist_falls_back_to_anchor_without_line_file_no(app):
|
||||
"""行结果未回填文件号(如 not_found)时,保持任务级锚点回退,行为不变。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-LINE-FILE-FALLBACK')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR-FB', 'BYAWSCMH01')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=None)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容)
|
||||
assert rows[0].inventory_snapshot_id == anchor_id
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
ACTION_CLOSE,
|
||||
ACTION_RELEASE_SHORTAGE,
|
||||
ACTION_RETRY_MATCHING,
|
||||
ACTION_RETRY_PREPARATION,
|
||||
normalize_match_quantities,
|
||||
@@ -116,7 +117,9 @@ def test_shortage_actions_preparation_and_close_only():
|
||||
user_line_status='shortage',
|
||||
)
|
||||
assert inv == [ACTION_RETRY_PREPARATION]
|
||||
assert line == [ACTION_CLOSE]
|
||||
# 断言意图(既有用例修复):对齐已上线契约(eed1068ae)——短缺行除关闭外
|
||||
# 同时下发 release_inventory_shortage(填写原因放行),本用例原断言已过期。
|
||||
assert line == [ACTION_CLOSE, ACTION_RELEASE_SHORTAGE]
|
||||
|
||||
|
||||
def test_wave_created_hides_line_actions():
|
||||
@@ -204,3 +207,28 @@ def test_user_status_maps_closed_and_system_ready():
|
||||
stored_line_status='ready_to_fulfill',
|
||||
decision_source='system',
|
||||
) == 'auto_fulfilling'
|
||||
|
||||
|
||||
def test_view_exposes_part_available_qty_gated_by_ready():
|
||||
"""料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。"""
|
||||
base = {
|
||||
'match_result': 'not_found', 'inventory_status': 'ready',
|
||||
'required_qty': '8', 'available_qty': None,
|
||||
'inventory_snapshot_id': 1, 'matched_at': None,
|
||||
'inventory_source_code': 'DSV', 'detail_json': {},
|
||||
}
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。
|
||||
assert view['available_qty'] == '0'
|
||||
assert view['part_available_qty'] == '9'
|
||||
pending = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。
|
||||
assert pending['part_available_qty'] is None
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
tests/test_order_extraction_workspace_projection.py
|
||||
|
||||
用途:锁定工作台投影中 EML 父项状态的收敛契约。
|
||||
依赖:order_extraction_workspace_projection._email_parent_rows。
|
||||
逻辑:pure_unit;运行中的 Run(queued/processing)EML 父项维持既有口径
|
||||
(parse_failed → failed,否则 processing);终态 Run 的 EML 父项必须跟随
|
||||
Run 结果收敛(failed/cancelled/completed/review_required),禁止停留在
|
||||
「处理中」——历史缺陷:全部 Unit 失败后父项仍显示处理中。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
_email_parent_rows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _run_stub(status: str, parse_status: str | None = 'parsed') -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
status=status,
|
||||
finished_at=None,
|
||||
input_snapshot_json={'intakes': [{'intake_id': 1, 'parse_status': parse_status}]},
|
||||
)
|
||||
|
||||
|
||||
def _documents() -> dict[int, dict]:
|
||||
return {
|
||||
906: {'document_id': 906, 'intake_id': 1, 'document_type': 'email_body', 'file_name': 'batch.eml'},
|
||||
}
|
||||
|
||||
|
||||
def test_queued_run_email_parent_stays_processing():
|
||||
"""运行中(queued)且未解析失败:EML 父项维持「处理中」(既有口径零变化)。"""
|
||||
rows = _email_parent_rows(
|
||||
run=_run_stub('queued'),
|
||||
documents=_documents(),
|
||||
existing_document_ids=set(),
|
||||
)
|
||||
# 关键断言:queued 运行下父项 processing,阶段为邮件解析
|
||||
assert rows[0]['status'] == 'processing'
|
||||
assert rows[0]['user_visible_stage'] == 'email_parsing'
|
||||
|
||||
|
||||
def test_failed_run_email_parent_converges_to_failed():
|
||||
"""终态 failed 的 Run:EML 父项必须收敛为 failed,不得停留「处理中」。"""
|
||||
rows = _email_parent_rows(
|
||||
run=_run_stub('failed', parse_status=None),
|
||||
documents=_documents(),
|
||||
existing_document_ids=set(),
|
||||
)
|
||||
# 关键断言:冻结 parse_status 为 None(消费型 Intake)时,failed Run 的父项
|
||||
# 曾无条件渲染 processing;现在必须跟随 Run 结果收敛
|
||||
assert rows[0]['status'] == 'failed'
|
||||
assert rows[0]['user_visible_stage'] == 'failed'
|
||||
|
||||
|
||||
def test_review_required_run_email_parent_converges_to_review():
|
||||
"""终态 review_required / partially_completed:父项收敛为需人工复核语义。"""
|
||||
for status in ('review_required', 'partially_completed'):
|
||||
rows = _email_parent_rows(
|
||||
run=_run_stub(status),
|
||||
documents=_documents(),
|
||||
existing_document_ids=set(),
|
||||
)
|
||||
# 关键断言:两种终态都投影为 review_required(partially_completed 同义)
|
||||
assert rows[0]['status'] == 'review_required', status
|
||||
|
||||
|
||||
def test_parse_failed_intake_parent_stays_failed_under_active_run():
|
||||
"""运行中但冻结 parse_status=parse_failed:父项仍为 failed(既有口径零变化)。"""
|
||||
rows = _email_parent_rows(
|
||||
run=_run_stub('processing', parse_status='parse_failed'),
|
||||
documents=_documents(),
|
||||
existing_document_ids=set(),
|
||||
)
|
||||
# 关键断言:解析失败优先于处理中,技术失败原因码保留
|
||||
assert rows[0]['status'] == 'failed'
|
||||
assert rows[0]['technical_failure_reason_code'] == 'intake_parse_failed'
|
||||
@@ -11,7 +11,8 @@ tests/test_order_profile_header_identity.py
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
别名的契约下跨措辞对齐,异义词不归并;camelCase 无分隔符表头(UnitCost/
|
||||
VendorPartNumber)与空格措辞同管线归一,不得再判身份互斥。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -296,3 +297,58 @@ def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# camelCase 无分隔符表头(真实故障:prod schema 别名 UnitCost/VendorPartNumber
|
||||
# 经 normalize_table_header 拆成 'Unit Cost'/'Vendor Part Number' 键,而匹配器
|
||||
# 词管线不拆驼峰,token 'UnitCost' 切成单词 'unitcost',短语匹配静默失效)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _contract_mapping(**aliases: str) -> dict[str, str]:
|
||||
"""按 compile_table_header_contract 真实链路构造别名键(normalize_table_header)。"""
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
normalize_table_header,
|
||||
)
|
||||
return {normalize_table_header(alias): code for alias, code in aliases.items()}
|
||||
|
||||
|
||||
def test_camelcase_token_hits_camelcase_alias():
|
||||
"""无分隔符驼峰 token 必须命中经 normalize_table_header 拆键的驼峰别名。"""
|
||||
mapping = _contract_mapping(UnitCost='unit_price')
|
||||
# 关键断言:契约键为 'Unit Cost'(拆驼峰),token 'UnitCost' 走同一拆分后命中
|
||||
assert 'Unit Cost' in mapping
|
||||
assert schema_canonical_header_atoms(['UnitCost'], mapping) == frozenset(
|
||||
{'field::unit_price'},
|
||||
)
|
||||
|
||||
|
||||
def test_word_atom_pipeline_stays_case_unsplit():
|
||||
"""词级原子管线有意不拆驼峰(真实表头大小写不可靠);camel 对齐由连写短语键承担。"""
|
||||
# 关键断言:无别名契约时 'UnitCost' 与 'Unit Cost' 词级原子不同(零行为变化契约);
|
||||
# 两者身份对齐只能在别名契约下经由连写短语键达成
|
||||
assert _header_token_atoms(['UnitCost']) == frozenset({'unitcost'})
|
||||
assert _header_token_atoms(['Unit Cost']) == frozenset({'unit', 'cost'})
|
||||
|
||||
|
||||
def test_camelcase_wording_difference_not_identity_conflict():
|
||||
"""模板侧连写、观测侧空格(或反向)在别名契约下不得判原子互斥冲突。"""
|
||||
mapping = _contract_mapping(UnitCost='unit_price')
|
||||
signature_tokens = ['Itm', 'UnitCost', 'Extended Cost']
|
||||
observed_tokens = ['itm', 'Unit Cost', 'extended cost']
|
||||
# 关键断言:唯一措辞差异是驼峰连写 vs 空格,且该列有别名覆盖 → 非身份冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature={'table_patterns': [{'header_tokens': signature_tokens}]},
|
||||
observed={'header_tokens': observed_tokens},
|
||||
header_to_field=mapping,
|
||||
) is False
|
||||
|
||||
|
||||
def test_camelcase_tokens_canonical_keeps_order_and_marker():
|
||||
"""canonical 序列版对驼峰 token 产出单个标记项且保持词序(与 atoms 同源)。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['VendorPartNumber', 'UnitCost'],
|
||||
_contract_mapping(VendorPartNumber='part_number', UnitCost='unit_price'),
|
||||
)
|
||||
# 关键断言:每个驼峰 token 各消费为单个 field 标记项,顺序保留、无单词残留
|
||||
assert canonical == ['field::part_number', 'field::unit_price']
|
||||
@@ -0,0 +1,406 @@
|
||||
"""
|
||||
tests/test_order_profile_ocr_rescue.py
|
||||
|
||||
用途:锁定表头带证据补洞(order_profile_ocr_rescue)的门禁契约。
|
||||
依赖:order_profile_ocr_rescue.rescue_match_with_header_ocr / _eligible_rescue_candidates /
|
||||
_glyphs_in_header_band、ProfileMatchResult/Candidate。
|
||||
逻辑:pure_unit;仅「候选集合 = 冲突仅表头判别 + 观测原子纯缺失」可补救;重跑匹配器
|
||||
必须恰好唯一命中集合内候选才采纳并打 identity_rescue_source 标记;改变竞争格局 /
|
||||
仍失败 / 无补洞字形 / 带外字形一律原样返回原判;原 layout 禁止突变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
|
||||
OCR_RESCUE_CONFIDENCE_FLOOR,
|
||||
_eligible_rescue_candidates,
|
||||
_glyphs_in_header_band,
|
||||
rescue_match_with_header_ocr,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchCandidate,
|
||||
ProfileMatchResult,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
V2_CODE = 'ODP-TEST-V2'
|
||||
OTHER_CODE = 'ODP-TEST-OTHER'
|
||||
|
||||
|
||||
def _candidate(code: str, reasons: list[str]) -> ProfileMatchCandidate:
|
||||
return ProfileMatchCandidate(
|
||||
profile_code=code, version=1, score=0.0, hard_match=False,
|
||||
reason_codes=reasons,
|
||||
)
|
||||
|
||||
|
||||
def _drift_match(candidates: list[ProfileMatchCandidate]) -> ProfileMatchResult:
|
||||
return ProfileMatchResult(status='layout_drift', candidates=candidates)
|
||||
|
||||
|
||||
def _layout() -> dict:
|
||||
return {
|
||||
'tables': [{'table_id': 't1', 'page_no': 1, 'bbox': [16, 185, 590, 266]}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 595.0, 'height': 842.0}},
|
||||
'page_glyphs': {'1': [{'text': 'I', 'bbox': {'x0': 23, 'y0': 190, 'x1': 26, 'y1': 202}}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _profiles() -> list[dict]:
|
||||
return [
|
||||
{'profile_code': V2_CODE, 'version': 1, 'definition': {}},
|
||||
{'profile_code': OTHER_CODE, 'version': 1, 'definition': {}},
|
||||
]
|
||||
|
||||
|
||||
def _patch_atoms(monkeypatch, per_code: dict[str, tuple[frozenset, frozenset]]) -> None:
|
||||
"""按 profile_code 固定期望/观测原子,隔离匹配器观测管线。"""
|
||||
def fake(*, raw_profile, layout, header_to_field):
|
||||
expected, observed = per_code[str(raw_profile['profile_code'])]
|
||||
return frozenset(expected), frozenset(observed), {'primary_table_bbox': [0.027, 0.22, 0.99, 0.32]}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.order_profile_ocr_rescue._candidate_header_atoms',
|
||||
fake,
|
||||
)
|
||||
|
||||
|
||||
def _ocr_line(text: str, x0: float, y0: float, x1: float, y1: float, confidence: float = 0.95):
|
||||
return SimpleNamespace(
|
||||
text=text, confidence=confidence,
|
||||
bbox=SimpleNamespace(x0=x0, y0=y0, x1=x1, y1=y1),
|
||||
)
|
||||
|
||||
|
||||
def _fake_page() -> SimpleNamespace:
|
||||
return SimpleNamespace(page_no=1, width=595.0, height=842.0, image=object())
|
||||
|
||||
|
||||
def test_eligibility_collects_all_subset_candidates(monkeypatch):
|
||||
"""近亲模板各自缺不同尾部列时可同时可补救;竞争由补洞后的重跑裁决。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd', 'eta'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'itm', 'qty', 'del'}, {'itm', 'qty'}),
|
||||
})
|
||||
eligible = _eligible_rescue_candidates(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
)
|
||||
# 关键断言:两个纯缺失候选都进入可补救集合,由重跑匹配器唯一性仲裁
|
||||
assert {(code, version) for (code, version) in eligible} == {(V2_CODE, 1), (OTHER_CODE, 1)}
|
||||
|
||||
|
||||
def test_eligibility_rejects_foreign_atoms(monkeypatch):
|
||||
"""观测侧存在期望之外的外来原子 → 不是单纯缺字,不可补救。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty', 'date'}),
|
||||
OTHER_CODE: ({'x', 'y', 'z'}, {'x'}),
|
||||
})
|
||||
# 关键断言:差集必须「纯缺失」(observed ⊂ expected),有外来词的候选被排除;
|
||||
# OTHER(含拓扑冲突非纯判别)同样不进集合 → 集合为空
|
||||
assert _eligible_rescue_candidates(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
) == {}
|
||||
|
||||
|
||||
def test_rescue_success_marks_unique_same_candidate(monkeypatch):
|
||||
"""补洞后重跑匹配器须恰好唯一命中集合内候选,成功时打 identity_rescue_source 标记。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
captured = {}
|
||||
|
||||
def fake_match_fn(*, profiles, layout, header_to_field):
|
||||
captured['layout'] = layout
|
||||
winner = ProfileMatchCandidate(
|
||||
profile_code=V2_CODE, version=1, score=0.99, hard_match=True, reason_codes=[],
|
||||
)
|
||||
loser = ProfileMatchCandidate(
|
||||
profile_code=OTHER_CODE, version=1, score=0.0, hard_match=False,
|
||||
reason_codes=['profile_column_topology_conflict'],
|
||||
)
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=V2_CODE, version=1,
|
||||
candidates=[winner, loser],
|
||||
)
|
||||
|
||||
layout = _layout()
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=layout, header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=fake_match_fn,
|
||||
page_images_fn=lambda content: [_fake_page()],
|
||||
ocr_lines_fn=lambda *a, **k: [
|
||||
_ocr_line('ETD', 460, 190, 480, 202),
|
||||
_ocr_line('ETA Komarom', 500, 190, 560, 202),
|
||||
],
|
||||
read_asset_fn=lambda asset_id: b'%PDF-fake',
|
||||
)
|
||||
# 关键断言:结果翻转为唯一命中且带补洞来源标记,仅命中候选被打标
|
||||
assert result.status == 'unique_match'
|
||||
assert result.identity_rescue_source == 'ocr_coordinate'
|
||||
marked = {c.profile_code: c.identity_rescue_assisted for c in result.candidates}
|
||||
assert marked == {V2_CODE: True, OTHER_CODE: False}
|
||||
# 关键断言:补洞字形只并入增强副本的页 1 表头带,且带来源标记
|
||||
original_glyphs = _layout()['coordinate_evidence']['page_glyphs']['1']
|
||||
augmented_glyphs = captured['layout']['coordinate_evidence']['page_glyphs']['1']
|
||||
assert len(augmented_glyphs) > len(original_glyphs)
|
||||
assert all(g.get('source') == 'ocr_coordinate' for g in augmented_glyphs[len(original_glyphs):])
|
||||
assert captured['layout']['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate+ocr_coordinate'
|
||||
# 关键断言:原 layout 不得被突变
|
||||
assert layout['coordinate_evidence']['page_glyphs']['1'] == original_glyphs
|
||||
assert layout['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_rescue_aborts_when_rematch_changes_winner(monkeypatch):
|
||||
"""补洞唤醒集合外候选(改变竞争格局)→ 维持原判。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
|
||||
def fake_match_fn(*, profiles, layout, header_to_field):
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=OTHER_CODE, version=1,
|
||||
candidates=[_candidate(OTHER_CODE, [])],
|
||||
)
|
||||
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=fake_match_fn,
|
||||
page_images_fn=lambda content: [_fake_page()],
|
||||
ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)],
|
||||
read_asset_fn=lambda asset_id: b'%PDF-fake',
|
||||
)
|
||||
# 关键断言:命中者不在可补救集合内 → 原样返回原 layout_drift 判定
|
||||
assert result is match
|
||||
|
||||
|
||||
def test_rescue_aborts_when_rematch_still_drift(monkeypatch):
|
||||
"""补洞词未能补齐原子(仍 layout_drift)→ 维持原判。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
|
||||
def fake_match_fn(*, profiles, layout, header_to_field):
|
||||
return _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=fake_match_fn,
|
||||
page_images_fn=lambda content: [_fake_page()],
|
||||
ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)],
|
||||
read_asset_fn=lambda asset_id: b'%PDF-fake',
|
||||
)
|
||||
assert result is match
|
||||
|
||||
|
||||
def test_rescue_aborts_without_ocr_lines(monkeypatch):
|
||||
"""OCR 无返回(引擎失败或全部低于置信度)→ 维持原判。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
seen = {}
|
||||
|
||||
def fake_ocr(*args, **kwargs):
|
||||
seen['minimum_confidence'] = kwargs.get('minimum_confidence')
|
||||
return []
|
||||
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
|
||||
page_images_fn=lambda content: [_fake_page()],
|
||||
ocr_lines_fn=fake_ocr,
|
||||
read_asset_fn=lambda asset_id: b'%PDF-fake',
|
||||
)
|
||||
assert result is match
|
||||
# 关键断言:OCR 置信度门禁与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐
|
||||
assert seen['minimum_confidence'] == OCR_RESCUE_CONFIDENCE_FLOOR
|
||||
|
||||
|
||||
def test_header_band_filter_drops_out_of_band_glyphs():
|
||||
"""带外补洞字形必须被过滤,只保留主表表头带内的字形并打来源标记。"""
|
||||
page_width, page_height = 595.0, 842.0
|
||||
glyphs = [
|
||||
{'text': 'E', 'bbox': {'x0': 460, 'y0': 190, 'x1': 466, 'y1': 202}},
|
||||
{'text': 'X', 'bbox': {'x0': 460, 'y0': 400, 'x1': 466, 'y1': 412}},
|
||||
{'text': 'Y', 'bbox': {'x0': 2, 'y0': 190, 'x1': 8, 'y1': 202}},
|
||||
]
|
||||
kept = _glyphs_in_header_band(
|
||||
glyphs=glyphs, page_width=page_width, page_height=page_height,
|
||||
primary_table_bbox=[0.027, 0.22, 0.99, 0.32], source='ocr_coordinate',
|
||||
)
|
||||
# 关键断言:仅带内字形保留(y≈0.23 ∈ [0.22, 0.22+0.3*0.1];x=0.008 < 0.022 带外),
|
||||
# 且带 source 标记
|
||||
assert [g['text'] for g in kept] == ['E']
|
||||
assert kept[0]['source'] == 'ocr_coordinate'
|
||||
|
||||
|
||||
def test_rescue_prefers_acroform_widgets_over_ocr(monkeypatch):
|
||||
"""AcroForm 控件文本是首选补洞来源(确定性);命中时不得触发渲染和 OCR。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
|
||||
def fake_widget(code: str, value: str):
|
||||
return SimpleNamespace(
|
||||
page_no=1, value=value,
|
||||
normalized_bbox={'x0': 0.77, 'y0': 0.235, 'x1': 0.85, 'y1': 0.25},
|
||||
qualified_name=code, short_name=code, widget_id=code,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets',
|
||||
lambda content: [
|
||||
fake_widget('C_ETD', 'ETD'),
|
||||
fake_widget('C_ETA', 'ETA Komarom'),
|
||||
],
|
||||
)
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=lambda **k: ProfileMatchResult(
|
||||
status='unique_match', profile_code=V2_CODE, version=1,
|
||||
candidates=[_candidate(V2_CODE, [])],
|
||||
),
|
||||
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
|
||||
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
|
||||
read_asset_fn=lambda asset_id: b'%PDF-fake',
|
||||
)
|
||||
# 关键断言:AcroForm 来源直接命中,OCR/渲染路径完全未被触达
|
||||
assert result.identity_rescue_source == 'acroform_widget'
|
||||
assert result.status == 'unique_match'
|
||||
|
||||
|
||||
def test_rescue_never_leaks_asset_read_errors(monkeypatch):
|
||||
"""资产读取抛 AttributeError(test 环境真实故障:int 传入 read_asset_bytes 访问
|
||||
.deleted_at)必须被收口为维持原判,不得炸穿抽取 Unit。"""
|
||||
match = _drift_match([
|
||||
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
|
||||
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
|
||||
])
|
||||
_patch_atoms(monkeypatch, {
|
||||
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
|
||||
OTHER_CODE: ({'a', 'b'}, {'a'}),
|
||||
})
|
||||
|
||||
def broken_read_asset(asset_id):
|
||||
raise AttributeError("'int' object has no attribute 'deleted_at'")
|
||||
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
|
||||
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
|
||||
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
|
||||
read_asset_fn=broken_read_asset,
|
||||
)
|
||||
# 关键断言:补洞证据读取的任意异常都收口为原判返回
|
||||
assert result is match
|
||||
|
||||
|
||||
def test_rescue_skipped_for_non_failed_status():
|
||||
"""常规匹配已成功(如 unique_match)时绝不触发证据补洞。"""
|
||||
match = ProfileMatchResult(
|
||||
status='unique_match', profile_code=V2_CODE, version=1,
|
||||
candidates=[_candidate(V2_CODE, [])],
|
||||
)
|
||||
result = rescue_match_with_header_ocr(
|
||||
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
|
||||
document=SimpleNamespace(asset_id=7),
|
||||
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
|
||||
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
|
||||
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
|
||||
read_asset_fn=lambda asset_id: (_ for _ in ()).throw(AssertionError('asset must not run')),
|
||||
)
|
||||
assert result is match
|
||||
|
||||
|
||||
def test_default_read_asset_loads_orm_before_read_asset_bytes(monkeypatch):
|
||||
"""默认资产读取必须先加载 FileAsset ORM 再交给 read_asset_bytes。
|
||||
|
||||
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——默认接线曾把
|
||||
document.asset_id(int)直接传给 read_asset_bytes,第一行访问
|
||||
``asset.deleted_at`` 即抛 AttributeError,炸穿补救层令整个抽取 Unit
|
||||
技术失败。本测试锁定默认接线契约:read_asset_bytes 只接收 ORM 对象。
|
||||
"""
|
||||
from types import SimpleNamespace as NS
|
||||
|
||||
import app.extensions as extensions
|
||||
import app.services.file_assets.service as asset_service
|
||||
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
|
||||
_default_read_asset_bytes,
|
||||
)
|
||||
|
||||
received_objects: list[object] = []
|
||||
|
||||
def fake_read_asset_bytes(asset):
|
||||
received_objects.append(asset)
|
||||
return b'%PDF-default-wired'
|
||||
|
||||
fake_asset = NS(id=7, deleted_at=None)
|
||||
|
||||
class FakeSession:
|
||||
def get(self, model, asset_id):
|
||||
assert model is not int and asset_id == 7
|
||||
return fake_asset
|
||||
|
||||
monkeypatch.setattr(asset_service, 'read_asset_bytes', fake_read_asset_bytes)
|
||||
monkeypatch.setattr(extensions, 'db', NS(session=FakeSession()))
|
||||
|
||||
# 关键断言 1:默认接线按 id 取 ORM,read_asset_bytes 收到对象而非 int。
|
||||
assert _default_read_asset_bytes(7) == b'%PDF-default-wired'
|
||||
assert received_objects == [fake_asset]
|
||||
|
||||
# 关键断言 2:资产不存在时抛 LookupError(可被补救层收口为原判)。
|
||||
class MissingSession:
|
||||
def get(self, model, asset_id):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(extensions, 'db', NS(session=MissingSession()))
|
||||
with pytest.raises(LookupError):
|
||||
_default_read_asset_bytes(404)
|
||||
@@ -14,7 +14,10 @@ from app.models import (
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
evaluate_inventory_source_rules,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
@@ -212,3 +215,111 @@ def test_five_digit_reservation_rule_can_route_to_crane(app):
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('CRANE',)
|
||||
|
||||
|
||||
# ---------- 库存源线索直连(引擎内建,优先于全部规则层) ----------
|
||||
|
||||
def _hint_sources(monkeypatch, codes):
|
||||
"""隔离线索解析的启用源清单(引擎自 list_database_inventory_sources 读取)。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_routing_engine.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': code} for code in codes],
|
||||
)
|
||||
|
||||
|
||||
def _set_snapshot_line_hint(task, hint: str) -> None:
|
||||
"""在冻结快照行的强类型线索列写入线索值(模拟订单明细「库存源线索」)。"""
|
||||
snapshot_line = ShippingOrderSnapshotLine.query.filter_by(
|
||||
snapshot_id=task.order_snapshot_id, position=0,
|
||||
).one()
|
||||
snapshot_line.inventory_source_hint = hint
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_hint_direct_connect_suffix_wins_over_reservation_fallback(app, monkeypatch):
|
||||
"""[断言] 核心需求:线索非空且可唯一后缀解析时直接 resolved,预约单号兜底规则不得参与。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_AWSCV'])
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
_set_snapshot_line_hint(task, 'BYAWSPRD01')
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',)
|
||||
assert result.evidence.get('reason') == 'inventory_source_hint'
|
||||
assert result.matched_rule_ids == ()
|
||||
|
||||
|
||||
def test_hint_direct_connect_exact_code_match(app, monkeypatch):
|
||||
"""[断言] 线索即完整源编码时精确命中。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSCV', 'DSV360_AWSDU'])
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
_set_snapshot_line_hint(task, 'DSV360_AWSCV')
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DSV360_AWSCV',)
|
||||
|
||||
|
||||
def test_hint_unresolvable_falls_back_to_reservation_rule(app, monkeypatch):
|
||||
"""[断言] fail-open:线索无命中(拼错/停用)时落回规则层,预约兜底照常,不阻断流程。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
_set_snapshot_line_hint(task, 'NOPE_WAREHOUSE')
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'ambiguous'
|
||||
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
|
||||
|
||||
|
||||
def test_hint_ambiguous_suffix_falls_back_to_rules(app, monkeypatch):
|
||||
"""[断言] 后缀撞多个启用源(多命中)时不采用线索,落回规则层裁决。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_CRANE_BYAWSPRD01'])
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
_set_snapshot_line_hint(task, 'BYAWSPRD01')
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DBS_DUB',)
|
||||
|
||||
|
||||
def test_hint_direct_connect_ignored_for_task_scope(app, monkeypatch):
|
||||
"""[断言] 线索是行级信号:任务级评估(line=None)维持原行为。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
|
||||
fields = _published_line_fields()
|
||||
task, _line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
_set_snapshot_line_hint(task, 'BYAWSPRD01')
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=None)
|
||||
assert result.status == 'unresolved'
|
||||
|
||||
|
||||
def test_draft_entry_hint_direct_connect_and_fallback(app, monkeypatch):
|
||||
"""[断言] Draft 入口:线索命中直接 resolved(无规则也生效);未传线索时维持 unresolved。"""
|
||||
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
|
||||
result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values={}, line_field_values={}, scope='line',
|
||||
line_source_hint='BYAWSPRD01',
|
||||
)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',)
|
||||
assert result.evidence.get('reason') == 'inventory_source_hint'
|
||||
fallback = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values={}, line_field_values={}, scope='line',
|
||||
)
|
||||
assert fallback.status == 'unresolved'
|
||||
@@ -31,6 +31,12 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact(Excel 源锁定判断,查库)依赖;
|
||||
# 纯单测无 Flask/DB,打桩为「Excel 已生成」使刷新块短路,保持本用例聚焦行级收窄断言。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_export_archive.py
|
||||
|
||||
用途:shipping_notice 批量导出归档(build_export_archive)下载授权单测。
|
||||
依赖:pytest、ShippingNotice、export_archive.build_export_archive。
|
||||
逻辑:批量选择与单票导出消费同一谓词口径(创建者或管理员);无 Artifact 时
|
||||
保留 manifest missing 语义,并按票携带 business_no 供端点写访问审计。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ShippingNotice
|
||||
|
||||
|
||||
def test_build_export_archive_selects_by_creator_or_admin(app):
|
||||
"""批量归档与单票下载同一谓词:陌生用户整体拒绝,创建者/管理员放行。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-ARC-OWNED", business_no="QMN-ARC-1", user_id=7, source_type="manual",
|
||||
)
|
||||
db.session.add(owned)
|
||||
db.session.commit()
|
||||
|
||||
# 非创建者普通用户:任一越权即整体拒绝(防部分成功)。
|
||||
with pytest.raises(NotFoundError):
|
||||
build_export_archive(user_id=8, business_nos=["QMN-ARC-1"])
|
||||
|
||||
# 创建者放行;无 Artifact 时保留 missing_artifact 语义并携带 business_no。
|
||||
_stream, _name, manifest = build_export_archive(user_id=7, business_nos=["QMN-ARC-1"])
|
||||
assert manifest["entries"][0]["status"] == "missing_artifact"
|
||||
assert manifest["entries"][0]["business_no"] == "QMN-ARC-1"
|
||||
|
||||
# 管理员可下载=可见:他人正式 Notice 放行(端点按票补访问审计)。
|
||||
_stream, _name, admin_manifest = build_export_archive(
|
||||
user_id=8, business_nos=["QMN-ARC-1"], is_admin=True,
|
||||
)
|
||||
assert admin_manifest["entries"][0]["task_no"] == "SN-ARC-OWNED"
|
||||
@@ -1697,3 +1697,70 @@ def test_merge_chat_log_payload_requires_exact_turn_ownership(app):
|
||||
'existing_key': 'kept',
|
||||
'shipping_order_extraction_state': {'status': 'completed'},
|
||||
}
|
||||
|
||||
|
||||
def test_persist_close_out_marks_failed_units_failed_not_completed(app):
|
||||
"""Unit 全失败的空结果收口必须写 failed,禁止把附件误标为识别完成。
|
||||
|
||||
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——persist 在 orders=[]
|
||||
时按「零 pending」把附件 order_extraction_status 写成 completed;随后的
|
||||
Run 失败收口因「已是 completed 终态」跳过回填,批次进度中心据此把整批
|
||||
误报为已完成/通知完成。
|
||||
"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, _runtime_context = _seed_extraction_input()
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
|
||||
run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-FAILED-UNITS-CLOSE-OUT',
|
||||
user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema.id),
|
||||
input_snapshot_hash='failed-units-close-out-snapshot',
|
||||
input_snapshot_json={},
|
||||
idempotency_key='failed-units-close-out-run',
|
||||
status='processing',
|
||||
)
|
||||
plan = ShippingOrderProcessingPlan(
|
||||
run=run,
|
||||
plan_version='test.v1',
|
||||
input_snapshot_hash=run.input_snapshot_hash,
|
||||
unit_count=1,
|
||||
)
|
||||
unit = ShippingOrderProcessingUnit(
|
||||
plan=plan,
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document.id),
|
||||
position=0,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
|
||||
error_message="'int' object has no attribute 'deleted_at'",
|
||||
)
|
||||
db.session.add_all([run, plan, unit])
|
||||
db.session.commit()
|
||||
|
||||
persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=[intake],
|
||||
documents=[document],
|
||||
current_snapshot='failed-units-close-out-snapshot',
|
||||
request_id='SNER-FAILED-UNITS-CLOSE-OUT',
|
||||
orders=[],
|
||||
run_id=int(run.id),
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='deterministic_order_parser',
|
||||
auto_create_enabled=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(document)
|
||||
db.session.refresh(intake)
|
||||
# 关键断言 1:Unit 失败且零候选裁决 → 文档必须落 failed 并携带 Unit 错误码。
|
||||
assert document.order_extraction_status == 'failed'
|
||||
assert document.order_extraction_error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
|
||||
# 关键断言 2:全部附件失败 → Intake 同步 failed;consumed 保留(孤儿重解析依赖)。
|
||||
assert intake.order_extraction_status == 'failed'
|
||||
assert intake.parse_status == 'consumed'
|
||||
@@ -321,6 +321,28 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
|
||||
|
||||
|
||||
def test_can_download_task_export_creator_or_admin(app):
|
||||
"""导出统一谓词:创建者/管理员可下载;非创建者普通用户与无主单一律拒绝。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import can_download_task_export
|
||||
|
||||
owned = ShippingNotice(task_no="SN-DL-OWNED", business_no="QMN-DL-1", user_id=7, source_type="manual")
|
||||
orphan = ShippingNotice(task_no="SN-DL-ORPHAN", business_no="QMN-DL-2", user_id=None, source_type="manual")
|
||||
db.session.add_all([owned, orphan])
|
||||
db.session.commit()
|
||||
|
||||
# 创建者可下载;同票对非创建者普通用户拒绝。
|
||||
assert can_download_task_export(owned, user_id=7) is True
|
||||
assert can_download_task_export(owned, user_id=8) is False
|
||||
# 管理员可下载=可见:他人票与无主票均放行(下载留痕审计兜底)。
|
||||
assert can_download_task_export(owned, user_id=8, is_admin=True) is True
|
||||
assert can_download_task_export(orphan, user_id=7) is False
|
||||
assert can_download_task_export(orphan, user_id=7, is_admin=True) is True
|
||||
# 缺实体一律拒绝。
|
||||
assert can_download_task_export(None, user_id=7, is_admin=True) is False
|
||||
|
||||
|
||||
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -465,6 +465,39 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
|
||||
assert "download_excel" in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_gates_download_by_viewer(app, monkeypatch) -> None:
|
||||
"""下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-VIEWER-EXPORT",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||||
)
|
||||
|
||||
def button_ids(state):
|
||||
return [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
|
||||
# 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7))
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True))
|
||||
# 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。
|
||||
assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8))
|
||||
# viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task))
|
||||
|
||||
|
||||
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
|
||||
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
|
||||
with app.app_context():
|
||||
@@ -891,6 +924,31 @@ def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_read
|
||||
assert preparation["has_match_result"] is False
|
||||
|
||||
|
||||
def test_preparation_lines_carry_part_available_qty(app) -> None:
|
||||
"""prep 行必须下发料号兜底总量,供前端新增「可用数量」列。"""
|
||||
with app.app_context():
|
||||
task, line = _frozen_task_with_line(
|
||||
task_no="OT-UI-PART-AVAILABLE",
|
||||
reservation_id="RSV-PART-AVAIL",
|
||||
part_number="PN-PART-AVAIL",
|
||||
qty="8",
|
||||
)
|
||||
# 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result="matched", inventory_status="ready", required_qty="8",
|
||||
available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9",
|
||||
reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL",
|
||||
inventory_source_code="DBS_DUB", is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
state = build_task_ui_state(task, include_stage_context=True)
|
||||
prep_line = state["stage_context"]["preparation"]["lines"][0]
|
||||
# 断言意图:ui_state 单源直透投影值,前端不做二次推导;不下发任何派生布尔标志。
|
||||
assert prep_line["part_available_qty"] == "9"
|
||||
|
||||
|
||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
|
||||
@@ -459,6 +459,56 @@ def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_ex
|
||||
assert gate_execution.status == 'blocked'
|
||||
|
||||
|
||||
def test_refresh_pointers_bumps_task_progress_version_without_notice(gate_execution):
|
||||
"""无 Notice 绑定时 Gate 指针事实变化必须递增 OT progress_version。
|
||||
|
||||
复现:通知准备/库存匹配阶段 Notice 尚未生成,历史实现只回填 stage、不推进版本;
|
||||
统一投影 progress_version 冻结导致工作台 [REFRESH_ON_CHANGE] 永不重拉任务详情,
|
||||
RPA 重取成功后行级可用数量/缺口停留在旧快照(界面显示「库存文件未准备」)。
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
|
||||
version_before = int(task.progress_version or 1)
|
||||
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
|
||||
if gate.gate_code in {
|
||||
'document_materialization', 'layout_parsing', 'document_profile_routing',
|
||||
'order_field_extraction', 'field_completeness', 'reservation_validation',
|
||||
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
|
||||
'task_creation', 'order_freeze_readiness', 'inventory_source_routing',
|
||||
'inventory_preparation', 'inventory_field_mapping', 'inventory_matching',
|
||||
}:
|
||||
gate.status = 'passed'
|
||||
gate.passed_at = now
|
||||
elif gate.gate_code == 'inventory_sufficiency':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_shortage_review_required'
|
||||
gate.next_action_code = 'open_shortage_review'
|
||||
elif gate.gate_code == 'excel_readiness':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'excel_not_ready'
|
||||
# 其余保持 pending
|
||||
db.session.flush()
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
# 关键断言:缺口落定属于真实事实变化,无 Notice 也必须经中央写入口推进版本。
|
||||
assert gate_execution.current_gate_code == 'inventory_sufficiency'
|
||||
assert gate_execution.status == 'blocked'
|
||||
assert int(task.progress_version or 1) == version_before + 1
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
# 关键断言:事实未变的重复刷新不得递增版本,避免轮询期被放大成详情刷新风暴。
|
||||
assert int(task.progress_version or 1) == version_before + 1
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1651,6 +1651,12 @@ def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖;
|
||||
# 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -519,6 +519,29 @@ def test_waiting_human_without_reconcile_action_has_no_false_primary_action():
|
||||
assert payload['primary_action'] is None
|
||||
|
||||
|
||||
def test_in_flight_gate_projects_running_not_waiting_human():
|
||||
"""RPA 在途(Gate waiting_external)必须投影 running,不得误报待人工。
|
||||
|
||||
Notice 生成前 OT.status 停留在建单前的 waiting_review;若在途期被投影成
|
||||
waiting_human,前端会把任务当终态停止投影轮询,RPA 回调完成将永远无法被
|
||||
感知(库存匹配表格冻结在「库存文件未准备」)。与门禁契约
|
||||
GATE_STATUS_TO_USER_STATUS['waiting_external']=='running' 对齐。
|
||||
"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'waiting_review',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'waiting_external',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
# 关键断言:Gate 在途 = 系统处理中;待人工只属于 blocked_manual 等人工阻断。
|
||||
assert payload['user_status'] == 'running'
|
||||
|
||||
|
||||
def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
||||
"""事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。"""
|
||||
payload = apply_user_projection_fields({
|
||||
|
||||
@@ -1504,15 +1504,20 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
|
||||
|
||||
|
||||
def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None:
|
||||
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。"""
|
||||
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。
|
||||
|
||||
回归语义(SNER-20261014-8EBAB7A1):无 OT 的文档级 completed 只是抽取收口,
|
||||
摘要不再译成业务已完成;混合场景改用 failed + processing 两类真实用户分组。
|
||||
"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, intake, completed_document = _seed_run_input(
|
||||
user, _agent, session, intake, failed_document = _seed_run_input(
|
||||
suffix='SUMMARY-MIXED-EML-LEAF-STATUS',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
completed_document.order_extraction_status = 'completed'
|
||||
failed_document.order_extraction_status = 'failed'
|
||||
failed_document.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
|
||||
processing_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
@@ -1531,17 +1536,17 @@ def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> Non
|
||||
conversation_id=session.session_id,
|
||||
)['conversation_processing']
|
||||
|
||||
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。
|
||||
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在失败容器。
|
||||
failed_rows = projection['status_groups']['failed']
|
||||
processing_rows = projection['status_groups']['processing']
|
||||
completed_rows = projection['status_groups']['completed']
|
||||
assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [
|
||||
processing_document.id,
|
||||
]
|
||||
assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [
|
||||
completed_document.id,
|
||||
assert [child['source_summary']['document_id'] for child in failed_rows[0]['aggregate_children']] == [
|
||||
failed_document.id,
|
||||
]
|
||||
assert projection['summary']['processing_files'] == 1
|
||||
assert projection['summary']['completed_files'] == 1
|
||||
assert projection['summary']['failed_files'] == 1
|
||||
assert projection['summary']['total_files'] == 2
|
||||
|
||||
|
||||
@@ -3423,3 +3428,58 @@ def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized
|
||||
assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf'
|
||||
# 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。
|
||||
assert _batch_file_counts(merged)['total_files'] == 1
|
||||
|
||||
|
||||
def test_summary_failed_run_does_not_project_document_completed_as_upload_complete(app) -> None:
|
||||
"""Run 失败时文档级 completed(抽取收口语义)不得译成业务终态「通知完成」。
|
||||
|
||||
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——9 个 Unit 全部
|
||||
ORDER_EXTRACTION_UNIT_FAILED,persist 收口零 pending 仍把附件写成
|
||||
order_extraction_status='completed';首屏摘要 _status() 据此映射
|
||||
('completed','completed'),批次进度中心误报 9/9 已完成 + 通知完成。
|
||||
"""
|
||||
with app.app_context():
|
||||
from datetime import datetime
|
||||
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-CLOSEOUT-NOT-COMPLETE',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
|
||||
run.status = 'failed'
|
||||
run.phase = 'failed'
|
||||
run.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
|
||||
# 脏数据形态:persist 收口已把文档/Intake 写成 completed(抽取收口 ≠ 业务完成)。
|
||||
document.order_extraction_status = 'completed'
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = datetime.utcnow()
|
||||
intake.order_extraction_status = 'completed'
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
projection = payload['conversation_processing']
|
||||
leaf = next(
|
||||
child
|
||||
for rows in projection['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
# 关键断言 1:无 OT/Notice 的文件不可能投影为「通知完成」。
|
||||
assert leaf['ui_state']['lifecycle_stage'] != 'upload_complete'
|
||||
# 关键断言 2:失败文件不得计入批次已完成统计。
|
||||
assert projection['summary']['completed'] == 0
|
||||
# 关键断言 3:与全量视图同判词 —— 失败停接收解析,主动作是重解析。
|
||||
assert leaf['user_group'] == 'failed'
|
||||
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'reparse'
|
||||
@@ -0,0 +1,504 @@
|
||||
"""
|
||||
tests/test_shipping_refresh_inventory_candidates.py
|
||||
|
||||
用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评,
|
||||
未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。
|
||||
依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与
|
||||
inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、
|
||||
process_gate_executor(Task 2 的挂载点集成测试)。
|
||||
逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫
|
||||
(目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在
|
||||
人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _task(set_id=10):
|
||||
"""构造最小 OT 形状:仅 helper/执行器读取的字段。"""
|
||||
return SimpleNamespace(
|
||||
id=19, task_no='SN-REFRESH',
|
||||
order_snapshot_id=3,
|
||||
active_inventory_candidate_set_id=set_id,
|
||||
step_payload_json={},
|
||||
)
|
||||
|
||||
|
||||
def _active_set(line_defs):
|
||||
"""构造最小活动候选集:lines 为 (line_no, codes) 列表。"""
|
||||
return SimpleNamespace(
|
||||
id=10, frozen_by_id=None, sources=[],
|
||||
lines=[
|
||||
SimpleNamespace(
|
||||
line_no=line_no, source_codes_json=list(codes),
|
||||
source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}',
|
||||
)
|
||||
for line_no, codes in line_defs
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'):
|
||||
"""隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.extract_routing_context',
|
||||
lambda _task: {'customer': 'X'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint',
|
||||
lambda _ctx: fingerprint,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version',
|
||||
lambda: config_version,
|
||||
)
|
||||
|
||||
|
||||
# ---------- 任务级刷新 ----------
|
||||
|
||||
def test_refresh_skips_when_single_source_resolved(app, monkeypatch):
|
||||
"""[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch):
|
||||
"""[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
|
||||
def _fake_readjudicate(_task, **_k):
|
||||
task.active_inventory_candidate_set_id = 11
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
_fake_readjudicate,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'task'
|
||||
assert events[0][1]['previous_set_id'] == 10
|
||||
assert events[0][1]['new_set_id'] == 11
|
||||
|
||||
|
||||
def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: None,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not events
|
||||
|
||||
|
||||
# ---------- 行级刷新 ----------
|
||||
|
||||
def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch):
|
||||
"""[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSDU'])]),
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch):
|
||||
"""[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='unresolved', source_codes=()),
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch):
|
||||
"""[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: None,
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch):
|
||||
"""[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([
|
||||
(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']),
|
||||
(2, ['DSV360_AWSCV']),
|
||||
]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
freeze_kwargs = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True
|
||||
projections = freeze_kwargs[0]['line_projections']
|
||||
assert projections[0]['line_no'] == 1
|
||||
assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert projections[1]['line_no'] == 2
|
||||
assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV']
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'line'
|
||||
assert events[0][1]['line_no'] == 1
|
||||
assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
|
||||
|
||||
def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not events
|
||||
|
||||
|
||||
def _retry_payload(**overrides):
|
||||
base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _exercise_retry_handler(
|
||||
monkeypatch, task, payload, *,
|
||||
refresh_calls, line_scope=None, excel_artifact=None, ensure_calls=None, line_refresh_result=False,
|
||||
):
|
||||
"""按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。
|
||||
|
||||
refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。
|
||||
line_scope 传 dict 时每次解析都返回它(缺省行为);传 list 时按调用次序逐个弹出
|
||||
(用尽后返回 None),用于断言「刷新产生新集后重解析行作用域」。
|
||||
line_refresh_result 控制行级刷新 helper mock 的返回值(True 表示产生了新候选集)。
|
||||
ensure_calls 顺序捕获 ensure_inventory 收到的 payload(供断言取数范围)。
|
||||
另须打桩 inventory_candidate_projection 三个读取函数:执行器 [STEP 0A] 会真实查库校验
|
||||
活动 CandidateSet,假 Task 不打桩会被提前拦回 inventory_source_routing_required,
|
||||
永远到不了被测的 [STEP 0B] 刷新块(与 test_shipping_line_scoped_inventory_retry 同模式)。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [SimpleNamespace(source_codes_json=['DSV360_AWSDU'])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: [SimpleNamespace(source_code='DSV360_AWSDU')],
|
||||
)
|
||||
if isinstance(line_scope, list):
|
||||
scope_sequence = list(line_scope)
|
||||
monkeypatch.setattr(
|
||||
executor,
|
||||
'_resolve_line_inventory_scope',
|
||||
lambda _task, **_k: scope_sequence.pop(0) if scope_sequence else None,
|
||||
)
|
||||
else:
|
||||
monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope)
|
||||
monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: excel_artifact,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or line_refresh_result,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||||
lambda **_k: {'outcome': 'passed'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_k: None,
|
||||
)
|
||||
if ensure_calls is None:
|
||||
ensure_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: ensure_calls.append(dict(_payload)) or {'status': 'ok', 'data': {}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
return executor._handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate, payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch):
|
||||
"""[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'task'
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch):
|
||||
"""[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch):
|
||||
"""[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。"""
|
||||
refresh_calls = []
|
||||
task = _task()
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls,
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
assert not refresh_calls
|
||||
|
||||
|
||||
def test_retry_line_refresh_requeries_with_new_scope(app, monkeypatch):
|
||||
"""[断言] 行级刷新产生新候选集后须按同参重解析行作用域:同一次点击的失效与 RPA 取数
|
||||
直接使用新冻结码,而非刷新前解析的旧码;重解析为 None 时才保守沿用旧值。"""
|
||||
refresh_calls = []
|
||||
ensure_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope=[
|
||||
{'source_codes': ['DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
{'source_codes': ['DSV360_AWSDU', 'DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
],
|
||||
line_refresh_result=True,
|
||||
ensure_calls=ensure_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert ensure_calls and ensure_calls[-1].get('source_codes') == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_from_preparation_does_not_refresh(app, monkeypatch):
|
||||
"""[断言] retry_inventory_from_preparation 不做候选集刷新前置(仅 retry_inventory_preparation 触发,锁定文档排除项)。"""
|
||||
refresh_calls = []
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(action_code='retry_inventory_from_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
assert not refresh_calls
|
||||
@@ -0,0 +1,322 @@
|
||||
"""验证 EML 无表头正文「裸 5/10 位数字兜底识别预约单号」的扫描、排除与合并裁决。
|
||||
|
||||
依赖:reservation_id 启发式原语与 order_supplement_merge 合并服务。
|
||||
逻辑:无表头数据行解析不出补充行时,正文裸数字候选在合并末段结合
|
||||
已提取字段值/主题标签值/跨单占用裁决——唯一候选低置信度写入,
|
||||
多候选转 supplement_field_conflict 人工裁决,已有值绝不覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
filter_reservation_heuristic_candidates,
|
||||
find_bare_numeric_reservation_candidates,
|
||||
reservation_ids_in_labeled_context,
|
||||
)
|
||||
|
||||
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID'],
|
||||
},
|
||||
]}
|
||||
|
||||
HEADER_RESERVATION_SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'aliases': ['Reservation ID'],
|
||||
},
|
||||
]}
|
||||
|
||||
|
||||
def _order() -> dict:
|
||||
"""构造 PDF 已解析出 PO/料号/数量、但缺预约单号的订单(截图 1 场景)。"""
|
||||
return {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '1000053337'}]}],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-AR1200163A1'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 120}]},
|
||||
]}],
|
||||
'conflicts': [],
|
||||
}
|
||||
|
||||
|
||||
def _supplement(candidates: list[str], **extra) -> dict:
|
||||
"""构造带裸数字候选的正文补充事实(无表头场景 rows 为空)。"""
|
||||
return {
|
||||
'rows': [],
|
||||
'issues': [],
|
||||
'version': 'email-supplement.v1',
|
||||
'document_id': 44,
|
||||
'reservation_candidates': [
|
||||
{'value': value, 'evidence': {
|
||||
'table_index': None, 'row_index': index + 1, 'column_index': None,
|
||||
'cell_id': f'reservation-heuristic:hash:line{index + 1}', 'raw_value': value,
|
||||
}}
|
||||
for index, value in enumerate(candidates)
|
||||
],
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def _reservation_observation(order: dict):
|
||||
"""读取兜底写入的 reservation Observation;未写入返回 None。"""
|
||||
for line in order['lines']:
|
||||
for field in line['fields']:
|
||||
if field['field_id'] == 'reservation':
|
||||
return field['observations'][0]
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 候选扫描
|
||||
|
||||
def test_scan_finds_bare_reservation_in_headerless_table_row():
|
||||
"""截图场景:无表头数据表只识别整格纯数字的 39739;PO 整格入选由合并端排除。"""
|
||||
html = (
|
||||
'<table><tr><td>DBS PHX01</td><td>39739</td><td>6233</td>'
|
||||
'<td>504-006055-001</td><td>D4-A08AR12000002</td><td>WEL</td>'
|
||||
'<td>10/12/2026</td><td>120</td><td>1000053286</td></tr></table>'
|
||||
)
|
||||
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
|
||||
# 断言:仅两个整格纯数字入选——预约号 39739 与 PO 1000053286(10 位同样合规,
|
||||
# 由合并端用已提取 PO 字段值/主题标签排除);仓库/料号/日期/数量格一概不取。
|
||||
assert [item['value'] for item in candidates] == ['39739', '1000053286']
|
||||
evidence = candidates[0]['evidence']
|
||||
# 断言:DOM 级证据齐全,可回溯到具体表格/行/列。
|
||||
assert evidence['table_index'] == 0
|
||||
assert evidence['row_index'] == 0 and evidence['column_index'] == 1
|
||||
assert evidence['cell_id'].startswith('reservation-heuristic:h:0')
|
||||
|
||||
|
||||
def test_scan_ignores_cells_with_any_surrounding_content():
|
||||
"""收紧规则:邮编地址、带字母/备注前后的值一律不取(07094/00410 误报修复)。"""
|
||||
html = (
|
||||
'<table><tr>'
|
||||
'<td>Secaucus, NJ 07094</td>'
|
||||
'<td>T00410</td>'
|
||||
'<td>00410-CN</td>'
|
||||
'<td>39739 (A)</td>'
|
||||
'<td> 39739 </td>'
|
||||
'<td>35354-1</td>'
|
||||
'</tr></table>'
|
||||
)
|
||||
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
|
||||
# 断言:只有去除首尾空白后恰好为纯数字的整格幸存(39739);
|
||||
# 07094 藏在地址文本里、00410 带字母前后、39739 带备注、35354-1 带后缀,全部排除。
|
||||
assert [item['value'] for item in candidates] == ['39739']
|
||||
|
||||
|
||||
def test_scan_returns_nothing_without_html_tables():
|
||||
"""收紧规则:正文无 HTML 表格时不做兜底,纯文本中的数字不再是候选来源。"""
|
||||
assert find_bare_numeric_reservation_candidates(html_tables=[], content_hash='h') == []
|
||||
assert find_bare_numeric_reservation_candidates(html_tables=None, content_hash='h') == []
|
||||
|
||||
|
||||
def test_scan_dedupes_and_caps_candidates():
|
||||
"""同值只留首个证据;候选总数截断到上限,防止大表刷爆快照。"""
|
||||
cells = '<td>4000122230</td><td>4000122230</td>' + ''.join(
|
||||
f'<td>{30000 + index}</td>' for index in range(25)
|
||||
)
|
||||
html = f'<table><tr>{cells}</tr></table>'
|
||||
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
|
||||
values = [item['value'] for item in candidates]
|
||||
# 断言:重复格只保留首个证据;总数截断到 20(1 个 10 位 + 前 19 个 5 位)。
|
||||
assert len(values) == 20
|
||||
assert values[0] == '4000122230'
|
||||
assert values.count('4000122230') == 1
|
||||
|
||||
|
||||
def test_labeled_context_helper_extracts_subject_po():
|
||||
"""主题「RE_ WELLTRUST ACC PO 1000053337」的 PO 号可被标签助手提取。"""
|
||||
assert reservation_ids_in_labeled_context('RE_ WELLTRUST ACC PO 1000053337.eml') == {'1000053337'}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 过滤裁决
|
||||
|
||||
def test_filter_returns_unique_ambiguous_none():
|
||||
"""过滤器三态:唯一→unique 可自动采纳;多个→ambiguous;全排除→none。"""
|
||||
candidates = [{'value': value} for value in ['4000122230', '1000053337']]
|
||||
surviving, status = filter_reservation_heuristic_candidates(
|
||||
candidates, excluded_values={'1000053337'},
|
||||
)
|
||||
assert status == 'unique' and surviving[0]['value'] == '4000122230'
|
||||
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=set())
|
||||
assert status == 'ambiguous' and len(surviving) == 2
|
||||
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values={'1000053337', '4000122230'})
|
||||
assert status == 'none' and surviving == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 合并裁决
|
||||
|
||||
def test_merge_applies_unique_heuristic_candidate_to_lines():
|
||||
"""唯一候选:低置信度写入缺失行;relation 标记 reservation_heuristic。"""
|
||||
order = _order()
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230', '1000053337'])},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
observation = _reservation_observation(merged[0])
|
||||
# 断言:候选中与已提取 PO 相同的 1000053337 被排除,唯一候选自动写入。
|
||||
assert observation is not None and observation['value'] == '4000122230'
|
||||
# 断言:启发式语义可辨识——confidence 0.5 + basis 标记,供复核端标注与审计。
|
||||
assert observation['confidence'] == 0.5
|
||||
assert observation['email_supplement_evidence']['basis'] == 'bare_numeric_heuristic'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'reservation_heuristic'
|
||||
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied'
|
||||
|
||||
|
||||
def test_merge_excludes_po_number_missing_from_pdf_via_subject_label():
|
||||
"""截图 1 修复路径:PDF 侧 PO 也解析失败时,主题标签排除 PO,仍唯一命中。"""
|
||||
order = _order()
|
||||
order['header_fields'] = []
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(
|
||||
['4000122230', '1000053337'],
|
||||
email_subject='RE_ WELLTRUST ACC PO 1000053337.eml',
|
||||
)},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
observation = _reservation_observation(merged[0])
|
||||
# 断言:主题「PO 1000053337」触发的标签排除让 4000122230 成为唯一候选。
|
||||
assert observation is not None and observation['value'] == '4000122230'
|
||||
|
||||
|
||||
def test_merge_ambiguous_candidates_become_review_conflict():
|
||||
"""多候选:不自动挑值,转 supplement_field_conflict 由现有面板裁决。"""
|
||||
order = _order()
|
||||
order['header_fields'] = []
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230', '5000122230'])},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
# 断言:未写入任何 reservation,冲突与人工裁决标记就位。
|
||||
assert _reservation_observation(merged[0]) is None
|
||||
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'ambiguous'
|
||||
conflicts = [item for item in merged[0]['conflicts'] if item.get('field') == 'reservation_id']
|
||||
assert len(conflicts) == 1
|
||||
conflict = conflicts[0]
|
||||
# 断言:复用现有冲突结构(reason/阻塞级别/header 作用域),候选值与逐候选证据齐全。
|
||||
assert conflict['reason'] == 'supplement_field_conflict'
|
||||
assert conflict['severity'] == 'blocking'
|
||||
assert conflict['scope'] == 'header'
|
||||
assert conflict['values'] == ['4000122230', '5000122230']
|
||||
assert all(source['source_type'] == 'email_body' for source in conflict['sources'])
|
||||
|
||||
|
||||
def test_merge_never_overwrites_existing_reservation():
|
||||
"""已有合法预约单号(含邮件补充表正常解析出的值)时兜底绝不写入。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append(
|
||||
{'field_id': 'reservation', 'observations': [{'value': '3000099143'}]},
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230'])},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
# 断言:原值保持不变,无启发式标记与 relation 变更。
|
||||
assert _reservation_observation(merged[0])['value'] == '3000099143'
|
||||
assert '_hxops_reservation_heuristic' not in merged[0]
|
||||
assert '_hxops_email_supplement_relation' not in merged[0]
|
||||
|
||||
|
||||
def test_merge_never_overwrites_invalid_format_reservation_raw_value():
|
||||
"""行上已有非法格式预约单号原值(如字母型编号)时同样不覆盖,交人工纠错。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append(
|
||||
{'field_id': 'reservation', 'observations': [{'value': 'RSV-88'}]},
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230'])},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
# 断言:非法原值虽不通过 5/10 位校验,仍属已有业务事实,兜底跳过。
|
||||
assert _reservation_observation(merged[0])['value'] == 'RSV-88'
|
||||
assert '_hxops_reservation_heuristic' not in merged[0]
|
||||
|
||||
|
||||
def test_merge_excludes_qty_and_row_values_from_candidates():
|
||||
"""数量 39739 与补充行已提取值都参与排除,防止把业务数值误当预约单号。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'][1]['observations'][0]['value'] = 39739
|
||||
supplement = _supplement(['39739'])
|
||||
supplement['rows'] = [{'customer_po_number': '1000053337'}]
|
||||
order['header_fields'] = []
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: supplement},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
# 断言:候选恰为行数量值 → 排除后 none:无注入、无标记。
|
||||
assert _reservation_observation(merged[0]) is None
|
||||
assert '_hxops_reservation_heuristic' not in merged[0]
|
||||
|
||||
|
||||
def test_merge_unique_claim_not_reused_across_orders():
|
||||
"""同 Intake 多订单共享候选:先到先得,第二个订单不得重复占用同一候选。"""
|
||||
first = _order()
|
||||
second = _order()
|
||||
second['lines'][0]['fields'][0]['observations'][0]['value'] = 'D4-A08AR12000002'
|
||||
merged = merge_email_supplements(
|
||||
orders=[first, second],
|
||||
supplements_by_intake={1: _supplement(['4000122230'])},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
# 断言:第一个订单占用后 claimed 生效,第二个订单无候选可用且不产生标记。
|
||||
assert _reservation_observation(merged[0])['value'] == '4000122230'
|
||||
assert _reservation_observation(merged[1]) is None
|
||||
assert '_hxops_reservation_heuristic' not in merged[1]
|
||||
|
||||
|
||||
def test_merge_skips_when_schema_lacks_reservation_field():
|
||||
"""Schema 未配置 reservation_id 时兜底整体跳过,不误建字段。"""
|
||||
schema = {'fields': [item for item in SCHEMA['fields'] if item.get('field_code') != 'reservation_id']}
|
||||
order = _order()
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230'])},
|
||||
schema_definition=schema,
|
||||
)
|
||||
assert _reservation_observation(merged[0]) is None
|
||||
assert '_hxops_reservation_heuristic' not in merged[0]
|
||||
|
||||
|
||||
def test_merge_writes_header_scope_reservation_when_schema_declares_header():
|
||||
"""Schema 声明 header 作用域预约单号时,唯一候选写入订单头默认值。"""
|
||||
order = _order()
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: _supplement(['4000122230', '1000053337'])},
|
||||
schema_definition=HEADER_RESERVATION_SCHEMA,
|
||||
)
|
||||
header_field = next(
|
||||
item for item in merged[0]['header_fields'] if item['field_id'] == 'reservation'
|
||||
)
|
||||
# 断言:header 作用域配置下候选写入 header_fields(effective = line ?? header 的头侧默认值)。
|
||||
assert header_field['observations'][0]['value'] == '4000122230'
|
||||
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied'
|
||||
|
||||
|
||||
def test_merge_without_candidates_key_is_noop():
|
||||
"""旧 Run 补充快照无 reservation_candidates 键:兜底静默跳过,行为不变。"""
|
||||
order = _order()
|
||||
supplement = _supplement([])
|
||||
supplement.pop('reservation_candidates')
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: supplement},
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
assert _reservation_observation(merged[0]) is None
|
||||
assert '_hxops_reservation_heuristic' not in merged[0]
|
||||
@@ -4,7 +4,9 @@ tests/test_shipping_review_line_fulfillment_decision.py
|
||||
用途:行级履约决定的库存安全、reopen 约束与审计参数契约测试。
|
||||
依赖:pytest、order_review_fulfillment_decision_service。
|
||||
逻辑:覆盖库存不足禁止先行、task_created 禁止 reopen、管理员重开边界、
|
||||
数量解析与评估助手;不依赖完整建单 Fixture。
|
||||
数量解析与评估助手;以及缺口放行证据字段按「预约号+料号」筛快照、
|
||||
预约键 0 行命中时按料号键兜底重筛(evidence_scope=part_fallback)与
|
||||
放行全量字段值落库契约;不依赖完整建单 Fixture。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,6 +30,7 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo
|
||||
_release_template_system_fields,
|
||||
_release_fact_identity,
|
||||
_resolve_shortage_release_inventory_source,
|
||||
_shortage_release_required_fields,
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
_is_shortage_match_fact,
|
||||
_has_terminal_inventory_rpa_failure,
|
||||
@@ -616,3 +619,610 @@ def test_project_empty_case_without_draft(app):
|
||||
result = project_review_case_line_decisions(case)
|
||||
assert result['lines'] == []
|
||||
assert result['has_open_lines'] is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [Task 6] 缺口料号兜底:放行证据字段按「预约号+料号」筛库存快照;预约键 0 行命中
|
||||
# 时按料号键重筛带出(evidence_scope=part_fallback,审计可见),并落全量模板字段值。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
*,
|
||||
inventory_rows: list[dict[str, str]] | None = None,
|
||||
order_reservation_id: str = 'R-ORDER',
|
||||
order_part_number: str = 'ODM-001',
|
||||
required_qty: str = '10',
|
||||
part_available_qty: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造放行字段判定夹具:「预约号+料号」匹配方案 + 行级库存快照 + 模板消费 ODM 字段。
|
||||
|
||||
核心逻辑:复用 conftest 种子源 DSV360_AWSDU(profile.match_keys=part_number +
|
||||
reservation_id,订单键 test-order-part-number / test-order-reservation-id),
|
||||
订单行预约号默认 'R-ORDER';库存快照行预约号默认 'R-INV'(≠订单)以制造
|
||||
预约键 0 行命中、料号键可命中的兜底场景。同时落一条真实行匹配事实
|
||||
(not_found 且指向本快照),供 decide 放行分支走真实模型查询。
|
||||
|
||||
Args:
|
||||
inventory_rows: 库存快照行(语义键 part / reservation / odm);
|
||||
None 时默认单行且 odm 值唯一('ODM-VAL')。
|
||||
required_qty: 行需求量(默认 '10' 保持 Task 6 口径)。
|
||||
part_available_qty: 匹配器下发的料号兜底总量;None 时不落列
|
||||
(自动放行服务视为不可判定并跳过,Task 7 使用)。
|
||||
|
||||
Returns:
|
||||
(task, inventory_file, odm_field)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventorySource,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
|
||||
part_field = ShippingInventoryField.query.filter_by(field_code='part_number').one()
|
||||
reservation_field = ShippingInventoryField.query.filter_by(field_code='reservation_id').one()
|
||||
odm_field = ShippingInventoryField.query.filter_by(field_code='odm_id').one()
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id))
|
||||
assert template is not None
|
||||
# 发货模板只消费 ODM 字段:该字段在快照行上的唯一值即放行自动带出的证据值。
|
||||
template.definition_json = {
|
||||
'mappings': [
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': str(odm_field.id)},
|
||||
],
|
||||
}
|
||||
|
||||
user = User(username='part-fallback', email='part-fallback@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema(schema_code='PART_FALLBACK', display_name='Part Fallback')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-PART-FALLBACK',
|
||||
user_id=user.id,
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=1,
|
||||
schema_version_id=schema_version.id,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
# 订单行 match-key 值必须写入 field_values_json(键 = match_keys.order_field_id)。
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
reservation_id=order_reservation_id,
|
||||
part_number=order_part_number,
|
||||
qty=required_qty,
|
||||
field_values_json={
|
||||
'test-order-part-number': order_part_number,
|
||||
'test-order-reservation-id': order_reservation_id,
|
||||
},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
|
||||
rows = [
|
||||
{
|
||||
str(part_field.id): str(row.get('part') or ''),
|
||||
str(reservation_field.id): str(row.get('reservation') or ''),
|
||||
str(odm_field.id): str(row.get('odm') or ''),
|
||||
}
|
||||
for row in (inventory_rows if inventory_rows is not None else [
|
||||
{'part': order_part_number, 'reservation': 'R-INV', 'odm': 'ODM-VAL'},
|
||||
])
|
||||
]
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-PART-FALLBACK',
|
||||
storage_path='test/part-fallback.xlsx',
|
||||
source_file_name='part-fallback.xlsx',
|
||||
source_code='DSV360_AWSDU',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=rows,
|
||||
line_count=len(rows),
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
|
||||
# 放行资格走真实模型查询:行匹配事实 = not_found(库存不足),指向本快照与本库存源。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='not_found',
|
||||
inventory_status='ready',
|
||||
required_qty=required_qty,
|
||||
available_qty='0',
|
||||
matched_qty='0',
|
||||
shortage_qty=required_qty,
|
||||
part_available_qty=part_available_qty,
|
||||
reservation_id=order_reservation_id,
|
||||
part_number=order_part_number,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
return task, inventory_file, odm_field
|
||||
|
||||
|
||||
def _decide_release_with_captured_snapshot(app, monkeypatch, *, task):
|
||||
"""
|
||||
经 decide_review_line_fulfillment 公开路径提交放行(预约不匹配场景),捕获落库快照。
|
||||
|
||||
核心逻辑:Case/草稿/决定行为进程内替身;放行分支真实执行(真实行匹配事实 +
|
||||
真实 _shortage_release_required_fields + 真实校验),Gate 重算、审计写库与
|
||||
resume/投影替身化,隔离外部副作用。提交 release_field_values={},
|
||||
用于证明自动带出值无须人工输入即可落库。
|
||||
|
||||
Returns:
|
||||
captured:决定行构造 kwargs(含 snapshot_json 全量内容)。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{
|
||||
'draft_line_id': 'L1',
|
||||
'qty': '10',
|
||||
'reservation_id': 'R-ORDER',
|
||||
'part_number': 'ODM-001',
|
||||
}],
|
||||
validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '0'}]},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
id=1,
|
||||
case_no='CASE-PART-FALLBACK',
|
||||
status='ready',
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='RUN-1'),
|
||||
confirmed_task_id=int(task.id),
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
id=None,
|
||||
draft_line_id='L1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
decision_source='user',
|
||||
line_status='released_shortage',
|
||||
is_active=True,
|
||||
reason=None,
|
||||
required_qty='10',
|
||||
available_qty='0',
|
||||
reservation_id='R-ORDER',
|
||||
part_number='ODM-001',
|
||||
task_id=None,
|
||||
wave_no=None,
|
||||
actor_user_id=1,
|
||||
snapshot_json={},
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
)
|
||||
captured = {}
|
||||
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingOrderReviewLineDecision',
|
||||
lambda **kwargs: (captured.update(kwargs), row)[1],
|
||||
)
|
||||
monkeypatch.setattr(svc.db.session, 'add', lambda value: None)
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42))
|
||||
# [STEP] 放行后 Gate 同步会重算任务履约态;测试中替身化重算与审计/resume/投影副作用。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||
lambda task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.resume_after_review_change',
|
||||
lambda **kwargs: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome',
|
||||
lambda payload, resume: payload,
|
||||
)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: (lambda **kwargs: case))
|
||||
monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||
lambda value: {},
|
||||
)
|
||||
|
||||
result = svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no=case.case_no,
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
reason='库存缺口按料号兜底放行',
|
||||
expected_draft_version=1,
|
||||
release_field_values={},
|
||||
)
|
||||
# 断言意图:决定行已分配主键并完成落库流程(flush 替身回填)。
|
||||
assert result['decision']['id'] == 42
|
||||
return captured
|
||||
|
||||
|
||||
def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses(app):
|
||||
"""预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual),
|
||||
# 且证据范围显式标记为 part_fallback(审计可见)。
|
||||
assert scope == 'part_fallback'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': 'ODM-VAL',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_part_fallback_still_manual_when_values_ambiguous(app):
|
||||
"""料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:scope 仍标记 part_fallback(确按料号重筛),但分歧字段禁止任取值,
|
||||
# 必须回退为人工必填、值为空。
|
||||
assert scope == 'part_fallback'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_reservation_hit_keeps_inventory_snapshot_scope(app):
|
||||
"""预约号+料号同时命中时不得误标兜底,证据范围必须保持 inventory_snapshot。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-ORDER', 'odm': 'ODM-VAL'},
|
||||
],
|
||||
)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:预约命中场景 scope 恒为 inventory_snapshot,字段照常自动带值。
|
||||
assert scope == 'inventory_snapshot'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': 'ODM-VAL',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_decision_records_part_fallback_scope(app, monkeypatch):
|
||||
"""放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」——scope 落在
|
||||
# 决定审计快照 snapshot_json['release_evidence_scope'](导出/审计同源读取)。
|
||||
assert captured['snapshot_json']['release_evidence_scope'] == 'part_fallback'
|
||||
|
||||
|
||||
def test_shortage_release_persists_full_template_field_values(app, monkeypatch):
|
||||
"""落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读
|
||||
# snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空;
|
||||
# 全部字段自动带出时人工必填清单为空、人工提交为空 dict 仍可放行。
|
||||
assert captured['snapshot_json']['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||
assert captured['snapshot_json']['release_required_fields'] == []
|
||||
|
||||
|
||||
def test_shortage_release_part_fallback_still_requires_manual_fill_on_decide(app, monkeypatch):
|
||||
"""料号兜底分歧字段未人工补录时,公开 decide 路径仍必须 409(fail-closed 不回退)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:兜底只解决「能唯一取值」的补录;分歧字段缺失人工补录仍按原契约拒绝。
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [Task 7] 料号兜底自动放行:料号总量满足需求时,匹配完成后缺口行由系统自动放行
|
||||
# (decision_source='system'、snapshot.auto_release=True、scope=part_fallback);
|
||||
# 量不足 / 证据分歧 / 已有活动决定一律跳过并维持人工路径(fail-closed)。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_auto_release_fixture(
|
||||
app,
|
||||
*,
|
||||
required_qty: str = '8',
|
||||
part_available_qty: str = '9',
|
||||
inventory_rows: list[dict[str, str]] | None = None,
|
||||
):
|
||||
"""
|
||||
构造自动放行端到端夹具:真实 OT/快照行/行事实(part_available_qty)/复核 Case+草稿。
|
||||
|
||||
核心逻辑:复用 Task 6 seed(预约号改用 10 位纯数字域契约值;订单预约号与库存行
|
||||
预约号不同 → 预约键 0 行命中、料号键命中),再落一条真实 Review Case 与草稿
|
||||
(与既有投影测试同构:run/unit/document 用悬挂占位 ID),使自动放行可走真实的
|
||||
Case 反查、草稿行定位、决定落库与门禁满足性查询。
|
||||
|
||||
Returns:
|
||||
(task, case, odm_field)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderSnapshot
|
||||
|
||||
task, _inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=inventory_rows,
|
||||
order_reservation_id='3000112934',
|
||||
required_qty=required_qty,
|
||||
part_available_qty=part_available_qty,
|
||||
)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='CASE-AUTO-RELEASE', run_id=921, unit_id=922, document_id=923,
|
||||
owner_user_id=int(task.user_id), status='confirmed', confirmed_task_id=task.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=int(snapshot.schema_version_id),
|
||||
header_values_json={},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'line-1',
|
||||
'qty': required_qty,
|
||||
'reservation_id': '3000112934',
|
||||
'part_number': 'ODM-001',
|
||||
}],
|
||||
validation_result_json={'line_projections': [
|
||||
{'draft_line_id': 'line-1', 'available_qty': '0'},
|
||||
]},
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
return task, case, odm_field
|
||||
|
||||
|
||||
def _patch_auto_release_side_effects(monkeypatch, *, stub_recompute: bool = True) -> list[dict]:
|
||||
"""
|
||||
替身化自动放行的编排副作用(与 Task 6 decide 测试同口径)。
|
||||
|
||||
Args:
|
||||
stub_recompute: True 时替身化任务履约态重算;False 保留真实重算
|
||||
(供门禁满足性测试走完整「放行→重算→sufficiency 放行」链路)。
|
||||
|
||||
Returns:
|
||||
auto_fulfill_jobs:enqueue_post_ot_auto_fulfill_job 捕获列表。
|
||||
"""
|
||||
if stub_recompute:
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||
lambda task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
auto_fulfill_jobs: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||
lambda **kwargs: auto_fulfill_jobs.append(kwargs),
|
||||
)
|
||||
return auto_fulfill_jobs
|
||||
|
||||
|
||||
def _active_auto_release_decisions(case):
|
||||
"""读取该 Case 活动的 release_inventory_shortage 决定(真实模型查询)。"""
|
||||
from app.models import ShippingOrderReviewLineDecision
|
||||
|
||||
return (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(
|
||||
review_case_id=int(case.id),
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
is_active=True,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatch):
|
||||
"""料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、
|
||||
# 模板字段(ODM)可由料号命中的快照行唯一取值。
|
||||
task, case, odm_field = _seed_auto_release_fixture(app)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。
|
||||
assert released == [0]
|
||||
decisions = _active_auto_release_decisions(case)
|
||||
assert len(decisions) == 1
|
||||
decision = decisions[0]
|
||||
assert decision.decision_source == 'system'
|
||||
assert decision.snapshot_json['auto_release'] is True
|
||||
assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback'
|
||||
# 自动带出值必须落库(导出覆盖唯一来源),与人工 decide 放行同契约。
|
||||
assert decision.snapshot_json['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||
assert decision.snapshot_json['release_required_fields'] == []
|
||||
|
||||
|
||||
def test_auto_release_skips_when_part_total_below_required(app, monkeypatch):
|
||||
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 同上构造,但料号总量改为 3(< 8)。
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app, part_available_qty='3')
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。
|
||||
assert released == []
|
||||
assert _active_auto_release_decisions(case) == []
|
||||
|
||||
|
||||
def test_auto_release_skips_when_evidence_field_ambiguous(app, monkeypatch):
|
||||
"""证据字段无法唯一取值(requires_manual 残留)时不得自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 同上构造,但两条同料号快照行在模板字段(ODM)上取值不同。
|
||||
task, case, _odm_field = _seed_auto_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': '3000420001', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': '3000420002', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:降级为人工放行(补录要求保留),不产生自动决定。
|
||||
assert released == []
|
||||
assert _active_auto_release_decisions(case) == []
|
||||
|
||||
|
||||
def test_auto_release_does_not_duplicate_existing_decision(app, monkeypatch):
|
||||
"""已有人工放行/结案决定(或已放行)的行不得重复自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
first = auto_release_part_fallback_shortages(task)
|
||||
second = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:幂等——不新建第二个活动决定,原决定保持不变。
|
||||
assert first == [0]
|
||||
assert second == []
|
||||
assert len(_active_auto_release_decisions(case)) == 1
|
||||
|
||||
|
||||
def test_auto_release_counted_in_sufficiency_and_gate_releases(app, monkeypatch):
|
||||
"""自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_recompute_task_match_aggregate,
|
||||
match_completed,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task, _case, _odm_field = _seed_auto_release_fixture(app)
|
||||
# 保留真实 recompute:完整走「放行落库 → 任务履约态重算 → 满足性门禁」链路。
|
||||
_patch_auto_release_side_effects(monkeypatch, stub_recompute=False)
|
||||
|
||||
# 放行前:缺口行未放行 → 整单不满足。
|
||||
assert match_completed(task) is False
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过,
|
||||
# inventory_sufficiency 不再因该行 blocked_manual。
|
||||
assert released == [0]
|
||||
assert match_completed(task) is True
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
line_results = task.step_payload_json['current_match_projection']['line_results']
|
||||
assert line_results[0]['line_status'] == 'released'
|
||||
@@ -236,3 +236,55 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke
|
||||
assert task.review_status == 'shortage_review'
|
||||
assert task.pending_human_reason == 'shortage'
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
|
||||
|
||||
|
||||
def test_system_auto_release_decision_counts_as_released(app):
|
||||
"""系统自动放行(decision_source='system')的活动决定必须被满足性门禁按放行读取。
|
||||
|
||||
核心逻辑:料号兜底自动放行(Task 7)落库的 release_inventory_shortage 决定
|
||||
decision_source='system';``_released_snapshot_line_ids_for_task`` 的真实查询
|
||||
(不经测试 seam)必须同等识别,match_completed / 聚合重算才能把放行行计入满足。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderReviewLineDecision
|
||||
from app.services.shipping_notice.fulfillment_workflow import _recompute_task_match_aggregate
|
||||
|
||||
with app.app_context():
|
||||
task = _task_with_current_matches(
|
||||
task_no='SN-AUTO-RELEASE-GATE',
|
||||
rows=[{'match_result': 'not_found', 'shortage_qty': '1'}],
|
||||
)
|
||||
# 放行前:缺口行未放行 → 整单不满足。
|
||||
assert match_completed(task) is False
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-AUTO-RELEASE-GATE', run_id=931, unit_id=932, document_id=933,
|
||||
owner_user_id=task.user_id, status='confirmed', confirmed_task_id=task.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=1,
|
||||
header_values_json={},
|
||||
lines_json=[{'draft_line_id': 'line-1', 'qty': '1', 'reservation_id': '3000112934'}],
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
draft_line_id='line-1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code='release_inventory_shortage',
|
||||
decision_source='system',
|
||||
line_status='released_shortage',
|
||||
is_active=True,
|
||||
snapshot_json={'auto_release': True, 'release_evidence_scope': 'part_fallback'},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
# 系统自动放行决定落库后走真实放行查询(不打 seam 补丁)必须满足。
|
||||
assert match_completed(task) is True
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released'
|
||||
@@ -215,6 +215,92 @@ def test_allowed_system_facts_use_notice_line_no_not_export_sequence():
|
||||
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_part_fallback_total_aggregates_across_reservations_within_allowed_source():
|
||||
"""预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。"""
|
||||
# Reservation 契约只接受 5/10 位纯数字(validated_reservation_id),
|
||||
# 故用互不相同的数字预约号表达「订单预约号 vs 其它预约号」。
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines,
|
||||
inventory_lines=inventory_lines,
|
||||
header_reservation_id=None,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:订单预约号无库存桶 → not_found;料号兜底总量 0+5+3=8 必须随行结果下发。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['available_qty'] == 0.0
|
||||
assert result['part_available_qty'] == 8.0
|
||||
|
||||
|
||||
def test_part_fallback_total_respects_allowed_source_and_ignores_unit():
|
||||
"""料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。"""
|
||||
order_lines = [{
|
||||
'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8,
|
||||
'allowed_source_codes': ['DSV'], 'candidate_line_id': 1,
|
||||
}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'},
|
||||
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['part_available_qty'] == 105.0
|
||||
|
||||
|
||||
def test_part_fallback_total_absent_for_conflict_and_missing_part():
|
||||
"""multi_file_conflict / 缺料号 / invalid(超出候选范围)行不下发料号总量,避免误导用户。"""
|
||||
order_lines = [
|
||||
{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 1,
|
||||
'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1},
|
||||
{'line_no': 2, 'reservation_id': '3000092918', 'quantity': 1,
|
||||
'allowed_source_codes': ['A'], 'candidate_line_id': 2},
|
||||
{'line_no': 3, 'part_number': 'P-2', 'reservation_id': '1380000000', 'quantity': 1,
|
||||
'allowed_source_codes': ['A'], 'candidate_line_id': 3},
|
||||
]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'},
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'},
|
||||
{'reservation_id': '1380000000', 'part_number': 'P-2', 'qty': 5, '__source_code': 'B'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
# 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。
|
||||
assert 'part_available_qty' not in payload['line_results'][0]
|
||||
assert 'part_available_qty' not in payload['line_results'][1]
|
||||
# 断言意图:命中仅存在于候选范围外源(invalid)的行同样不写键,不得误导放行判断。
|
||||
assert payload['line_results'][2]['disposition'] == 'invalid'
|
||||
assert 'part_available_qty' not in payload['line_results'][2]
|
||||
|
||||
|
||||
def test_part_fallback_total_on_shortage_line_sums_other_reservations():
|
||||
"""预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。"""
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。
|
||||
assert result['disposition'] == 'shortage'
|
||||
assert result['available_qty'] == 2.0
|
||||
assert result['shortage_qty'] == 6.0
|
||||
assert result['part_available_qty'] == 9.0
|
||||
|
||||
|
||||
def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||
"""货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
Reference in new issue
Block a user