Files
syops/backend/app/services/schedule/scheduler_service.py
T
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

747 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新)与单次运行执行器。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。
"""
from __future__ import annotations
import time
import uuid
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
def request_cancel_run(run_id: int) -> None:
"""
持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。
核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过
ScheduleRun 状态/存在性复检停止可中断的长循环。business_ref 兼容
`schedule_run:{id}` 与 `schedule_run:{id}:{platform_api_path}`。
"""
from app.models import Job
from app.services.schedule.queue_service import query_jobs_for_schedule_run
now = datetime.utcnow()
jobs = (
query_jobs_for_schedule_run(run_id)
.filter(Job.status.in_(("queued", "running")))
.all()
)
for job in jobs:
job.status = "cancelled"
job.message = "排程已取消"
job.error_message = "排程已删除,执行中断"
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
def is_run_cancelled(run_id: int) -> bool:
"""通过数据库业务状态判断运行是否已被跨进程取消或删除。"""
run = db.session.get(ScheduleRun, int(run_id))
return run is None or str(run.status or "") not in {"queued", "running"}
def clear_cancelled_run(run_id: int) -> None:
"""兼容旧调用;取消状态已持久化,无需清理进程内内存。"""
return None
def _generate_schedule_no() -> str:
return f"SCH{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
def _generate_run_no() -> str:
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
def _generate_test_run_no() -> str:
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
_WECOM_STATUS_LABEL = {
'success': '成功',
'failed': '失败',
'partial_failed': '部分失败',
}
_WECOM_EVENT_TYPE = 'schedule_completed'
def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) -> dict[str, Any]:
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
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
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
'task_id': task.id,
'run_id': run.id,
}
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'inventory_raw_zip'
elif receipt_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'receipt_raw_zip'
return params
def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
from app.models import ShippingReceiptRpaUnitRun
task = run.task
if (
task is None
or task.schedule_type != 'platform_job'
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
):
return []
return (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id)
.all()
)
def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
"""
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存/收料归档时提示包已随通知发送或可点击下载。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
description = (
f'执行单号: {run.run_no}\n'
f'状态: {status_label}\n'
f'总数: {run.total_count} 成功: {run.success_count} '
f'跳过: {skipped_count} 失败: {run.failed_count}'
)
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
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
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
if receipt_raw_zip_available_from_summary(summary):
description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载'
return description
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
"""
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
收料附加该 run 的原始收料 ZIP(不再逐文件推送)。
"""
from app.services.integrations.wecom.notify import (
upload_wecom_temp_media,
send_wecom_file_message,
send_wecom_textcard_message,
_create_audit,
_build_jump_url,
_get_enabled_events,
)
# 领域自行管理通知时跳过通用完成通知,避免重复刷屏
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('domain_notification_managed'):
run.wecom_notify_error = 'domain_notification_managed'
return
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
if _WECOM_EVENT_TYPE not in _get_enabled_events():
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
return
user_ids = task.notify_user_ids_json or []
if not user_ids:
return
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
wecom_users = [u for u in users if u.wecom_userid]
if not wecom_users:
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
return
title = f'排程执行结果: {task.name}'
jump_params = _build_schedule_run_wecom_jump_params(task, run)
media_id = None
if run.excel_file_data and run.excel_file_name:
try:
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
except Exception as exc:
current_app.logger.warning(
'[wecom-schedule] media upload failed for run %s: %s',
run.run_no, exc,
)
raw_zip_media_id = None
raw_zip_file_name = None
try:
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw inventory zip media skipped for run %s: %s',
run.run_no, exc,
)
receipt_zip_media_id = None
receipt_zip_file_name = None
try:
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(
receipt_zip_path.read_bytes(), receipt_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw receipt zip media skipped for run %s: %s',
run.run_no, exc,
)
textcard_ok_count = 0
errors = []
for u in wecom_users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url('/admin/schedules', trace_id, jump_params)
description = _build_schedule_run_wecom_description(run)
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
textcard_ok_count += 1
else:
audit.error_code = str(data.get('errcode'))
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
if media_id:
try:
file_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_file', u,
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
)
file_data = send_wecom_file_message(u.wecom_userid, media_id)
if file_data.get('errcode') == 0:
file_audit.status = 'sent'
else:
file_audit.error_code = str(file_data.get('errcode'))
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: file exception={exc}')
if raw_zip_media_id:
try:
raw_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_inventory_raw_zip', u,
title, f'[原始库存包] {raw_zip_file_name}', uuid.uuid4().hex,
)
raw_zip_data = send_wecom_file_message(u.wecom_userid, raw_zip_media_id)
if raw_zip_data.get('errcode') == 0:
raw_zip_audit.status = 'sent'
else:
raw_zip_audit.error_code = str(raw_zip_data.get('errcode'))
raw_zip_audit.error_message = str(raw_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: raw zip errcode={raw_zip_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
if receipt_zip_media_id:
try:
receipt_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u,
title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex,
)
receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id)
if receipt_zip_data.get('errcode') == 0:
receipt_zip_audit.status = 'sent'
else:
receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode'))
receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
else:
run.wecom_notified = False
if errors:
run.wecom_notify_error = '; '.join(errors[:5])
db.session.flush()
def create_task(
*,
name: str,
schedule_type: str,
owner_user_id: int,
cron_expr: str,
schedule_timezone: str | None = None,
wait_seconds: int,
dify_agent_id: int | None,
platform_api_path: str | None,
data_source_type: str | None,
job_params: dict[str, Any] | None = None,
notify_user_ids_json: list[int] | None,
notify_enabled: bool,
enabled: bool,
kb_sync_enabled: bool = False,
kb_group_id: int | None = None,
actor_id: int | None,
commit: bool = True,
check_options: bool = True,
) -> ScheduleTask:
"""
创建排程任务。
核心逻辑:契约校验后,job_params 经 normalize_job_params_for_contract 唯一归一化再写入。
Args:
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
"""
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
cron_expr = normalize_cron_expr(cron_expr)
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
normalized_job_params = normalize_job_params_for_contract(
contract['schedule_type'],
contract['platform_api_path'],
job_params,
check_options=check_options,
)
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
schedule_type=contract['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
wait_seconds=max(0, int(wait_seconds or 0)),
dify_agent_id=dify_agent_id,
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
job_params=normalized_job_params,
kb_sync_enabled=bool(kb_sync_enabled),
kb_group_id=kb_group_id,
notify_user_ids_json=notify_user_ids_json or [],
notify_enabled=bool(notify_enabled),
enabled=bool(enabled),
created_by=actor_id,
updated_by=actor_id,
)
if task.enabled and task.cron_expr:
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
if task.next_run_at is None:
task.enabled = False
db.session.add(task)
if commit:
db.session.commit()
else:
db.session.flush()
return task
def update_task(
task: ScheduleTask,
*,
payload: dict[str, Any],
actor_id: int | None,
commit: bool = True,
check_options: bool = True,
) -> ScheduleTask:
"""
更新排程任务字段。
核心逻辑:契约字段与 job_params 在本层统一归一化——显式传 job_params 时按新契约校验;
切换 platform_api_path 且未传 job_params 时重置为新 schema 默认值(或清空)。
Args:
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
"""
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
normalize_job_key,
)
for key in [
"name",
"owner_user_id",
"cron_expr",
"schedule_timezone",
"wait_seconds",
"dify_agent_id",
"notify_enabled",
"enabled",
]:
if key in payload:
if key == "schedule_timezone":
value = normalize_schedule_timezone(payload[key])
elif key == "cron_expr":
value = normalize_cron_expr(str(payload[key] or ""))
else:
value = payload[key]
setattr(task, key, value)
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
task.notify_user_ids_json = payload.get("notify_user_ids_json")
if "kb_sync_enabled" in payload:
task.kb_sync_enabled = bool(payload.get("kb_sync_enabled"))
if "kb_group_id" in payload:
raw_group_id = payload.get("kb_group_id")
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
# [STEP 1] 契约字段:有变更则校验并写回;否则沿用当前任务三层语义
previous_path = task.platform_api_path
contract_touched = any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path"))
if contract_touched:
contract = apply_schedule_contract_to_payload({
"schedule_type": payload.get("schedule_type", task.schedule_type),
"data_source_type": payload.get("data_source_type", task.data_source_type),
"platform_api_path": payload.get("platform_api_path", task.platform_api_path),
})
task.schedule_type = contract["schedule_type"]
task.data_source_type = contract["data_source_type"]
task.platform_api_path = contract["platform_api_path"]
else:
contract = {
"schedule_type": task.schedule_type,
"data_source_type": task.data_source_type,
"platform_api_path": task.platform_api_path,
}
# [STEP 2] job_params 唯一归一化入口:显式传参 / 切换 job key 重置 / 非平台任务清空
path_changed = normalize_job_key(previous_path) != normalize_job_key(contract["platform_api_path"])
if "job_params" in payload:
task.job_params = normalize_job_params_for_contract(
contract["schedule_type"],
contract["platform_api_path"],
payload.get("job_params"),
check_options=check_options,
)
elif contract_touched and (
contract["schedule_type"] != "platform_job"
or path_changed
):
task.job_params = normalize_job_params_for_contract(
contract["schedule_type"],
contract["platform_api_path"],
None,
check_options=check_options,
)
if task.enabled and task.cron_expr:
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)
else:
task.next_run_at = None
task.updated_by = actor_id
if commit:
db.session.commit()
return task
def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool = True) -> ScheduleTask:
"""
启用排程并重新计算 next_run_at。
核心逻辑:启用前重新校验三层契约(含 registry enabled);platform_job 顺带归一化 job_params,
避免停用任务或失效参数被重新放入调度队列。
Args:
check_options: 是否校验 select/multi_select 选项范围。
Raises:
ValueError: 契约非法、平台任务已停用或 job_params 校验失败。
"""
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
contract = apply_schedule_contract_to_payload({
'schedule_type': task.schedule_type,
'data_source_type': task.data_source_type,
'platform_api_path': task.platform_api_path,
})
task.schedule_type = contract['schedule_type']
task.data_source_type = contract['data_source_type']
task.platform_api_path = contract['platform_api_path']
if contract['schedule_type'] == 'platform_job':
task.job_params = normalize_job_params_for_contract(
contract['schedule_type'],
contract['platform_api_path'],
task.job_params,
check_options=check_options,
)
task.enabled = True
if task.cron_expr:
task.cron_expr = normalize_cron_expr(task.cron_expr)
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)
else:
task.next_run_at = None
if commit:
db.session.commit()
return task
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
"""
立即执行一条排程并写入 ScheduleRun 终态。
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success;
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
"""
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if existing:
return existing
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type=trigger_type,
triggered_by_user_id=triggered_by_user_id,
started_at=datetime.utcnow(),
status="running",
)
db.session.add(run)
db.session.commit()
capture_dify_execution_snapshot(run, task)
db.session.commit()
if task.cron_expr and trigger_type == "cron":
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
db.session.commit()
start_ts = time.time()
step_logs: list = []
try:
executor = resolve_schedule_executor(task)
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
except Exception as exc:
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 1, 0, [], [str(exc)]
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
if current_app:
current_app.logger.exception(
"[schedule-run] executor failed name=%s path=%s run_no=%s error=%s",
task.name,
task.platform_api_path,
run.run_no,
exc,
)
try:
db.session.refresh(run)
except Exception:
pass
if is_run_cancelled(run.id):
run.finished_at = datetime.utcnow()
run.duration_ms = int((time.time() - start_ts) * 1000)
run.status = "failed"
run.error_message = "排程已被删除,执行中断"
db.session.commit()
clear_cancelled_run(run.id)
return run
if should_defer_schedule_run_finalization(task, step_logs):
return apply_deferred_schedule_run_state(
run,
task,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
details=details,
errors=errors,
step_logs=step_logs,
)
if should_defer_receipt_schedule_run(task, step_logs):
return apply_deferred_receipt_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
duration_ms = int((time.time() - start_ts) * 1000)
if current_app:
error_preview = "; ".join(str(item) for item in (errors or [])[:3])
current_app.logger.info(
"[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d error=%s",
task.name,
task.platform_api_path,
run.run_no,
total_count,
success_count,
failed_count,
skipped_count,
len(errors or []),
error_preview or "-",
)
if total_count == 0 and not errors:
status = "success"
run.error_message = "无待处理数据"
elif failed_count == 0:
status = "success"
elif success_count == 0:
status = "failed"
else:
status = "partial_failed"
try:
cfg = get_schedule_sql_config_by_task_id(task.id)
if cfg and cfg.alias_order and cfg.header_labels:
header_order, header_labels = cfg.alias_order, cfg.header_labels
else:
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
detail_alias_order = (cfg.detail_alias_order if cfg else None) or []
file_data, file_name, file_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
"status": status,
"total_count": total_count,
"success_count": success_count,
"failed_count": failed_count,
"duration_ms": duration_ms,
},
details=details,
header_order=header_order,
header_labels=header_labels,
detail_alias_order=detail_alias_order,
)
except Exception as excel_exc:
if current_app:
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
file_data, file_name, file_size = None, None, 0
errors.append(f"Excel导出失败: {excel_exc}")
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = status
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None
response_summary = dict(run.response_summary_json or {})
response_summary.update({
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
})
run.response_summary_json = response_summary
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
task.last_run_at = datetime.utcnow()
db.session.commit()
try:
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
db.session.refresh(task)
db.session.refresh(run)
sync_schedule_run_excel_to_kb(task, run, process_inline=True)
db.session.refresh(run)
except Exception as kb_exc:
db.session.rollback()
db.session.refresh(run)
if current_app:
current_app.logger.error("[schedule-run] kb sync failed: %s", kb_exc, exc_info=True)
run.kb_sync_status = "failed"
run.kb_group_id = getattr(task, "kb_group_id", None)
run.kb_sync_error = str(kb_exc)
db.session.commit()
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
if current_app:
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
return run