refactor(rpa): 重构货代RPA上传成功判定与按需库存trigger构造
This commit is contained in:
1 parent
420f1a4abb
commit
fee28bd1e9
8 files changed
+1019
-348
No files matched your search
@@ -932,8 +932,8 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
|
||||
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
|
||||
|
||||
|
||||
def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
"""DSV 上传须复用登录态打开入口、设置文件,并以 History 绿色回执作为证据返回。"""
|
||||
def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
"""DSV 上传须点击 Process File,并以结果页三项判定的证据回传。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
@@ -986,10 +986,10 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
|
||||
def fake_history(_page, filename):
|
||||
return {"reference": "FREIGHT-REF-001", "success_evidence": {"kind": "dsv_history_green_dom", "selector": "em.fa.fa-circle.success-color.status-icon", "filename": filename, "reference": "FREIGHT-REF-001", "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<em/>", "dom_sha256": "abc"}}
|
||||
def fake_result(_page, filename):
|
||||
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
|
||||
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", fake_history)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", fake_result)
|
||||
|
||||
result = worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={
|
||||
"connector_type": "dbs",
|
||||
@@ -1001,11 +1001,12 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
"result_mode": "page_notice", "result_selector": None, "success_texts": [], "timeout_seconds": 120,
|
||||
},
|
||||
})
|
||||
assert result['reference'] == 'FREIGHT-REF-001'
|
||||
assert result['success_evidence']['kind'] == 'dsv_history_green_dom'
|
||||
assert result['reference'] == ''
|
||||
assert result['success_evidence']['kind'] == 'dsv_upload_success_dom'
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") in events
|
||||
assert ("file", str(workbook)) in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
@@ -1053,7 +1054,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
|
||||
|
||||
assert worker._upload_shipment_with_browser(
|
||||
workbook, connector_type="dbs", upload_source={
|
||||
@@ -1068,12 +1069,52 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
"success_texts": [], "timeout_seconds": 120,
|
||||
},
|
||||
}
|
||||
) == "REF-shipment.xlsx"
|
||||
) == {"reference": "", "success_evidence": {}}
|
||||
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
|
||||
assert ("file", "#file2") in events
|
||||
assert ("click", 'button.upload-button:has-text("Process File")') in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_always_confirms_process_file_after_selecting_file(monkeypatch, tmp_path):
|
||||
"""DSV 选中文件后必须点击 Process File,不能仅凭 set_input_files 视为已上传。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
def __init__(self, selector: str):
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def set_input_files(self, value: str, **_kwargs) -> None:
|
||||
events.append(("file", value))
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
events.append(("click", self.selector))
|
||||
|
||||
class _Page:
|
||||
def goto(self, _url: str, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def locator(self, selector: str) -> _Locator:
|
||||
return _Locator(selector)
|
||||
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: None)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda *_args: {"reference": "", "success_evidence": {}})
|
||||
worker.DsvUploadAdapter(
|
||||
file_path=workbook,
|
||||
upload_config={
|
||||
"entry_url": "https://s360.dbschenker.com/upload",
|
||||
"file_input_selector": "#file2",
|
||||
"submit_mode": "auto_after_file",
|
||||
"timeout_seconds": 1,
|
||||
},
|
||||
).run(_Page(), login_url="https://s360.dbschenker.com/")
|
||||
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
|
||||
@@ -1154,6 +1195,48 @@ def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeyp
|
||||
assert evidence["page_url"]
|
||||
|
||||
|
||||
def test_crane_upload_result_requires_processing_and_shipping_order_allocated():
|
||||
"""Crane 上传成功必须同时满足单号行状态与状态描述。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Processing",
|
||||
"order_status_description": "Shipping Order Allocated",
|
||||
}) is True
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Completed",
|
||||
"order_status_description": "Shipping Order Allocated",
|
||||
}) is False
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Processing",
|
||||
"order_status_description": "Allocating the Shipping Order",
|
||||
}) is False
|
||||
|
||||
|
||||
def test_dsv_upload_result_requires_success_button_and_empty_errors():
|
||||
"""DSV 只有成功按钮且两类错误均为空时才算上传成功。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Successful",
|
||||
"upload_file_errors": "",
|
||||
"wms_errors": "",
|
||||
}) is True
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Unsuccessful",
|
||||
"upload_file_errors": "",
|
||||
"wms_errors": "",
|
||||
}) is False
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Successful",
|
||||
"upload_file_errors": "Missing column",
|
||||
"wms_errors": "",
|
||||
}) is False
|
||||
|
||||
|
||||
def test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
|
||||
"""首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.models import (
|
||||
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import (
|
||||
@@ -45,7 +45,7 @@ def _tool_headers():
|
||||
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
def _attach_dynamic_order(task: ShippingOrderTask | ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
"""为库存/RPA 测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
@@ -74,12 +74,18 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
str(item['field_code']): str(item['field_id'])
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
|
||||
if owner is None:
|
||||
owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task.order_task_id = owner.id
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
|
||||
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
|
||||
@@ -94,11 +100,11 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
owner.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
|
||||
def _confirm_direct_rpa_task_customer(task: ShippingOrderTask | ShippingNotice) -> None:
|
||||
"""为直接构造的 RPA 回调任务补齐已确认客户。
|
||||
|
||||
核心逻辑:测试不经建单工作流时,显式绑定激活客户,
|
||||
@@ -111,15 +117,31 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
task.customer = customer
|
||||
task.customer_name_snapshot = customer.standard_name
|
||||
task.customer_short_code_snapshot = customer.short_code
|
||||
task.customer_resolution_status = 'confirmed'
|
||||
task.customer_resolution_method = 'test_fixture'
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
|
||||
if owner is None:
|
||||
owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task.order_task_id = owner.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
|
||||
if extraction is None:
|
||||
rows = getattr(task, 'lines_json', None)
|
||||
if not isinstance(rows, list) or len(rows) != 1 or not isinstance(rows[0], dict):
|
||||
raise ValueError('RPA test task must have an accepted extraction before customer confirmation')
|
||||
row = rows[0]
|
||||
_attach_dynamic_order(
|
||||
task,
|
||||
part_number=str(row.get('part_number') or ''),
|
||||
reservation_id=str(row.get('reservation_id') or ''),
|
||||
quantity=int(row.get('qty') or 0),
|
||||
)
|
||||
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
|
||||
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
|
||||
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
|
||||
task._test_customer_confirmed = True
|
||||
owner._test_customer_confirmed = True
|
||||
if not isinstance(task, ShippingOrderTask):
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -169,7 +191,7 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
|
||||
trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
|
||||
lambda _task, *, mode: trigger,
|
||||
lambda _task, *, mode, allow_auto_retry=True: trigger,
|
||||
)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
@@ -203,7 +225,7 @@ def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypat
|
||||
monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode: calls.append((actual_task, mode)) or prepared,
|
||||
lambda actual_task, *, mode, allow_auto_retry=True: calls.append((actual_task, mode)) or prepared,
|
||||
)
|
||||
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None)
|
||||
@@ -288,14 +310,8 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
|
||||
"""库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。"""
|
||||
from app.services.shipping_notice import inventory_mapping_workflow as workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
id=1, task_no="SN-INV-CLEAR", inventory_lines_json=None,
|
||||
match_status="unfulfillable", line_results_json=[{"a": 1}], shortage_json={"lines": []},
|
||||
)
|
||||
linked_task = SimpleNamespace(
|
||||
id=2, task_no="SN-INV-CLEAR-LINKED", inventory_lines_json=None,
|
||||
match_status="unfulfillable", line_results_json=None, shortage_json=None,
|
||||
)
|
||||
task = SimpleNamespace(id=1, task_no="SN-INV-CLEAR")
|
||||
linked_task = SimpleNamespace(id=2, task_no="SN-INV-CLEAR-LINKED")
|
||||
inventory_file = SimpleNamespace(inventory_file_no="INV-CLEAR")
|
||||
|
||||
monkeypatch.setattr(workflow, "active_inventory_file_for_task", lambda _task: inventory_file)
|
||||
@@ -317,7 +333,7 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
|
||||
lambda notice: None,
|
||||
)
|
||||
|
||||
workflow.inventory_loaded_response(
|
||||
response = workflow.inventory_loaded_response(
|
||||
task,
|
||||
[{"part_number": "A001", "qty": 1}],
|
||||
source="rpa",
|
||||
@@ -325,13 +341,11 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
|
||||
commit=False,
|
||||
)
|
||||
|
||||
# 库存内容变更后,task 与其同库存文件的关联任务都不能再读旧匹配结果。
|
||||
assert task.match_status is None
|
||||
assert task.line_results_json is None
|
||||
assert task.shortage_json is None
|
||||
assert linked_task.match_status is None
|
||||
assert linked_task.line_results_json is None
|
||||
assert linked_task.shortage_json is None
|
||||
# 新模型不再向 OT 写入库存匹配旧投影;库存事实由 File/Link/Match/Gate 承载。
|
||||
assert response['status'] == 'ok'
|
||||
assert not hasattr(task, 'match_status')
|
||||
assert not hasattr(task, 'shortage_json')
|
||||
assert not hasattr(linked_task, 'line_results_json')
|
||||
|
||||
|
||||
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
|
||||
@@ -363,9 +377,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand',
|
||||
},
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-SNAPSHOT-SOURCE-UNIQUE', user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
source_snapshot = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-SOURCE-UNIQUE', storage_path=str(source_file), snapshot_status='ready',
|
||||
@@ -422,28 +435,32 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-PROFILE-001', source_type='manual',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-MANUAL-PROFILE-001', user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
assert task.order_snapshot_id is not None
|
||||
|
||||
upload = FileStorage(
|
||||
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()),
|
||||
filename='manual-stock.xlsx',
|
||||
)
|
||||
result = upload_inventory_file(task.task_no, upload)
|
||||
result = upload_inventory_file(
|
||||
task.task_no,
|
||||
upload,
|
||||
)
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert result['checkpoint'] == 'ready_to_match'
|
||||
assert task.inventory_snapshot_id is not None
|
||||
assert task.review_status is None
|
||||
assert task.pending_human_reason is None
|
||||
snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id)
|
||||
assert result['status'] == 'ok', result
|
||||
assert result['data']['stage'] == 'step5_match_inventory'
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
|
||||
assert snapshot is not None
|
||||
assert snapshot.mapping_source == 'parsing_profile'
|
||||
assert snapshot.mapping_confirmed is True
|
||||
@@ -473,10 +490,12 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
stream.seek(0)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-DRIFT-001', source_type='manual',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-MANUAL-DRIFT-001', user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
db.session.add(task)
|
||||
@@ -490,8 +509,6 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
|
||||
assert result['status'] == 'failed'
|
||||
assert '结构' in result['message'] or '解析' in result['message']
|
||||
assert task.inventory_snapshot_id is None
|
||||
assert task.inventory_lines_json in (None, [])
|
||||
assert ShippingInventoryFile.query.count() == 0
|
||||
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0
|
||||
assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*'))
|
||||
@@ -680,12 +697,12 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-RUNNO",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-BATCH-RUNNO", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
from tests.conftest import seed_rpa_inventory_trigger
|
||||
@@ -702,15 +719,15 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(sample),
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
}],
|
||||
}))
|
||||
db.session.refresh(task)
|
||||
|
||||
assert receipt["status"] == "ok"
|
||||
assert receipt["result_status"] == "accepted"
|
||||
assert task.inventory_snapshot_id is None
|
||||
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0
|
||||
job = db.session.get(Job, int(receipt["data"]["job_id"]))
|
||||
assert job is not None
|
||||
assert job.status == "queued"
|
||||
@@ -729,8 +746,8 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(sample),
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
}],
|
||||
}))
|
||||
assert replay["result_status"] == "accepted"
|
||||
@@ -739,7 +756,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
result = _process_batch_callback(job.payload_json)
|
||||
db.session.refresh(task)
|
||||
assert result["result_status"] == "success"
|
||||
assert task.inventory_snapshot_id is not None
|
||||
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 1
|
||||
|
||||
|
||||
def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
@@ -760,12 +777,12 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-FAIL-TASK",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-BATCH-FAIL-TASK", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
from tests.conftest import seed_rpa_inventory_trigger
|
||||
@@ -801,7 +818,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
status="running",
|
||||
lease_token="batch-fail-lease",
|
||||
extra_json={
|
||||
"candidate_set_id": 0,
|
||||
"candidate_set_id": task.active_inventory_candidate_set_id,
|
||||
"execution_id": execution.id,
|
||||
"gate_id": gate.id,
|
||||
},
|
||||
@@ -826,7 +843,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
"callback_id": "callback-batch-fail-dsv-a1",
|
||||
"attempt_no": 1,
|
||||
"lease_token": "batch-fail-lease",
|
||||
"candidate_set_id": 0,
|
||||
"candidate_set_id": task.active_inventory_candidate_set_id,
|
||||
"execution_id": execution.id,
|
||||
"gate_id": gate.id,
|
||||
"status": "failed",
|
||||
@@ -838,13 +855,11 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.error_message
|
||||
db.session.refresh(rpa_attempt)
|
||||
db.session.refresh(preparation)
|
||||
db.session.refresh(execution)
|
||||
db.session.refresh(gate)
|
||||
assert rpa_attempt.status == "failed"
|
||||
assert rpa_attempt.status == "consumed"
|
||||
assert preparation.status == "failed"
|
||||
assert gate.status == "blocked_retryable"
|
||||
assert gate.blocking_reason_code == "inventory_rpa_timeout"
|
||||
@@ -904,15 +919,14 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
|
||||
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CRANE-EMPTY-WAREHOUSE",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-CRANE-EMPTY-WAREHOUSE", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source, task])
|
||||
db.session.add_all([crane_profile, crane_source])
|
||||
db.session.flush()
|
||||
seed_task_inventory_source(task, source_code="CRANE")
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
@@ -946,8 +960,8 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
|
||||
|
||||
assert result["success_count"] == 1, result
|
||||
assert result["failed_count"] == 0
|
||||
assert task.inventory_snapshot_id is not None
|
||||
assert task.inventory_warehouse_id == "CRANE-WH"
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
assert link.matched_warehouse_id == "CRANE-WH"
|
||||
|
||||
|
||||
def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolvable(app, tmp_path):
|
||||
@@ -982,15 +996,14 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CRANE-UNRESOLVED-LINK",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-CRANE-UNRESOLVED-LINK", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source, task])
|
||||
db.session.add_all([crane_profile, crane_source])
|
||||
db.session.flush()
|
||||
seed_task_inventory_source(task, source_code="CRANE")
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
@@ -1031,7 +1044,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
|
||||
assert result["success_count"] == 1, result
|
||||
assert result["failed_count"] == 0
|
||||
assert task.inventory_snapshot_id is not None
|
||||
snapshot = ShippingInventoryFile.query.filter_by(
|
||||
rpa_run_no="RUN-CRANE-UNRESOLVED-LINK", source_code="CRANE",
|
||||
).one()
|
||||
@@ -1043,7 +1055,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
task_id=task.id, inventory_file_id=snapshot.id, is_active=True,
|
||||
).one()
|
||||
assert link.identity_check_status == "pending_matching"
|
||||
assert task.pending_human_reason is None
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
db.session.refresh(execution)
|
||||
@@ -1095,20 +1106,88 @@ def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatc
|
||||
assert job.result_json["callback_result"]["data"]["result_status"] == "failed"
|
||||
|
||||
|
||||
def test_inventory_callback_job_marks_top_level_failure_as_failed(app, monkeypatch):
|
||||
"""事务级失败没有 result_status 时,回调 Job 也必须失败。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import shipping_inventory_callback_process as handler
|
||||
from app.models import Job
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain="shipping_notice",
|
||||
job_type="shipping_inventory_callback_process",
|
||||
status="running",
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
payload_json={"callback_id": "callback-transaction-failed"},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow.process_rpa_report_inventory_batch",
|
||||
lambda _payload: {
|
||||
"status": "failed",
|
||||
"message": "batch callback transaction failed",
|
||||
"data": {"run_no": "RUN-TRANSACTION-FAILED"},
|
||||
},
|
||||
)
|
||||
settled = []
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow.settle_failed_inventory_callback",
|
||||
lambda payload, *, error: settled.append((payload, error)),
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {"job_id": job.id},
|
||||
)
|
||||
db.session.refresh(job)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_message == "batch callback transaction failed"
|
||||
assert settled == [(job.payload_json, "batch callback transaction failed")]
|
||||
|
||||
|
||||
def test_rpa_callback_locks_order_task_model(app):
|
||||
"""订单生命周期的库存回调必须锁定 ShippingOrderTask,不得查询旧 Notice。"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, User
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _lock_task_for_rpa_callback
|
||||
|
||||
with app.app_context():
|
||||
user = User(username="callback-lock-user", email="callback-lock@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-CALLBACK-LOCK",
|
||||
user_id=int(user.id),
|
||||
status="processing",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
locked = _lock_task_for_rpa_callback(task)
|
||||
|
||||
assert isinstance(locked, ShippingOrderTask)
|
||||
assert locked.id == task.id
|
||||
|
||||
|
||||
def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
"""单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-FAIL-NO-IDENT",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-FAIL-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
freeze_test_task_order_snapshot(task)
|
||||
assert task.order_snapshot_id is not None
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -1123,8 +1202,6 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result["status"] == "needs_human"
|
||||
assert result["checkpoint"] == "upload_req"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_failed",
|
||||
@@ -1319,12 +1396,13 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-NO-IDENT",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-BATCH-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
|
||||
db.session.add(task)
|
||||
@@ -1344,7 +1422,6 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
|
||||
|
||||
def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch):
|
||||
@@ -1386,12 +1463,13 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
assert storage_path.is_file()
|
||||
snap_id = snap.id
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUSE-INGEST-FAIL",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-REUSE-INGEST-FAIL", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no=run_no)
|
||||
db.session.add(task)
|
||||
@@ -1415,7 +1493,6 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
assert snap_after.snapshot_status == "ready"
|
||||
assert Path(snap_after.storage_path).is_file()
|
||||
assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
|
||||
|
||||
def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
@@ -1501,27 +1578,23 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task_a = ShippingNotice(
|
||||
task_no="SN-BATCH-OK",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task_a = ShippingOrderTask(
|
||||
task_no="OT-BATCH-OK", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
task_b = ShippingNotice(
|
||||
task_no="SN-BATCH-FAIL",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
task_b = ShippingOrderTask(
|
||||
task_no="OT-BATCH-FAIL", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add_all([task_a, task_b])
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task_a, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_attach_dynamic_order(task_b, part_number='B001', reservation_id='00002', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task_a)
|
||||
_confirm_direct_rpa_task_customer(task_b)
|
||||
seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
|
||||
seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task_a, run_no=run_no)
|
||||
seed_rpa_inventory_trigger(task_b, run_no=run_no)
|
||||
db.session.add_all([task_a, task_b])
|
||||
db.session.commit()
|
||||
before_b_status = task_b.pending_human_reason
|
||||
|
||||
result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
@@ -1546,9 +1619,8 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
|
||||
assert result["success_count"] == 1
|
||||
assert result["failed_count"] == 1
|
||||
assert task_a.inventory_rpa_consumed_run_no == run_no
|
||||
assert task_b.inventory_rpa_consumed_run_no is None
|
||||
assert task_b.pending_human_reason == before_b_status
|
||||
assert ShippingTaskInventoryLink.query.filter_by(task_id=task_a.id, is_active=True).count() == 1
|
||||
assert ShippingTaskInventoryLink.query.filter_by(task_id=task_b.id, is_active=True).count() == 0
|
||||
|
||||
|
||||
def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, monkeypatch):
|
||||
@@ -1582,12 +1654,13 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-DEFER-CONFIRM",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-BATCH-DEFER-CONFIRM", user_id=1, source_type="direct_pdf", status="ready",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-DEFER-CONFIRM")
|
||||
@@ -1624,25 +1697,22 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
run_no = "RUN-SHARED-LINK"
|
||||
|
||||
with app.app_context():
|
||||
task_ok = ShippingNotice(
|
||||
task_no="SN-SHARED-OK",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task_ok = ShippingOrderTask(
|
||||
task_no="OT-SHARED-OK", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
task_fail = ShippingNotice(
|
||||
task_no="SN-SHARED-FAIL",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
task_fail = ShippingOrderTask(
|
||||
task_no="OT-SHARED-FAIL", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add_all([task_ok, task_fail])
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task_ok, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_attach_dynamic_order(task_fail, part_number='B001', reservation_id='00002', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task_ok)
|
||||
_confirm_direct_rpa_task_customer(task_fail)
|
||||
seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
|
||||
seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task_ok, run_no=run_no)
|
||||
seed_rpa_inventory_trigger(task_fail, run_no=run_no)
|
||||
db.session.add_all([task_ok, task_fail])
|
||||
db.session.commit()
|
||||
|
||||
ok_result = _process_batch_callback({
|
||||
@@ -1711,12 +1781,12 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-POST-COMMIT-FAIL",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-POST-COMMIT-FAIL", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
|
||||
@@ -1729,7 +1799,6 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
assert snap is not None
|
||||
assert Path(snap.storage_path).is_file()
|
||||
assert result.get("data", {}).get("post_commit_warnings")
|
||||
assert task.inventory_rpa_consumed_run_no == "RUN-POST-COMMIT"
|
||||
|
||||
|
||||
def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkeypatch):
|
||||
@@ -1755,12 +1824,12 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROMOTE-FAIL-REBUILD",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-PROMOTE-FAIL-REBUILD", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
|
||||
@@ -1774,7 +1843,6 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
warnings = result.get("data", {}).get("post_commit_warnings") or []
|
||||
assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings)
|
||||
assert attachment is not None and attachment.is_file()
|
||||
assert task.inventory_rpa_consumed_run_no == "RUN-PROMOTE-FAIL"
|
||||
|
||||
|
||||
def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
@@ -1792,11 +1860,13 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REPAIR-ATTACH",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-REPAIR-ATTACH", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -1949,14 +2019,14 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
|
||||
other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REPAIR-REJECT",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-REPAIR-REJECT", user_id=1, source_type="direct_pdf", status="ready",
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
active_snap = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-ACTIVE-SNAP",
|
||||
storage_path=str(active_file),
|
||||
@@ -2028,3 +2098,176 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
|
||||
assert list(processed_dir.glob("stuck.xlsx"))
|
||||
assert not stuck.is_file()
|
||||
assert warnings == []
|
||||
|
||||
|
||||
def test_ensure_all_required_sources_writes_single_batch_trigger(monkeypatch, app):
|
||||
"""[断言] 多候选源缺失快照时:一轮 ensure 只写 1 个批次 trigger(单文件多源),
|
||||
逐源身份键(task_no/source_run_no/lease_token/callback_id)进入条目,
|
||||
且全部 Attempt 共享该 trigger_file_path;批次载荷为 on_demand。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-BATCH-SINGLE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
captured = {}
|
||||
|
||||
def _fake_batch_writer(run_no, sources, payload=None):
|
||||
captured['run_no'] = run_no
|
||||
captured['sources'] = [dict(item) for item in sources]
|
||||
captured['payload'] = dict(payload or {})
|
||||
return 'trigger/batch.json'
|
||||
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A', 'SRC_B'])
|
||||
monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda task: {'source_code': 'SRC_A'},
|
||||
)
|
||||
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', _fake_batch_writer)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto')
|
||||
|
||||
assert result.pending_source_codes == ['SRC_A', 'SRC_B']
|
||||
assert result.failed_source_codes == []
|
||||
assert captured['run_no'].startswith('BATCH-SN-PREP-BATCH-SINGLE-')
|
||||
assert [item['source_code'] for item in captured['sources']] == ['SRC_A', 'SRC_B']
|
||||
for item in captured['sources']:
|
||||
assert item['task_no'] == task.task_no
|
||||
assert item['source_run_no']
|
||||
assert item['lease_token']
|
||||
assert item['callback_id'].endswith(':C1')
|
||||
assert captured['payload']['trigger_type'] == 'on_demand'
|
||||
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task.task_no).all()
|
||||
assert len(attempts) == 2
|
||||
assert all(att.trigger_file_path == 'trigger/batch.json' for att in attempts)
|
||||
assert all(att.status == 'queued' for att in attempts)
|
||||
|
||||
|
||||
def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app):
|
||||
"""[断言] 多候选缺文件:auto 模式自动触发批次探测并返回 running(D3),
|
||||
而非旧的 needs_human + inv_unavail;无候选集的 blocked 场景维持 needs_human。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
from app.services.shipping_notice.state_machine import TaskTransition
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='SN-STP-AUTO-PROBE',
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=5,
|
||||
error_message='stale',
|
||||
)
|
||||
transitions = []
|
||||
probe_calls = []
|
||||
|
||||
def _fake_transition(actual_task, transition):
|
||||
transitions.append(transition)
|
||||
|
||||
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, 'apply_task_transition', _fake_transition)
|
||||
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, '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(
|
||||
'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': 'missing_files',
|
||||
'lines': [],
|
||||
'missing_source_codes': ['SRC_A', 'SRC_B'],
|
||||
'loaded_source_codes': [],
|
||||
'evidence': [],
|
||||
'required_source_codes': ['SRC_A', 'SRC_B'],
|
||||
},
|
||||
)
|
||||
|
||||
def _fake_probe(actual_task, *, mode, allow_auto_retry=True):
|
||||
probe_calls.append((actual_task, mode))
|
||||
return SimpleNamespace(
|
||||
pending_source_codes=['SRC_A', 'SRC_B'],
|
||||
prepared_source_codes=[],
|
||||
failed_source_codes=[],
|
||||
source_attempts={},
|
||||
all_prepared=False,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
_fake_probe,
|
||||
)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
|
||||
assert probe_calls == [(task, 'auto')]
|
||||
assert result['status'] == 'running'
|
||||
assert result['data']['rpa']['pending_source_codes'] == ['SRC_A', 'SRC_B']
|
||||
assert transitions == [TaskTransition.RPA_PENDING]
|
||||
assert task.error_message is None
|
||||
|
||||
|
||||
def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypatch, app):
|
||||
"""[断言] 探测无 pending(全部触发失败)→ needs_human,不得伪装 running。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='SN-STP-PROBE-FAILED',
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=5,
|
||||
)
|
||||
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, 'set_task_step_progress', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'log_task_event', 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(
|
||||
'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': 'missing_files',
|
||||
'lines': [],
|
||||
'missing_source_codes': ['SRC_A'],
|
||||
'loaded_source_codes': [],
|
||||
'evidence': [],
|
||||
'required_source_codes': ['SRC_A'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode, allow_auto_retry=True: SimpleNamespace(
|
||||
pending_source_codes=[],
|
||||
prepared_source_codes=[],
|
||||
failed_source_codes=['SRC_A'],
|
||||
source_attempts={},
|
||||
all_prepared=False,
|
||||
),
|
||||
)
|
||||
|
||||
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_preparation_failed'
|
||||
Reference in new issue
Block a user