Files
hugo abf3d48927 feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误
- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
2026-09-30 00:20:06 +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.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_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()}