947 lines
41 KiB
Python
947 lines
41 KiB
Python
"""
|
||
backend/tests/test_shipping_notice_query_service.py
|
||
|
||
用途:shipping_notice query_service 读路径单测(任务/待办;co8 已移除批次排序用例)。
|
||
依赖:pytest、ShippingNotice、query_service。
|
||
逻辑:覆盖 task_no 解析、分页、投影与 my_todos UNION。
|
||
"""
|
||
|
||
import pytest
|
||
|
||
from app.models import ShippingNotice
|
||
|
||
from app.services.shipping_notice.query_service import (
|
||
TaskProjection,
|
||
extract_task_no_from_text,
|
||
get_task_by_ref,
|
||
list_tasks_for_user,
|
||
list_tasks_page_for_user,
|
||
resolve_task_from_payload,
|
||
serialize_task,
|
||
task_export_error_message,
|
||
list_freight_notice_groups_for_task,
|
||
)
|
||
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 = ShippingNotice(
|
||
task_no="SN-TEST-QUERY-001",
|
||
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_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
|
||
"""库存缺口筛选应读取领域事实和复核状态。"""
|
||
with app.app_context():
|
||
from app import db
|
||
|
||
shortage = ShippingNotice(
|
||
task_no="SN-FILTER-SHORTAGE",
|
||
review_status="shortage_review",
|
||
pending_human_reason="shortage",
|
||
source_type="manual",
|
||
user_id=999999,
|
||
)
|
||
ordinary = ShippingNotice(
|
||
task_no="SN-FILTER-PARSE",
|
||
review_status="parse_review",
|
||
pending_human_reason="low_confidence",
|
||
source_type="manual",
|
||
user_id=2,
|
||
)
|
||
db.session.add_all([shortage, ordinary])
|
||
db.session.commit()
|
||
|
||
rows = list_tasks_for_user(999999)
|
||
|
||
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([
|
||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", 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([
|
||
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
|
||
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
|
||
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"),
|
||
])
|
||
db.session.commit()
|
||
|
||
result = list_tasks_page_for_user(999999, lifecycle_status="active", 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 = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
|
||
assert task_export_error_message(empty) == "export file not found"
|
||
|
||
missing = ShippingNotice(
|
||
task_no="SN-MISSING-FILE",
|
||
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 = ShippingNotice(
|
||
task_no="SN-PROJ-TOOL",
|
||
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 = ShippingNotice(
|
||
task_no="SN-PROJ-INT",
|
||
review_status="parse_review",
|
||
source_type="manual",
|
||
)
|
||
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
|
||
assert "review_status" in data
|
||
assert data["review_status"] == "parse_review"
|
||
|
||
|
||
|
||
def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
|
||
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
|
||
with app.app_context():
|
||
task = ShippingNotice(
|
||
task_no="SN-CONV-1",
|
||
conversation_id="conv-abc",
|
||
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(
|
||
[
|
||
ShippingNotice(
|
||
task_no="SN-CONV-MULTI-1",
|
||
conversation_id="conv-multi",
|
||
source_type="manual",
|
||
),
|
||
ShippingNotice(
|
||
task_no="SN-CONV-MULTI-2",
|
||
conversation_id="conv-multi",
|
||
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 = ShippingNotice(
|
||
task_no="SN-HANDLE-OWN",
|
||
source_type="manual",
|
||
user_id=42,
|
||
)
|
||
orphan = ShippingNotice(
|
||
task_no="SN-HANDLE-ORPHAN",
|
||
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 = ShippingNotice(
|
||
task_no="SN-NULL-OWNER",
|
||
source_type="manual",
|
||
user_id=None,
|
||
)
|
||
owned = ShippingNotice(
|
||
task_no="SN-OWNED",
|
||
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 = ShippingNotice(
|
||
task_no="SN-ENRICH-1",
|
||
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"]["code"] == "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_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||
"""同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch
|
||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||
|
||
first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11)
|
||
second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11)
|
||
db.session.add_all([first, second]); db.session.flush()
|
||
db.session.add_all([
|
||
ShippingNoticeLine(
|
||
notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST',
|
||
reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'},
|
||
),
|
||
ShippingNoticeLine(
|
||
notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND',
|
||
reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'},
|
||
),
|
||
ShippingNoticeLineInventoryMatch(
|
||
task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready',
|
||
available_qty='20', shortage_qty='0', is_current=True,
|
||
),
|
||
ShippingNoticeLineInventoryMatch(
|
||
task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready',
|
||
available_qty='9', shortage_qty='0', is_current=True,
|
||
),
|
||
])
|
||
db.session.commit()
|
||
|
||
data = serialize_task_summary(first, viewer_user_id=11)
|
||
|
||
assert data['business_no'] == 'WVC26082301'
|
||
assert data['notice_line_summary'] == [{
|
||
'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST',
|
||
'customer_part_number': None,
|
||
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
|
||
'shortage_qty': '0', 'inventory_status': 'ready',
|
||
}]
|
||
|
||
|
||
def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
|
||
"""货代上传聚合必须按同 PO 的 business_no 拆组,并排除无业务号及他人 Notice。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import ShippingNoticeLine
|
||
from app.services.shipping_notice import query_service
|
||
|
||
def with_po(task_no, business_no, user_id):
|
||
return ShippingNotice(task_no=task_no, business_no=business_no, source_type='manual', user_id=user_id)
|
||
|
||
first = with_po('SN-GROUP-1', 'WYC26082401', 11)
|
||
second = with_po('SN-GROUP-2', 'WYC26082402', 11)
|
||
no_business = with_po('SN-GROUP-3', None, 11)
|
||
other = with_po('SN-GROUP-4', 'WYC26082499', 99)
|
||
db.session.add_all([first, second, no_business, other]); db.session.flush()
|
||
db.session.add_all([
|
||
ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}),
|
||
ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}),
|
||
])
|
||
db.session.commit()
|
||
|
||
original_header_reader = query_service.current_header_field_values_or_empty
|
||
# customer_po_number 是当前动态 Schema 的正式 PO 字段;聚合必须不依赖旧兼容投影。
|
||
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-GROUP'}
|
||
try:
|
||
result = list_freight_notice_groups_for_task(first, user_id=11)
|
||
finally:
|
||
query_service.current_header_field_values_or_empty = original_header_reader
|
||
assert result['po_number'] == 'PO-GROUP'
|
||
assert [item['business_no'] for item in result['items']] == ['WYC26082401', 'WYC26082402']
|
||
# 单条菜单必须消费服务端授权投影,前端不得按上传状态自行猜测可执行动作。
|
||
assert 'available_actions' in result['items'][0]
|
||
assert result['items'][0]['lines'][0]['part_number'] == 'PART-A'
|
||
assert result['items'][1]['lines'][0]['part_number'] == 'PART-B'
|
||
|
||
|
||
def test_freight_notice_groups_exposes_per_notice_upload_error(app):
|
||
"""货代上传聚合必须逐单透出上传错误码/原因/需人工原因,供「按通知单展示状态」消费。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import ShippingNotice
|
||
from app.services.shipping_notice import query_service
|
||
|
||
first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11)
|
||
db.session.add(first); db.session.flush()
|
||
first.upload_status = 'failed'
|
||
first.upload_error_code = 'RPA_UPLOAD_FAILED'
|
||
first.upload_error_message = '货代平台拒绝:凭证无效'
|
||
db.session.commit()
|
||
|
||
original_header_reader = query_service.current_header_field_values_or_empty
|
||
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-ERR'}
|
||
try:
|
||
result = list_freight_notice_groups_for_task(first, user_id=11)
|
||
finally:
|
||
query_service.current_header_field_values_or_empty = original_header_reader
|
||
|
||
item = result['items'][0]
|
||
assert item['business_no'] == 'WYC26082401'
|
||
assert item['upload_status'] == 'failed'
|
||
assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED'
|
||
assert item['upload_error_message'] == '货代平台拒绝:凭证无效'
|
||
|
||
|
||
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
|
||
"""当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import ShippingOrderSnapshot
|
||
from app.services.shipping_notice import query_service
|
||
|
||
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11)
|
||
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11)
|
||
db.session.add_all([first, second]); db.session.flush()
|
||
for task in (first, second):
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id,
|
||
extraction_id=task.id,
|
||
schema_version_id=1,
|
||
order_data_version=1,
|
||
header_values_json={},
|
||
customer_po_number='ZNB-16754796',
|
||
)
|
||
db.session.add(snapshot); db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
db.session.commit()
|
||
|
||
original_header_reader = query_service.current_header_field_values_or_empty
|
||
query_service.current_header_field_values_or_empty = lambda _task: {}
|
||
try:
|
||
result = list_freight_notice_groups_for_task(first, user_id=11)
|
||
finally:
|
||
query_service.current_header_field_values_or_empty = original_header_reader
|
||
|
||
assert result['po_number'] == '16754796'
|
||
assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412']
|
||
|
||
|
||
def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
|
||
"""通知完成面的上传方式必须取自 ShippingUploadAttempt,而非恒为 None 的 Notice.upload_mode。
|
||
|
||
回归点:denormalized Notice.upload_mode 从未被写入真实值;人工确认/RPA 的成功事实
|
||
只保存在 ShippingUploadAttempt.mode。聚合投影若直接读列会导致「通知完成」卡片拿不到
|
||
「人工確認 vs RPA 上传」的徽标来源。
|
||
"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import (
|
||
ShippingExportArtifact, ShippingExcelTemplate, ShippingInventoryParsingProfile,
|
||
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||
)
|
||
from app.services.shipping_notice import query_service
|
||
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
|
||
|
||
notice = ShippingNotice(task_no='SN-GROUP-MODE-1', business_no='WYC26082501', source_type='manual', user_id=11)
|
||
template = ShippingExcelTemplate(
|
||
template_code='MODE', display_name='Mode', version=1, status='published', storage_bucket='test',
|
||
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64,
|
||
definition_json={},
|
||
)
|
||
profile = ShippingInventoryParsingProfile(
|
||
profile_code='MODE', display_name='Mode', version=1, status='published', file_format='xlsx',
|
||
definition_json={},
|
||
)
|
||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||
db.session.add_all([notice, template, profile, schema]); db.session.flush()
|
||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||
db.session.add(version); db.session.flush()
|
||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted')
|
||
db.session.add(extraction); db.session.flush()
|
||
artifact = ShippingExportArtifact(
|
||
artifact_no='ART-MODE-1', task_id=notice.id, template_id=template.id, order_schema_version_id=version.id,
|
||
order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='b' * 64,
|
||
file_path='/tmp/notice.xlsx', file_name='notice.xlsx', file_checksum='c' * 64, file_size=100, status='ready',
|
||
)
|
||
db.session.add(artifact); db.session.flush()
|
||
notice.export_file_name = 'notice.xlsx'
|
||
notice.export_file_path = '/tmp/notice.xlsx'
|
||
# 人为把陈旧列写成错误值,证明聚合不再消费它。
|
||
notice.upload_mode = 'rpa'
|
||
notice.upload_attempt = 99
|
||
db.session.commit()
|
||
|
||
# 一条人工确认成功 Attempt = 唯一可信的来源。
|
||
record_manual_upload(notice, artifact_id=artifact.id, operator_id=22)
|
||
db.session.commit()
|
||
|
||
original_header_reader = query_service.current_header_field_values_or_empty
|
||
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-MODE'}
|
||
try:
|
||
result = list_freight_notice_groups_for_task(notice, user_id=11)
|
||
finally:
|
||
query_service.current_header_field_values_or_empty = original_header_reader
|
||
|
||
item = result['items'][0]
|
||
assert item['business_no'] == 'WYC26082501'
|
||
# 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。
|
||
assert item['upload_mode'] == 'manual'
|
||
assert item['upload_attempt'] == 1
|
||
|
||
|
||
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 = ShippingNotice(
|
||
task_no="SN-TODO-REVIEW",
|
||
review_status="parse_review",
|
||
pending_human_reason="low_confidence",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
)
|
||
upload = ShippingNotice(
|
||
task_no="SN-TODO-UPLOAD",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
export_file_path="/tmp/u.xlsx",
|
||
export_file_name="u.xlsx",
|
||
)
|
||
done = ShippingNotice(
|
||
task_no="SN-TODO-DONE",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
upload_status="uploaded",
|
||
)
|
||
other = ShippingNotice(
|
||
task_no="SN-TODO-OTHER",
|
||
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': [],
|
||
}],
|
||
}
|
||
from app.models import ShippingOrderCandidate
|
||
|
||
db.session.add(ShippingOrderCandidate(
|
||
candidate_no='CAND-TODO-REV-DL',
|
||
intake_id=intake.id,
|
||
primary_document_id=document.id,
|
||
candidate_key='todo-review-deep-link',
|
||
order_extraction_run_id=run.id,
|
||
))
|
||
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'
|
||
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
|
||
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
|
||
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
|
||
]
|
||
|
||
counts = count_my_todos(user.id)
|
||
assert counts['pending'] >= 1
|
||
assert counts['total_pending_badge'] == counts['pending']
|
||
|
||
|
||
def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_still_open(app):
|
||
"""待办只能指向文件 Stream 当前 Case,不能因旧 Case 状态残留而重复展示。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||
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 app.services.shipping_notice.review_stream_service import activate_review_case
|
||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||
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-STREAM-CURRENT')
|
||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||
original = ensure_run_review_cases(run=source)[0]
|
||
transition_order_extraction_run(source, target_status='processing')
|
||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||
|
||
replacement_run, _ = reparse_case_document(
|
||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||
)
|
||
ensure_order_extraction_plan(replacement_run)
|
||
for unit in replacement_run.extraction_plan.units:
|
||
unit.status = 'candidate_ready'
|
||
replacement = ensure_run_review_cases(run=replacement_run)[0]
|
||
activate_review_case(case=replacement, trigger='document_reparse_succeeded')
|
||
|
||
# 模拟旧数据未正确标成 superseded:当前态仍必须由 Stream 指针裁决。
|
||
original.status = 'draft'
|
||
original.confirmed_task_id = None
|
||
db.session.commit()
|
||
|
||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||
review_case_nos = {
|
||
item['review_case_no']
|
||
for item in pending['items']
|
||
if item.get('item_kind') == 'review_case'
|
||
}
|
||
assert replacement.case_no in review_case_nos
|
||
assert original.case_no not in review_case_nos
|
||
|
||
|
||
def test_open_review_case_without_current_candidate_enters_intake_parse(app):
|
||
"""无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。"""
|
||
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-EMPTY-CASE')
|
||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||
unit = run.extraction_plan.units[0]
|
||
unit.result_json = {'orders': []}
|
||
db.session.commit()
|
||
case = ensure_run_review_cases(run=run)[0]
|
||
|
||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||
hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no)
|
||
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||
assert hit['ui_state']['intake_parse_authorized'] is True
|
||
assert hit['ui_state']['lifecycle_entries'] == []
|
||
|
||
|
||
def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||
"""
|
||
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
|
||
|
||
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
|
||
"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.models import FileAsset, ShippingOrderIntake, User
|
||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||
|
||
user = User(username='todo-orphan-intake', email='todo-orphan@example.com', password_hash='x')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
asset = FileAsset(
|
||
asset_no=f'FA-ORPHAN-{user.id}',
|
||
owner_user_id=user.id,
|
||
original_filename='orphan-fail.pdf',
|
||
storage_provider='minio',
|
||
storage_bucket='test',
|
||
storage_key=f'temporary/{user.id}/orphan-fail.pdf',
|
||
content_hash='b' * 64,
|
||
file_size=12,
|
||
mime_type='application/pdf',
|
||
upload_status='ready',
|
||
lifecycle_status='temporary',
|
||
)
|
||
db.session.add(asset)
|
||
db.session.flush()
|
||
intake = ShippingOrderIntake(
|
||
intake_no=f'SNI-ORPHAN-{user.id}',
|
||
asset_id=int(asset.id),
|
||
user_id=int(user.id),
|
||
conversation_id='c' * 32,
|
||
upload_batch_id='batch-orphan-1',
|
||
source_type='direct_pdf',
|
||
purpose='shipping_notice',
|
||
parse_status='parse_failed',
|
||
parser_version='test-v1',
|
||
error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
|
||
error_message='parse boom',
|
||
)
|
||
db.session.add(intake)
|
||
db.session.commit()
|
||
|
||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||
intake_items = [item for item in pending['items'] if item.get('item_kind') == 'order_intake']
|
||
assert intake_items, 'pending 应包含未建 OT 的失败 Intake'
|
||
hit = next(item for item in intake_items if item.get('intake_no') == intake.intake_no)
|
||
assert hit['todo_category'] == 'intake_parse'
|
||
assert hit['conversation_id'] == 'c' * 32
|
||
assert hit['source_file_name'] == 'orphan-fail.pdf'
|
||
assert hit['can_handle'] is True
|
||
assert hit['ui_state']['summary']['entry_surface'] == 'conversation_processing'
|
||
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||
assert hit['ui_state']['lifecycle_entries'] == []
|
||
|
||
filtered = list_my_todos(
|
||
user.id, bucket='pending', page=1, page_size=50, todo_category='intake_parse',
|
||
)
|
||
assert any(item.get('intake_no') == intake.intake_no for item in filtered['items'])
|
||
|
||
counts = count_my_todos(user.id)
|
||
assert counts['pending'] >= 1
|
||
|
||
|
||
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 = [
|
||
ShippingNotice(
|
||
task_no=f"SN-TODO-PAGE-{index:04d}",
|
||
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 = [
|
||
ShippingNotice(
|
||
task_no="SN-LW-REVIEW",
|
||
review_status="parse_review",
|
||
pending_human_reason="low_confidence",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
),
|
||
ShippingNotice(
|
||
task_no="SN-LW-UPLOAD",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
export_file_path="/tmp/lw.xlsx",
|
||
export_file_name="lw.xlsx",
|
||
),
|
||
ShippingNotice(
|
||
task_no="SN-LW-SHORTAGE",
|
||
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
|
||
review_status="shortage_review",
|
||
pending_human_reason="shortage",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
),
|
||
ShippingNotice(
|
||
task_no="SN-LW-DONE",
|
||
upload_status="uploaded",
|
||
source_type="manual",
|
||
user_id=owner,
|
||
),
|
||
ShippingNotice(
|
||
task_no="SN-LW-PROGRESS",
|
||
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(
|
||
review_status=task.review_status,
|
||
pending_human_reason=task.pending_human_reason,
|
||
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,
|
||
upload_status=task.upload_status,
|
||
)
|
||
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(ShippingNotice.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
|
||
|
||
|
||
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||
"""工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。"""
|
||
with app.app_context():
|
||
from app import db
|
||
from app.services.shipping_notice.query_service import serialize_task_detail
|
||
|
||
task = ShippingNotice(
|
||
task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11,
|
||
export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx",
|
||
)
|
||
db.session.add(task)
|
||
db.session.commit()
|
||
|
||
full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True)
|
||
wb = serialize_task_detail(
|
||
task, viewer_user_id=11, include_stage_context=True, view="workbench",
|
||
)
|
||
|
||
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
|
||
for key in (
|
||
"lines", "order_header", "order_header_fields", "order_line_fields",
|
||
"events", "field_conflicts",
|
||
):
|
||
assert key in full
|
||
assert key not in wb
|
||
# workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。
|
||
assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW"
|
||
assert wb["ui_state"]["stage_context"] is not None
|
||
assert wb["artifact_summary"]["export_file_name"] == "n.xlsx"
|
||
assert "notice_line_summary" in wb
|
||
assert "export_artifacts" in wb
|