feat(schedule): 新增平台任务参数契约与动态选项支持

This commit is contained in:
hugo committed 2026-07-09 13:19:36 +08:00
1 parent 2ce1aca023
commit 8b5b0b49bf
76 files changed
+7103 -1203

No files matched your search

+4 -3
View File
@@ -98,7 +98,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
cleanup_temp_notice_uploads(temp_request_id)
if not notice_items:
raise ValidationError(
"all uploaded files failed extraction or contained no parseable text",
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
details={"file_summary": file_summary},
)
payload["notice_items"] = notice_items
@@ -138,10 +138,11 @@ def register_chat_turn_routes(chat_bp) -> None:
body, uploads = _parse_turn_body_and_files()
request_id = uuid.uuid4().hex[:12]
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
if uploads:
_inject_multipart_upload_payload(body, uploads)
def relay_stream():
if uploads:
_inject_multipart_upload_payload(body, uploads)
yield from ChatTurnRuntime.stream(
user=user,
agent=agent,
+31
View File
@@ -19,6 +19,11 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@@ -128,6 +133,7 @@ def run_internal_job(name: str):
raise NotFoundError(f"Unknown platform job: {name}")
task, run = _resolve_schedule_task_and_run(key, data)
recover_stale_awaiting_rpa_schedule_runs(task)
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data,
@@ -152,6 +158,31 @@ def run_internal_job(name: str):
},
)
if should_defer_schedule_run_finalization(task, step_logs):
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,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
'awaiting_rpa_callback': True,
})
_finalize_run(
run,
total_count=total_count,
+2 -1
View File
@@ -2,7 +2,7 @@
backend/app/api/schedule/__init__.py
用途:排程管理 Blueprint 入口(Wave 3 分包)。
依赖:schedule/blueprint.py、config、tasks、runs。
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
"""
from app.api.schedule.blueprint import schedule_admin_bp
@@ -11,5 +11,6 @@ import app.api.schedule.common # noqa: F401
import app.api.schedule.config # noqa: F401
import app.api.schedule.tasks # noqa: F401
import app.api.schedule.runs # noqa: F401
import app.api.schedule.platform_tasks # noqa: F401
__all__ = ['schedule_admin_bp']
+5 -2
View File
@@ -67,14 +67,17 @@ def update_schedule_task_config(task_id: int):
config_data = data.get('config', data)
if isinstance(config_data, dict) and config_data:
# platform_job 仅白名单任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
raise ValidationError(
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
)
upsert_schedule_task_config(task_id, config_data, commit=False)
db.session.commit()
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
cfg_model = task.config
if cfg_model is None:
with db.session.no_autoflush:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
return jsonify({
'data_source_type': task.data_source_type,
'config': serialize_task_config(cfg_model) if cfg_model else None,
@@ -0,0 +1,59 @@
"""
backend/app/api/schedule/platform_tasks.py
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
"""
from __future__ import annotations
from flask import request
from app.api.schedule.blueprint import schedule_admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.schedule.job_options import list_job_options
from app.services.schedule.job_registry import list_platform_jobs
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
@require_admin
def get_platform_task_definitions():
"""
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
"""
return ok([
{
'task_type': job.key,
'label': job.label,
'label_key': job.label_key or None,
'description': job.description,
'description_key': job.description_key or None,
'category': job.category,
'enabled': job.enabled,
'params_schema': list(job.params_schema),
'defaults': job.defaults,
}
for job in list_platform_jobs()
if job.enabled
])
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
@require_admin
def get_platform_task_options():
"""
按 options_source 返回动态选项(统一 {label, value, description?})。
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
"""
source = str(request.args.get('source') or '').strip()
if not source:
raise ValidationError('source is required')
try:
options = list_job_options(source)
except ValueError as exc:
raise ValidationError(str(exc))
return ok(options)
+2
View File
@@ -21,6 +21,7 @@ from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@@ -33,6 +34,7 @@ def run_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
recover_stale_awaiting_rpa_schedule_runs(task)
user = get_current_user()
existing = (
db.session.query(ScheduleRun)
+30 -14
View File
@@ -3,7 +3,9 @@ backend/app/api/schedule/tasks.py
用途:排程任务 CRUD、导入导出、启用/禁用 API。
依赖:schedule.blueprint、schedule.common、services/schedule/*。
逻辑:/schedules* 路由(不含 run 触发与运行记录)。
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
ValueError→ValidationError 映射。
"""
from __future__ import annotations
@@ -39,7 +41,10 @@ def get_schedules():
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
@require_admin
def get_platform_jobs():
"""返回 Job Registry 已注册平台任务列表,供前端下拉动态加载。"""
"""
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
"""
from app.services.schedule.job_registry import list_platform_jobs
return jsonify([
@@ -48,8 +53,10 @@ def get_platform_jobs():
'label_key': job.label_key or None,
'label': job.label,
'description': job.description,
'enabled': job.enabled,
}
for job in list_platform_jobs()
if job.enabled
])
@@ -103,6 +110,7 @@ def post_schedule():
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
data_source_type = 'database'
try:
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
@@ -123,6 +131,7 @@ def post_schedule():
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
data_source_type=str(data_source_type) if data_source_type is not None else None,
job_params=data.get('job_params'),
notify_user_ids_json=data.get('notify_user_ids_json')
if isinstance(data.get('notify_user_ids_json'), list)
else [],
@@ -139,7 +148,10 @@ def post_schedule():
try:
upsert_schedule_task_config(task.id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
cfg_model = task.config
if cfg_model is None:
with db.session.no_autoflush:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
@@ -173,7 +185,7 @@ def patch_schedule(task_id: int):
if config_data is not None and not isinstance(config_data, dict):
raise ValidationError('config must be a JSON object')
try:
# [STEP 1] 先校验契约与 config 写入权限,避免 update_task 已提交后 config 被拒产生半更新
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
contract = apply_schedule_contract_to_payload({
'schedule_type': data.get('schedule_type', task.schedule_type),
'data_source_type': data.get('data_source_type', task.data_source_type),
@@ -193,7 +205,10 @@ def patch_schedule(task_id: int):
if config_data:
upsert_schedule_task_config(task_id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
cfg_model = task.config
if cfg_model is None:
with db.session.no_autoflush:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
if config_data:
@@ -237,19 +252,20 @@ def delete_schedule(task_id: int):
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
@require_admin
def enable_schedule(task_id: int):
"""启用排程并重新计算 next_run_at。"""
"""
启用排程并重新计算 next_run_at。
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
from app.services.schedule.scheduler_service import enable_task
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)
db.session.commit()
try:
task = enable_task(task)
except ValueError as exc:
db.session.rollback()
raise ValidationError(str(exc)) from exc
return jsonify(serialize_task(task))
+1 -1
View File
@@ -178,7 +178,7 @@ class Config:
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.json'
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
)
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
+21 -3
View File
@@ -25,10 +25,29 @@ def _get_current_user() -> User:
return user
def _resolve_request_agent_id() -> str | None:
"""
从 JSON body、query 或 multipart form 解析 agent_id。
核心逻辑:Chat Turn 附件上传走 multipart/form-data,agent_id 在 form 字段而非 JSON body。
"""
data = request.get_json(silent=True) or {}
if not isinstance(data, dict):
data = {}
return (
data.get("agent_id")
or data.get("agentId")
or request.args.get("agent_id")
or request.args.get("agentId")
or request.form.get("agent_id")
or request.form.get("agentId")
)
def require_agent_permission(f):
"""
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
核心逻辑:从 body/query 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
Args:
f: 被装饰的视图函数。
Returns:
@@ -37,8 +56,7 @@ def require_agent_permission(f):
@wraps(f)
def decorated_function(*args, **kwargs):
data = request.get_json(silent=True) or {}
agent_id = data.get('agent_id') or request.args.get('agent_id')
agent_id = _resolve_request_agent_id()
if not agent_id:
raise ValidationError('agent_id is required')
user = _get_current_user()
+2
View File
@@ -33,6 +33,8 @@ class ScheduleTask(Base):
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
data_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# platform_job 结构化参数(按 job_registry.params_schema 校验后写入)
job_params: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
@@ -340,6 +340,9 @@ def _register_headers_from_config() -> None:
for name, cfg in get_all_schedule_sql_configs().items():
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
register_inventory_rpa_excel_headers()
def reload_config() -> dict[str, Any]:
@@ -3,7 +3,8 @@ backend/app/services/schedule/faq_hot_aggregate_job.py
用途:排程管理触发的 FAQ 热点离线聚合执行器。
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用。
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用;
参数取 task.job_params.app_id(schema 契约),历史任务回退 task.dify_agent_id。
"""
from __future__ import annotations
@@ -15,15 +16,28 @@ from app.services.hot_faq_aggregator import HotFaqAggregator
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _resolve_agent_filter(task: ScheduleTask) -> int | None:
"""
解析限定应用参数。
核心逻辑:优先读结构化 job_params.app_id(params_schema 契约);
历史任务回退 task.dify_agent_id(旧参数通道)。
"""
params = task.job_params if isinstance(task.job_params, dict) else {}
raw = params.get("app_id")
if raw not in (None, ""):
return int(raw)
return int(task.dify_agent_id) if task.dify_agent_id else None
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行 FAQ 热点离线聚合(非 dry-run)。
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
核心逻辑:委托 HotFaqAggregator;job_params.app_id(回退 dify_agent_id)可限定 Agent。
@param task - 排程任务;参数经 job_registry.run_platform_job 按 params_schema 预校验
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
@returns ScheduleExecuteResult 元组
"""
agent_id = int(task.dify_agent_id) if task.dify_agent_id else None
agent_id = _resolve_agent_filter(task)
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=False)
step_logs: list[dict[str, Any]] = [
@@ -60,6 +60,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
platform_api_path=contract['platform_api_path'],
config=cfg,
)
# job_params 由 create_task/update_task 唯一归一化(导入跨环境不校选项范围)
existing = None
schedule_no = str(migrated.get('schedule_no') or '').strip()
if schedule_no:
@@ -74,6 +75,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
'dify_agent_id': migrated.get('dify_agent_id'),
'platform_api_path': contract['platform_api_path'],
'data_source_type': contract['data_source_type'],
'job_params': migrated.get('job_params'),
'notify_user_ids_json': migrated.get('notify_user_ids_json')
if isinstance(migrated.get('notify_user_ids_json'), list)
else [],
@@ -83,7 +85,13 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
'kb_group_id': migrated.get('kb_group_id'),
}
if existing:
update_task(existing, payload=task_payload, actor_id=actor_id, commit=False)
update_task(
existing,
payload=task_payload,
actor_id=actor_id,
commit=False,
check_options=False,
)
if cfg:
upsert_schedule_task_config(existing.id, cfg, commit=False)
else:
@@ -97,6 +105,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
dify_agent_id=task_payload['dify_agent_id'],
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
job_params=task_payload['job_params'],
notify_user_ids_json=task_payload['notify_user_ids_json'],
notify_enabled=task_payload['notify_enabled'],
enabled=task_payload['enabled'],
@@ -107,6 +116,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
else None
),
actor_id=actor_id,
check_options=False,
commit=False,
)
if cfg:
@@ -0,0 +1,74 @@
"""
backend/app/services/schedule/job_options.py
用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。
依赖:models.Agent、shipping_notice.inventory_sources。
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
"""
from __future__ import annotations
from typing import Any, Callable
def _agent_apps_options() -> list[dict[str, Any]]:
"""启用中的 Agent 应用列表(value=agents.id)。"""
from app.models import Agent
agents = (
Agent.query.filter(Agent.is_active.is_(True))
.order_by(Agent.sort_order.asc(), Agent.id.asc())
.all()
)
return [
{
"label": agent.name,
"value": agent.id,
"description": (agent.description or "")[:120] or None,
}
for agent in agents
]
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
"""启用中的货代库存源(value=source_code,来自 backend/config/shipping_inventory_sources.yaml)。"""
from app.services.shipping_notice.inventory_sources import list_inventory_sources
return [
{
"label": source.get("display_name") or source.get("source_code"),
"value": source.get("source_code"),
"description": f"{source.get('site')} · {source.get('warehouse_id')}",
}
for source in list_inventory_sources()
]
# 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,
}
def is_known_options_source(source: str) -> bool:
"""判断 options_source 是否已登记。"""
return str(source or "").strip() in _OPTIONS_PROVIDERS
def list_job_options(source: str) -> list[dict[str, Any]]:
"""
返回指定 options_source 的选项列表(统一 {label, value, description?} 结构)。
Args:
source: params_schema 中声明的 options_source 标识。
Returns:
选项列表;value 为 str/int,前端直接写入 job_params。
Raises:
ValueError: 未登记的 options_source。
"""
key = str(source or "").strip()
provider = _OPTIONS_PROVIDERS.get(key)
if not provider:
raise ValueError(f"Unknown options source: {source}")
return provider()
+246
View File
@@ -0,0 +1,246 @@
"""
backend/app/services/schedule/job_params.py
用途:平台任务 job_params 统一校验与契约归一化(保存排程、切换任务、导入、执行前共用)。
依赖:job_registry(读取 params_schema/defaults)、job_options(select 选项范围校验)、croniter(cron 校验)。
逻辑:scheduler_service.create_task/update_task 为唯一写入前归一化入口(API/import 只传原始值);
job_registry.run_platform_job 执行前调用 validate_task_params(check_options=False)。
"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any
# 高级参数逃生舱:折叠 JSON 区域的键,不做 schema 声明校验(兼容历史/特殊任务)
ADVANCED_PARAMS_KEY = "_advanced"
_SUPPORTED_TYPES = frozenset({
"text", "textarea", "number", "boolean", "select", "multi_select",
"date", "datetime", "cron", "json", "info",
})
class JobParamsValidationError(ValueError):
"""job_params 不满足注册表 params_schema。"""
def _validate_scalar(field: dict[str, Any], value: Any) -> Any:
"""
按字段 type 校验并归一化单个值。
核心逻辑:类型不符直接抛错,不做隐式转换(str "1" 不会转 number),
仅 number 允许 int/float 互通。
Raises:
JobParamsValidationError: 类型或格式非法
"""
key = field.get("key")
ftype = str(field.get("type") or "text")
if ftype in ("text", "textarea"):
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be a string")
return value
if ftype == "number":
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise JobParamsValidationError(f"param '{key}' must be a number")
return value
if ftype == "boolean":
if not isinstance(value, bool):
raise JobParamsValidationError(f"param '{key}' must be a boolean")
return value
if ftype == "select":
if not isinstance(value, (str, int)):
raise JobParamsValidationError(f"param '{key}' must be a string or integer option value")
return value
if ftype == "multi_select":
if not isinstance(value, list) or any(not isinstance(item, (str, int)) for item in value):
raise JobParamsValidationError(f"param '{key}' must be a list of option values")
return value
if ftype == "date":
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be a YYYY-MM-DD date string")
try:
datetime.strptime(value, "%Y-%m-%d")
except ValueError:
raise JobParamsValidationError(f"param '{key}' is not a valid date (YYYY-MM-DD)")
return value
if ftype == "datetime":
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be an ISO datetime string")
try:
datetime.fromisoformat(value)
except ValueError:
raise JobParamsValidationError(f"param '{key}' is not a valid ISO datetime")
return value
if ftype == "cron":
if not isinstance(value, str) or len(value.split()) != 5:
raise JobParamsValidationError(f"param '{key}' must be a 5-field cron expression")
try:
from croniter import croniter
if not croniter.is_valid(value):
raise JobParamsValidationError(f"param '{key}' is not a valid cron expression")
except ImportError:
pass
return value
if ftype == "json":
if isinstance(value, (dict, list)):
return value
if isinstance(value, str):
try:
return json.loads(value)
except json.JSONDecodeError:
raise JobParamsValidationError(f"param '{key}' is not valid JSON")
raise JobParamsValidationError(f"param '{key}' must be a JSON object/array")
raise JobParamsValidationError(f"param '{key}' has unsupported type '{ftype}'")
def _check_option_range(field: dict[str, Any], value: Any) -> None:
"""
校验 select/multi_select 值是否在 options_source 当前选项范围内。
Raises:
JobParamsValidationError: 值不在选项范围
"""
source = str(field.get("options_source") or "").strip()
if not source:
return
from app.services.schedule.job_options import list_job_options
allowed = {str(option["value"]) for option in list_job_options(source)}
values = value if isinstance(value, list) else [value]
invalid = [str(item) for item in values if str(item) not in allowed]
if invalid:
raise JobParamsValidationError(
f"param '{field.get('key')}' has values not in options of '{source}': {invalid}"
)
def validate_task_params(
task_type: str,
job_params: dict[str, Any] | None,
*,
check_options: bool = True,
) -> dict[str, Any]:
"""
按注册表 params_schema 校验平台任务参数并返回归一化结果。
【AI 触发时机】:保存排程(POST/PATCH /schedules)与执行平台任务前均须调用本函数。
核心逻辑:
[STEP 1] 查注册表拿 params_schema;未注册 key 抛错。
[STEP 2] 未声明字段默认拒绝(_advanced 例外:原样透传,供折叠 JSON 高级配置兜底)。
[STEP 3] 逐字段校验必填 + 类型 + 格式;缺省回填 field.default / defaults。
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
Args:
task_type: platform job key(如 shipping-inventory-rpa)。
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
Returns:
归一化后的参数 dict(含默认值回填与 _advanced 透传)。
Raises:
JobParamsValidationError: 未注册任务、未声明字段、必填缺失或类型/格式/范围非法。
"""
from app.services.schedule.job_registry import get_platform_job
definition = get_platform_job(task_type)
if not definition:
raise JobParamsValidationError(f"Unknown platform job: {task_type}")
raw = dict(job_params or {})
if not isinstance(raw, dict):
raise JobParamsValidationError("job_params must be a JSON object")
schema_fields = [f for f in definition.params_schema if f.get("type") != "info"]
declared_keys = {f.get("key") for f in schema_fields}
# [STEP 2] 未声明字段默认拒绝;_advanced 例外
advanced = raw.pop(ADVANCED_PARAMS_KEY, None)
if advanced is not None and not isinstance(advanced, dict):
raise JobParamsValidationError(f"'{ADVANCED_PARAMS_KEY}' must be a JSON object")
unknown = sorted(set(raw) - declared_keys)
if unknown:
raise JobParamsValidationError(f"unknown params for '{definition.key}': {unknown}")
# [STEP 3] 逐字段校验与默认值回填
result: dict[str, Any] = {}
for field in schema_fields:
key = field.get("key")
provided = key in raw
value = raw.get(key)
if value is None or (not provided):
default = field.get("default", definition.defaults.get(key))
result[key] = default
if field.get("required") and result[key] in (None, "", []):
raise JobParamsValidationError(f"param '{key}' is required")
continue
value = _validate_scalar(field, value)
if field.get("required") and value in ("", []):
raise JobParamsValidationError(f"param '{key}' is required")
# [STEP 4] 选项范围校验(仅保存期)
if check_options and field.get("type") in ("select", "multi_select") and value not in (None, []):
_check_option_range(field, value)
result[key] = value
if advanced:
result[ADVANCED_PARAMS_KEY] = advanced
return result
def normalize_job_params_for_contract(
schedule_type: str,
platform_api_path: str | None,
raw_job_params: Any = None,
*,
check_options: bool = True,
) -> dict[str, Any] | None:
"""
按排程契约归一化 job_params(保存 / 切换任务 / 导入共用)。
核心逻辑:
- 非 platform_job:禁止携带 job_params,返回 None。
- platform_job 有 params_schema:raw 为 None 时按 {} 校验并回填默认值。
- platform_job 无 params_schema:None → None;dict → 原样(空 dict 视为 None)。
Args:
schedule_type: data_pipeline | platform_job
platform_api_path: 平台任务 key
raw_job_params: 请求体或既有参数;切换任务且未传时可传 None 触发默认值重置
check_options: 是否校验 options_source 取值范围
Returns:
归一化后的 job_params,或 None(无 schema / 非平台任务)
Raises:
JobParamsValidationError: 类型非法、未知字段、schema/选项校验失败
"""
from app.services.schedule.schedule_contract import SCHEDULE_TYPE_PLATFORM_JOB
if schedule_type != SCHEDULE_TYPE_PLATFORM_JOB:
if raw_job_params is not None:
raise JobParamsValidationError("job_params is only supported for platform_job schedules")
return None
from app.services.schedule.job_registry import get_platform_job
definition = get_platform_job(platform_api_path)
has_schema = bool(definition and definition.params_schema)
if raw_job_params is None:
if not has_schema:
return None
raw_job_params = {}
if not isinstance(raw_job_params, dict):
raise JobParamsValidationError("job_params must be a JSON object")
if not has_schema:
return raw_job_params or None
return validate_task_params(
str(platform_api_path or ""),
raw_job_params,
check_options=check_options,
)
+87 -10
View File
@@ -1,14 +1,15 @@
"""
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(key → handler)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key。
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、job_params(执行前校验)。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Any, Callable
from app.models import ScheduleRun, ScheduleTask
@@ -22,7 +23,22 @@ _REGISTRY: dict[str, "PlatformJobDefinition"] = {}
@dataclass(frozen=True)
class PlatformJobDefinition:
"""平台内置 Job 元数据与执行 handler。"""
"""
平台内置 Job 的完整任务契约:执行入口 + 展示信息 + 参数 schema + 默认值。
params_schema 字段通用结构(前端 DynamicTaskParamsForm 按 type 渲染,不认识具体任务):
{
"key": "source_codes", # job_params 中的键名
"type": "multi_select", # text|textarea|number|boolean|select|multi_select|date|datetime|cron|json|info
"label": "库存源", # 中文 fallback;前端优先 $t(label_key)
"label_key": "...", # 前端 i18n key(可选)
"required": False,
"default": [],
"options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选)
"placeholder": "...", "placeholder_key": "...",
"help": "...", "help_key": "...",
}
"""
key: str
label: str
@@ -31,6 +47,13 @@ class PlatformJobDefinition:
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
label_key: str = ""
description_key: str = ""
category: str = "platform"
# 任务停用开关:False 时列表不下发、契约校验拒绝创建/改指向、执行入口拒绝运行
enabled: bool = True
# 参数契约:字段 schema 列表(tuple 保持 frozen dataclass 不可变)与默认值
params_schema: tuple[dict[str, Any], ...] = ()
defaults: dict[str, Any] = field(default_factory=dict)
def register_platform_job(definition: PlatformJobDefinition) -> None:
@@ -44,6 +67,11 @@ def register_platform_job(definition: PlatformJobDefinition) -> None:
handler=definition.handler,
description=definition.description,
label_key=definition.label_key,
description_key=definition.description_key,
category=definition.category,
enabled=definition.enabled,
params_schema=tuple(definition.params_schema or ()),
defaults=dict(definition.defaults or {}),
)
@@ -70,25 +98,36 @@ def run_platform_job(
) -> ScheduleExecuteResult:
"""
执行已注册平台 Job。
核心逻辑:执行前按注册表 params_schema 再校验一次 task.job_params
(check_options=False:选项集合可能随时间漂移,运行期只校验类型与必填),
校验失败直接抛错终止本次 run。
Args:
key: platform_api_path job key
task: 排程任务
task: 排程任务(结构化参数存 task.job_params)
run: 执行批次
payload: internal API 请求体(部分 handler 可读 agent_id 等)
Returns:
ScheduleExecuteResult 七元组
Raises:
KeyError: 未注册 key
ValueError: 任务已停用,或 job_params 不满足 params_schema
"""
definition = get_platform_job(key)
if not definition:
raise KeyError(f"Unknown platform job: {key}")
_ = payload # 预留扩展;FAQ 等从 task 读取 dify_agent_id
if not definition.enabled:
raise ValueError(f"Platform job is disabled: {definition.key}")
_ = payload # 预留扩展;handler 从 task.job_params(已归一化)/ legacy 字段读取参数
if definition.params_schema:
from app.services.schedule.job_params import validate_task_params
# [STEP 1] 执行前再校验;归一化结果写回 task,handler 读到的是契约后的参数
task.job_params = validate_task_params(key, task.job_params or {}, check_options=False)
return definition.handler(task, run)
def _register_builtin_platform_jobs() -> None:
"""模块加载时注册内置平台 Job。"""
"""模块加载时注册内置平台 Job(含参数契约)。"""
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
@@ -98,14 +137,51 @@ def _register_builtin_platform_jobs() -> None:
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
description="批量写入库存 RPA export trigger,由 freight_rpa_worker 异步导出。",
description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。",
description_key="admin.schedule.form.shippingInventoryJobHint",
category="shipping",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "库存源",
"label_key": "admin.schedule.form.shippingInventorySources",
# 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
"placeholder": "留空则导出全部启用库存源",
"placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder",
"help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
"help_key": "admin.schedule.form.shippingInventorySourcesHelp",
},
),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
label_key="admin.schedule.form.platformJobFaqHotAggregate",
handler=run_faq_hot_aggregate_schedule,
description="ChatLog 热点发现,结果写入 faq_hot_candidates。",
description="按 Cron 自动执行 ChatLog 热点发现,结果写入 faq_hot_candidates。",
description_key="admin.schedule.form.faqHotAggregateHint",
category="faq",
params_schema=(
{
"key": "app_id",
"type": "select",
"label": "限定应用",
"label_key": "admin.schedule.form.faqHotAgentFilter",
"required": False,
"default": None,
"options_source": "agent_apps",
"placeholder": "全部应用",
"placeholder_key": "admin.schedule.form.faqHotAllAgents",
"help": "留空则聚合所有 Agent;选定后仅统计该应用的 ChatLog。",
"help_key": "admin.schedule.form.faqHotAgentFilterHelp",
},
),
defaults={"app_id": None},
))
register_platform_job(PlatformJobDefinition(
key="fixed-assets-snapshot",
@@ -113,6 +189,7 @@ def _register_builtin_platform_jobs() -> None:
label_key="admin.schedule.form.platformJobFixedAssetsSnapshot",
handler=run_fixed_assets_snapshot_schedule,
description="同步 PLM 固资快照至本地 manifest。",
category="assets",
))
@@ -44,6 +44,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
'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 [],
@@ -2,8 +2,10 @@
backend/app/services/schedule/schedule_contract.py
用途:排程三层语义校验与旧数据迁移(schedule_type / data_source_type / platform_api_path)。
依赖:job_registry.get_platform_job。
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用。
依赖:job_registry.get_platform_job(含 enabled 停用判定,含 config 白名单)。
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用;
enabled=False 的平台任务在契约校验阶段即拒绝新建/改指向;
platform_job_allows_config 同步要求 registry enabled,禁止给停用任务写 ScheduleTaskConfig。
"""
from __future__ import annotations
@@ -31,8 +33,19 @@ PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
def platform_job_allows_config(key: str | None) -> bool:
"""判断该 platform_job 是否允许写 ScheduleTaskConfig。"""
return normalize_job_key(key) in PLATFORM_JOBS_ALLOWING_CONFIG
"""
判断该 platform_job 是否允许写 ScheduleTaskConfig。
核心逻辑:须在白名单内,且 registry 中存在且 enabled=True。
停用任务与创建/更新/执行一致,禁止继续改其 ScheduleTaskConfig。
"""
normalized = normalize_job_key(key)
if normalized not in PLATFORM_JOBS_ALLOWING_CONFIG:
return False
from app.services.schedule.job_registry import get_platform_job
definition = get_platform_job(normalized)
return bool(definition and definition.enabled)
def assert_schedule_config_writable(
@@ -44,7 +57,7 @@ def assert_schedule_config_writable(
"""
携带 config 时校验是否允许写入 ScheduleTaskConfig。
Raises:
ValueError: 非白名单 platform_job 携带 config
ValueError: 非白名单 / 已停用 platform_job 携带 config
"""
if not config or not isinstance(config, dict):
return
@@ -156,11 +169,11 @@ def validate_schedule_fields(
Args:
schedule_type: data_pipeline | platform_job
data_source_type: 仅 data_pipeline 必填
platform_api_path: 仅 platform_job 必填且须已注册
platform_api_path: 仅 platform_job 必填且须已注册且 enabled
Returns:
(schedule_type, data_source_type, platform_api_path)
Raises:
ValueError: schedule_type 未知、字段组合非法或未注册 job key
ValueError: schedule_type 未知、字段组合非法、未注册或已停用 job key
"""
st = str(schedule_type or "").strip().lower()
if st not in VALID_SCHEDULE_TYPES:
@@ -180,8 +193,12 @@ def validate_schedule_fields(
raise ValueError("platform_api_path is required for platform_job")
from app.services.schedule.job_registry import get_platform_job
if not get_platform_job(path):
definition = get_platform_job(path)
if not definition:
raise ValueError(f"Unknown platform job key: {path}")
# enabled=False 表示任务停用:不可新建/改指向该 key(列表接口也不展示)
if not definition.enabled:
raise ValueError(f"Platform job is disabled: {path}")
return st, None, path
raise ValueError(f"Unsupported schedule_type: {schedule_type}")
@@ -1,3 +1,12 @@
"""
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新/立即执行)与后台调度 worker。
依赖: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
未传参时重置默认值);run_task_now 经 resolve_schedule_executor 分发 handler。
"""
from __future__ import annotations
import threading
@@ -14,6 +23,14 @@ 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
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
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, utc_now_naive
@@ -94,6 +111,9 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
f'状态: {status_label}\n'
f'总数: {run.total_count} 成功: {run.success_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 生成失败'
media_id = None
if run.excel_file_data and run.excel_file_name:
@@ -166,6 +186,7 @@ def create_task(
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,
@@ -173,7 +194,15 @@ def create_task(
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)
@@ -182,6 +211,12 @@ def create_task(
'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,
@@ -193,6 +228,7 @@ def create_task(
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 [],
@@ -219,8 +255,20 @@ def update_task(
payload: dict[str, Any],
actor_id: int | None,
commit: bool = True,
check_options: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
"""
更新排程任务字段。
核心逻辑:契约字段与 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",
@@ -248,7 +296,10 @@ def update_task(
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
if any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path")):
# [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),
@@ -257,6 +308,32 @@ def update_task(
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))
@@ -270,7 +347,51 @@ def update_task(
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:
recover_stale_awaiting_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
@@ -319,6 +440,19 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
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,
)
duration_ms = int((time.time() - start_ts) * 1000)
if current_app:
current_app.logger.info(
@@ -449,13 +583,27 @@ def start_scheduler(app):
stuck = db.session.query(ScheduleRun).filter(
ScheduleRun.status == "running",
).all()
cleaned = 0
for r in stuck:
if is_awaiting_rpa_schedule_run(r):
continue
r.status = "failed"
r.error_message = "服务重启,执行中断"
r.finished_at = datetime.utcnow()
if stuck:
cleaned += 1
if cleaned:
db.session.commit()
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
current_app.logger.info(
"[schedule-worker] cleaned %d stuck running runs on startup (skipped awaiting RPA)",
cleaned,
)
recovered_awaiting = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered_awaiting:
current_app.logger.info(
"[schedule-worker] recovered %d stale awaiting RPA runs on startup",
recovered_awaiting,
)
while True:
try:
@@ -466,6 +614,7 @@ def start_scheduler(app):
ScheduleTask.next_run_at <= now,
).limit(5).with_for_update(skip_locked=True).all()
for task in due_tasks:
recover_stale_awaiting_rpa_schedule_runs(task)
has_running = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
@@ -0,0 +1,551 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import normalize_platform_api_path
from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds
SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa"
AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback"
FinalizeScheduleRunResult = dict[str, Any]
_INVENTORY_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"display_name",
"inventory_file_no",
"export_status",
"error_message",
]
_INVENTORY_RPA_HEADER_LABELS = {
"source_code": "库存源",
"warehouse_id": "仓库",
"display_name": "名称",
"inventory_file_no": "库存快照号",
"export_status": "导出状态",
"error_message": "错误原因",
}
def register_inventory_rpa_excel_headers() -> None:
"""
注册货代库存 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
SHIPPING_INVENTORY_RPA_JOB_KEY,
_INVENTORY_RPA_HEADER_ORDER,
_INVENTORY_RPA_HEADER_LABELS,
)
def is_awaiting_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否处于等待 RPA 回调的 running 态。"""
if not run or run.status != "running":
return False
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return bool(summary.get("awaiting_rpa"))
def _source_identity_key(source_code: Any, warehouse_id: Any) -> tuple[str, str]:
"""库存源匹配键:(source_code, warehouse_id) 均 uppercase。"""
return (
str(source_code or "").strip().upper(),
str(warehouse_id or "").strip().upper(),
)
def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool:
"""判断是否为货代库存 RPA 平台排程任务。"""
if not task or task.schedule_type != "platform_job":
return False
return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY
def is_awaiting_rpa_callback(step_logs: list | None) -> bool:
"""step_logs 是否包含 awaiting_rpa_callback 标记。"""
if not step_logs:
return False
return any(
isinstance(item, dict) and item.get("status") == AWAITING_RPA_CALLBACK_STATUS
for item in step_logs
)
def should_defer_schedule_run_finalization(task: ScheduleTask, step_logs: list | None) -> bool:
"""货代库存 RPA 写 trigger 成功后应 defer 终态。"""
return is_shipping_inventory_rpa_task(task) and is_awaiting_rpa_callback(step_logs)
def _compute_run_status(*, total_count: int, success_count: int, failed_count: int) -> str:
"""
根据成功/失败数计算排程终态。
核心逻辑:须 success_count == total_count 且无失败才算 success;全失败 failed;否则 partial_failed。
"""
if total_count <= 0:
return "failed"
if success_count >= total_count and failed_count == 0:
return "success"
if success_count == 0:
return "failed"
return "partial_failed"
def _build_finalize_details(
pending_details: list[dict[str, Any]],
*,
created: list[dict[str, Any]],
failed: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""
合并 trigger 阶段 pending 明细与 RPA 回调结果,供 Excel 导出。
核心逻辑:按 (source_code, warehouse_id) 对齐;未回调的 pending 源补为 failed。
"""
pending_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for item in pending_details:
if not isinstance(item, dict):
continue
code = str(item.get("source_code") or "").strip()
if not code:
continue
pending_by_key[_source_identity_key(code, item.get("warehouse_id"))] = item
handled_keys: set[tuple[str, str]] = set()
details: list[dict[str, Any]] = []
for item in created:
if not isinstance(item, dict):
continue
code = str(item.get("source_code") or "").strip()
wh = str(item.get("warehouse_id") or "").strip()
key = _source_identity_key(code, wh)
handled_keys.add(key)
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": item.get("inventory_file_no"),
"export_status": "success",
"error_message": "",
})
for item in failed:
if not isinstance(item, dict):
continue
code = str(item.get("source_code") or "").strip()
wh = str(item.get("warehouse_id") or "").strip()
key = _source_identity_key(code, wh)
handled_keys.add(key)
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
"export_status": "failed",
"error_message": str(item.get("error") or item.get("error_message") or "export failed")[:500],
})
for key, base in pending_by_key.items():
if key in handled_keys:
continue
details.append({
"source_code": base.get("source_code"),
"warehouse_id": base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
"export_status": "failed",
"error_message": "RPA callback missing",
})
return details
def apply_deferred_schedule_run_state(
run: ScheduleRun,
task: ScheduleTask,
*,
total_count: int,
success_count: int,
failed_count: int,
skipped_count: int,
details: list[dict[str, Any]],
errors: list[str],
step_logs: list[dict[str, Any]] | None,
) -> ScheduleRun:
"""
trigger 已写入、等待 RPA 回调:保持 running,记录 awaiting 元数据,跳过终态收尾。
核心逻辑:复用 run 时若 started_at 为空则补写,避免 recover 立即判超时。
"""
run.status = "running"
if not run.started_at:
run.started_at = datetime.utcnow()
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
run.finished_at = None
run.duration_ms = 0
run.error_message = "; ".join(errors[:3]) if errors else None
run.response_summary_json = {
"awaiting_rpa": True,
"pending_details": details,
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
"schedule_finalize_status": None,
"schedule_finalize_error": None,
}
run.excel_file_data = None
run.excel_file_name = None
run.excel_file_size = 0
db.session.commit()
if current_app:
current_app.logger.info(
"[schedule-run] run_no=%s deferred awaiting_rpa_callback total=%d",
run.run_no,
total_count,
)
return run
def _try_recover_stale_awaiting_run(
run: ScheduleRun,
*,
cutoff: datetime,
timeout_seconds: int,
require_inventory_rpa_task: bool = True,
) -> bool:
"""
尝试回收单条超时 awaiting RPA run。
核心逻辑:可选校验 task 为货代库存 RPA,避免其他流程复用 awaiting_rpa 字段被误杀。
Returns:
bool: 是否已标记回收(未 commit,由调用方统一提交)。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get("awaiting_rpa"):
return False
if require_inventory_rpa_task:
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_shipping_inventory_rpa_task(task):
return False
if run.started_at is None:
return False
if run.started_at > cutoff:
return False
finished_at = datetime.utcnow()
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "failed",
"detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds},
})
run.status = "failed"
run.finished_at = finished_at
run.duration_ms = int((finished_at - run.started_at).total_seconds() * 1000)
run.error_message = "RPA 库存导出等待超时"
run.step_logs = step_logs
summary = dict(summary)
summary["awaiting_rpa"] = False
summary["recovered_reason"] = "rpa_callback_timeout"
run.response_summary_json = summary
return True
def recover_stale_awaiting_rpa_schedule_runs(task: ScheduleTask) -> int:
"""
回收超时的 awaiting RPA 排程 run,避免后续执行被 running 卡住。
核心逻辑:仅处理 response_summary_json.awaiting_rpa=true 的 running run。
Returns:
int: 回收条数
"""
if not is_shipping_inventory_rpa_task(task):
return 0
timeout_seconds = max(60, rpa_inventory_timeout_seconds())
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
stale_runs = (
db.session.query(ScheduleRun)
.filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
)
.all()
)
recovered = 0
for run in stale_runs:
if _try_recover_stale_awaiting_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds):
recovered += 1
if recovered:
db.session.commit()
if current_app:
current_app.logger.warning(
"[schedule-run] recovered %d stale awaiting_rpa runs task_id=%s",
recovered,
task.id,
)
return recovered
def recover_all_stale_awaiting_rpa_schedule_runs() -> int:
"""
全局扫描并回收已超时的 awaiting RPA run(服务启动时调用)。
核心逻辑:不依赖 task 是否 due,启动后立即清理陈旧 running。
Returns:
int: 回收条数
"""
timeout_seconds = max(60, rpa_inventory_timeout_seconds())
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
runs = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
recovered = 0
for run in runs:
if _try_recover_stale_awaiting_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds):
recovered += 1
if recovered:
db.session.commit()
if current_app:
current_app.logger.warning(
"[schedule-run] recovered %d stale awaiting_rpa runs on startup sweep",
recovered,
)
return recovered
def _record_finalize_failure(run: ScheduleRun, exc: Exception) -> None:
"""finalize 失败时保留 awaiting 态并写入错误摘要,便于回调安全重试。"""
summary = dict(run.response_summary_json or {})
summary["awaiting_rpa"] = True
summary["schedule_finalize_status"] = "failed"
summary["schedule_finalize_error"] = str(exc)[:500]
run.response_summary_json = summary
run.error_message = f"排程终态化失败: {exc}"[:500]
db.session.commit()
def finalize_shipping_inventory_schedule_run(
schedule_run_id: int,
*,
created: list[dict[str, Any]],
failed: list[dict[str, Any]],
payload: dict[str, Any] | None = None,
) -> FinalizeScheduleRunResult:
"""
RPA 批量回调后终态化排程 run:计数、Excel、KB 同步、企微通知。
核心逻辑:awaiting_rpa=true 且 running 时可执行;已终态则幂等返回;失败保留 awaiting 供重试。
Returns:
FinalizeScheduleRunResult: ok / already_finalized / schedule_finalize_status / error
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if not run:
return {"ok": False, "error": "schedule run not found", "schedule_finalize_status": "skipped"}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != "running":
if run.status in {"success", "failed", "partial_failed"} and not summary.get("awaiting_rpa"):
return {
"ok": True,
"already_finalized": True,
"schedule_finalize_status": "ok",
"run_status": run.status,
}
return {
"ok": False,
"error": f"schedule run status is {run.status}",
"schedule_finalize_status": "skipped",
}
if not summary.get("awaiting_rpa"):
return {"ok": False, "error": "schedule run is not awaiting RPA callback", "schedule_finalize_status": "skipped"}
try:
return _finalize_shipping_inventory_schedule_run_impl(run, created=created, failed=failed, payload=payload)
except Exception as exc:
db.session.rollback()
db.session.refresh(run)
_record_finalize_failure(run, exc)
if current_app:
current_app.logger.error(
"[schedule-run] finalize failed run_id=%s run_no=%s: %s",
run.id,
run.run_no,
exc,
exc_info=True,
)
return {
"ok": False,
"error": str(exc),
"schedule_finalize_status": "failed",
"manual_retryable": True,
}
def _finalize_shipping_inventory_schedule_run_impl(
run: ScheduleRun,
*,
created: list[dict[str, Any]],
failed: list[dict[str, Any]],
payload: dict[str, Any] | None,
) -> FinalizeScheduleRunResult:
"""finalize 主流程(内部使用,异常由外层捕获并记录)。"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not task:
raise RuntimeError("schedule task not found")
pending_details = summary.get("pending_details") if isinstance(summary.get("pending_details"), list) else []
details = _build_finalize_details(pending_details, created=created, failed=failed)
success_count = sum(1 for item in details if item.get("export_status") == "success")
failed_count = sum(1 for item in details if item.get("export_status") == "failed")
total_count = max(int(run.total_count or 0), len(pending_details), len(details))
status = _compute_run_status(
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
)
finished_at = datetime.utcnow()
duration_ms = 0
if run.started_at:
duration_ms = int((finished_at - run.started_at).total_seconds() * 1000)
errors: list[str] = []
if failed_count:
errors.extend(
f"{item.get('source_code')}/{item.get('warehouse_id')}: {item.get('error_message')}"
for item in details
if item.get("export_status") == "failed" and item.get("error_message")
)
register_inventory_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY)
excel_export_ok = True
try:
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,
)
except Exception as excel_exc:
excel_export_ok = False
if current_app:
current_app.logger.error("[schedule-run] inventory RPA excel export failed: %s", excel_exc)
file_data, file_name, file_size = None, None, 0
errors.append(f"Excel导出失败: {excel_exc}")
if status == "success":
status = "partial_failed"
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed",
"detail": {
"created_count": success_count,
"failed_count": failed_count,
"rpa_mode": (payload or {}).get("rpa_mode"),
"run_no": (payload or {}).get("run_no"),
"excel_export_ok": excel_export_ok,
},
})
run.finished_at = finished_at
run.duration_ms = duration_ms
run.status = status
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.step_logs = step_logs
run.api_response_json = {
"run_no": (payload or {}).get("run_no"),
"rpa_mode": (payload or {}).get("rpa_mode"),
"created": created,
"failed": failed,
}
run.response_summary_json = {
"awaiting_rpa": False,
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
"schedule_finalize_status": "ok",
"schedule_finalize_error": None,
"excel_export_status": "ok" if excel_export_ok else "failed",
"excel_failed": not excel_export_ok,
"rpa_finalize": {
"created_count": success_count,
"failed_count": failed_count,
"excel_failed": not excel_export_ok,
},
}
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 = finished_at
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] inventory RPA 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:
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
if current_app:
current_app.logger.error("[schedule-run] inventory RPA wecom notify failed: %s", wecom_exc)
if current_app:
current_app.logger.info(
"[schedule-run] run_no=%s finalized after RPA callback status=%s success=%d failed=%d",
run.run_no,
status,
success_count,
failed_count,
)
return {
"ok": True,
"schedule_finalize_status": "ok",
"run_status": status,
"success_count": success_count,
"failed_count": failed_count,
}
@@ -3,7 +3,8 @@ backend/app/services/schedule/shipping_inventory_rpa_job.py
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
"""
from __future__ import annotations
@@ -14,6 +15,7 @@ from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
@@ -35,24 +37,90 @@ def _parse_api_body_template(task: ScheduleTask) -> dict[str, Any] | None:
return None
def _normalize_filter_tokens(raw: Any) -> set[str]:
"""
将 JSON 中的筛选值归一为 uppercase token 集合。
核心逻辑:支持 str / list;忽略空值。
"""
if isinstance(raw, str):
values = [raw]
elif isinstance(raw, list):
values = raw
else:
return set()
return {str(item).strip().upper() for item in values if str(item).strip()}
def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
"""收集库存源可用于匹配的标识集合(source_code / warehouse_id / match_aliases)。"""
tokens: set[str] = set()
for key in ("source_code", "warehouse_id", "warehouse_code"):
value = str(source.get(key) or "").strip().upper()
if value:
tokens.add(value)
for alias in source.get("match_aliases") or []:
value = str(alias or "").strip().upper()
if value:
tokens.add(value)
return tokens
def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]:
"""
从 api_body_template 提取筛选 token。
推荐键:source_codes;兼容:source_code / warehouse_ids / warehouse_id / match_aliases。
"""
wanted: set[str] = set()
for key in (
"source_codes",
"source_code",
"warehouse_ids",
"warehouse_id",
"match_aliases",
):
if key in body_template:
wanted |= _normalize_filter_tokens(body_template.get(key))
return wanted
def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None:
"""
解析筛选参数来源。
核心逻辑:优先结构化 job_params(含 _advanced 展平合并,params_schema 契约通道);
历史任务回退 ScheduleTaskConfig.api_body_template JSON。
"""
params = task.job_params if isinstance(task.job_params, dict) else None
if params:
merged = {k: v for k, v in params.items() if k != "_advanced"}
advanced = params.get("_advanced")
if isinstance(advanced, dict):
merged.update(advanced)
if any(v not in (None, "", []) for v in merged.values()):
return merged
return _parse_api_body_template(task)
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
"""读取 enabled 库存源;api_body_template 可限定 source_code 子集。"""
"""
读取 enabled 库存源;job_params / api_body_template 可限定子集。
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / warehouse_id / match_aliases 命中。
"""
enabled = list_inventory_sources()
body_template = _parse_api_body_template(task)
body_template = _resolve_filter_payload(task)
if body_template:
codes = body_template.get("source_codes") or body_template.get("source_code")
if isinstance(codes, str):
codes = [codes]
if isinstance(codes, list):
wanted = {str(code).strip().upper() for code in codes if str(code).strip()}
enabled = [item for item in enabled if str(item.get("source_code") or "").upper() in wanted]
wanted = _extract_wanted_tokens(body_template)
if wanted:
enabled = [
item for item in enabled
if _source_identity_tokens(item) & wanted
]
return [source for source in enabled if build_rpa_inventory_source(source.get("source_code"))]
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。
核心逻辑:不在排程内同步等待 RPA;ScheduleRun 记录 trigger 写入结果。
核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。
"""
sources = _filter_sources(task)
step_logs: list[dict[str, Any]] = [{
@@ -90,7 +158,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "triggered",
"status": AWAITING_RPA_CALLBACK_STATUS,
"detail": {"trigger_path": trigger_path, "run_no": run_no},
})
details = [
@@ -101,4 +169,4 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
}
for item in sources
]
return len(sources), len(sources), 0, 0, details, [], step_logs
return len(sources), 0, 0, 0, details, [], step_logs
+65 -5
View File
@@ -1,3 +1,10 @@
"""
backend/app/services/schedule/sql_config.py
用途:排程 SQL/数据源配置 dataclass 与 ScheduleTaskConfig ORM 读写。
依赖:models.ScheduleTask、ScheduleTaskConfig。
逻辑:由 api/schedule/*、import_service、scheduler_service 调用 upsert/get。
"""
from __future__ import annotations
import os
@@ -212,6 +219,63 @@ def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
return results
def _sync_postgres_serial_sequence(table_name: str) -> None:
"""
将 PostgreSQL serial 序列校准为 MAX(id),避免手工导入或迁移后主键冲突。
核心逻辑:仅对白名单表执行 setval;非 PostgreSQL 方言下无操作。
Args:
table_name: 仅允许 schedule_task_configs。
"""
from app import db
if table_name != 'schedule_task_configs':
raise ValueError(f'unsupported table for sequence sync: {table_name}')
bind = db.session.get_bind()
if bind.dialect.name != 'postgresql':
return
db.session.execute(
db.text(
"SELECT setval("
"pg_get_serial_sequence('public.schedule_task_configs', 'id'), "
"COALESCE((SELECT MAX(id) FROM public.schedule_task_configs), 1), "
"true)"
)
)
def _get_or_create_schedule_task_config_model(task_id: int):
"""
获取或创建 ScheduleTaskConfig ORM,优先走 task.config 关系避免重复 pending INSERT。
核心逻辑:no_autoflush 下二次查库;新建前同步 PostgreSQL 序列。
Args:
task_id: schedule_tasks 主键。
Returns:
(ScheduleTask, ScheduleTaskConfig) 元组。
Raises:
ValueError: 排程任务不存在。
"""
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
task = db.session.get(ScheduleTask, task_id)
if task is None:
raise ValueError(f'Schedule task {task_id} not found')
cfg_model = task.config
if cfg_model is None:
with db.session.no_autoflush:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model is None:
_sync_postgres_serial_sequence('schedule_task_configs')
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
task.config = cfg_model
db.session.add(cfg_model)
return task, cfg_model
def upsert_schedule_task_config(
task_id: int,
data: dict[str, Any],
@@ -219,12 +283,8 @@ def upsert_schedule_task_config(
commit: bool = True,
) -> ScheduleSqlConfig:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if not cfg_model:
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
db.session.add(cfg_model)
_task, cfg_model = _get_or_create_schedule_task_config_model(task_id)
for k, v in data.items():
if k == "data_source" and isinstance(v, dict):
@@ -41,7 +41,7 @@ def create_shipping_batch_from_notice_items(
from app.core.errors import ValidationError
raise ValidationError(
"all uploaded files failed extraction or contained no parseable text",
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
details={"file_summary": file_summary or {}},
)
@@ -660,7 +660,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务。
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务;
含 schedule_run_id 时委托 finalize 终态化排程 run。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
@@ -748,13 +749,32 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
})
db.session.commit()
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
if schedule_run_id is not None:
from app.services.schedule.shipping_inventory_rpa_finalize import finalize_shipping_inventory_schedule_run
finalize_result = finalize_shipping_inventory_schedule_run(
schedule_run_id,
created=created,
failed=failed,
payload=payload,
)
response_data = {
"run_no": run_no,
"created": created,
"failed": failed,
"rpa_mode": payload.get("rpa_mode"),
"schedule_finalize_status": finalize_result.get("schedule_finalize_status"),
}
if finalize_result.get("error"):
response_data["schedule_finalize_error"] = finalize_result.get("error")
if finalize_result.get("manual_retryable"):
response_data["schedule_finalize_manual_retryable"] = True
return tool_response(
status="ok" if created else "failed",
message=f"批量库存回调完成:成功 {len(created)},失败 {len(failed)}",
data={
"run_no": run_no,
"created": created,
"failed": failed,
"rpa_mode": payload.get("rpa_mode"),
},
data=response_data,
)
@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_sources.py
用途:从 JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
依赖:Flask current_app、pathlib/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.json,不改 Python。
用途:从 YAML/JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
依赖:Flask current_app、pathlib、PyYAML/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.yaml,不改 Python。
"""
from __future__ import annotations
@@ -13,6 +13,7 @@ from copy import deepcopy
from pathlib import Path
from typing import Any
import yaml
from flask import current_app
_SITE_TO_SOURCE_TYPE = {
@@ -24,7 +25,7 @@ _CONFIG_CACHE: dict[str, Any] | None = None
class InventorySourceConfigError(ValueError):
"""库存源 JSON 配置校验失败。"""
"""库存源配置校验失败。"""
def _config_path() -> Path:
@@ -39,10 +40,34 @@ def _config_path() -> Path:
return path
from app.path_utils import resolve_backend_relative_path
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.json"
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.yaml"
return Path(resolve_backend_relative_path(None, default))
def _parse_config_payload(path: Path) -> dict[str, Any]:
"""
按文件后缀解析库存源配置(默认 YAML;测试夹具仍可用 .json)。
Raises:
InventorySourceConfigError: 后缀不支持或解析失败
"""
text = path.read_text(encoding="utf-8")
suffix = path.suffix.lower()
try:
if suffix in {".yaml", ".yml"}:
payload = yaml.safe_load(text)
elif suffix == ".json":
payload = json.loads(text)
else:
raise InventorySourceConfigError(
f"unsupported inventory sources config format: {path.suffix} (use .yaml, .yml, or .json)"
)
except (yaml.YAMLError, json.JSONDecodeError) as exc:
raise InventorySourceConfigError(f"failed to parse inventory sources config: {path}: {exc}") from exc
if not isinstance(payload, dict):
raise InventorySourceConfigError("inventory sources config root must be a mapping")
return payload
def _join_parameter_values(parameter: dict[str, Any]) -> str | None:
"""将 multi_text 参数值按 joiner 拼接为单字符串。"""
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
@@ -160,7 +185,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
"""加载并缓存 JSON 配置;force_reload 用于测试。"""
"""加载并缓存 YAML/JSON 配置;force_reload 用于测试。"""
global _CONFIG_CACHE
if _CONFIG_CACHE is not None and not force_reload:
return _CONFIG_CACHE
@@ -169,7 +194,7 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
if not path.is_file():
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
payload = json.loads(path.read_text(encoding="utf-8"))
payload = _parse_config_payload(path)
sources_raw = payload.get("sources")
if not isinstance(sources_raw, list):
raise InventorySourceConfigError("sources must be a list")
@@ -1,923 +0,0 @@
{
"version": 1,
"sources": [
{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"warehouse_code": "BYAWSATL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSATL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSATL01",
"ATL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSAVP01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSAVP01",
"warehouse_id": "BYAWSAVP01",
"warehouse_code": "BYAWSAVP01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSAVP01"
],
"required": true
}
],
"match_aliases": [
"BYAWSAVP01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSAZA01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSAZA01",
"warehouse_id": "BYAWSAZA01",
"warehouse_code": "BYAWSAZA01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSAZA01"
],
"required": true
}
],
"match_aliases": [
"BYAWSAZA01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSCMH01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSCMH01",
"warehouse_id": "BYAWSCMH01",
"warehouse_code": "BYAWSCMH01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSCMH01"
],
"required": true
}
],
"match_aliases": [
"BYAWSCMH01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSCMN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSCMN01",
"warehouse_id": "BYAWSCMN01",
"warehouse_code": "BYAWSCMN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSCMN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSCMN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSEZE01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSEZE01",
"warehouse_id": "BYAWSEZE01",
"warehouse_code": "BYAWSEZE01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSEZE01"
],
"required": true
}
],
"match_aliases": [
"BYAWSEZE01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSFRA01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSFRA01",
"warehouse_id": "BYAWSFRA01",
"warehouse_code": "BYAWSFRA01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSFRA01"
],
"required": true
}
],
"match_aliases": [
"BYAWSFRA01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSGRU01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSGRU01",
"warehouse_id": "BYAWSGRU01",
"warehouse_code": "BYAWSGRU01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSGRU01"
],
"required": true
}
],
"match_aliases": [
"BYAWSGRU01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSIAD01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSIAD01",
"warehouse_id": "BYAWSIAD01",
"warehouse_code": "BYAWSIAD01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSIAD01"
],
"required": true
}
],
"match_aliases": [
"BYAWSIAD01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSJAN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSJAN01",
"warehouse_id": "BYAWSJAN01",
"warehouse_code": "BYAWSJAN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSJAN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSJAN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSLTN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSLTN01",
"warehouse_id": "BYAWSLTN01",
"warehouse_code": "BYAWSLTN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSLTN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSLTN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSMEL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSMEL01",
"warehouse_id": "BYAWSMEL01",
"warehouse_code": "BYAWSMEL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSMEL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSMEL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSNRT01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSNRT01",
"warehouse_id": "BYAWSNRT01",
"warehouse_code": "BYAWSNRT01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSNRT01"
],
"required": true
}
],
"match_aliases": [
"BYAWSNRT01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPHX01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPHX01",
"warehouse_id": "BYAWSPHX01",
"warehouse_code": "BYAWSPHX01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPHX01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPHX01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPNE01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPNE01",
"warehouse_id": "BYAWSPNE01",
"warehouse_code": "BYAWSPNE01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPNE01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPNE01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPRD01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPRD01",
"warehouse_id": "BYAWSPRD01",
"warehouse_code": "BYAWSPRD01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPRD01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPRD01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSPSC01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSPSC01",
"warehouse_id": "BYAWSPSC01",
"warehouse_code": "BYAWSPSC01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSPSC01"
],
"required": true
}
],
"match_aliases": [
"BYAWSPSC01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSQRO01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSQRO01",
"warehouse_id": "BYAWSQRO01",
"warehouse_code": "BYAWSQRO01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSQRO01"
],
"required": true
}
],
"match_aliases": [
"BYAWSQRO01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRIC01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRIC01",
"warehouse_id": "BYAWSRIC01",
"warehouse_code": "BYAWSRIC01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRIC01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRIC01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRNO01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRNO01",
"warehouse_id": "BYAWSRNO01",
"warehouse_code": "BYAWSRNO01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRNO01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRNO01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSRUH01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSRUH01",
"warehouse_id": "BYAWSRUH01",
"warehouse_code": "BYAWSRUH01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSRUH01"
],
"required": true
}
],
"match_aliases": [
"BYAWSRUH01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSSBN01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSSBN01",
"warehouse_id": "BYAWSSBN01",
"warehouse_code": "BYAWSSBN01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSSBN01"
],
"required": true
}
],
"match_aliases": [
"BYAWSSBN01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSSCL01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSSCL01",
"warehouse_id": "BYAWSSCL01",
"warehouse_code": "BYAWSSCL01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSSCL01"
],
"required": true
}
],
"match_aliases": [
"BYAWSSCL01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSYYZ01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSYYZ01",
"warehouse_id": "BYAWSYYZ01",
"warehouse_code": "BYAWSYYZ01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSYYZ01"
],
"required": true
}
],
"match_aliases": [
"BYAWSYYZ01"
]
},
{
"source_code": "DSV360_AWSBI_BYAWSZAZ01",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSZAZ01",
"warehouse_id": "BYAWSZAZ01",
"warehouse_code": "BYAWSZAZ01",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Bison",
"program_label": "AWSBI",
"report_group": "Inventory",
"report_name": "On Hand Inventory By Location 3lv"
},
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"BYAWSZAZ01"
],
"required": true
}
],
"match_aliases": [
"BYAWSZAZ01"
]
},
{
"source_code": "DSV360_AWSCV",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Cincinnati / AWSCV",
"warehouse_id": "AWSCV",
"warehouse_code": "AWSCV",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Cincinnati",
"program_label": "AWSCV",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"CINCINNATI",
"CVG",
"AWSCV"
]
},
{
"source_code": "DSV360_AWSDU",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"warehouse_id": "AWSDU",
"warehouse_code": "AWSDU",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Dublin",
"program_label": "AWSDU - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CADU-0000000100"
],
"required": true
}
],
"match_aliases": [
"DBS DUB",
"DUB",
"DUBLIN"
]
},
{
"source_code": "DSV360_AWSAMS",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Moerdijk / AWSAMS",
"warehouse_id": "AWSAMS",
"warehouse_code": "AWSAMS",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Moerdijk",
"program_label": "AWSAMS",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CADU-0000000100"
],
"required": true
}
],
"match_aliases": [
"MOERDIJK",
"AMS",
"AWSAMS"
]
},
{
"source_code": "DSV360_AWSSL",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Salt Lake City / AWSSL",
"warehouse_id": "AWSSL",
"warehouse_code": "AWSSL",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Salt Lake City",
"program_label": "AWSSL",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"USLCK",
"SALT LAKE CITY",
"SALTLAKECITY"
]
},
{
"source_code": "DSV360_AWSSG",
"enabled": true,
"site": "dsv360",
"display_name": "DSV 360 / Singapore / AWSSG - Prod (JDA)",
"warehouse_id": "AWSSG",
"warehouse_code": "AWSSG",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {
"program_group": "Singapore",
"program_label": "AWSSG - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_DSV_OWNER_SELECTOR",
"mode": "single",
"values": [
"CACV-0000000100"
],
"required": true
}
],
"match_aliases": [
"SINGAPORE HUB",
"SINGAPORE",
"SG"
]
},
{
"source_code": "CRANE_TZR2",
"enabled": true,
"site": "crane_footprint",
"display_name": "Crane FootPrint / Warehouse TZR2",
"warehouse_id": "TZR2",
"warehouse_code": "TZR2",
"entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query",
"navigation": {
"report_name": "On Hand Details Query",
"download_mode": "file_download"
},
"parameters": [
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR",
"mode": "single",
"values": [
"0000000100"
],
"required": true
},
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR",
"mode": "single",
"values": [
"TZR2"
],
"required": true
}
],
"match_aliases": [
"TZR2",
"THAILAND"
]
}
]
}
@@ -0,0 +1,673 @@
# backend/config/shipping_inventory_sources.yaml
# 货代库存 RPA 源配置(新增 Warehouse 只改本文件,改后需重启后端)。
# 环境变量 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG 可覆盖路径。
version: 1
sources:
- source_code: DSV360_AWSBI_BYAWSATL01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSATL01
warehouse_id: BYAWSATL01
warehouse_code: BYAWSATL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSATL01
required: true
match_aliases:
- BYAWSATL01
- ATL01
- source_code: DSV360_AWSBI_BYAWSAVP01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01
warehouse_id: BYAWSAVP01
warehouse_code: BYAWSAVP01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAVP01
required: true
match_aliases:
- BYAWSAVP01
- source_code: DSV360_AWSBI_BYAWSAZA01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01
warehouse_id: BYAWSAZA01
warehouse_code: BYAWSAZA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAZA01
required: true
match_aliases:
- BYAWSAZA01
- source_code: DSV360_AWSBI_BYAWSCMH01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01
warehouse_id: BYAWSCMH01
warehouse_code: BYAWSCMH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMH01
required: true
match_aliases:
- BYAWSCMH01
- source_code: DSV360_AWSBI_BYAWSCMN01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01
warehouse_id: BYAWSCMN01
warehouse_code: BYAWSCMN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMN01
required: true
match_aliases:
- BYAWSCMN01
- source_code: DSV360_AWSBI_BYAWSEZE01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01
warehouse_id: BYAWSEZE01
warehouse_code: BYAWSEZE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSEZE01
required: true
match_aliases:
- BYAWSEZE01
- source_code: DSV360_AWSBI_BYAWSFRA01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01
warehouse_id: BYAWSFRA01
warehouse_code: BYAWSFRA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSFRA01
required: true
match_aliases:
- BYAWSFRA01
- source_code: DSV360_AWSBI_BYAWSGRU01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01
warehouse_id: BYAWSGRU01
warehouse_code: BYAWSGRU01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSGRU01
required: true
match_aliases:
- BYAWSGRU01
- source_code: DSV360_AWSBI_BYAWSIAD01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01
warehouse_id: BYAWSIAD01
warehouse_code: BYAWSIAD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSIAD01
required: true
match_aliases:
- BYAWSIAD01
- source_code: DSV360_AWSBI_BYAWSJAN01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01
warehouse_id: BYAWSJAN01
warehouse_code: BYAWSJAN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSJAN01
required: true
match_aliases:
- BYAWSJAN01
- source_code: DSV360_AWSBI_BYAWSLTN01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01
warehouse_id: BYAWSLTN01
warehouse_code: BYAWSLTN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSLTN01
required: true
match_aliases:
- BYAWSLTN01
- source_code: DSV360_AWSBI_BYAWSMEL01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01
warehouse_id: BYAWSMEL01
warehouse_code: BYAWSMEL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSMEL01
required: true
match_aliases:
- BYAWSMEL01
- source_code: DSV360_AWSBI_BYAWSNRT01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01
warehouse_id: BYAWSNRT01
warehouse_code: BYAWSNRT01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSNRT01
required: true
match_aliases:
- BYAWSNRT01
- source_code: DSV360_AWSBI_BYAWSPHX01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01
warehouse_id: BYAWSPHX01
warehouse_code: BYAWSPHX01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPHX01
required: true
match_aliases:
- BYAWSPHX01
- source_code: DSV360_AWSBI_BYAWSPNE01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01
warehouse_id: BYAWSPNE01
warehouse_code: BYAWSPNE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPNE01
required: true
match_aliases:
- BYAWSPNE01
- source_code: DSV360_AWSBI_BYAWSPRD01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01
warehouse_id: BYAWSPRD01
warehouse_code: BYAWSPRD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPRD01
required: true
match_aliases:
- BYAWSPRD01
- source_code: DSV360_AWSBI_BYAWSPSC01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01
warehouse_id: BYAWSPSC01
warehouse_code: BYAWSPSC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPSC01
required: true
match_aliases:
- BYAWSPSC01
- source_code: DSV360_AWSBI_BYAWSQRO01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01
warehouse_id: BYAWSQRO01
warehouse_code: BYAWSQRO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSQRO01
required: true
match_aliases:
- BYAWSQRO01
- source_code: DSV360_AWSBI_BYAWSRIC01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01
warehouse_id: BYAWSRIC01
warehouse_code: BYAWSRIC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRIC01
required: true
match_aliases:
- BYAWSRIC01
- source_code: DSV360_AWSBI_BYAWSRNO01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01
warehouse_id: BYAWSRNO01
warehouse_code: BYAWSRNO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRNO01
required: true
match_aliases:
- BYAWSRNO01
- source_code: DSV360_AWSBI_BYAWSRUH01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01
warehouse_id: BYAWSRUH01
warehouse_code: BYAWSRUH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRUH01
required: true
match_aliases:
- BYAWSRUH01
- source_code: DSV360_AWSBI_BYAWSSBN01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01
warehouse_id: BYAWSSBN01
warehouse_code: BYAWSSBN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSBN01
required: true
match_aliases:
- BYAWSSBN01
- source_code: DSV360_AWSBI_BYAWSSCL01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01
warehouse_id: BYAWSSCL01
warehouse_code: BYAWSSCL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSCL01
required: true
match_aliases:
- BYAWSSCL01
- source_code: DSV360_AWSBI_BYAWSYYZ01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01
warehouse_id: BYAWSYYZ01
warehouse_code: BYAWSYYZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSYYZ01
required: true
match_aliases:
- BYAWSYYZ01
- source_code: DSV360_AWSBI_BYAWSZAZ01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01
warehouse_id: BYAWSZAZ01
warehouse_code: BYAWSZAZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
program_label: AWSBI
report_group: Inventory
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSZAZ01
required: true
match_aliases:
- BYAWSZAZ01
- source_code: DSV360_AWSCV
enabled: true
site: dsv360
display_name: DSV 360 / Cincinnati / AWSCV
warehouse_id: AWSCV
warehouse_code: AWSCV
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Cincinnati
program_label: AWSCV
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- CINCINNATI
- CVG
- AWSCV
- source_code: DSV360_AWSDU
enabled: true
site: dsv360
display_name: DSV 360 / Dublin / AWSDU - Prod (JDA)
warehouse_id: AWSDU
warehouse_code: AWSDU
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Dublin
program_label: AWSDU - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CADU-0000000100
required: true
match_aliases:
- DBS DUB
- DUB
- DUBLIN
- source_code: DSV360_AWSAMS
enabled: true
site: dsv360
display_name: DSV 360 / Moerdijk / AWSAMS
warehouse_id: AWSAMS
warehouse_code: AWSAMS
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Moerdijk
program_label: AWSAMS
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CADU-0000000100
required: true
match_aliases:
- MOERDIJK
- AMS
- AWSAMS
- source_code: DSV360_AWSSL
enabled: true
site: dsv360
display_name: DSV 360 / Salt Lake City / AWSSL
warehouse_id: AWSSL
warehouse_code: AWSSL
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Salt Lake City
program_label: AWSSL
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- USLCK
- SALT LAKE CITY
- SALTLAKECITY
- source_code: DSV360_AWSSG
enabled: true
site: dsv360
display_name: DSV 360 / Singapore / AWSSG - Prod (JDA)
warehouse_id: AWSSG
warehouse_code: AWSSG
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Singapore
program_label: AWSSG - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- SINGAPORE HUB
- SINGAPORE
- SG
- source_code: CRANE_TZR2
enabled: true
site: crane_footprint
display_name: Crane FootPrint / Warehouse TZR2
warehouse_id: TZR2
warehouse_code: TZR2
entry_url: https://wms-portal.craneww.com/#/on-hand-details-query
navigation:
report_name: On Hand Details Query
download_mode: file_download
parameters:
- name: Owner
selector_env: FREIGHT_RPA_CRANE_OWNER_SELECTOR
mode: single
values:
- '0000000100'
required: true
- name: Warehouse
selector_env: FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR
mode: single
values:
- TZR2
required: true
match_aliases:
- TZR2
- THAILAND
@@ -0,0 +1,34 @@
"""resync schedule_task_configs id sequence
Revision ID: c0d1e2f3a4b5
Revises: b9c0d1e2f3a4
Create Date: 2026-07-08
用途:修复 schedule_task_configs 主键序列与 MAX(id) 漂移,避免 PATCH 新建 config 时主键冲突。
"""
from alembic import op
revision = 'c0d1e2f3a4b5'
down_revision = 'b9c0d1e2f3a4'
branch_labels = None
depends_on = None
def upgrade():
bind = op.get_bind()
if bind.dialect.name != 'postgresql':
return
op.execute(
"""
SELECT setval(
pg_get_serial_sequence('public.schedule_task_configs', 'id'),
COALESCE((SELECT MAX(id) FROM public.schedule_task_configs), 1),
true
)
"""
)
def downgrade():
pass
@@ -0,0 +1,25 @@
"""add schedule_tasks.job_params
Revision ID: d1e2f3a4b5c6
Revises: c0d1e2f3a4b5
Create Date: 2026-07-08
用途:platform_job 排程结构化参数列(按 job_registry.params_schema 校验后写入),
取代按任务硬编码复用 dify_agent_id / api_body_template 的旧参数通道。
"""
from alembic import op
import sqlalchemy as sa
revision = 'd1e2f3a4b5c6'
down_revision = 'c0d1e2f3a4b5'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_tasks', sa.Column('job_params', sa.JSON(), nullable=True))
def downgrade():
op.drop_column('schedule_tasks', 'job_params')
+45
View File
@@ -156,3 +156,48 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkeypatch, tmp_path):
"""multipart 上传发货通知时,agent_id 应从 form 字段解析,而非 JSON body。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
lambda **kwargs: {
"status": "ok",
"batch_no": "SB-MULTIPART-001",
"data": {
"tasks": [{"task_id": "SN-MULTIPART-001"}],
"focus_task": {"task_no": "SN-MULTIPART-001"},
},
},
)
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role},
data={
"agent_id": str(agent.id),
"input": json.dumps(
{
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {},
},
ensure_ascii=False,
),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
},
content_type="multipart/form-data",
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "run.completed" in event_names
assert "run.failed" not in event_names
+63 -2
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib.util
import json
import os
import sys
from pathlib import Path
import pytest
@@ -60,13 +61,73 @@ def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"htcus@hoo-thai.com"')
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "'secret-pass'")
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "htcus@hoo-thai.com"
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "user@example.com"
assert worker._env("FREIGHT_RPA_DSV_PASSWORD") == "secret-pass"
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "logs" / "worker.log"
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
original_stdout = sys.stdout
original_stderr = sys.stderr
try:
resolved = worker._configure_file_logging()
print("hello stdout")
print("hello stderr", file=sys.stderr)
finally:
sys.stdout.flush()
sys.stderr.flush()
sys.stdout = original_stdout
sys.stderr = original_stderr
captured = capsys.readouterr()
assert resolved == log_path
assert "hello stdout" in captured.out
assert "hello stderr" in captured.err
text = log_path.read_text(encoding="utf-8")
assert "[logging] tee enabled" in text
assert "hello stdout" in text
assert "hello stderr" in text
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 FREIGHT_RPA_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "2")
worker._rotate_log_file_if_needed(log_path)
assert not log_path.exists()
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
assert Path(f"{log_path}.2").read_text(encoding="utf-8") == "old-1"
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "0")
worker._rotate_log_file_if_needed(log_path)
assert not log_path.exists()
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
worker = _load_freight_rpa_worker()
+13 -1
View File
@@ -38,6 +38,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
db.session.commit()
run_no = run.run_no
task_id = task.id
run_id = run.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
@@ -46,9 +47,20 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
)
assert resp.status_code == 200
body = resp.get_json()
assert body["summary"]["success_count"] >= 1
assert body["summary"]["success_count"] == 0
assert body["summary"]["total_count"] >= 1
assert body.get("awaiting_rpa_callback") is True
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
with app.app_context():
from app import db
refreshed = db.session.get(ScheduleRun, run_id)
assert refreshed is not None
assert refreshed.status == "running"
assert refreshed.finished_at is None
assert (refreshed.response_summary_json or {}).get("awaiting_rpa") is True
def test_internal_job_unknown_key_returns_404(client):
"""未注册 job key 应返回 404。"""
+32
View File
@@ -154,3 +154,35 @@ def test_post_and_patch_schedule_reject_non_object_config(app, client, admin_jwt
'config': 'not-an-object',
})
assert patch_res.status_code == 400
def test_patch_schedule_creates_config_for_task_without_config(app, client, admin_jwt_headers):
"""PATCH 为尚无 config 的排程写入 config 应成功,不因主键序列漂移 500。"""
with app.app_context():
owner = _mk_user('cfg_create_owner_u', 'cfg_create_owner@example.com')
db.session.commit()
owner_id = owner.id
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'config-create-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 4 * * *',
})
assert create_res.status_code == 201
task_id = create_res.get_json()['id']
patch_res = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'config': {
'row_id_key': 'id',
'data_source': {'db_type': 'sqlserver'},
},
})
assert patch_res.status_code == 200
cfg_res = client.get(f'/api/admin/schedule-config/{task_id}', headers=admin_jwt_headers)
assert cfg_res.status_code == 200
cfg_body = cfg_res.get_json()
assert cfg_body['config'] is not None
assert cfg_body['config']['row_id_key'] == 'id'
+41 -13
View File
@@ -188,19 +188,47 @@ def test_common_executor_in_process_without_base_url(app, monkeypatch):
def test_get_platform_jobs_api(client, admin_jwt_headers):
"""GET /api/admin/schedule/platform-jobs 应返回 registry 列表及 label_key。"""
res = client.get("/api/admin/schedule/platform-jobs", headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
keys = {item["key"] for item in body}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert all("label" in item for item in body)
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
by_key = {item["key"]: item for item in body}
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
"""GET /api/admin/schedule/platform-jobs 应返回启用中的 registry 列表及 label_key。"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
# 临时注册 disabled job,验证下拉接口与 definitions 一样只返回 enabled
register_platform_job(PlatformJobDefinition(
key='disabled-for-filter-test',
label='disabled job',
handler=lambda task, run: (0, 0, 0, 0, [], [], []),
enabled=False,
))
try:
res = client.get("/api/admin/schedule/platform-jobs", headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
keys = {item["key"] for item in body}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert "disabled-for-filter-test" not in keys
assert all(item.get("enabled") is True for item in body)
assert all("label" in item for item in body)
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
by_key = {item["key"]: item for item in body}
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
assert defs.status_code == 200
def_keys = {item["task_type"] for item in defs.get_json()["data"]}
assert "disabled-for-filter-test" not in def_keys
# 两个接口的启用集合应对齐
assert keys == def_keys
finally:
# 清掉临时注册项,避免污染其他用例
from app.services.schedule import job_registry as jr
jr._REGISTRY.pop('disabled-for-filter-test', None)
assert get_platform_job('disabled-for-filter-test') is None
def test_schedule_config_rejects_data_source_type_for_platform_job(client, admin_jwt_headers, app):
@@ -0,0 +1,548 @@
"""
backend/tests/test_schedule_platform_tasks.py
用途:平台任务契约中心测试(definitions/options 接口、job_params schema 校验、handler 参数读取)。
依赖:conftest 的 app/client fixture、job_registry、job_params、job_options。
逻辑:覆盖 schema 下发、动态选项、保存期校验(必填/类型/未知字段/选项范围/_advanced)、
执行期回退(job_params 优先、legacy 字段兜底)。
"""
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ScheduleTask, User
from app.services.schedule.job_params import (
ADVANCED_PARAMS_KEY,
JobParamsValidationError,
validate_task_params,
)
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
# ---------- definitions / options 接口 ----------
def test_platform_task_definitions_returns_params_schema(client, admin_jwt_headers):
"""definitions 接口应下发注册表完整契约(task_type/label/params_schema/defaults)。"""
res = client.get('/api/admin/platform-tasks/definitions', headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
# 统一 envelope:success + data
assert body['success'] is True
by_type = {item['task_type']: item for item in body['data']}
# 货代库存 RPA:multi_select 库存源字段
rpa = by_type['shipping-inventory-rpa']
assert rpa['category'] == 'shipping'
schema_keys = {f['key']: f for f in rpa['params_schema']}
assert schema_keys['source_codes']['type'] == 'multi_select'
assert schema_keys['source_codes']['options_source'] == 'shipping_inventory_sources'
assert rpa['defaults'] == {'source_codes': []}
# FAQ 热点聚合:select 应用字段
faq = by_type['faq-aggregate-hot']
faq_fields = {f['key']: f for f in faq['params_schema']}
assert faq_fields['app_id']['type'] == 'select'
assert faq_fields['app_id']['options_source'] == 'agent_apps'
# 无参数任务 params_schema 为空列表
assert by_type['fixed-assets-snapshot']['params_schema'] == []
def test_platform_task_options_shipping_sources(client, admin_jwt_headers, app):
"""options 接口应返回库存源统一 label/value 结构。"""
res = client.get(
'/api/admin/platform-tasks/options?source=shipping_inventory_sources',
headers=admin_jwt_headers,
)
assert res.status_code == 200
body = res.get_json()
assert body['success'] is True
options = body['data']
assert options, 'expected at least one enabled inventory source'
assert all('label' in item and 'value' in item for item in options)
values = {item['value'] for item in options}
assert 'DSV360_AWSBI_BYAWSATL01' in values
def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers):
"""未登记的 options_source 应 400;缺 source 参数同样 400。"""
res = client.get('/api/admin/platform-tasks/options?source=not_a_source', headers=admin_jwt_headers)
assert res.status_code == 400
res2 = client.get('/api/admin/platform-tasks/options', headers=admin_jwt_headers)
assert res2.status_code == 400
# ---------- validate_task_params 校验 ----------
def test_validate_task_params_fills_defaults(app):
"""未提供字段应回填注册表默认值。"""
with app.app_context():
result = validate_task_params('shipping-inventory-rpa', {}, check_options=False)
assert result == {'source_codes': []}
result_faq = validate_task_params('faq-aggregate-hot', {}, check_options=False)
assert result_faq == {'app_id': None}
def test_validate_task_params_rejects_unknown_key(app):
"""未声明字段默认拒绝,防止参数漂移。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='unknown params'):
validate_task_params('faq-aggregate-hot', {'foo': 1}, check_options=False)
def test_validate_task_params_rejects_wrong_type(app):
"""multi_select 传入非 list 应报类型错误。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='list of option values'):
validate_task_params(
'shipping-inventory-rpa',
{'source_codes': 'DSV360_AWSBI_BYAWSATL01'},
check_options=False,
)
def test_validate_task_params_checks_option_range(app):
"""check_options=True 时,multi_select 值不在选项范围内应报错。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='not in options'):
validate_task_params(
'shipping-inventory-rpa',
{'source_codes': ['NOT_A_REAL_SOURCE']},
check_options=True,
)
# 合法值应通过
result = validate_task_params(
'shipping-inventory-rpa',
{'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
check_options=True,
)
assert result['source_codes'] == ['DSV360_AWSBI_BYAWSATL01']
def test_validate_task_params_passes_advanced_through(app):
"""_advanced 高级 JSON 区域应原样透传(历史/特殊任务兜底)。"""
with app.app_context():
result = validate_task_params(
'shipping-inventory-rpa',
{'source_codes': [], ADVANCED_PARAMS_KEY: {'timeout_seconds': 300}},
check_options=False,
)
assert result[ADVANCED_PARAMS_KEY] == {'timeout_seconds': 300}
def test_validate_task_params_unknown_job(app):
"""未注册任务直接报错。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='Unknown platform job'):
validate_task_params('not-a-job', {}, check_options=False)
# ---------- 保存排程时的 API 校验 ----------
def _create_platform_schedule(client, headers, owner_id, *, job_params=None, extra=None):
"""POST /schedules 创建 platform_job 排程的公共入口。"""
payload = {
'name': 'contract test',
'schedule_type': 'platform_job',
'platform_api_path': 'shipping-inventory-rpa',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
}
if job_params is not None:
payload['job_params'] = job_params
if extra:
payload.update(extra)
return client.post('/api/admin/schedules', headers=headers, json=payload)
@pytest.fixture
def owner_id(app):
"""普通用户作为排程 owner。"""
with app.app_context():
user = User(username='pt_owner', email='pt_owner@example.com')
db.session.add(user)
db.session.commit()
return user.id
def test_post_schedule_persists_valid_job_params(client, admin_jwt_headers, owner_id, app):
"""合法 job_params 应持久化并出现在 serialize_task 响应中。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
with app.app_context():
task = db.session.get(ScheduleTask, body['id'])
assert task.job_params == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
def test_post_schedule_without_job_params_applies_schema_defaults(client, admin_jwt_headers, owner_id, app):
"""platform_job 未传 job_params 时仍应按 schema 校验并回填默认值,不可绕过契约。"""
res = _create_platform_schedule(client, admin_jwt_headers, owner_id)
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] == {'source_codes': []}
with app.app_context():
task = db.session.get(ScheduleTask, body['id'])
assert task.job_params == {'source_codes': []}
def test_post_fixed_assets_snapshot_without_job_params_stays_none(client, admin_jwt_headers, owner_id, app):
"""无 params_schema 的 platform_job 仍允许 job_params 为 None。"""
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'fixed assets cron',
'schedule_type': 'platform_job',
'platform_api_path': 'fixed-assets-snapshot',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] is None
def test_post_schedule_rejects_invalid_job_params(client, admin_jwt_headers, owner_id):
"""非法 job_params(选项范围外 / 未知字段 / 非对象)应 400。"""
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['NOT_EXIST']},
).status_code == 400
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'unknown_field': 1},
).status_code == 400
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params=[1, 2],
).status_code == 400
def test_post_data_pipeline_rejects_job_params(client, admin_jwt_headers, owner_id):
"""data_pipeline 携带 job_params 应 400(参数契约仅属于平台任务)。"""
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'pipeline with job_params',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
'job_params': {'source_codes': []},
})
assert res.status_code == 400
def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""PATCH 应支持更新;显式 null 对有 schema 的任务重置为默认值。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'job_params': {'source_codes': []},
})
assert res2.status_code == 200
assert res2.get_json()['job_params'] == {'source_codes': []}
res3 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'job_params': None,
})
assert res3.status_code == 200
assert res3.get_json()['job_params'] == {'source_codes': []}
def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin_jwt_headers, owner_id, app):
"""切换 platform_api_path 且未传 job_params 时,应按新任务 schema 重置,避免旧参数残留。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'faq-aggregate-hot',
})
assert res2.status_code == 200
body = res2.get_json()
assert body['platform_api_path'] == 'faq-aggregate-hot'
assert body['job_params'] == {'app_id': None}
with app.app_context():
task = db.session.get(ScheduleTask, task_id)
assert task.job_params == {'app_id': None}
def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""切换到无 params_schema 的平台任务且未传 job_params 时应清空旧参数。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'fixed-assets-snapshot',
})
assert res2.status_code == 200
body = res2.get_json()
assert body['platform_api_path'] == 'fixed-assets-snapshot'
assert body['job_params'] is None
def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id):
"""切换 platform_api_path 同时显式传 job_params 时,应保留请求体参数(经新 schema 校验)。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'faq-aggregate-hot',
'job_params': {'app_id': None},
})
assert res2.status_code == 200
assert res2.get_json()['job_params'] == {'app_id': None}
# ---------- 执行链路参数读取 ----------
def test_faq_job_prefers_job_params_over_dify_agent_id(app):
"""FAQ handler 应优先读 job_params.app_id,历史任务回退 dify_agent_id。"""
from app.services.schedule.faq_hot_aggregate_job import _resolve_agent_filter
with app.app_context():
task = ScheduleTask(job_params={'app_id': 7}, dify_agent_id=3)
assert _resolve_agent_filter(task) == 7
legacy = ScheduleTask(job_params=None, dify_agent_id=3)
assert _resolve_agent_filter(legacy) == 3
empty = ScheduleTask(job_params={'app_id': None}, dify_agent_id=None)
assert _resolve_agent_filter(empty) is None
def test_shipping_rpa_filter_prefers_job_params(app):
"""货代 RPA 应优先按 job_params.source_codes 筛选库存源。"""
from app.services.schedule.shipping_inventory_rpa_job import _filter_sources
with app.app_context():
task = ScheduleTask(job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']})
sources = _filter_sources(task)
assert [item.get('source_code') for item in sources] == ['DSV360_AWSBI_BYAWSATL01']
# job_params 为空(默认值)时不筛选 → 返回全部启用源
task_all = ScheduleTask(job_params={'source_codes': []})
assert len(_filter_sources(task_all)) >= 1
def test_run_platform_job_writes_normalized_job_params(app):
"""执行前 validate_task_params 的归一化结果应写回 task.job_params 供 handler 读取。"""
from app.models import ScheduleRun
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
run_platform_job,
)
original = get_platform_job('faq-aggregate-hot')
seen: dict = {}
def _fake_handler(task, _run):
seen['params'] = dict(task.job_params)
return 0, 0, 0, 0, [], [], []
register_platform_job(PlatformJobDefinition(
key=original.key,
label=original.label,
handler=_fake_handler,
description=original.description,
label_key=original.label_key,
description_key=original.description_key,
category=original.category,
enabled=original.enabled,
params_schema=original.params_schema,
defaults=original.defaults,
))
try:
with app.app_context():
task = ScheduleTask(
schedule_no='SCH-NORM-001',
name='norm params',
schedule_type='platform_job',
platform_api_path='faq-aggregate-hot',
owner_user_id=1,
cron_expr='0 3 * * *',
job_params={},
)
run = ScheduleRun(run_no='RUN-NORM-001', schedule_task_id=1, status='running')
run_platform_job('faq-aggregate-hot', task, run, {})
assert seen['params'] == {'app_id': None}
assert task.job_params == {'app_id': None}
finally:
register_platform_job(original)
def test_disabled_platform_job_rejected_by_contract_and_run(app, client, admin_jwt_headers, owner_id):
"""enabled=False 表示任务停用:契约校验拒绝创建/改指向,执行入口也拒绝。"""
from app.models import ScheduleRun
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
run_platform_job,
)
from app.services.schedule.schedule_contract import validate_schedule_fields
register_platform_job(PlatformJobDefinition(
key='disabled-contract-job',
label='disabled contract job',
handler=lambda task, run: (0, 0, 0, 0, [], [], []),
enabled=False,
))
try:
with app.app_context():
with pytest.raises(ValueError, match='disabled'):
validate_schedule_fields(
schedule_type='platform_job',
data_source_type=None,
platform_api_path='disabled-contract-job',
)
task = ScheduleTask(
schedule_no='SCH-DIS-001',
name='disabled job run',
schedule_type='platform_job',
platform_api_path='disabled-contract-job',
owner_user_id=1,
cron_expr='0 3 * * *',
)
run = ScheduleRun(run_no='RUN-DIS-001', schedule_task_id=1, status='running')
with pytest.raises(ValueError, match='disabled'):
run_platform_job('disabled-contract-job', task, run, {})
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'create disabled job',
'schedule_type': 'platform_job',
'platform_api_path': 'disabled-contract-job',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 400
body = res.get_json() or {}
err = body.get('error')
msg = err.get('message') if isinstance(err, dict) else (err or body.get('message') or '')
assert 'disabled' in str(msg).lower()
finally:
from app.services.schedule import job_registry as jr
jr._REGISTRY.pop('disabled-contract-job', None)
assert get_platform_job('disabled-contract-job') is None
def test_platform_job_allows_config_respects_enabled(app):
"""
白名单 job 被 enabled=False 后,platform_job_allows_config 也应为 False,
避免 /schedule-config 继续写入已停用任务的 ScheduleTaskConfig。
"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
from app.services.schedule.schedule_contract import (
PLATFORM_JOBS_ALLOWING_CONFIG,
platform_job_allows_config,
)
# 选取一个已在白名单中的 key;若 registry 原本 enabled,临时改为 False
whitelist_key = next(iter(PLATFORM_JOBS_ALLOWING_CONFIG))
original = get_platform_job(whitelist_key)
assert original is not None, f'expected {whitelist_key} registered'
assert platform_job_allows_config(whitelist_key) is True
register_platform_job(PlatformJobDefinition(
key=whitelist_key,
label=original.label,
handler=original.handler,
enabled=False,
params_schema=list(original.params_schema or []),
defaults=dict(original.defaults or {}),
))
try:
with app.app_context():
assert platform_job_allows_config(whitelist_key) is False
with pytest.raises(ValueError, match='does not accept ScheduleTaskConfig'):
from app.services.schedule.schedule_contract import assert_schedule_config_writable
assert_schedule_config_writable(
schedule_type='platform_job',
platform_api_path=whitelist_key,
config={'fetch_sql': 'SELECT 1'},
)
finally:
register_platform_job(original)
assert platform_job_allows_config(whitelist_key) is True
def test_enable_rejects_disabled_platform_job(client, admin_jwt_headers, owner_id, app):
"""
既有 platform_job 排程在 registry job 被停用后,/enable 应拒绝重新入队。
避免 cron 到点才在运行阶段失败。
"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
job_key = 'shipping-inventory-rpa'
original = get_platform_job(job_key)
assert original is not None
res = _create_platform_schedule(client, admin_jwt_headers, owner_id)
assert res.status_code == 201
task_id = res.get_json()['id']
disable_res = client.post(f'/api/admin/schedules/{task_id}/disable', headers=admin_jwt_headers)
assert disable_res.status_code == 200
register_platform_job(PlatformJobDefinition(
key=job_key,
label=original.label,
handler=original.handler,
enabled=False,
params_schema=list(original.params_schema or []),
defaults=dict(original.defaults or {}),
))
try:
enable_res = client.post(f'/api/admin/schedules/{task_id}/enable', headers=admin_jwt_headers)
assert enable_res.status_code == 400
body = enable_res.get_json() or {}
err = body.get('error')
msg = err.get('message') if isinstance(err, dict) else (err or body.get('message') or '')
assert 'disabled' in str(msg).lower()
with app.app_context():
task = db.session.get(ScheduleTask, task_id)
assert task is not None
assert task.enabled is False
finally:
register_platform_job(original)
@@ -505,8 +505,8 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
assert res.status_code == 400
payload = res.get_json()
assert payload["success"] is False
assert payload["error"]["message"] == "all uploaded files failed extraction or contained no parseable text"
assert payload["error"]["details"]["rejected_files"] == [
assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试"
assert payload["error"]["details"]["file_summary"]["rejected_files"] == [
{
"filename": "notice-a.pdf",
"source_type": "pdf",
@@ -1,7 +1,71 @@
"""shipping_notice 库存 RPA 定时排程 executor 测试。"""
"""
backend/tests/test_shipping_notice_inventory_schedule.py
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
依赖:ScheduleTask/ScheduleRun、shipping_inventory_rpa_job、shipping_inventory_rpa_finalize。
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
"""
from datetime import datetime, timedelta
from app import db
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
from app.services.schedule.scheduler_service import run_task_now
from app.services.schedule.shipping_inventory_rpa_finalize import (
_build_finalize_details,
_compute_run_status,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule import reload_config, resolve_schedule_header
from app.services.schedule.shipping_inventory_rpa_job import (
_filter_sources,
run_shipping_inventory_rpa_schedule,
)
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
def _make_inventory_schedule_task(
*,
schedule_no: str,
username: str,
api_body_template: str | None = None,
) -> ScheduleTask:
"""
构造带/不带 api_body_template 的库存 RPA 排程任务。
Args:
schedule_no: 排程编号
username: 唯一用户名
api_body_template: 可选 JSON 文本
Returns:
已 flush 的 ScheduleTask
"""
user = User(username=username, email=f"{username}@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no=schedule_no,
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.flush()
if api_body_template is not None:
db.session.add(
ScheduleTaskConfig(
schedule_task_id=task.id,
api_body_template=api_body_template,
)
)
db.session.flush()
db.session.refresh(task)
return task
def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
@@ -11,23 +75,10 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
user = User(username="schedule_inv_user", email="schedule_inv_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
username="schedule_inv_user",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260707030000",
schedule_task_id=task.id,
@@ -38,6 +89,522 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
total, success, failed, skipped, details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
assert total >= 1
assert success >= 1
assert success == 0
assert failed == 0
assert skipped == 0
assert any(
isinstance(log, dict) and log.get("status") == "awaiting_rpa_callback"
for log in logs
)
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
assert any(item.get("source_code") for item in details)
def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-DEFER",
username="schedule_inv_defer_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
db.session.commit()
result = run_task_now(task, trigger_type="manual", triggered_by_user_id=None)
assert result.status == "running"
assert result.finished_at is None
assert result.success_count == 0
assert result.total_count == 1
assert (result.response_summary_json or {}).get("awaiting_rpa") is True
assert result.excel_file_data is None
def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-STARTED-AT",
username="schedule_inv_started_at_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080400",
schedule_task_id=task.id,
status="running",
started_at=None,
)
db.session.add(run)
db.session.commit()
run_task_now(task, trigger_type="manual", triggered_by_user_id=None, run=run)
db.session.refresh(run)
assert run.started_at is not None
assert run.status == "running"
recovered = recover_stale_awaiting_rpa_schedule_runs(task)
assert recovered == 0
def test_recover_all_stale_awaiting_on_startup(app):
"""全局回收应清理已超时的 awaiting run。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-GLOBAL-RECOVER",
username="schedule_inv_global_recover_user",
)
run = ScheduleRun(
run_no="RUN20260709080500",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
assert recovered == 1
db.session.refresh(run)
assert run.status == "failed"
def test_recover_all_skips_non_inventory_rpa_task(app):
"""全局回收不应误杀非货代库存 RPA 任务上复用 awaiting_rpa 的 run。"""
with app.app_context():
user = User(username="other_await_user", email="other_await@x.com")
db.session.add(user)
db.session.flush()
other_task = ScheduleTask(
schedule_no="SCH-OTHER-AWAIT",
name="other",
schedule_type="platform_job",
platform_api_path="faq-hot-aggregate",
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(other_task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260709080550",
schedule_task_id=other_task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "other", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
assert recovered == 0
db.session.refresh(run)
assert run.status == "running"
def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch):
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
def _excel_boom(*_args, **_kwargs):
raise RuntimeError("excel exploded")
monkeypatch.setattr(
"app.services.schedule.shipping_inventory_rpa_finalize.export_schedule_result_excel",
_excel_boom,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-EXCEL-FAIL",
username="schedule_inv_excel_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080700",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "partial_failed"
assert run.failed_count == 0
assert run.error_message
assert "Excel" in run.error_message
assert (run.response_summary_json or {}).get("excel_export_status") == "failed"
assert (run.response_summary_json or {}).get("excel_failed") is True
assert (run.response_summary_json or {}).get("rpa_finalize", {}).get("excel_failed") is True
assert not run.excel_file_data
def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeypatch):
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
monkeypatch.setattr(
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
_boom,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE-FAIL",
username="schedule_inv_finalize_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080600",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
result = rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "running"
assert (run.response_summary_json or {}).get("awaiting_rpa") is True
assert (run.response_summary_json or {}).get("schedule_finalize_status") == "failed"
assert result["data"]["schedule_finalize_status"] == "failed"
assert result["data"].get("schedule_finalize_manual_retryable") is True
def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
"""RPA 回调后应终态化排程 run 并生成 Excel。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
processed_dir = drop_dir / "processed"
processed_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE",
username="schedule_inv_finalize_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080000",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "success"
assert run.finished_at is not None
assert run.success_count == 1
assert run.failed_count == 0
assert run.excel_file_data
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
def test_recover_stale_awaiting_rpa_schedule_run(app):
"""超时 awaiting run 应回收为 failed,避免阻塞后续执行。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RECOVER",
username="schedule_inv_recover_user",
)
run = ScheduleRun(
run_no="RUN20260709080100",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_stale_awaiting_rpa_schedule_runs(task)
assert recovered == 1
db.session.refresh(run)
assert run.status == "failed"
assert run.finished_at is not None
assert "超时" in (run.error_message or "")
def test_compute_run_status_requires_all_sources_success():
"""触发 3 源仅 1 成功 0 失败时应 partial_failed,不能误标 success。"""
assert _compute_run_status(total_count=3, success_count=1, failed_count=0) == "partial_failed"
assert _compute_run_status(total_count=3, success_count=3, failed_count=0) == "success"
assert _compute_run_status(total_count=3, success_count=0, failed_count=3) == "failed"
def test_build_finalize_details_marks_missing_callback_as_failed():
"""未出现在回调结果中的 pending source 应补为 failed。"""
pending = [
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
{"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
]
details = _build_finalize_details(
pending,
created=[{"source_code": "SRC_A", "warehouse_id": "WH1", "inventory_file_no": "INV-1"}],
failed=[],
)
assert len(details) == 3
assert sum(1 for item in details if item.get("export_status") == "success") == 1
assert sum(1 for item in details if item.get("export_status") == "failed") == 2
missing = [item for item in details if item.get("error_message") == "RPA callback missing"]
assert len(missing) == 2
assert any(item.get("warehouse_id") == "WH2" for item in missing)
def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PARTIAL",
username="schedule_inv_partial_user",
)
run = ScheduleRun(
run_no="RUN20260709080200",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=3,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
{"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "SRC_A",
"warehouse_id": "WH1",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "partial_failed"
assert run.success_count == 1
assert run.failed_count == 2
def test_is_awaiting_rpa_schedule_run_helper(app):
"""awaiting RPA run 应被识别,普通 running 不应误判。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-AWAIT-FLAG",
username="schedule_inv_await_flag_user",
)
awaiting = ScheduleRun(
run_no="RUN20260709080300",
schedule_task_id=task.id,
status="running",
response_summary_json={"awaiting_rpa": True},
)
plain = ScheduleRun(
run_no="RUN20260709080301",
schedule_task_id=task.id,
status="running",
response_summary_json={},
)
db.session.add_all([awaiting, plain])
db.session.commit()
assert is_awaiting_rpa_schedule_run(awaiting) is True
assert is_awaiting_rpa_schedule_run(plain) is False
def test_inventory_rpa_excel_headers_survive_reload_config(app):
"""reload_config 后 shipping-inventory-rpa 表头仍应可用。"""
with app.app_context():
reload_config()
header_order, header_labels = resolve_schedule_header("shipping-inventory-rpa")
assert header_order
assert header_labels.get("inventory_file_no") == "库存快照号"
def test_filter_sources_by_source_codes(app):
"""推荐写法 source_codes 应精确筛到对应库存源。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-SRC",
username="schedule_inv_filter_src",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_warehouse_id(app):
"""兼容占位符常用的 warehouse_id(如 BYAWSATL01)。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-WH",
username="schedule_inv_filter_wh",
api_body_template='{"source_codes": ["BYAWSATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_match_aliases(app):
"""兼容误填 match_aliases 的历史排程参数。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-ALIAS",
username="schedule_inv_filter_alias",
api_body_template='{"match_aliases": ["ATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
@@ -1,4 +1,4 @@
"""shipping_notice inventory_sources JSON 配置加载与校验测试。"""
"""shipping_notice inventory_sources YAML/JSON 配置加载与校验测试。"""
from pathlib import Path
@@ -13,8 +13,8 @@ from app.services.shipping_notice.inventory_sources import (
)
def test_inventory_sources_json_loads(app):
"""默认 JSON 配置应成功加载并包含 DSV360_AWSDU。"""
def test_inventory_sources_yaml_loads(app):
"""默认 YAML 配置应成功加载并包含 DSV360_AWSDU。"""
with app.app_context():
reload_inventory_sources_config()
source = get_inventory_source("DSV360_AWSDU")