feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
+9
-176
@@ -2,10 +2,8 @@
|
||||
backend/app/api/chat.py
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、app.core.response、services.dify、integrations、
|
||||
shipping_notice.audit_service(货代会话删除审计)。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError;
|
||||
shipping_notice 会话删除写不可变审计并返回标准 envelope。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -30,7 +28,7 @@ from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderProcessingRun
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
@@ -206,12 +204,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(
|
||||
session: ChatSession,
|
||||
*, unseen_order_extraction_count: int = 0,
|
||||
unseen_order_extraction_severity: str | None = None,
|
||||
) -> dict:
|
||||
"""输出会话摘要及订单抽取待查看聚合,不返回 Run 内容或错误正文。"""
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
@@ -219,46 +212,9 @@ def _serialize_session(
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
'unseen_order_extraction_count': max(0, int(unseen_order_extraction_count or 0)),
|
||||
'unseen_order_extraction_severity': unseen_order_extraction_severity,
|
||||
}
|
||||
|
||||
|
||||
def _order_extraction_attention_by_conversation(
|
||||
*, user_id: int, agent_id: int, conversation_ids: set[str],
|
||||
) -> dict[str, tuple[int, str]]:
|
||||
"""聚合同用户同 Agent 尚未确认的终态订单抽取提醒,防止跨会话泄露。"""
|
||||
if not conversation_ids:
|
||||
return {}
|
||||
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
|
||||
status_severity = {
|
||||
'completed': 'info',
|
||||
'partially_completed': 'warning',
|
||||
'review_required': 'warning',
|
||||
'failed': 'error',
|
||||
'cancelled': 'error',
|
||||
}
|
||||
rows = db.session.query(
|
||||
ShippingOrderProcessingRun.conversation_id,
|
||||
ShippingOrderProcessingRun.status,
|
||||
).filter(
|
||||
ShippingOrderProcessingRun.user_id == user_id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == agent_id,
|
||||
ShippingOrderProcessingRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderProcessingRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderProcessingRun.seen_at.is_(None),
|
||||
).all()
|
||||
aggregate: dict[str, tuple[int, str]] = {}
|
||||
for conversation_id, status in rows:
|
||||
severity = status_severity.get(str(status or ''), 'info')
|
||||
count, existing = aggregate.get(conversation_id, (0, severity))
|
||||
aggregate[conversation_id] = (
|
||||
count + 1,
|
||||
severity if severity_rank[severity] >= severity_rank[existing] else existing,
|
||||
)
|
||||
return aggregate
|
||||
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
@@ -1074,90 +1030,36 @@ def get_chat_sessions():
|
||||
})
|
||||
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
attention_by_conversation = _order_extraction_attention_by_conversation(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_ids={str(item['conversation_id']) for item in sessions if item.get('conversation_id')},
|
||||
)
|
||||
for item in sessions:
|
||||
count, severity = attention_by_conversation.get(str(item.get('conversation_id') or ''), (0, None))
|
||||
item['unseen_order_extraction_count'] = count
|
||||
item['unseen_order_extraction_severity'] = severity
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话。
|
||||
|
||||
核心逻辑:批量清理 ChatLog / Feedback / ChatSession;shipping_notice 写审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true } }`。
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_count = (
|
||||
db.session.query(ChatSession)
|
||||
.filter_by(user_id=user.id, agent_id=agent.id)
|
||||
.count()
|
||||
)
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_sessions_deleted_all',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=f'user:{int(user.id)}:agent:{int(agent.id)}',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
action='delete_all_chat_sessions',
|
||||
reason_code='user_deleted_all_sessions',
|
||||
before={'session_count': int(session_count), 'chat_log_count': len(chat_log_ids)},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return ok({'deleted': True, 'session_count': int(session_count)})
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_chat_session(conversation_id):
|
||||
"""
|
||||
删除指定的会话记录。
|
||||
|
||||
核心逻辑:清理 ChatLog / Feedback;shipping_notice Agent 额外写不可变审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Args:
|
||||
conversation_id: 会话 ID(路径参数)。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true, conversation_id } }`。
|
||||
删除指定的会话记录
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
@@ -1181,9 +1083,6 @@ def delete_chat_session(conversation_id):
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_id_for_audit = str(
|
||||
getattr(session, 'session_id', None) or conversation_id or ''
|
||||
).strip()
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
@@ -1191,38 +1090,9 @@ def delete_chat_session(conversation_id):
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
|
||||
# [BE-16] 货代会话删除必须留审计;与业务删除同事务提交。
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_session_deleted',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=session_id_for_audit or str(conversation_id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
conversation_id=session_id_for_audit or str(conversation_id),
|
||||
action='delete_chat_session',
|
||||
reason_code='user_deleted_session',
|
||||
before={
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
'chat_log_count': len(chat_log_ids),
|
||||
},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id), 'chat_log_count': len(chat_log_ids)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return ok({
|
||||
'deleted': True,
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
})
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -1243,29 +1113,6 @@ def get_chat_messages():
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
def _is_order_extraction_state_card(payload):
|
||||
"""只识别正式 Run 状态卡;用户上传锚点不得回放为重复的助手卡。"""
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
run_no = str(payload.get('order_extraction_run_no') or '').strip()
|
||||
return bool(run_no and payload.get('formId') == f'shipping-order-extraction-run:{run_no}')
|
||||
|
||||
run_nos = {
|
||||
str(log.payload.get('order_extraction_run_no') or '').strip()
|
||||
for log in logs if _is_order_extraction_state_card(log.payload)
|
||||
}
|
||||
order_extraction_runs = {}
|
||||
if run_nos:
|
||||
order_extraction_runs = {
|
||||
run.run_no: run
|
||||
for run in db.session.query(ShippingOrderProcessingRun).filter(
|
||||
ShippingOrderProcessingRun.user_id == g.current_user.id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderProcessingRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderProcessingRun.run_no.in_(run_nos),
|
||||
).all()
|
||||
}
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
@@ -1277,20 +1124,11 @@ def get_chat_messages():
|
||||
for key, value in raw_payload.items()
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
run_no = str(assistant_payload.get('order_extraction_run_no') or '').strip()
|
||||
if _is_order_extraction_state_card(raw_payload) and run_no in order_extraction_runs:
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_message_state
|
||||
|
||||
assistant_payload['shipping_order_extraction_state'] = serialize_order_extraction_message_state(
|
||||
order_extraction_runs[run_no],
|
||||
)
|
||||
if log.query or user_attachments:
|
||||
user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)}
|
||||
if user_attachments:
|
||||
user_msg['attachments'] = user_attachments
|
||||
messages.append(user_msg)
|
||||
if str(raw_payload.get('formId') or '').strip() == f'shipping-order-extraction-user:{run_no}':
|
||||
continue
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
@@ -1851,12 +1689,7 @@ def chat_completions():
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
|
||||
payload = {
|
||||
'event': 'error',
|
||||
'message': '当前服务暂时无法完成回答,请稍后重试。',
|
||||
'conversation_id': local_session_id,
|
||||
'session_status': 'error',
|
||||
}
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
|
||||
Reference in new issue
Block a user