939 lines
42 KiB
Python
939 lines
42 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 (
|
||
ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource,
|
||
ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User,
|
||
)
|
||
from app.services.shipping_notice.constants import (
|
||
CP_EXPORT_READY,
|
||
CP_ORDER_FREEZE,
|
||
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 _frozen_task_with_line(
|
||
*,
|
||
task_no: str,
|
||
user_id: int = 1,
|
||
reservation_id: str | None = None,
|
||
part_number: str | None = None,
|
||
qty: str | None = None,
|
||
field_values_json: dict | None = None,
|
||
) -> tuple[ShippingOrderTask, ShippingOrderSnapshotLine]:
|
||
"""建立通知准备测试所需的最小 OT 冻结档与订单项次。"""
|
||
task = ShippingOrderTask(task_no=task_no, user_id=user_id, source_type='direct_pdf')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id,
|
||
extraction_id=task.id,
|
||
schema_version_id=1,
|
||
order_data_version=1,
|
||
header_values_json={},
|
||
)
|
||
db.session.add(snapshot)
|
||
db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
line = ShippingOrderSnapshotLine(
|
||
snapshot_id=snapshot.id,
|
||
position=0,
|
||
line_no=1,
|
||
reservation_id=reservation_id,
|
||
part_number=part_number,
|
||
qty=qty,
|
||
field_values_json=field_values_json or {},
|
||
)
|
||
db.session.add(line)
|
||
db.session.flush()
|
||
return task, line
|
||
|
||
|
||
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 = ShippingOrderTask(
|
||
task_no="OT-UI-SUMMARY", user_id=1,
|
||
review_status=RS_PARSE_REVIEW,
|
||
pending_human_reason=PH_LOW_CONF,
|
||
source_type="direct_pdf",
|
||
)
|
||
state = build_task_ui_state(task)
|
||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||
assert state["checkpoint"]["code"] == CP_ORDER_FREEZE
|
||
assert state["checkpoint_kind"] == "auto_continue"
|
||
assert "stp_facts" not in state["summary"]
|
||
|
||
|
||
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||
"""列表等轻量调用默认不得加载阶段工作面详情。"""
|
||
with app.app_context():
|
||
task = ShippingOrderTask(task_no="OT-UI-LIGHTWEIGHT", user_id=1, source_type="direct_pdf")
|
||
|
||
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_without_formal_gate_is_unclassified(app) -> None:
|
||
"""旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。"""
|
||
with app.app_context():
|
||
task = ShippingOrderTask(
|
||
task_no="OT-UI-STAGE-ACTIONS", user_id=1,
|
||
review_status=RS_PARSE_REVIEW,
|
||
pending_human_reason=PH_LOW_CONF,
|
||
source_type="direct_pdf",
|
||
)
|
||
state = build_task_ui_state(task)
|
||
assert state["stage"]["code"] == "unclassified"
|
||
assert state["stage"]["index"] == 0
|
||
assert state["stage"]["total"] == 5
|
||
assert state["actions"]["primary"] is None
|
||
assert state["actions"]["secondary"] == []
|
||
|
||
|
||
def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None:
|
||
"""正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。"""
|
||
with app.app_context():
|
||
task = ShippingOrderTask(
|
||
task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1,
|
||
review_status=RS_PARSE_REVIEW,
|
||
pending_human_reason=PH_LOW_CONF,
|
||
source_type="direct_pdf",
|
||
)
|
||
state = build_task_ui_state(task)
|
||
assert state["lifecycle_stage"] == "unclassified"
|
||
assert state["lifecycle_entries"] == []
|
||
|
||
|
||
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 = ShippingOrderTask(task_no='OT-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='direct_pdf')
|
||
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 = ShippingOrderTask(
|
||
task_no='OT-UI-GATE-AUTHORITY',
|
||
user_id=user.id,
|
||
source_type='direct_pdf',
|
||
# 模拟历史字段尚未同步:旧字段仍像解析复核。
|
||
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', '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 = ShippingOrderTask(
|
||
task_no='OT-UI-UPLOAD-GATE-AUTHORITY',
|
||
user_id=user.id,
|
||
source_type='direct_pdf',
|
||
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_does_not_map_domain_fields_to_lifecycle(app) -> None:
|
||
"""库存和上传历史字段不能再替代正式 Gate 生成生命周期。"""
|
||
with app.app_context():
|
||
fulfillment = ShippingOrderTask(
|
||
task_no="OT-UI-FULFILLMENT", user_id=1,
|
||
source_type="direct_pdf",
|
||
)
|
||
upload = ShippingOrderTask(task_no="OT-UI-UPLOAD", user_id=1, source_type="direct_pdf")
|
||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified"
|
||
upload_state = build_task_ui_state(upload, include_stage_context=True)
|
||
assert upload_state["stage"]["code"] == "unclassified"
|
||
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
|
||
assert upload_state["stage_context"]["upload"]["outcome"] == "not_started"
|
||
|
||
|
||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||
"""解析复核应进入人工复核工作台。"""
|
||
with app.app_context():
|
||
task = ShippingOrderTask(
|
||
task_no="OT-UI-REVIEW", user_id=1,
|
||
review_status=RS_PARSE_REVIEW,
|
||
pending_human_reason=PH_LOW_CONF,
|
||
source_type="direct_pdf",
|
||
)
|
||
state = build_task_ui_state(task)
|
||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||
|
||
|
||
def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
|
||
"""Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。"""
|
||
with app.app_context():
|
||
task = ShippingNotice(
|
||
task_no="SN-UI-EXPORT",
|
||
source_type="manual",
|
||
)
|
||
# Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
|
||
from types import SimpleNamespace
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||
lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'),
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
|
||
lambda _task: None,
|
||
)
|
||
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",
|
||
)
|
||
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_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatch) -> None:
|
||
"""通知完成是终态,即使旧 Gate 尚未清理也不得继续下发下一步。"""
|
||
with app.app_context():
|
||
task = ShippingNotice(task_no='SN-UI-UPLOAD-COMPLETE', source_type='manual')
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||
lambda _task: True,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||
lambda _task: {
|
||
'current_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
|
||
'current_blocking_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
|
||
'primary_action': {'code': 'mark_manual_uploaded', 'label': '确认上传'},
|
||
'action_presentation': [],
|
||
},
|
||
)
|
||
|
||
state = build_task_ui_state(task)
|
||
|
||
# 关键断言:已核验上传成功优先于滞后的 Gate,完成态不能渲染任何下一步。
|
||
assert state['lifecycle_stage'] == 'upload_complete'
|
||
assert state['actions'] == {'primary': None, 'secondary': []}
|
||
|
||
|
||
def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
|
||
with app.app_context():
|
||
task = ShippingOrderTask(
|
||
task_no="OT-UI-STP-FROZEN", user_id=1, source_type="direct_pdf",
|
||
)
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
candidate_set = ShippingInventoryCandidateSet(
|
||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64,
|
||
)
|
||
db.session.add(candidate_set)
|
||
db.session.flush()
|
||
db.session.add_all([
|
||
ShippingInventoryCandidateSource(
|
||
candidate_set_id=candidate_set.id, source_code=code, candidate_order=index,
|
||
)
|
||
for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1)
|
||
])
|
||
db.session.add(ShippingInventoryCandidateLine(
|
||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'],
|
||
))
|
||
task.active_inventory_candidate_set_id = candidate_set.id
|
||
db.session.commit()
|
||
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 须从当前行级 Match 投影逐行库存证据,不能读取 OT payload。"""
|
||
with app.app_context():
|
||
user = User(username='ui-stp-lines', email='ui-stp-lines@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
task = ShippingOrderTask(
|
||
task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching',
|
||
)
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id, extraction_id=3, schema_version_id=1,
|
||
order_data_version=1, header_values_json={},
|
||
)
|
||
db.session.add(snapshot)
|
||
db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
snapshot_line = ShippingOrderSnapshotLine(
|
||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||
reservation_id='3000092917', part_number='PN-1', qty='10', field_values_json={},
|
||
)
|
||
db.session.add(snapshot_line)
|
||
db.session.flush()
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||
match_result='matched', inventory_status='ready', required_qty='10', available_qty='10',
|
||
matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1',
|
||
inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True,
|
||
))
|
||
db.session.commit()
|
||
|
||
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"
|
||
# §1.5:行级字段是展示契约核心,但不锁全 dict(随 §1.5 字段扩展)。断言关键现存字段 + 新增明细按钮字段。
|
||
line = stage_context["preparation"]["lines"][0]
|
||
assert line["snapshot_line_id"] == snapshot_line.id
|
||
assert line["line_no"] == 1
|
||
assert line["customer_po_line_no"] is None
|
||
assert line["reservation_id"] == "3000092917"
|
||
assert line["part_number"] == "PN-1"
|
||
assert line["required_qty"] == "10"
|
||
assert line["available_qty"] == "10"
|
||
assert line["shortage_qty"] == "0"
|
||
assert line["source_code"] == "DBS_DUB"
|
||
# §1.5 status 现取 user_line_status(展示契约),不再是裸 match_result 的 disposition。
|
||
assert line["status"] == "inventory_matched"
|
||
assert line["source_ambiguous"] is False
|
||
assert line["source_candidates"] == []
|
||
# §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮;
|
||
# line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。
|
||
assert line["inventory_file_no"] == "INV-1"
|
||
assert line["is_shortage"] is False
|
||
assert line["inventory_allowed_actions"] == []
|
||
assert line["line_allowed_actions"] == ["close_unfulfillable"]
|
||
assert line["user_line_status"] == "inventory_matched"
|
||
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
|
||
assert stage_context["upload"]["outcome"] == "not_started"
|
||
|
||
|
||
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||
"""通知准备必须从 Snapshot 与行级 Match 投影,不依赖 OT JSON 或 NoticeLine。"""
|
||
with app.app_context():
|
||
user = User(username='ui-structured-match', email='ui-structured-match@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id, extraction_id=1, schema_version_id=1,
|
||
order_data_version=1, header_values_json={},
|
||
)
|
||
db.session.add(snapshot)
|
||
db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
snapshot_line = ShippingOrderSnapshotLine(
|
||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||
reservation_id='RSV-1', part_number='PN-1', qty='10', field_values_json={},
|
||
)
|
||
db.session.add(snapshot_line)
|
||
db.session.flush()
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id,
|
||
snapshot_line_id=snapshot_line.id,
|
||
line_no=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
|
||
line = preparation["lines"][0]
|
||
assert line["snapshot_line_id"] == snapshot_line.id
|
||
assert line["line_no"] == 1
|
||
assert line["customer_po_line_no"] is None
|
||
assert line["reservation_id"] == "RSV-1"
|
||
assert line["part_number"] == "PN-1"
|
||
assert line["required_qty"] == "10"
|
||
assert line["available_qty"] == "7"
|
||
assert line["shortage_qty"] == "3"
|
||
assert line["source_code"] == "DBS_DUB"
|
||
assert line["status"] == "shortage"
|
||
assert line["source_ambiguous"] is False
|
||
assert line["source_candidates"] == []
|
||
# §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。
|
||
assert line["is_shortage"] is True
|
||
assert line["user_line_status"] == "shortage"
|
||
assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"}
|
||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||
|
||
|
||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None:
|
||
"""行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。"""
|
||
with app.app_context():
|
||
user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id, extraction_id=2, schema_version_id=1,
|
||
order_data_version=1, header_values_json={},
|
||
)
|
||
db.session.add(snapshot)
|
||
db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={})
|
||
db.session.add(line)
|
||
db.session.flush()
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||
match_result='source_conflict', inventory_status='source_conflict',
|
||
allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True,
|
||
))
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||
assert preparation['lines'][0]['source_ambiguous'] is True
|
||
assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B']
|
||
assert preparation['lines'][0]['source_code'] is None
|
||
assert preparation['source_locked'] is False
|
||
|
||
|
||
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
|
||
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
|
||
with app.app_context():
|
||
task, line = _frozen_task_with_line(
|
||
task_no="OT-UI-FROZEN-ORDER",
|
||
reservation_id="RSV-FROZEN",
|
||
part_number="PN-FROZEN",
|
||
qty="6",
|
||
)
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||
|
||
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
|
||
assert preparation["frozen_order_lines"] == [{
|
||
"snapshot_line_id": line.id,
|
||
"line_no": 1,
|
||
"reservation_id": "RSV-FROZEN",
|
||
"part_number": "PN-FROZEN",
|
||
"required_qty": "6.00000000",
|
||
}]
|
||
assert preparation["lines"][0]["snapshot_line_id"] == line.id
|
||
assert preparation["lines"][0]["line_no"] == 1
|
||
assert preparation["lines"][0]["reservation_id"] == "RSV-FROZEN"
|
||
assert preparation["lines"][0]["part_number"] == "PN-FROZEN"
|
||
assert preparation["lines"][0]["available_qty"] is None
|
||
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 = ShippingOrderTask(
|
||
task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf",
|
||
)
|
||
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 = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf')
|
||
no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf')
|
||
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/OT-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/OT-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/OT-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, snapshot_line = _frozen_task_with_line(
|
||
task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id,
|
||
)
|
||
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, snapshot_line_id=snapshot_line.id, line_no=1, 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/OT-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/OT-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:
|
||
"""行级 Match 的事实字段应补齐冻结订单行的库存展示。"""
|
||
with app.app_context():
|
||
task, snapshot_line = _frozen_task_with_line(
|
||
task_no="OT-UI-STRUCTURED-PARTIAL",
|
||
reservation_id="RSV-LEGACY",
|
||
part_number="PN-LEGACY",
|
||
qty="10",
|
||
)
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id,
|
||
snapshot_line_id=snapshot_line.id,
|
||
line_no=1,
|
||
line_index=0,
|
||
match_result="matched",
|
||
inventory_status="ready",
|
||
required_qty="10",
|
||
available_qty="8",
|
||
shortage_qty="2",
|
||
reservation_id="RSV-LEGACY",
|
||
part_number="PN-LEGACY",
|
||
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, snapshot_line = _frozen_task_with_line(
|
||
task_no="OT-UI-DETAIL-CONTEXT",
|
||
reservation_id="RSV-DETAIL",
|
||
part_number="PN-DETAIL",
|
||
qty="2",
|
||
)
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id,
|
||
snapshot_line_id=snapshot_line.id,
|
||
line_no=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)
|
||
|
||
# 视图函数经 request.args 读取 view 参数,必须包一层请求上下文(直接调用无 request)。
|
||
with app.test_request_context():
|
||
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:
|
||
"""行级多源冲突应覆盖通知准备的暂停原因。"""
|
||
with app.app_context():
|
||
task, snapshot_line = _frozen_task_with_line(
|
||
task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1",
|
||
)
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||
match_result='source_conflict', inventory_status='source_conflict',
|
||
allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True,
|
||
))
|
||
db.session.commit()
|
||
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"
|
||
|
||
|
||
def test_preparation_editable_present_for_live_formal_task(monkeypatch):
|
||
"""活任务(active/blocked/空值)判定可操作;作废/归档/删除/待作废/取消视图不可操作。
|
||
|
||
按 ShippingNotice 真实 lifecycle_status 值域逐值覆盖(不用 WorkflowItem 的
|
||
{'closed', 'cancelled'} 终态集);排除集见 ui_state 的
|
||
_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES 注释。
|
||
"""
|
||
class FakeTask:
|
||
id = 1
|
||
task_no = 'SN-LIVE-1'
|
||
order_task_no = 'SN-LIVE-1'
|
||
# 真实值域:ShippingNotice 无 in_progress 写入方,活任务为 active。
|
||
lifecycle_status = 'active'
|
||
export_file_path = ''
|
||
order_snapshot_id = None
|
||
inventory_source_code = None
|
||
match_status = None
|
||
|
||
# 直接依赖 _build_stage_context 内部较重;此处最小断言 editable 键存在且为 bool 语义。
|
||
# 实现时若 _build_stage_context 依赖过多,改为抽纯谓词 _preparation_editable(task) 单测。
|
||
from app.services.shipping_notice.ui_state import _preparation_editable
|
||
|
||
# 关键断言:活任务(active)判定可操作(任务级 editable=True 语义)。
|
||
assert _preparation_editable(FakeTask()) is True
|
||
|
||
class BlockedTask(FakeTask):
|
||
lifecycle_status = 'blocked'
|
||
|
||
# 关键断言:blocked 是新任务暂堵态(task_supersession_service.py),不算作废/历史
|
||
# 视图,保持可编辑——与 case 级 edit_formal_task 镜像语义一致;闸口语义由
|
||
# pending_human_reason 等机制表达,不在此谓词收紧。
|
||
assert _preparation_editable(BlockedTask()) is True
|
||
|
||
class NoStatusTask(FakeTask):
|
||
lifecycle_status = None
|
||
|
||
# 边界断言:空/缺失 lifecycle_status 不得误判为终态,默认可操作。
|
||
assert _preparation_editable(NoStatusTask()) is True
|
||
|
||
# 关键断言:每个非可操作生命周期必须置 False,供 Prep 波次出单门控拦截——
|
||
# 终态 voided/archived/deleted;co8 只读语义 pending_void
|
||
# (freight_cancellation_service.py:154);兼容双拼 cancelled/canceled。
|
||
for status in ('voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled'):
|
||
class NonEditableTask(FakeTask):
|
||
pass
|
||
NonEditableTask.lifecycle_status = status
|
||
# 意图:该值域命中 _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES → editable=False。
|
||
assert _preparation_editable(NonEditableTask()) is False
|
||
|
||
class NoisyStatusTask(FakeTask):
|
||
lifecycle_status = ' Voided '
|
||
|
||
# 边界断言:strip/lower 归一化必须保留(防终态因空白/大小写漏判为可编辑)。
|
||
assert _preparation_editable(NoisyStatusTask()) is False
|
||
|
||
|
||
def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None:
|
||
"""[断言] preparation 携带任务级 editable(active=True / voided=False);
|
||
行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。"""
|
||
with app.app_context():
|
||
task, first_line = _frozen_task_with_line(
|
||
task_no="OT-UI-PREP-EDITABLE",
|
||
reservation_id="RSV-PO-1", part_number="PN-PO-1", qty="5",
|
||
field_values_json={"customer_po_line_no": "7"},
|
||
)
|
||
second_line = ShippingOrderSnapshotLine(
|
||
snapshot_id=first_line.snapshot_id, position=1, line_no=2,
|
||
reservation_id="RSV-PO-2", part_number="PN-PO-2", qty="3", field_values_json={},
|
||
)
|
||
db.session.add(second_line)
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||
# 关键断言:活任务(默认 active)必须下发任务级可操作标志 True。
|
||
assert preparation["editable"] is True
|
||
# 未绑定 Schema 字段 ID 时,冻结档不会把 field_code 当成正式字段事实。
|
||
assert preparation["lines"][0]["customer_po_line_no"] is None
|
||
# 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。
|
||
assert preparation["lines"][1]["customer_po_line_no"] is None
|