Files
syops/backend/app/api/schedule/runs.py
T

120 lines
4.1 KiB
Python

"""
backend/app/api/schedule/runs.py
用途:排程运行触发与运行记录查询 API。
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
"""
from __future__ import annotations
from datetime import datetime
from io import BytesIO
from flask import jsonify, request, send_file
from app import db
from app.api.schedule.blueprint import schedule_admin_bp
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@require_admin
def run_schedule(task_id: int):
"""
手动触发排程并立即返回 queued 运行记录。
核心逻辑:queue_service 同事务创建 ScheduleRun + Job;独立 worker 后台执行。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
user = get_current_user()
run, _job_id, created = enqueue_manual_schedule_run(
task.id,
triggered_by_user_id=getattr(user, 'id', None),
)
if not created:
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
fresh = db.session.get(ScheduleRun, run.id)
return jsonify(serialize_run(fresh))
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
@require_admin
def get_schedule_runs(task_id: int):
"""按任务 ID 分页/过滤返回运行记录。"""
status = str(request.args.get('status') or '').strip() or None
limit = int(request.args.get('limit') or 100)
started_after = None
started_before = None
sa = request.args.get('started_after')
sb = request.args.get('started_before')
if sa:
try:
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
if sb:
try:
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
return jsonify(
list_runs(
task_id=task_id,
status=status,
started_after=started_after,
started_before=started_before,
limit=limit,
)
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
@require_admin
def get_schedule_run(run_id: int):
"""返回单条运行记录详情。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
return jsonify(serialize_run(run))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
@require_admin
def get_schedule_run_excel(run_id: int):
"""下载运行结果 Excel 附件。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
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',
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
@require_admin
def get_schedule_run_inventory_raw_zip(run_id: int):
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
zip_path, file_name = resolve_inventory_raw_zip_download(run)
return send_file(
zip_path,
as_attachment=True,
download_name=file_name,
mimetype='application/zip',
)