Files
syops/backend/tests/test_shipping_notice_query_service.py
T

652 lines
25 KiB
Python

"""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_tasks_for_user,
list_tasks_page_for_user,
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_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
"""库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。"""
with app.app_context():
from app import db
shortage = ShippingTask(
task_no="SN-FILTER-SHORTAGE",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
)
ordinary = ShippingTask(
task_no="SN-FILTER-PARSE",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
)
db.session.add_all([shortage, ordinary])
db.session.commit()
rows = list_tasks_for_user(999999, process_status="shortage_review")
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
"""分页必须由数据库排序、计数后切片,不能把固定上限结果伪装成分页。"""
with app.app_context():
from app import db
db.session.add_all([
ShippingTask(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
for index in range(1, 6)
])
db.session.commit()
first_page = list_tasks_page_for_user(999999, page=1, page_size=2)
second_page = list_tasks_page_for_user(999999, page=2, page_size=2)
# 关键断言:总数独立于每页大小,页面之间不重叠且均不超过 page_size。
assert first_page["total"] == 5
assert first_page["page"] == 1
assert len(first_page["items"]) == 2
assert second_page["total"] == 5
assert second_page["page"] == 2
assert len(second_page["items"]) == 2
assert {item["task_no"] for item in first_page["items"]}.isdisjoint(
{item["task_no"] for item in second_page["items"]}
)
def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
"""分页总数必须只统计当前状态筛选命中的任务。"""
with app.app_context():
from app import db
db.session.add_all([
ShippingTask(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
ShippingTask(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
ShippingTask(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
])
db.session.commit()
result = list_tasks_page_for_user(999999, process_status="created", page=1, page_size=10)
# 关键断言:uploaded 任务既不在 items 中,也不计入总数。
assert result["total"] == 2
assert {item["task_no"] for item in result["items"]} == {
"SN-PAGE-FILTER-1", "SN-PAGE-FILTER-2",
}
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 not found" # 未落库 Task 不具备 Artifact 身份。
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"] is None
assert data["lines"] == []
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]
summary = compute_batch_process_summary(tasks)
assert summary["total"] == 2
assert summary["completed"] == 1
assert summary["failed"] == 0
assert summary["running"] == 1
assert summary["pending"] == 2
assert summary["current_task_no"] == "SN-RUN"
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_single_active_task(app):
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
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"
def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
"""同一 conversation_id 下多票可操作任务时,禁止按最近一票静默回退。"""
with app.app_context():
from app import db
db.session.add_all(
[
ShippingTask(
task_no="SN-CONV-MULTI-1",
conversation_id="conv-multi",
process_status="parsed",
source_type="manual",
),
ShippingTask(
task_no="SN-CONV-MULTI-2",
conversation_id="conv-multi",
process_status="pending_review",
source_type="manual",
),
]
)
db.session.commit()
assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None
resolved = resolve_task_from_payload(
{"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"}
)
assert resolved is not None
assert resolved.task_no == "SN-CONV-MULTI-1"
def test_task_can_handle_only_creator(app):
"""仅创建者 can_handle;无主任务与非创建者均为 False。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import task_can_handle
owned = ShippingTask(
task_no="SN-HANDLE-OWN",
process_status="created",
source_type="manual",
user_id=42,
)
orphan = ShippingTask(
task_no="SN-HANDLE-ORPHAN",
process_status="created",
source_type="manual",
user_id=None,
)
db.session.add_all([owned, orphan])
db.session.commit()
assert task_can_handle(owned, 42) is True
assert task_can_handle(owned, 42, is_admin=True) is True
assert task_can_handle(owned, 99) is False
assert task_can_handle(owned, 99, is_admin=True) is False
assert task_can_handle(orphan, 42) is False
def test_get_task_for_user_rejects_null_owner(app):
"""写路径 get_task_for_user 拒绝 user_id IS NULL;管理员只读走 visible。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import (
get_task_for_user,
get_task_visible_to_user,
)
orphan = ShippingTask(
task_no="SN-NULL-OWNER",
process_status="created",
source_type="manual",
user_id=None,
)
owned = ShippingTask(
task_no="SN-OWNED",
process_status="created",
source_type="manual",
user_id=7,
)
db.session.add_all([orphan, owned])
db.session.commit()
assert get_task_for_user("SN-NULL-OWNER", 7) is None
assert get_task_for_user("SN-OWNED", 7) is not None
assert get_task_for_user("SN-OWNED", 8) is None
assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None
assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import serialize_task_summary
task = ShippingTask(
task_no="SN-ENRICH-1",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=11,
export_file_name="a.xlsx",
export_file_path="/tmp/a.xlsx",
)
db.session.add(task)
db.session.commit()
data = serialize_task_summary(task, viewer_user_id=11)
assert data["todo_category"] == "review"
assert data["created_by"] == 11
assert data["can_handle"] is True
assert data["ui_state"]["checkpoint"] == "parse_review"
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
no_viewer = serialize_task_summary(task)
assert "can_handle" not in no_viewer
def test_list_my_todos_and_count_buckets(app):
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
owner = 55
review = ShippingTask(
task_no="SN-TODO-REVIEW",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=owner,
)
upload = ShippingTask(
task_no="SN-TODO-UPLOAD",
process_status="matched",
source_type="manual",
user_id=owner,
export_file_path="/tmp/u.xlsx",
export_file_name="u.xlsx",
)
done = ShippingTask(
task_no="SN-TODO-DONE",
process_status="uploaded",
source_type="manual",
user_id=owner,
)
other = ShippingTask(
task_no="SN-TODO-OTHER",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=99,
)
db.session.add_all([review, upload, done, other])
db.session.commit()
pending = list_my_todos(owner, bucket="pending", page=1, page_size=20)
assert pending["total"] == 2
assert {item["task_no"] for item in pending["items"]} == {
"SN-TODO-REVIEW",
"SN-TODO-UPLOAD",
}
assert all(item["can_handle"] is True for item in pending["items"])
done_page = list_my_todos(owner, bucket="done")
assert done_page["total"] == 1
assert done_page["items"][0]["task_no"] == "SN-TODO-DONE"
counts = count_my_todos(owner)
assert counts["pending"] == 2
assert counts["done"] == 1
assert counts["total_pending_badge"] == 2
admin_pending = list_my_todos(owner, bucket="pending", is_admin=True)
assert admin_pending["total"] >= 3
other_item = next(
item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER"
)
assert other_item["can_handle"] is False
def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
"""开放 Review Case 进入 pending,并暴露 review_run_no 供人工复核深链。"""
with app.app_context():
from app import db
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
from tests.test_shipping_order_review_service import _materialized_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-REV-DL')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.result_json = {
'orders': [{
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-DL'}]}],
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A1'}]}]}],
'conflicts': [],
}],
}
db.session.commit()
cases = ensure_run_review_cases(run=run)
assert cases
case = cases[0]
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
review_items = [item for item in pending['items'] if item.get('item_kind') == 'review_case']
assert review_items, 'pending 应包含建单前复核 Case'
hit = next(item for item in review_items if item.get('review_case_no') == case.case_no)
assert hit['todo_category'] == 'review'
assert hit['review_run_no'] == run.run_no
assert hit['owner_agent_id'] == agent.id
assert hit['conversation_id'] == session.session_id
assert hit['can_handle'] is True
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
counts = count_my_todos(user.id)
assert counts['pending'] >= 1
assert counts['total_pending_badge'] == counts['pending']
def test_list_my_todos_filters_review_case_by_customer_filename(app):
"""Review Case 客户过滤按来源文件名/Case 号匹配,不能只筛 Task。"""
with app.app_context():
from app import db
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.query_service import list_my_todos
from tests.test_shipping_order_review_service import _materialized_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, document = _seed_run_input(suffix='TODO-REV-CUST')
document.filename = 'ACME-PO-450099.pdf'
db.session.flush()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.result_json = {
'orders': [{
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-CUST'}]}],
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'B1'}]}]}],
'conflicts': [],
}],
}
db.session.commit()
cases = ensure_run_review_cases(run=run)
assert cases
hit = list_my_todos(user.id, bucket='pending', page=1, page_size=50, customer='ACME')
review_hits = [item for item in hit['items'] if item.get('item_kind') == 'review_case']
assert review_hits, '按文件名关键字应命中 Review Case'
miss = list_my_todos(user.id, bucket='pending', page=1, page_size=50, customer='NO-SUCH-CUSTOMER')
assert not any(item.get('item_kind') == 'review_case' for item in miss['items'])
def test_list_my_todos_total_and_high_page_are_not_capped(app):
"""total 必须是完整匹配数;超过旧 500 截断后高页码仍可访问。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import list_my_todos
owner = 77
# 520 > 旧 limit(500),用于证明截断不再作为 total 来源。
total_tasks = 520
tasks = [
ShippingTask(
task_no=f"SN-TODO-PAGE-{index:04d}",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=owner,
)
for index in range(total_tasks)
]
db.session.add_all(tasks)
db.session.commit()
page1 = list_my_todos(owner, bucket="pending", page=1, page_size=20)
assert page1["total"] == total_tasks
assert len(page1["items"]) == 20
# 第 26 页:offset=500,恰好是旧截断边界之后;必须仍能返回数据。
page26 = list_my_todos(owner, bucket="pending", page=26, page_size=20)
assert page26["total"] == total_tasks
assert len(page26["items"]) == 20
page27 = list_my_todos(owner, bucket="pending", page=27, page_size=20)
assert page27["total"] == total_tasks
assert len(page27["items"]) == 0
far = list_my_todos(owner, bucket="pending", page=30, page_size=20)
assert far["total"] == total_tasks
assert far["items"] == []
def test_todo_category_lightweight_matches_orm_and_count(app):
"""
轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。
断言意图:UNION 分页下推的 SQL 分类不得漂移口径。
"""
with app.app_context():
from types import SimpleNamespace
from app import db
from app.services.shipping_notice.query_service import (
_task_todo_category_sql_expr,
_todo_category_from_task_row,
count_my_todos,
list_my_todos,
task_todo_category,
)
owner = 88
fixtures = [
ShippingTask(
task_no="SN-LW-REVIEW",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=owner,
),
ShippingTask(
task_no="SN-LW-UPLOAD",
process_status="matched",
source_type="manual",
user_id=owner,
export_file_path="/tmp/lw.xlsx",
export_file_name="lw.xlsx",
),
ShippingTask(
task_no="SN-LW-SHORTAGE",
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
process_status="parsed",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
user_id=owner,
),
ShippingTask(
task_no="SN-LW-DONE",
process_status="uploaded",
source_type="manual",
user_id=owner,
),
ShippingTask(
task_no="SN-LW-PROGRESS",
process_status="parsed",
source_type="manual",
user_id=owner,
),
]
db.session.add_all(fixtures)
db.session.commit()
category_expr = _task_todo_category_sql_expr()
for task in fixtures:
row = SimpleNamespace(
process_status=task.process_status,
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
shipping_case_id=task.shipping_case_id,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
current_order_extraction_id=task.current_order_extraction_id,
inventory_lines_json=task.inventory_lines_json,
match_status=task.match_status,
export_file_path=task.export_file_path,
)
expected = task_todo_category(task)
# 轻量路径与 ORM 路径同分类。
assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected
# SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。
sql_category = (
db.session.query(category_expr)
.filter(ShippingTask.id == task.id)
.scalar()
)
assert sql_category == expected
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
assert pending["total"] == 3
counts = count_my_todos(owner)
assert counts["pending"] == 3
assert counts["done"] == 1
assert counts["processing"] == 1
assert counts["total_pending_badge"] == 3