Files
syops/backend/tests/test_shipping_notice_ui_state.py
T
hugo 935bf26fa6 feat(shipping-notice): 升级货代发货流程为五阶段,完善业务校验
将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段;
统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认";
新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成;
新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式;
更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
2026-08-21 09:20:47 +08:00

736 lines
31 KiB
Python

"""
tests/test_shipping_notice_ui_state.py
用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。
依赖:pytest、ShippingNotice、ui_state、state_machine constants。
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
"""
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_PARSE_REVIEW,
PH_LOW_CONF,
RS_PARSE_REVIEW,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
from app.services.shipping_notice.ui_state import _unified_actions
_REQUIRED_SUMMARY_KEYS = {
"title",
"message",
"issues",
"stage",
"checkpoint_kind",
"current_todo",
"pause_reason",
"next_auto_step",
"event_at",
"entry_surface",
"allowed_actions",
}
def test_unified_actions_deduplicates_gate_primary_action():
"""Gate 主动作同时出现在展示列表时,只能渲染一次。"""
state = _unified_actions(
process_gate={
"primary_action": {"code": "open_order_review", "label": "进入订单复核"},
"action_presentation": [
{"code": "open_order_review", "label": "进入订单复核"},
{"code": "view_audit", "label": "查看审计", "kind": "view"},
],
},
)
assert state["primary"]["code"] == "open_order_review"
assert [item["code"] for item in state["secondary"]] == ["view_audit"]
def test_unified_action_shape_contains_gate_version_fields():
"""统一动作 DTO 必须包含前端提交所需的版本、分派与禁用字段。"""
state = _unified_actions(
process_gate={
"lock_version": 7,
"current_gate": {"evaluation_version": 3},
"primary_action": {
"code": "retry_inventory_matching",
"label": "重新匹配",
"dispatch": "mutation",
},
"action_presentation": [],
},
)
assert state["primary"]["expected_gate_version"] == 3
# 关键断言:前端必须按 Gate 声明的执行方式分派,不能按动作码硬编码。
assert state["primary"]["dispatch"] == "mutation"
assert "disabled_reason" in state["primary"]
def test_unified_actions_preserve_backend_surface_without_action_code_fallback():
"""UI State 只透传动作来源声明的位置,不再按下载动作码补默认工作面。"""
state = _unified_actions(
process_gate={
"primary_action": {
"code": "mark_manual_uploaded",
"label": "登记人工上传",
"target_surface": "freight_upload",
},
"action_presentation": [{
"code": "download_excel",
"label": "下载发货 Excel",
"target_surface": "freight_upload",
"target_anchor": "excel_artifact",
}],
},
)
assert state["primary"]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_anchor"] == "excel_artifact"
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
"""summary 必须包含 STP 可解释字段全集。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-SUMMARY",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW
assert state["checkpoint_kind"] == "must_human"
assert "stp_facts" not in state["summary"]
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
"""列表等轻量调用默认不得加载阶段工作面详情。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual")
state = build_task_ui_state(task)
detailed_state = build_task_ui_state(task, include_stage_context=True)
# 关键断言:只有详情接口显式请求时才查询行、Artifact 和上传 Attempt。
assert "stage_context" not in state
assert "stage_context" in detailed_state
def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(app) -> None:
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STAGE-ACTIONS",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert state["stage"]["code"] == "order_review"
assert state["stage"]["index"] == 2
assert state["stage"]["total"] == 5
assert state["actions"]["primary"] is None
assert state["actions"]["secondary"] == []
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
"""正式工作台的五个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-LIFECYCLE-ENTRIES",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert state["lifecycle_stage"] == "order_review"
assert state["lifecycle_entries"] == [
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "freight_upload", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
]
def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
"""被替代的 Execution 不能继续给正式工作台下发历史 Gate 或按钮。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
)
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual')
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.status = 'superseded'
db.session.flush()
state = build_task_ui_state(task)
assert state['process_gate'] is None
def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
"""正式 Gate 与旧任务字段冲突时,任务详情必须与批次中心同样以 Gate 裁决阶段。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no='SN-UI-GATE-AUTHORITY',
user_id=user.id,
source_type='manual',
# 模拟历史字段尚未同步:旧字段仍像解析复核。
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.current_gate_code = 'inventory_matching'
db.session.flush()
state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'fulfillment_prep'
assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'fulfillment_prep'
assert state['current_step']['code'] == 'fulfillment_prep'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'current', 'unavailable',
]
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
"""正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no='SN-UI-UPLOAD-GATE-AUTHORITY',
user_id=user.id,
source_type='manual',
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.current_gate_code = 'manual_upload_handoff'
db.session.flush()
state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'freight_upload'
assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'freight_upload'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'available', 'current', 'unavailable',
]
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
"""库存匹配与无证据历史上传分别映射通知准备和货代上传。"""
with app.app_context():
fulfillment = ShippingNotice(
task_no="SN-UI-FULFILLMENT",
source_type="manual",
match_status="partial",
inventory_lines_json=[{"part_number": "P-1"}],
)
upload = ShippingNotice(
task_no="SN-UI-UPLOAD",
source_type="manual",
upload_status="uploaded",
)
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
upload_state = build_task_ui_state(upload, include_stage_context=True)
assert upload_state["stage"]["code"] == "freight_upload"
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
"""解析复核应进入人工复核工作台。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-REVIEW",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert state["summary"]["entry_surface"] == "review_workbench"
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-EXPORT",
source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
)
state = build_task_ui_state(task)
assert state["checkpoint"]["code"] == CP_EXPORT_READY
assert state["checkpoint_kind"] == "wait_manual_upload"
assert state["summary"]["entry_surface"] == "task_workbench"
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
assert "download_excel" not in button_ids
assert "mark_manual_uploaded" not in button_ids
def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypatch) -> None:
"""下载入口必须由后端 Artifact 解析结果裁决,而不是由遗留文件名裁决。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-RESOLVED-EXPORT",
source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download',
lambda _task: (object(), 'shipping-export.xlsx'),
)
state = build_task_ui_state(task)
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "download_excel" in button_ids
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-GATE-EXPORT", source_type="manual")
monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download',
lambda _task: (None, 'shipping-export.xlsx'),
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda _task: {
'current_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
'current_blocking_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
'primary_action': {'code': 'retry_freight_upload_rpa', 'label': '重新上传'},
'action_presentation': [],
},
)
state = build_task_ui_state(task)
assert state['actions']['primary']['code'] == 'retry_freight_upload_rpa'
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-FROZEN",
source_type="manual",
inventory_source_status="candidates_frozen",
inventory_source_method="stp_build_freeze",
step_payload_json={
"line_inventory_candidates": {
"source_codes": ["DBS_DUB", "DBS_RTM"],
"frozen_at": "build",
},
},
)
state = build_task_ui_state(task)
facts = state["summary"]["stp_facts"]
assert facts["inventory_source_status"] == "candidates_frozen"
assert facts["frozen_candidate_codes"] == ["DBS_DUB", "DBS_RTM"]
assert facts["multi_source_excel_block"] is False
def test_stp_facts_projects_line_resolutions(app) -> None:
"""stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-LINES",
source_type="manual",
match_status="fulfillable",
inventory_source_status="resolved",
inventory_source_code="DBS_DUB",
inventory_source_method="stp_line_match",
step_payload_json={
"line_inventory_resolutions": [
{
"line_index": 0,
"disposition": "ok",
"effective_reservation_id": "3000092917",
"part_number": "PN-1",
"resolved_inventory_source_code": "DBS_DUB",
"inventory_file_no": "INV-1",
"inventory_row_ref": {
"reservation_id": "3000092917",
"part_number": "PN-1",
"source_code": "DBS_DUB",
},
},
],
},
)
state = build_task_ui_state(task, include_stage_context=True)
rows = state["summary"]["stp_facts"]["line_resolutions"]
assert rows[0]["effective_reservation_id"] == "3000092917"
assert rows[0]["part_number"] == "PN-1"
assert rows[0]["resolved_inventory_source_code"] == "DBS_DUB"
assert rows[0]["inventory_file_no"] == "INV-1"
stage_context = state["stage_context"]
assert stage_context["preparation"]["status"] == "ready"
assert stage_context["preparation"]["lines"] == [{
"line_key": None,
"reservation_id": "3000092917",
"part_number": "PN-1",
"required_qty": None,
"available_qty": None,
"shortage_qty": None,
"source_code": "DBS_DUB",
"status": "ok",
}]
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
assert stage_context["upload"]["outcome"] == "not_started"
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STRUCTURED-MATCH",
source_type="manual",
match_status="partial",
inventory_source_code="DBS_DUB",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
line_results_json=[],
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="10",
available_qty="7",
matched_qty="7",
shortage_qty="3",
reservation_id="RSV-1",
part_number="PN-1",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
assert preparation["has_match_result"] is True
assert preparation["lines"] == [{
"line_key": "line-1",
"reservation_id": "RSV-1",
"part_number": "PN-1",
"required_qty": "10",
"available_qty": "7",
"shortage_qty": "3",
"source_code": "DBS_DUB",
"status": "matched",
}]
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual")
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLine(
notice_id=task.id,
position=0,
line_key="line-frozen-1",
reservation_id="RSV-FROZEN",
part_number="PN-FROZEN",
required_qty="6",
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
assert preparation["frozen_order_lines"] == [{
"line_key": "line-frozen-1",
"reservation_id": "RSV-FROZEN",
"part_number": "PN-FROZEN",
"required_qty": "6.00000000",
}]
assert preparation["lines"] == []
assert preparation["has_match_result"] is False
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
with app.app_context():
inventory_path = tmp_path / "task-inventory.xlsx"
inventory_path.write_bytes(b"inventory-content")
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual")
inventory_file = ShippingInventoryFile(
inventory_file_no="SIF-UI-DOWNLOAD",
storage_path=str(inventory_path),
source_file_name="task-inventory.xlsx",
snapshot_status="ready",
)
db.session.add_all([task, inventory_file])
db.session.flush()
# 未建立 task link 时不得因为文件存在而放行下载。
assert resolve_task_inventory_download(task) is None
db.session.add(ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
is_active=True,
access_mode="readonly",
))
db.session.commit()
resolved = resolve_task_inventory_download(task)
assert resolved is not None
assert resolved[0] == inventory_path.resolve()
assert resolved[1] == "task-inventory.xlsx"
def test_workspace_inventory_download_requires_owned_active_file(app, client, tmp_path) -> None:
"""库存下载路由只能返回当前用户任务的 active link 文件,不能泄漏其他任务或无关联文件。"""
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
with app.app_context():
owner = User(username='inventory-download-owner', email='inventory-download-owner@example.com')
other = User(username='inventory-download-other', email='inventory-download-other@example.com')
db.session.add_all([owner, other])
db.session.flush()
inventory_path = tmp_path / 'inventory-download.xlsx'
inventory_path.write_bytes(b'inventory-download-content')
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual')
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual')
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
storage_path=str(inventory_path),
source_file_name='inventory-download.xlsx',
snapshot_status='ready',
)
db.session.add_all([task, no_file_task, inventory_file])
db.session.flush()
db.session.add(ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
is_active=True,
access_mode='readonly',
))
db.session.commit()
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
assert success.status_code == 200
assert success.data == b'inventory-download-content'
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
assert missing.status_code == 404
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
assert forbidden.status_code == 404
def test_workspace_line_inventory_download_requires_current_line_reference(app, client, tmp_path) -> None:
"""行内下载只能读取当前匹配事实引用的库存文件,不能按文件号探测同任务其他来源。"""
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
with app.app_context():
owner = User(username='line-inventory-download-owner', email='line-inventory-download-owner@example.com')
db.session.add(owner)
db.session.flush()
allowed_path = tmp_path / 'crane.xlsx'
denied_path = tmp_path / 'dbs.xlsx'
allowed_path.write_bytes(b'crane-content')
denied_path.write_bytes(b'dbs-content')
task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual')
allowed_file = ShippingInventoryFile(
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
)
denied_file = ShippingInventoryFile(
inventory_file_no='SIF-LINE-DBS', storage_path=str(denied_path),
source_file_name='dbs.xlsx', source_code='DBS', snapshot_status='ready',
)
db.session.add_all([task, allowed_file, denied_file])
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, line_key='line-crane', line_index=0,
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
))
db.session.commit()
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
allowed = client.get(
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
headers=headers,
)
assert allowed.status_code == 200
assert allowed.data == b'crane-content'
assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '')
denied = client.get(
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
headers=headers,
)
assert denied.status_code == 404
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STRUCTURED-PARTIAL",
source_type="manual",
match_status="partial",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
step_payload_json={"line_inventory_resolutions": [{
"line_index": 0,
"line_key": "line-1",
"effective_reservation_id": "RSV-LEGACY",
"part_number": "PN-LEGACY",
"inventory_file_no": "INV-1",
"disposition": "ok",
}]},
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="10",
available_qty="8",
shortage_qty="2",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
line = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]["lines"][0]
assert line["reservation_id"] == "RSV-LEGACY"
assert line["part_number"] == "PN-LEGACY"
assert line["available_qty"] == "8"
def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch) -> None:
"""正式详情接口必须原样携带通知准备摘要,供工作台首屏消费。"""
from types import SimpleNamespace
from app.api.workspace import shipping_notice as api
from app.services.shipping_notice import query_service
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-DETAIL-CONTEXT",
source_type="manual",
match_status="fulfillable",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="2",
available_qty="2",
shortage_qty="0",
reservation_id="RSV-DETAIL",
part_number="PN-DETAIL",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1, role='user'))
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
monkeypatch.setattr(api, '_ok', lambda data: data)
payload = api.workspace_shipping_task_detail(task.task_no)
preparation = payload['ui_state']['stage_context']['preparation']
assert preparation['has_match_result'] is True
assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL'
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
"""历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。"""
from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-MULTI",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason="shortage",
source_type="manual",
match_status="fulfillable",
inventory_source_status="candidates_frozen",
inventory_source_method="stp_line_match",
step_payload_json={
"multi_source_excel_block": True,
"resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"],
"line_inventory_resolutions": [
{"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"},
{"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"},
],
},
)
state = build_task_ui_state(task)
summary = state["summary"]
assert summary["pause_reason_code"] == "multi_source_excel_block"
assert summary["stp_facts"]["multi_source_excel_block"] is True
assert summary["entry_surface"] == "task_workbench"