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 from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.core.errors import ( AppError, ConflictError, ForbiddenError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError, raise_for_status, ) 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 {} if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}: from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1) row_count = int(summary.get('row_count') or 0) return jsonify({ 'summary': { 'total_count': row_count, 'success_count': row_count, 'failed_count': 0, 'skipped_count': 0, }, 'details': [summary], 'errors': [], 'step_logs': [ { 'step': 'fixed_assets_snapshot_sync', 'status': 'success', 'detail': { 'version': summary.get('current_version'), 'row_count': row_count, }, } ], }) if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}: from app.services.hot_faq_aggregator import HotFaqAggregator schedule_task_id = data.get('schedule_task_id') agent_id = data.get('agent_id') if schedule_task_id: task = db.session.get(ScheduleTask, int(schedule_task_id)) if task and task.dify_agent_id: agent_id = task.dify_agent_id result = HotFaqAggregator.aggregate_hot_faq_candidates( agent_id=int(agent_id) if agent_id else None, dry_run=False, ) if not result.get('enabled'): message = str(result.get('message') or 'FAQ_HOT_ENABLED is false') return jsonify({ 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1}, 'details': [], 'errors': [message], 'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}], }) promoted = int(result.get('promoted_count') or 0) skipped = int(result.get('skipped_count') or 0) total = max(promoted + skipped, 1) return jsonify({ 'summary': { 'total_count': total, 'success_count': promoted, 'failed_count': 0, 'skipped_count': skipped, }, 'details': (result.get('candidates') or [])[:20], 'errors': [], 'step_logs': [{ 'step': 'faq_hot_aggregate', 'status': 'success', 'detail': { 'scanned_logs': result.get('scanned_logs'), 'promoted_count': promoted, 'skipped_count': skipped, }, }], }) 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: raise NotFoundError(f"No schedule task found for '{name}'") 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() if not run.dify_execution_snapshot: capture_dify_execution_snapshot(run, task) 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() raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}}) 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) run.step_logs = step_logs if step_logs else None 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})