""" backend/app/api/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_with_source 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), '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 {} 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") match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id) return jsonify({ 'ok': True, 'run': _serialize_progress_run(match.run) if match.run else None, 'match_source': match.match_source, }) @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/', 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//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')