Files
syops/backend/app/services/schedule/query_service.py
T
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00

196 lines
7.9 KiB
Python

"""
backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
normalize_schedule_timezone,
)
def _schedule_timezone_label(task: ScheduleTask | None = None) -> str:
if task is not None:
return normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
return DEFAULT_SCHEDULE_TIMEZONE
def _as_naive_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
return {
'id': task.id,
'schedule_no': task.schedule_no,
'name': task.name,
'schedule_type': task.schedule_type,
'owner_user_id': task.owner_user_id,
'owner_username': task.owner.username if task.owner else None,
'cron_expr': task.cron_expr,
'schedule_timezone': _schedule_timezone_label(task),
'wait_seconds': task.wait_seconds,
'dify_agent_id': task.dify_agent_id,
'platform_api_path': task.platform_api_path,
'data_source_type': task.data_source_type,
'job_params': task.job_params,
'kb_sync_enabled': bool(getattr(task, 'kb_sync_enabled', False)),
'kb_group_id': getattr(task, 'kb_group_id', None),
'notify_user_ids_json': task.notify_user_ids_json or [],
'notify_enabled': bool(task.notify_enabled),
'enabled': bool(task.enabled),
'next_run_at': utc_iso(task.next_run_at),
'last_run_at': utc_iso(task.last_run_at),
'last_status': last_status,
'created_at': utc_iso(task.created_at),
'updated_at': utc_iso(task.updated_at),
}
def serialize_run(run: ScheduleRun) -> dict:
"""序列化单条运行记录;附带库存/入站/出站 raw-zip 是否可下载。"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
'run_no': run.run_no,
'schedule_task_id': run.schedule_task_id,
'schedule_name': run.task.name if run.task else None,
'trigger_type': run.trigger_type,
'triggered_by_user_id': run.triggered_by_user_id,
'started_at': utc_iso(run.started_at),
'finished_at': utc_iso(run.finished_at),
'duration_ms': run.duration_ms,
'status': run.status,
'total_count': run.total_count,
'success_count': run.success_count,
'failed_count': run.failed_count,
'skipped_count': run.skipped_count,
'api_request_json': run.api_request_json,
'api_response_json': run.api_response_json,
'response_summary_json': run.response_summary_json,
'step_logs': run.step_logs,
'dify_execution_snapshot': run.dify_execution_snapshot,
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'inbound_raw_zip_available': inbound_raw_zip_available_from_summary(summary),
'outbound_raw_zip_available': outbound_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
'kb_document_version_id': run.kb_document_version_id,
'kb_sync_job_id': run.kb_sync_job_id,
'kb_sync_error': run.kb_sync_error,
'wecom_notified': bool(run.wecom_notified),
'wecom_notified_at': utc_iso(run.wecom_notified_at),
'wecom_notify_error': run.wecom_notify_error,
'created_at': utc_iso(run.created_at),
}
def _repair_next_run_if_needed(task: ScheduleTask) -> bool:
"""启用中但 next_run_at 为空时补算,返回是否发生修改。"""
if not task.enabled or not str(task.cron_expr or '').strip():
return False
if task.next_run_at is not None:
return False
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
return task.next_run_at is not None
def list_tasks() -> list[dict]:
latest_run_subquery = (
db.session.query(
ScheduleRun.schedule_task_id.label('task_id'),
func.max(ScheduleRun.id).label('last_run_id'),
)
.group_by(ScheduleRun.schedule_task_id)
.subquery()
)
rows = (
db.session.query(ScheduleTask, ScheduleRun.status.label('last_status'))
.options(joinedload(ScheduleTask.owner))
.outerjoin(latest_run_subquery, latest_run_subquery.c.task_id == ScheduleTask.id)
.outerjoin(ScheduleRun, ScheduleRun.id == latest_run_subquery.c.last_run_id)
.order_by(ScheduleTask.created_at.desc())
.all()
)
repaired = False
for task, _last_status in rows:
if _repair_next_run_if_needed(task):
repaired = True
if repaired:
db.session.commit()
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
def list_runs(
*,
task_id: Optional[int] = None,
owner_user_id: Optional[int] = None,
notify_user_id: Optional[int] = None,
schedule_name: Optional[str] = None,
status: Optional[str] = None,
started_after: Optional[datetime] = None,
started_before: Optional[datetime] = None,
limit: int = 100,
) -> list[dict]:
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
if schedule_name:
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
if status:
query = query.filter(ScheduleRun.status == status)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None:
query = query.filter(
(ScheduleTask.owner_user_id == notify_user_id)
| ScheduleTask.notify_user_ids_json.cast(db.String).ilike(f'%{notify_user_id}%')
)
runs = query.order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 500))).all()
return [serialize_run(r) for r in runs]
def get_run(run_id: int) -> ScheduleRun | None:
return db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).filter(ScheduleRun.id == run_id).first()
def can_view_run(run: ScheduleRun, user_id: int) -> bool:
task = run.task
if not task:
return False
if task.owner_user_id == user_id:
return True
notify = task.notify_user_ids_json or []
return int(user_id) in {int(x) for x in notify if str(x).isdigit()}