- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划
1390 lines
61 KiB
Python
1390 lines
61 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 待上传入口面正确;
|
||
stage_context.preparation 短缺行投影 release_required_fields;
|
||
preparation.source_options 下发已启用源供行级覆写下拉;
|
||
行级 selected_source_code(Candidate)与 source_code(Match)分字段;
|
||
Notice 详情经 order_task_id→OT 读取 Snapshot/Match。
|
||
"""
|
||
|
||
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 (
|
||
POSITION_EXPORT_READY,
|
||
POSITION_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",
|
||
"user_mode",
|
||
"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())
|
||
# 无 Gate 时按领域标量回退:parse_review 不得再被 OT 空 stage 盖成 order_freeze。
|
||
assert state["position"] == POSITION_PARSE_REVIEW
|
||
assert state["user_mode"] == "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 = 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_notice_uses_ot_stage_not_freeze_gate_lifecycle(app) -> None:
|
||
"""
|
||
Notice 路径必须读 OT.stage 做五阶段,禁止仅靠 order_freeze→order_review 兜底。
|
||
|
||
断言意图:OT.stage=order_creating 时,任务中心/详情与批次同为 fulfillment_prep,
|
||
不得因 Notice 无 stage 列 + freeze Gate 显示「订单复核」。
|
||
"""
|
||
with app.app_context():
|
||
from app.services.shipping_notice.process_gate_service import (
|
||
ensure_execution_for_workflow_version,
|
||
)
|
||
from app.services.shipping_notice.ui_state import (
|
||
_process_gate_user_summary_for_task,
|
||
_task_lifecycle,
|
||
)
|
||
|
||
user = User(
|
||
username='ui-notice-ot-stage',
|
||
email='ui-notice-ot-stage@example.com',
|
||
password_hash='x',
|
||
)
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
order_task = ShippingOrderTask(
|
||
task_no='OT-UI-NOTICE-OT-STAGE',
|
||
user_id=user.id,
|
||
source_type='direct_pdf',
|
||
status='waiting_review',
|
||
stage='order_creating',
|
||
progress_version=1,
|
||
)
|
||
db.session.add(order_task)
|
||
db.session.flush()
|
||
notice = ShippingNotice(
|
||
task_no='SN-UI-NOTICE-OT-STAGE',
|
||
user_id=user.id,
|
||
source_type='manual',
|
||
order_task_id=int(order_task.id),
|
||
)
|
||
db.session.add(notice)
|
||
db.session.flush()
|
||
execution = ensure_execution_for_workflow_version(
|
||
task_id=int(order_task.id), actor_type='system',
|
||
)
|
||
execution.status = 'blocked'
|
||
execution.current_gate_code = 'order_freeze_readiness'
|
||
order_task.active_process_execution_id = int(execution.id)
|
||
# ensure_execution 在已有 Notice 时会 sync_order_task_stage_for_notice,
|
||
# 可能把 stage 写成 waiting_review;本用例要验证「已写入的 order_creating」权威。
|
||
order_task.stage = 'order_creating'
|
||
order_task.status = 'waiting_review'
|
||
db.session.commit()
|
||
|
||
process_gate = _process_gate_user_summary_for_task(notice)
|
||
lifecycle = _task_lifecycle(task=notice, position=None, process_gate=process_gate)
|
||
|
||
assert lifecycle['lifecycle_stage'] == 'fulfillment_prep'
|
||
assert lifecycle['lifecycle_authority'] == 'processing_stage'
|
||
assert lifecycle['lifecycle_stage'] != 'order_review'
|
||
|
||
|
||
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||
"""无正式 Gate 时位置不能再推导五阶段或任何可写 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,不能按旧位置码生成。"""
|
||
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'
|
||
# Notice/OT 无合法 stage 时由 Gate 抬升为 inventory_matching,权威记为 processing_stage。
|
||
assert state['lifecycle_authority'] == 'processing_stage'
|
||
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"] == "review_workbench"
|
||
|
||
|
||
def test_build_task_ui_state_queries_process_gate_once(app, monkeypatch) -> None:
|
||
"""build_task_ui_state 同一次构建只查 Gate 摘要一次,禁止再经 resolve 二次查库。"""
|
||
with app.app_context():
|
||
calls = {'n': 0}
|
||
|
||
def _fake_gate(_task):
|
||
calls['n'] += 1
|
||
return {
|
||
'current_gate_code': 'inventory_sufficiency',
|
||
'status': 'blocked',
|
||
'lifecycle_stage': 'fulfillment_prep',
|
||
'current_blocking_gate': {
|
||
'gate_code': 'inventory_sufficiency',
|
||
'status': 'blocked_manual',
|
||
},
|
||
'primary_action': None,
|
||
'action_presentation': [],
|
||
}
|
||
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||
_fake_gate,
|
||
)
|
||
task = ShippingOrderTask(task_no="OT-UI-GATE-ONCE", user_id=1, source_type="direct_pdf")
|
||
state = build_task_ui_state(task)
|
||
assert calls['n'] == 1
|
||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||
|
||
|
||
def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
|
||
"""Gate artifact_generation 投影 export_ready 时进入工作台;未验证 Artifact 不得授权下载。"""
|
||
with app.app_context():
|
||
task = ShippingNotice(
|
||
task_no="SN-UI-EXPORT",
|
||
source_type="manual",
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||
lambda _task: {
|
||
'current_gate_code': 'artifact_generation',
|
||
'status': 'waiting_human',
|
||
'lifecycle_stage': 'freight_upload',
|
||
'current_blocking_gate': {
|
||
'gate_code': 'artifact_generation',
|
||
'status': 'blocked_manual',
|
||
},
|
||
},
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||
lambda _task: None,
|
||
)
|
||
state = build_task_ui_state(task)
|
||
assert state["position"] == POSITION_EXPORT_READY
|
||
# Gate freight_upload + waiting_human → wait_manual_upload
|
||
assert state["user_mode"] == "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 时不得生成下载按钮。
|
||
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_gates_download_by_viewer(app, monkeypatch) -> None:
|
||
"""下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。"""
|
||
with app.app_context():
|
||
from app import db
|
||
|
||
task = ShippingNotice(
|
||
task_no="SN-UI-VIEWER-EXPORT",
|
||
source_type="manual",
|
||
user_id=7,
|
||
)
|
||
db.session.add(task)
|
||
db.session.commit()
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||
)
|
||
|
||
def button_ids(state):
|
||
return [
|
||
item.get("code")
|
||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||
if item
|
||
]
|
||
|
||
# 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。
|
||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7))
|
||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True))
|
||
# 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。
|
||
assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8))
|
||
# viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。
|
||
assert "download_excel" in button_ids(build_task_ui_state(task))
|
||
|
||
|
||
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"] == []
|
||
assert line["can_fulfill_complete_line"] is True
|
||
# §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_hides_inventory_actions_while_rpa_running(app) -> None:
|
||
"""库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。
|
||
|
||
与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。
|
||
"""
|
||
from app.models import ShippingTaskInventoryRpaAttempt
|
||
|
||
with app.app_context():
|
||
user = User(username='ui-rpa-running', email='ui-rpa-running@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', 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-RPA', part_number='PN-RPA', 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-RPA',
|
||
part_number='PN-RPA',
|
||
inventory_source_code='DBS_DUB',
|
||
is_current=True,
|
||
))
|
||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||
task_no=task.task_no,
|
||
source_code='DBS_DUB',
|
||
attempt_no=1,
|
||
source_run_no='PSR-UI-RPA-1',
|
||
status='running',
|
||
))
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||
line = preparation['lines'][0]
|
||
# 关键断言:RPA 运行中必须清空库存动作,前端 Bot 不得渲染/触发。
|
||
assert line['user_line_status'] == 'acquiring_inventory'
|
||
assert line['inventory_allowed_actions'] == []
|
||
|
||
|
||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
|
||
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||
lambda enabled_only=True: [
|
||
{'source_code': 'src_a', 'display_name': 'Source A'},
|
||
{'source_code': 'SRC_B', 'display_name': ''},
|
||
],
|
||
)
|
||
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
|
||
# 关键断言:行级覆写下拉依赖 preparation.source_options;编码统一大写。
|
||
assert preparation['source_options'] == [
|
||
{'source_code': 'SRC_A', 'display_name': 'Source A'},
|
||
{'source_code': 'SRC_B', 'display_name': 'SRC_B'},
|
||
]
|
||
|
||
|
||
def test_stage_context_projects_selected_source_without_backfilling_match_source(app) -> None:
|
||
"""CandidateSet 单源只填 selected_source_code,禁止回填 Match 的 source_code。"""
|
||
with app.app_context():
|
||
task, line = _frozen_task_with_line(
|
||
task_no='OT-UI-SELECTED-SOURCE',
|
||
reservation_id='RSV-SEL',
|
||
part_number='PN-SEL',
|
||
qty='2',
|
||
)
|
||
candidate_set = ShippingInventoryCandidateSet(
|
||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='b' * 64,
|
||
)
|
||
db.session.add(candidate_set)
|
||
db.session.flush()
|
||
db.session.add(ShippingInventoryCandidateSource(
|
||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||
))
|
||
db.session.add(ShippingInventoryCandidateLine(
|
||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||
))
|
||
task.active_inventory_candidate_set_id = candidate_set.id
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||
row = preparation['lines'][0]
|
||
# 关键断言:取数目标与匹配结论分字段;未匹配时 source_code 必须为空。
|
||
assert row['snapshot_line_id'] == line.id
|
||
assert row['selected_source_code'] == 'DSV360_AWSSG'
|
||
assert row['source_code'] is None
|
||
assert row['source_ambiguous'] is False
|
||
|
||
|
||
def test_stage_context_notice_resolves_ot_match_and_selected_source(app) -> None:
|
||
"""Notice 详情入口须经 order_task_id→OT 读 Snapshot/Match/Candidate,禁止用 Notice.id。"""
|
||
with app.app_context():
|
||
# 垫偏 OT.id,避免空库 Notice.id==OT.id 碰巧绿。
|
||
for index in range(3):
|
||
db.session.add(ShippingOrderTask(
|
||
task_no=f'OT-UI-SPACER-{index}', user_id=1, source_type='direct_pdf',
|
||
))
|
||
db.session.flush()
|
||
task, line = _frozen_task_with_line(
|
||
task_no='OT-UI-NOTICE-RESOLVE',
|
||
reservation_id='RSV-NOTICE',
|
||
part_number='PN-NOTICE',
|
||
qty='3',
|
||
)
|
||
candidate_set = ShippingInventoryCandidateSet(
|
||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64,
|
||
)
|
||
db.session.add(candidate_set)
|
||
db.session.flush()
|
||
db.session.add(ShippingInventoryCandidateSource(
|
||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||
))
|
||
db.session.add(ShippingInventoryCandidateLine(
|
||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||
))
|
||
task.active_inventory_candidate_set_id = candidate_set.id
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||
match_result='matched', inventory_status='ready', required_qty='3', available_qty='3',
|
||
matched_qty='3', shortage_qty='0', reservation_id='RSV-NOTICE', part_number='PN-NOTICE',
|
||
inventory_source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True,
|
||
))
|
||
notice = ShippingNotice(
|
||
task_no='SN-UI-NOTICE-RESOLVE',
|
||
source_type='manual',
|
||
user_id=1,
|
||
order_task_id=task.id,
|
||
)
|
||
db.session.add(notice)
|
||
db.session.commit()
|
||
|
||
assert int(notice.id) != int(task.id)
|
||
preparation = build_task_ui_state(notice, include_stage_context=True)['stage_context']['preparation']
|
||
row = preparation['lines'][0]
|
||
# 关键断言:SN 入口仍投影 OT 上的匹配正式源与取数目标。
|
||
assert preparation['frozen_order']['task_no'] == task.task_no
|
||
assert preparation['frozen_order']['snapshot_id'] == task.order_snapshot_id
|
||
assert row['source_code'] == 'DSV360_AWSSG'
|
||
assert row['selected_source_code'] == 'DSV360_AWSSG'
|
||
assert preparation['has_match_result'] is True
|
||
|
||
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_preparation_lines_carry_part_available_qty(app) -> None:
|
||
"""prep 行必须下发料号兜底总量,供前端新增「可用数量」列。"""
|
||
with app.app_context():
|
||
task, line = _frozen_task_with_line(
|
||
task_no="OT-UI-PART-AVAILABLE",
|
||
reservation_id="RSV-PART-AVAIL",
|
||
part_number="PN-PART-AVAIL",
|
||
qty="8",
|
||
)
|
||
# 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||
match_result="matched", inventory_status="ready", required_qty="8",
|
||
available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9",
|
||
reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL",
|
||
inventory_source_code="DBS_DUB", is_current=True,
|
||
))
|
||
db.session.commit()
|
||
|
||
state = build_task_ui_state(task, include_stage_context=True)
|
||
prep_line = state["stage_context"]["preparation"]["lines"][0]
|
||
# 断言意图:ui_state 单源直透投影值,前端不做二次推导;不下发任何派生布尔标志。
|
||
assert prep_line["part_available_qty"] == "9"
|
||
|
||
|
||
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_line_actions_without_match_rows(app) -> None:
|
||
"""正式 OT 无匹配行时,preparation.lines 仍须下发明细库存重试动作。
|
||
|
||
断言:has_formal_ot 不得用 current_match_rows 判定;无 match 时 fact 兜底 preparing,
|
||
inventory_allowed_actions 含 retry_inventory_preparation。
|
||
"""
|
||
with app.app_context():
|
||
user = User(username='ui-no-match-actions', email='ui-no-match-actions@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
task, _line = _frozen_task_with_line(
|
||
task_no='OT-UI-NO-MATCH-ACTIONS',
|
||
user_id=user.id,
|
||
reservation_id='RSV-NM-1',
|
||
part_number='PN-NM-1',
|
||
qty='4',
|
||
)
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||
assert preparation["has_match_result"] is False
|
||
assert len(preparation["lines"]) == 1
|
||
line = preparation["lines"][0]
|
||
# 关键断言:无 Match 行时明细仍可点「重试库存准备」,不得因 has_formal_ot=False 空动作。
|
||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||
assert "close_unfulfillable" in line["line_allowed_actions"]
|
||
|
||
|
||
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
|
||
|
||
|
||
def test_stage_context_preparation_projects_shortage_release_template_fields(app) -> None:
|
||
"""短缺行必须按库存源发货模板投影人工补录字段,禁止 fail-closed 空列表。"""
|
||
from app.models import (
|
||
ShippingExcelTemplate,
|
||
ShippingInventoryField,
|
||
ShippingInventorySource,
|
||
ShippingOrderSchema,
|
||
ShippingOrderSchemaVersion,
|
||
)
|
||
|
||
with app.app_context():
|
||
location = ShippingInventoryField.query.filter_by(field_code='location').one()
|
||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||
template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id))
|
||
assert template is not None
|
||
template.definition_json = {
|
||
'mappings': [
|
||
{
|
||
'row_mode': 'line',
|
||
'source_kind': 'inventory_field',
|
||
'source_key': str(location.id),
|
||
},
|
||
],
|
||
}
|
||
|
||
user = User(username='ui-release-fields', email='ui-release-fields@example.com')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
schema = ShippingOrderSchema(schema_code='UI_RELEASE_FIELDS', display_name='UI Release Fields')
|
||
db.session.add(schema)
|
||
db.session.flush()
|
||
schema_version = ShippingOrderSchemaVersion(
|
||
schema_id=schema.id,
|
||
version=1,
|
||
status='published',
|
||
definition_json={'fields': []},
|
||
)
|
||
db.session.add(schema_version)
|
||
db.session.flush()
|
||
|
||
task = ShippingOrderTask(
|
||
task_no='OT-UI-RELEASE-FIELDS',
|
||
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=schema_version.id,
|
||
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-RELEASE',
|
||
part_number='PN-RELEASE',
|
||
qty='10',
|
||
field_values_json={},
|
||
)
|
||
db.session.add(snapshot_line)
|
||
db.session.flush()
|
||
# 无库存快照时模板库存字段全部人工补录;源码必须能解析到 published 发货模板。
|
||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||
task_id=task.id,
|
||
snapshot_line_id=snapshot_line.id,
|
||
line_no=1,
|
||
line_index=0,
|
||
match_result='not_found',
|
||
inventory_status='ready',
|
||
required_qty='10',
|
||
available_qty='0',
|
||
matched_qty='0',
|
||
shortage_qty='10',
|
||
reservation_id='RSV-RELEASE',
|
||
part_number='PN-RELEASE',
|
||
inventory_source_code='DSV360_AWSDU',
|
||
inventory_snapshot_id=None,
|
||
is_current=True,
|
||
))
|
||
db.session.commit()
|
||
|
||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||
line = preparation['lines'][0]
|
||
|
||
assert line['is_shortage'] is True
|
||
assert line['release_field_resolution_error'] is None
|
||
assert line['release_required_fields'] == [
|
||
{'field_id': str(location.id), 'display_name': '库位'},
|
||
]
|
||
assert line['release_template_fields'] == [
|
||
{
|
||
'field_id': str(location.id),
|
||
'display_name': '库位',
|
||
'value': None,
|
||
'value_source': 'manual_required',
|
||
'requires_manual': True,
|
||
},
|
||
]
|