feat(chat): 优化发货相关消息处理逻辑

- 在列出聊天消息时,过滤掉类型为'shipping-parse-review'的消息
- 移除不再使用的shippingConversationTaskIdCache
- 更新发货决策处理逻辑,简化保存消息的参数
- 添加发货动作按钮刷新时的任务定位优先级逻辑
- 移除解析复核消息的展示逻辑,统一处理到轻量工作台
- 增加单元测试,验证发货动作按钮刷新时的任务定位优先级
This commit is contained in:
hugo committed 2026-07-01 08:57:36 +08:00
1 parent 9f5493185d
commit 6a0a51313f
18 files changed
+1230 -199

No files matched your search

+3
View File
@@ -985,6 +985,9 @@ def save_local_message():
if role == 'user':
user_query = user_query or content
content = ''
else:
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
user_query = ''
if not message_type:
raise ValidationError('type is required')
+2 -1
View File
@@ -67,10 +67,11 @@ def build_hxops_context(
normalized_refs.append({"field": field, "value": value})
seen_fields.add(field)
return {
payload: dict[str, Any] = {
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
"session": {"id": normalized_session_id},
"request": request_payload,
"refs": normalized_refs,
}
return payload
@@ -37,17 +37,12 @@ def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None
)
def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
"""按会话号获取最近一个未拒绝任务,用于恢复当前任务焦点。"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
def _task_by_task_no(task_id: str) -> ShippingTask | None:
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
normalized = str(task_id or "").strip().upper()
if not normalized:
return None
return (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(["rejected"]))
.order_by(ShippingTask.id.desc())
.first()
)
return ShippingTask.query.filter_by(task_no=normalized).first()
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
@@ -81,24 +76,22 @@ def build_dify_chat_inputs(
explicit_batch = str(batch_no or "").strip().upper()
batch = _latest_batch_for_conversation(conv_id)
task = _latest_task_for_conversation(conv_id)
explicit_task_row = _task_by_task_no(explicit_task)
focus_task = explicit_task
if not focus_task and batch and batch.current_focus_task_no:
focus_task = str(batch.current_focus_task_no or "").strip().upper()
elif not focus_task and task and task.task_no:
focus_task = str(task.task_no or "").strip().upper()
focus_batch = explicit_batch
if not focus_batch and batch and batch.batch_no:
focus_batch = str(batch.batch_no or "").strip().upper()
elif (
not focus_batch
and task
and getattr(task, "batch", None) is not None
and getattr(task.batch, "batch_no", None)
and explicit_task_row
and getattr(explicit_task_row, "batch", None) is not None
and getattr(explicit_task_row.batch, "batch_no", None)
):
focus_batch = str(task.batch.batch_no or "").strip().upper()
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
hxops_context = build_hxops_context(
session_id=conv_id,
@@ -15,8 +15,7 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ChatLog, ShippingBatch, ShippingTask
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_OK,
@@ -133,75 +132,13 @@ def start_task_orchestrator(task_no: str | None) -> bool:
return _start(task_no)
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
return {
"taskId": task.task_no,
"checkpoint": "parse_review",
"header": {
"customer_name": task.customer_name,
"customer_code": task.customer_code,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
},
"lines": task.lines_json or [],
"saving": False,
}
def _upsert_parse_review_chat_message(task: ShippingTask) -> None:
"""
将 parse_review 结果直接回填到当前聊天会话。
保留旧调用点但不再写聊天表单消息。
设计意图:
- 不再依赖“前端再次发一轮消息”去索取解析结果;
- 同任务只保留一条 shipping-parse-review 消息,重复解析时直接更新。
核心逻辑:解析复核动作统一由当前任务动作按钮和轻量工作台承载,避免可编辑表单进入聊天历史后在其他会话复活。
"""
session_id = str(task.conversation_id or "").strip()
if not session_id or not task.user_id:
return
agent = resolve_chat_agent()
if not agent or not getattr(agent, "id", None):
return
payload = _build_parse_review_chat_payload(task)
content = f"请确认或修订以下解析结果。\n任务编号:{task.task_no}"
chat_logs = (
db.session.query(ChatLog)
.filter_by(
user_id=task.user_id,
agent_id=agent.id,
session_id=session_id,
message_type="shipping-parse-review",
)
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
.all()
)
existing = None
for item in chat_logs:
item_payload = item.payload if isinstance(item.payload, dict) else {}
if str(item_payload.get("taskId") or "").strip().upper() == str(task.task_no or "").strip().upper():
existing = item
break
if existing:
existing.answer = content
existing.payload = payload
return
db.session.add(
ChatLog(
user_id=task.user_id,
agent_id=agent.id,
conversation_id=session_id,
session_id=session_id,
query="",
answer=content,
message_type="shipping-parse-review",
payload=payload,
)
)
_ = task
def recompute_batch_summary(batch: ShippingBatch | None) -> None:
@@ -1124,6 +1124,7 @@ def test_build_dify_chat_inputs_returns_hxops_context_only(app):
{"field": "task", "value": "SN-20260622-DDDD0004"},
{"field": "batch", "value": "SB-DIFY-INPUTS"},
]
assert "instructions" not in inputs["hxops_context"]
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
@@ -1158,6 +1159,32 @@ def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation
]
def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explicit_anchor(app):
"""多票/无码头场景缺少显式锚点时,不应按最近任务给 Dify 注入 task ref。"""
with app.app_context():
conversation_id = "conv-shipping-no-anchor-001"
older_task = ShippingTask(
task_no="SN-20260630-OLDER001",
conversation_id=conversation_id,
source_type="manual",
process_status="created",
)
newer_task = ShippingTask(
task_no="SN-20260630-NEWER001",
conversation_id=conversation_id,
source_type="manual",
process_status="created",
)
db.session.add_all([older_task, newer_task])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["session"]["id"] == conversation_id
assert inputs["hxops_context"]["refs"] == []
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
class AgentLike:
+44 -1
View File
@@ -1,7 +1,7 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
@@ -1177,6 +1177,49 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app, client):
headers = _tool_headers(app)
with app.app_context():
from app.models import User
user = User(username="parse_review_card_user", email="parse_review_card_user@example.com")
db.session.add(user)
db.session.commit()
user_id = user.id
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-no-parse-card", "user_id": user_id},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"conversation_id": "conv-no-parse-card",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "needs_human"
assert parse_data.get("checkpoint") == "parse_review"
with app.app_context():
assert db.session.query(ChatLog).filter_by(
session_id="conv-no-parse-card",
message_type="shipping-parse-review",
).count() == 0
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
+33 -1
View File
@@ -56,7 +56,7 @@ def test_chat_history_with_query_param(client):
# 1. Test without agent_id (Should fail with 400)
res = client.get('/api/chat/sessions', headers=headers)
assert res.status_code == 400
assert 'agent_id is required' in res.get_json()['error']
assert res.get_json()['error']['message'] == 'agent_id is required'
# 2. Test with agent_id in query string (Should succeed)
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
@@ -86,6 +86,38 @@ def test_chat_messages_history(client):
assert msgs[1]['content'] == 'Hello'
def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
"""助手本地消息即使误传 query,历史回放也不能多生成一条用户确认。"""
headers = get_headers(client)
user_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
'conversation_id': 'conv-local-confirm',
'role': 'user',
'type': 'text',
'content': '确认\n任务编号:SN-001',
'query': '确认',
})
assert user_res.status_code == 200
assistant_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
'conversation_id': 'conv-local-confirm',
'role': 'assistant',
'type': 'text',
'content': '已确认,进入下一步。',
'query': '确认',
})
assert assistant_res.status_code == 200
res = client.get('/api/chat/messages?conversation_id=conv-local-confirm&agent_id=1', headers=headers)
assert res.status_code == 200
msgs = res.get_json()
user_messages = [item for item in msgs if item['role'] == 'user']
assert len(user_messages) == 1
assert user_messages[0]['content'] == '确认'
assert msgs[-1]['role'] == 'assistant'
assert msgs[-1]['content'] == '已确认,进入下一步。'
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
headers = get_headers(client)