""" backend/tests/test_shipping_notice_reference_context.py 用途:验证发货通知 reference_context 的 focus/动作/失败候选摘要构建。 依赖:models.ShippingBatch/ShippingTask/ShippingTaskEvent、shipping_notice.reference_context。 逻辑:直接构造批次、任务与少量事件,确保 Dify 只拿到短期指代线索,不会收到整批任务明细。 """ from __future__ import annotations import json from datetime import datetime, timedelta from app import db from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent from app.services.agent_runtime_context.policy import MAX_RECENT_ACTIVITY_SUMMARY_CHARS from app.services.shipping_notice.reference_context import build_shipping_reference_context def _make_task( *, task_no: str, batch: ShippingBatch, updated_at: datetime, process_status: str = "created", current_step: str | None = None, pending_human_reason: str | None = None, review_status: str | None = None, match_status: str | None = None, upload_status: str | None = None, shortage_json: dict | None = None, error_message: str | None = None, ) -> ShippingTask: """构造测试任务,减少样板字段噪音。""" return ShippingTask( task_no=task_no, batch=batch, conversation_id=batch.conversation_id, source_type="manual", process_status=process_status, current_step=current_step, pending_human_reason=pending_human_reason, review_status=review_status, match_status=match_status, upload_status=upload_status, shortage_json=shortage_json, error_message=error_message, updated_at=updated_at, created_at=updated_at - timedelta(minutes=5), ) def test_build_shipping_reference_context_includes_focus_and_last_action(app): """当前 focus task 与最近确认动作应进入 reference_context。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-001", conversation_id="conv-ref-001", current_focus_task_no="SN-REF-FOCUS-001", file_count=2, ) action_task = _make_task( task_no="SN-REF-ACTION-001", batch=batch, updated_at=datetime(2026, 7, 2, 9, 0, 0), process_status="parsed", ) focus_task = _make_task( task_no="SN-REF-FOCUS-001", batch=batch, updated_at=datetime(2026, 7, 2, 9, 5, 0), process_status="pending_review", current_step="step2_parse_confirm", ) db.session.add_all([batch, action_task, focus_task]) db.session.flush() db.session.add( ShippingTaskEvent( task_id=action_task.id, event_type="parse_confirmed", detail_json={"comment": "ok"}, created_at=datetime(2026, 7, 2, 9, 6, 0), ) ) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=focus_task) assert context["focus_object"] == {"type": "task", "id": "SN-REF-FOCUS-001"} assert context["last_action_target"] == { "type": "task", "id": "SN-REF-ACTION-001", "action": "confirm_parse", } assert "当前 focus 为 SN-REF-FOCUS-001" in context["recent_activity_summary"] assert "用户已确认 SN-REF-ACTION-001 解析" in context["recent_activity_summary"] def test_build_shipping_reference_context_includes_last_failed_target(app): """最近失败任务应收敛为 last_failed_target,而不是要求 Dify 自己遍历整批任务。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-FAIL", conversation_id="conv-ref-fail", current_focus_task_no="SN-REF-FOCUS-002", file_count=2, ) focus_task = _make_task( task_no="SN-REF-FOCUS-002", batch=batch, updated_at=datetime(2026, 7, 2, 10, 0, 0), process_status="inventory_ready", ) failed_task = _make_task( task_no="SN-REF-FAIL-002", batch=batch, updated_at=datetime(2026, 7, 2, 10, 10, 0), process_status="pending_review", match_status="shortage", pending_human_reason="shortage", shortage_json={"A001": 10}, ) db.session.add_all([batch, focus_task, failed_task]) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=focus_task) assert context["last_failed_target"] == { "type": "task", "id": "SN-REF-FAIL-002", "reason": "shortage", "label": "异常:库存不足", } assert "SN-REF-FAIL-002 库存匹配失败" in context["recent_activity_summary"] def test_build_shipping_reference_context_limits_candidates_to_failure_tasks(app): """candidates 只应暴露少量失败/异常任务,不应把正常任务或整批明细塞进 context。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-CAND", conversation_id="conv-ref-cand", current_focus_task_no="SN-REF-FOCUS-003", file_count=5, ) focus_task = _make_task( task_no="SN-REF-FOCUS-003", batch=batch, updated_at=datetime(2026, 7, 2, 11, 0, 0), process_status="parsed", ) shortage_task = _make_task( task_no="SN-REF-SHORT-003", batch=batch, updated_at=datetime(2026, 7, 2, 11, 1, 0), process_status="pending_review", match_status="shortage", pending_human_reason="shortage", shortage_json={"A001": 1}, ) rejected_task = _make_task( task_no="SN-REF-REJECT-003", batch=batch, updated_at=datetime(2026, 7, 2, 11, 2, 0), process_status="rejected", review_status="rejected", ) upload_failed_task = _make_task( task_no="SN-REF-UPFAIL-003", batch=batch, updated_at=datetime(2026, 7, 2, 11, 3, 0), process_status="upload_failed", upload_status="failed", pending_human_reason="upload_rpa_failed", ) normal_task = _make_task( task_no="SN-REF-NORMAL-003", batch=batch, updated_at=datetime(2026, 7, 2, 11, 4, 0), process_status="matched", ) db.session.add_all([batch, focus_task, shortage_task, rejected_task, upload_failed_task, normal_task]) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=focus_task) candidates = {item["id"]: item["label"] for item in context["candidates"]} assert candidates == { "SN-REF-UPFAIL-003": "异常:上传失败", "SN-REF-REJECT-003": "已驳回", "SN-REF-SHORT-003": "异常:库存不足", } assert "SN-REF-NORMAL-003" not in json.dumps(context, ensure_ascii=False) def test_build_shipping_reference_context_controls_summary_length_and_avoids_full_batch_dump(app): """多任务批次应只输出短摘要,不能把所有 task_no 都拼进 recent_activity_summary。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-SUMMARY", conversation_id="conv-ref-summary", current_focus_task_no="SN-REF-FOCUS-004", file_count=10, ) focus_task = _make_task( task_no="SN-REF-FOCUS-004", batch=batch, updated_at=datetime(2026, 7, 2, 12, 0, 0), process_status="parsed", ) db.session.add_all([batch, focus_task]) for index in range(10): db.session.add( _make_task( task_no=f"SN-REF-NOISE-{index:03d}", batch=batch, updated_at=datetime(2026, 7, 2, 12, 1, 0) + timedelta(minutes=index), process_status="pending_review" if index % 2 == 0 else "matched", match_status="shortage" if index == 0 else None, pending_human_reason="shortage" if index == 0 else None, shortage_json={"SKU": index} if index == 0 else None, ) ) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=focus_task) summary = context["recent_activity_summary"] assert len(summary) <= MAX_RECENT_ACTIVITY_SUMMARY_CHARS assert "SN-REF-FOCUS-004" in summary assert "SN-REF-NOISE-000" in summary assert "SN-REF-NOISE-009" not in summary def test_build_shipping_reference_context_maps_real_decision_event_names(app): """真实决策事件名应能映射到标准 action,避免 reference builder 只认理想化别名。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-ACTION-MAP", conversation_id="conv-ref-action-map", current_focus_task_no="SN-REF-ACTION-MAP-001", file_count=2, ) reject_task = _make_task( task_no="SN-REF-REJECT-REAL", batch=batch, updated_at=datetime(2026, 7, 2, 13, 0, 0), process_status="rejected", review_status="rejected", ) focus_task = _make_task( task_no="SN-REF-ACTION-MAP-001", batch=batch, updated_at=datetime(2026, 7, 2, 13, 1, 0), process_status="parsed", ) db.session.add_all([batch, reject_task, focus_task]) db.session.flush() db.session.add_all([ ShippingTaskEvent( task_id=reject_task.id, event_type="decision_rejected", detail_json={"action": "reject", "target_id": reject_task.task_no}, created_at=datetime(2026, 7, 2, 13, 2, 0), ), ShippingTaskEvent( task_id=focus_task.id, event_type="decision_rematch", detail_json={"action": "rematch", "target_id": focus_task.task_no}, created_at=datetime(2026, 7, 2, 13, 3, 0), ), ]) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=focus_task) assert context["last_action_target"] == { "type": "task", "id": "SN-REF-ACTION-MAP-001", "action": "rematch", } assert context["last_failed_target"]["id"] == "SN-REF-REJECT-REAL" assert context["last_failed_target"]["reason"] == "rejected" def test_build_shipping_reference_context_recognizes_focus_switch_event(app): """focus_switched 应能进入 last_action_target,供 Dify 理解“刚才切过去那个”。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-SWITCH", conversation_id="conv-ref-switch", current_focus_task_no="SN-REF-SWITCH-002", file_count=2, ) old_focus = _make_task( task_no="SN-REF-SWITCH-001", batch=batch, updated_at=datetime(2026, 7, 2, 14, 0, 0), process_status="parsed", ) new_focus = _make_task( task_no="SN-REF-SWITCH-002", batch=batch, updated_at=datetime(2026, 7, 2, 14, 5, 0), process_status="pending_review", ) db.session.add_all([batch, old_focus, new_focus]) db.session.flush() db.session.add( ShippingTaskEvent( task_id=new_focus.id, event_type="focus_switched", detail_json={ "action": "switch_focus", "target_id": new_focus.task_no, "previous_focus_task_no": old_focus.task_no, "next_focus_task_no": new_focus.task_no, }, created_at=datetime(2026, 7, 2, 14, 6, 0), ) ) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=new_focus) assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-002"} assert context["last_action_target"] == { "type": "task", "id": "SN-REF-SWITCH-002", "action": "switch_focus", } assert "用户已切换 focus 到 SN-REF-SWITCH-002" in context["recent_activity_summary"] def test_build_shipping_reference_context_distinguishes_confirm_parse_and_confirm_matched(app): """parse_confirmed 与 decision_confirmed 应映射到不同 action,避免“确认解析”和“确认匹配结果”混淆。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-CONFIRM-TYPES", conversation_id="conv-ref-confirm-types", current_focus_task_no="SN-REF-CONFIRM-TYPES-002", file_count=2, ) parse_task = _make_task( task_no="SN-REF-CONFIRM-TYPES-001", batch=batch, updated_at=datetime(2026, 7, 2, 15, 0, 0), process_status="parsed", ) matched_task = _make_task( task_no="SN-REF-CONFIRM-TYPES-002", batch=batch, updated_at=datetime(2026, 7, 2, 15, 1, 0), process_status="matched", ) db.session.add_all([batch, parse_task, matched_task]) db.session.flush() db.session.add_all([ ShippingTaskEvent( task_id=parse_task.id, event_type="parse_confirmed", detail_json={"source": "workspace_api", "target_id": parse_task.task_no}, created_at=datetime(2026, 7, 2, 15, 2, 0), ), ShippingTaskEvent( task_id=matched_task.id, event_type="decision_confirmed", detail_json={"source": "workspace_api", "target_id": matched_task.task_no}, created_at=datetime(2026, 7, 2, 15, 3, 0), ), ]) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=matched_task) assert context["last_action_target"] == { "type": "task", "id": "SN-REF-CONFIRM-TYPES-002", "action": "confirm_matched", } assert "用户已确认 SN-REF-CONFIRM-TYPES-002 当前结果" in context["recent_activity_summary"] def test_build_shipping_reference_context_prefers_user_focus_switch_over_auto_switch(app): """用户切票与系统自动切票并存时,应优先保留用户动作,避免“刚才那个”被后台动作覆盖。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-SWITCH-PRIORITY", conversation_id="conv-ref-switch-priority", current_focus_task_no="SN-REF-SWITCH-PRIORITY-002", file_count=2, ) user_focus = _make_task( task_no="SN-REF-SWITCH-PRIORITY-001", batch=batch, updated_at=datetime(2026, 7, 2, 16, 0, 0), process_status="parsed", ) auto_focus = _make_task( task_no="SN-REF-SWITCH-PRIORITY-002", batch=batch, updated_at=datetime(2026, 7, 2, 16, 1, 0), process_status="pending_review", ) db.session.add_all([batch, user_focus, auto_focus]) db.session.flush() db.session.add_all([ ShippingTaskEvent( task_id=user_focus.id, event_type="focus_switched", detail_json={"source": "workspace_api", "target_id": user_focus.task_no}, created_at=datetime(2026, 7, 2, 16, 2, 0), ), ShippingTaskEvent( task_id=auto_focus.id, event_type="focus_auto_switched", detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no}, created_at=datetime(2026, 7, 2, 16, 3, 0), ), ]) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=auto_focus) assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-PRIORITY-002"} assert context["last_action_target"] == { "type": "task", "id": "SN-REF-SWITCH-PRIORITY-001", "action": "switch_focus", } assert "用户已切换 focus 到 SN-REF-SWITCH-PRIORITY-001" in context["recent_activity_summary"] def test_build_shipping_reference_context_uses_auto_focus_when_only_auto_switch_exists(app): """只有系统自动切票时,应显式暴露 auto_focus,避免与用户手动切票混淆。""" with app.app_context(): batch = ShippingBatch( batch_no="SB-REF-AUTO-FOCUS", conversation_id="conv-ref-auto-focus", current_focus_task_no="SN-REF-AUTO-FOCUS-002", file_count=2, ) old_focus = _make_task( task_no="SN-REF-AUTO-FOCUS-001", batch=batch, updated_at=datetime(2026, 7, 2, 17, 0, 0), process_status="parsed", ) auto_focus = _make_task( task_no="SN-REF-AUTO-FOCUS-002", batch=batch, updated_at=datetime(2026, 7, 2, 17, 1, 0), process_status="pending_review", ) db.session.add_all([batch, old_focus, auto_focus]) db.session.flush() db.session.add( ShippingTaskEvent( task_id=auto_focus.id, event_type="focus_auto_switched", detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no}, created_at=datetime(2026, 7, 2, 17, 2, 0), ) ) db.session.commit() context = build_shipping_reference_context(batch=batch, focus_task=auto_focus) assert context["focus_object"] == {"type": "task", "id": "SN-REF-AUTO-FOCUS-002"} assert context["last_action_target"] == { "type": "task", "id": "SN-REF-AUTO-FOCUS-002", "action": "auto_focus", } assert "系统自动聚焦到 SN-REF-AUTO-FOCUS-002" in context["recent_activity_summary"]