refactor(backend): 重构后端admin和schedule部分

This commit is contained in:
sophie committed 2026-07-01 13:34:29 +08:00
1 parent 9f5493185d
commit 4a14960e01
74 files changed
+5937 -3644

No files matched your search

+9 -6
View File
@@ -1,15 +1,18 @@
"""
backend/app/api/workspace/__init__.py
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。
逻辑:Wave 1 前 re-export 旧 workspace_* 模块。
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
依赖:workspace 各子模块 blueprint。
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
"""
from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401
from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401
from app.api.workspace.announcements import workspace_announcements_bp
from app.api.workspace.file_check import workspace_file_check_bp
from app.api.workspace.schedule import workspace_schedule_bp
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
__all__ = [
'workspace_announcements_bp',
'workspace_file_check_bp',
'workspace_schedule_bp',
'workspace_shipping_notice_bp',
'workspace_file_check_bp',
]
@@ -0,0 +1,27 @@
"""
backend/app/api/workspace/announcements.py
用途:工作台/登录页只读公告列表 API。
依赖:services/admin/announcement_service(读活跃公告)。
逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。
"""
from flask import Blueprint, jsonify
from sqlalchemy.exc import DatabaseError, OperationalError
from app.core.errors import ServiceUnavailableError
from app.services.admin import announcement_service
workspace_announcements_bp = Blueprint('workspace_announcements', __name__)
@workspace_announcements_bp.route('/announcements', methods=['GET'])
def list_active_announcements():
"""返回已发布的公司公告(公开,供登录页与工作台展示)。"""
try:
return jsonify(announcement_service.list_active_announcements())
except (OperationalError, DatabaseError) as exc:
from flask import current_app
current_app.logger.warning('workspace.announcements query failed: %s', exc)
raise ServiceUnavailableError('Database connection failed')
+107 -1
View File
@@ -1,5 +1,111 @@
"""
backend/app/api/workspace/file_check.py
用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
from io import BytesIO
from flask import Blueprint, jsonify, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
from app.services.schedule.query_service import get_run, serialize_run
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
def _require_user():
"""
校验当前登录用户。
Raises:
UnauthorizedError: 未认证。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def serialize_file_judgement(payload: dict) -> dict:
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
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)}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
if not current_step:
return None
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get('total_count') or 0)
success = int(payload.get('success_count') or 0)
failed = int(payload.get('failed_count') or 0)
skipped = int(payload.get('skipped_count') or 0)
processed = success + failed + skipped
percent = int(round(processed / total * 100)) if total > 0 else 0
percent = max(0, min(percent, 100))
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
def workspace_file_check_run_for_log():
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
_require_user()
task_id = request.args.get('task_id', type=int)
chat_log_id = request.args.get('chat_log_id', type=int)
if not task_id or task_id <= 0:
raise ValidationError("task_id_required")
if not chat_log_id or chat_log_id <= 0:
raise ValidationError("chat_log_id_required")
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None, 'match_source': 'chat_log' if run else None})
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
def workspace_file_check_run_for_session():
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
_require_user()
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
def workspace_file_check_active_run():
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
_require_user()
task_id = request.args.get('task_id', type=int)
conversation_id = str(request.args.get('conversation_id') or '').strip()
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
rows = query.order_by(ScheduleRun.id.desc()).all()
if task_id is not None:
run = rows[0] if rows else None
else:
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
def workspace_file_check_run_detail(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError('run_not_found')
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
def workspace_file_check_run_excel(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError('run_not_found')
if not run.excel_file_data:
raise NotFoundError('excel_not_found')
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
+76 -1
View File
@@ -1,5 +1,80 @@
"""
backend/app/api/workspace/schedule.py
用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。
用途:工作台排程运行记录查询 API。
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
from datetime import datetime
from flask import Blueprint, jsonify, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
def _require_user():
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
def workspace_schedule_runs():
user = _require_user()
status = str(request.args.get("status") or "").strip() or None
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
started_after_str = request.args.get("started_after")
started_before_str = request.args.get("started_before")
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
limit = int(request.args.get("limit") or 100)
return jsonify(
list_runs(
notify_user_id=user.id,
schedule_name=schedule_name,
status=status,
started_after=started_after,
started_before=started_before,
limit=limit,
)
)
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
def workspace_schedule_run_detail(run_id: int):
user = _require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("Not found")
if not can_view_run(run, user.id):
raise ForbiddenError("Forbidden")
return jsonify(serialize_run(run))
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
def workspace_schedule_run_excel(run_id: int):
from io import BytesIO
user = _require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("Not found")
if not can_view_run(run, user.id):
raise ForbiddenError("Forbidden")
if not run.excel_file_data:
raise NotFoundError("Excel not found")
buf = BytesIO(run.excel_file_data)
return send_file(
buf,
as_attachment=True,
download_name=run.excel_file_name or "result.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+555 -1
View File
@@ -1,5 +1,559 @@
"""
backend/app/api/workspace/shipping_notice.py
用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
from flask import Blueprint, 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.models import ShippingBatch, ShippingTask
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,
MAP_JSON,
)
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,
list_tasks_for_batch,
list_tasks_for_user,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
"""
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
Returns:
User 模型实例。
Raises:
UnauthorizedError: 无有效 JWT 或 legacy header。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
user = _require_user()
batch_no = str(request.args.get('batch_no') or '').strip() or None
process_status = str(request.args.get('process_status') or '').strip() or None
limit = int(request.args.get('limit') or 100)
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。"""
user = _require_user()
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()
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():
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
user = _require_user()
uploads = request.files.getlist('files')
if not uploads:
single = request.files.get('file')
if single:
uploads = [single]
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
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}
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
tasks_data = data.get('tasks') if isinstance(data, dict) else None
batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip()
orchestrator_started = False
if batch_no:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
if isinstance(data, dict) and batch_no:
focus_task = get_focus_task_for_batch(batch_no, user.id)
if focus_task:
data['focus_task'] = serialize_task_summary(focus_task)
if isinstance(tasks_data, list):
data['tasks'] = tasks_data
data['orchestrator_started'] = orchestrator_started
if isinstance(created, dict):
base_message = str(created.get('message') or '').strip()
if orchestrator_started:
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
return jsonify(created)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""返回批次详情、批次内任务列表和当前焦点任务。"""
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})
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
"""返回指定批次下的任务列表。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str):
"""返回指定批次当前焦点任务的摘要。"""
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)
if not focus_task:
raise NotFoundError('Focus task not found')
return jsonify(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str):
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
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()
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
db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user = _require_user()
data = request.get_json(silent=True) or {}
payload = {'user_id': user.id}
source_type = str(data.get('source_type') or '').strip()
if source_type:
payload['source_type'] = source_type
conversation_id = str(data.get('conversation_id') or '').strip()
if conversation_id:
payload['conversation_id'] = conversation_id
raw_content = str(data.get('raw_content') or '').strip()
if raw_content:
payload['raw_content'] = raw_content
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
user = _require_user()
upload = request.files.get('file')
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 '')
conversation_id = str(request.form.get('conversation_id') or '').strip()
payload = {'user_id': user.id, 'source_type': source_type}
if conversation_id:
payload['conversation_id'] = conversation_id
created = shipping_tools.create_task(payload)
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:
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()
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
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}})
@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):
"""返回指定任务的详情快照。"""
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))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return jsonify(build_chat_actions_payload(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
def workspace_retry_shipping_task(task_no: str):
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
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
data = request.get_json(silent=True) or {}
payload = {'task_id': task.task_no}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
def workspace_upload_shipping_inventory(task_no: str):
"""用户态上传库存 Excel,并在服务端完成解析。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
upload = request.files.get('file')
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):
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
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
data = request.get_json(silent=True) or {}
map_json = data.get(MAP_JSON)
if not isinstance(map_json, dict) or not map_json:
raise ValidationError(f'{MAP_JSON} is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
return jsonify(shipping_tools.apply_inventory_mapping(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
def workspace_submit_shipping_decision(task_no: str):
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
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 {}
decision = str(data.get('decision') or '').strip()
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}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
def workspace_update_shipping_notice_fields(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 {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
raise ValidationError('fields is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'fields': fields}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
def workspace_update_shipping_notice_line(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:
line_index = int(data.get('line_index'))
except (TypeError, ValueError):
raise ValidationError('line_index is required')
patch = data.get('patch')
if not isinstance(patch, dict) or not patch:
raise ValidationError('patch is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
def workspace_add_shipping_notice_line(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 {}
line = data.get('line')
if not isinstance(line, dict) or not line:
raise ValidationError('line is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line': line}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
def workspace_remove_shipping_notice_line(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:
line_index = int(data.get('line_index'))
except (TypeError, ValueError):
raise ValidationError('line_index is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
def workspace_auto_progress_shipping_task(task_no: str):
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
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
data = request.get_json(silent=True) or {}
payload: dict = {'task_id': task.task_no}
for key in ('lang', 'locale', 'language'):
if data.get(key):
payload[key] = data[key]
break
result = shipping_tools.auto_progress(payload)
if isinstance(result, dict) and result.get('status') == 'ok':
gen_data = result.get('data')
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
result = {**result, 'data': gen_data}
return jsonify(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
def workspace_match_shipping_inventory(task_no: str):
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
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
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
if not isinstance(matched, dict):
return jsonify(matched)
data = matched.get('data')
if isinstance(data, dict) and data.get('export_file_path'):
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
matched['checkpoint'] = checkpoint
if 'human_options' not in matched:
options = human_options_for_checkpoint(checkpoint)
if options is not None:
matched['human_options'] = options
if 'action_buttons' not in matched:
buttons = action_buttons_for_checkpoint(checkpoint)
if buttons:
matched['action_buttons'] = buttons
return jsonify(matched)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
def workspace_mark_manual_uploaded(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': '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,并补充工作台下载链接。"""
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
result = shipping_tools.generate_excel({'task_id': task.task_no})
if isinstance(result, dict) and result.get('status') == 'ok':
data = result.get('data')
if not isinstance(data, dict):
data = {}
result['data'] = data
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
return jsonify(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
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))