Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
ffccf19ba2
143 files changed
+27635
-1021
No files matched your search
+187
-2
@@ -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 注入",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -201,3 +201,102 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey
|
||||
assert "run.started" in event_names
|
||||
assert "run.completed" in event_names
|
||||
assert "run.failed" not in event_names
|
||||
|
||||
|
||||
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
|
||||
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
|
||||
from io import BytesIO
|
||||
|
||||
user = _create_user()
|
||||
agent = _create_shipping_agent()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
||||
captured: dict = {}
|
||||
|
||||
def fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": "SB-CHAT-IDEM-001",
|
||||
"data": {
|
||||
"tasks": [{"task_id": "SN-CHAT-IDEM-001"}],
|
||||
"focus_task": {"task_no": "SN-CHAT-IDEM-001"},
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
|
||||
fake_create,
|
||||
)
|
||||
|
||||
res = client.post(
|
||||
"/api/chat/turns/stream",
|
||||
headers={"X-Username": user.username, "X-Role": user.role},
|
||||
data={
|
||||
"agent_id": str(agent.id),
|
||||
"input": json.dumps(
|
||||
{
|
||||
"type": "upload_followup",
|
||||
"display_text": "上传发货通知:notice.txt",
|
||||
"action_type": "shipping.create_batch_from_notices",
|
||||
"payload": {"idempotency_key": "chat-idem-001"},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert res.status_code == 200
|
||||
res.get_data(as_text=True)
|
||||
assert captured.get("create_idempotency_key") == "chat-idem-001"
|
||||
notice_items = captured.get("notice_items") or []
|
||||
assert notice_items
|
||||
assert notice_items[0].get("source_content_hash")
|
||||
|
||||
|
||||
def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
|
||||
"""相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
|
||||
from io import BytesIO
|
||||
|
||||
user = _create_user()
|
||||
agent = _create_shipping_agent()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
||||
orchestrator_calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator",
|
||||
lambda batch_no: orchestrator_calls.append(batch_no) or True,
|
||||
)
|
||||
|
||||
payload_input = {
|
||||
"type": "upload_followup",
|
||||
"display_text": "上传发货通知:notice.txt",
|
||||
"action_type": "shipping.create_batch_from_notices",
|
||||
"payload": {"idempotency_key": "chat-replay-integration-001"},
|
||||
}
|
||||
headers = {"X-Username": user.username, "X-Role": user.role}
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
|
||||
def _post_turn():
|
||||
return client.post(
|
||||
"/api/chat/turns/stream",
|
||||
headers=headers,
|
||||
data={
|
||||
"agent_id": str(agent.id),
|
||||
"input": json.dumps(payload_input, ensure_ascii=False),
|
||||
"files": (BytesIO(raw), "notice.txt"),
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
|
||||
first = _post_turn()
|
||||
assert first.status_code == 200
|
||||
first_events = _parse_sse_events(first.get_data(as_text=True))
|
||||
assert "run.failed" not in [item.get("event") for item in first_events]
|
||||
|
||||
second = _post_turn()
|
||||
assert second.status_code == 200
|
||||
second_events = _parse_sse_events(second.get_data(as_text=True))
|
||||
completed = [item for item in second_events if item.get("event") == "message.completed"]
|
||||
assert completed
|
||||
assert "已恢复此前创建的批次" in str(completed[-1].get("content", ""))
|
||||
assert len(orchestrator_calls) == 1
|
||||
@@ -103,11 +103,12 @@ def test_intake_temp_notice_uploads_splits_accepted_and_rejected(app, tmp_path,
|
||||
]
|
||||
|
||||
with app.app_context():
|
||||
accepted, rejected = notice_upload.intake_temp_notice_uploads("req-batch", uploads)
|
||||
accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-batch", uploads)
|
||||
summary = notice_upload.build_notice_file_summary(
|
||||
total_files=len(uploads),
|
||||
accepted=accepted,
|
||||
rejected=rejected,
|
||||
duplicate_files=duplicate_files,
|
||||
)
|
||||
|
||||
assert len(accepted) == 1
|
||||
@@ -140,3 +141,97 @@ def test_intake_notice_attachment_extract_failure(app, tmp_path, monkeypatch):
|
||||
assert result.accepted is False
|
||||
assert result.status == "extract_failed"
|
||||
assert result.warnings[0].startswith("notice_extract_failed:")
|
||||
|
||||
|
||||
def test_intake_notice_attachment_same_bytes_same_hash(app, tmp_path):
|
||||
"""相同字节内容应得到相同 SHA-256(与文件名无关)。"""
|
||||
from app.services.shipping_notice.notice_upload import intake_notice_attachment
|
||||
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
with app.app_context():
|
||||
first = intake_notice_attachment(
|
||||
filename="notice-a.txt",
|
||||
raw=raw,
|
||||
storage="temp",
|
||||
temp_request_id="req-hash-a",
|
||||
temp_index=1,
|
||||
)
|
||||
second = intake_notice_attachment(
|
||||
filename="notice-b.txt",
|
||||
raw=raw,
|
||||
storage="temp",
|
||||
temp_request_id="req-hash-b",
|
||||
temp_index=1,
|
||||
)
|
||||
|
||||
assert first.content_hash == second.content_hash
|
||||
assert len(first.content_hash) == 64
|
||||
assert first.content_hash == first.content_hash.lower()
|
||||
|
||||
|
||||
def test_intake_notice_attachment_different_bytes_different_hash(app, tmp_path):
|
||||
"""不同字节内容应得到不同 SHA-256。"""
|
||||
from app.services.shipping_notice.notice_upload import intake_notice_attachment
|
||||
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
||||
with app.app_context():
|
||||
first = intake_notice_attachment(
|
||||
filename="notice-a.txt",
|
||||
raw=b"content-a",
|
||||
storage="temp",
|
||||
temp_request_id="req-diff-a",
|
||||
temp_index=1,
|
||||
)
|
||||
second = intake_notice_attachment(
|
||||
filename="notice-b.txt",
|
||||
raw=b"content-b",
|
||||
storage="temp",
|
||||
temp_request_id="req-diff-b",
|
||||
temp_index=1,
|
||||
)
|
||||
|
||||
assert first.content_hash != second.content_hash
|
||||
|
||||
|
||||
def test_intake_temp_notice_uploads_dedupes_same_content_in_one_request(app, tmp_path, monkeypatch):
|
||||
"""同一请求内相同内容文件只进入 accepted 一次,duplicate 不计入 rejected。"""
|
||||
from app.services.shipping_notice import notice_upload
|
||||
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
||||
monkeypatch.setattr(
|
||||
notice_upload,
|
||||
"extract_notice_text",
|
||||
lambda saved_path: ("客户:ACME\nA001 x 10", {"warnings": [], "file_type": "txt"}),
|
||||
)
|
||||
|
||||
class _Upload:
|
||||
def __init__(self, name: str, raw: bytes, mimetype: str):
|
||||
self.filename = name
|
||||
self._raw = raw
|
||||
self.mimetype = mimetype
|
||||
|
||||
def read(self):
|
||||
return self._raw
|
||||
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
uploads = [
|
||||
_Upload("original.pdf", raw, "application/pdf"),
|
||||
_Upload("copy.pdf", raw, "application/pdf"),
|
||||
_Upload("another-copy.txt", raw, "text/plain"),
|
||||
]
|
||||
|
||||
with app.app_context():
|
||||
accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-dedupe", uploads)
|
||||
summary = notice_upload.build_notice_file_summary(
|
||||
total_files=len(uploads),
|
||||
accepted=accepted,
|
||||
rejected=rejected,
|
||||
duplicate_files=duplicate_files,
|
||||
)
|
||||
|
||||
assert len(accepted) == 1
|
||||
assert len(rejected) == 0
|
||||
assert summary["duplicate_count"] == 2
|
||||
assert summary["duplicate_files"][0]["duplicate_of"] == "original.pdf"
|
||||
assert accepted[0].to_notice_item()["source_content_hash"] == accepted[0].content_hash
|
||||
@@ -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):
|
||||
@@ -358,21 +359,15 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
|
||||
assert result["data"]["batch"]["batch_no"] == result["batch_no"]
|
||||
assert result["data"]["tasks"][0]["parse_status"] == "deferred"
|
||||
assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"]
|
||||
assert result["file_summary"] == {
|
||||
"total_files": 1,
|
||||
"accepted_count": 1,
|
||||
"rejected_count": 0,
|
||||
"accepted_files": [
|
||||
{
|
||||
"filename": "notice-a.txt",
|
||||
"source_type": "manual",
|
||||
"source_file_type": "text/plain",
|
||||
"text_length": len("客户:ACME\nA001 x 10"),
|
||||
"warnings": [],
|
||||
}
|
||||
],
|
||||
"rejected_files": [],
|
||||
}
|
||||
file_summary = result["file_summary"]
|
||||
assert file_summary["total_files"] == 1
|
||||
assert file_summary["accepted_count"] == 1
|
||||
assert file_summary["rejected_count"] == 0
|
||||
assert file_summary["duplicate_count"] == 0
|
||||
assert file_summary["accepted_files"][0]["filename"] == "notice-a.txt"
|
||||
assert len(file_summary["accepted_files"][0]["content_hash"]) == 64
|
||||
assert file_summary["rejected_files"] == []
|
||||
assert file_summary["duplicate_files"] == []
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
|
||||
@@ -506,7 +501,11 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
|
||||
payload = res.get_json()
|
||||
assert payload["success"] is False
|
||||
assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试"
|
||||
assert payload["error"]["details"]["file_summary"]["rejected_files"] == [
|
||||
file_summary = payload["error"]["details"]["file_summary"]
|
||||
assert file_summary["accepted_count"] == 0
|
||||
assert file_summary["rejected_count"] == 1
|
||||
assert file_summary["duplicate_count"] == 1
|
||||
assert file_summary["rejected_files"] == [
|
||||
{
|
||||
"filename": "notice-a.pdf",
|
||||
"source_type": "pdf",
|
||||
@@ -515,17 +514,9 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
|
||||
"message": "notice text is empty after extraction",
|
||||
"warnings": ["ocr_empty"],
|
||||
},
|
||||
{
|
||||
"filename": "notice-b.pdf",
|
||||
"source_type": "pdf",
|
||||
"source_file_type": "application/pdf",
|
||||
"reason": "empty_text",
|
||||
"message": "notice text is empty after extraction",
|
||||
"warnings": ["ocr_empty"],
|
||||
},
|
||||
]
|
||||
assert payload["error"]["details"]["file_summary"]["accepted_count"] == 0
|
||||
assert payload["error"]["details"]["file_summary"]["rejected_count"] == 2
|
||||
assert file_summary["duplicate_files"][0]["filename"] == "notice-b.pdf"
|
||||
assert file_summary["duplicate_files"][0]["duplicate_of"] == "notice-a.pdf"
|
||||
|
||||
with app.app_context():
|
||||
assert ShippingBatch.query.count() == batch_count_before
|
||||
@@ -655,6 +646,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 +732,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 +785,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 +814,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
|
||||
@@ -902,6 +894,43 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
|
||||
]
|
||||
|
||||
|
||||
def test_parse_stage_ui_state_lists_all_issues(app):
|
||||
"""文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。"""
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-PARSE-ISSUES-LIST",
|
||||
source_type="pdf",
|
||||
process_status="pending_review",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
error_message="无法根据发货通知唯一确定库存查询来源",
|
||||
parse_confidence=0.4,
|
||||
step_payload_json={
|
||||
"pending_parse_review_after_source": True,
|
||||
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
|
||||
"current_step_progress": {
|
||||
"extra": {
|
||||
"warnings": [
|
||||
"部分订单行缺少 Reservation ID,可能影响精确匹配。",
|
||||
"parse_fallback_heuristic",
|
||||
]
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
ui_state = build_task_ui_state(task)
|
||||
issues = ui_state["summary"]["issues"]
|
||||
|
||||
assert ui_state["checkpoint"] == "inventory_source_review"
|
||||
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
|
||||
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
|
||||
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
|
||||
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
|
||||
assert len(issues) == 4
|
||||
|
||||
|
||||
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
|
||||
"""任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。"""
|
||||
headers = _workspace_headers(app)
|
||||
@@ -1447,6 +1476,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,
|
||||
)
|
||||
@@ -1655,3 +1685,229 @@ def test_create_empty_batch_returns_batch_shell(app, client):
|
||||
assert data["status"] == "ok"
|
||||
assert data["batch_no"].startswith("SB-")
|
||||
assert data["data"]["file_count"] == 1
|
||||
|
||||
|
||||
def _workspace_user_headers(app, username: str):
|
||||
"""创建独立工作台用户并返回 Authorization header。"""
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
user_id = user.id
|
||||
return {"Authorization": f"Bearer {token}"}, user_id
|
||||
|
||||
|
||||
def test_create_batch_idempotency_key_replays_same_batch(app, client, monkeypatch):
|
||||
"""相同建单幂等键调用两次只创建一个批次,第二次不启动编排器。"""
|
||||
headers = _workspace_headers(app)
|
||||
idempotency_key = "batch-idem-001"
|
||||
started: list[str] = []
|
||||
|
||||
def fake_start(batch_no: str | None) -> bool:
|
||||
if batch_no:
|
||||
started.append(batch_no)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
|
||||
def _payload():
|
||||
return {
|
||||
"files": (BytesIO(raw), "notice-a.txt"),
|
||||
"conversation_id": "conv-idem-001",
|
||||
"idempotency_key": idempotency_key,
|
||||
}
|
||||
|
||||
first = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
second = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
first_result = _unwrap_ok(first)
|
||||
second_result = _unwrap_ok(second)
|
||||
assert first_result["batch_no"] == second_result["batch_no"]
|
||||
assert second_result.get("idempotent_replay") is True
|
||||
assert second_result["data"]["orchestrator_started"] is False
|
||||
assert started == [first_result["batch_no"]]
|
||||
|
||||
with app.app_context():
|
||||
batch_count = ShippingBatch.query.filter_by(create_idempotency_key=idempotency_key).count()
|
||||
task_count = ShippingTask.query.filter_by(batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id).count()
|
||||
assert batch_count == 1
|
||||
assert task_count == 1
|
||||
|
||||
|
||||
def test_create_batch_same_request_duplicate_files_create_one_task(app, client):
|
||||
"""同一次上传两个内容相同文件只创建一个任务。"""
|
||||
headers = _workspace_headers(app)
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
res = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers=headers,
|
||||
data={
|
||||
"files": [
|
||||
(BytesIO(raw), "notice-a.txt"),
|
||||
(BytesIO(raw), "notice-b.txt"),
|
||||
],
|
||||
"conversation_id": "conv-dedupe-files",
|
||||
"idempotency_key": "batch-dedupe-files-001",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
result = _unwrap_ok(res)
|
||||
assert result["file_summary"]["duplicate_count"] == 1
|
||||
assert len(result["data"]["tasks"]) == 1
|
||||
|
||||
|
||||
def test_create_batch_persists_source_content_hash(app, client):
|
||||
"""建单后任务应保存完整 SHA-256 内容哈希。"""
|
||||
import hashlib
|
||||
|
||||
headers = _workspace_headers(app)
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
res = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers=headers,
|
||||
data={
|
||||
"files": (BytesIO(raw), "notice-a.txt"),
|
||||
"conversation_id": "conv-hash-persist",
|
||||
"idempotency_key": "batch-hash-persist-001",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
result = _unwrap_ok(res)
|
||||
expected_hash = hashlib.sha256(raw).hexdigest().lower()
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
|
||||
assert task is not None
|
||||
assert task.source_content_hash == expected_hash
|
||||
|
||||
|
||||
def test_create_batch_idempotency_key_scoped_per_user(app, client):
|
||||
"""不同用户使用相同幂等键互不冲突。"""
|
||||
headers_a, _user_a = _workspace_user_headers(app, "shipping_idem_user_a")
|
||||
headers_b, _user_b = _workspace_user_headers(app, "shipping_idem_user_b")
|
||||
idempotency_key = "shared-idem-key"
|
||||
|
||||
def _payload():
|
||||
return {
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"idempotency_key": idempotency_key,
|
||||
}
|
||||
|
||||
res_a = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers_a, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
res_b = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers_b, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
batch_a = _unwrap_ok(res_a)["batch_no"]
|
||||
batch_b = _unwrap_ok(res_b)["batch_no"]
|
||||
assert batch_a != batch_b
|
||||
|
||||
|
||||
def test_create_batch_without_idempotency_key_still_works(app, client):
|
||||
"""兼容期:缺少幂等键的旧请求仍可建批。"""
|
||||
headers = _workspace_headers(app)
|
||||
res = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers=headers,
|
||||
data={
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"conversation_id": "conv-legacy-no-idem",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
result = _unwrap_ok(res)
|
||||
assert result["batch_no"].startswith("SB-")
|
||||
|
||||
|
||||
def test_create_batch_idempotency_replays_after_tasks_exist(app, client):
|
||||
"""相同幂等键在首批任务已落库后应幂等重放,而非返回文件重复错误。"""
|
||||
headers = _workspace_headers(app)
|
||||
idempotency_key = "batch-idem-after-tasks"
|
||||
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
||||
|
||||
def _payload():
|
||||
return {
|
||||
"files": (BytesIO(raw), "notice-a.txt"),
|
||||
"conversation_id": "conv-idem-after-tasks",
|
||||
"idempotency_key": idempotency_key,
|
||||
}
|
||||
|
||||
first = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
second = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data=_payload(),
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
first_result = _unwrap_ok(first)
|
||||
second_result = _unwrap_ok(second)
|
||||
assert second_result.get("idempotent_replay") is True
|
||||
assert first_result["batch_no"] == second_result["batch_no"]
|
||||
|
||||
with app.app_context():
|
||||
task_count = ShippingTask.query.filter_by(
|
||||
batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id
|
||||
).count()
|
||||
assert task_count == 1
|
||||
|
||||
|
||||
def test_create_batch_idempotency_key_conflicts_on_different_files(app, client):
|
||||
"""相同幂等键但文件集合不同时应返回 SHIPPING.BATCH_IDEMPOTENCY_CONFLICT。"""
|
||||
headers = _workspace_headers(app)
|
||||
idempotency_key = "batch-idem-conflict-001"
|
||||
first = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data={
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"idempotency_key": idempotency_key,
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert first.status_code == 200
|
||||
|
||||
second = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
data={
|
||||
"files": (BytesIO("客户:BETA\nB002 x 20".encode("utf-8")), "notice-b.txt"),
|
||||
"idempotency_key": idempotency_key,
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert second.status_code == 409
|
||||
payload = second.get_json()
|
||||
assert payload["success"] is False
|
||||
assert payload["error"]["code"] == "SHIPPING.BATCH_IDEMPOTENCY_CONFLICT"
|
||||
@@ -0,0 +1,750 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_business_dedup.py
|
||||
|
||||
用途:第三阶段业务指纹、重复检测与决策门闩核心用例。
|
||||
依赖:pytest、business_fingerprint、duplicate_detection、batch_from_intakes。
|
||||
逻辑:覆盖指纹稳定性、阻断门闩、open_existing / create_revision 分流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingBatch,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
detect_duplicates_for_candidate,
|
||||
detect_duplicates_for_intake,
|
||||
)
|
||||
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dedup_user(app):
|
||||
with app.app_context():
|
||||
user = User(username='dedup-user', email='dedup@example.com', password_hash='x', role='user')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
yield user
|
||||
|
||||
|
||||
def _seed_parsed_intake(
|
||||
user_id: int,
|
||||
*,
|
||||
intake_no: str,
|
||||
hash_value: str,
|
||||
business_summary: dict,
|
||||
fingerprint: dict,
|
||||
):
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{intake_no}',
|
||||
owner_user_id=user_id,
|
||||
original_filename='notice.txt',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
|
||||
content_hash=hash_value,
|
||||
file_size=12,
|
||||
mime_type='text/plain',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=intake_no,
|
||||
asset_id=asset.id,
|
||||
user_id=user_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v1',
|
||||
extracted_text='SKU001 qty 10',
|
||||
structured_result_json={'business_summary': business_summary},
|
||||
business_fingerprint=fingerprint.get('fingerprint'),
|
||||
fingerprint_version=fingerprint.get('version'),
|
||||
fingerprint_strength=fingerprint.get('strength'),
|
||||
duplicate_status='none',
|
||||
duplicate_matches_json=[],
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
return asset, intake
|
||||
|
||||
|
||||
def test_fingerprint_stable_across_line_order():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
|
||||
'required_date': '2026-01-01',
|
||||
'lines': [
|
||||
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
|
||||
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
|
||||
],
|
||||
}
|
||||
swapped = {
|
||||
**base,
|
||||
'lines': [
|
||||
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
|
||||
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
|
||||
],
|
||||
}
|
||||
a = build_business_fingerprint(base)
|
||||
b = build_business_fingerprint(swapped)
|
||||
assert a['strength'] == 'medium'
|
||||
assert a['fingerprint'] == b['fingerprint']
|
||||
|
||||
|
||||
def test_fingerprint_changes_with_qty():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
|
||||
'required_date': '2026-01-01',
|
||||
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
|
||||
}
|
||||
changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
|
||||
assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
|
||||
|
||||
|
||||
def test_blocking_create_requires_resolution(app, dedup_user):
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-9',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-DEDUP-BLOCK',
|
||||
hash_value='hash-block-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
batch = ShippingBatch(batch_no='SB-DEDUP-OLD', user_id=dedup_user.id, file_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
existing = ShippingTask(
|
||||
task_no='SN-DEDUP-OLD',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
result = detect_duplicates_for_intake(intake=intake, asset=asset, business_summary=summary, fingerprint_result=fp)
|
||||
assert result['blocking'] is True
|
||||
assert result['status'] == 'same_active_task'
|
||||
|
||||
with pytest.raises(ConflictError) as excinfo:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-dedup',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-block',
|
||||
)
|
||||
assert excinfo.value.code == 'SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED'
|
||||
|
||||
|
||||
def test_open_existing_does_not_create_batch(app, dedup_user):
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-OPEN',
|
||||
'reservation_ids': ['1000140352'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-DEDUP-OPEN',
|
||||
hash_value='hash-open-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
batch = ShippingBatch(batch_no='SB-OPEN-OLD', user_id=dedup_user.id, file_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
existing = ShippingTask(
|
||||
task_no='SN-OPEN-OLD',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
# 模拟前端已决策:写入 resolution,避免 resolve 内 refresh 对 SQLite 时间敏感
|
||||
intake.duplicate_status = 'same_active_task'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': existing.process_status,
|
||||
'document_version': 1,
|
||||
'match_type': 'business_fingerprint',
|
||||
'matched_fields': ['customer_code', 'po_number'],
|
||||
'lifecycle': 'active',
|
||||
}
|
||||
]
|
||||
intake.duplicate_resolution = 'open_existing'
|
||||
intake.duplicate_target_task_no = existing.task_no
|
||||
intake.duplicate_resolved_by_id = dedup_user.id
|
||||
intake.duplicate_resolved_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items'
|
||||
) as create_mock:
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-open',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-open',
|
||||
)
|
||||
create_mock.assert_not_called()
|
||||
|
||||
assert result.get('batch_no') in (None, '')
|
||||
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
|
||||
assert refreshed.parse_status == 'consumed'
|
||||
assert refreshed.consumed_task_id == existing.id
|
||||
|
||||
|
||||
def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatch):
|
||||
"""create_revision 应写入 supersedes_task_id 与 document_version+1。"""
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-REV-1',
|
||||
'reservation_ids': ['12345678'],
|
||||
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-REV-1',
|
||||
hash_value='hash-rev-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-REV-BASE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
intake.duplicate_status = 'same_completed_task'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': 'uploaded',
|
||||
'document_version': 1,
|
||||
'match_type': 'business_fingerprint',
|
||||
'matched_fields': ['customer_code', 'po_number'],
|
||||
}
|
||||
]
|
||||
intake.duplicate_resolution = 'create_revision'
|
||||
intake.duplicate_target_task_no = existing.task_no
|
||||
intake.duplicate_resolved_by_id = dedup_user.id
|
||||
intake.duplicate_resolved_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
notice_items = kwargs['notice_items']
|
||||
item = notice_items[0]
|
||||
batch = ShippingBatch(
|
||||
batch_no='SB-REV-1',
|
||||
user_id=dedup_user.id,
|
||||
file_count=1,
|
||||
create_idempotency_key=kwargs.get('create_idempotency_key'),
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no='SN-REV-NEW',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
source_content_hash=item.get('source_content_hash'),
|
||||
source_asset_id=item.get('source_asset_id'),
|
||||
source_intake_id=item.get('source_intake_id'),
|
||||
business_fingerprint=item.get('business_fingerprint'),
|
||||
fingerprint_version=item.get('fingerprint_version'),
|
||||
document_version=int(item.get('document_version') or 1),
|
||||
supersedes_task_id=item.get('supersedes_task_id'),
|
||||
duplicate_resolution_type=item.get('duplicate_resolution_type'),
|
||||
raw_content=item.get('raw_text'),
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'batch_no': batch.batch_no,
|
||||
'data': {
|
||||
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
|
||||
'tasks': [{'task_id': task.task_no}],
|
||||
'focus_task': {
|
||||
'task_no': task.task_no,
|
||||
'document_version': task.document_version,
|
||||
'duplicate_resolution_type': task.duplicate_resolution_type,
|
||||
'supersedes_task_no': existing.task_no,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
|
||||
_fake_create,
|
||||
)
|
||||
# 确保 detect 仍命中
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
|
||||
lambda **kwargs: {
|
||||
'status': 'same_completed_task',
|
||||
'blocking': True,
|
||||
'fingerprint': fp.get('fingerprint'),
|
||||
'fingerprint_version': fp.get('version'),
|
||||
'fingerprint_strength': fp.get('strength'),
|
||||
'matches': intake.duplicate_matches_json,
|
||||
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
|
||||
},
|
||||
)
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-rev',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-rev',
|
||||
)
|
||||
assert result['batch_no'] == 'SB-REV-1'
|
||||
created = db.session.query(ShippingTask).filter_by(task_no='SN-REV-NEW').one()
|
||||
assert created.supersedes_task_id == existing.id
|
||||
assert int(created.document_version) == 2
|
||||
assert created.duplicate_resolution_type == 'revision'
|
||||
|
||||
|
||||
def test_fingerprint_strong_with_customer_name_po_reservation():
|
||||
"""启发式常只有客户名:客户名 + PO + Reservation 应产出 strong 指纹。"""
|
||||
summary = {
|
||||
'customer_name': 'ACME',
|
||||
'customer_code': None,
|
||||
'po_number': 'PO-20260714',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
assert fp['strength'] == 'strong'
|
||||
assert fp['fingerprint']
|
||||
assert fp['components'].get('customer_name') == 'ACME'
|
||||
|
||||
|
||||
def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
"""pending_review 属活跃态:业务指纹命中应为 same_active_task 且 blocking。"""
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-PENDING',
|
||||
'reservation_ids': ['1000140399'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-PENDING-ACTIVE',
|
||||
hash_value='hash-pending-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-PENDING-1',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
result = detect_duplicates_for_intake(
|
||||
intake=intake,
|
||||
asset=asset,
|
||||
business_summary=summary,
|
||||
fingerprint_result=fp,
|
||||
)
|
||||
assert result['status'] == 'same_active_task'
|
||||
assert result['blocking'] is True
|
||||
|
||||
|
||||
def test_assert_no_exact_duplicate_allows_revision_and_force(app, dedup_user):
|
||||
"""revision/force_create 可越过同 content_hash 的旧门闩;无决议仍阻断。"""
|
||||
from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices
|
||||
|
||||
with app.app_context():
|
||||
existing = ShippingTask(
|
||||
task_no='SN-HASH-GATE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
source_content_hash='samehashabc',
|
||||
process_status='pending_review',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
'duplicate_resolution_type': 'revision',
|
||||
}
|
||||
],
|
||||
)
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
'duplicate_resolution_type': 'force_create',
|
||||
}
|
||||
],
|
||||
)
|
||||
with pytest.raises(ConflictError) as excinfo:
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
}
|
||||
],
|
||||
)
|
||||
assert excinfo.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
|
||||
|
||||
|
||||
def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
|
||||
"""API 投影:possible_duplicate 必须 blocking,供前端弹窗确认。"""
|
||||
from app.services.shipping_notice.intake_service import serialize_intake
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-POSSIBLE-1',
|
||||
hash_value='hash-possible-1',
|
||||
business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]},
|
||||
fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'},
|
||||
)
|
||||
intake.duplicate_status = 'possible_duplicate'
|
||||
intake.fingerprint_strength = 'weak'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': 'SN-OLD',
|
||||
'process_status': 'waiting_inventory',
|
||||
'document_version': 1,
|
||||
'match_type': 'weak_fingerprint',
|
||||
'matched_fields': ['line_digest'],
|
||||
}
|
||||
]
|
||||
db.session.commit()
|
||||
payload = serialize_intake(intake, asset=asset)
|
||||
assert payload['duplicate']['status'] == 'possible_duplicate'
|
||||
assert payload['duplicate']['blocking'] is True
|
||||
assert 'force_create' in payload['duplicate']['allowed_actions']
|
||||
|
||||
|
||||
def test_task_summary_includes_version_chain(app, dedup_user):
|
||||
"""query_service SUMMARY 须暴露版本链与 duplicate 决策字段。"""
|
||||
from app.services.shipping_notice.query_service import TaskProjection, serialize_task
|
||||
|
||||
with app.app_context():
|
||||
base = ShippingTask(
|
||||
task_no='SN-VER-BASE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(base)
|
||||
db.session.flush()
|
||||
rev = ShippingTask(
|
||||
task_no='SN-VER-REV',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
document_version=2,
|
||||
supersedes_task_id=base.id,
|
||||
duplicate_resolution_type='revision',
|
||||
duplicate_source_task_id=base.id,
|
||||
duplicate_override_reason=None,
|
||||
business_fingerprint='fp-x',
|
||||
fingerprint_version='shipping-v1',
|
||||
)
|
||||
db.session.add(rev)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task(rev, TaskProjection.SUMMARY)
|
||||
assert data['document_version'] == 2
|
||||
assert data['supersedes_task_no'] == 'SN-VER-BASE'
|
||||
assert data['duplicate_source_task_no'] == 'SN-VER-BASE'
|
||||
assert data['duplicate_resolution_type'] == 'revision'
|
||||
assert data['business_fingerprint'] == 'fp-x'
|
||||
|
||||
base_data = serialize_task(base, TaskProjection.SUMMARY)
|
||||
assert base_data['superseded_by_task_no'] == 'SN-VER-REV'
|
||||
|
||||
|
||||
def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
"""
|
||||
阶段二:同一邮件中候选 A 与已有任务重复时,仅 A 被阻断;B/C 仍可为 none。
|
||||
"""
|
||||
with app.app_context():
|
||||
existing_fp = build_business_fingerprint(
|
||||
{
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-EXISTING-PO-A',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-other-file',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-STAGE2-DEDUP-EML',
|
||||
owner_user_id=dedup_user.id,
|
||||
original_filename='multi.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{dedup_user.id}/stage2.eml',
|
||||
content_hash='eml-parent-hash',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
asset_role='upload',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-STAGE2-DEDUP',
|
||||
asset_id=parent.id,
|
||||
user_id=dedup_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='multi',
|
||||
duplicate_status='unchecked',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
docs = []
|
||||
for idx, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
|
||||
doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key=f'att-00{idx}',
|
||||
document_type='attachment',
|
||||
filename=f'{po}.pdf',
|
||||
content_hash=f'pdf-hash-{po}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO {po}',
|
||||
)
|
||||
db.session.add(doc)
|
||||
docs.append(doc)
|
||||
db.session.flush()
|
||||
|
||||
results = []
|
||||
for doc, po in zip(docs, ('4510039227', '4510039228', '4510039229')):
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': po,
|
||||
'reservation_ids': ['1000140351'] if po == '4510039227' else [],
|
||||
'lines': [],
|
||||
}
|
||||
if po != '4510039227':
|
||||
summary['reservation_ids'] = [f'100014035{po[-1]}']
|
||||
fp = build_business_fingerprint(summary)
|
||||
dup = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
document=doc,
|
||||
business_summary=summary,
|
||||
fingerprint_result=fp,
|
||||
)
|
||||
cand = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-{po}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
po_number=po,
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
fingerprint_strength=fp.get('strength'),
|
||||
duplicate_status=str(dup.get('status') or 'none'),
|
||||
duplicate_matches_json=list(dup.get('matches') or []),
|
||||
selected=True,
|
||||
validation_status='pending',
|
||||
)
|
||||
db.session.add(cand)
|
||||
results.append(dup)
|
||||
db.session.commit()
|
||||
|
||||
assert results[0]['blocking'] is True
|
||||
assert results[0]['status'] in {'same_active_task', 'exact_file', 'possible_duplicate'}
|
||||
assert results[1]['blocking'] is False
|
||||
assert results[1]['status'] == 'none'
|
||||
assert results[2]['blocking'] is False
|
||||
assert results[2]['status'] == 'none'
|
||||
|
||||
refreshed = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter_by(intake_id=intake.id)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
assert refreshed[0].duplicate_status != 'none'
|
||||
assert refreshed[1].duplicate_status == 'none'
|
||||
assert refreshed[2].duplicate_status == 'none'
|
||||
|
||||
|
||||
def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
"""刷新重复检测须重写各 Candidate.duplicate_status,再聚合到 Intake。"""
|
||||
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||
|
||||
with app.app_context():
|
||||
existing_fp = build_business_fingerprint(
|
||||
{
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510099999',
|
||||
'reservation_ids': ['1000199999'],
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-REFRESH-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-refresh-other',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-REFRESH-DEDUP',
|
||||
owner_user_id=dedup_user.id,
|
||||
original_filename='refresh.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{dedup_user.id}/refresh.eml',
|
||||
content_hash='eml-refresh-hash',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
asset_role='upload',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-REFRESH-DEDUP',
|
||||
asset_id=parent.id,
|
||||
user_id=dedup_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='refresh',
|
||||
duplicate_status='none',
|
||||
structured_result_json={'business_summary': {'customer_code': 'C1'}},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510099999',
|
||||
'reservation_ids': ['1000199999'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key='att-001',
|
||||
document_type='attachment',
|
||||
filename='dup.pdf',
|
||||
content_hash='pdf-refresh-1',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 4510099999',
|
||||
)
|
||||
db.session.add(doc)
|
||||
db.session.flush()
|
||||
cand = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-REFRESH-1',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
po_number='4510099999',
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
fingerprint_strength=fp.get('strength'),
|
||||
# 模拟解析后任务尚未存在时的旧结果;刷新时应变为阻断
|
||||
duplicate_status='none',
|
||||
duplicate_matches_json=[],
|
||||
selected=True,
|
||||
validation_status='pending',
|
||||
)
|
||||
db.session.add(cand)
|
||||
db.session.commit()
|
||||
|
||||
payload = refresh_intake_duplicate_detection(
|
||||
user_id=dedup_user.id,
|
||||
intake_no='SNI-REFRESH-DEDUP',
|
||||
)
|
||||
assert payload['duplicate']['blocking'] is True
|
||||
db.session.expire_all()
|
||||
cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
|
||||
assert cand2.duplicate_status != 'none'
|
||||
assert list(cand2.duplicate_matches_json or [])
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user