feat(shipping-notice): 收敛订单处理状态与履约门禁
This commit is contained in:
1 parent
bffcd55b40
commit
70dd0051b8
153 files changed
+10916
-4296
No files matched your search
+123
-90
@@ -26,38 +26,6 @@ def pytest_configure(config):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _capture_legacy_order_rows_for_tests(monkeypatch):
|
||||
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
|
||||
from app.models import ShippingNotice
|
||||
|
||||
original_init = ShippingNotice.__init__
|
||||
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
|
||||
|
||||
def _init(self, **kwargs):
|
||||
rows = kwargs.pop('lines_json', None)
|
||||
kwargs.pop('order_lines_migration_status', None)
|
||||
header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs}
|
||||
original_init(self, **kwargs)
|
||||
if rows is not None:
|
||||
self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)]
|
||||
for key, value in header_values.items():
|
||||
setattr(self, f'_test_{key}', value)
|
||||
|
||||
monkeypatch.setattr(ShippingNotice, '__init__', _init)
|
||||
for key in (*legacy_headers, 'lines_json'):
|
||||
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
|
||||
monkeypatch.setattr(
|
||||
ShippingNotice,
|
||||
key,
|
||||
property(
|
||||
lambda task, name=storage: getattr(task, name, None),
|
||||
lambda task, value, name=storage: setattr(task, name, value),
|
||||
),
|
||||
raising=False,
|
||||
)
|
||||
|
||||
|
||||
def parse_api_error(body: dict) -> dict:
|
||||
"""
|
||||
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
|
||||
@@ -193,12 +161,17 @@ def seed_task_inventory_source(
|
||||
*,
|
||||
source_code: str = "DSV360_AWSDU",
|
||||
) -> None:
|
||||
"""测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。"""
|
||||
"""测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。"""
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task
|
||||
from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
@@ -207,35 +180,39 @@ def seed_task_inventory_source(
|
||||
source = get_database_inventory_source(source_code)
|
||||
if not source:
|
||||
raise ValueError(f"unknown inventory source for tests: {source_code}")
|
||||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||||
|
||||
context = extract_routing_context(task)
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
raise ValueError(
|
||||
f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
|
||||
)
|
||||
identity = resolution.identity
|
||||
task.inventory_source_code = identity.source_code
|
||||
task.inventory_connector_type = identity.connector_type
|
||||
task.inventory_warehouse_id = identity.warehouse_id
|
||||
task.inventory_source_status = "resolved"
|
||||
task.inventory_source_method = "rule_exact"
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
|
||||
if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id:
|
||||
freeze_test_task_order_snapshot(task)
|
||||
if not owner.order_snapshot_id:
|
||||
raise ValueError('test task must have a frozen order snapshot before inventory source selection')
|
||||
freeze_candidates_for_task(
|
||||
owner,
|
||||
adjudication=InventorySourceAdjudication(
|
||||
status='resolved',
|
||||
method='test_fixture',
|
||||
source_code=str(source.get('source_code') or source_code).strip().upper(),
|
||||
candidates=[source],
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
if task.order_snapshot_id:
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
if owner.order_snapshot_id:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
lines = task.lines_json if isinstance(task.lines_json, list) else []
|
||||
lines = getattr(task, 'lines_json', None)
|
||||
lines = lines if isinstance(lines, list) else []
|
||||
rows = [
|
||||
{
|
||||
'part_number': row.get('part_number'),
|
||||
@@ -244,33 +221,19 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
}
|
||||
for row in lines if isinstance(row, dict)
|
||||
]
|
||||
task._test_order_rows = rows
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
task.order_data_version = int(task.order_data_version or 1)
|
||||
from app import db
|
||||
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
|
||||
owner._test_order_rows = rows
|
||||
_ensure_test_task_dynamic_order(owner)
|
||||
owner.order_data_version = int(owner.order_data_version or 1)
|
||||
from app.models import ShippingOrderExtraction
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
customer = getattr(task, 'customer', None)
|
||||
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
).one_or_none() is None:
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
raw_name=customer.standard_name,
|
||||
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint='r' * 64,
|
||||
identity_rule_version='test.v1', resolution_method='manual',
|
||||
confirmation_reason='测试确认', confirmed_by_id=None,
|
||||
))
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
|
||||
customer = getattr(owner, 'customer', None)
|
||||
if extraction is not None and customer is not None:
|
||||
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
owner,
|
||||
actor_id=None,
|
||||
expected_order_data_version=int(task.order_data_version),
|
||||
expected_order_data_version=int(owner.order_data_version),
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
'test_fixture': True,
|
||||
@@ -284,6 +247,47 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None:
|
||||
"""为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。"""
|
||||
from app import db
|
||||
from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake
|
||||
|
||||
candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None
|
||||
if candidate is None:
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id),
|
||||
user_id=int(task.user_id), parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id,
|
||||
primary_document_id=1, candidate_key=f'test-resolution-{task.id}',
|
||||
candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.candidate_id = candidate.id
|
||||
if extraction is not None:
|
||||
candidate.order_extraction_id = int(extraction.id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none()
|
||||
if resolution is None:
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=candidate.intake_id,
|
||||
resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
|
||||
identity_rule_set_checksum='t' * 64,
|
||||
)
|
||||
db.session.add(resolution)
|
||||
resolution.status = 'confirmed'
|
||||
resolution.confirmed_customer_id = customer.id
|
||||
resolution.confirmation_method = 'test_fixture'
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
|
||||
from decimal import Decimal
|
||||
@@ -292,16 +296,35 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask, User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
if task.current_order_extraction_id is not None:
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
if task.id is None:
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first()
|
||||
user_id = user_id[0] if isinstance(user_id, tuple) else user_id
|
||||
owner = ShippingOrderTask(
|
||||
task_no=f'OT-TEST-{task.task_no}',
|
||||
user_id=int(user_id or 1),
|
||||
status='ready',
|
||||
current_step='customer_review',
|
||||
)
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task.order_task_id = owner.id
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
if owner.current_order_extraction_id is not None:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
return
|
||||
if task.id is None:
|
||||
db.session.add(task)
|
||||
if owner.id is None:
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
@@ -335,11 +358,11 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
required = {'part_number', 'reservation_id', 'qty'}
|
||||
if not required.issubset(field_ids):
|
||||
raise ValueError('RPA test schema lacks required order business purposes')
|
||||
extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
|
||||
extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code in required:
|
||||
@@ -358,7 +381,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=json_value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
owner.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
@@ -425,9 +448,14 @@ def inventory_csv_with_warehouse(
|
||||
|
||||
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
|
||||
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"source_code": str(task.inventory_source_code or ""),
|
||||
"warehouse_id": str(task.inventory_warehouse_id or ""),
|
||||
"source_code": str(source_code or ""),
|
||||
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
|
||||
}
|
||||
|
||||
|
||||
@@ -464,6 +492,11 @@ def rpa_callback_payload(
|
||||
status: str = "success",
|
||||
) -> dict:
|
||||
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"test-callback:{run_no}",
|
||||
@@ -472,8 +505,8 @@ def rpa_callback_payload(
|
||||
"file_path": str(file_path),
|
||||
"run_no": run_no,
|
||||
"source_run_no": run_no,
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"source_code": source_code,
|
||||
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
|
||||
"attempt_no": 1,
|
||||
"lease_token": "test-lease-token",
|
||||
"candidate_set_id": 1,
|
||||
|
||||
@@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s
|
||||
('failed', False, 'failed', '业务阻断失败 → failed'),
|
||||
('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'),
|
||||
('failed', True, 'retryable', '技术失败 retryable → retryable'),
|
||||
('idle', False, 'idle', 'Idle → idle(默认)'),
|
||||
('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'),
|
||||
],
|
||||
ids=lambda t: t[3] if isinstance(t, tuple) else '',
|
||||
)
|
||||
def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label):
|
||||
"""[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。"""
|
||||
def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label):
|
||||
"""[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import project_case_user_status
|
||||
|
||||
case = _fake_case(status='draft')
|
||||
|
||||
@@ -80,7 +80,7 @@ def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
|
||||
"input": {
|
||||
"type": "action",
|
||||
"display_text": "确认",
|
||||
"action_type": "shipping.submit_decision",
|
||||
"action_type": "shipping.match_inventory",
|
||||
"payload": {"task_no": task_no, "decision": "confirm"},
|
||||
},
|
||||
},
|
||||
@@ -128,7 +128,7 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
|
||||
"input": {
|
||||
"type": "action",
|
||||
"display_text": "确认",
|
||||
"action_type": "shipping.submit_decision",
|
||||
"action_type": "shipping.match_inventory",
|
||||
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -106,13 +106,14 @@ def test_export_scheduled_report_flow(monkeypatch):
|
||||
def _download(*args, **kwargs):
|
||||
calls.append("download")
|
||||
captured["download_description"] = kwargs.get("description", "")
|
||||
captured["download_dir"] = kwargs.get("download_dir", "")
|
||||
return "download-object"
|
||||
|
||||
monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download)
|
||||
|
||||
result = module.export_crane_inventory_report(
|
||||
page,
|
||||
{"parameters": [], "source_code": "CRANE_TZR2"},
|
||||
{"parameters": [], "source_code": "CRANE_TZR2", "__download_dir": "D:/tmp/crane-drop"},
|
||||
trigger={"task_no": "SN-1001"},
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
@@ -124,6 +125,7 @@ def test_export_scheduled_report_flow(monkeypatch):
|
||||
assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"]
|
||||
assert captured["description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
assert captured["download_dir"] == "D:/tmp/crane-drop"
|
||||
|
||||
|
||||
def test_should_run_report_before_schedule_uses_driver_environment_only():
|
||||
@@ -443,3 +445,154 @@ def test_resolve_download_mode_uses_driver_environment_only():
|
||||
module = _load_export()
|
||||
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
|
||||
"""
|
||||
expect_download 超时后,应短窗口扫描 downloads_path 并返回目录文件适配器。
|
||||
断言意图:主路径事件丢失时复用 DSV 同款兜底,而不是直接失败。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
locator = MagicMock()
|
||||
fallback = MagicMock()
|
||||
fallback.suggested_filename = "OnHandDetails.xlsx"
|
||||
fallback_calls: list[dict] = []
|
||||
|
||||
class _TimeoutDownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
if exc_type is not None:
|
||||
return False
|
||||
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
raise AssertionError("download event should not resolve")
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", locator),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
|
||||
|
||||
def _fake_wait(*, download_dir, baseline_names, timeout_seconds):
|
||||
fallback_calls.append(
|
||||
{
|
||||
"download_dir": str(download_dir),
|
||||
"baseline_names": set(baseline_names),
|
||||
"timeout_seconds": timeout_seconds,
|
||||
}
|
||||
)
|
||||
return fallback
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
|
||||
|
||||
result = module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
expected_report_name="OnHandDetails.xlsx",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
assert result is fallback
|
||||
assert fallback_calls == [
|
||||
{
|
||||
"download_dir": str(tmp_path),
|
||||
"baseline_names": set(),
|
||||
"timeout_seconds": module._CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_reraises_when_fallback_misses(tmp_path, monkeypatch):
|
||||
"""
|
||||
expect_download 超时且目录无新文件时,应继续抛出原超时。
|
||||
断言意图:兜底失败不能吞掉异常。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
|
||||
class _TimeoutDownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
if exc_type is not None:
|
||||
return False
|
||||
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", MagicMock()),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", lambda **_k: None)
|
||||
|
||||
with pytest.raises(TimeoutError, match="download"):
|
||||
module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_path, monkeypatch):
|
||||
"""
|
||||
Download 链接点击失败时不应进入目录兜底。
|
||||
断言意图:避免点击失败后空等 15s。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
fallback_called = {"value": False}
|
||||
|
||||
class _DownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
raise AssertionError("should not reach download value")
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _DownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", MagicMock()),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: False)
|
||||
|
||||
def _fake_wait(**_kwargs):
|
||||
fallback_called["value"] = True
|
||||
return MagicMock()
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Download link click failed"):
|
||||
module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
assert fallback_called["value"] is False
|
||||
@@ -430,3 +430,60 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>'''],
|
||||
)
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
|
||||
|
||||
def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict():
|
||||
"""邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。
|
||||
|
||||
回归:ZNE 邮件正文 PO 表把客户件号(504-006043-001)放进 PN 列并映射到
|
||||
`part_number`,而 PDF 同一行的 `part_number` 是内部件号(D4-A08AR12000001)、
|
||||
`customer_part_number` 是 504-006043-001。邮件值命中 PDF 的客户件号即同一料号,
|
||||
不得判成 `part_number` 的 `supplement_field_conflict`。
|
||||
"""
|
||||
order = _order() # header PO 4518738152;line part D4-A08AR12000002
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': '504-006043-001'}],
|
||||
})
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': '504-006043-001', # 邮件 PN 列,实为客户件号(MPN)
|
||||
'evidence': {},
|
||||
}],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
# PDF 内部件号保持不变,且不再误判 part_number 冲突
|
||||
assert _value(merged['lines'][0]['fields'], 'part') == 'D4-A08AR12000002'
|
||||
assert not any(item.get('field') == 'part_number' for item in merged['conflicts'])
|
||||
|
||||
|
||||
def test_supplement_field_conflict_pdf_string_evidence_ref_does_not_crash():
|
||||
"""坐标 PDF observation 的 evidence_ref 是字符串时不得崩溃(dict.update length1 回归)。
|
||||
|
||||
回归:`_supplement_field_conflict` 曾用 `dict(pdf.get('evidence_ref') or {})` 直接构造证据,
|
||||
而坐标 PDF observation 的 `evidence_ref` 是字符串(如 `layout:...:row-7:qty`),
|
||||
`dict(<字符串>)` 会按字符拆成长度 1 序列 → `dictionary update sequence element #0 has length 1; 2 is required`。
|
||||
修复后改用 observation 的证据 dict(`layout_evidence`,或 `evidence_ref` 为 dict 时用其本身)。
|
||||
"""
|
||||
from app.services.shipping_notice.order_supplement_merge import _supplement_field_conflict
|
||||
|
||||
conflict = _supplement_field_conflict(
|
||||
field_code='qty', config={'field_id': 'qty', 'field_code': 'qty'}, line_index=0,
|
||||
pdf_observations=[{
|
||||
'value': '30', 'document_id': 305,
|
||||
'evidence_ref': 'layout:305:p1:t1:row-1:qty', # 字符串(坐标 evidence_ref,触发旧崩溃)
|
||||
'layout_evidence': {'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty'},
|
||||
}],
|
||||
email_value='99', email_evidence={'table_index': 0, 'row_index': 1},
|
||||
email_document_id=44, schema_version='v1',
|
||||
)
|
||||
|
||||
assert conflict['conflict_key'] == '0:qty'
|
||||
# evidence_ref 保持 dict 契约,并取 observation 的证据 dict(layout_evidence)
|
||||
assert conflict['sources'][0]['evidence_ref'] == {
|
||||
'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty',
|
||||
}
|
||||
assert conflict['sources'][1]['evidence_ref'] == {'table_index': 0, 'row_index': 1}
|
||||
@@ -14,6 +14,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -648,9 +649,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
temp_roots: list[Path] = []
|
||||
@@ -1346,7 +1349,7 @@ def test_summarize_inventory_batch_results_all_skipped_is_success():
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
|
||||
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
|
||||
"""关闭会话复用时,每次都应在配置目录下生成新的 run_* 临时 profile。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -1371,9 +1374,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
|
||||
@@ -1392,8 +1397,8 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
}
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
|
||||
def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monkeypatch, tmp_path):
|
||||
"""会话复用开启时按 connector+rpa_profile 固定目录,且不得当作临时目录清理。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -1417,20 +1422,92 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads", reuse_dsv_session=True
|
||||
tmp_path / "downloads",
|
||||
reuse_session=True,
|
||||
connector_type="crane_footprint",
|
||||
profile_code="CRANE-MAIN",
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360_session"
|
||||
assert profile_dir == tmp_path / "profile" / "crane_footprint__CRANE-MAIN_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
assert (profile_dir / ".hxops_rpa_session_meta.json").is_file()
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""兼容旧参数 reuse_dsv_session:开启复用时落到 dsv360__* 持久目录。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
class _FakePage:
|
||||
def set_default_timeout(self, value: int) -> None:
|
||||
observed["timeout"] = value
|
||||
|
||||
class _FakeContext:
|
||||
pages = [_FakePage()]
|
||||
|
||||
class _FakeChromium:
|
||||
def launch_persistent_context(self, profile: str, **kwargs):
|
||||
observed["profile"] = profile
|
||||
return _FakeContext()
|
||||
|
||||
class _FakePlaywright:
|
||||
chromium = _FakeChromium()
|
||||
|
||||
class _FakeStarter:
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads",
|
||||
reuse_dsv_session=True,
|
||||
connector_type="dsv360",
|
||||
profile_code="DSV-A",
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360__DSV-A_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
|
||||
|
||||
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
|
||||
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
profile_dir = tmp_path / "dsv360__OLD_session"
|
||||
profile_dir.mkdir(parents=True)
|
||||
stale_marker = profile_dir / "stale.txt"
|
||||
stale_marker.write_text("keep-me", encoding="utf-8")
|
||||
created = time.time() - (25 * 3600)
|
||||
(profile_dir / ".hxops_rpa_session_meta.json").write_text(
|
||||
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
|
||||
|
||||
prepared = worker._prepare_reusable_session_profile(
|
||||
profile_dir,
|
||||
connector_type="dsv360",
|
||||
profile_code="OLD",
|
||||
)
|
||||
|
||||
assert prepared == profile_dir
|
||||
assert not stale_marker.exists()
|
||||
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
|
||||
assert float(meta["created_at_unix"]) > created
|
||||
|
||||
def test_is_dsv_username_page_ignores_login_method_page_text():
|
||||
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
backend/tests/test_gate_derivation.py
|
||||
|
||||
用途:验收 Gate 推导的粗分类 / 位置 / 待办分类,替代旧 checkpoint_kind。
|
||||
依赖:process_gate_contract.derive_*、query_service._todo_category_from_gate、
|
||||
ui_state._derived_*、user_facing_status、pytest。
|
||||
逻辑:Task1–6 契约纯函数与消费点迁移断言;SQL CASE 双读过渡不在此覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
derive_position,
|
||||
derive_todo_category,
|
||||
derive_user_mode,
|
||||
)
|
||||
|
||||
|
||||
def test_user_mode_complete_when_rejected():
|
||||
assert derive_user_mode(
|
||||
user_status='completed',
|
||||
gate_code=None,
|
||||
review_status='rejected',
|
||||
lifecycle_stage=None,
|
||||
) == 'complete'
|
||||
|
||||
|
||||
def test_user_mode_wait_upload_handoff():
|
||||
assert derive_user_mode(
|
||||
user_status='waiting_human',
|
||||
gate_code='manual_upload_handoff',
|
||||
review_status=None,
|
||||
lifecycle_stage='freight_upload',
|
||||
) == 'wait_manual_upload'
|
||||
|
||||
|
||||
def test_user_mode_must_human():
|
||||
assert derive_user_mode(
|
||||
user_status='waiting_human',
|
||||
gate_code='inventory_matching',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'must_human'
|
||||
|
||||
|
||||
def test_user_mode_auto():
|
||||
assert derive_user_mode(
|
||||
user_status='running',
|
||||
gate_code='inventory_preparation',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'auto_continue'
|
||||
|
||||
|
||||
def test_position_review_dispositions():
|
||||
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
|
||||
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
|
||||
assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req'
|
||||
|
||||
|
||||
def test_position_fulfillment():
|
||||
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
|
||||
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
|
||||
|
||||
|
||||
def test_todo_category():
|
||||
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
|
||||
assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception'
|
||||
assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload'
|
||||
assert derive_todo_category(user_mode='complete') == 'done'
|
||||
assert derive_todo_category(user_mode='auto_continue') == 'in_progress'
|
||||
|
||||
|
||||
def test_fetch_gate_positions_empty():
|
||||
from app.services.shipping_notice.query_service import fetch_gate_positions
|
||||
|
||||
assert fetch_gate_positions([]) == {}
|
||||
|
||||
|
||||
def test_fetch_gate_positions_batched(app):
|
||||
"""关键断言:一次查询按 task_id 返回 current_gate_code / status。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import fetch_gate_positions
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='GATE-POS')
|
||||
ot_a = ShippingOrderTask(
|
||||
task_no='OT-GATE-POS-A',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
task_no='OT-GATE-POS-B',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='processing',
|
||||
stage='inventory_fetching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add_all([ot_a, ot_b])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-GATE-POS-A',
|
||||
task_id=int(ot_a.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
),
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-GATE-POS-B',
|
||||
task_id=int(ot_b.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999])
|
||||
assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency'
|
||||
assert result[int(ot_a.id)]['status'] == 'blocked'
|
||||
assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation'
|
||||
assert 999999 not in result
|
||||
|
||||
|
||||
def test_early_stop_uses_derive_user_mode(monkeypatch):
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'SN-1'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_gate': {
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
},
|
||||
'responsible_party': 'owner',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
|
||||
|
||||
def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch):
|
||||
"""
|
||||
回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为
|
||||
blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停,
|
||||
否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。
|
||||
"""
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-INV-EMPTY'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'responsible_party': 'worker',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'auto_continue'
|
||||
|
||||
|
||||
def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch):
|
||||
"""RPA 耗尽属 needs_human,入口仍须早停,不能自动空转重试。"""
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-INV-EXHAUSTED'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
|
||||
|
||||
def test_position_inventory_sufficiency():
|
||||
assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review'
|
||||
|
||||
|
||||
def test_todo_category_from_gate_positions():
|
||||
from app.services.shipping_notice.query_service import _todo_category_from_gate
|
||||
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'},
|
||||
None,
|
||||
)
|
||||
== 'review'
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_preparation', 'status': 'active'},
|
||||
None,
|
||||
)
|
||||
== 'in_progress'
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'},
|
||||
None,
|
||||
)
|
||||
== 'exception'
|
||||
)
|
||||
|
||||
|
||||
def test_user_facing_stage_uses_position(monkeypatch):
|
||||
from app.services.shipping_notice import user_facing_status as ufs
|
||||
|
||||
class FakeTask:
|
||||
step_payload_json = {}
|
||||
pending_human_reason = None
|
||||
lifecycle_status = 'active'
|
||||
review_status = None
|
||||
order_task_id = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
lambda t: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {'current_gate_code': 'inventory_preparation'},
|
||||
)
|
||||
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
|
||||
|
||||
|
||||
def test_derived_entry_surface_review():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
|
||||
assert (
|
||||
_derived_entry_surface(
|
||||
gate_code='order_field_extraction',
|
||||
review_status='parse_review',
|
||||
user_mode='must_human',
|
||||
)
|
||||
== 'review_workbench'
|
||||
)
|
||||
|
||||
|
||||
def test_derived_entry_surface_task():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
|
||||
assert (
|
||||
_derived_entry_surface(
|
||||
gate_code='artifact_generation',
|
||||
review_status=None,
|
||||
user_mode='wait_manual_upload',
|
||||
)
|
||||
== 'task_workbench'
|
||||
)
|
||||
|
||||
|
||||
def test_summary_prefers_gate_shortage_over_freeze(monkeypatch):
|
||||
"""关键断言:Gate 短缺时摘要不再沿用 OT 默认 order_freeze 文案。"""
|
||||
from app.services.shipping_notice import ui_state as us
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-SHORT'
|
||||
review_status = None
|
||||
order_task_id = None
|
||||
updated_at = None
|
||||
error_message = None
|
||||
step_payload_json = {}
|
||||
|
||||
monkeypatch.setattr(us, '_build_stp_facts', lambda t: None)
|
||||
monkeypatch.setattr(us, '_collect_parse_stage_issues', lambda *a, **k: [])
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
lambda t: 'inventory_shortage_review_required',
|
||||
)
|
||||
monkeypatch.setattr(us, 'user_facing_task_stage', lambda t: '库存不足,无法发货')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_progress_contract.project_task_progress_nodes',
|
||||
lambda t: [],
|
||||
)
|
||||
summary = us._build_task_summary(
|
||||
FakeTask(),
|
||||
'shortage_review',
|
||||
user_mode='must_human',
|
||||
gate_code='inventory_sufficiency',
|
||||
)
|
||||
assert '缺口' in summary['message'] or '库存' in summary['message']
|
||||
assert summary['user_mode'] == 'must_human'
|
||||
assert summary['entry_surface'] == 'task_workbench'
|
||||
assert summary['next_auto_step'] is None
|
||||
|
||||
|
||||
def test_rejected_maps_to_review_disposition():
|
||||
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
|
||||
|
||||
|
||||
def test_notice_text_failure_maps_to_quality_issue():
|
||||
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
|
||||
|
||||
|
||||
def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
"""关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-GATE-SHORT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-GATE-SHORT',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'exception'
|
||||
|
||||
|
||||
def test_sql_todo_category_prefers_gate_manual_upload(app):
|
||||
"""关键断言:manual_upload_handoff → manual_upload。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE-MU')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-GATE-MU',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_upload',
|
||||
stage='freight_upload',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-GATE-MU',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'manual_upload'
|
||||
|
||||
|
||||
def test_user_mode_review_status_must_human():
|
||||
"""复核处置 review_status 在默认 auto 之前映射为 must_human。"""
|
||||
for rs in ('parse_review', 'rsv_req', 'quality_issue', 'customer_review', 'shortage_review'):
|
||||
assert derive_user_mode(
|
||||
user_status='running',
|
||||
gate_code=None,
|
||||
review_status=rs,
|
||||
lifecycle_stage=None,
|
||||
) == 'must_human'
|
||||
@@ -14,6 +14,8 @@ import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
@@ -59,6 +61,9 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
|
||||
assert created['definition']['main_table_id'] == 'sample-table'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
|
||||
asset = db.session.get(FileAsset, db.session.get(ShippingOrderDocument, sample.document_id).asset_id)
|
||||
assert asset.lifecycle_status == 'referenced'
|
||||
assert int(asset.reference_count or 0) >= 1
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
|
||||
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
|
||||
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_preview_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
@@ -15,7 +17,13 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocument,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality_service
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
@@ -120,6 +128,62 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc
|
||||
assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND'
|
||||
|
||||
|
||||
def test_frozen_sample_preview_recovers_legacy_table_page_count_when_frozen_evidence_has_all_pages(
|
||||
app, monkeypatch, admin_headers_factory,
|
||||
):
|
||||
"""历史快照把页数误记为表格页数时,仅可由同一冻结证据中的完整物理页数修复预览。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None)
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(
|
||||
draft['id'],
|
||||
sample_role='annotation',
|
||||
physical_page_count=2,
|
||||
include_top_level_pages=False,
|
||||
)
|
||||
published = profile_service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=draft['lock_version'],
|
||||
)
|
||||
profile_id = int(published['id'])
|
||||
sample_id = int(sample.id)
|
||||
# 模拟修复上线前已发布的历史记录:页数被退化为仅第一页业务表。
|
||||
sample.page_count_snapshot = 1
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, sample.layout_version_id)
|
||||
evidence_ref = (layout_version.payload_json or {}).get('coordinate_evidence_ref')
|
||||
assert isinstance(evidence_ref, dict)
|
||||
evidence_asset_no = str(evidence_ref['asset_no'])
|
||||
db.session.commit()
|
||||
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
coordinate_evidence_bytes = gzip.compress(json.dumps({
|
||||
'pages': {'1': {'width': 200, 'height': 100}, '2': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
|
||||
'tables': {'sample-table': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
|
||||
}).encode('utf-8'))
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes',
|
||||
lambda asset: coordinate_evidence_bytes if asset.asset_no == evidence_asset_no else b'%PDF-frozen-preview',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [
|
||||
SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=2, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
|
||||
],
|
||||
)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=admin_headers_factory('frozen-preview-legacy-page-count'),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert parse_api_data(response.get_json())['page_count'] == 2
|
||||
|
||||
|
||||
def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch):
|
||||
"""发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。"""
|
||||
profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
|
||||
|
||||
@@ -336,6 +336,9 @@ def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_
|
||||
'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=draft['id'], sample_role='annotation',
|
||||
).first().document_id,
|
||||
# 本变更将 bind-po-001 改名为 bind-po-002(字段/值源未变),
|
||||
# 正式 XFA 按 binding_id 身份识别删除,故显式确认该身份变更。
|
||||
'allow_formal_binding_deletions': ['bind-po-001'],
|
||||
}, actor_id=user.id, profile_id=draft['id'],
|
||||
browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease['lease_token'],
|
||||
|
||||
@@ -175,12 +175,12 @@ def test_same_po_conflicting_reservations_do_not_merge_lines():
|
||||
|
||||
|
||||
def test_same_po_conflicting_line_no_does_not_merge_same_part_number():
|
||||
"""料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。"""
|
||||
"""料号一致但双方都有不同客户项次(customer_po_line_no)时,不能忽略项次而错误补入 Reservation。"""
|
||||
pdf_line = _partial_line(1, part='PN-1', qty=30)
|
||||
pdf_line['fields'].append(_field('line-id', '00010', 1))
|
||||
email_line = _partial_line(2, part='PN-1', reservation='1000123456')
|
||||
email_line['fields'].append(_field('line-id', '00020', 2))
|
||||
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]}
|
||||
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'customer_po_line_no'}]}
|
||||
|
||||
merged = merge_unit_orders(
|
||||
orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])],
|
||||
|
||||
@@ -4,7 +4,8 @@ tests/test_shipping_auto_progress_p0_3.py
|
||||
用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。
|
||||
依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。
|
||||
逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox
|
||||
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。
|
||||
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链;
|
||||
显式 retry_rpa 覆盖 waiting_external 残留 poll。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -207,6 +208,62 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
"""waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。
|
||||
|
||||
回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa)
|
||||
后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队
|
||||
poll;poll 遇失败 Preparation 直接收口,表现为「改源已保存但 RPA 不触发」。
|
||||
"""
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=905, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_export_failed'
|
||||
gate.next_action_code = 'poll_inventory_preparation'
|
||||
execution.status = 'waiting_external'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'poll_inventory_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls',
|
||||
return_value=0,
|
||||
):
|
||||
result = submit_auto_progress(
|
||||
task=task,
|
||||
trigger='manual_override_source',
|
||||
resume_gate_code='inventory_preparation',
|
||||
inventory_mode='retry_rpa',
|
||||
commit=True,
|
||||
)
|
||||
|
||||
db.session.refresh(gate)
|
||||
# 关键断言:显式重抓必须入队 retry_inventory_preparation(而非残留 poll)。
|
||||
assert result['status'] == 'queued'
|
||||
assert result.get('reused') is False
|
||||
queued = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(gate_id=int(gate.id), status='queued')
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
assert queued is not None
|
||||
assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation'
|
||||
assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa'
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -319,7 +376,7 @@ def test_retry_inventory_matching_fulfillable_passes():
|
||||
query = MagicMock(get=MagicMock(return_value=_Task()))
|
||||
|
||||
with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={
|
||||
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None,
|
||||
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'position': None,
|
||||
}), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \
|
||||
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
|
||||
|
||||
@@ -78,6 +78,26 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac
|
||||
]) is True
|
||||
|
||||
|
||||
def test_unique_notice_warehouse_id_for_header_mapping():
|
||||
"""Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.export import _unique_notice_warehouse_id
|
||||
|
||||
assert _unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id='AWSSG'),
|
||||
SimpleNamespace(inventory_warehouse_id='awssg'),
|
||||
]) == 'AWSSG'
|
||||
assert _unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id=None),
|
||||
SimpleNamespace(inventory_warehouse_id=''),
|
||||
]) is None
|
||||
with pytest.raises(ValueError, match='多库位'):
|
||||
_unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id='AWSSG'),
|
||||
SimpleNamespace(inventory_warehouse_id='MOW'),
|
||||
])
|
||||
|
||||
|
||||
def _freeze_export_snapshot(
|
||||
task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
"""
|
||||
tests/test_shipping_gate_orchestration_separation.py
|
||||
|
||||
用途:锁定履约 Gate「匹配 Attempt 不内嵌 Excel / 匹配通过后续跑独立 artifact Attempt」。
|
||||
依赖:pytest、fulfillment_workflow.try_auto_chain_after_match、process_gate_executor、
|
||||
process_gate_bridge、process_gate_service、auto_progress fixtures。
|
||||
逻辑:Gate 路径(_orchestrator_internal_dispatch)禁止 generate/upload;
|
||||
match pass + sync 后须留下可自动投递的 artifact_generation Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
mark_gates_passed_through,
|
||||
sync_fulfillment_gates_from_task,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
complete_gate_attempt,
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
|
||||
def _task_with_candidate(*, task_no: str = 'OT-ORCH-SEP-001') -> ShippingOrderTask:
|
||||
"""创建带冻结候选集的正式 OT,供 20-Gate Execution 绑定。"""
|
||||
task = ShippingOrderTask(task_no=task_no, user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
task_id=task.id,
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
input_fingerprint='b' * 64,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = candidate.id
|
||||
task.current_order_extraction_id = 101
|
||||
task.order_snapshot_id = 201
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def _patch_fulfillable_inventory(monkeypatch) -> None:
|
||||
"""让 sync_fulfillment 能越过 prep,到达 excel_readiness / artifact。"""
|
||||
inv_file = SimpleNamespace(
|
||||
id=1,
|
||||
snapshot_status='ready',
|
||||
invalidated_at=None,
|
||||
mapping_confirmed=True,
|
||||
source_query_json={},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
lambda _task: inv_file,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_lines_for_task',
|
||||
lambda _task: [{'reservation_id': 'R1', 'part_number': 'P1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status',
|
||||
lambda _task: 'matched',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_completed',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
|
||||
def test_try_auto_chain_gate_path_does_not_call_generate_or_upload(app, monkeypatch) -> None:
|
||||
"""Gate Attempt 路径:try_auto_chain 不得同 Attempt 内嵌 generate_excel / upload。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
|
||||
|
||||
task = ShippingOrderTask(task_no='OT-ORCH-CHAIN-0', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow._current_export_artifact',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
generate_calls: list[dict] = []
|
||||
upload_calls: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.upload_to_freight',
|
||||
lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'},
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{'status': 'ok', 'message': 'matched'},
|
||||
payload={
|
||||
'task_id': task.task_no,
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
'source': 'process_gate',
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert generate_calls == []
|
||||
assert upload_calls == []
|
||||
|
||||
|
||||
def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch) -> None:
|
||||
"""inventory_matching Handler 成功履约时不得调用 generate_excel。"""
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
_patch_fulfillable_inventory(monkeypatch)
|
||||
|
||||
task = _task_with_candidate(task_no='OT-ORCH-SEP-HANDLER')
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9201, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
reason='test_orch_sep',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
generate_calls: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
|
||||
lambda payload: try_auto_chain_after_match(
|
||||
task,
|
||||
{'status': 'ok', 'message': 'matched', 'task_id': task.task_no},
|
||||
payload=payload,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
|
||||
)
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
).one()
|
||||
result = _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload={'actor_user_id': 1},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'passed'
|
||||
assert generate_calls == []
|
||||
|
||||
db.session.refresh(execution)
|
||||
artifact_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='artifact_generation',
|
||||
).one()
|
||||
assert artifact_gate.status != 'passed'
|
||||
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
|
||||
|
||||
|
||||
def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> None:
|
||||
"""匹配事实就绪且无 Artifact 时,submit_auto_progress 须入队 artifact Attempt。"""
|
||||
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_MATCH_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
|
||||
_patch_fulfillable_inventory(monkeypatch)
|
||||
|
||||
task = _task_with_candidate(task_no='OT-ORCH-SEP-ENQ')
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9202, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
reason='test_orch_sep_enqueue',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
matching_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
).one()
|
||||
if matching_gate.status != 'passed':
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_matching',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key=f'test-orch-sep-match:{execution.id}',
|
||||
expected_gate_version=int(matching_gate.evaluation_version),
|
||||
input_snapshot={'action_code': 'retry_inventory_matching', 'payload': {}},
|
||||
)
|
||||
assert attempt is not None
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'action_code': 'retry_inventory_matching'},
|
||||
effective_result_json={'match_status': 'fulfillable'},
|
||||
)
|
||||
|
||||
db.session.refresh(execution)
|
||||
artifact_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='artifact_generation',
|
||||
).one()
|
||||
assert artifact_gate.status != 'passed'
|
||||
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
|
||||
|
||||
queued = submit_auto_progress(task=task, trigger='user_retry', commit=True)
|
||||
assert queued.get('status') in {'queued', 'running'}
|
||||
assert queued.get('gate_code') == 'artifact_generation'
|
||||
attempt = db.session.get(ShippingProcessGateAttempt, int(queued['attempt_id']))
|
||||
assert attempt is not None
|
||||
assert isinstance(attempt.input_snapshot_json, dict)
|
||||
assert attempt.input_snapshot_json.get('action_code') == 'regenerate_excel_artifact'
|
||||
assert Job.query.filter_by(id=int(queued['job_id'])).one().job_type == 'shipping_process_gate'
|
||||
|
||||
|
||||
def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) -> None:
|
||||
"""端到端:match Handler 不生成;artifact Handler 才调用 generate_excel 一次。"""
|
||||
from app.services.shipping_notice.process_gate_executor import (
|
||||
_handle_regenerate_excel,
|
||||
_handle_retry_inventory_matching,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False
|
||||
_patch_fulfillable_inventory(monkeypatch)
|
||||
|
||||
task = _task_with_candidate(task_no='OT-ORCH-SEP-E2E')
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9203, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
reason='test_orch_sep_e2e',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
generate_calls: list[dict] = []
|
||||
|
||||
def _fake_generate(payload):
|
||||
generate_calls.append(dict(payload or {}))
|
||||
artifact = SimpleNamespace(
|
||||
id=99,
|
||||
file_path='/tmp/orch-sep.xlsx',
|
||||
file_name='orch-sep.xlsx',
|
||||
status='ready',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: artifact,
|
||||
)
|
||||
return {'status': 'ok', 'message': 'excel-ok'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
_fake_generate,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
|
||||
lambda payload: try_auto_chain_after_match(
|
||||
task,
|
||||
{'status': 'ok', 'message': 'matched', 'task_id': task.task_no},
|
||||
payload=payload,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
|
||||
)
|
||||
|
||||
matching_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
).one()
|
||||
match_result = _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=matching_gate,
|
||||
payload={'actor_user_id': 1},
|
||||
)
|
||||
assert match_result['outcome'] == 'passed'
|
||||
assert generate_calls == []
|
||||
|
||||
# match handler 内 sync 已投影 artifact;禁止再 force sync matching(会 allow_repass
|
||||
# 入队 artifact Attempt,把 next_action 清成 queued→None)。
|
||||
db.session.refresh(execution)
|
||||
artifact_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='artifact_generation',
|
||||
).one()
|
||||
assert artifact_gate.status != 'passed'
|
||||
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
|
||||
|
||||
artifact_result = _handle_regenerate_excel(
|
||||
execution=execution,
|
||||
gate=artifact_gate,
|
||||
payload={'actor_user_id': 1},
|
||||
)
|
||||
assert artifact_result.get('outcome') == 'passed'
|
||||
assert len(generate_calls) == 1
|
||||
assert generate_calls[0].get('_orchestrator_internal_dispatch') is True
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
tests/test_shipping_inventory_link_ot_owner.py
|
||||
|
||||
用途:锁定库存 Link 挂在正式 OT 上;传入 ShippingNotice 时仍须解析到该 OT 的 active link。
|
||||
依赖:pytest、inventory_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。
|
||||
逻辑:复现「Notice.id ≠ OT.id → Excel 导出读到 0 行库存」回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
resolve_inventory_lines_for_execution,
|
||||
)
|
||||
|
||||
|
||||
def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) -> None:
|
||||
"""Notice 导出路径必须通过 order_task_id 找到挂在 OT 上的库存 Link。"""
|
||||
with app.app_context():
|
||||
inventory_path = tmp_path / 'ot-owned-inventory.xlsx'
|
||||
inventory_path.write_bytes(b'inventory-rows')
|
||||
|
||||
# 先占用 Notice 自增 id=1,确保后续正式 Notice.id ≠ OT.id(复现生产错位)。
|
||||
db.session.add(ShippingNotice(
|
||||
task_no='SN-INV-LINK-BURN',
|
||||
user_id=1,
|
||||
source_type='manual',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
ot = ShippingOrderTask(task_no='OT-INV-LINK-OWNER', user_id=1, source_type='direct_pdf')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INV-LINK-OWNER',
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name='ot-owned-inventory.xlsx',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=[
|
||||
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001'},
|
||||
],
|
||||
line_count=1,
|
||||
)
|
||||
db.session.add_all([ot, inventory_file])
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-INV-LINK-OWNER',
|
||||
user_id=1,
|
||||
source_type='inventory_gate',
|
||||
order_task_id=int(ot.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
assert int(notice.id) != int(ot.id)
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(ot.id),
|
||||
inventory_file_id=int(inventory_file.id),
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 断言:不得用 Notice.id 查 Link(会 miss);必须落到 OT Link。
|
||||
assert active_inventory_file_for_task(ot) is not None
|
||||
assert active_inventory_file_for_task(ot).id == inventory_file.id
|
||||
assert active_inventory_file_for_task(notice) is not None
|
||||
assert active_inventory_file_for_task(notice).id == inventory_file.id
|
||||
assert len(resolve_inventory_lines_for_execution(notice)) == 1
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
tests/test_shipping_inventory_source_adjudication.py
|
||||
|
||||
用途:锁定库存源裁决不得在 unresolved/空候选时兜底全部启用源,并采纳行级 ambiguous。
|
||||
依赖:inventory_source_rules、inventory_routing_engine、pytest monkeypatch。
|
||||
逻辑:用可控引擎结果复现 OT-C68 类缺陷——行级 PREFIX 多候选被丢弃后膨胀为全源。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.inventory_routing_engine import InventoryRoutingResult
|
||||
from app.services.shipping_notice import inventory_source_rules as rules
|
||||
|
||||
|
||||
def _source(code: str) -> dict:
|
||||
"""构造最小可裁决库存源字典。"""
|
||||
return {
|
||||
'source_code': code,
|
||||
'display_name': code,
|
||||
'connector_type': 'dbs',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': code,
|
||||
}
|
||||
|
||||
|
||||
def test_result_to_adjudication_unresolved_keeps_empty_candidates(monkeypatch):
|
||||
"""
|
||||
unresolved 且规则候选为空时,candidates 必须为空。
|
||||
|
||||
关键断言:禁止 list_database_inventory_sources 全源兜底(OT-C68 根因之一)。
|
||||
"""
|
||||
all_sources = [_source(f'SRC_{i}') for i in range(9)]
|
||||
called = {'list_all': False}
|
||||
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'list_database_inventory_sources',
|
||||
lambda: (called.__setitem__('list_all', True) or all_sources),
|
||||
)
|
||||
monkeypatch.setattr(rules, 'get_database_inventory_source', lambda code: None)
|
||||
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
|
||||
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
|
||||
result = InventoryRoutingResult(
|
||||
'unresolved',
|
||||
(),
|
||||
(),
|
||||
{'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []},
|
||||
)
|
||||
adjudication = rules._result_to_adjudication(result, context={})
|
||||
|
||||
assert adjudication.status == 'unresolved'
|
||||
assert adjudication.reason == 'routing_rule_unresolved'
|
||||
assert adjudication.candidates == []
|
||||
assert called['list_all'] is False
|
||||
|
||||
|
||||
def test_result_to_adjudication_ambiguous_only_keeps_rule_sources(monkeypatch):
|
||||
"""
|
||||
ambiguous 多候选只保留规则给出的源;缺失 DB 配置的源不得用全库补齐。
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'list_database_inventory_sources',
|
||||
lambda: [_source('SHOULD_NOT_APPEAR'), _source('ALSO_NO')],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'get_database_inventory_source',
|
||||
lambda code: _source(code) if code in {'A', 'B'} else None,
|
||||
)
|
||||
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
|
||||
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
|
||||
result = InventoryRoutingResult(
|
||||
'ambiguous',
|
||||
('A', 'B', 'MISSING'),
|
||||
(33,),
|
||||
{
|
||||
'priority': 100,
|
||||
'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'],
|
||||
'raw_source_codes': ['A', 'B', 'MISSING'],
|
||||
},
|
||||
)
|
||||
adjudication = rules._result_to_adjudication(result, context={})
|
||||
|
||||
assert adjudication.status == 'ambiguous'
|
||||
assert [item['source_code'] for item in adjudication.candidates] == ['A', 'B']
|
||||
|
||||
|
||||
def test_adjudicate_accepts_unanimous_line_ambiguous(monkeypatch):
|
||||
"""
|
||||
任务级 unresolved、各行一致 ambiguous 时,必须采纳行级候选,不得回落全源。
|
||||
|
||||
复现:Reservation 前缀规则给出 3 源 ambiguous,旧逻辑返回 9 个启用源。
|
||||
"""
|
||||
line_ambiguous = InventoryRoutingResult(
|
||||
'ambiguous',
|
||||
('DSV360_AWSBI_BYAWSCMH01', 'DSV360_AWSBI_BYAWSFRA01', 'DSV360_AWSCV'),
|
||||
(33,),
|
||||
{
|
||||
'priority': 100,
|
||||
'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'],
|
||||
'raw_source_codes': [
|
||||
'DSV360_AWSBI_BYAWSCMH01',
|
||||
'DSV360_AWSBI_BYAWSFRA01',
|
||||
'DSV360_AWSCV',
|
||||
],
|
||||
},
|
||||
)
|
||||
task_unresolved = InventoryRoutingResult(
|
||||
'unresolved',
|
||||
(),
|
||||
(),
|
||||
{'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []},
|
||||
)
|
||||
|
||||
def _evaluate(*, task, line=None, now=None):
|
||||
del task, now
|
||||
return task_unresolved if line is None else line_ambiguous
|
||||
|
||||
monkeypatch.setattr(rules, 'evaluate_inventory_source_rules', _evaluate)
|
||||
monkeypatch.setattr(rules, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'_task_routing_lines',
|
||||
lambda _task, required=None: [{'reservation_id': '2000488715', '_position': 0}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'get_database_inventory_source',
|
||||
lambda code: _source(code),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rules,
|
||||
'list_database_inventory_sources',
|
||||
lambda: [_source(f'EXTRA_{i}') for i in range(9)],
|
||||
)
|
||||
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
|
||||
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
|
||||
adjudication = rules.adjudicate_inventory_source(SimpleNamespace(id=1))
|
||||
|
||||
assert adjudication.status == 'ambiguous'
|
||||
assert [item['source_code'] for item in adjudication.candidates] == [
|
||||
'DSV360_AWSBI_BYAWSCMH01',
|
||||
'DSV360_AWSBI_BYAWSFRA01',
|
||||
'DSV360_AWSCV',
|
||||
]
|
||||
assert adjudication.reason == 'routing_rule_ambiguous'
|
||||
@@ -0,0 +1,245 @@
|
||||
"""
|
||||
tests/test_shipping_line_scoped_inventory_retry.py
|
||||
|
||||
用途:守门明细行重抓/重匹配按行 source_codes 收窄,且不伤已发通知行。
|
||||
依赖:pytest pure_unit、process_gate_executor、recovery_invalidation_service。
|
||||
逻辑:与 display-and-button-contract §6.1 行级收窄约定对齐;不启 Flask/DB。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
"""行级重抓必须把该行 source_codes 交给 ensure_inventory,并收窄失效范围。"""
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-SCOPE')
|
||||
captured: list[dict] = []
|
||||
invalidate_calls: list[dict] = []
|
||||
line = SimpleNamespace(source_codes_json=['DBS'])
|
||||
candidate_set = SimpleNamespace(id=1)
|
||||
sources = [SimpleNamespace(source_code='DBS')]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [line],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: sources,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope',
|
||||
lambda _task, *, line_scope_key=None: {
|
||||
'snapshot_line_id': 1001,
|
||||
'line_no': 2,
|
||||
'source_codes': ['WH_A'],
|
||||
} if line_scope_key not in (None, '') else None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||||
lambda **kwargs: invalidate_calls.append(dict(kwargs)) or {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
|
||||
_handle_retry_inventory_preparation(
|
||||
execution=SimpleNamespace(task_id=1, id=21, candidate_set_id=None),
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
payload={
|
||||
'action_code': 'retry_inventory_preparation',
|
||||
'actor_user_id': 5,
|
||||
'snapshot_line_id': 1001,
|
||||
},
|
||||
)
|
||||
|
||||
# 关键断言:行级强制 RPA 只带该行源,失效也按同行源收窄。
|
||||
assert captured[-1].get('mode') == 'retry_rpa'
|
||||
assert captured[-1].get('source_codes') == ['WH_A']
|
||||
assert captured[-1].get('snapshot_line_id') == 1001
|
||||
assert invalidate_calls[-1].get('source_codes') == ['WH_A']
|
||||
assert invalidate_calls[-1].get('snapshot_line_id') == 1001
|
||||
|
||||
|
||||
def test_inventory_matching_line_scope_uses_match_inventory_line(monkeypatch):
|
||||
"""行级重匹配必须走 match_inventory_line,并携带该行 source_codes。"""
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
|
||||
|
||||
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-MATCH')
|
||||
match_calls: list[dict] = []
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope',
|
||||
lambda _task, *, line_scope_key=None: {
|
||||
'snapshot_line_id': 1002,
|
||||
'line_no': 3,
|
||||
'source_codes': ['WH_B'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory_line',
|
||||
lambda payload, *, line_no: match_calls.append({'payload': dict(payload), 'line_no': line_no})
|
||||
or {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
|
||||
lambda _payload: (_ for _ in ()).throw(AssertionError('整单 match_inventory 不应被行级点击调用')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_completed',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {},
|
||||
)
|
||||
|
||||
result = _handle_retry_inventory_matching(
|
||||
execution=SimpleNamespace(task_id=1, id=21),
|
||||
gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
payload={'action_code': 'retry_inventory_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5},
|
||||
)
|
||||
|
||||
assert match_calls and match_calls[0]['line_no'] == 3
|
||||
assert match_calls[0]['payload'].get('source_codes') == ['WH_B']
|
||||
assert result['outcome'] == 'passed'
|
||||
|
||||
|
||||
def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch):
|
||||
"""行级失效不得改写已发通知行匹配,也不得 supersede 已有 Notice Artifact。"""
|
||||
from app.services.shipping_notice import recovery_invalidation_service as svc
|
||||
|
||||
link_a = SimpleNamespace(
|
||||
id=11, inventory_file_id=101, matched_source_code='WH_A',
|
||||
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
link_b = SimpleNamespace(
|
||||
id=12, inventory_file_id=102, matched_source_code='WH_B',
|
||||
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
match_open = SimpleNamespace(
|
||||
id=21, snapshot_line_id=1001, inventory_source_code='WH_A',
|
||||
allowed_source_codes_snapshot=['WH_A'], is_current=True,
|
||||
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
match_noticed = SimpleNamespace(
|
||||
id=22, snapshot_line_id=1002, inventory_source_code='WH_A',
|
||||
allowed_source_codes_snapshot=['WH_A'], is_current=True,
|
||||
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
|
||||
class _Query:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def with_for_update(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return list(self._rows)
|
||||
|
||||
def filter(self, *_a, **_k):
|
||||
return self
|
||||
|
||||
monkeypatch.setattr(svc, '_noticed_snapshot_line_ids', lambda _task_id: {1002})
|
||||
monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['inventory_matching'])
|
||||
monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: SimpleNamespace(id=1))
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
|
||||
# 纯单测不启 Flask:替换模块内模型符号,避免触碰 Flask-SQLAlchemy query 描述符。
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingTaskInventoryLink',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([link_a, link_b]))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingNoticeLineInventoryMatch',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([match_open, match_noticed]))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingInventoryMapping',
|
||||
SimpleNamespace(
|
||||
inventory_file_id=SimpleNamespace(in_=lambda _ids: True),
|
||||
status='active',
|
||||
query=SimpleNamespace(filter=lambda *_a, **_k: _Query([])),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingNotice',
|
||||
SimpleNamespace(
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_: (_ for _ in ()).throw(AssertionError('行级失效不得查询 Notice Artifact'))
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
result = svc.invalidate_inventory_downstream(
|
||||
execution=SimpleNamespace(task_id=1),
|
||||
action_code='retry_inventory_preparation',
|
||||
attempt_id=9,
|
||||
source_codes=['WH_A'],
|
||||
snapshot_line_id=1001,
|
||||
)
|
||||
|
||||
assert link_a.is_active is False
|
||||
assert link_b.is_active is True
|
||||
assert match_open.is_current is False
|
||||
assert match_noticed.is_current is True
|
||||
assert result['links'] == [11]
|
||||
assert result['matches'] == [21]
|
||||
assert result['artifacts'] == []
|
||||
assert result['uploads'] == []
|
||||
@@ -306,6 +306,86 @@ def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatc
|
||||
assert synced == [task, linked_task]
|
||||
|
||||
|
||||
def test_inventory_loaded_response_reuse_skips_file_line_overwrite(monkeypatch):
|
||||
"""[断言] persist_lines=False 时只推进状态,禁止调用写回 File.inventory_lines_json。"""
|
||||
from app.services.shipping_notice import inventory_mapping_workflow as workflow
|
||||
|
||||
owner_task = SimpleNamespace(id=1, task_no='OT-REUSE-NO-WRITE')
|
||||
linked_task = SimpleNamespace(id=2, task_no='OT-REUSE-LINKED')
|
||||
inventory_file = SimpleNamespace(
|
||||
inventory_file_no='INV-SHARED',
|
||||
inventory_lines_json=[{'part_number': 'KEEP', 'qty': 9}],
|
||||
links=[
|
||||
SimpleNamespace(is_active=True, task=owner_task),
|
||||
SimpleNamespace(is_active=True, task=linked_task),
|
||||
],
|
||||
)
|
||||
apply_calls: list[object] = []
|
||||
|
||||
monkeypatch.setattr(workflow, 'active_inventory_file_for_task', lambda _task: inventory_file)
|
||||
monkeypatch.setattr(
|
||||
workflow,
|
||||
'apply_inventory_parse_result_to_linked_tasks',
|
||||
lambda *args, **kwargs: apply_calls.append((args, kwargs)) or [owner_task],
|
||||
)
|
||||
monkeypatch.setattr(workflow, '_can_relink_inventory', lambda _task: True)
|
||||
monkeypatch.setattr(workflow, 'task_line_purpose_values', lambda _task: [])
|
||||
monkeypatch.setattr(workflow, 'build_field_alignment_preview', lambda *_a, **_k: {})
|
||||
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(workflow, 'log_task_event', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(workflow.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice',
|
||||
lambda _notice: None,
|
||||
)
|
||||
|
||||
response = workflow.inventory_loaded_response(
|
||||
owner_task,
|
||||
[{'part_number': 'MERGED', 'qty': 1, '__source_code': 'SRC_A'}],
|
||||
source='snapshot_reuse',
|
||||
event_type='inventory_snapshot_reused',
|
||||
commit=False,
|
||||
persist_lines=False,
|
||||
)
|
||||
|
||||
assert apply_calls == []
|
||||
assert inventory_file.inventory_lines_json == [{'part_number': 'KEEP', 'qty': 9}]
|
||||
assert response['status'] == 'ok'
|
||||
assert response['data']['persist_lines'] is False
|
||||
|
||||
|
||||
def test_resolve_inventory_lines_prefers_candidate_prep_when_frozen(monkeypatch):
|
||||
"""[断言] 冻结候选 OT 匹配输入取 prepare 合并行,不依赖 active File 上的单源缓存。"""
|
||||
from app.services.shipping_notice import inventory_file_store as store
|
||||
|
||||
task = SimpleNamespace(id=88, task_no='OT-RESOLVE-CAND')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['SRC_A', 'SRC_B'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
lambda _task: {
|
||||
'status': 'ready',
|
||||
'lines': [
|
||||
{'part_number': 'P1', '__source_code': 'SRC_A'},
|
||||
{'part_number': 'P2', '__source_code': 'SRC_B'},
|
||||
],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
store,
|
||||
'active_inventory_file_for_task',
|
||||
lambda _task: (_ for _ in ()).throw(AssertionError('must not fall back to active file')),
|
||||
)
|
||||
|
||||
rows = store.resolve_inventory_lines_for_execution(task)
|
||||
assert [row['__source_code'] for row in rows] == ['SRC_A', 'SRC_B']
|
||||
|
||||
|
||||
def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
|
||||
"""库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。"""
|
||||
from app.services.shipping_notice import inventory_mapping_workflow as workflow
|
||||
@@ -2191,7 +2271,7 @@ def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app)
|
||||
},
|
||||
)
|
||||
|
||||
def _fake_probe(actual_task, *, mode, allow_auto_retry=True):
|
||||
def _fake_probe(actual_task, *, mode, allow_auto_retry=True, source_codes=None):
|
||||
probe_calls.append((actual_task, mode))
|
||||
return SimpleNamespace(
|
||||
pending_source_codes=['SRC_A', 'SRC_B'],
|
||||
@@ -2254,7 +2334,7 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode, allow_auto_retry=True: SimpleNamespace(
|
||||
lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: SimpleNamespace(
|
||||
pending_source_codes=[],
|
||||
prepared_source_codes=[],
|
||||
failed_source_codes=['SRC_A'],
|
||||
@@ -2271,3 +2351,168 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat
|
||||
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['data']['blocking_reason']['code'] == 'inventory_preparation_failed'
|
||||
|
||||
|
||||
def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, app):
|
||||
"""[断言] 冻结源 ready 复用必须先 link;禁止未绑定直接 inventory_loaded_response 抛 ValueError。"""
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='OT-STP-READY-LINK',
|
||||
id=701,
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=9,
|
||||
)
|
||||
snapshot = SimpleNamespace(
|
||||
inventory_file_no='INV-READY-001',
|
||||
source_code='SRC_A',
|
||||
warehouse_id='WH1',
|
||||
)
|
||||
call_order: list[str] = []
|
||||
|
||||
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
|
||||
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['SRC_A'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
lambda _task: {
|
||||
'status': 'ready',
|
||||
'candidate_set_id': 9,
|
||||
'lines': [{'part_number': 'P1', '__source_code': 'SRC_A', '__inventory_file_no': 'INV-READY-001'}],
|
||||
'missing_source_codes': [],
|
||||
'loaded_source_codes': ['SRC_A'],
|
||||
'evidence': [{
|
||||
'source_code': 'SRC_A',
|
||||
'status': 'loaded',
|
||||
'inventory_file_no': 'INV-READY-001',
|
||||
'line_count': 1,
|
||||
'required': True,
|
||||
}],
|
||||
'required_source_codes': ['SRC_A'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ShippingInventoryFile,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
|
||||
def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None):
|
||||
call_order.append(f'link:{reason}')
|
||||
assert actual_task is task
|
||||
assert inv_file is snapshot
|
||||
assert reason == 'stp_candidate_prep'
|
||||
return SimpleNamespace(id=1)
|
||||
|
||||
def _fake_loaded(actual_task, lines, **kwargs):
|
||||
call_order.append('loaded')
|
||||
assert actual_task is task
|
||||
assert lines
|
||||
assert kwargs.get('persist_lines') is False
|
||||
return {'status': 'ok', 'message': 'linked-and-loaded'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
_fake_link,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
|
||||
_fake_loaded,
|
||||
)
|
||||
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert call_order == ['link:stp_candidate_prep', 'loaded']
|
||||
|
||||
|
||||
def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
|
||||
"""[断言] ready 快照无法绑定 OT 时返回 needs_human,不得抛未绑定 ValueError。"""
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='OT-STP-LINK-FAIL',
|
||||
id=702,
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=10,
|
||||
)
|
||||
snapshot = SimpleNamespace(inventory_file_no='INV-MISMATCH', source_code='SRC_A', warehouse_id='WH1')
|
||||
|
||||
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
|
||||
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(inventory_workflow, 'apply_task_transition', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['SRC_A'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
lambda _task: {
|
||||
'status': 'ready',
|
||||
'candidate_set_id': 10,
|
||||
'lines': [{'part_number': 'P1', '__inventory_file_no': 'INV-MISMATCH'}],
|
||||
'missing_source_codes': [],
|
||||
'loaded_source_codes': ['SRC_A'],
|
||||
'evidence': [{
|
||||
'source_code': 'SRC_A',
|
||||
'status': 'loaded',
|
||||
'inventory_file_no': 'INV-MISMATCH',
|
||||
'required': True,
|
||||
}],
|
||||
'required_source_codes': ['SRC_A'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ShippingInventoryFile,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
lambda *_a, **_k: None,
|
||||
)
|
||||
|
||||
def _boom(*_a, **_k):
|
||||
raise AssertionError('inventory_loaded_response must not run when link failed')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
|
||||
_boom,
|
||||
)
|
||||
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _boom)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['data']['blocking_reason']['code'] == 'inventory_file_missing'
|
||||
@@ -340,7 +340,9 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
assert data["todo_category"] == "in_progress"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
assert data["ui_state"]["checkpoint"]["code"] == "order_freeze"
|
||||
# 无 Gate 且无 review_status:薄回退不投影 order_freeze
|
||||
assert data["ui_state"]["position"] is None
|
||||
assert data["ui_state"]["user_mode"] == "auto_continue"
|
||||
assert data["artifact_summary"] is None
|
||||
|
||||
no_viewer = serialize_task_summary(task)
|
||||
@@ -575,11 +577,85 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
|
||||
|
||||
item = result['items'][0]
|
||||
assert item['business_no'] == 'WYC26082501'
|
||||
# 权威事实:人工确认成功 → Attempt.status=succeeded,但 Notice 面必须投影为 uploaded。
|
||||
assert item['upload_status'] == 'uploaded'
|
||||
# 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。
|
||||
assert item['upload_mode'] == 'manual'
|
||||
assert item['upload_attempt'] == 1
|
||||
|
||||
|
||||
def test_freight_notice_groups_available_actions_use_order_task_execution(app):
|
||||
"""货代上传单条菜单必须经 Notice.order_task_id 读 OT Execution,禁止用 Notice.id 查 Gate。
|
||||
|
||||
回归点:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id;
|
||||
Artifact.task_id 才是 Notice 主键。若误用 Notice.id,聚合只会留下 download_excel,
|
||||
行内 RPA/确认上传按钮全部消失。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
# 两张表在空库上都会从 1 起号;只给 OT 表垫一条废数据,强制 Notice.id ≠ OT.id,
|
||||
# 否则「误用 Notice.id 查 Execution」在单测里会碰巧命中。
|
||||
db.session.add(ShippingOrderTask(
|
||||
task_no='OT-GROUP-ACTIONS-PAD', user_id=11, source_type='direct_pdf',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-GROUP-ACTIONS-1', user_id=11, source_type='direct_pdf',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-GROUP-ACTIONS-1',
|
||||
business_no='WYC26090601',
|
||||
source_type='manual',
|
||||
user_id=11,
|
||||
order_task_id=order_task.id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
# Notice.id 与 OT.id 必须不同,否则会掩盖「误用 Notice.id 查 Execution」的回归。
|
||||
assert int(notice.id) != int(order_task.id)
|
||||
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='EXE-GROUP-ACTIONS-1',
|
||||
task_id=int(order_task.id),
|
||||
status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='mark_manual_uploaded',
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='manual_upload_handoff',
|
||||
sequence_no=20,
|
||||
status='blocked_manual',
|
||||
evaluation_version=1,
|
||||
blocking_reason_code='manual_upload_pending',
|
||||
next_action_code='mark_manual_uploaded',
|
||||
))
|
||||
order_task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
original_header_reader = query_service.current_header_field_values_or_empty
|
||||
query_service.current_header_field_values_or_empty = lambda _task: {
|
||||
'customer_po_number': 'PO-ACTIONS',
|
||||
}
|
||||
try:
|
||||
result = list_freight_notice_groups_for_task(notice, user_id=11)
|
||||
finally:
|
||||
query_service.current_header_field_values_or_empty = original_header_reader
|
||||
|
||||
actions = set(result['items'][0]['available_actions'] or [])
|
||||
assert 'mark_manual_uploaded' in actions
|
||||
assert 'retry_freight_upload_rpa' in actions
|
||||
|
||||
|
||||
def test_list_my_todos_and_count_buckets(app):
|
||||
"""待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。"""
|
||||
with app.app_context():
|
||||
@@ -1094,8 +1170,10 @@ def test_todo_category_sql_matches_formal_notice_facts(app):
|
||||
|
||||
|
||||
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
"""工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。"""
|
||||
"""工作台 view=workbench 跳过 DETAIL 重投影,保留 ui_state/产物/行摘要,全量视图不受影响。"""
|
||||
with app.app_context():
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import serialize_task_detail
|
||||
|
||||
@@ -1106,11 +1184,16 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
db.session.commit()
|
||||
|
||||
full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True)
|
||||
wb = serialize_task_detail(
|
||||
task, viewer_user_id=11, include_stage_context=True, view="workbench",
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.query_service.serialize_task',
|
||||
) as serialize_task_mock:
|
||||
wb = serialize_task_detail(
|
||||
task, viewer_user_id=11, include_stage_context=True, view="workbench",
|
||||
)
|
||||
|
||||
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
|
||||
# workbench 不得进入 SUMMARY/DETAIL 重投影(算之前就轻)。
|
||||
serialize_task_mock.assert_not_called()
|
||||
# full 保留编辑器重字段;workbench 身份壳不含它们。
|
||||
for key in (
|
||||
"lines", "order_header", "order_header_fields", "order_line_fields",
|
||||
):
|
||||
@@ -1122,3 +1205,5 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
assert wb["artifact_summary"] is None
|
||||
assert "notice_line_summary" in wb
|
||||
assert "export_artifacts" not in wb
|
||||
assert wb["task_no"] == "OT-WORKBENCH-VIEW"
|
||||
assert wb["order_task_no"] == "OT-WORKBENCH-VIEW"
|
||||
@@ -1,45 +1,45 @@
|
||||
"""
|
||||
tests/test_shipping_notice_state_machine.py
|
||||
|
||||
用途:校验发货通知 checkpoint 内部流程映射与 STP checkpoint_kind。
|
||||
依赖:pytest、state_machine、constants、ShippingNotice。
|
||||
逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。
|
||||
用途:校验发货通知位置→用户模式查找表与 Gate/review 薄回退。
|
||||
依赖:pytest、state_machine、constants、ShippingOrderTask。
|
||||
逻辑:validate_registry 无错误;关键位置 user_mode 正确;resolve_task_ui_state
|
||||
无 Gate 时仅凭 review_status 回退。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_READY_EXPORT,
|
||||
CP_UPLOADED,
|
||||
POSITION_EXPORT_READY,
|
||||
POSITION_PARSE_REVIEW,
|
||||
POSITION_UPLOADED,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_REJECTED,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
checkpoint_kind_for,
|
||||
UserMode,
|
||||
resolve_task_ui_state,
|
||||
resolve_task_ui_state_from_fields,
|
||||
user_mode_for_position,
|
||||
validate_registry,
|
||||
)
|
||||
|
||||
|
||||
def test_validate_registry_has_no_errors() -> None:
|
||||
"""checkpoint 仅维护内部流程分类。"""
|
||||
"""位置→用户模式查找表非空且自洽。"""
|
||||
assert validate_registry() == []
|
||||
|
||||
|
||||
def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
"""STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。"""
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN
|
||||
assert checkpoint_kind_for(CP_UPLOADED) == CheckpointKind.COMPLETE
|
||||
def test_user_modes_for_stp_stop_points() -> None:
|
||||
"""STP 关键位置 user_mode:导出就绪待人工 / 解析复核 / 已上传终态。"""
|
||||
assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD
|
||||
assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN
|
||||
assert user_mode_for_position(POSITION_UPLOADED) == UserMode.COMPLETE
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
"""pending_review + parse_review 应映射为 must_human / parse_review。"""
|
||||
"""无 Gate 时 review_status=parse_review 应映射为 must_human / parse_review。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-SM-PARSE",
|
||||
@@ -47,94 +47,41 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=None,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
has_dynamic_order_lines=False,
|
||||
)
|
||||
assert ui.checkpoint == CP_PARSE_REVIEW
|
||||
assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.position == POSITION_PARSE_REVIEW
|
||||
assert ui.user_mode == UserMode.MUST_HUMAN
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
"""matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。"""
|
||||
def test_resolve_task_ui_state_rejected(app) -> None:
|
||||
"""无 Gate 时 review_status=rejected → complete / rejected。"""
|
||||
with app.app_context():
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=1,
|
||||
match_status=None,
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
has_dynamic_order_lines=False,
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-SM-REJECT",
|
||||
user_id=1,
|
||||
review_status=RS_REJECTED,
|
||||
)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert not hasattr(ui, 'human_options')
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.position == 'rejected'
|
||||
assert ui.user_mode == UserMode.COMPLETE
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app, monkeypatch) -> None:
|
||||
"""upload_status=uploaded 应为 complete。"""
|
||||
def test_resolve_without_review_status_is_thin(app) -> None:
|
||||
"""无 Gate 且无 review_status 时不从领域标量投影位置(薄回退)。"""
|
||||
with app.app_context():
|
||||
task = SimpleNamespace(upload_status="uploaded", lifecycle_status="active")
|
||||
# [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
lambda _task: True,
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=1,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
has_dynamic_order_lines=False,
|
||||
upload_req_task=task,
|
||||
)
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
task = ShippingOrderTask(task_no="OT-SM-THIN", user_id=1)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.position is None
|
||||
assert ui.user_mode == UserMode.AUTO_CONTINUE
|
||||
|
||||
|
||||
def test_resolve_with_mocked_simple_namespace_attributes(monkeypatch) -> None:
|
||||
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
|
||||
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
"""无 DB 会话时简易命名空间:无 review_status → 薄回退 None/auto。"""
|
||||
task = SimpleNamespace(
|
||||
upload_status="uploaded",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=None,
|
||||
inventory_lines_json=None,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
current_order_extraction_id=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
# [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
lambda _task: True,
|
||||
order_task_id=None,
|
||||
id=None,
|
||||
)
|
||||
ui = resolve_task_ui_state(task) # type: ignore[arg-type]
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
|
||||
|
||||
def test_order_task_inventory_checkpoint_uses_structured_facts(monkeypatch) -> None:
|
||||
"""OT 库存 JSON 为空时,状态机仍须按 Link/File/Match 事实进入导出准备。"""
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import state_machine
|
||||
|
||||
task = ShippingOrderTask(task_no='OT-SM-STRUCTURED', user_id=1, stage='inventory_matching')
|
||||
monkeypatch.setattr(state_machine, '_order_task_inventory_facts', lambda _task: {
|
||||
'inventory_ready': True,
|
||||
'match_complete': True,
|
||||
'match_sufficient': True,
|
||||
'has_shortage': False,
|
||||
})
|
||||
|
||||
assert state_machine.resolve_task_ui_state(task).checkpoint == CP_READY_EXPORT
|
||||
assert ui.user_mode == UserMode.AUTO_CONTINUE
|
||||
assert ui.position is None
|
||||
@@ -24,15 +24,15 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
POSITION_EXPORT_READY,
|
||||
POSITION_PARSE_REVIEW,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match, upload_to_freight
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for
|
||||
from app.services.shipping_notice.state_machine import UserMode, user_mode_for_position
|
||||
|
||||
|
||||
def _seed_export_artifact_view(monkeypatch) -> None:
|
||||
@@ -61,10 +61,10 @@ def _seed_export_artifact_view(monkeypatch) -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
|
||||
def test_stp_user_mode_matrix_covers_nine_scenario_stops() -> None:
|
||||
"""九条场景依赖的停点 kind 不得漂移。"""
|
||||
assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN
|
||||
assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None:
|
||||
@@ -86,7 +86,7 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app,
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "source": "system"})
|
||||
assert result["status"] == "ok"
|
||||
assert result.get("checkpoint") == CP_EXPORT_READY
|
||||
assert result.get("position") == POSITION_EXPORT_READY
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
assert result.get("stop_agent_turn") is True
|
||||
assert "登记凭据" in str(result.get("message") or "")
|
||||
@@ -118,86 +118,120 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "source": "system"})
|
||||
assert result["status"] == "needs_human"
|
||||
assert result.get("checkpoint") == CP_PARSE_REVIEW
|
||||
assert result.get("position") == POSITION_PARSE_REVIEW
|
||||
|
||||
|
||||
def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch) -> None:
|
||||
"""场景:AUTO_UPLOAD=true 时匹配后串联须调用 upload_to_freight(mode=auto)。"""
|
||||
def test_try_auto_chain_gate_path_skips_generate_and_upload(app, monkeypatch) -> None:
|
||||
"""Gate Attempt 路径:匹配成功后不得内嵌 generate_excel / upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-RPA-ON",
|
||||
source_type="manual",
|
||||
)
|
||||
task = ShippingNotice(task_no='SN-STP-CHAIN-GATE', source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
upload_calls: list[dict] = []
|
||||
|
||||
def _fake_upload(payload):
|
||||
upload_calls.append(dict(payload or {}))
|
||||
return {"status": "running", "message": "rpa-triggered"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.upload_to_freight",
|
||||
_fake_upload,
|
||||
'app.services.shipping_notice.fulfillment_workflow._current_export_artifact',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
generate_calls: list[dict] = []
|
||||
upload_calls: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.upload_to_freight',
|
||||
lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'},
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{"status": "ok", "message": "matched"},
|
||||
payload={"task_id": task.task_no},
|
||||
)
|
||||
# 关键断言:自动链接入货代上传 RPA。
|
||||
assert len(upload_calls) == 1
|
||||
assert upload_calls[0].get("mode") == "auto"
|
||||
assert result["status"] == "running"
|
||||
|
||||
|
||||
def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch) -> None:
|
||||
"""场景:AUTO_UPLOAD=false 时停在人工上传,不调用 upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-NO-RPA",
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
upload_calls: list[dict] = []
|
||||
|
||||
def _fake_upload(payload):
|
||||
upload_calls.append(dict(payload or {}))
|
||||
return {"status": "running", "message": "should-not-run"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.upload_to_freight",
|
||||
_fake_upload,
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{"status": "ok", "message": "matched"},
|
||||
payload={"task_id": task.task_no},
|
||||
{'status': 'ok', 'message': 'matched'},
|
||||
payload={
|
||||
'task_id': task.task_no,
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
'source': 'process_gate',
|
||||
},
|
||||
)
|
||||
assert result['status'] == 'ok'
|
||||
assert generate_calls == []
|
||||
assert upload_calls == []
|
||||
assert result["status"] == "ok"
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
|
||||
|
||||
def test_try_auto_chain_legacy_path_submits_artifact_auto_progress(app, monkeypatch) -> None:
|
||||
"""非 Gate 遗留路径:只提交 artifact_generation auto_progress,禁止直跑 generate。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
|
||||
|
||||
task = ShippingNotice(task_no='SN-STP-CHAIN-LEGACY', source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
progress_calls: list[dict] = []
|
||||
generate_calls: list[dict] = []
|
||||
|
||||
def _fake_progress(task_no, **kwargs):
|
||||
progress_calls.append({'task_no': task_no, **kwargs})
|
||||
return {'status': 'running', 'message': 'queued-artifact'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
_fake_progress,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{'status': 'ok', 'message': 'matched'},
|
||||
payload={'task_id': task.task_no, 'source': 'legacy_tool'},
|
||||
)
|
||||
assert generate_calls == []
|
||||
assert len(progress_calls) == 1
|
||||
assert progress_calls[0]['resume_gate_code'] == 'artifact_generation'
|
||||
assert result['status'] == 'running'
|
||||
|
||||
|
||||
def test_try_auto_chain_skips_when_auto_generate_disabled(app, monkeypatch) -> None:
|
||||
"""AUTO_GENERATE_EXCEL=false 时遗留路径也不提交下游 chain。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = False
|
||||
|
||||
task = ShippingNotice(task_no='SN-STP-NO-CHAIN', source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
progress_calls: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
lambda *args, **kwargs: progress_calls.append(kwargs) or {'status': 'running'},
|
||||
)
|
||||
|
||||
result = try_auto_chain_after_match(
|
||||
task,
|
||||
{'status': 'ok', 'message': 'matched'},
|
||||
payload={'task_id': task.task_no},
|
||||
)
|
||||
assert progress_calls == []
|
||||
assert result['status'] == 'ok'
|
||||
assert result.get('message') == 'matched'
|
||||
|
||||
|
||||
def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch) -> None:
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
tests/test_shipping_notice_ui_state.py
|
||||
|
||||
用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。
|
||||
依赖:pytest、ShippingNotice、ui_state、state_machine constants。
|
||||
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
|
||||
依赖:pytest、ShippingNotice、ui_state、state_machine constants、库存源/发货模板模型。
|
||||
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确;
|
||||
stage_context.preparation 短缺行投影 release_required_fields;
|
||||
preparation.source_options 下发已启用源供行级覆写下拉;
|
||||
行级 selected_source_code(Candidate)与 source_code(Match)分字段;
|
||||
Notice 详情经 order_task_id→OT 读取 Snapshot/Match。
|
||||
"""
|
||||
|
||||
from app import db
|
||||
@@ -14,9 +18,8 @@ from app.models import (
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_ORDER_FREEZE,
|
||||
CP_PARSE_REVIEW,
|
||||
POSITION_EXPORT_READY,
|
||||
POSITION_PARSE_REVIEW,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
@@ -29,7 +32,7 @@ _REQUIRED_SUMMARY_KEYS = {
|
||||
"message",
|
||||
"issues",
|
||||
"stage",
|
||||
"checkpoint_kind",
|
||||
"user_mode",
|
||||
"current_todo",
|
||||
"pause_reason",
|
||||
"next_auto_step",
|
||||
@@ -145,8 +148,9 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"]["code"] == CP_ORDER_FREEZE
|
||||
assert state["checkpoint_kind"] == "auto_continue"
|
||||
# 无 Gate 时按领域标量回退:parse_review 不得再被 OT 空 stage 盖成 order_freeze。
|
||||
assert state["position"] == POSITION_PARSE_REVIEW
|
||||
assert state["user_mode"] == "must_human"
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
@@ -164,7 +168,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
|
||||
|
||||
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||||
"""旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。"""
|
||||
"""无正式 Gate 时位置不能再推导五阶段或任何可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-STAGE-ACTIONS", user_id=1,
|
||||
@@ -181,7 +185,7 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||||
|
||||
|
||||
def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None:
|
||||
"""正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。"""
|
||||
"""正式工作台入口必须来自 Gate,不能按旧位置码生成。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1,
|
||||
@@ -305,29 +309,65 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"]["entry_surface"] == "review_workbench"
|
||||
|
||||
|
||||
def test_build_task_ui_state_queries_process_gate_once(app, monkeypatch) -> None:
|
||||
"""build_task_ui_state 同一次构建只查 Gate 摘要一次,禁止再经 resolve 二次查库。"""
|
||||
with app.app_context():
|
||||
calls = {'n': 0}
|
||||
|
||||
def _fake_gate(_task):
|
||||
calls['n'] += 1
|
||||
return {
|
||||
'current_gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked_manual',
|
||||
},
|
||||
'primary_action': None,
|
||||
'action_presentation': [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
_fake_gate,
|
||||
)
|
||||
task = ShippingOrderTask(task_no="OT-UI-GATE-ONCE", user_id=1, source_type="direct_pdf")
|
||||
state = build_task_ui_state(task)
|
||||
assert calls['n'] == 1
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
|
||||
"""Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。"""
|
||||
"""Gate artifact_generation 投影 export_ready 时进入工作台;未验证 Artifact 不得授权下载。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-EXPORT",
|
||||
source_type="manual",
|
||||
)
|
||||
# Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
|
||||
from types import SimpleNamespace
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'),
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda _task: {
|
||||
'current_gate_code': 'artifact_generation',
|
||||
'status': 'waiting_human',
|
||||
'lifecycle_stage': 'freight_upload',
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'artifact_generation',
|
||||
'status': 'blocked_manual',
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: None,
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint"]["code"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["position"] == POSITION_EXPORT_READY
|
||||
# Gate freight_upload + waiting_human → wait_manual_upload
|
||||
assert state["user_mode"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
|
||||
assert "货代平台上传" in str(state["summary"].get("pause_reason") or "")
|
||||
@@ -336,7 +376,7 @@ def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
|
||||
# 关键断言:没有可验证 Artifact 时不得生成下载按钮。
|
||||
assert "download_excel" not in button_ids
|
||||
assert "mark_manual_uploaded" not in button_ids
|
||||
|
||||
@@ -498,6 +538,7 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
assert line["status"] == "inventory_matched"
|
||||
assert line["source_ambiguous"] is False
|
||||
assert line["source_candidates"] == []
|
||||
assert line["can_fulfill_complete_line"] is True
|
||||
# §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮;
|
||||
# line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。
|
||||
assert line["inventory_file_no"] == "INV-1"
|
||||
@@ -571,8 +612,15 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None:
|
||||
"""行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。"""
|
||||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
|
||||
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [
|
||||
{'source_code': 'src_a', 'display_name': 'Source A'},
|
||||
{'source_code': 'SRC_B', 'display_name': ''},
|
||||
],
|
||||
)
|
||||
with app.app_context():
|
||||
user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com')
|
||||
db.session.add(user)
|
||||
@@ -602,8 +650,97 @@ def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> No
|
||||
assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B']
|
||||
assert preparation['lines'][0]['source_code'] is None
|
||||
assert preparation['source_locked'] is False
|
||||
# 关键断言:行级覆写下拉依赖 preparation.source_options;编码统一大写。
|
||||
assert preparation['source_options'] == [
|
||||
{'source_code': 'SRC_A', 'display_name': 'Source A'},
|
||||
{'source_code': 'SRC_B', 'display_name': 'SRC_B'},
|
||||
]
|
||||
|
||||
|
||||
def test_stage_context_projects_selected_source_without_backfilling_match_source(app) -> None:
|
||||
"""CandidateSet 单源只填 selected_source_code,禁止回填 Match 的 source_code。"""
|
||||
with app.app_context():
|
||||
task, line = _frozen_task_with_line(
|
||||
task_no='OT-UI-SELECTED-SOURCE',
|
||||
reservation_id='RSV-SEL',
|
||||
part_number='PN-SEL',
|
||||
qty='2',
|
||||
)
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='b' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||||
row = preparation['lines'][0]
|
||||
# 关键断言:取数目标与匹配结论分字段;未匹配时 source_code 必须为空。
|
||||
assert row['snapshot_line_id'] == line.id
|
||||
assert row['selected_source_code'] == 'DSV360_AWSSG'
|
||||
assert row['source_code'] is None
|
||||
assert row['source_ambiguous'] is False
|
||||
|
||||
|
||||
def test_stage_context_notice_resolves_ot_match_and_selected_source(app) -> None:
|
||||
"""Notice 详情入口须经 order_task_id→OT 读 Snapshot/Match/Candidate,禁止用 Notice.id。"""
|
||||
with app.app_context():
|
||||
# 垫偏 OT.id,避免空库 Notice.id==OT.id 碰巧绿。
|
||||
for index in range(3):
|
||||
db.session.add(ShippingOrderTask(
|
||||
task_no=f'OT-UI-SPACER-{index}', user_id=1, source_type='direct_pdf',
|
||||
))
|
||||
db.session.flush()
|
||||
task, line = _frozen_task_with_line(
|
||||
task_no='OT-UI-NOTICE-RESOLVE',
|
||||
reservation_id='RSV-NOTICE',
|
||||
part_number='PN-NOTICE',
|
||||
qty='3',
|
||||
)
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
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='3', available_qty='3',
|
||||
matched_qty='3', shortage_qty='0', reservation_id='RSV-NOTICE', part_number='PN-NOTICE',
|
||||
inventory_source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True,
|
||||
))
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-UI-NOTICE-RESOLVE',
|
||||
source_type='manual',
|
||||
user_id=1,
|
||||
order_task_id=task.id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
|
||||
assert int(notice.id) != int(task.id)
|
||||
preparation = build_task_ui_state(notice, include_stage_context=True)['stage_context']['preparation']
|
||||
row = preparation['lines'][0]
|
||||
# 关键断言:SN 入口仍投影 OT 上的匹配正式源与取数目标。
|
||||
assert preparation['frozen_order']['task_no'] == task.task_no
|
||||
assert preparation['frozen_order']['snapshot_id'] == task.order_snapshot_id
|
||||
assert row['source_code'] == 'DSV360_AWSSG'
|
||||
assert row['selected_source_code'] == 'DSV360_AWSSG'
|
||||
assert preparation['has_match_result'] is True
|
||||
|
||||
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
|
||||
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
|
||||
with app.app_context():
|
||||
@@ -913,6 +1050,34 @@ def test_preparation_editable_present_for_live_formal_task(monkeypatch):
|
||||
assert _preparation_editable(NoisyStatusTask()) is False
|
||||
|
||||
|
||||
def test_stage_context_line_actions_without_match_rows(app) -> None:
|
||||
"""正式 OT 无匹配行时,preparation.lines 仍须下发明细库存重试动作。
|
||||
|
||||
断言:has_formal_ot 不得用 current_match_rows 判定;无 match 时 fact 兜底 preparing,
|
||||
inventory_allowed_actions 含 retry_inventory_preparation。
|
||||
"""
|
||||
with app.app_context():
|
||||
user = User(username='ui-no-match-actions', email='ui-no-match-actions@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task, _line = _frozen_task_with_line(
|
||||
task_no='OT-UI-NO-MATCH-ACTIONS',
|
||||
user_id=user.id,
|
||||
reservation_id='RSV-NM-1',
|
||||
part_number='PN-NM-1',
|
||||
qty='4',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
assert preparation["has_match_result"] is False
|
||||
assert len(preparation["lines"]) == 1
|
||||
line = preparation["lines"][0]
|
||||
# 关键断言:无 Match 行时明细仍可点「重试库存准备」,不得因 has_formal_ot=False 空动作。
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
assert "close_unfulfillable" in line["line_allowed_actions"]
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None:
|
||||
"""[断言] preparation 携带任务级 editable(active=True / voided=False);
|
||||
行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。"""
|
||||
@@ -936,3 +1101,110 @@ def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app
|
||||
assert preparation["lines"][0]["customer_po_line_no"] is None
|
||||
# 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。
|
||||
assert preparation["lines"][1]["customer_po_line_no"] is None
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_shortage_release_template_fields(app) -> None:
|
||||
"""短缺行必须按库存源发货模板投影人工补录字段,禁止 fail-closed 空列表。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
location = ShippingInventoryField.query.filter_by(field_code='location').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
|
||||
template.definition_json = {
|
||||
'mappings': [
|
||||
{
|
||||
'row_mode': 'line',
|
||||
'source_kind': 'inventory_field',
|
||||
'source_key': str(location.id),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
user = User(username='ui-release-fields', email='ui-release-fields@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema(schema_code='UI_RELEASE_FIELDS', display_name='UI Release Fields')
|
||||
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-UI-RELEASE-FIELDS',
|
||||
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
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
reservation_id='RSV-RELEASE',
|
||||
part_number='PN-RELEASE',
|
||||
qty='10',
|
||||
field_values_json={},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
# 无库存快照时模板库存字段全部人工补录;源码必须能解析到 published 发货模板。
|
||||
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='10',
|
||||
available_qty='0',
|
||||
matched_qty='0',
|
||||
shortage_qty='10',
|
||||
reservation_id='RSV-RELEASE',
|
||||
part_number='PN-RELEASE',
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
inventory_snapshot_id=None,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||||
line = preparation['lines'][0]
|
||||
|
||||
assert line['is_shortage'] is True
|
||||
assert line['release_field_resolution_error'] is None
|
||||
assert line['release_required_fields'] == [
|
||||
{'field_id': str(location.id), 'display_name': '库位'},
|
||||
]
|
||||
assert line['release_template_fields'] == [
|
||||
{
|
||||
'field_id': str(location.id),
|
||||
'display_name': '库位',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
@@ -302,8 +302,8 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app):
|
||||
]
|
||||
|
||||
|
||||
def test_review_queue_uses_formal_task_lifecycle_stage(app):
|
||||
"""Case 已绑定正式任务后,队列阶段必须随正式 Gate/领域事实推进。"""
|
||||
def test_review_queue_uses_formal_task_lifecycle_stage(app, monkeypatch):
|
||||
"""Case 已绑定正式任务后,队列阶段必须随正式 OT.stage 推进,且不得走全量 ui_state。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-FORMAL-STAGE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
@@ -332,6 +332,13 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app):
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
def _forbid_full_ui_state(*_args, **_kwargs):
|
||||
raise AssertionError('queue summary must not call build_task_ui_state')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.build_task_ui_state',
|
||||
_forbid_full_ui_state,
|
||||
)
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
assert item['po_number'] == 'PO-QUEUE-002'
|
||||
@@ -341,6 +348,65 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app):
|
||||
]
|
||||
|
||||
|
||||
def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(app, monkeypatch):
|
||||
"""旧 OT.stage=step* 不在五阶段映射表时,队列须用批量 Gate 兜底,不能塌成 intake_parse。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-LEGACY-STAGE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-LEGACY-STAGE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-legacy-stage',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-LEGACY',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-LEGACY-STAGE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-LEGACY',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='active',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.build_task_ui_state',
|
||||
lambda *_a, **_k: (_ for _ in ()).throw(AssertionError('no full ui_state')),
|
||||
)
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
assert item['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert item['lifecycle_entries'][2]['state'] == 'current'
|
||||
|
||||
|
||||
|
||||
def test_review_case_does_not_expose_replacement_upload(app):
|
||||
"""复核 Case 仅允许原 PDF 重识别,不暴露上传替代文件动作。"""
|
||||
with app.app_context():
|
||||
@@ -726,7 +792,7 @@ def test_review_case_initialization_closes_legacy_extraction_gates(app):
|
||||
# 未确认 Case 的当前 Gate 是建单前复核(order_review_build),不是正式 Gate。
|
||||
assert bundle['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert bundle['blocking_reason']['code'] is None
|
||||
assert bundle['user_status'] == 'idle'
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app):
|
||||
|
||||
@@ -1622,6 +1622,103 @@ def test_inventory_preparation_retry_rejects_legacy_task_without_snapshot(monkey
|
||||
assert result['blocking_reason_code'] == 'inventory_source_routing_required'
|
||||
|
||||
|
||||
def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
|
||||
"""库存准备执行器按已有动作码映射 ensure_inventory mode,禁止人工入口一律 retry_rpa。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-MODE-MAP')
|
||||
captured: list[dict] = []
|
||||
line = SimpleNamespace(source_codes_json=['DBS'])
|
||||
candidate_set = SimpleNamespace(id=1)
|
||||
sources = [SimpleNamespace(source_code='DBS')]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [line],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: sources,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||||
lambda **_: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
# poll 路径会查失败 Attempt;无失败行时继续 ensure_inventory。
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingInventoryPreparationAttempt.query',
|
||||
SimpleNamespace(
|
||||
filter_by=lambda **_: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(
|
||||
order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
execution = SimpleNamespace(task_id=1, id=21, candidate_set_id=None)
|
||||
gate = SimpleNamespace(gate_code='inventory_preparation')
|
||||
|
||||
captured.clear()
|
||||
_handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate,
|
||||
payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5},
|
||||
)
|
||||
# 显式强制 RPA 码 → mode=retry_rpa。
|
||||
assert captured[-1].get('mode') == 'retry_rpa'
|
||||
|
||||
captured.clear()
|
||||
_handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate,
|
||||
payload={'action_code': 'poll_inventory_preparation', 'actor_user_id': 5},
|
||||
)
|
||||
# 只读轮询:默认 auto,禁止自动再试。
|
||||
assert captured[-1].get('mode') in (None, 'auto')
|
||||
assert captured[-1].get('allow_auto_retry') is False
|
||||
|
||||
captured.clear()
|
||||
_handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate,
|
||||
payload={
|
||||
'action_code': 'retry_inventory_preparation',
|
||||
'trigger': 'gate_attempt_passed',
|
||||
'actor_user_id': 5,
|
||||
},
|
||||
)
|
||||
# 首次自动投递:不强制 retry_rpa,保留默认 auto(先复用快照)。
|
||||
assert captured[-1].get('mode') in (None, 'auto')
|
||||
|
||||
|
||||
def test_manual_business_block_is_a_successful_attempt(app):
|
||||
"""库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。"""
|
||||
from app import db
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_processing_projection.py
|
||||
|
||||
???????? processing ?????OT ??????PDF ???????
|
||||
???Flask/SQLite?create_order_extraction_run?project_conversation_processing?
|
||||
????? queued / frozen-failed / completed???? PDF ????????hash ?????
|
||||
processing OT PDF
|
||||
Flask/SQLite?create_order_extraction_run?project_conversation_processing?
|
||||
queued / frozen-failed / completed PDF hash
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,11 +29,11 @@ from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
def _ensure_run_order_task(*, run, intake, document) -> None:
|
||||
"""
|
||||
????????? Candidate + OT???? Run.user_task_no?
|
||||
Candidate + OT Run.user_task_no?
|
||||
|
||||
??????? test_shipping_conversation_processing_api ???
|
||||
Candidate ? Run ???? OT ????? order_task ??
|
||||
????? OT ???????
|
||||
test_shipping_conversation_processing_api
|
||||
Candidate ? Run OT order_task
|
||||
OT
|
||||
"""
|
||||
candidate = ShippingOrderCandidate.query.filter_by(
|
||||
order_extraction_run_id=int(run.id),
|
||||
@@ -63,7 +63,7 @@ def _ensure_run_order_task(*, run, intake, document) -> None:
|
||||
|
||||
|
||||
def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
|
||||
"""???? Run ?????????? OT ??????"""
|
||||
""" Run OT """
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A')
|
||||
run_processing, _ = create_order_extraction_run(
|
||||
@@ -135,10 +135,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
|
||||
completed_nos = {row['user_task_no'] for row in projection.get('completed') or []}
|
||||
assert run_processing.user_task_no in processing_nos
|
||||
assert run_failed.user_task_no in needs_nos
|
||||
# ???? completed ????????? completed ???
|
||||
# completed completed
|
||||
assert run_done.user_task_no in completed_nos
|
||||
|
||||
# ????????? OT ??????
|
||||
# OT
|
||||
all_nos = list(processing_nos | needs_nos | completed_nos)
|
||||
assert len(all_nos) == len(set(all_nos)) == 3
|
||||
|
||||
@@ -150,7 +150,7 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
|
||||
assert 'view_details' in (failed_task.get('available_actions') or [])
|
||||
primary = failed_task.get('primary_action')
|
||||
assert primary
|
||||
# ???cancel / view_details ???? CTA?BE-01??
|
||||
# cancel / view_details CTA?BE-01
|
||||
assert primary not in {'cancel_task', 'cancel_run', 'view_details'}
|
||||
|
||||
done_task = next(
|
||||
@@ -244,7 +244,7 @@ def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app):
|
||||
|
||||
|
||||
def test_completed_current_run_hidden_after_viewed(app):
|
||||
"""UI-04??? completed ?????????"""
|
||||
"""UI-04 completed """
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -273,14 +273,14 @@ def test_completed_current_run_hidden_after_viewed(app):
|
||||
)
|
||||
shown = after['processing'] + after['needs_action'] + list(after.get('completed') or [])
|
||||
assert all(row['user_task_no'] != run.user_task_no for row in shown)
|
||||
# ?????? completed ?? history?????????
|
||||
# completed history
|
||||
history_nos = {row['user_task_no'] for row in (after.get('history') or [])}
|
||||
assert run.user_task_no in history_nos
|
||||
assert after['summary']['history'] >= 1
|
||||
|
||||
|
||||
def _set_run_documents(run, documents: list[dict]) -> None:
|
||||
"""?? Run ?? documents????????PDF ?????"""
|
||||
""" Run documentsPDF """
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
intakes = list(snapshot.get('intakes') or [])
|
||||
if not intakes:
|
||||
@@ -293,7 +293,7 @@ def _set_run_documents(run, documents: list[dict]) -> None:
|
||||
|
||||
|
||||
def test_single_pdf_task_title_is_none_for_frontend_unified_label(app):
|
||||
"""BE-05?? PDF ?? title ?? None?????? document_names / objects?"""
|
||||
"""BE-05 PDF title None document_names / objects?"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -321,7 +321,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app):
|
||||
row for row in projection['processing'] + projection['needs_action']
|
||||
if row['user_task_no'] == run.user_task_no
|
||||
)
|
||||
# ???????????????????????????? title?
|
||||
# title?
|
||||
assert task['title'] is None
|
||||
assert task['file_count'] == 1
|
||||
assert task['display_kind'] == 'single_document_task'
|
||||
@@ -332,7 +332,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app):
|
||||
|
||||
|
||||
def test_multi_pdf_task_does_not_use_first_filename_as_title(app):
|
||||
"""? PDF ???title ???file_count=2?objects ????? PDF?"""
|
||||
"""? PDF title file_count=2?objects PDF?"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -485,7 +485,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
|
||||
|
||||
|
||||
def test_same_filename_different_hash_counts_as_two_pdfs(app):
|
||||
"""???? hash?file_count=2???????????"""
|
||||
""" hash?file_count=2"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -525,7 +525,7 @@ def test_same_filename_different_hash_counts_as_two_pdfs(app):
|
||||
|
||||
|
||||
def test_same_hash_different_document_id_counts_as_one_pdf(app):
|
||||
"""? hash ?? document_id?????file_count=1?"""
|
||||
"""? hash document_idfile_count=1?"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -564,7 +564,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app):
|
||||
)
|
||||
assert task['file_count'] == 1
|
||||
assert task['display_kind'] == 'single_document_task'
|
||||
# BE-05: title ?? None?? hash ???????????
|
||||
# BE-05: title None hash
|
||||
assert task['title'] is None
|
||||
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
|
||||
assert len(doc_objects) == 1
|
||||
@@ -572,7 +572,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app):
|
||||
|
||||
|
||||
def test_sparse_snapshot_enriched_by_extraction_units(app):
|
||||
"""??? 1 PDF ? Unit ?? 2 ?????? multi + file_count=2?"""
|
||||
""" 1 PDF ? Unit 2 multi + file_count=2?"""
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingOrderDocument,
|
||||
@@ -619,7 +619,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app):
|
||||
keep_input_open=True,
|
||||
)
|
||||
_ensure_run_order_task(run=run, intake=intake, document=document)
|
||||
# ???? 1 ???????????????????????
|
||||
# 1
|
||||
_set_run_documents(run, [{
|
||||
'document_id': int(document.id),
|
||||
'root_document_id': int(document.id),
|
||||
@@ -660,7 +660,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app):
|
||||
|
||||
@pytest.mark.skip(reason='workflow ledger removed')
|
||||
def test_sparse_snapshot_enriched_by_workflow_items(app):
|
||||
"""??? 1 PDF ?? Run ?? 2 ? WorkflowItem ????? multi?"""
|
||||
""" 1 PDF Run 2 ? WorkflowItem multi?"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W')
|
||||
from app.models import FileAsset, ShippingOrderDocument
|
||||
|
||||
@@ -508,6 +508,77 @@ def test_order_task_current_gate_ignores_empty_review_case(app) -> None:
|
||||
assert item['current_gate'] is None
|
||||
|
||||
|
||||
def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None:
|
||||
"""
|
||||
无正式 Notice 时仍须读 OT 活跃 Execution,禁止 waiting_review 误合成 open_order_review。
|
||||
|
||||
关键断言:库存满足性人工阻断(inventory_sufficiency)发生在 Notice 创建前;
|
||||
work-item 右卡若回落 order_freeze_readiness,会永久显示「订单复核」而非缺口恢复。
|
||||
"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
get_shipping_processing_work_item,
|
||||
)
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='OT-EXEC-NO-NOTICE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-EXEC-NO-NOTICE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-OT-EXEC-NO-NOTICE',
|
||||
task_id=int(task.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
evaluation_version=1,
|
||||
lock_version=1,
|
||||
blocking_reason_code='inventory_shortage_review_required',
|
||||
next_action_code='open_shortage_review',
|
||||
))
|
||||
run.user_task_no = task.task_no
|
||||
db.session.commit()
|
||||
|
||||
item = get_shipping_processing_work_item(
|
||||
user_id=user.id,
|
||||
work_item_type='order_task',
|
||||
work_item_no=task.task_no,
|
||||
)
|
||||
|
||||
assert item['current_gate']['gate_code'] == 'inventory_sufficiency'
|
||||
assert item['current_gate']['next_action_code'] in {
|
||||
'open_shortage_review',
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_preparation',
|
||||
}
|
||||
assert item['current_gate']['next_action_code'] != 'open_order_review'
|
||||
assert item['ui_state']['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert item['ui_state']['status'] == 'waiting_human'
|
||||
primary = (item.get('ui_state') or {}).get('primary_action') or {}
|
||||
assert str(primary.get('code') or '') != 'open_order_review'
|
||||
|
||||
|
||||
def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None:
|
||||
"""历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。"""
|
||||
with app.app_context():
|
||||
@@ -1411,6 +1482,96 @@ def test_summary_lifecycle_authority_is_processing_stage_for_stale_completed_tas
|
||||
assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human'
|
||||
|
||||
|
||||
def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app) -> None:
|
||||
"""首屏摘要必须按 OT.id 批量加载 ProcessExecution,禁止误用 candidate_id。
|
||||
|
||||
回归:candidate.id ≠ OT.id 时,若用 tasks_by_candidate_id 的 key 去查
|
||||
ShippingProcessExecution.task_id,Gate 整批查空;叶子会退化成遗留 stage +
|
||||
open_order_review,批次中心同时失去五阶段入口与门禁主按钮。
|
||||
"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-OT-ID-NOT-CANDIDATE',
|
||||
)
|
||||
# [STEP 1] 垫高 Candidate 序号,强制 candidate.id ≠ OT.id(SQLite 默认同号会掩盖 bug)。
|
||||
for idx in range(3):
|
||||
db.session.add(ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-PAD-{idx}-{uuid.uuid4().hex[:8]}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key=f'summary-pad-{idx}-{uuid.uuid4().hex[:8]}',
|
||||
candidate_status='rejected',
|
||||
is_current_version=False,
|
||||
po_number=f'PO-PAD-{idx}',
|
||||
))
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-SUMMARY-OT-ID-{uuid.uuid4().hex[:8]}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key=f'summary-ot-id-{uuid.uuid4().hex[:8]}',
|
||||
candidate_status='accepted',
|
||||
is_current_version=True,
|
||||
po_number='PO-SUMMARY-OT-ID',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-SUMMARY-OT-ID',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_id=intake.id,
|
||||
candidate_id=candidate.id,
|
||||
status='waiting_review',
|
||||
stage='step3_inventory_prepare',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
assert int(candidate.id) != int(order_task.id)
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-SUMMARY-OT-ID',
|
||||
task_id=int(order_task.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_preparation',
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
order_task.active_process_execution_id = int(execution.id)
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_preparation',
|
||||
sequence_no=13,
|
||||
status='blocked_retryable',
|
||||
evaluation_version=1,
|
||||
lock_version=1,
|
||||
blocking_reason_code='inventory_rpa_export_failed',
|
||||
next_action_code='retry_inventory_preparation',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
leaf = next(
|
||||
child
|
||||
for rows in payload['conversation_processing']['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
# 关键断言:Gate 命中后五阶段与库存恢复主操作必须同时存在。
|
||||
assert leaf['current_gate']['gate_code'] == 'inventory_preparation'
|
||||
assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert len(leaf['ui_state']['lifecycle_entries']) == 5
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
assert leaf['ui_state']['primary_action']['code'] != 'open_order_review'
|
||||
|
||||
|
||||
def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None:
|
||||
"""接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。"""
|
||||
with app.app_context():
|
||||
@@ -1632,7 +1793,7 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None:
|
||||
leaf = leaves[document_id]
|
||||
# [BE-05] 未确认 Candidate Review Case 由后端 bundle 权威裁决为 idle(待用户处置),
|
||||
# 用户阶段固定在订单复核;建单前 Gate 由 order_review_build / mark_non_order 唯一给出。
|
||||
assert leaf['user_status'] == 'idle'
|
||||
assert leaf['user_status'] == 'waiting_human'
|
||||
assert leaf['user_stage'] == 'order_review'
|
||||
assert leaf['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert leaf['current_gate']['next_action_code'] == 'mark_non_order'
|
||||
@@ -2481,7 +2642,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
assert result[0]['user_status'] == 'waiting_human'
|
||||
assert result[0]['user_stage'] == 'order_review'
|
||||
assert leaf['case_no'] == case.case_no
|
||||
assert leaf['user_status'] == 'idle'
|
||||
assert leaf['user_status'] == 'waiting_human'
|
||||
assert leaf['user_stage'] == 'order_review'
|
||||
assert leaf['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert 'edit_draft' in leaf['available_actions']
|
||||
|
||||
@@ -417,13 +417,9 @@ def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario):
|
||||
gate_code=gate_code, status='blocked_manual',
|
||||
blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation',
|
||||
)
|
||||
# 让 notice 路径(_process_gate_user_summary_for_task 按 task.id=notice.id 查 execution)
|
||||
# 命中同一 execution:B 在生产中把 Notice 传给 build_task_ui_state。
|
||||
from app.models import ShippingProcessExecution
|
||||
execution = db.session.get(ShippingProcessExecution, execution_id)
|
||||
execution.task_id = int(notice.id)
|
||||
db.session.commit()
|
||||
|
||||
# 让 notice 路径经 order_task_id 命中同一 execution(B 在生产中把 Notice
|
||||
# 传给 build_task_ui_state;Execution.task_id 必须保持为 OT.id)。
|
||||
assert int(notice.order_task_id) == int(order_task.id)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
b = build_task_ui_state(notice)
|
||||
b_stage = str((b.get('stage') or {}).get('code') or '').strip()
|
||||
|
||||
@@ -160,6 +160,36 @@ def test_shortage_release_export_uses_audited_header_override_when_no_snapshot_c
|
||||
) == [{'6': 'ODM-001'}]
|
||||
|
||||
|
||||
def test_narrow_inventory_lines_keeps_only_reservation_and_part_hits():
|
||||
"""导出匹配前必须按本单 reservation+part 裁剪,不得把全量快照送进逐行匹配。"""
|
||||
from app.services.shipping_notice.export import (
|
||||
_narrow_inventory_lines_by_wanted_match_keys,
|
||||
_wanted_order_match_keys,
|
||||
)
|
||||
|
||||
order_lines = [
|
||||
{'ord_rsv': '3000112934', 'ord_part': 'D4-A08AR12000001'},
|
||||
]
|
||||
wanted = _wanted_order_match_keys(
|
||||
order_lines,
|
||||
order_field_ids=['ord_rsv', 'ord_part'],
|
||||
)
|
||||
assert wanted == {('3000112934', 'd4-a08ar12000001')}
|
||||
|
||||
inventory_lines = [
|
||||
{'inv_rsv': '3000112934', 'inv_part': 'D4-A08AR12000001', 'extra': 'HIT'},
|
||||
{'inv_rsv': '999', 'inv_part': 'OTHER', 'extra': 'MISS'},
|
||||
*[{'inv_rsv': f'R{i}', 'inv_part': f'P{i}', 'extra': 'NOISE'} for i in range(200)],
|
||||
]
|
||||
narrowed = _narrow_inventory_lines_by_wanted_match_keys(
|
||||
inventory_lines,
|
||||
inventory_field_keys=['inv_rsv', 'inv_part'],
|
||||
wanted_keys=wanted,
|
||||
)
|
||||
assert len(narrowed) == 1
|
||||
assert narrowed[0]['extra'] == 'HIT'
|
||||
|
||||
|
||||
def test_shortage_release_export_allows_reservation_miss_when_template_uses_no_inventory_field():
|
||||
"""已审计短缺放行时,库存预约单未命中不能阻断只消费订单字段的 Excel。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
@@ -16,9 +16,45 @@ from app.services.shipping_notice.order_review_projection import (
|
||||
_inventory_rpa_is_running,
|
||||
_project_case_automation_status,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import _unified_actions
|
||||
from app.services.shipping_notice.shipping_processing_projection import _processing_ui_state_from_item
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
|
||||
def test_unified_actions_keeps_blocked_gate_next_action_when_presentation_missing():
|
||||
"""Gate 展示元数据缺失时仍保留已授权的库存 RPA 重试按钮。"""
|
||||
result = _unified_actions(process_gate={
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'gate_code': 'inventory_preparation',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
},
|
||||
'action_presentation': [],
|
||||
})
|
||||
assert result['primary']['code'] == 'retry_inventory_preparation'
|
||||
|
||||
|
||||
def test_processing_ui_state_backfills_blocked_gate_action():
|
||||
"""工作项顶层动作缺失时,正式 Gate 恢复动作仍进入 ui_state 主动作。"""
|
||||
result = _processing_ui_state_from_item({
|
||||
'user_status': 'retryable',
|
||||
'user_stage': 'inventory_fetch',
|
||||
'process_gate': {
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'gate_code': 'inventory_preparation',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
},
|
||||
},
|
||||
'primary_action': None,
|
||||
'available_actions': [],
|
||||
'source_summary': {},
|
||||
})
|
||||
assert result['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
|
||||
|
||||
def test_inventory_running_is_not_inferred_from_stage_automation_job():
|
||||
"""阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。"""
|
||||
task = SimpleNamespace(task_no='OT-TEST-1')
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
tests/test_shipping_status_contract_hygiene.py
|
||||
|
||||
用途:状态契约卫生门禁——禁止在 projector 白名单外扩散 synonym frozenset。
|
||||
依赖:pathlib、re、pytest。
|
||||
逻辑:扫描 services/shipping_notice/*.py;白名单内允许持有跨层翻译袋
|
||||
(upload_attempt_service、order_review_workbench_projection);
|
||||
另断言货代前端视图不再双读 pending_human_reason。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
SERVICES_DIR = BACKEND_ROOT / 'app' / 'services' / 'shipping_notice'
|
||||
FRONTEND_FREIGHT_VIEW = (
|
||||
BACKEND_ROOT.parent
|
||||
/ 'frontend'
|
||||
/ 'src'
|
||||
/ 'features'
|
||||
/ 'chat'
|
||||
/ 'views'
|
||||
/ 'ShippingOrderReviewView.vue'
|
||||
)
|
||||
|
||||
# 允许持有跨层 synonym 袋的唯一投影模块。
|
||||
_WHITELIST = frozenset({
|
||||
'upload_attempt_service.py',
|
||||
'order_review_workbench_projection.py',
|
||||
})
|
||||
|
||||
# 读侧禁止外溢的典型 synonym 袋(字面量形态)。
|
||||
_FORBIDDEN_PATTERNS = (
|
||||
re.compile(r"\{['\"]cancelled['\"]\s*,\s*['\"]canceled['\"]"),
|
||||
re.compile(r"\{['\"]canceled['\"]\s*,\s*['\"]cancelled['\"]"),
|
||||
re.compile(r"\{['\"]succeeded['\"]\s*,\s*['\"]success['\"]\s*,\s*['\"]completed['\"]"),
|
||||
re.compile(r"\{['\"]failed['\"]\s*,\s*['\"]dead['\"]"),
|
||||
re.compile(r"\{['\"]uploaded['\"]\s*,\s*['\"]succeeded['\"]\s*,\s*['\"]success['\"]"),
|
||||
re.compile(r"\{['\"]waiting_human['\"]\s*,\s*['\"]idle['\"]"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_synonym_frozenset_only_in_whitelist_projectors():
|
||||
"""白名单外不得出现状态同义词 frozenset/set 字面量。"""
|
||||
offenders: list[str] = []
|
||||
for path in sorted(SERVICES_DIR.glob('*.py')):
|
||||
if path.name in _WHITELIST or path.name.startswith('_'):
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8')
|
||||
for pattern in _FORBIDDEN_PATTERNS:
|
||||
if pattern.search(text):
|
||||
offenders.append(f'{path.name}: {pattern.pattern}')
|
||||
assert not offenders, 'synonym bags leaked outside projectors:\n' + '\n'.join(offenders)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_freight_view_does_not_read_pending_human_reason():
|
||||
"""货代上传 FE 禁止再双读 pending_human_reason(D1)。"""
|
||||
text = FRONTEND_FREIGHT_VIEW.read_text(encoding='utf-8')
|
||||
assert 'pending_human_reason' not in text
|
||||
@@ -145,6 +145,29 @@ def test_cross_candidate_marks_out_of_scope_when_only_disallowed_source_matches(
|
||||
assert result['line_results'][0]['out_of_candidate_scope'] is True
|
||||
|
||||
|
||||
def test_match_without_source_tag_uses_reservation_and_part_only():
|
||||
"""活动库存 Excel 行可不带 __source_code;匹配只按 Reservation ID + Part Number。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'D4-A08AR12000001',
|
||||
'reservation_id': '3000112934',
|
||||
'quantity': '3',
|
||||
'allowed_source_codes': ['DSV360_AWSSG'],
|
||||
'candidate_scope_present': True,
|
||||
}],
|
||||
inventory_lines=[
|
||||
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0},
|
||||
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0},
|
||||
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0},
|
||||
],
|
||||
)
|
||||
assert result['match_status'] == 'fulfillable'
|
||||
assert result['line_results'][0]['disposition'] == 'ok'
|
||||
assert result['line_results'][0]['available_qty'] == 3.0
|
||||
assert result['line_results'][0]['shortage_qty'] == 0.0
|
||||
assert result['line_results'][0]['resolved_inventory_source_code'] == 'DSV360_AWSSG'
|
||||
|
||||
|
||||
def test_header_reservation_fallback_for_match():
|
||||
"""行缺 Reservation 时可回退头级有效 Reservation。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_center_review_run_deep_link.py
|
||||
|
||||
用途:验收任务中心 Notice 摘要注入 review_run_no,供 UI-04 深链订单处理工作台。
|
||||
用途:验收任务中心 Notice/OT 摘要注入 review_run_no 与 order_task_no,供 UI-04 深链
|
||||
与工作台右卡 work-item 投影键。
|
||||
依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。
|
||||
逻辑:OT 挂 extraction_run 时 SUMMARY 必含 review_run_no / owner_agent_id。
|
||||
逻辑:Notice 挂 OT 时 SUMMARY 必含 review_run_no;直接序列化 OT 时 order_task_no
|
||||
必须等于自身 task_no(禁止 enrich 冲成 null)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
from app.services.shipping_notice.query_service import serialize_task_detail, serialize_task_summary
|
||||
|
||||
|
||||
def test_serialize_task_summary_injects_review_run_no_for_order_processing_deeplink(app):
|
||||
@@ -51,3 +53,48 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
|
||||
assert data['order_task_no'] == 'OT-TC-DEEPLINK-1'
|
||||
assert data['review_run_no'] == run.run_no
|
||||
assert int(data.get('owner_agent_id') or 0) == int(agent.id)
|
||||
|
||||
|
||||
def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
"""
|
||||
OT 自序列化后 enrich 不得把 order_task_no 冲成 null。
|
||||
|
||||
关键断言:工作台右卡权威投影键 authoritativeOrderTaskNo 依赖详情里的
|
||||
order_task_no;若 enrich 只认 Notice.order_task_id,OT 自身会被写成 null,
|
||||
右卡永久停在「正在获取最新状态 / 待机」。
|
||||
"""
|
||||
with app.app_context():
|
||||
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='TC-OT-SELF')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-TC-OT-SELF-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
run.user_task_no = order_task.task_no
|
||||
run.owner_agent_id = int(agent.id)
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_task_summary(order_task, viewer_user_id=user.id)
|
||||
detail = serialize_task_detail(
|
||||
order_task,
|
||||
viewer_user_id=user.id,
|
||||
include_stage_context=True,
|
||||
view='workbench',
|
||||
)
|
||||
# 关键断言:SUMMARY / DETAIL 在 enrich 后仍保留自身 OT 号与深链 Run。
|
||||
assert summary['order_task_no'] == 'OT-TC-OT-SELF-1'
|
||||
assert summary['review_run_no'] == run.run_no
|
||||
assert detail['order_task_no'] == 'OT-TC-OT-SELF-1'
|
||||
assert detail['task_no'] == 'OT-TC-OT-SELF-1'
|
||||
assert detail['review_run_no'] == run.run_no
|
||||
@@ -281,8 +281,8 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
|
||||
mark_attempt_result_unknown(attempt)
|
||||
|
||||
state = resolve_task_ui_state(task)
|
||||
assert state.checkpoint == 'upload_result_unknown'
|
||||
# checkpoint 仅描述内部流程;下载与人工凭据登记必须由 Gate/Artifact 下发。
|
||||
# 无 Gate 时薄回退不从 upload attempt 投影位置;动作由 Gate/Artifact 下发。
|
||||
assert state.position is None
|
||||
assert not hasattr(state, 'human_options')
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
|
||||
Reference in new issue
Block a user