Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -40,7 +40,7 @@ def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failed',
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""独立收料文件抓取排程(08:00)。
|
||||
|
||||
用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。
|
||||
依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。
|
||||
逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
def _wanted_sources(task: ScheduleTask) -> list[str]:
|
||||
"""提取结构化 source_codes;留空代表全部启用来源。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
values = params.get("source_codes") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
return [str(item).strip() for item in values if str(item).strip()]
|
||||
|
||||
|
||||
def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""08:00 收料文件抓取;按来源实例独立执行。"""
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
sources = _wanted_sources(task) or []
|
||||
business_date = str(business_date_now())
|
||||
total = success = failed = empty = 0
|
||||
results: list[dict[str, Any]] = []
|
||||
warnings: list[str] = []
|
||||
errors: list[str] = []
|
||||
for source_code in sources:
|
||||
total += 1
|
||||
try:
|
||||
prepared = ensure_receipt_file_ready(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
repository=deps.file_repository,
|
||||
rpa_trigger=deps.rpa_trigger,
|
||||
)
|
||||
results.append({"source_code": source_code, "stage": prepared.stage})
|
||||
if prepared.stage == "file_ready":
|
||||
success += 1
|
||||
elif prepared.stage == "waiting_rpa_callback":
|
||||
empty += 1
|
||||
else:
|
||||
failed += 1
|
||||
errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}")
|
||||
except Exception as exc: # noqa: BLE001 —— 来源隔离
|
||||
failed += 1
|
||||
errors.append(f"{source_code}: {exc}")
|
||||
return (total, success, failed, empty, results, warnings, errors)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""自动调拨排程(09:00)。
|
||||
|
||||
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
|
||||
依赖:auto_transfer、transfer deps、ScheduleExecuteResult。
|
||||
逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
def _task_params(task: ScheduleTask) -> dict[str, Any]:
|
||||
return task.job_params if isinstance(task.job_params, dict) else {}
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""09:00 自动调拨:恢复 + 预检 + 执行 + 通知。"""
|
||||
params = _task_params(task)
|
||||
source_codes = params.get("source_codes") or []
|
||||
if isinstance(source_codes, str):
|
||||
source_codes = [source_codes]
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
recipients = params.get("notify_user_ids") or []
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = run_auto_transfer(
|
||||
business_date=str(business_date_now()),
|
||||
deps=deps,
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
recover_history=recover_history,
|
||||
sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果)
|
||||
recipients=[str(item) for item in recipients],
|
||||
)
|
||||
results: list[dict[str, Any]] = []
|
||||
errors: list[str] = list(outcome.errors)
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
"notification_status": outcome.notification_status,
|
||||
})
|
||||
recovery = outcome.recovery
|
||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
||||
return (
|
||||
success + recovery.recovered_count,
|
||||
success,
|
||||
recovery.still_blocked_count,
|
||||
0,
|
||||
results,
|
||||
[f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"],
|
||||
errors,
|
||||
)
|
||||
@@ -144,7 +144,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
)
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
@@ -183,6 +183,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。",
|
||||
category="procurement",
|
||||
))
|
||||
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
|
||||
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-order-extraction-progress-cleanup",
|
||||
@@ -342,7 +344,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
label="立账凭证检核",
|
||||
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
|
||||
handler=run_voucher_check_schedule,
|
||||
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
|
||||
description="每周二检核上一个自然月的销售开票附件,扫描文档库类型目录并按 invoice 归档。",
|
||||
description_key="admin.schedule.form.accountingVoucherCheckHint",
|
||||
category="finance",
|
||||
params_schema=(
|
||||
@@ -356,30 +358,12 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"options": [{"value": "HXJM", "label": "HXJM"}],
|
||||
},
|
||||
{
|
||||
"key": "directory_template",
|
||||
"key": "profile_code",
|
||||
"type": "text",
|
||||
"label": "目录模板",
|
||||
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
|
||||
"label": "业务方 Profile",
|
||||
"label_key": "admin.schedule.form.voucherCheckProfile",
|
||||
"required": True,
|
||||
"default": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"help_key": "admin.schedule.form.voucherCheckDirTemplateHelp",
|
||||
},
|
||||
{
|
||||
"key": "required_files",
|
||||
"type": "json",
|
||||
"label": "必检材料",
|
||||
"label_key": "admin.schedule.form.voucherCheckRequiredFiles",
|
||||
"required": True,
|
||||
"default": DEFAULT_REQUIRED_FILES,
|
||||
},
|
||||
{
|
||||
"key": "filename_case_sensitive",
|
||||
"type": "boolean",
|
||||
"label": "文件名区分大小写",
|
||||
"label_key": "admin.schedule.form.voucherCheckCaseSensitive",
|
||||
"required": True,
|
||||
"default": True,
|
||||
"default": "sales",
|
||||
},
|
||||
{
|
||||
"key": "notify_missing_enabled",
|
||||
@@ -397,16 +381,69 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
),
|
||||
defaults=dict(DEFAULT_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-receipt-file",
|
||||
label="在途收料文件抓取",
|
||||
handler=run_in_transit_receipt_file_schedule,
|
||||
description=(
|
||||
"每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。"
|
||||
"09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "same_day_dedup_enabled",
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
"label": "来源实例",
|
||||
"label_key": "admin.schedule.form.transferSourceCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "shipping_inventory_sources",
|
||||
},
|
||||
),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-transfer",
|
||||
label="在途自动调拨",
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"每日 09:00 自动处理新增可调拨项与历史可恢复异常;"
|
||||
"每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
"label": "来源实例",
|
||||
"label_key": "admin.schedule.form.transferSourceCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "shipping_inventory_sources",
|
||||
},
|
||||
{
|
||||
"key": "recover_history",
|
||||
"type": "boolean",
|
||||
"label": "同票同日去重",
|
||||
"label_key": "admin.schedule.form.voucherCheckSameDayDedup",
|
||||
"label": "历史可恢复异常复核",
|
||||
"label_key": "admin.schedule.form.transferRecoverHistory",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
{
|
||||
"key": "notify_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "通知人",
|
||||
"label_key": "admin.schedule.form.transferNotifyUsers",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "users",
|
||||
},
|
||||
),
|
||||
defaults=dict(DEFAULT_JOB_PARAMS),
|
||||
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -4,11 +4,14 @@ backend/app/services/schedule/queue_service.py
|
||||
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
|
||||
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
|
||||
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
|
||||
domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入
|
||||
business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -28,6 +31,86 @@ from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
|
||||
|
||||
_worker_initialized = False
|
||||
_BUSINESS_REF_SLUG_MAX = 80
|
||||
|
||||
|
||||
def _schedule_job_slug(task: ScheduleTask) -> str:
|
||||
"""
|
||||
从排程任务生成写入 jobs.business_ref 的业务短码。
|
||||
|
||||
核心逻辑:优先 platform_api_path(如 accounting-voucher-check);无 path 时用 untagged。
|
||||
冒号替换为连字符,避免破坏 `schedule_run:{id}:{slug}` 三段格式。
|
||||
|
||||
Args:
|
||||
task: 排程任务。
|
||||
|
||||
Returns:
|
||||
最长 80 字符的 slug。
|
||||
"""
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
|
||||
slug = normalize_platform_api_path(getattr(task, "platform_api_path", None)) or "untagged"
|
||||
slug = slug.replace(":", "-").replace("/", "-")
|
||||
return slug[:_BUSINESS_REF_SLUG_MAX]
|
||||
|
||||
|
||||
def _schedule_task_label(task: ScheduleTask) -> str:
|
||||
"""
|
||||
jobs.message 与 worker 日志用的任务显示名。
|
||||
|
||||
核心逻辑:优先中文 name(如「立账凭证检核」);否则回落到 platform_api_path。
|
||||
|
||||
Args:
|
||||
task: 排程任务。
|
||||
|
||||
Returns:
|
||||
非空显示名。
|
||||
"""
|
||||
name = str(getattr(task, "name", None) or "").strip()
|
||||
if name:
|
||||
return name
|
||||
slug = _schedule_job_slug(task)
|
||||
return slug if slug != "untagged" else "未命名排程"
|
||||
|
||||
|
||||
def schedule_job_business_ref(run_id: int, task: ScheduleTask) -> str:
|
||||
"""
|
||||
生成 schedule Job 的 business_ref。
|
||||
|
||||
格式:`schedule_run:{run_id}:{platform_api_path}`,便于在 jobs 表区分立账凭证检核等任务。
|
||||
仍保留 run_id,取消/回收可按前缀精确匹配,避免 `schedule_run:1` 误伤 `schedule_run:13`。
|
||||
|
||||
Args:
|
||||
run_id: ScheduleRun 主键。
|
||||
task: 排程任务。
|
||||
|
||||
Returns:
|
||||
长度不超过 128 的 business_ref。
|
||||
"""
|
||||
return f"schedule_run:{int(run_id)}:{_schedule_job_slug(task)}"
|
||||
|
||||
|
||||
def query_jobs_for_schedule_run(run_id: int):
|
||||
"""
|
||||
按 ScheduleRun 主键查找对应通用 Job。
|
||||
|
||||
核心逻辑:兼容旧格式 `schedule_run:{id}` 与新格式 `schedule_run:{id}:{path}`。
|
||||
新格式必须带 `id` 后的冒号,避免 run_id=1 匹配到 10/11/13。
|
||||
|
||||
Args:
|
||||
run_id: ScheduleRun 主键。
|
||||
|
||||
Returns:
|
||||
已过滤 domain/job_type/business_ref 的 Query;调用方可继续按 status 收窄。
|
||||
"""
|
||||
run_id = int(run_id)
|
||||
legacy = f"schedule_run:{run_id}"
|
||||
prefix = f"schedule_run:{run_id}:"
|
||||
return db.session.query(Job).filter(
|
||||
Job.domain == "schedule",
|
||||
Job.job_type == JobType.SCHEDULE_RUN.value,
|
||||
db.or_(Job.business_ref == legacy, Job.business_ref.startswith(prefix)),
|
||||
)
|
||||
|
||||
|
||||
def _active_run(task_id: int) -> ScheduleRun | None:
|
||||
@@ -61,14 +144,19 @@ def _create_queued_run(
|
||||
*,
|
||||
trigger_type: str,
|
||||
triggered_by_user_id: int | None,
|
||||
api_request_json: dict[str, Any] | None = None,
|
||||
) -> tuple[ScheduleRun, int]:
|
||||
"""
|
||||
在当前事务创建 ScheduleRun 与对应通用 Job。
|
||||
|
||||
核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run;
|
||||
业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。
|
||||
|
||||
Args:
|
||||
task: 已由调用方锁定的排程任务。
|
||||
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
|
||||
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
|
||||
api_request_json: 可选运行参数(如立账凭证 `run_options.mode=force_all`),须在入队前写入以免 worker 抢跑。
|
||||
|
||||
Returns:
|
||||
`(ScheduleRun, job_id)`;调用方负责提交事务。
|
||||
@@ -86,22 +174,29 @@ def _create_queued_run(
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
started_at=None,
|
||||
status="queued",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
task_label = _schedule_task_label(task)
|
||||
platform_path = str(getattr(task, "platform_api_path", None) or "").strip()
|
||||
job_id = enqueue(
|
||||
JobType.SCHEDULE_RUN,
|
||||
{
|
||||
"schedule_task_id": task.id,
|
||||
"schedule_run_id": run.id,
|
||||
"schedule_no": task.schedule_no,
|
||||
"run_no": run.run_no,
|
||||
"task_name": task_label,
|
||||
"platform_api_path": platform_path,
|
||||
"trigger_type": normalized_trigger,
|
||||
"triggered_by_user_id": triggered_by_user_id,
|
||||
},
|
||||
domain="schedule",
|
||||
business_ref=f"schedule_run:{run.id}",
|
||||
business_ref=schedule_job_business_ref(run.id, task),
|
||||
created_by_id=triggered_by_user_id,
|
||||
max_attempts=3,
|
||||
message="排程等待后台执行",
|
||||
message=f"{task_label}等待后台执行",
|
||||
dedupe_active=False,
|
||||
commit=False,
|
||||
)
|
||||
@@ -112,6 +207,7 @@ def enqueue_manual_schedule_run(
|
||||
task_id: int,
|
||||
*,
|
||||
triggered_by_user_id: int | None,
|
||||
api_request_json: dict[str, Any] | None = None,
|
||||
) -> tuple[ScheduleRun, int, bool]:
|
||||
"""
|
||||
手动触发排程并写入 schedule 队列。
|
||||
@@ -119,6 +215,11 @@ def enqueue_manual_schedule_run(
|
||||
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
|
||||
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
|
||||
|
||||
Args:
|
||||
task_id: 排程任务主键。
|
||||
triggered_by_user_id: 触发人;系统触发可为空。
|
||||
api_request_json: 写入新 run 的请求快照;已有活动 run 时不会覆盖。
|
||||
|
||||
Returns:
|
||||
`(run, job_id, created)`;created=False 表示已有活动 run。
|
||||
"""
|
||||
@@ -135,13 +236,8 @@ def enqueue_manual_schedule_run(
|
||||
active = _active_run(task.id)
|
||||
if active is not None:
|
||||
job = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == "schedule",
|
||||
Job.job_type == JobType.SCHEDULE_RUN.value,
|
||||
Job.status.in_(("queued", "running")),
|
||||
Job.business_ref == f"schedule_run:{active.id}",
|
||||
)
|
||||
query_jobs_for_schedule_run(active.id)
|
||||
.filter(Job.status.in_(("queued", "running")))
|
||||
.order_by(Job.id.asc())
|
||||
.first()
|
||||
)
|
||||
@@ -151,6 +247,7 @@ def enqueue_manual_schedule_run(
|
||||
task,
|
||||
trigger_type="manual",
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.commit()
|
||||
return run, job_id, True
|
||||
@@ -242,13 +339,9 @@ def prepare_schedule_queue() -> int:
|
||||
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
|
||||
continue
|
||||
active_job = (
|
||||
db.session.query(Job.id)
|
||||
.filter(
|
||||
Job.domain == "schedule",
|
||||
Job.job_type == JobType.SCHEDULE_RUN.value,
|
||||
Job.business_ref == f"schedule_run:{run.id}",
|
||||
Job.status.in_(("queued", "running")),
|
||||
)
|
||||
query_jobs_for_schedule_run(run.id)
|
||||
.filter(Job.status.in_(("queued", "running")))
|
||||
.with_entities(Job.id)
|
||||
.first()
|
||||
)
|
||||
if active_job is None:
|
||||
@@ -308,11 +401,13 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
if task is None:
|
||||
finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除")
|
||||
return None
|
||||
task_label = _schedule_task_label(task)
|
||||
platform_path = str(getattr(task, "platform_api_path", None) or "").strip() or "untagged"
|
||||
if run.status in {"success", "failed", "partial_failed"}:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={"schedule_run_id": run.id, "status": run.status},
|
||||
message="排程已处于终态",
|
||||
result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path},
|
||||
message=f"{task_label}已处于终态",
|
||||
)
|
||||
return run
|
||||
|
||||
@@ -323,6 +418,14 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
run.started_at = run.started_at or datetime.utcnow()
|
||||
run.error_message = None
|
||||
db.session.commit()
|
||||
logger.info(
|
||||
"[schedule-run] start name=%s path=%s run_no=%s run_id=%s job_id=%s",
|
||||
task_label,
|
||||
platform_path,
|
||||
run.run_no,
|
||||
run.id,
|
||||
job_id,
|
||||
)
|
||||
result_run = run_task_now(
|
||||
task,
|
||||
trigger_type=run.trigger_type,
|
||||
@@ -331,8 +434,12 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
)
|
||||
finish_job(
|
||||
job_id,
|
||||
result={"schedule_run_id": result_run.id, "status": result_run.status},
|
||||
message="排程执行完成",
|
||||
result={
|
||||
"schedule_run_id": result_run.id,
|
||||
"status": result_run.status,
|
||||
"platform_api_path": platform_path,
|
||||
},
|
||||
message=f"{task_label}执行完成",
|
||||
)
|
||||
return result_run
|
||||
except Exception as exc:
|
||||
@@ -355,5 +462,11 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
|
||||
logger.exception(
|
||||
"[schedule-run] failed name=%s path=%s run_id=%s job_id=%s",
|
||||
task_label,
|
||||
platform_path,
|
||||
run_id,
|
||||
job_id,
|
||||
)
|
||||
return run
|
||||
@@ -5,7 +5,8 @@ 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。
|
||||
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
|
||||
handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -43,20 +44,16 @@ def request_cancel_run(run_id: int) -> None:
|
||||
持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。
|
||||
|
||||
核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过
|
||||
ScheduleRun 状态/存在性复检停止可中断的长循环。
|
||||
ScheduleRun 状态/存在性复检停止可中断的长循环。business_ref 兼容
|
||||
`schedule_run:{id}` 与 `schedule_run:{id}:{platform_api_path}`。
|
||||
"""
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.schedule.queue_service import query_jobs_for_schedule_run
|
||||
|
||||
now = datetime.utcnow()
|
||||
jobs = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == "schedule",
|
||||
Job.job_type == JobType.SCHEDULE_RUN.value,
|
||||
Job.business_ref == f"schedule_run:{int(run_id)}",
|
||||
Job.status.in_(("queued", "running")),
|
||||
)
|
||||
query_jobs_for_schedule_run(run_id)
|
||||
.filter(Job.status.in_(("queued", "running")))
|
||||
.all()
|
||||
)
|
||||
for job in jobs:
|
||||
@@ -493,6 +490,12 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -527,8 +530,16 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
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, 0, 0, [], [str(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)
|
||||
@@ -563,9 +574,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
|
||||
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] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
|
||||
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
|
||||
"[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"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py
|
||||
|
||||
用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。
|
||||
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。
|
||||
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_snapshot_line_ids。
|
||||
逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op;
|
||||
仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。
|
||||
"""
|
||||
@@ -18,7 +18,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
|
||||
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
|
||||
list_eligible_post_ot_line_keys,
|
||||
list_eligible_post_ot_snapshot_line_ids,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
@@ -63,7 +63,7 @@ def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]:
|
||||
if scanned >= safe_limit:
|
||||
break
|
||||
scanned += 1
|
||||
eligible = list_eligible_post_ot_line_keys(case)
|
||||
eligible = list_eligible_post_ot_snapshot_line_ids(case)
|
||||
if not eligible:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
@@ -38,7 +38,7 @@ def _ensure_headers() -> None:
|
||||
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证检核排程。
|
||||
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
|
||||
核心逻辑:注册 Excel 表头后委托 runner;周批默认 incremental。
|
||||
"""
|
||||
_ensure_headers()
|
||||
return run_voucher_check_batch(task, run)
|
||||
Reference in new issue
Block a user