Files
syops/backend/app/services/schedule/query_service.py
T
hugoandCursor ffc0d4a430 feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:18:48 +08:00

186 lines
7.3 KiB
Python

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_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_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:
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),
'receipt_raw_zip_available': receipt_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()}