feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理

This commit is contained in:
hugo committed 2026-06-17 20:45:19 +08:00
1 parent 457f0f4e5e
commit 634dee4b81
81 files changed
+9088 -3625

No files matched your search

+18
View File
@@ -17,6 +17,24 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env')
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
if request.node.get_closest_marker("auto_rpa"):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
def pytest_configure(config):
config.addinivalue_line(
"markers",
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
)
@pytest.fixture
def app():
from app import create_app, db
@@ -0,0 +1,109 @@
"""shipping_notice batch tests.
覆盖 batch 新增能力的最小闭环:
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。
"""
from app.models import ShippingBatch, ShippingTask
def _tool_headers():
return {
"Content-Type": "application/json",
}
def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"source_type": "manual",
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
{
"source_file_name": "notice-b.txt",
"raw_text": "客户:Wistron 料号B002 x 5",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "B002", "reservation_id": "R-2", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
],
},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
batch = create_data["data"]["batch"]
tasks = create_data["data"]["tasks"]
batch_no = batch["batch_no"]
assert batch_no.startswith("SB-")
assert len(tasks) == 2
assert batch["current_focus_task_no"] == tasks[0]["task_id"]
assert batch["process_summary"]["total"] == 2
status_res = client.post(
"/api/shipping-notice/tools/get_batch_status",
headers=headers,
json={"batch_no": batch_no},
)
assert status_res.status_code == 200
status_data = status_res.get_json()
assert status_data["status"] == "ok"
assert status_data["data"]["batch_no"] == batch_no
assert len(status_data["data"]["tasks"]) == 2
assert status_data["data"]["focus_task"] is None
assert status_data["data"]["tasks"][0]["task_no"] == tasks[0]["task_id"]
target_task_no = tasks[1]["task_id"]
switch_res = client.post(
"/api/shipping-notice/tools/switch_focus_task",
headers=headers,
json={"batch_no": batch_no, "task_no": target_task_no},
)
assert switch_res.status_code == 200
switch_data = switch_res.get_json()
assert switch_data["status"] == "ok"
assert switch_data["task_no"] == target_task_no
assert switch_data["data"]["batch"]["current_focus_task_no"] == target_task_no
assert switch_data["data"]["focus_task"]["task_no"] == target_task_no
with app.app_context():
batch_row = ShippingBatch.query.filter_by(batch_no=batch_no).first()
task_rows = ShippingTask.query.filter_by(batch_id=batch_row.id).order_by(ShippingTask.batch_index.asc()).all()
assert batch_row is not None
assert len(task_rows) == 2
assert batch_row.current_focus_task_no == target_task_no
assert task_rows[0].batch_total == 2
assert task_rows[1].batch_total == 2
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers()
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"file_count": 1},
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["file_count"] == 1
@@ -0,0 +1,101 @@
"""shipping_notice inventory_rpa_workflow 单测。
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。
2. rpa_report_inventory 回调落盘后进入字段映射确认。
"""
from app.models import ShippingTask, ShippingTaskEvent
def _tool_headers():
return {"Content-Type": "application/json"}
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
"""mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。"""
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "mode": "auto"},
)
body = inv_res.get_json()
assert body["status"] == "running"
assert body.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered")
.all()
)
assert len(events) == 1
def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path):
"""RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。"""
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["料号", "Reservation ID", "可用数量"])
ws.append(["A001", "R-1", 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)},
)
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") in {"align_review", "map_infer"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
@@ -38,4 +38,4 @@ def test_format_match_summary_shortage():
)
assert "| R-1 | A001 | 100 | 5 | 95 |" in msg
assert "⚠️ 部分满足" in msg
assert "部分行库存不足" in msg
assert "存在库存缺口" in msg
@@ -0,0 +1,179 @@
"""shipping_notice query_service 读路径单测。"""
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.query_service import (
BatchProjection,
TaskProjection,
compute_batch_process_summary,
extract_task_no_from_text,
get_task_by_ref,
get_task_in_batch,
list_batch_task_summaries,
resolve_task_from_payload,
serialize_batch,
serialize_task,
sort_batch_tasks,
task_export_error_message,
task_sort_key,
)
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。"""
with app.app_context():
task = ShippingTask(
task_no="SN-TEST-QUERY-001",
process_status="created",
source_type="manual",
)
from app import db
db.session.add(task)
db.session.commit()
by_no = get_task_by_ref("SN-TEST-QUERY-001")
by_id = get_task_by_ref(str(task.id))
assert by_no is not None
assert by_id is not None
assert by_no.id == by_id.id
def test_sort_batch_tasks_orders_by_batch_index_then_created_at(app):
"""批次内排序应与 batch_index、created_at 规则一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-TEST-SORT", file_count=2)
second = ShippingTask(task_no="SN-SORT-2", batch_index=2, process_status="created", source_type="manual")
first = ShippingTask(task_no="SN-SORT-1", batch_index=1, process_status="created", source_type="manual")
from app import db
db.session.add(batch)
db.session.flush()
second.batch_id = batch.id
first.batch_id = batch.id
db.session.add_all([first, second])
db.session.commit()
ordered = sort_batch_tasks([second, first])
assert [item.task_no for item in ordered] == ["SN-SORT-1", "SN-SORT-2"]
assert task_sort_key(first) < task_sort_key(second)
summaries = list_batch_task_summaries(batch)
assert [row["task_no"] for row in summaries] == ["SN-SORT-1", "SN-SORT-2"]
def test_get_task_in_batch_rejects_foreign_task(app):
"""不属于目标批次的任务应返回 None。"""
with app.app_context():
batch_a = ShippingBatch(batch_no="SB-A", file_count=1)
batch_b = ShippingBatch(batch_no="SB-B", file_count=1)
task = ShippingTask(task_no="SN-FOREIGN", process_status="created", source_type="manual")
from app import db
db.session.add_all([batch_a, batch_b])
db.session.flush()
task.batch_id = batch_a.id
db.session.add(task)
db.session.commit()
assert get_task_in_batch("SB-A", "SN-FOREIGN") is not None
assert get_task_in_batch("SB-B", "SN-FOREIGN") is None
def test_task_export_error_message_distinct_for_missing_path(app):
"""无导出路径与磁盘缺失应返回不同错误文案。"""
with app.app_context():
empty = ShippingTask(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
assert task_export_error_message(empty) == "export file not found"
missing = ShippingTask(
task_no="SN-MISSING-FILE",
process_status="matched",
source_type="manual",
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
)
assert task_export_error_message(missing) == "export file missing on disk"
def test_task_projection_tool_strips_internal_fields(app):
"""TOOL 投影应剔除 Agent 不应复述的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task_no="SN-PROJ-TOOL",
process_status="waiting_inventory",
review_status="align_review",
match_status="pending",
pending_human_reason="rpa_pending",
error_message="boom",
source_type="manual",
customer_name="ACME",
lines_json=[{"sku": "A001"}],
)
data = serialize_task(task, TaskProjection.TOOL)
assert data["task_no"] == "SN-PROJ-TOOL"
assert data["customer_name"] == "ACME"
assert data["lines"] == [{"sku": "A001"}]
assert not TOOL_TASK_DATA_OMIT.intersection(data.keys())
def test_task_projection_internal_keeps_status_fields(app):
"""TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task_no="SN-PROJ-INT",
process_status="parsed",
review_status="parse_review",
source_type="manual",
)
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
assert data["process_status"] == "parsed"
assert data["review_status"] == "parse_review"
def test_batch_process_summary_shared_formula(app):
"""批次汇总公式在 serialize_batch 与 compute_batch_process_summary 间应一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-SUMMARY", file_count=2)
done = ShippingTask(task_no="SN-DONE", process_status="uploaded", source_type="manual", batch_index=1)
running = ShippingTask(task_no="SN-RUN", process_status="matched", source_type="manual", batch_index=2)
from app import db
db.session.add(batch)
db.session.flush()
done.batch_id = batch.id
running.batch_id = batch.id
db.session.add_all([done, running])
db.session.commit()
tasks = [done, running]
assert compute_batch_process_summary(tasks) == {
"total": 2,
"completed": 1,
"failed": 0,
"running": 1,
}
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
assert tool_batch["process_summary"]["completed"] == 1
assert tool_batch["batch_no"] == "SB-SUMMARY"
assert "id" not in tool_batch
def test_resolve_task_from_payload_by_conversation_id(app):
"""conversation_id 应能解析到最近非 rejected 任务。"""
with app.app_context():
task = ShippingTask(
task_no="SN-CONV-1",
conversation_id="conv-abc",
process_status="parsed",
source_type="manual",
)
from app import db
db.session.add(task)
db.session.commit()
resolved = resolve_task_from_payload({"conversation_id": "conv-abc"})
assert resolved is not None
assert resolved.task_no == "SN-CONV-1"
assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01"
+31 -17
View File
@@ -1,3 +1,5 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
@@ -35,7 +37,7 @@ def test_shipping_notice_tool_flow(app, client):
)
assert parse_res.status_code == 200
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert parse_body["status"] in {"ok", "needs_human", "running"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
@@ -121,14 +123,17 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
assert "confirm" in (data.get("human_options") or [])
options = data.get("human_options") or []
assert "confirm" not in options
assert "reparse_inventory" in options
assert "rematch" in options
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "ok"
assert confirm_res.get_json()["status"] == "failed"
def test_openapi_spec_public(app, client):
@@ -178,7 +183,7 @@ def test_parse_inventory_from_chat_text(app, client):
assert parse_inv.status_code == 200
data = parse_inv.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_field_mapping_review"
assert data.get("checkpoint") == "align_review"
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
@@ -190,7 +195,7 @@ def test_parse_inventory_from_chat_text(app, client):
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "inventory_field_mapping_review"
assert confirm_data.get("checkpoint") == "align_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
@@ -215,7 +220,9 @@ def test_parse_inventory_empty_needs_human(app, client):
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
body = res.get_json()
assert body.get("checkpoint") in {"map_infer", "upload_req"}
assert body.get("human_options") is not None or body.get("action_buttons")
def test_match_by_aws_sku_and_reservation_id(app, client):
@@ -308,7 +315,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
assert blocked.get("checkpoint") == "inventory_field_mapping_review"
assert blocked.get("checkpoint") == "align_review"
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
@@ -352,7 +359,7 @@ def test_match_inventory_requires_reservation_id(app, client):
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "reservation_id_required"
assert data.get("checkpoint") == "rsv_req"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
@@ -393,8 +400,9 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
assert data.get("checkpoint") == "inventory_mapping_inference"
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "map_infer"
assert data.get("stop_agent_turn") is True
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
@@ -433,8 +441,12 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
assert cb_res.status_code == 200
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data["data"]["process_status"] == "inventory_ready"
assert data.get("checkpoint") in {"map_infer", "align_review"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
def test_rpa_upload_callback(app, client, tmp_path):
@@ -614,7 +626,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_res.status_code == 200
upload_data = upload_res.get_json()
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "inventory_mapping_inference"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
@@ -632,7 +644,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "inventory_field_mapping_review"
assert apply_data.get("checkpoint") == "align_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
@@ -704,7 +716,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
headers=headers,
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
assert missing.get_json()["checkpoint"] == "upload_req"
def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
@@ -751,7 +763,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["available_qty"] == 12
@@ -804,6 +816,7 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
headers = _tool_headers(app)
@@ -832,6 +845,7 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
assert parse_data.get("checkpoint") != "parse_review"
@pytest.mark.auto_rpa
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path):
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
@@ -909,7 +923,7 @@ def test_submit_decision_by_conversation_id(app, client):
)
dup_data = dup_res.get_json()
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_already_exists"
assert dup_data.get("checkpoint") == "task_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
@@ -930,7 +944,7 @@ def test_parse_inventory_rejects_oversized_text(app, client):
)
data = res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_upload_required"
assert data.get("checkpoint") == "upload_req"
assert "过大" in data["message"]