feat(shipping-notice): 收敛订单处理状态与履约门禁
This commit is contained in:
1 parent
bffcd55b40
commit
70dd0051b8
153 files changed
+10916
-4296
No files matched your search
@@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||
from .shared import ( # noqa: E402, F401
|
||||
CHAT_USER_ATTACHMENT_LIMIT,
|
||||
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
||||
CHAT_USER_ATTACHMENT_SOURCES,
|
||||
CHAT_USER_ATTACHMENT_TYPES,
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
__all__ = ['chat_bp']
|
||||
__all__ = [
|
||||
'chat_bp',
|
||||
'CHAT_USER_ATTACHMENT_LIMIT',
|
||||
'CHAT_USER_ATTACHMENT_MAX_SIZE',
|
||||
'CHAT_USER_ATTACHMENT_SOURCES',
|
||||
'CHAT_USER_ATTACHMENT_TYPES',
|
||||
'_merge_user_attachments_from_terminal_event',
|
||||
'_normalize_user_attachments',
|
||||
]
|
||||
@@ -8,6 +8,7 @@ api/chat/sessions.py
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from .shared import _normalize_user_attachments
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_chat_logs_for_session,
|
||||
@@ -194,19 +195,32 @@ 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 = {
|
||||
@@ -220,8 +234,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)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
@@ -41,6 +42,95 @@ from app.core.errors import (
|
||||
)
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
|
||||
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'}
|
||||
|
||||
|
||||
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,
|
||||
}
|
||||
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},
|
||||
)
|
||||
|
||||
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -256,15 +256,6 @@ def tool_match_inventory():
|
||||
resume_gate_code='inventory_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
@@ -26,8 +26,8 @@ from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNot
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
POSITION_EXPORT_GENERATED,
|
||||
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
|
||||
from app.services.shipping_notice.query_service import (
|
||||
@@ -410,7 +410,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
from app.models import ShippingOrderTask
|
||||
from app.models import ShippingOrderIntake
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
@@ -462,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
@@ -470,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
# [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段,
|
||||
# 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。
|
||||
# [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich;
|
||||
# 缺省/非法值一律回退 full,保持兼容。
|
||||
view = str(request.args.get('view', 'full') or 'full').strip().lower()
|
||||
if view not in ('full', 'workbench'):
|
||||
view = 'full'
|
||||
@@ -2331,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
'message': '无需调度自动推进,或任务已离开待推进态',
|
||||
}
|
||||
else:
|
||||
# [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。
|
||||
position = progress.get('position')
|
||||
user_mode = progress.get('user_mode')
|
||||
if not position or not user_mode:
|
||||
try:
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.progress_workflow import (
|
||||
_entry_position,
|
||||
_entry_user_mode,
|
||||
)
|
||||
|
||||
ot = (
|
||||
db.session.query(ShippingOrderTask)
|
||||
.filter(
|
||||
ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper()
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if ot is not None:
|
||||
position = position or _entry_position(ot)
|
||||
user_mode = user_mode or _entry_user_mode(ot)
|
||||
except Exception:
|
||||
pass
|
||||
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
|
||||
result['auto_progress'] = {
|
||||
'status': progress.get('status'),
|
||||
'message': progress.get('message'),
|
||||
'enqueue_result': progress.get('enqueue_result'),
|
||||
'checkpoint': progress.get('checkpoint'),
|
||||
'position': position,
|
||||
'user_mode': user_mode,
|
||||
}
|
||||
result['confirm_outcome'] = resolve_confirm_outcome(
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user