from __future__ import annotations import traceback from datetime import datetime from flask import Blueprint, jsonify, request from app import db from app.models import ScheduleRun, ScheduleTask from app.services.schedule import _run_generic_check_job internal_jobs_bp = Blueprint('internal_jobs', __name__) @internal_jobs_bp.route('/', methods=['POST']) def run_internal_job(name: str): key = name.strip().lower() data = request.get_json(silent=True) or {} run_no = str(data.get("run_no") or "").strip() schedule_task_id = data.get("schedule_task_id") task = None if schedule_task_id: task = db.session.get(ScheduleTask, int(schedule_task_id)) if not task and key.isdigit(): task = db.session.get(ScheduleTask, int(key)) if not task: task = ScheduleTask.query.filter( ScheduleTask.platform_api_path.ilike(f"%{key}%") ).first() if not task: return jsonify({"error": f"No schedule task found for '{name}'"}), 404 run = None if run_no: run = ScheduleRun.query.filter_by(run_no=run_no).first() if not run: from app.services.schedule.scheduler_service import _generate_run_no run = ScheduleRun( run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running', ) db.session.add(run) db.session.commit() try: total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run) except Exception as exc: run.status = "failed" run.error_message = str(exc) run.finished_at = datetime.utcnow() db.session.commit() return jsonify({ "error": str(exc), "traceback": traceback.format_exc(), "summary": {"total_count": 0, "success_count": 0, "failed_count": 0, "skipped_count": 0}, }), 500 run.status = "success" if failed_count == 0 else ("failed" if success_count == 0 else "partial_failed") run.total_count = total_count run.success_count = success_count run.failed_count = failed_count run.skipped_count = skipped_count run.finished_at = datetime.utcnow() if run.started_at and run.finished_at: run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) db.session.commit() return jsonify({ "summary": { "total_count": total_count, "success_count": success_count, "failed_count": failed_count, "skipped_count": skipped_count, }, "details": details, "errors": errors, "step_logs": step_logs, })