feat(shipping-notice): 完成货代发货通知全流程开发与代码重构

- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑
- 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示
- 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败
- 新增路径工具类统一管理相对路径,优化配置文件处理逻辑
- 归档旧文档,将部署、Dify配置合并到`shipping_notice.md`
- 新增完整单元测试与集成测试覆盖核心流程
- 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
hugo committed 2026-06-04 15:26:34 +08:00
1 parent b62082758b
commit 8deae3146b
65 files changed
+6477 -1937

No files matched your search

+86 -56
View File
@@ -206,12 +206,28 @@ class DifyService:
@staticmethod
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
def _is_file_obj(v: Any) -> bool:
if not isinstance(v, dict):
return False
if not str(v.get("type") or "").strip():
return False
tm = str(v.get("transfer_method") or "").strip()
if tm not in {"local_file", "remote_url"}:
return False
if tm == "local_file":
return bool(str(v.get("upload_file_id") or "").strip())
return bool(str(v.get("url") or "").strip())
def _convert(v):
if v is None:
return ""
if _is_file_obj(v):
return v
if isinstance(v, dict):
return {kk: _convert(vv) for kk, vv in v.items()}
if isinstance(v, list):
if v and all(_is_file_obj(i) for i in v):
return v
return [_convert(i) for i in v]
return str(v)
return {k: _convert(v) for k, v in (inputs or {}).items()}
@@ -550,11 +566,78 @@ class DifyService:
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
chat_logged = False
def persist_stream_chat(data: dict, event_name: str) -> None:
nonlocal chat_logged
if chat_logged:
return
if data.get('answer'):
full_answer.append(data.get('answer', ''))
answer_text = ''.join(full_answer).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'text', 'result'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
chat_logged = True
if current_app:
current_app.logger.info(
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
@@ -625,63 +708,10 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end request_id=%s collected retriever_resources=%s",
request_id,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
enrich_done_at = time.time()
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
db_write_done_at = time.time()
if chat_log_id:
data['chat_log_id'] = chat_log_id
if current_app:
current_app.logger.info(
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
request_id,
latency,
int((first_token_at - start_time) * 1000) if first_token_at else None,
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
int((time.time() - message_end_started) * 1000),
int((enrich_done_at - message_end_started) * 1000),
int((db_write_done_at - db_write_started) * 1000),
event_count,
message_count,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
data.get('conversation_id') or normalized_conversation_id,
)
if event in ('message_end', 'workflow_finished'):
persist_stream_chat(data, event)
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break