feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认
This commit is contained in:
1 parent
b595e157e9
commit
4fbaed2b4c
176 files changed
+14011
-994
No files matched your search
@@ -70,5 +70,5 @@ class AgentHandler:
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游 message_end/workflow_finished 后追加的 SSE 行。"""
|
||||
"""上游 error/message_end/workflow_finished 后执行领域收口并追加 SSE 行。"""
|
||||
return iter(())
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/shipping_notice.py
|
||||
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流 UI State 与上下文准备。
|
||||
依赖:shipping_notice.query_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:SSE relay 调用 build_ui_state_event;不替代 Dify 正文生成。
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流订单抽取生命周期、UI State 与上下文准备。
|
||||
依赖:shipping_notice.order_extraction/query_service、chat.log_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:Dify 请求前登记并推送订单抽取状态,terminal/error 后收口、持久化结果并补发 Batch UI State;
|
||||
不替代 Dify 正文生成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,41 +39,148 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
货代发货通知业务 Handler。
|
||||
|
||||
核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。
|
||||
核心逻辑:订单抽取请求进入 Dify 前登记 request/intakes 并推送 extracting;终态时先落失败、
|
||||
推送并持久化抽取结果,再按 adapter_hints / task_id / batch_no 构造 shipping_ui_state。
|
||||
阶段约束:`open_existing` 终态必须能为前端提供恢复锚点;最小字段是 `task_no`,若已知批次则补
|
||||
`batch_no`,若已构造快照则补 `ui_state / batch_ui_state`,供实时消息与历史回放共用。
|
||||
"""
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
@staticmethod
|
||||
def _shipping_hints(ctx: ChatStreamContext) -> dict[str, Any]:
|
||||
"""读取 shipping adapter_hints,非法或缺失时返回空字典。"""
|
||||
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
|
||||
shipping_hints = hints.get('shipping_notice')
|
||||
return shipping_hints if isinstance(shipping_hints, dict) else {}
|
||||
|
||||
@classmethod
|
||||
def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]:
|
||||
"""仅在能力与契约均匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
|
||||
hints = cls._shipping_hints(ctx)
|
||||
if (
|
||||
str(hints.get('capability') or '') != 'order_extraction'
|
||||
or str(hints.get('contract_version') or '') != 'shipping-order-extraction-v1'
|
||||
or not isinstance(hints.get('intake_nos'), list)
|
||||
):
|
||||
return []
|
||||
return sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in hints.get('intake_nos') or []
|
||||
if str(item or '').strip()
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def _workflow_failure_message(event_data: dict[str, Any]) -> str:
|
||||
"""从 Dify terminal/error 事件提取已友好化的错误文本,缺失时返回空字符串。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
data = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
|
||||
failed = event_name == 'error' or (
|
||||
event_name == 'workflow_finished'
|
||||
and str(data.get('status') or '').strip().lower() == 'failed'
|
||||
)
|
||||
if not failed:
|
||||
return ''
|
||||
for value in (
|
||||
event_data.get('message'),
|
||||
event_data.get('error'),
|
||||
event_data.get('description'),
|
||||
data.get('message'),
|
||||
data.get('error'),
|
||||
data.get('description'),
|
||||
):
|
||||
text = str(value or '').strip()
|
||||
if text:
|
||||
return text
|
||||
return '订单识别失败,请重新发送当前邮件。'
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""
|
||||
在订单抽取请求进入 Dify 前登记权威 extracting 状态。
|
||||
|
||||
核心逻辑:仅消费平台 adapter_hints 中的固定能力契约,并把 HXOPS request_id 绑定到完整 Intake 集合;
|
||||
失败直接阻止上游调用,避免前端显示本地 extracting 而后端仍为 not_started。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return ctx
|
||||
from app.services.shipping_notice.order_extraction import start_order_extraction
|
||||
|
||||
start_order_extraction(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
*,
|
||||
resolve_order_extraction: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 shipping_ui_state SSE 事件。
|
||||
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
|
||||
用途:为聊天页当前消息与历史回放提供任务/批次恢复锚点。
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;订单抽取终态可按 intake 反查新建批次或
|
||||
`open_existing` 命中的既有任务。`open_existing` 场景下即使没有新建批次,也必须至少返回
|
||||
`task_no`;失败时记录日志并返回 None。
|
||||
"""
|
||||
if not _uses_shipping_ui_state_progress(ctx.agent):
|
||||
return None
|
||||
|
||||
task_id = str(ctx.shipping_task_id or '').strip()
|
||||
batch_no = str(ctx.shipping_batch_no or '').strip()
|
||||
shipping_hints = self._shipping_hints(ctx)
|
||||
if not task_id and not batch_no:
|
||||
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
|
||||
shipping_hints = hints.get('shipping_notice') if isinstance(hints.get('shipping_notice'), dict) else {}
|
||||
task_id = str(shipping_hints.get('task_id') or '').strip()
|
||||
batch_no = str(shipping_hints.get('batch_no') or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not task_id and not batch_no and not (resolve_order_extraction and intake_nos):
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_by_no,
|
||||
get_task_by_ref,
|
||||
resolve_order_extraction_ui_target,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
resolved_from_order_extraction = False
|
||||
if task is None and batch is None and resolve_order_extraction and intake_nos:
|
||||
batch, task = resolve_order_extraction_ui_target(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
conversation_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
)
|
||||
resolved_from_order_extraction = batch is not None or task is not None
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if resolved_from_order_extraction and batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
'source': 'order_extraction',
|
||||
}
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
@@ -80,13 +188,23 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
**({'source': 'order_extraction'} if resolved_from_order_extraction else {}),
|
||||
}
|
||||
if batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'batch_ui_state': build_batch_ui_state(batch),
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
@@ -98,7 +216,129 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
)
|
||||
return None
|
||||
|
||||
def build_order_extraction_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造当前请求的 shipping_order_extraction_state SSE 事件。
|
||||
|
||||
核心逻辑:只为固定订单抽取能力契约读取权威 Intake 状态;身份围栏失败时记录日志并跳过,
|
||||
避免把旧请求或其他会话结果推送到当前消息。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文,必须包含用户、会话、request_id 与 Intake 集合。
|
||||
|
||||
Returns:
|
||||
可直接格式化为 SSE 的事件字典;非订单抽取回合或读取失败时返回 None。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.order_extraction import get_order_extraction_state
|
||||
|
||||
state = get_order_extraction_state(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_order_extraction_state',
|
||||
'conversation_id': str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
**state,
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] build order extraction state failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _build_history_recovery_payload_patch(
|
||||
*,
|
||||
state_event: dict[str, Any] | None,
|
||||
ui_event: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
提取历史回放所需的最小恢复载荷。
|
||||
|
||||
核心逻辑:抽取终态负责统计摘要,UI State 负责任务/批次锚点;两者都存在时合并为同一条
|
||||
ChatLog.payload patch,保证历史消息可直接恢复工作台。
|
||||
"""
|
||||
payload_patch: dict[str, Any] = {}
|
||||
if isinstance(state_event, dict) and state_event.get('terminal') is True:
|
||||
payload_patch['shipping_order_extraction_state'] = {
|
||||
key: value
|
||||
for key, value in state_event.items()
|
||||
if key not in {'event', 'conversation_id'}
|
||||
}
|
||||
if isinstance(ui_event, dict) and str(ui_event.get('event') or '') == 'shipping_ui_state':
|
||||
task_no = str(ui_event.get('task_no') or '').strip()
|
||||
if task_no:
|
||||
payload_patch['task_no'] = task_no
|
||||
if 'batch_no' in ui_event:
|
||||
batch_no = str(ui_event.get('batch_no') or '').strip()
|
||||
payload_patch['batch_no'] = batch_no or None
|
||||
ui_state = ui_event.get('ui_state')
|
||||
if isinstance(ui_state, dict):
|
||||
payload_patch['shipping_ui_state'] = ui_state
|
||||
batch_ui_state = ui_event.get('batch_ui_state')
|
||||
if isinstance(batch_ui_state, dict):
|
||||
payload_patch['shipping_batch_ui_state'] = batch_ui_state
|
||||
return payload_patch
|
||||
|
||||
def _persist_history_recovery_payload(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
*,
|
||||
state_event: dict[str, Any] | None = None,
|
||||
ui_event: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
把订单抽取终态与 UI 锚点合并到本轮已落库 ChatLog,供历史消息恢复。
|
||||
|
||||
核心逻辑:使用上游终态附带的 chat_log_id 与当前身份做归属校验;缺少日志主键时保留实时 SSE,
|
||||
不创建额外聊天记录。阶段 1 要求 `open_existing` 至少补齐 `task_no`,有批次或快照时继续补齐
|
||||
`batch_no / shipping_ui_state / shipping_batch_ui_state`。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文。
|
||||
event_data: Dify terminal/error 原始事件。
|
||||
state_event: 已构造的订单抽取状态事件。
|
||||
ui_event: 已构造的 shipping_ui_state 事件。
|
||||
"""
|
||||
payload_patch = self._build_history_recovery_payload_patch(
|
||||
state_event=state_event,
|
||||
ui_event=ui_event,
|
||||
)
|
||||
if not payload_patch:
|
||||
return
|
||||
try:
|
||||
chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
chat_log_id = 0
|
||||
if chat_log_id <= 0:
|
||||
return
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
|
||||
merge_chat_log_payload(
|
||||
chat_log_id=chat_log_id,
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
payload_patch=payload_patch,
|
||||
)
|
||||
|
||||
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
|
||||
"""仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。"""
|
||||
if str(event.get('event') or '') != 'shipping_ui_state':
|
||||
return None
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = (
|
||||
@@ -115,9 +355,14 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
def _format_sse(self, event: dict[str, Any]) -> str:
|
||||
"""把领域事件编码为单条 SSE data frame。"""
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
"""上游调用前先推送订单抽取进行态,再补充已有任务 UI State。"""
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
@@ -127,9 +372,46 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游终态后收口抽取状态,依次推送抽取事实和任务 UI State。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
if event_name not in {'message_end', 'workflow_finished'}:
|
||||
if event_name not in {'error', 'message_end', 'workflow_finished'}:
|
||||
return iter(())
|
||||
event = self.build_ui_state_event(ctx)
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if intake_nos:
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
finalize_order_extraction_failure,
|
||||
)
|
||||
|
||||
failure_message = self._workflow_failure_message(event_data)
|
||||
try:
|
||||
finalize_order_extraction_failure(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
error_message=failure_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
)
|
||||
except Exception:
|
||||
from app import db
|
||||
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] finalize order extraction failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
event = self.build_ui_state_event(ctx, resolve_order_extraction=True)
|
||||
if extraction_event or event:
|
||||
self._persist_history_recovery_payload(
|
||||
ctx,
|
||||
event_data,
|
||||
state_event=extraction_event,
|
||||
ui_event=event,
|
||||
)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
Reference in new issue
Block a user