feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认
This commit is contained in:
1 parent
b595e157e9
commit
4fbaed2b4c
176 files changed
+14011
-994
No files matched your search
@@ -19,5 +19,6 @@ import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_customers.py
|
||||
|
||||
用途:货代客户主数据、识别证据与期初导入管理 API。
|
||||
依赖:admin blueprint、require_admin、shipping_customer_* services、customer_shadow_resolution、customer_auto_resolution。
|
||||
逻辑:薄路由完成鉴权、参数读取和文件响应;业务校验与事务全部委托服务层。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import g, jsonify, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.admin import shipping_customer_import_service, shipping_customer_service
|
||||
from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
get_shadow_quality_report,
|
||||
label_shadow_resolution,
|
||||
)
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
backfill_historical_task_customer,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""返回 require_admin 已解析的当前管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
"""将管理列表 query 参数转换为普通字符串字典。"""
|
||||
return {key: str(value) for key, value in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_customers():
|
||||
"""分页查询货代标准客户。"""
|
||||
return jsonify(shipping_customer_service.list_customers(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer(customer_id: int):
|
||||
"""查询单个标准客户及识别证据。"""
|
||||
return jsonify(shipping_customer_service.get_customer(customer_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer():
|
||||
"""创建货代标准客户。"""
|
||||
return jsonify(shipping_customer_service.create_customer(request.get_json(silent=True) or {}, actor_id=_actor_id())), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_customer(customer_id: int):
|
||||
"""更新货代标准客户。"""
|
||||
return jsonify(shipping_customer_service.update_customer(
|
||||
customer_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/deactivate', methods=['POST'])
|
||||
@require_admin
|
||||
def deactivate_shipping_customer(customer_id: int):
|
||||
"""停用标准客户并保留历史引用。"""
|
||||
return jsonify(shipping_customer_service.deactivate_customer(customer_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/identifiers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_identifier(customer_id: int):
|
||||
"""为客户新增名称、邮箱、域名或模板指纹识别证据。"""
|
||||
return jsonify(shipping_customer_service.create_identifier(
|
||||
customer_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
)), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-identifiers/<int:identifier_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_customer_identifier(identifier_id: int):
|
||||
"""审核、停用或调整客户识别证据的自动匹配授权。"""
|
||||
return jsonify(shipping_customer_service.update_identifier(
|
||||
identifier_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/import-template', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_customer_import_template():
|
||||
"""下载期初客户标准 Excel 模板。"""
|
||||
content = shipping_customer_import_service.build_import_template()
|
||||
return send_file(
|
||||
BytesIO(content),
|
||||
as_attachment=True,
|
||||
download_name='shipping_customer_import_template.xlsx',
|
||||
mimetype=XLSX_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-imports', methods=['POST'])
|
||||
@require_admin
|
||||
def upload_shipping_customer_import():
|
||||
"""上传并预检期初客户 Excel,不直接写正式客户表。"""
|
||||
upload = request.files.get('file')
|
||||
if upload is None:
|
||||
raise ValidationError(
|
||||
'Customer import file is required',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_FILE_REQUIRED',
|
||||
)
|
||||
source_system = str(request.form.get('source_system') or 'INITIAL_EXCEL').strip()
|
||||
return jsonify(shipping_customer_import_service.create_import_batch(
|
||||
upload,
|
||||
source_system=source_system,
|
||||
actor_id=_actor_id(),
|
||||
)), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-imports/<int:batch_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_import(batch_id: int):
|
||||
"""查询导入批次统计、错误、警告和逐行决定。"""
|
||||
return jsonify(shipping_customer_import_service.get_import_batch(batch_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-import-rows/<int:row_id>/decision', methods=['PUT'])
|
||||
@require_admin
|
||||
def decide_shipping_customer_import_row(row_id: int):
|
||||
"""保存警告行的新增、更新、合并或跳过决定。"""
|
||||
return jsonify(shipping_customer_import_service.decide_import_row(
|
||||
row_id,
|
||||
request.get_json(silent=True) or {},
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-imports/<int:batch_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_customer_import(batch_id: int):
|
||||
"""单事务发布已完成预检和冲突决定的客户导入批次。"""
|
||||
return jsonify(shipping_customer_import_service.publish_import_batch(batch_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-imports/<int:batch_id>/reconciliation', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_customer_import_reconciliation(batch_id: int):
|
||||
"""下载导入批次逐行对账 CSV。"""
|
||||
content, filename = shipping_customer_import_service.build_reconciliation_csv(batch_id)
|
||||
return send_file(
|
||||
BytesIO(content),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype='text/csv; charset=utf-8',
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-shadow-report', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_shadow_report():
|
||||
"""查询客户影子识别分布、已标注准确率和最近样本。"""
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Invalid report limit') from exc
|
||||
report = get_shadow_quality_report(limit=limit)
|
||||
report['auto_resolution'] = get_auto_resolution_metrics()
|
||||
return jsonify(report)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/historical-task-backfill', methods=['POST'])
|
||||
@require_admin
|
||||
def backfill_shipping_historical_task_customer():
|
||||
"""管理员为历史无业务单任务确认客户;默认不生成历史业务编号。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or '').strip().upper()
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Customer id is required') from exc
|
||||
task = ShippingTask.query.filter_by(task_no=task_no).first()
|
||||
if task is None:
|
||||
raise ValidationError('Historical task not found', code='SHIPPING.HISTORICAL_TASK_NOT_FOUND')
|
||||
try:
|
||||
return jsonify(backfill_historical_task_customer(task, customer_id=customer_id, actor_id=_actor_id()))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.HISTORICAL_BACKFILL_INVALID') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
|
||||
@require_admin
|
||||
def correct_shipping_numbered_task_customer():
|
||||
"""管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper()
|
||||
if not task_ref:
|
||||
raise ValidationError(
|
||||
'Task reference is required',
|
||||
code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED',
|
||||
)
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc
|
||||
task = get_task_by_ref(task_ref)
|
||||
if task is None:
|
||||
raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING')
|
||||
return jsonify(correct_numbered_task_customer(
|
||||
task,
|
||||
customer_id=customer_id,
|
||||
reason=str(data.get('reason') or ''),
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-shadow-resolutions/<int:resolution_id>/label', methods=['PUT'])
|
||||
@require_admin
|
||||
def label_shipping_customer_shadow_resolution(resolution_id: int):
|
||||
"""为影子识别样本写入人工客户真值,不执行业务绑定。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_SHADOW_LABEL_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
return jsonify(label_shadow_resolution(resolution_id, customer_id=customer_id, actor_id=_actor_id()))
|
||||
+160
-28
@@ -12,6 +12,7 @@ import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
@@ -42,11 +43,100 @@ from app.core.errors import (
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
CHAT_USER_ATTACHMENT_LIMIT = 20
|
||||
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
|
||||
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
|
||||
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
|
||||
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
def _normalize_user_attachments(value) -> list[dict]:
|
||||
"""
|
||||
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
|
||||
|
||||
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
|
||||
|
||||
Args:
|
||||
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
|
||||
|
||||
Returns:
|
||||
可安全写入 JSON 的附件快照列表;非法项目被忽略。
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
normalized: list[dict] = []
|
||||
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
raw_name = str(item.get('name') or '')
|
||||
basename = re.split(r'[\\/]+', raw_name)[-1]
|
||||
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
|
||||
attachment_type = str(item.get('type') or '').strip().lower()
|
||||
source = str(item.get('source') or '').strip().lower()
|
||||
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
|
||||
continue
|
||||
snapshot = {
|
||||
'name': name,
|
||||
'type': attachment_type,
|
||||
'source': source,
|
||||
}
|
||||
attachment_id = re.sub(r'[\x00-\x1f\x7f]', '', str(item.get('id') or '')).strip()[:128]
|
||||
if attachment_id:
|
||||
snapshot['id'] = attachment_id
|
||||
extension = str(item.get('extension') or '').strip().lower()
|
||||
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
|
||||
snapshot['extension'] = extension
|
||||
try:
|
||||
size = int(item.get('size')) if item.get('size') is not None else None
|
||||
except (TypeError, ValueError):
|
||||
size = None
|
||||
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
|
||||
snapshot['size'] = size
|
||||
normalized.append(snapshot)
|
||||
return normalized
|
||||
|
||||
|
||||
def _merge_user_attachments_from_terminal_event(
|
||||
event_data: dict,
|
||||
*,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
user_attachments: list[dict],
|
||||
) -> bool:
|
||||
"""
|
||||
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
|
||||
|
||||
Args:
|
||||
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
|
||||
user_id: 当前用户 ID。
|
||||
agent_id: 当前 Agent ID。
|
||||
session_id: 当前 HXOPS 本地会话 ID。
|
||||
user_attachments: 已完成白名单校验的附件快照。
|
||||
|
||||
Returns:
|
||||
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
|
||||
"""
|
||||
if not user_attachments:
|
||||
return False
|
||||
try:
|
||||
chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if chat_log_id <= 0:
|
||||
return False
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
return merge_chat_log_payload(
|
||||
chat_log_id=chat_log_id,
|
||||
user_id=int(user_id or 0),
|
||||
agent_id=int(agent_id or 0),
|
||||
session_id=session_id,
|
||||
payload_patch={'user_attachments': user_attachments},
|
||||
)
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
@@ -1030,19 +1120,29 @@ def get_chat_messages():
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
raw_payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
|
||||
assistant_payload = {
|
||||
key: value
|
||||
for key, value in raw_payload.items()
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
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 (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
and not assistant_payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
and not assistant_payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
@@ -1056,8 +1156,8 @@ def get_chat_messages():
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
assistant_msg['payload'] = log.payload
|
||||
if assistant_payload:
|
||||
assistant_msg['payload'] = assistant_payload
|
||||
messages.append(assistant_msg)
|
||||
return jsonify(messages)
|
||||
|
||||
@@ -1279,7 +1379,9 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
display_query = str(
|
||||
data.get('display_query') if 'display_query' in data else query or ''
|
||||
).strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
@@ -1293,6 +1395,8 @@ def chat_completions():
|
||||
if str(item or '').strip()
|
||||
})
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
user_attachments = _normalize_user_attachments(data.get('user_attachments'))
|
||||
session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip())
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
user = getattr(g, 'current_user', None)
|
||||
@@ -1350,7 +1454,7 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=display_query,
|
||||
title=session_title,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
@@ -1372,13 +1476,20 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=display_query,
|
||||
title=session_title,
|
||||
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=display_query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=session_title, status='running')
|
||||
|
||||
# [STEP 1] 流式响应可能在原请求 DB Session 清理后才开始迭代;提前快照会话标量,
|
||||
# 避免 Handler 的事务提交使 ORM 对象过期后触发 DetachedInstanceError。
|
||||
local_session_id = str(session.session_id)
|
||||
initial_session_status = str(session.status or 'running')
|
||||
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
|
||||
stream_session = SimpleNamespace(session_id=local_session_id)
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1414,8 +1525,8 @@ def chat_completions():
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
session=stream_session,
|
||||
external_conversation_id=initial_external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
@@ -1438,8 +1549,8 @@ def chat_completions():
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
session_id=local_session_id,
|
||||
external_conversation_id=initial_external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
@@ -1451,13 +1562,13 @@ def chat_completions():
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
initial_external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
session_id=local_session_id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
session_id=local_session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
@@ -1480,14 +1591,14 @@ def chat_completions():
|
||||
relay_first_chunk_at: float | None = None
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
'provider_conversation_id': session.external_conversation_id,
|
||||
'session_status': session.status,
|
||||
'conversation_id': local_session_id,
|
||||
'provider_conversation_id': initial_external_conversation_id,
|
||||
'session_status': initial_session_status,
|
||||
}
|
||||
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
known_provider_conversation_id = initial_external_conversation_id
|
||||
known_status = initial_session_status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
@@ -1499,6 +1610,7 @@ def chat_completions():
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
merged_attachment_log_ids: set[int] = set()
|
||||
for chunk in generator:
|
||||
if relay_first_chunk_at is None:
|
||||
relay_first_chunk_at = time.perf_counter()
|
||||
@@ -1515,6 +1627,20 @@ def chat_completions():
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments:
|
||||
try:
|
||||
attachment_chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
attachment_chat_log_id = 0
|
||||
if attachment_chat_log_id > 0 and attachment_chat_log_id not in merged_attachment_log_ids:
|
||||
if _merge_user_attachments_from_terminal_event(
|
||||
event_data,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=local_session_id,
|
||||
user_attachments=user_attachments,
|
||||
):
|
||||
merged_attachment_log_ids.add(attachment_chat_log_id)
|
||||
should_touch = False
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
@@ -1530,7 +1656,7 @@ def chat_completions():
|
||||
updated_session = _update_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
session.session_id,
|
||||
local_session_id,
|
||||
status=known_status,
|
||||
external_conversation_id=known_provider_conversation_id,
|
||||
touch=True,
|
||||
@@ -1539,7 +1665,7 @@ def chat_completions():
|
||||
known_status = updated_session.status
|
||||
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['conversation_id'] = local_session_id
|
||||
event_data['session_status'] = known_status
|
||||
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
||||
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
||||
@@ -1547,7 +1673,7 @@ def chat_completions():
|
||||
current_app.logger.info(
|
||||
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
local_session_id,
|
||||
relay_first_ms,
|
||||
relay_total_ms,
|
||||
event_name,
|
||||
@@ -1557,7 +1683,7 @@ def chat_completions():
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
if event_name in ('error', 'message_end', 'workflow_finished'):
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
@@ -1565,9 +1691,15 @@ 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, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
|
||||
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,
|
||||
payload,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
|
||||
@@ -291,6 +291,15 @@ def tool_confirm_inventory_source():
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
确认任务所属标准客户(仅提交 customer_id)。
|
||||
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_customer(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
|
||||
@@ -40,6 +40,10 @@ from app.services.shipping_notice.query_service import (
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
list_customer_options,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
@@ -79,6 +83,38 @@ 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-customers', methods=['GET'])
|
||||
def workspace_shipping_customers():
|
||||
"""列出可供当前业务用户确认的启用标准客户。"""
|
||||
_require_user()
|
||||
query = str(request.args.get('q') or '').strip()
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Invalid customer limit') from exc
|
||||
return jsonify(list_customer_options(query=query, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-customer', methods=['POST'])
|
||||
def workspace_confirm_shipping_customer(task_no: str):
|
||||
"""为当前用户任务确认标准客户,并原子生成正式业务编号。"""
|
||||
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 {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return jsonify(serialize_task_detail(updated))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
|
||||
Reference in new issue
Block a user