feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程

清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
hugo committed 2026-08-20 20:23:10 +08:00
1 parent 260465b72d
commit 1b6483a4ea
466 files changed
+32115 -33796

No files matched your search

@@ -0,0 +1,160 @@
"""独立收料 RPA 排程等待态收口辅助。"""
from __future__ import annotations
from datetime import datetime, timedelta
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import ShippingReceiptRpaUnitRun
from app.services.schedule import normalize_platform_api_path
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
)
def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。"""
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa'))
def apply_deferred_receipt_schedule_run_state(
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
) -> ScheduleRun:
"""将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。"""
run.status = 'running'
run.started_at = run.started_at or datetime.utcnow()
run.total_count = total_count
run.success_count = 0
run.failed_count = 0
run.skipped_count = 0
run.finished_at = None
run.step_logs = step_logs
run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]}
db.session.commit()
return run
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
return {'finalized': False, 'reason': 'units_pending'}
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
run.total_count = len(units)
run.success_count = success_count
run.skipped_count = skipped_count
run.failed_count = failed_count
run.finished_at = datetime.utcnow()
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
db.session.commit()
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
deliver_schedule_receipt_summary(run.id)
return {'finalized': True, 'status': run.status}
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。"""
return bool(
task
and task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
return False
now = datetime.utcnow()
pending = ShippingReceiptRpaUnitRun.query.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
).all()
for unit in pending:
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=run.run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'timeout_seconds': timeout_seconds},
)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)'
run.step_logs = [*(run.step_logs or []), {
'step': 'freight_receipt_rpa', 'status': 'failed',
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
}]
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'}
return True
def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_receipt_rpa_task(task):
return 0
timeout_seconds = _receipt_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
)
if recovered:
db.session.commit()
return recovered
def recover_all_stale_receipt_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。"""
timeout_seconds = _receipt_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(status='running').all()
)
if recovered:
db.session.commit()
return recovered
@@ -0,0 +1,113 @@
"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。"""
from __future__ import annotations
import uuid
from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _wanted_source_codes(task: ScheduleTask) -> set[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(value).strip().upper() for value in values if str(value).strip()}
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
"""读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。"""
source = unit.inventory_source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}')
snapshot = dict(unit.config_snapshot_json or {})
return {
'unit_run_id': unit.id,
'callback_id': unit.callback_id,
'source_code': unit.source_code,
'connector_type': unit.connector_type,
'warehouse_id': unit.warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
}
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
units: list[ShippingReceiptRpaUnitRun] = []
for source, config in _eligible_sources(task):
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
for warehouse_id in warehouses:
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
unit.schedule_run_id = run.id
units.append(unit)
if not units:
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
db.session.add_all(units)
db.session.flush()
try:
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
except RuntimeError as exc:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
db.session.commit()
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, {
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
})
if not trigger_path:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
db.session.commit()
return len(units), 0, 0, 0, details, [], [{
'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS,
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
}]
@@ -0,0 +1,49 @@
"""收料原样归档三年到期对象清理。"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
try:
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', 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='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
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',
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}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
@@ -11,6 +11,8 @@ from __future__ import annotations
from typing import Any, Callable
from app import db
def _agent_apps_options() -> list[dict[str, Any]]:
"""启用中的 Agent 应用列表(value=agents.id)。"""
@@ -49,10 +51,24 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
]
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
} for source, _config in rows]
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"shipping_inventory_sources": _shipping_inventory_sources_options,
"shipping_receipt_sources": _shipping_receipt_sources_options,
}
@@ -133,6 +133,8 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
@@ -233,6 +235,25 @@ def _register_builtin_platform_jobs() -> None:
),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="freight-receipt-rpa",
label="货代收料 RPA",
handler=run_freight_receipt_rpa_schedule,
description="按计划从已配置收料报表的站点导出并归档收料文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
"default": [], "options_source": "shipping_receipt_sources",
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
handler=run_freight_receipt_rpa_retention_schedule,
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
+14 -1
View File
@@ -20,6 +20,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
is_awaiting_receipt_rpa_schedule_run,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
_worker_initialized = False
@@ -126,6 +131,7 @@ def enqueue_manual_schedule_run(
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
@@ -180,6 +186,10 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
created = 0
for task in tasks:
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
# 这只是终态化失败,不会自动重新导出。
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
@@ -229,7 +239,7 @@ def prepare_schedule_queue() -> int:
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run):
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
continue
active_job = (
db.session.query(Job.id)
@@ -254,6 +264,9 @@ def prepare_schedule_queue() -> int:
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_recovered:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
@@ -28,6 +28,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
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
@@ -489,6 +494,7 @@ 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:
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
@@ -550,6 +556,10 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
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: