190 lines
7.8 KiB
Python
190 lines
7.8 KiB
Python
from __future__ import annotations
|
||
|
||
from io import BytesIO
|
||
|
||
from flask import Blueprint, jsonify, request, send_file
|
||
|
||
from app.auth_jwt import get_current_user
|
||
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||
from app.models import ScheduleRun, ScheduleTask
|
||
from app.services.rohs_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||
from app.services.schedule.query_service import get_run, serialize_run
|
||
|
||
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
|
||
|
||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||
|
||
|
||
def _require_user():
|
||
user = get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError()
|
||
return user
|
||
|
||
|
||
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
||
if not task:
|
||
return False
|
||
values = (
|
||
getattr(task, "schedule_no", None),
|
||
getattr(task, "name", None),
|
||
getattr(task, "platform_api_path", None),
|
||
)
|
||
haystack = " ".join(str(item or "").lower() for item in values)
|
||
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
|
||
|
||
|
||
def serialize_rohs_judgement(payload: dict) -> dict:
|
||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
|
||
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 "RoHS 文件检核",
|
||
"status": payload["status"],
|
||
"total_count": total,
|
||
"processed_count": processed,
|
||
"success_count": success,
|
||
"failed_count": failed,
|
||
"skipped_count": skipped,
|
||
"judgement": serialize_rohs_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/rohs-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_rohs_check_bp.route("/rohs-check/runs/for-log", methods=["GET"])
|
||
def workspace_rohs_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:
|
||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||
if not chat_log_id or chat_log_id <= 0:
|
||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||
|
||
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_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"])
|
||
def workspace_rohs_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_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
|
||
def workspace_rohs_active_run():
|
||
"""查询当前进行中的 RoHS 检核批次;优先按 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:
|
||
# 已按 schedule_task_id 过滤;不再比对 conversation_id(HXOPS session_id ≠ Dify sys.conversation_id)
|
||
run = next((row for row in rows if _is_rohs_check_task(row.task)), None)
|
||
else:
|
||
run = next((
|
||
row for row in rows
|
||
if _is_rohs_check_task(row.task)
|
||
and (
|
||
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_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
|
||
def workspace_rohs_run_detail(run_id: int):
|
||
_require_user()
|
||
run = get_run(run_id)
|
||
if not run:
|
||
raise NotFoundError("run_not_found")
|
||
if not _is_rohs_check_task(run.task):
|
||
raise ForbiddenError("Forbidden")
|
||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||
|
||
|
||
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
|
||
def workspace_rohs_run_excel(run_id: int):
|
||
_require_user()
|
||
run = get_run(run_id)
|
||
if not run:
|
||
raise NotFoundError("run_not_found")
|
||
if not _is_rohs_check_task(run.task):
|
||
raise ForbiddenError("Forbidden")
|
||
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",
|
||
)
|