feat(shipping-notice): 新增库存确认来源接口及相关逻辑

This commit is contained in:
hugo committed 2026-07-13 21:53:45 +08:00
1 parent a31735b689
commit 0a9bd6415d
69 files changed
+8442 -775

No files matched your search

+187 -2
View File
@@ -1,4 +1,5 @@
import pytest
from pathlib import Path
def parse_api_error(body: dict) -> dict:
@@ -50,7 +51,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
@@ -61,6 +62,10 @@ def _shipping_notice_stable_auto_config(app, request):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
@@ -78,6 +83,186 @@ def _shipping_notice_stable_auto_config(app, request):
reset_rpa_worker_alert_state_for_tests()
@pytest.fixture(autouse=True)
def _shipping_test_default_destination(monkeypatch, request):
"""
为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
"""
if request.node.get_closest_marker("inventory_source_gate"):
return
from app.services.shipping_notice import extract as extract_mod
import app.services.shipping_notice.task_workflow as task_workflow_mod
original = extract_mod.extract_notice_fields
def _extract_with_default_destination(*args, structured=None, **kwargs):
patched = structured
if isinstance(structured, dict):
patched = dict(structured)
has_dest = any(
str(patched.get(key) or "").strip()
for key in ("ship_to", "destination_city", "destination_port", "destination_country", "warehouse_hint")
) or isinstance(patched.get("destination"), dict)
if not has_dest:
for line in patched.get("lines") or []:
if isinstance(line, dict) and any(
str(line.get(key) or "").strip()
for key in ("ship_to", "destination_city", "destination_port", "warehouse_hint")
):
has_dest = True
break
if not has_dest:
patched.setdefault("ship_to", "Dublin")
patched.setdefault("destination", {"city": "Dublin", "country": "IE"})
return original(*args, structured=patched, **kwargs)
monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination)
monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination)
def seed_task_inventory_source(
task: "ShippingTask",
*,
source_code: str = "DSV360_AWSDU",
) -> None:
"""测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
from app.services.shipping_notice.inventory_source_rules import (
compute_routing_fingerprint,
extract_routing_context,
)
from app.services.shipping_notice.inventory_sources import (
get_inventory_source,
get_inventory_sources_config_version,
)
source = get_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_source_type = identity.source_type
task.inventory_site_id = identity.site_id
task.inventory_warehouse_id = identity.warehouse_id
task.inventory_source_status = "resolved"
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = get_inventory_sources_config_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
def seed_rpa_inventory_trigger(
task: "ShippingTask",
*,
run_no: str = "RUN-TEST-001",
trigger_path: str | None = None,
) -> None:
"""测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
from app import db
from app.services.shipping_notice.tool_common import log_task_event
if task.id is None:
db.session.add(task)
db.session.flush()
trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
log_task_event(
task,
"inventory_rpa_triggered",
{"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
)
def inventory_xlsx_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
qty: int = 1,
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "SKU", "Qty"])
ws.append([warehouse_id, sku, qty])
wb.save(buf)
wb.close()
buf.seek(0)
return buf
def inventory_csv_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
qty: int = 1,
delimiter: str = ",",
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 CSV,供身份校验测试使用。"""
from io import BytesIO
buf = BytesIO()
content = f"Warehouse ID{delimiter}SKU{delimiter}Qty\n{warehouse_id}{delimiter}{sku}{delimiter}{qty}\n"
buf.write(content.encode("utf-8"))
buf.seek(0)
return buf
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
return {
"source_code": str(task.inventory_source_code or ""),
"site_id": str(task.inventory_site_id or ""),
"warehouse_id": str(task.inventory_warehouse_id or ""),
}
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
from app.services.shipping_notice.inventory_sources import get_inventory_source
source = get_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
item = {
"source_code": source_code,
"site_id": str(source.get("site_id") or ""),
"warehouse_id": str(source.get("warehouse_id") or ""),
}
item.update(overrides)
return item
def rpa_callback_payload(
task: "ShippingTask",
file_path: str | Path,
*,
run_no: str = "RUN-TEST-001",
status: str = "success",
) -> dict:
"""构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
return {
"task_id": task.task_no,
"status": status,
"file_path": str(file_path),
"run_no": run_no,
"source_code": task.inventory_source_code,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
}
def pytest_configure(config):
config.addinivalue_line(
"markers",
@@ -85,7 +270,7 @@ def pytest_configure(config):
)
config.addinivalue_line(
"markers",
"rpa_e2e: 真实货代 RPA 浏览器导出测试,默认跳过,需 FREIGHT_RPA_E2E=true",
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)
@@ -19,6 +19,7 @@ from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
from tests.conftest import seed_task_inventory_source
def _tool_headers(app):
@@ -655,6 +656,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
}
},
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.commit()
@@ -740,6 +742,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
db.session.add(user)
@@ -792,8 +795,7 @@ def test_inventory_source_rules_cover_dsv360_programs(app):
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source is not None
assert resolution.source["source_code"] == expected_code
assert resolution.source_code == expected_code
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
@@ -822,7 +824,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app)
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "inventory_source_review"
assert task.process_status == "waiting_inventory"
assert task.process_status == "pending_review"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
@@ -1447,6 +1449,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
dify_api_key="test-dify-key",
is_active=True,
)
@@ -298,7 +298,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
def test_build_schedule_run_wecom_description_mentions_raw_zip_download(app):
"""企微正文在 summary 标记可下载时应提示点击通知进入 HXOPS,不写完整 URL。"""
"""企微正文在 summary 标记可下载时应提示登录后自动下载,不写完整 URL。"""
with app.app_context():
run = _make_inventory_run_with_created(
schedule_no="ARCH-WECOM-1",
@@ -308,13 +308,13 @@ def test_build_schedule_run_wecom_description_mentions_raw_zip_download(app):
)
db.session.commit()
text = _build_schedule_run_wecom_description(run)
assert "原始库存包:点击本通知进入 HXOPS 下载" in text
assert "原始库存包:点击本通知,登录 HXOPS 后自动下载" in text
assert "https://" not in text
assert "http://" not in text
def test_build_schedule_run_wecom_jump_params_adds_raw_zip_flag_when_archive_available(app):
"""有原始库存归档时跳转参数应包含 raw_zip=1。"""
"""有原始库存归档时跳转参数应包含 raw_zip=1 与自动下载意图。"""
with app.app_context():
run = _make_inventory_run_with_created(
schedule_no="ARCH-JUMP-1",
@@ -328,6 +328,7 @@ def test_build_schedule_run_wecom_jump_params_adds_raw_zip_flag_when_archive_ava
assert params["task_id"] == task.id
assert params["run_id"] == run.id
assert params["raw_zip"] == "1"
assert params["download"] == "inventory_raw_zip"
def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app):
@@ -345,6 +346,7 @@ def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app)
assert params["task_id"] == task.id
assert params["run_id"] == run.id
assert "raw_zip" not in params
assert "download" not in params
def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
@@ -369,12 +371,14 @@ def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app):
assert _get_notify_base_url() == "https://hxops.example.com"
def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monkeypatch):
def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monkeypatch, tmp_path):
"""企微 textcard 跳转应指向管理端执行记录页,而非 workspace。"""
from app.models import User
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
captured: list[str] = []
media_uploads: list[str] = []
file_sends: list[str] = []
def _fake_send_textcard(_userid, _title, _description, jump_url):
captured.append(jump_url)
@@ -390,13 +394,18 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
)
monkeypatch.setattr(
"app.services.wecom_notify.upload_wecom_temp_media",
lambda *_args, **_kwargs: None,
lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}",
)
monkeypatch.setattr(
"app.services.wecom_notify.send_wecom_file_message",
lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0},
)
with app.app_context():
app.config["WECOM_NOTIFY_ENABLED"] = True
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
user = User(
username="wecom_jump_user",
@@ -414,10 +423,15 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
created=[{"inventory_file_no": "SIF-NOTIFY-1"}],
summary={"raw_inventory_zip_available": True},
)
raw_excel = tmp_path / "raw_inventory.xlsx"
raw_excel.write_bytes(b"raw inventory")
_attach_inventory_file(inventory_file_no="SIF-NOTIFY-1", storage_path=raw_excel)
run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
task = run.task
task.notify_enabled = True
task.notify_user_ids_json = [user.id]
run.excel_file_data = None
run.excel_file_data = b"schedule excel"
run.excel_file_name = "schedule.xlsx"
db.session.commit()
_notify_schedule_run_wecom(task, run)
@@ -427,6 +441,10 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
assert "task_id=" in captured[0]
assert "run_id=" in captured[0]
assert "raw_zip=1" in captured[0]
assert "download=inventory_raw_zip" in captured[0]
assert "schedule.xlsx" in media_uploads
assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads
assert file_sends == ["media-1", "media-2"]
def test_get_inventory_raw_zip_requires_admin_auth(client, app):
File diff suppressed because it is too large. Load diff
@@ -25,6 +25,13 @@ from app.services.schedule.shipping_inventory_rpa_job import (
run_shipping_inventory_rpa_schedule,
)
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item
def _write_sample_inventory(path: Path, warehouse_id: str) -> None:
"""写入带 Warehouse ID 列的样例库存 Excel。"""
with open(path, "wb") as handle:
handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku="A001", qty=1).getvalue())
def _make_inventory_schedule_task(
@@ -218,16 +225,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
_write_sample_inventory(sample, "BYAWSATL01")
def _excel_boom(*_args, **_kwargs):
raise RuntimeError("excel exploded")
@@ -266,12 +264,11 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
success=True,
file_path=str(sample),
)],
})
db.session.refresh(run)
@@ -293,16 +290,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
_write_sample_inventory(sample, "BYAWSATL01")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
@@ -341,12 +329,11 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
success=True,
file_path=str(sample),
)],
})
db.session.refresh(run)
@@ -367,16 +354,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
_write_sample_inventory(sample, "BYAWSATL01")
with app.app_context():
task = _make_inventory_schedule_task(
@@ -407,12 +385,11 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
success=True,
file_path=str(sample),
)],
})
db.session.refresh(run)
@@ -520,16 +497,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
_write_sample_inventory(sample, "AWSDU")
with app.app_context():
task = _make_inventory_schedule_task(
@@ -545,9 +513,9 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
response_summary_json={
"awaiting_rpa": True,
"pending_details": [
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
{"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
{"source_code": "DSV360_AWSDU", "warehouse_id": "AWSDU", "display_name": "Dublin"},
{"source_code": "DSV360_AWSCV", "warehouse_id": "AWSCV", "display_name": "CV"},
{"source_code": "DSV360_AWSAMS", "warehouse_id": "RTM", "display_name": "AMS"},
],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
@@ -559,12 +527,11 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "SRC_A",
"warehouse_id": "WH1",
"success": True,
"file_path": str(sample),
}],
"results": [scheduled_rpa_batch_item(
"DSV360_AWSDU",
success=True,
file_path=str(sample),
)],
})
db.session.refresh(run)
@@ -729,3 +696,206 @@ def test_build_schedule_run_wecom_description_includes_skipped_count():
assert "跳过: 1" in text
assert "成功: 2" in text
assert "失败: 0" in text
def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
"""定时 batch 回调 run_no 与排程 run 不一致时必须拒绝终态化。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RUNNO-MISMATCH",
username="schedule_runno_mismatch_user",
)
run = ScheduleRun(
run_no="RUN-EXPECTED",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={"awaiting_rpa": True, "pending_details": []},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
result = rpa_report_inventory_batch({
"run_no": "RUN-WRONG",
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [],
})
db.session.refresh(run)
assert result["status"] == "failed"
assert (result.get("data") or {}).get("schedule_run_error") == "schedule_run_no_mismatch"
assert run.status == "running"
def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path):
"""定时 batch 成功项缺少 site_id 时必须拒绝,不得仅靠 source_code 入库。"""
from app.models import ShippingInventoryFile
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "missing_site.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
with app.app_context():
before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
result = rpa_report_inventory_batch({
"run_no": "RUN-MISSING-SITE",
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert result["data"]["failed"][0]["error"] == "site_id_missing"
assert after == before
def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkeypatch):
"""finalize 失败重试同一回调时不得重复创建 ready 快照。"""
from app.models import ShippingInventoryFile
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_snapshot.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
monkeypatch.setattr(
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
_boom,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RETRY-SNAPSHOT",
username="schedule_inv_retry_snapshot_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260713163000",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={"awaiting_rpa": True, "pending_details": []},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
payload = {
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
success=True,
file_path=str(sample),
)],
}
first = rpa_report_inventory_batch(payload)
second = rpa_report_inventory_batch(payload)
count = ShippingInventoryFile.query.filter_by(
rpa_run_no=run.run_no,
source_code="DSV360_AWSBI_BYAWSATL01",
site_id="AWSBI",
warehouse_id="BYAWSATL01",
snapshot_status="ready",
).count()
assert first["data"]["schedule_finalize_status"] == "failed"
assert second["data"]["schedule_finalize_status"] == "failed"
assert count == 1
assert second["data"]["created"][0].get("reused_existing_snapshot") is True
def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch):
"""finalize 首次失败、重试成功后应归档 callback 原文件。"""
from app.models import ShippingInventoryFile
from app.services.schedule import shipping_inventory_rpa_finalize as finalize_mod
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_move.xlsx"
_write_sample_inventory(sample, "BYAWSATL01")
processed_dir = drop_dir / "processed"
original_finalize = finalize_mod.finalize_shipping_inventory_schedule_run
state = {"calls": 0}
def _finalize_fail_once(schedule_run_id, **kwargs):
state["calls"] += 1
if state["calls"] == 1:
return {
"ok": False,
"error": "finalize exploded",
"schedule_finalize_status": "failed",
"manual_retryable": True,
}
return original_finalize(schedule_run_id, **kwargs)
monkeypatch.setattr(
finalize_mod,
"finalize_shipping_inventory_schedule_run",
_finalize_fail_once,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RETRY-MOVE",
username="schedule_inv_retry_move_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260713170000",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={"awaiting_rpa": True, "pending_details": []},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
payload = {
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSBI_BYAWSATL01",
success=True,
file_path=str(sample),
)],
}
first = rpa_report_inventory_batch(payload)
assert first["data"]["schedule_finalize_status"] == "failed"
assert sample.is_file()
second = rpa_report_inventory_batch(payload)
assert second["data"]["schedule_finalize_status"] == "ok"
assert second["data"]["created"][0].get("reused_existing_snapshot") is True
assert not sample.is_file()
assert list(processed_dir.glob("retry_move.xlsx"))
assert ShippingInventoryFile.query.filter_by(
rpa_run_no=run.run_no,
snapshot_status="ready",
).count() == 1
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from pathlib import Path
from app import db
from app.models import ShippingInventoryFile, ShippingTask
from app.models import ShippingTask
from app.services.shipping_notice.inventory_snapshot_store import (
create_inventory_snapshot_from_rpa,
find_latest_ready_snapshot,
@@ -15,19 +15,45 @@ from app.services.shipping_notice.inventory_snapshot_store import (
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
from tests.conftest import inventory_xlsx_with_warehouse, seed_task_inventory_source
def _write_inventory_xlsx(path: Path, warehouse_id: str, *, sku: str = "A001", qty: int = 10) -> None:
with open(path, "wb") as handle:
handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku=sku, qty=qty).getvalue())
def _task_with_inventory_source(
task_no: str,
*,
source_code: str,
source_type: str | None = None,
site_id: str | None = None,
warehouse_id: str = "",
) -> ShippingTask:
"""构造已通过库存源门禁的任务,供快照关联测试使用。"""
task = ShippingTask(
task_no=task_no,
source_type="manual",
process_status="parsed",
)
seed_task_inventory_source(task, source_code=source_code)
if site_id:
task.inventory_site_id = site_id
if warehouse_id:
task.inventory_warehouse_id = warehouse_id
if source_type:
task.inventory_source_type = source_type
return task
def test_fresh_snapshot_is_reused(app, tmp_path):
"""未过期 ready 快照应被 find_latest_ready_snapshot 命中。"""
"""未过期 ready 快照应被 find_latest_ready_snapshot 按 source+site 命中。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.active.append(["A001", 10])
wb.save(xlsx)
wb.close()
_write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
assert source is not None
@@ -40,24 +66,19 @@ def test_fresh_snapshot_is_reused(app, tmp_path):
success=True,
)
db.session.commit()
found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU")
found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU")
assert found is not None
assert found.inventory_file_no == inv.inventory_file_no
assert found.site_id == "AWSDU"
assert is_snapshot_fresh(found)
def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
"""DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。"""
def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path):
"""DSV 子仓快照应分别落库 site_id 与 warehouse_id,禁止混用。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.active.append(["A001", 10])
wb.save(xlsx)
wb.close()
_write_inventory_xlsx(xlsx, "BYAWSATL01")
source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert source is not None
@@ -66,26 +87,36 @@ def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory")
task = _task_with_inventory_source(
"SN-SNAPSHOT-SITE",
source_code="DSV360_AWSBI_BYAWSATL01",
source_type="dsv360",
site_id="AWSBI",
warehouse_id="BYAWSATL01",
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
assert inv.warehouse_id == "AWSBI"
assert inv.site_id == "AWSBI"
assert inv.warehouse_id == "BYAWSATL01"
assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01"
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01") is not None
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01_WRONG") is None
assert link is not None
assert link.matched_warehouse_id == "AWSBI"
assert link.matched_site_id == "AWSBI"
assert link.matched_warehouse_id == "BYAWSATL01"
def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path):
"""无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。"""
def test_crane_runtime_source_carries_dynamic_warehouse(app, tmp_path):
"""Crane 运行时 RPA source 应携带任务动态库位 TZR2。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
xlsx = tmp_path / "crane_stock.xlsx"
wb = Workbook()
wb.active.append(["Warehouse ID", "sku", "qty"])
@@ -93,41 +124,69 @@ def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_pat
wb.save(xlsx)
wb.close()
source = {
"source_code": "CRANE",
"source_type": "crane_footprint",
"site_id": "",
"warehouse_id": "",
}
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory")
task = ShippingTask(
task_no="SN-SNAPSHOT-CRANE-RUNTIME",
source_type="manual",
process_status="parsed",
ship_to="TZR2 footprint",
)
seed_task_inventory_source(task, source_code="CRANE")
runtime_source = build_task_rpa_inventory_source(task)
assert runtime_source is not None
assert runtime_source["site_id"] == "CRANE"
assert runtime_source["warehouse_id"] == "TZR2"
assert runtime_source["query"]["warehouse_code"] == "TZR2"
inv = create_inventory_snapshot_from_rpa(
source=runtime_source,
local_path=xlsx,
trigger_type="on_demand",
success=True,
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="rpa_callback")
db.session.commit()
assert inv.warehouse_id == "TZR2"
assert (inv.source_query_json or {}).get("site_id") is None
assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2"
assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel"
assert (inv.source_query_json or {}).get("warehouse_id_source") == "task_identity_excel_verified"
assert (inv.source_query_json or {}).get("excel_warehouse_verified") is True
assert link is not None
assert link.matched_warehouse_id == "TZR2"
def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path):
"""相同 SKU 但库存源不同不能复用快照。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
xlsx = tmp_path / "stock.xlsx"
_write_inventory_xlsx(xlsx, "AWSDU")
with app.app_context():
source = build_rpa_inventory_source("DSV360_AWSDU")
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = _task_with_inventory_source(
"SN-SNAPSHOT-MISMATCH",
source_code="DSV360_AWSAMS",
source_type="dsv360",
site_id="AWSAMS",
)
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
assert link is None
assert inv.identity_status == "mismatch"
def test_expired_snapshot_not_reused(app, tmp_path):
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.save(xlsx)
wb.close()
_write_inventory_xlsx(xlsx, "AWSDU")
source = build_rpa_inventory_source("DSV360_AWSDU")
with app.app_context():
@@ -136,23 +195,23 @@ def test_expired_snapshot_not_reused(app, tmp_path):
inv.expires_at = snapshot_expires_at(inv.exported_at)
db.session.commit()
assert not is_snapshot_fresh(inv)
assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU") is None
assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") is None
def test_link_snapshot_writes_audit_fields(app, tmp_path):
"""任务与快照 link 应写入 link_reason 与 audit_payload。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.save(xlsx)
wb.close()
_write_inventory_xlsx(xlsx, "AWSDU")
with app.app_context():
task = ShippingTask(task_no="SN-SNAPSHOT-LINK", source_type="manual", process_status="waiting_inventory")
task = _task_with_inventory_source(
"SN-SNAPSHOT-LINK",
source_code="DSV360_AWSDU",
source_type="dsv360",
site_id="AWSDU",
)
db.session.add(task)
db.session.commit()
@@ -163,5 +222,6 @@ def test_link_snapshot_writes_audit_fields(app, tmp_path):
assert link is not None
assert link.link_reason == "reuse_latest"
assert link.matched_warehouse_id == "AWSDU"
assert link.matched_site_id == "AWSDU"
assert link.matched_source_code == "DSV360_AWSDU"
assert link.audit_payload_json["source_code"] == "DSV360_AWSDU"
File diff suppressed because it is too large. Load diff
@@ -21,7 +21,7 @@ def test_inventory_sources_yaml_loads(app):
assert source is not None
assert source["source_type"] == "dsv360"
assert source["site_id"] == "AWSDU"
assert source["warehouse_id"] == ""
assert source["warehouse_id"] == "AWSDU"
assert source["query"]["program_label"]
@@ -100,15 +100,40 @@ sources:
reload_inventory_sources_config()
def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app):
"""Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。"""
def test_dsv_source_requires_warehouse_id(app, tmp_path):
"""DSV 源必须显式配置 warehouse_id。"""
bad = tmp_path / "bad_sources.yaml"
bad.write_text(
"""
version: 1
sources:
- source_code: DSV360_BAD
enabled: true
source_type: dsv360
site_id: AWSBI
entry_url: http://x
navigation: {}
parameters: []
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="warehouse_id is required"):
reload_inventory_sources_config()
def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app):
"""Crane 源须配置 site_id 与 match_aliases,库位由订单别名解析。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("CRANE")
assert payload is not None
assert payload["source_type"] == "crane_footprint"
assert payload["site_id"] == ""
assert payload["site_id"] == "CRANE"
assert payload["warehouse_id"] == ""
assert payload["warehouse_resolution"] == "alias_match"
assert payload.get("allowed_warehouse_ids") == ["TZR", "TZR2", "TZR3"]
assert payload["parameters"] == []
assert payload["navigation"]["download_mode"] == "scheduled_report"
@@ -123,3 +148,46 @@ def test_match_aliases_available_via_list(app):
assert "CRANE" in codes
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
assert awsbi_count == 25
def test_inventory_sources_cache_refreshes_when_content_changes_with_same_mtime(app, tmp_path, monkeypatch):
"""配置内容变化但 mtime 不变时,缓存仍须刷新。"""
import os
from app.services.shipping_notice import inventory_sources as mod
cfg = tmp_path / "sources.yaml"
cfg.write_text(
"""
version: 1
sources:
- source_code: CACHE_TEST
enabled: true
source_type: dsv360
site_id: S1
warehouse_id: W1
entry_url: http://example.com
navigation: {}
parameters: []
""",
encoding="utf-8",
)
fixed_mtime = 1_700_000_000.0
os.utime(cfg, (fixed_mtime, fixed_mtime))
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(cfg)
with app.app_context():
mod._CONFIG_CACHE = None
mod._CONFIG_PATH = None
mod._CONFIG_RAW_DIGEST = None
first = mod.reload_inventory_sources_config()
assert first["sources"]["CACHE_TEST"]["warehouse_id"] == "W1"
cfg.write_text(
cfg.read_text(encoding="utf-8").replace("warehouse_id: W1", "warehouse_id: W2"),
encoding="utf-8",
)
os.utime(cfg, (fixed_mtime, fixed_mtime))
second = mod.reload_inventory_sources_config()
assert second["sources"]["CACHE_TEST"]["warehouse_id"] == "W2"
assert second is not first
+105 -17
View File
@@ -6,6 +6,7 @@ import pytest
from app import db
from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
def _tool_headers(app):
@@ -17,6 +18,23 @@ def _tool_headers(app):
}
def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None:
"""测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。"""
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"ship_to": "Dublin",
"lines": [{"sku": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
@@ -389,6 +407,7 @@ def test_openapi_spec_public(app, client):
map_json_schema = apply_mapping["properties"]["map_json"]
assert map_json_schema["type"] == "string"
assert "JSON 字符串" in map_json_schema["description"]
assert "/tools/confirm_inventory_source" in spec["paths"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
spec_text = str(spec)
@@ -410,6 +429,30 @@ def test_openapi_spec_public(app, client):
assert "按钮由 HXOPS 前端渲染" in submit_desc
def test_confirm_inventory_source_route_returns_json(app, client):
"""confirm_inventory_source HTTP 路由必须存在且可调用。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(
task_no="SN-HTTP-CONFIRM-SRC",
source_type="manual",
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
)
db.session.add(task)
db.session.commit()
res = client.post(
"/api/shipping-notice/tools/confirm_inventory_source",
headers=headers,
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
)
assert res.status_code == 200
assert res.get_json()["status"] in {"ok", "needs_human", "running"}
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
"""静态 OpenAPI 快照应同步最新推进约束,避免 Dify 导入旧版说明。"""
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json"
@@ -495,6 +538,7 @@ def test_parse_inventory_empty_needs_human(app, client):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
@@ -620,11 +664,16 @@ def test_match_inventory_requires_reservation_id(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
@@ -704,20 +753,38 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
)
task_id = create_res.get_json()["task_id"]
from app import db
from tests.conftest import seed_task_inventory_source
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-TOOLS-CB")
db.session.commit()
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 20])
ws.append(["Warehouse ID", "料号", "可用数量"])
ws.append(["AWSDU", "A001", 20])
wb.save(inv_file)
wb.close()
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
json={
"task_no": task_id,
"success": True,
"file_path": str(inv_file),
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
},
)
assert cb_res.status_code == 200
data = cb_res.get_json()
@@ -890,8 +957,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["10-40594-001", "AWS-311", 5])
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -909,7 +976,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
@@ -941,6 +1008,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
from app.models import ShippingBatch, ShippingTaskInventoryLink
from app.services.shipping_notice import inventory_file_store
from tests.conftest import seed_task_inventory_source
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
@@ -976,15 +1044,16 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
batch_index=2,
batch_total=2,
)
seed_task_inventory_source(pending, source_code="DSV360_AWSDU")
db.session.add_all([batch, completed, pending])
db.session.commit()
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["SKU", "Reservation ID", "Available Qty"])
ws.append(["A001", "R-1", 10])
ws.append(["A002", "R-2", 10])
ws.append(["Warehouse ID", "SKU", "Reservation ID", "Available Qty"])
ws.append(["AWSDU", "A001", "R-1", 10])
ws.append(["AWSDU", "A002", "R-2", 10])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1019,6 +1088,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
@@ -1026,8 +1096,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["504-010213-001", "1000140351", 5])
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
@@ -1067,6 +1137,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
@@ -1086,6 +1157,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
@@ -1094,8 +1166,8 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Part No", "Resv", "On Hand"])
ws.append(["SKU-99", "R-1", 12])
ws.append(["Warehouse ID", "Part No", "Resv", "On Hand"])
ws.append(["AWSDU", "SKU-99", "R-1", 12])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1143,7 +1215,8 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"ship_to": "Dublin",
"lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1437,7 +1510,11 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path):
def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
@@ -1478,6 +1555,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.process_status = "parsed"
db.session.commit()
retry_res = client.post(
@@ -1544,6 +1623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1568,7 +1648,11 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
@pytest.mark.auto_rpa
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path):
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
from datetime import datetime, timedelta
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
@@ -1602,6 +1686,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.process_status = "parsed"
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
@@ -1681,6 +1767,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1849,6 +1936,7 @@ def test_parse_inventory_rejects_oversized_text(app, client):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",