Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-07-06 15:20:40 +08:00
commit fa8f6990a7
113 files changed
+19714 -9259

No files matched your search

+2
View File
@@ -27,6 +27,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
from app.api.kb import knowledge_base_bp
@@ -55,6 +56,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
@@ -0,0 +1,107 @@
"""
backend/app/api/agent_runtime_context_tools.py
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
def _require_tool_auth() -> None:
"""
校验 agent_runtime_context Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
Raises:
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
UnauthorizedError: 缺少或传入错误鉴权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""
归一化 Tool API 错误码。
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
Args:
exc: 业务异常。
Returns:
Tool 侧错误码。
"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
return exc.code
@agent_runtime_context_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@agent_runtime_context_bp.before_request
def _verify_tool_access():
"""
对上下文解析 Tool 做统一 Header 鉴权。
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
"""
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
def parse_context_tool():
"""
解析 agent_runtime_context 的白名单字段。
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
不用于推进业务状态。
"""
payload = request.get_json(silent=True) or {}
return jsonify(
parse_agent_runtime_context(
payload.get("agent_runtime_context"),
payload.get("paths"),
)
)
+51 -19
View File
@@ -20,6 +20,7 @@ import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
@@ -48,6 +49,25 @@ def _can_use_leave_feature(agent_proxy) -> bool:
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
"""
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
@@ -1386,7 +1406,25 @@ 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)
elif leave_supported:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
elif kb_type == 'ERP知识库':
from app.services.text2sql import Text2SQLService
if normalized_files:
@@ -1399,23 +1437,26 @@ 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, object] | None = None
hxops_turn_id: str | None = None
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
dify_inputs = build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
)
if declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
# [STEP 1] file_check 的 task_id 校验已在统一 dify_inputs 分发入口完成;这里只保留 turn 注册
if is_file_check_agent:
hxops_turn_id = uuid.uuid4().hex
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
@@ -1427,15 +1468,6 @@ def chat_completions():
agent_id=agent_proxy.id,
query=query,
)
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
trigger_source="frontend_chat",
request_id=request_id,
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
+6 -1
View File
@@ -33,6 +33,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
@@ -314,7 +315,11 @@ def tool_switch_focus_task():
task = get_task_in_batch(batch_no, task_no)
if not task:
raise NotFoundError("task not found in batch")
batch.current_focus_task_no = task.task_no
switch_batch_focus(
batch,
task,
source="tool_api",
)
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
+12 -1
View File
@@ -37,7 +37,18 @@ def serialize_file_judgement(payload: dict) -> dict:
judgement = response_summary.get('file_judgement')
if not isinstance(judgement, dict):
judgement = {}
return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)}
return {
'qualified_count': int(judgement.get('qualified_count') or 0),
'unqualified_count': int(judgement.get('unqualified_count') or 0),
'manual_count': int(judgement.get('manual_count') or 0),
'dify_error_count': int(judgement.get('dify_error_count') or 0),
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
'business_manual_count': int(judgement.get('business_manual_count') or 0),
'system_error_count': int(judgement.get('system_error_count') or 0),
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
+134 -73
View File
@@ -2,16 +2,19 @@
backend/app/api/workspace/shipping_notice.py
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file
import uuid
from flask import Blueprint, g, jsonify, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import (
@@ -20,6 +23,7 @@ from app.services.shipping_notice.constants import (
CP_NOTICE_TEXT_EXTRACTION_FAILED,
MAP_JSON,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
@@ -35,6 +39,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -53,6 +58,11 @@ def _require_user():
return user
def _ok(payload: dict):
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
return ok(payload, request_id=getattr(g, 'request_id', None))
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
@@ -73,10 +83,7 @@ def workspace_shipping_batches():
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()
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
return _ok(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():
@@ -90,29 +97,37 @@ def workspace_create_shipping_batch_from_notices():
if not uploads:
raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
from app.services.shipping_notice.notice_upload import (
build_notice_file_summary,
cleanup_temp_notice_uploads,
intake_temp_notice_uploads,
)
conversation_id = str(request.form.get('conversation_id') or '').strip()
notice_items: list[dict] = []
for upload in uploads:
raw = upload.read() or b''
filename = upload.filename or 'notice'
source_type = guess_source_type(filename)
text = ''
warnings: list[str] = []
try:
temp_task_no = f'TMP-{len(notice_items) + 1}'
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f'notice_extract_failed:{exc}']
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f'notice_text_truncated:{limit}')
notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings})
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True}
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
try:
accepted, rejected = intake_temp_notice_uploads(temp_request_id, uploads)
finally:
cleanup_temp_notice_uploads(temp_request_id)
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
)
notice_items = [item.to_notice_item() for item in accepted]
if not notice_items:
raise ValidationError(
'all uploaded files failed extraction or contained no parseable text',
details={'rejected_files': file_summary['rejected_files'], 'file_summary': file_summary},
)
payload = {
'user_id': user.id,
'conversation_id': conversation_id or None,
'file_count': len(notice_items),
'notice_items': notice_items,
'defer_parse': True,
}
created = shipping_tools.create_batch_tasks(payload)
data = created.get('data') if isinstance(created, dict) else None
batch_data = data.get('batch') if isinstance(data, dict) else None
@@ -133,17 +148,37 @@ def workspace_create_shipping_batch_from_notices():
base_message = str(created.get('message') or '').strip()
if orchestrator_started:
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
return jsonify(created)
created['file_summary'] = file_summary
return _ok(created)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""返回批次详情、批次内任务列表和当前焦点任务。"""
"""
返回批次详情与聚合 UI State。
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
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})
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""
返回批次级 UI State。
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
@@ -175,12 +210,19 @@ def workspace_switch_shipping_batch_focus_task(batch_no: str):
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
comment = str(data.get('comment') or '').strip()
if not task_no:
raise ValidationError('task_no is required')
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
raise NotFoundError('Task not found in batch')
batch.current_focus_task_no = task.task_no
switch_batch_focus(
batch,
task,
source='workspace_api',
comment=comment or None,
extra={'actor_user_id': user.id},
)
db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@@ -210,8 +252,11 @@ def workspace_create_shipping_task_from_notice():
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
source_type = guess_source_type(upload.filename or '')
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
filename = upload.filename or 'notice'
raw = upload.read() or b''
source_file_type = notice_source_file_type(upload)
source_type = guess_source_type(filename)
conversation_id = str(request.form.get('conversation_id') or '').strip()
payload = {'user_id': user.id, 'source_type': source_type}
if conversation_id:
@@ -220,29 +265,25 @@ def workspace_create_shipping_task_from_notice():
task_id = str(created.get('task_id') or '').strip()
if not task_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
raw = upload.read() or b''
saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw)
text, meta = extract_notice_text(saved_path)
if not text:
intake = intake_notice_attachment(
filename=filename,
raw=raw,
source_file_type=source_file_type,
storage='task',
task_no=task_id,
)
if not intake.accepted:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}')
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = text
db.session.commit()
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or '').strip() or task.source_file_name
task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type
task.raw_content = intake.text
task.source_file_name = intake.filename or task.source_file_name
task.source_file_type = intake.source_file_type or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
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}})
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': intake.to_notice_upload_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):
@@ -255,38 +296,58 @@ def workspace_replace_shipping_task_notice(task_no: str):
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
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
intake = intake_notice_attachment(
filename=upload.filename or 'notice',
raw=upload.read() or b'',
source_file_type=notice_source_file_type(upload),
storage='task',
task_no=task.task_no,
)
task.source_type = intake.source_type 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,
raw_text=intake.text,
source_file_name=intake.filename,
source_file_type=intake.source_file_type,
warnings=list(intake.warnings),
)
data = result.setdefault('data', {})
if isinstance(data, dict):
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
return jsonify(result)
data['notice_upload'] = intake.to_notice_upload_meta()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
def workspace_shipping_task_detail(task_no: str):
"""返回指定任务的详情快照。"""
"""
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return jsonify(serialize_task_detail(task))
return _ok({
**serialize_task_detail(task),
'ui_state': build_task_ui_state(task),
})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
def workspace_shipping_task_ui_state(task_no: str):
"""
返回单票任务 UI State。
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
避免不同前端入口重复拼装按钮集合。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok(build_task_ui_state(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
@@ -365,7 +426,7 @@ def workspace_submit_shipping_decision(task_no: str):
if not decision:
raise ValidationError('decision is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True}
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment