Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/jobs/queue.py
This commit is contained in:
commit
ce80867d09
89 files changed
+10328
-4126
No files matched your search
+50
-8
@@ -38,6 +38,7 @@ from app.core.errors import (
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
@@ -52,6 +53,28 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
@@ -909,9 +932,23 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_name)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
@@ -940,10 +977,14 @@ def save_local_message():
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -1074,6 +1115,7 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
@@ -1117,7 +1159,7 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
@@ -1126,13 +1168,13 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1199,7 +1241,7 @@ def chat_completions():
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
dify_inputs: dict[str, object] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
@@ -1230,12 +1272,11 @@ def chat_completions():
|
||||
elif is_shipping_agent:
|
||||
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
|
||||
dify_inputs = build_shipping_notice_dify_inputs(
|
||||
external_conversation_id or session.session_id,
|
||||
session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
request_id=request_id,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
@@ -1247,6 +1288,7 @@ def chat_completions():
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
display_query=display_query,
|
||||
)
|
||||
|
||||
def relay_stream():
|
||||
|
||||
@@ -122,7 +122,7 @@ def openapi_dify_yaml():
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
@@ -130,7 +130,7 @@ def tool_create_task():
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
@@ -222,7 +222,7 @@ def tool_apply_inventory_mapping():
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
@@ -230,7 +230,7 @@ def tool_ensure_inventory():
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@@ -238,7 +238,7 @@ def tool_auto_progress():
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
@@ -254,7 +254,7 @@ def tool_submit_decision():
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
@@ -262,7 +262,7 @@ def tool_generate_shipment_excel():
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@@ -294,7 +294,7 @@ def tool_get_batch_status():
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
|
||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.constants import (
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
@@ -51,6 +52,28 @@ def _require_user():
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _maybe_recheck_inventory_rpa_wait(task: ShippingTask | None) -> None:
|
||||
"""
|
||||
工作台查询兜底复查库存 RPA 等待态。
|
||||
|
||||
常规超时/重试由 shipping worker 执行;这里仅在用户查询时发现已超时仍未推进的任务,补偿触发一次幂等复查。
|
||||
"""
|
||||
if not task:
|
||||
return
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
|
||||
|
||||
maybe_recheck_inventory_rpa_wait(task, source="workspace_query")
|
||||
|
||||
|
||||
def _maybe_recheck_batch_inventory_rpa_wait(batch: ShippingBatch | None) -> None:
|
||||
"""对批次下任务执行工作台查询兜底复查,避免 worker 异常时页面长期停在等待结果。"""
|
||||
if not batch:
|
||||
return
|
||||
for task in batch.tasks or []:
|
||||
_maybe_recheck_inventory_rpa_wait(task)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
@@ -67,6 +90,17 @@ def workspace_shipping_batches():
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
|
||||
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
|
||||
).all()
|
||||
for batch in batches:
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
@@ -131,6 +165,7 @@ def workspace_shipping_batch_detail(batch_no: str):
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None})
|
||||
|
||||
@@ -141,6 +176,7 @@ def workspace_shipping_batch_tasks(batch_no: str):
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
@@ -150,6 +186,7 @@ def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_batch_inventory_rpa_wait(batch)
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
@@ -233,6 +270,41 @@ def workspace_create_shipping_task_from_notice():
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
saved_path = save_task_notice_upload(task.task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
task.source_type = guess_source_type(filename) or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=text,
|
||||
source_file_name=filename,
|
||||
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
|
||||
warnings=warnings,
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""返回指定任务的详情快照。"""
|
||||
@@ -240,6 +312,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_maybe_recheck_inventory_rpa_wait(task)
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
@@ -277,6 +350,20 @@ def workspace_upload_shipping_inventory(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
@@ -448,6 +535,16 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
@@ -486,4 +583,4 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
Reference in new issue
Block a user