feat(schedule): 新增平台任务参数契约与动态选项支持
This commit is contained in:
1 parent
2ce1aca023
commit
8b5b0b49bf
76 files changed
+7103
-1203
No files matched your search
@@ -59,7 +59,7 @@ MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -68,7 +68,7 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.json
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
@@ -61,6 +61,19 @@ MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
# SHIPPING_NOTICE_TOOL_API_KEY=nsCL8xn3shu6u-5grXsd7jXlPzYcRrvLoaHnl9OMfE5nmuqNEsUah2n9uPGXEsy_
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -64,6 +64,8 @@ MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
# SHIPPING_NOTICE_TOOL_API_KEY=
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -72,7 +74,7 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.json
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
@@ -95,12 +97,11 @@ SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
@@ -120,4 +121,4 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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']
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
@@ -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')
|
||||
@@ -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
|
||||
@@ -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()
|
||||
|
||||
@@ -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。"""
|
||||
|
||||
@@ -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'
|
||||
@@ -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")
|
||||
|
||||
@@ -128,21 +128,472 @@ $env:FREIGHT_RPA_MOCK = "true"
|
||||
python scripts/rpa/freight_rpa_worker.py
|
||||
```
|
||||
|
||||
### 1.5 前端入口
|
||||
### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端)
|
||||
|
||||
> **安全提示**:本节示例中的 IP、账号名、密码、API Key 均为占位符(如 `请替换为...`、`your-tool-key`)。请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。
|
||||
|
||||
> 适用场景:HXOPS 后端运行在 Ubuntu,货代系统登录在 Linux 上不稳定;RPA 独立部署到一台可稳定登录 DSV/Crane 的 Windows 主机。\
|
||||
> 核心分工:Ubuntu 后端只写 trigger、接回调和入库;Windows RPA 主机只负责登录货代系统、下载库存 Excel、回调 HXOPS;两者通过 SMB 共享目录交换文件。
|
||||
|
||||
#### 1.5.1 路径规划
|
||||
|
||||
以下示例请替换成实际 IP、账号与路径:
|
||||
|
||||
```text
|
||||
Ubuntu HXOPS 后端主机 IP:192.168.1.20
|
||||
Windows RPA 主机 IP:192.168.100.165
|
||||
Windows 测试环境共享名:hxops-rpa-test-data
|
||||
Windows 正式环境共享名:hxops-rpa-prod-data
|
||||
Windows 测试环境本地目录:C:\HxopsRpaTest
|
||||
Windows 正式环境本地目录:C:\HxopsRpaProd
|
||||
Ubuntu 测试环境挂载目录:/mnt/hxops-rpa-test-data
|
||||
Ubuntu 正式环境挂载目录:/mnt/hxops-rpa-prod-data
|
||||
HXOPS 后端服务用户:hxops
|
||||
```
|
||||
|
||||
最终路径关系必须是一一对应:
|
||||
|
||||
```text
|
||||
测试环境:
|
||||
Windows RPA:C:\HxopsRpaTest\data\inventory_triggers
|
||||
Ubuntu 后端:/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
|
||||
Windows RPA:C:\HxopsRpaTest\data\inventory_drop
|
||||
Ubuntu 后端:/mnt/hxops-rpa-test-data/inventory_drop
|
||||
|
||||
正式环境:
|
||||
Windows RPA:C:\HxopsRpaProd\data\inventory_triggers
|
||||
Ubuntu 后端:/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
|
||||
Windows RPA:C:\HxopsRpaProd\data\inventory_drop
|
||||
Ubuntu 后端:/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
```
|
||||
|
||||
Ubuntu 后端写 Linux 挂载路径,Windows RPA worker 读 Windows 本地路径;二者实际指向同一个 SMB 共享目录。测试与正式必须使用不同目录、不同共享、不同挂载点、不同 worker 任务名,避免测试任务误消费正式 trigger。
|
||||
|
||||
#### 1.5.2 Windows RPA 主机:创建目录
|
||||
|
||||
在 Windows RPA 主机用 PowerShell 执行:
|
||||
|
||||
```powershell
|
||||
foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
|
||||
New-Item -ItemType Directory -Force $root
|
||||
New-Item -ItemType Directory -Force "$root\scripts\rpa"
|
||||
New-Item -ItemType Directory -Force "$root\backend\config"
|
||||
|
||||
New-Item -ItemType Directory -Force "$root\data\inventory_triggers"
|
||||
New-Item -ItemType Directory -Force "$root\data\inventory_drop"
|
||||
New-Item -ItemType Directory -Force "$root\data\upload_triggers"
|
||||
New-Item -ItemType Directory -Force "$root\data\upload_queue"
|
||||
New-Item -ItemType Directory -Force "$root\data\browser_profile"
|
||||
New-Item -ItemType Directory -Force "$root\data\logs"
|
||||
}
|
||||
```
|
||||
|
||||
从项目仓库复制以下文件到 Windows RPA 主机:
|
||||
|
||||
```text
|
||||
scripts\rpa\freight_rpa_worker.py
|
||||
scripts\rpa\dsv_report_parameters.py
|
||||
scripts\rpa\dsv_login_smoke.py
|
||||
scripts\rpa\dsv_export_smoke.py
|
||||
scripts\rpa\dsv_export_batch_smoke.py
|
||||
backend\config\shipping_inventory_sources.yaml
|
||||
```
|
||||
|
||||
放置为:
|
||||
|
||||
```text
|
||||
C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py
|
||||
C:\HxopsRpaTest\scripts\rpa\dsv_report_parameters.py
|
||||
C:\HxopsRpaTest\scripts\rpa\dsv_login_smoke.py
|
||||
C:\HxopsRpaTest\scripts\rpa\dsv_export_smoke.py
|
||||
C:\HxopsRpaTest\scripts\rpa\dsv_export_batch_smoke.py
|
||||
C:\HxopsRpaTest\backend\config\shipping_inventory_sources.yaml
|
||||
|
||||
C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py
|
||||
C:\HxopsRpaProd\scripts\rpa\dsv_report_parameters.py
|
||||
C:\HxopsRpaProd\scripts\rpa\dsv_login_smoke.py
|
||||
C:\HxopsRpaProd\scripts\rpa\dsv_export_smoke.py
|
||||
C:\HxopsRpaProd\scripts\rpa\dsv_export_batch_smoke.py
|
||||
C:\HxopsRpaProd\backend\config\shipping_inventory_sources.yaml
|
||||
```
|
||||
|
||||
不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。
|
||||
|
||||
#### 1.5.3 Windows RPA 主机:创建共享目录
|
||||
|
||||
建议单独创建共享账号,例如 `hxops_share`:
|
||||
|
||||
```powershell
|
||||
net user hxops_share "请替换为强密码" /add
|
||||
```
|
||||
|
||||
分别共享测试与正式 data 目录:
|
||||
|
||||
1. 右键 `C:\HxopsRpaTest\data` → 属性 → 共享 → 高级共享。
|
||||
2. 勾选“共享此文件夹”,共享名填写 `hxops-rpa-test-data`。
|
||||
3. 共享权限给 `hxops_share`:读取、更改、完全控制。
|
||||
4. “安全”选项卡也给 `hxops_share`:读取、写入、修改。
|
||||
5. 对 `C:\HxopsRpaProd\data` 重复以上步骤,共享名填写 `hxops-rpa-prod-data`。
|
||||
|
||||
Ubuntu 后端将通过下面的 SMB 地址访问:
|
||||
|
||||
```text
|
||||
//192.168.100.165/hxops-rpa-test-data
|
||||
//192.168.100.165/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
#### 1.5.4 Windows RPA 主机:安装 Python 与依赖
|
||||
|
||||
安装 Python 3.12,安装时勾选 `Add Python to PATH`。安装后检查:
|
||||
|
||||
```powershell
|
||||
python --version
|
||||
pip --version
|
||||
```
|
||||
|
||||
安装 RPA 依赖:
|
||||
|
||||
```powershell
|
||||
cd C:\HxopsRpaTest
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install playwright openpyxl pyyaml
|
||||
python -m playwright install chromium
|
||||
```
|
||||
|
||||
若使用本机 Edge 浏览器,worker 可配置 `FREIGHT_RPA_BROWSER_CHANNEL=msedge`。
|
||||
|
||||
#### 1.5.5 Windows RPA 主机:临时环境变量与登录测试
|
||||
|
||||
先在 PowerShell 当前窗口配置临时环境变量,确认链路可用后再改成永久环境变量:
|
||||
|
||||
```powershell
|
||||
cd C:\HxopsRpaTest
|
||||
|
||||
$env:HXOPS_API_BASE = "http://测试后端地址:端口"
|
||||
$env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOOL_API_KEY"
|
||||
|
||||
$env:FREIGHT_RPA_MOCK = "false"
|
||||
$env:FREIGHT_RPA_HEADLESS = "false"
|
||||
$env:FREIGHT_RPA_BROWSER_CHANNEL = "msedge"
|
||||
$env:FREIGHT_RPA_POLL_SECONDS = "3"
|
||||
|
||||
$env:FREIGHT_RPA_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers"
|
||||
$env:FREIGHT_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop"
|
||||
$env:FREIGHT_RPA_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers"
|
||||
$env:FREIGHT_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue"
|
||||
$env:FREIGHT_RPA_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile"
|
||||
$env:FREIGHT_RPA_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log"
|
||||
$env:FREIGHT_RPA_LOG_MAX_BYTES = "10485760"
|
||||
$env:FREIGHT_RPA_LOG_BACKUP_COUNT = "5"
|
||||
|
||||
$env:FREIGHT_RPA_DSV_USERNAME = "请替换为DSV账号"
|
||||
$env:FREIGHT_RPA_DSV_PASSWORD = "请替换为DSV密码"
|
||||
|
||||
# 如需 Crane:
|
||||
# $env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号"
|
||||
# $env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码"
|
||||
```
|
||||
|
||||
正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。
|
||||
|
||||
先验证 DSV 登录:
|
||||
|
||||
```powershell
|
||||
python scripts\rpa\dsv_login_smoke.py
|
||||
```
|
||||
|
||||
成功时会看到:
|
||||
|
||||
```text
|
||||
SUCCESS — DSV session ready
|
||||
```
|
||||
|
||||
再验证单个库存源导出:
|
||||
|
||||
```powershell
|
||||
python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSCMH01
|
||||
```
|
||||
|
||||
如果登录或导出失败,先排查 Windows 主机是否能手工打开 DSV/Crane、账号密码是否正确、是否需要 MFA/验证码/SSO、公司代理和证书是否正常。
|
||||
|
||||
#### 1.5.6 Ubuntu 后端主机:安装 SMB 工具并测试共享
|
||||
|
||||
Ubuntu 上安装工具:
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y cifs-utils smbclient
|
||||
```
|
||||
|
||||
测试能否看到 Windows 共享:
|
||||
|
||||
```bash
|
||||
smbclient -L //192.168.100.165 -U hxops_share
|
||||
```
|
||||
|
||||
能看到 `hxops-rpa-test-data` 和 `hxops-rpa-prod-data` 后,再进入共享:
|
||||
|
||||
```bash
|
||||
smbclient //192.168.100.165/hxops-rpa-test-data -U hxops_share
|
||||
smbclient //192.168.100.165/hxops-rpa-prod-data -U hxops_share
|
||||
```
|
||||
|
||||
输入 `ls`,应看到:
|
||||
|
||||
```text
|
||||
inventory_triggers
|
||||
inventory_drop
|
||||
upload_triggers
|
||||
upload_queue
|
||||
browser_profile
|
||||
logs
|
||||
```
|
||||
|
||||
#### 1.5.7 Ubuntu 后端主机:挂载 SMB 共享
|
||||
|
||||
创建挂载点和凭据文件:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /mnt/hxops-rpa-test-data
|
||||
sudo mkdir -p /mnt/hxops-rpa-prod-data
|
||||
sudo mkdir -p /etc/smbcredentials
|
||||
sudo nano /etc/smbcredentials/hxops-rpa
|
||||
```
|
||||
|
||||
凭据文件内容:
|
||||
|
||||
```ini
|
||||
username=hxops_share
|
||||
password=请替换为Windows共享密码
|
||||
domain=WORKGROUP
|
||||
```
|
||||
|
||||
如果使用域账号,`domain` 改为实际域名。保存后设置权限:
|
||||
|
||||
```bash
|
||||
sudo chmod 600 /etc/smbcredentials/hxops-rpa
|
||||
```
|
||||
|
||||
确认后端运行用户的 uid/gid:
|
||||
|
||||
```bash
|
||||
id hxops
|
||||
```
|
||||
|
||||
示例输出:
|
||||
|
||||
```text
|
||||
uid=1001(hxops) gid=1001(hxops)
|
||||
```
|
||||
|
||||
用实际 uid/gid 挂载,下面以 `1001` 举例:
|
||||
|
||||
```bash
|
||||
sudo mount -t cifs //192.168.100.165/hxops-rpa-test-data /mnt/hxops-rpa-test-data \
|
||||
-o credentials=/etc/smbcredentials/hxops-rpa,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0775,dir_mode=0775
|
||||
|
||||
sudo mount -t cifs //192.168.100.165/hxops-rpa-prod-data /mnt/hxops-rpa-prod-data \
|
||||
-o credentials=/etc/smbcredentials/hxops-rpa,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0775,dir_mode=0775
|
||||
```
|
||||
|
||||
检查目录:
|
||||
|
||||
```bash
|
||||
ls -la /mnt/hxops-rpa-test-data
|
||||
ls -la /mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
用后端服务用户测试写入:
|
||||
|
||||
```bash
|
||||
sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/ubuntu_write_test.txt
|
||||
sudo -u hxops rm /mnt/hxops-rpa-test-data/inventory_triggers/ubuntu_write_test.txt
|
||||
|
||||
sudo -u hxops touch /mnt/hxops-rpa-prod-data/inventory_triggers/ubuntu_write_test.txt
|
||||
sudo -u hxops rm /mnt/hxops-rpa-prod-data/inventory_triggers/ubuntu_write_test.txt
|
||||
```
|
||||
|
||||
测试文件应能分别在 Windows 的 `C:\HxopsRpaTest\data\inventory_triggers` 与 `C:\HxopsRpaProd\data\inventory_triggers` 中看到。
|
||||
|
||||
#### 1.5.8 Ubuntu 后端主机:开机自动挂载
|
||||
|
||||
编辑 `/etc/fstab`:
|
||||
|
||||
```bash
|
||||
sudo nano /etc/fstab
|
||||
```
|
||||
|
||||
追加一行,注意替换实际 IP、uid、gid:
|
||||
|
||||
```fstab
|
||||
//192.168.100.165/hxops-rpa-test-data /mnt/hxops-rpa-test-data cifs credentials=/etc/smbcredentials/hxops-rpa,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0775,dir_mode=0775,nofail,_netdev 0 0
|
||||
//192.168.100.165/hxops-rpa-prod-data /mnt/hxops-rpa-prod-data cifs credentials=/etc/smbcredentials/hxops-rpa,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0775,dir_mode=0775,nofail,_netdev 0 0
|
||||
```
|
||||
|
||||
测试:
|
||||
|
||||
```bash
|
||||
sudo umount /mnt/hxops-rpa-test-data
|
||||
sudo umount /mnt/hxops-rpa-prod-data
|
||||
sudo mount -a
|
||||
ls -la /mnt/hxops-rpa-test-data
|
||||
ls -la /mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
无报错且能看到共享目录,即自动挂载配置成功。
|
||||
|
||||
#### 1.5.9 Ubuntu 后端:配置 HXOPS 环境变量
|
||||
|
||||
Ubuntu 后端必须使用 Linux 挂载路径,不要写 Windows UNC 路径。测试环境配置示例:
|
||||
|
||||
```env
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=请替换为强随机ASCII密钥
|
||||
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
```
|
||||
|
||||
正式环境只把路径改为 `/mnt/hxops-rpa-prod-data/...`,并使用正式环境的 `SHIPPING_NOTICE_TOOL_API_KEY`。
|
||||
|
||||
重启后端:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart hxops-backend
|
||||
```
|
||||
|
||||
如果使用 Docker Compose,需把挂载目录映射进容器:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
|
||||
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
|
||||
```
|
||||
|
||||
容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。
|
||||
|
||||
#### 1.5.10 Windows RPA 主机:永久环境变量与自启动
|
||||
|
||||
手动验证通过后,可设置用户级永久环境变量:
|
||||
|
||||
```powershell
|
||||
[Environment]::SetEnvironmentVariable("HXOPS_API_BASE", "http://192.168.1.20:8890", "User")
|
||||
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_TOOL_API_KEY", "请替换为与后端一致的ASCII密钥", "User")
|
||||
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_MOCK", "false", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_HEADLESS", "false", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_BROWSER_CHANNEL", "msedge", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_POLL_SECONDS", "3", "User")
|
||||
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "C:\HxopsRpaTest\data\inventory_triggers", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_INVENTORY_DROP_DIR", "C:\HxopsRpaTest\data\inventory_drop", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "C:\HxopsRpaTest\data\upload_triggers", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_UPLOAD_QUEUE_DIR", "C:\HxopsRpaTest\data\upload_queue", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_BROWSER_PROFILE_DIR", "C:\HxopsRpaTest\data\browser_profile", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_FILE", "C:\HxopsRpaTest\data\logs\worker.log", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_MAX_BYTES", "10485760", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_BACKUP_COUNT", "5", "User")
|
||||
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_USERNAME", "请替换为DSV账号", "User")
|
||||
[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_PASSWORD", "请替换为DSV密码", "User")
|
||||
```
|
||||
|
||||
以上写法适合只常驻一个 worker。若同一台 Windows 主机要同时常驻测试与正式,建议不要依赖用户级环境变量,而是分别准备两个启动脚本或任务计划,确保每个任务内显式设置各自的目录、API Base 与 Key。
|
||||
|
||||
关闭并重新打开 PowerShell 后检查:
|
||||
|
||||
```powershell
|
||||
echo $env:HXOPS_API_BASE
|
||||
echo $env:FREIGHT_RPA_INVENTORY_TRIGGER_DIR
|
||||
```
|
||||
|
||||
确认 worker 可手动启动:
|
||||
|
||||
```powershell
|
||||
cd C:\HxopsRpaTest
|
||||
python scripts\rpa\freight_rpa_worker.py
|
||||
```
|
||||
|
||||
启动后应看到 `[logging] tee enabled path=...`;日志会同时写入 `C:\HxopsRpaTest\data\logs\worker.log`。正式环境建议配置为 `C:\HxopsRpaProd\data\logs\worker.log`。
|
||||
|
||||
日志默认按大小轮转,避免单个文件长期膨胀:
|
||||
|
||||
```text
|
||||
FREIGHT_RPA_LOG_MAX_BYTES=10485760 # 单个 worker.log 最大 10MB;设为 0 可禁用轮转
|
||||
FREIGHT_RPA_LOG_BACKUP_COUNT=5 # 最多保留 worker.log.1 到 worker.log.5
|
||||
```
|
||||
|
||||
确认可用后再创建任务计划。先查 Python 路径:
|
||||
|
||||
```powershell
|
||||
where python
|
||||
```
|
||||
|
||||
用实际 Python 路径创建登录后自启动任务;可见浏览器模式建议优先用 `AtLogOn`:
|
||||
|
||||
```powershell
|
||||
$Action = New-ScheduledTaskAction `
|
||||
-Execute "C:\Users\rpa\AppData\Local\Programs\Python\Python312\python.exe" `
|
||||
-Argument "C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py" `
|
||||
-WorkingDirectory "C:\HxopsRpaTest"
|
||||
|
||||
$Trigger = New-ScheduledTaskTrigger -AtLogOn
|
||||
|
||||
Register-ScheduledTask `
|
||||
-TaskName "HXOPS Inventory RPA Worker TEST" `
|
||||
-Action $Action `
|
||||
-Trigger $Trigger `
|
||||
-Description "HXOPS inventory export RPA worker TEST"
|
||||
```
|
||||
|
||||
正式环境任务计划使用 `C:\HxopsRpaProd`,任务名建议为 `HXOPS Inventory RPA Worker PROD`。
|
||||
|
||||
#### 1.5.11 端到端验证
|
||||
|
||||
1. Windows 手工打开 Edge,确认能访问 DSV/Crane。
|
||||
2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。
|
||||
3. Windows 执行 `python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01`。
|
||||
4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。
|
||||
5. Windows 启动 `python scripts\rpa\freight_rpa_worker.py`。
|
||||
6. HXOPS 页面或排程触发库存 RPA 导出。
|
||||
7. Ubuntu 查看 trigger:`ls -lt /mnt/hxops-rpa-test-data/inventory_triggers`。
|
||||
8. Windows 查看 worker 输出;成功后 trigger 会进入 `C:\HxopsRpaTest\data\inventory_triggers\processed`。
|
||||
9. Excel 会落到 `C:\HxopsRpaTest\data\inventory_drop`,随后由后端回调流程入库为库存快照。
|
||||
10. HXOPS 任务应进入库存字段映射/库存匹配阶段;定时排程 run 应由 `awaiting_rpa_callback` 终态化为 `success` / `failed` / `partial_failed`。
|
||||
|
||||
#### 1.5.12 常见问题
|
||||
|
||||
- Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。
|
||||
- Windows worker 没反应:确认 worker 正在运行,测试环境 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\inventory_triggers`,正式环境指向 `C:\HxopsRpaProd\data\inventory_triggers`,且后端真的把 JSON 写到了对应共享目录。
|
||||
- worker 回调失败:确认 Windows 能访问 `HXOPS_API_BASE`,`SHIPPING_NOTICE_TOOL_API_KEY` 与后端一致,Ubuntu 防火墙允许 Windows 访问 HXOPS 端口。
|
||||
- DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。
|
||||
- Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。
|
||||
- 排程一直 running:检查对应环境的 `/mnt/hxops-rpa-*-data/inventory_triggers/processed` 是否有对应 trigger、worker 日志是否回调 `/api/shipping-notice/rpa/inventory-batch-ready` 成功。
|
||||
|
||||
### 1.6 前端入口
|
||||
|
||||
- 聊天界面仍是**主上传入口**,通知附件、库存附件与对话续办都优先在 Chat 完成
|
||||
- 聊天页右侧**轻量批次工作台**允许执行当前任务动作,但业务按钮必须直接消费后端 `ui_state.action_buttons`,禁止前端按 `process_status / pending_human_reason` 本地二次推导
|
||||
- 独立工作台入口 **货代发货** 仍以只读查看、筛选排查与跳转聊天界面为主,不单独维护第二套业务动作口径
|
||||
- **在 Chat 中继续** → `/chat/{agentId}?task_id=SN-...`
|
||||
|
||||
### 1.6 端到端验证
|
||||
### 1.7 端到端验证
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_service.py tests/test_shipping_notice_batches.py -q
|
||||
```
|
||||
|
||||
### 1.7 待业务提供
|
||||
### 1.8 待业务提供
|
||||
|
||||
- 货代系统库存导出 SOP + 样例 Excel 列名
|
||||
- 货代上传 SOP + 正式上传模板列映射
|
||||
@@ -2729,7 +3180,7 @@ API 层
|
||||
| `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 |
|
||||
| `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 |
|
||||
| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) |
|
||||
| `backend/config/shipping_inventory_sources.json` | 库存 RPA 源配置(新增 Warehouse 只改此 JSON) |
|
||||
| `backend/config/shipping_inventory_sources.yaml` | 库存 RPA 源配置(新增 Warehouse 只改此 YAML) |
|
||||
| `seed_shipping_notice_agents.py` | Agent 注册脚本 |
|
||||
|
||||
---
|
||||
@@ -2738,8 +3189,8 @@ API 层
|
||||
|
||||
### 5.1 配置文件
|
||||
|
||||
- 路径:`backend/config/shipping_inventory_sources.json`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`)
|
||||
- **新增 Warehouse 只改 JSON**,不改 Python;字段含 `source_code`、`site`(`dsv360` / `crane_footprint`)、`warehouse_id`、`navigation`、`parameters`、`match_aliases`
|
||||
- 路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`)
|
||||
- **新增 Warehouse 只改 YAML**,不改 Python;字段含 `source_code`、`site`(`dsv360` / `crane_footprint`)、`warehouse_id`、`navigation`、`parameters`、`match_aliases`
|
||||
- 环境变量:
|
||||
- `SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS`(默认 24)
|
||||
- `SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED`(默认 true)
|
||||
@@ -2768,3 +3219,4 @@ API 层
|
||||
|
||||
- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`
|
||||
- `shipping_task_inventory_links`:`link_reason`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`
|
||||
|
||||
+12
-1
@@ -56,12 +56,23 @@
|
||||
| --- | --- | --- |
|
||||
| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) |
|
||||
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
|
||||
| 库存 RPA 源 JSON 配置 | 已实现 | `backend/config/shipping_inventory_sources.json`,新增 Warehouse 只改 JSON |
|
||||
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
|
||||
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
|
||||
| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` |
|
||||
| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` |
|
||||
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
|
||||
|
||||
### 排程平台任务契约中心(schedule)
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 平台任务注册表升级 | 已实现 | `job_registry.PlatformJobDefinition` 补 `category / params_schema / defaults`,注册表即任务契约中心 |
|
||||
| 任务定义接口 | 已实现 | `GET /api/admin/platform-tasks/definitions` 下发完整契约(含 params_schema) |
|
||||
| 动态选项接口 | 已实现 | `GET /api/admin/platform-tasks/options?source=...`;已支持 `agent_apps`、`shipping_inventory_sources` |
|
||||
| job_params 统一校验 | 已实现 | `job_params.validate_task_params`:保存与执行前各校验一次;未声明字段拒绝,`_advanced` 例外透传 |
|
||||
| 结构化参数存储 | 已实现 | `schedule_tasks.job_params`(JSON),迁移 `d1e2f3a4b5c6`;FAQ/RPA handler 优先读取并回退旧字段 |
|
||||
| 前端通用参数表单 | 已实现 | `DynamicTaskParamsForm.vue` 按 schema 渲染 + 折叠高级 JSON,编辑弹窗移除任务级 v-if |
|
||||
|
||||
### Agent 应用管理(platform)
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -44,6 +44,49 @@ export interface PlatformJobOption {
|
||||
export const listAdminPlatformJobs = () =>
|
||||
getJson<PlatformJobOption[]>('/api/admin/schedule/platform-jobs');
|
||||
|
||||
/** 平台任务参数 schema 字段(DynamicTaskParamsForm 按 type 通用渲染) */
|
||||
export interface PlatformTaskParamField {
|
||||
key: string;
|
||||
type:
|
||||
| 'text' | 'textarea' | 'number' | 'boolean'
|
||||
| 'select' | 'multi_select'
|
||||
| 'date' | 'datetime' | 'cron' | 'json' | 'info';
|
||||
label: string;
|
||||
label_key?: string | null;
|
||||
required?: boolean;
|
||||
default?: any;
|
||||
options_source?: string | null;
|
||||
placeholder?: string;
|
||||
placeholder_key?: string | null;
|
||||
help?: string;
|
||||
help_key?: string | null;
|
||||
}
|
||||
|
||||
/** 平台任务完整契约(注册表下发:展示信息 + params_schema + defaults) */
|
||||
export interface PlatformTaskDefinition {
|
||||
task_type: string;
|
||||
label: string;
|
||||
label_key?: string | null;
|
||||
description?: string;
|
||||
description_key?: string | null;
|
||||
category?: string;
|
||||
params_schema: PlatformTaskParamField[];
|
||||
defaults: Record<string, any>;
|
||||
}
|
||||
|
||||
/** options_source 动态选项统一结构 */
|
||||
export interface PlatformTaskOption {
|
||||
label: string;
|
||||
value: string | number;
|
||||
description?: string | null;
|
||||
}
|
||||
|
||||
export const listAdminPlatformTaskDefinitions = () =>
|
||||
getJson<PlatformTaskDefinition[]>('/api/admin/platform-tasks/definitions');
|
||||
|
||||
export const listAdminPlatformTaskOptions = (source: string) =>
|
||||
getJson<PlatformTaskOption[]>(`/api/admin/platform-tasks/options?source=${encodeURIComponent(source)}`);
|
||||
|
||||
export const getAdminScheduleTaskConfig = (taskId: number) =>
|
||||
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
|
||||
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/schedules/components/DynamicTaskParamsForm.vue
|
||||
* 用途:平台任务参数通用表单——按注册表 params_schema 渲染控件并输出统一 job_params。
|
||||
* 依赖:schedule.api(PlatformTaskDefinition/listAdminPlatformTaskOptions)、vue-i18n。
|
||||
* 逻辑:ScheduleCreateEditModal 传入选中任务的 definition;本组件只认识控件 type 与
|
||||
* options_source,不认识具体任务(红框参数区完全由 schema 决定);
|
||||
* 高级配置折叠 JSON 与 schema type=json 字段均本地校验,非法时 emit valid=false 阻止保存;
|
||||
* modelValue 异步回填时同步 _advanced / json 文本(用户已编辑时不覆盖)。
|
||||
*/
|
||||
import { computed, reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
listAdminPlatformTaskOptions,
|
||||
type PlatformTaskDefinition,
|
||||
type PlatformTaskOption,
|
||||
type PlatformTaskParamField,
|
||||
} from '@/features/admin/api/schedule.api';
|
||||
|
||||
const props = defineProps<{
|
||||
definition: PlatformTaskDefinition;
|
||||
modelValue: Record<string, any> | null;
|
||||
valid?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: Record<string, any> | null): void;
|
||||
(e: 'update:valid', value: boolean): void;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/** options_source → 选项列表缓存(组件生命周期内共享,避免重复请求) */
|
||||
const optionsCache = reactive<Record<string, PlatformTaskOption[]>>({});
|
||||
const optionsLoading = reactive<Record<string, boolean>>({});
|
||||
|
||||
const advancedJsonText = ref('');
|
||||
const advancedJsonError = ref(false);
|
||||
/** schema type=json 字段的本地文本与非法标记(key → text/error) */
|
||||
const jsonFieldTexts = reactive<Record<string, string>>({});
|
||||
const jsonFieldErrors = reactive<Record<string, boolean>>({});
|
||||
|
||||
/** 向父级同步表单合法性(高级 JSON 或 schema json 字段非法时为 false,阻止保存)。 */
|
||||
const syncValid = (): void => {
|
||||
const jsonFieldsInvalid = Object.values(jsonFieldErrors).some(Boolean);
|
||||
emit('update:valid', !advancedJsonError.value && !jsonFieldsInvalid);
|
||||
};
|
||||
|
||||
/**
|
||||
* 将当前值格式化为 json 字段 textarea 文本。
|
||||
* @param value - job_params 中该字段的现值
|
||||
*/
|
||||
const formatJsonFieldText = (value: unknown): string => {
|
||||
if (value === null || value === undefined || value === '') return '';
|
||||
if (typeof value === 'string') return value;
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验 schema type=json 字段:空允许;非空须为可 JSON.parse 的文本(与后端一致)。
|
||||
* 合法时解析后写入 job_params,非法时只标记错误不 emit 坏值。
|
||||
*/
|
||||
const handleJsonFieldInput = (key: string, rawText: string): void => {
|
||||
jsonFieldTexts[key] = rawText;
|
||||
const text = rawText.trim();
|
||||
if (!text) {
|
||||
jsonFieldErrors[key] = false;
|
||||
setField(key, null);
|
||||
syncValid();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
jsonFieldErrors[key] = false;
|
||||
setField(key, parsed);
|
||||
} catch {
|
||||
jsonFieldErrors[key] = true;
|
||||
}
|
||||
syncValid();
|
||||
};
|
||||
|
||||
/**
|
||||
* i18n key 优先解析文案:te(key) 命中用 $t(key),否则回退注册表内置中文。
|
||||
* @param key - schema 下发的 i18n key(可空)
|
||||
* @param fallback - 注册表中文 fallback
|
||||
*/
|
||||
const resolveText = (key: string | null | undefined, fallback: string | undefined): string => {
|
||||
if (key && te(key)) return t(key);
|
||||
return fallback || '';
|
||||
};
|
||||
|
||||
const schemaFields = computed<PlatformTaskParamField[]>(
|
||||
() => props.definition.params_schema || [],
|
||||
);
|
||||
|
||||
const descriptionText = computed(() =>
|
||||
resolveText(props.definition.description_key, props.definition.description),
|
||||
);
|
||||
|
||||
/**
|
||||
* 当前 job_params 值(保证非空对象,方便字段读写)。
|
||||
*/
|
||||
const params = computed<Record<string, any>>(() => props.modelValue || {});
|
||||
|
||||
/**
|
||||
* 更新单个字段值并向外发出完整 job_params。
|
||||
* 核心逻辑:以 defaults 为底、合并现值与新值,保证输出结构稳定。
|
||||
*/
|
||||
const setField = (key: string, value: any): void => {
|
||||
emit('update:modelValue', {
|
||||
...(props.definition.defaults || {}),
|
||||
...params.value,
|
||||
[key]: value,
|
||||
});
|
||||
};
|
||||
|
||||
/** 拉取并缓存某个 options_source 的动态选项。 */
|
||||
const loadOptions = async (source: string): Promise<void> => {
|
||||
if (optionsCache[source] || optionsLoading[source]) return;
|
||||
optionsLoading[source] = true;
|
||||
try {
|
||||
optionsCache[source] = await listAdminPlatformTaskOptions(source);
|
||||
} catch (e) {
|
||||
console.error(`Failed to load options for ${source}`, e);
|
||||
optionsCache[source] = [];
|
||||
} finally {
|
||||
optionsLoading[source] = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** multi_select 勾选切换。 */
|
||||
const toggleMultiValue = (key: string, value: string | number): void => {
|
||||
const current: Array<string | number> = Array.isArray(params.value[key]) ? [...params.value[key]] : [];
|
||||
const idx = current.indexOf(value);
|
||||
if (idx >= 0) current.splice(idx, 1);
|
||||
else current.push(value);
|
||||
setField(key, current);
|
||||
};
|
||||
|
||||
/**
|
||||
* 高级 JSON 文本变更:合法时写入 _advanced,空文本移除该键。
|
||||
*/
|
||||
const handleAdvancedInput = (): void => {
|
||||
const text = advancedJsonText.value.trim();
|
||||
if (!text) {
|
||||
advancedJsonError.value = false;
|
||||
const next = { ...(props.modelValue || {}) };
|
||||
delete next._advanced;
|
||||
emit('update:modelValue', Object.keys(next).length ? next : null);
|
||||
syncValid();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not object');
|
||||
advancedJsonError.value = false;
|
||||
setField('_advanced', parsed);
|
||||
} catch {
|
||||
advancedJsonError.value = true;
|
||||
}
|
||||
syncValid();
|
||||
};
|
||||
|
||||
// 任务切换时:预加载动态选项、回填 _advanced / json 字段文本
|
||||
watch(
|
||||
() => props.definition.task_type,
|
||||
() => {
|
||||
Object.keys(jsonFieldTexts).forEach((k) => delete jsonFieldTexts[k]);
|
||||
Object.keys(jsonFieldErrors).forEach((k) => delete jsonFieldErrors[k]);
|
||||
schemaFields.value.forEach((field) => {
|
||||
if (field.options_source && (field.type === 'select' || field.type === 'multi_select')) {
|
||||
void loadOptions(field.options_source);
|
||||
}
|
||||
if (field.type === 'json') {
|
||||
jsonFieldTexts[field.key] = formatJsonFieldText(params.value[field.key]);
|
||||
jsonFieldErrors[field.key] = false;
|
||||
}
|
||||
});
|
||||
const advanced = (props.modelValue || {})._advanced;
|
||||
advancedJsonText.value = advanced ? JSON.stringify(advanced, null, 2) : '';
|
||||
advancedJsonError.value = false;
|
||||
syncValid();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// 编辑回填异步到达时同步 _advanced 文本(用户正在编辑且已有文本时不覆盖)
|
||||
watch(
|
||||
() => props.modelValue?._advanced,
|
||||
(advanced) => {
|
||||
if (advancedJsonText.value.trim() || !advanced) return;
|
||||
advancedJsonText.value = JSON.stringify(advanced, null, 2);
|
||||
},
|
||||
);
|
||||
|
||||
// 编辑回填异步到达时同步 schema type=json 字段文本(task_type 未变时也要跟上)
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(value) => {
|
||||
schemaFields.value.forEach((field) => {
|
||||
if (field.type !== 'json') return;
|
||||
// 用户已输入或校验中:不覆盖本地 textarea
|
||||
if ((jsonFieldTexts[field.key] || '').trim() || jsonFieldErrors[field.key]) return;
|
||||
const incoming = value?.[field.key];
|
||||
if (incoming === undefined || incoming === null || incoming === '') return;
|
||||
jsonFieldTexts[field.key] = formatJsonFieldText(incoming);
|
||||
jsonFieldErrors[field.key] = false;
|
||||
});
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl border border-blue-200 bg-blue-50/40 p-4 space-y-3">
|
||||
<!-- 任务说明块(schema 之外的任务级描述) -->
|
||||
<p v-if="descriptionText" class="text-sm text-blue-900">{{ descriptionText }}</p>
|
||||
|
||||
<div v-for="field in schemaFields" :key="field.key">
|
||||
<!-- info:纯说明块 -->
|
||||
<p v-if="field.type === 'info'" class="text-xs text-muted">
|
||||
{{ resolveText(field.help_key, field.help) || resolveText(field.label_key, field.label) }}
|
||||
</p>
|
||||
|
||||
<template v-else>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">
|
||||
{{ resolveText(field.label_key, field.label) }}
|
||||
<span v-if="field.required" class="text-rose-500">*</span>
|
||||
</label>
|
||||
|
||||
<!-- text / cron / date / datetime -->
|
||||
<input
|
||||
v-if="field.type === 'text' || field.type === 'cron'"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
:class="field.type === 'cron' ? 'font-mono' : ''"
|
||||
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<input
|
||||
v-else-if="field.type === 'date'"
|
||||
type="date"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<input
|
||||
v-else-if="field.type === 'datetime'"
|
||||
type="datetime-local"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
|
||||
<!-- number -->
|
||||
<input
|
||||
v-else-if="field.type === 'number'"
|
||||
type="number"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value))"
|
||||
/>
|
||||
|
||||
<!-- boolean -->
|
||||
<label v-else-if="field.type === 'boolean'" class="inline-flex items-center gap-2 text-sm text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded text-blue-600"
|
||||
:checked="!!params[field.key]"
|
||||
@change="setField(field.key, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ resolveText(field.placeholder_key, field.placeholder) }}
|
||||
</label>
|
||||
|
||||
<!-- textarea -->
|
||||
<textarea
|
||||
v-else-if="field.type === 'textarea'"
|
||||
:value="typeof params[field.key] === 'string' ? params[field.key] : (params[field.key] ? String(params[field.key]) : '')"
|
||||
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
|
||||
:placeholder="resolveText(field.placeholder_key, field.placeholder)"
|
||||
@input="setField(field.key, ($event.target as HTMLTextAreaElement).value)"
|
||||
></textarea>
|
||||
|
||||
<!-- json:本地解析,非法时阻止保存 -->
|
||||
<div v-else-if="field.type === 'json'" class="space-y-1">
|
||||
<textarea
|
||||
:value="jsonFieldTexts[field.key] ?? ''"
|
||||
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
|
||||
:class="jsonFieldErrors[field.key] ? 'border-red-400 focus:border-red-500' : ''"
|
||||
:placeholder="resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsAdvancedPlaceholder')"
|
||||
@input="handleJsonFieldInput(field.key, ($event.target as HTMLTextAreaElement).value)"
|
||||
></textarea>
|
||||
<p v-if="jsonFieldErrors[field.key]" class="text-xs text-red-600">
|
||||
{{ $t('admin.schedule.form.dynamicParamsJsonInvalid') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- select(单选,动态选项) -->
|
||||
<select
|
||||
v-else-if="field.type === 'select'"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
@change="setField(field.key, ($event.target as HTMLSelectElement).value === '' ? null : (optionsCache[field.options_source || '']?.find((o) => String(o.value) === ($event.target as HTMLSelectElement).value)?.value ?? ($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option value="">{{ resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsSelectPlaceholder') }}</option>
|
||||
<option
|
||||
v-for="option in optionsCache[field.options_source || ''] || []"
|
||||
:key="String(option.value)"
|
||||
:value="String(option.value)"
|
||||
>
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
|
||||
<!-- multi_select(多选,动态选项,复选框列表) -->
|
||||
<div
|
||||
v-else-if="field.type === 'multi_select'"
|
||||
class="max-h-52 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2"
|
||||
>
|
||||
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
|
||||
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="!(optionsCache[field.options_source || ''] || []).length"
|
||||
class="px-2 py-1 text-xs text-muted"
|
||||
>
|
||||
{{ $t('admin.schedule.form.dynamicParamsNoOptions') }}
|
||||
</p>
|
||||
<label
|
||||
v-for="option in optionsCache[field.options_source || ''] || []"
|
||||
:key="String(option.value)"
|
||||
class="flex cursor-pointer items-start gap-2 rounded-lg px-2 py-1.5 text-sm transition hover:bg-surface-soft"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-3.5 w-3.5 rounded text-blue-600"
|
||||
:checked="Array.isArray(params[field.key]) && params[field.key].includes(option.value)"
|
||||
@change="toggleMultiValue(field.key, option.value)"
|
||||
/>
|
||||
<span class="min-w-0">
|
||||
<span class="block text-secondary">{{ option.label }}</span>
|
||||
<span v-if="option.description" class="block text-xs text-muted">{{ option.description }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="resolveText(field.help_key, field.help)" class="mt-1 text-xs text-muted">
|
||||
{{ resolveText(field.help_key, field.help) }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 高级配置折叠 JSON(写入 job_params._advanced,兜底历史/特殊任务) -->
|
||||
<details class="rounded-xl border border-default bg-surface">
|
||||
<summary class="cursor-pointer rounded-xl px-3 py-2 text-xs font-semibold text-secondary hover:bg-surface-soft">
|
||||
{{ $t('admin.schedule.form.dynamicParamsAdvanced') }}
|
||||
</summary>
|
||||
<div class="px-3 pb-3 pt-1">
|
||||
<textarea
|
||||
v-model="advancedJsonText"
|
||||
class="w-full min-h-[72px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
|
||||
:class="advancedJsonError ? '!border-rose-300' : ''"
|
||||
:placeholder="$t('admin.schedule.form.dynamicParamsAdvancedPlaceholder')"
|
||||
@input="handleAdvancedInput"
|
||||
></textarea>
|
||||
<p v-if="advancedJsonError" class="mt-1 text-xs text-rose-600">
|
||||
{{ $t('admin.schedule.form.dynamicParamsAdvancedInvalid') }}
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
+15
-32
@@ -2,11 +2,13 @@
|
||||
/**
|
||||
* features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
|
||||
* 用途:定时任务创建/编辑弹窗。
|
||||
* 依赖:schedules.context、ScheduleCronDesigner。
|
||||
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染,前端不维护 key→i18n 映射。
|
||||
* 依赖:schedules.context、ScheduleCronDesigner、DynamicTaskParamsForm。
|
||||
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染;平台任务参数区由
|
||||
* DynamicTaskParamsForm 按 params_schema 通用渲染,本组件不再按任务硬编码 v-if。
|
||||
*/
|
||||
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
|
||||
import { useScheduleCreateModalOpen, useSchedulesAdminContext } from '../composables/schedules.context';
|
||||
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
|
||||
import ScheduleCronDesigner from './ScheduleCronDesigner.vue';
|
||||
|
||||
const admin = useSchedulesAdminContext();
|
||||
@@ -102,6 +104,7 @@ const showCreateModal = useScheduleCreateModalOpen();
|
||||
<select
|
||||
v-model="admin.scheduleCreateForm.platform_api_path"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
@change="admin.handlePlatformJobChange"
|
||||
>
|
||||
<option :value="null">{{ $t('admin.schedule.form.selectPlatformJob') }}</option>
|
||||
<option v-for="job in admin.platformJobs" :key="job.key" :value="job.key">
|
||||
@@ -297,38 +300,18 @@ const showCreateModal = useScheduleCreateModalOpen();
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if -->
|
||||
<div
|
||||
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'"
|
||||
class="mt-3 space-y-3"
|
||||
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job' && admin.selectedPlatformTaskDefinition"
|
||||
class="mt-3"
|
||||
>
|
||||
<div
|
||||
v-if="admin.scheduleCreateForm.platform_api_path === 'faq-aggregate-hot'"
|
||||
class="rounded-xl border border-amber-200 bg-amber-50/60 p-4 space-y-3"
|
||||
>
|
||||
<p class="text-sm text-amber-900">{{ $t('admin.schedule.form.faqHotAggregateHint') }}</p>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.faqHotAgentFilter') }}</label>
|
||||
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field !text-sm !leading-5" :disabled="admin.agents.length === 0">
|
||||
<option :value="null">{{ $t('admin.schedule.form.faqHotAllAgents') }}</option>
|
||||
<option v-for="agent in admin.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
|
||||
</select>
|
||||
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="admin.scheduleCreateForm.platform_api_path === 'shipping-inventory-rpa'"
|
||||
class="rounded-xl border border-blue-200 bg-blue-50/40 p-4 space-y-2"
|
||||
>
|
||||
<p class="text-sm text-blue-900">{{ $t('admin.schedule.form.shippingInventoryJobHint') }}</p>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.shippingInventoryJobParams') }}</label>
|
||||
<textarea
|
||||
v-model="admin.scheduleSqlEditForm.api_body_template"
|
||||
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
|
||||
:placeholder="$t('admin.schedule.form.shippingInventoryJobParamsPlaceholder')"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<DynamicTaskParamsForm
|
||||
:definition="admin.selectedPlatformTaskDefinition"
|
||||
:model-value="admin.scheduleCreateForm.job_params"
|
||||
:valid="admin.platformJobParamsValid"
|
||||
@update:model-value="admin.scheduleCreateForm.job_params = $event"
|
||||
@update:valid="admin.platformJobParamsValid = $event"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
|
||||
|
||||
@@ -211,7 +211,13 @@ const admin = useSchedulesAdminContext();
|
||||
</td>
|
||||
<td class="max-w-0 truncate px-4 py-2.5">{{ r.total_count }}</td>
|
||||
<td class="max-w-0 truncate px-4 py-2.5">{{ r.success_count }}</td>
|
||||
<td class="max-w-0 truncate px-4 py-2.5">{{ r.failed_count }}</td>
|
||||
<td class="max-w-0 truncate px-4 py-2.5" :title="admin.getScheduleRunFailedCountTitle(r)">
|
||||
<span>{{ r.failed_count }}</span>
|
||||
<span
|
||||
v-if="admin.isScheduleRunExcelExportFailed(r)"
|
||||
class="ml-1 text-xs font-medium text-amber-600"
|
||||
>+Excel</span>
|
||||
</td>
|
||||
<td class="max-w-0 overflow-hidden px-4 py-2.5">
|
||||
<span v-if="r.wecom_notified" class="inline-flex max-w-full shrink-0 items-center gap-1 truncate text-xs text-emerald-600" :title="$t('admin.schedule.notified')">
|
||||
<svg class="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
|
||||
|
||||
+6
-1
@@ -3,7 +3,7 @@
|
||||
* 定时任务管理页共享 ref 与删除确认弹窗状态。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import type { PlatformJobOption, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
|
||||
import type { PlatformJobOption, PlatformTaskDefinition, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
|
||||
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import type { KbGroup } from '@/features/kb/api/kb.api';
|
||||
import {
|
||||
@@ -16,6 +16,8 @@ export function createScheduleAdminState() {
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const kbGroups = ref<KbGroup[]>([]);
|
||||
const platformJobs = ref<PlatformJobOption[]>([]);
|
||||
/** 平台任务完整契约(含 params_schema),供 DynamicTaskParamsForm 渲染 */
|
||||
const platformTaskDefinitions = ref<PlatformTaskDefinition[]>([]);
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmTitle = ref('');
|
||||
@@ -103,12 +105,14 @@ export function createScheduleAdminState() {
|
||||
const scheduleNotifyUserQuery = ref('');
|
||||
const scheduleOwnerDropdownOpen = ref(false);
|
||||
const scheduleOwnerQuery = ref('');
|
||||
const platformJobParamsValid = ref(true);
|
||||
|
||||
return {
|
||||
agents,
|
||||
users,
|
||||
kbGroups,
|
||||
platformJobs,
|
||||
platformTaskDefinitions,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmTitle,
|
||||
deleteConfirmMessage,
|
||||
@@ -151,6 +155,7 @@ export function createScheduleAdminState() {
|
||||
scheduleNotifyUserQuery,
|
||||
scheduleOwnerDropdownOpen,
|
||||
scheduleOwnerQuery,
|
||||
platformJobParamsValid,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+81
-9
@@ -1,6 +1,9 @@
|
||||
/**
|
||||
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
|
||||
* 创建/编辑弹窗:Cron 设计器、负责人/通知人、SQL 配置与提交。
|
||||
* 用途:创建/编辑弹窗——Cron 设计器、负责人/通知人、SQL 配置、平台任务 job_params 契约与提交。
|
||||
* 依赖:schedule.api(含 platform-tasks definitions)、schedule-admin.state、schedule-form-payload.utils。
|
||||
* 逻辑:platform_job 参数由 DynamicTaskParamsForm 按 selectedPlatformTaskDefinition.params_schema
|
||||
* 渲染并写入 form.job_params;历史任务(dify_agent_id / api_body_template)编辑时自动迁移。
|
||||
*/
|
||||
import { computed, markRaw, watch } from 'vue';
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
@@ -27,7 +30,7 @@ import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
|
||||
|
||||
export function useScheduleAdminForm(
|
||||
state: ScheduleAdminState,
|
||||
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups' | 'loadPlatformJobs'>,
|
||||
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups' | 'loadPlatformJobs' | 'loadPlatformTaskDefinitions'>,
|
||||
list: Pick<ScheduleAdminList, 'loadSchedules'>,
|
||||
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
|
||||
t: ComposerTranslation,
|
||||
@@ -37,6 +40,7 @@ export function useScheduleAdminForm(
|
||||
const cronDesigner = markRaw(useScheduleCronDesigner());
|
||||
const {
|
||||
users,
|
||||
platformTaskDefinitions,
|
||||
showScheduleCreateModal,
|
||||
scheduleCreateSaving,
|
||||
scheduleEditingId,
|
||||
@@ -49,11 +53,33 @@ export function useScheduleAdminForm(
|
||||
scheduleNotifyUserQuery,
|
||||
scheduleOwnerDropdownOpen,
|
||||
scheduleOwnerQuery,
|
||||
platformJobParamsValid,
|
||||
} = state;
|
||||
|
||||
let scheduleNotifyCloseTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let scheduleOwnerCloseTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
/** 当前选中平台任务的完整契约(params_schema/defaults);未选中或非 platform_job 为 null */
|
||||
const selectedPlatformTaskDefinition = computed(() => {
|
||||
const form = scheduleCreateForm.value;
|
||||
if (form.schedule_type !== 'platform_job' || !form.platform_api_path) return null;
|
||||
return platformTaskDefinitions.value.find((d) => d.task_type === form.platform_api_path) || null;
|
||||
});
|
||||
|
||||
/**
|
||||
* 用户在下拉切换平台任务时重置参数为注册表默认值(避免脏参数带到别的任务)。
|
||||
* 核心逻辑:由 modal select @change 触发(不用 watch,防止编辑回填被覆盖)。
|
||||
*/
|
||||
const handlePlatformJobChange = (): void => {
|
||||
const definition = platformTaskDefinitions.value.find(
|
||||
(d) => d.task_type === scheduleCreateForm.value.platform_api_path,
|
||||
);
|
||||
scheduleCreateForm.value.job_params = definition && Object.keys(definition.defaults || {}).length
|
||||
? { ...definition.defaults }
|
||||
: null;
|
||||
platformJobParamsValid.value = true;
|
||||
};
|
||||
|
||||
const formatUserOptionLabel = (u: AdminUserRow) =>
|
||||
`${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
|
||||
|
||||
@@ -96,6 +122,7 @@ export function useScheduleAdminForm(
|
||||
scheduleNotifyDropdownOpen.value = false;
|
||||
scheduleOwnerQuery.value = '';
|
||||
scheduleOwnerDropdownOpen.value = false;
|
||||
platformJobParamsValid.value = true;
|
||||
cronDesigner.reset();
|
||||
};
|
||||
|
||||
@@ -111,6 +138,26 @@ export function useScheduleAdminForm(
|
||||
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as ScheduleCreateForm['data_source_type'];
|
||||
}
|
||||
if (!cfg) return;
|
||||
// 历史货代 RPA 任务兼容:job_params 为空时把旧 api_body_template JSON 迁移进 schema 表单
|
||||
if (
|
||||
scheduleCreateForm.value.schedule_type === 'platform_job'
|
||||
&& scheduleCreateForm.value.platform_api_path === 'shipping-inventory-rpa'
|
||||
&& !(scheduleCreateForm.value.job_params && Object.values(scheduleCreateForm.value.job_params).some((v) => Array.isArray(v) ? v.length : v))
|
||||
&& (cfg.external_api?.body_template || '').trim()
|
||||
) {
|
||||
try {
|
||||
const legacy = JSON.parse(cfg.external_api.body_template);
|
||||
if (legacy && typeof legacy === 'object' && !Array.isArray(legacy)) {
|
||||
const { source_codes: sourceCodes, ...rest } = legacy;
|
||||
scheduleCreateForm.value.job_params = {
|
||||
source_codes: Array.isArray(sourceCodes) ? sourceCodes : [],
|
||||
...(Object.keys(rest).length ? { _advanced: rest } : {}),
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// 非法历史 JSON 不迁移,保留高级区手工处理
|
||||
}
|
||||
}
|
||||
scheduleSqlEditForm.value = {
|
||||
base_fetch_sql: cfg.base_fetch_sql || '',
|
||||
fetch_where_conditions: cfg.fetch_where_conditions || '',
|
||||
@@ -146,6 +193,7 @@ export function useScheduleAdminForm(
|
||||
lookups.loadUsers(),
|
||||
lookups.loadKbGroups(),
|
||||
lookups.loadPlatformJobs(),
|
||||
lookups.loadPlatformTaskDefinitions(),
|
||||
]);
|
||||
syncScheduleOwnerQuery();
|
||||
try {
|
||||
@@ -168,6 +216,7 @@ export function useScheduleAdminForm(
|
||||
lookups.loadUsers(),
|
||||
lookups.loadKbGroups(),
|
||||
lookups.loadPlatformJobs(),
|
||||
lookups.loadPlatformTaskDefinitions(),
|
||||
]);
|
||||
};
|
||||
|
||||
@@ -189,6 +238,13 @@ export function useScheduleAdminForm(
|
||||
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
|
||||
: null,
|
||||
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
|
||||
// 历史 FAQ 任务兼容:无 job_params 时把旧 dify_agent_id 迁移为 app_id
|
||||
job_params: task.schedule_type === 'platform_job'
|
||||
? (task.job_params
|
||||
|| (task.platform_api_path === 'faq-aggregate-hot' && task.dify_agent_id
|
||||
? { app_id: task.dify_agent_id }
|
||||
: null))
|
||||
: null,
|
||||
dify_agent_id: task.dify_agent_id || null,
|
||||
owner_user_id: task.owner_user_id || null,
|
||||
wait_seconds: task.wait_seconds || 0,
|
||||
@@ -297,7 +353,6 @@ export function useScheduleAdminForm(
|
||||
const form = scheduleCreateForm.value;
|
||||
const isDataPipeline = form.schedule_type === 'data_pipeline';
|
||||
const isPlatformJob = form.schedule_type === 'platform_job';
|
||||
const isShippingRpa = isPlatformJob && form.platform_api_path === 'shipping-inventory-rpa';
|
||||
const dst = form.data_source_type;
|
||||
const hasAgent = !!form.dify_agent_id;
|
||||
const hasSql = isDataPipeline && dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
|
||||
@@ -307,6 +362,23 @@ export function useScheduleAdminForm(
|
||||
msg.error(t('admin.schedule.msg.platformJobRequired'));
|
||||
return;
|
||||
}
|
||||
if (isPlatformJob && selectedPlatformTaskDefinition.value && !platformJobParamsValid.value) {
|
||||
msg.error(t('admin.schedule.form.dynamicParamsInvalid'));
|
||||
return;
|
||||
}
|
||||
// 平台任务参数:按选中任务 params_schema 校验必填字段(后端保存时会再校验一次)
|
||||
if (isPlatformJob && selectedPlatformTaskDefinition.value) {
|
||||
const jobParams = form.job_params || {};
|
||||
const missing = selectedPlatformTaskDefinition.value.params_schema.find((field) => {
|
||||
if (!field.required || field.type === 'info') return false;
|
||||
const value = jobParams[field.key];
|
||||
return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0);
|
||||
});
|
||||
if (missing) {
|
||||
msg.error(t('admin.schedule.msg.jobParamRequired', { field: missing.label_key ? t(missing.label_key) : missing.label }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isDataPipeline && !hasAgent && !hasSql && !hasApi) {
|
||||
msg.error(t('admin.schedule.msg.configRequired'));
|
||||
return;
|
||||
@@ -339,10 +411,6 @@ export function useScheduleAdminForm(
|
||||
headerLabels,
|
||||
apiHeaders,
|
||||
);
|
||||
} else if (isShippingRpa && scheduleSqlEditForm.value.api_body_template.trim()) {
|
||||
configPayload = {
|
||||
api_body_template: scheduleSqlEditForm.value.api_body_template,
|
||||
};
|
||||
}
|
||||
|
||||
scheduleCreateSaving.value = true;
|
||||
@@ -353,7 +421,8 @@ export function useScheduleAdminForm(
|
||||
owner_user_id: form.owner_user_id,
|
||||
cron_expr: cronDesigner.cronExpr.value,
|
||||
wait_seconds: Math.max(0, Number(form.wait_seconds || 0)),
|
||||
dify_agent_id: form.dify_agent_id || undefined,
|
||||
// platform_job 参数走 job_params 契约通道;显式清空 dify_agent_id 避免旧参数通道残留
|
||||
dify_agent_id: isPlatformJob ? null : (form.dify_agent_id || undefined),
|
||||
notify_user_ids_json: form.notify_enabled ? form.notify_user_ids_json : [],
|
||||
notify_enabled: form.notify_enabled,
|
||||
kb_sync_enabled: isDataPipeline ? form.kb_sync_enabled : false,
|
||||
@@ -361,7 +430,7 @@ export function useScheduleAdminForm(
|
||||
enabled: form.enabled,
|
||||
...(isDataPipeline
|
||||
? { data_source_type: dst, platform_api_path: null }
|
||||
: { data_source_type: null, platform_api_path: form.platform_api_path }),
|
||||
: { data_source_type: null, platform_api_path: form.platform_api_path, job_params: form.job_params }),
|
||||
...(configPayload ? { config: configPayload } : {}),
|
||||
};
|
||||
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
|
||||
@@ -390,6 +459,9 @@ export function useScheduleAdminForm(
|
||||
|
||||
return {
|
||||
cronDesigner,
|
||||
selectedPlatformTaskDefinition,
|
||||
handlePlatformJobChange,
|
||||
platformJobParamsValid,
|
||||
filteredNotifyUsers,
|
||||
filteredOwnerUsers,
|
||||
openScheduleCreateModal,
|
||||
|
||||
+17
-3
@@ -1,14 +1,14 @@
|
||||
/**
|
||||
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts
|
||||
* 定时任务表单依赖的下拉数据:Agent、用户、知识库分组。
|
||||
* 定时任务表单依赖的下拉数据:Agent、用户、知识库分组、平台任务契约。
|
||||
*/
|
||||
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
|
||||
import { listAdminPlatformJobs } from '@/features/admin/api/schedule.api';
|
||||
import { listAdminPlatformJobs, listAdminPlatformTaskDefinitions } from '@/features/admin/api/schedule.api';
|
||||
import { getKbGroups } from '@/features/kb/api/kb.api';
|
||||
import type { ScheduleAdminState } from './schedule-admin.state';
|
||||
|
||||
export function useScheduleAdminLookups(state: ScheduleAdminState) {
|
||||
const { agents, users, kbGroups, platformJobs } = state;
|
||||
const { agents, users, kbGroups, platformJobs, platformTaskDefinitions } = state;
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
@@ -50,11 +50,25 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载平台任务完整契约(task_type + params_schema + defaults)。
|
||||
* 核心逻辑:GET /api/admin/platform-tasks/definitions,供 DynamicTaskParamsForm 按 schema 渲染。
|
||||
*/
|
||||
const loadPlatformTaskDefinitions = async (): Promise<void> => {
|
||||
try {
|
||||
platformTaskDefinitions.value = await listAdminPlatformTaskDefinitions();
|
||||
} catch (e) {
|
||||
console.error('Failed to load platform task definitions', e);
|
||||
platformTaskDefinitions.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
loadAgents,
|
||||
loadUsers,
|
||||
loadKbGroups,
|
||||
loadPlatformJobs,
|
||||
loadPlatformTaskDefinitions,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+9
@@ -8,6 +8,10 @@ import { listAdminScheduleRuns } from '@/features/admin/api/schedule.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { formatDateTime } from '../../utils/schedule-format.utils';
|
||||
import {
|
||||
getScheduleRunFailedCountTitle as buildScheduleRunFailedCountTitle,
|
||||
isScheduleRunExcelExportFailed,
|
||||
} from '@/shared/utils/schedule-run-display.utils';
|
||||
import type { ScheduleAdminState } from './schedule-admin.state';
|
||||
|
||||
export function useScheduleAdminRuns(
|
||||
@@ -194,6 +198,9 @@ export function useScheduleAdminRuns(
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const getScheduleRunFailedCountTitle = (run: (typeof selectedScheduleRuns.value)[number]) =>
|
||||
buildScheduleRunFailedCountTitle(run, t('admin.schedule.excelExportFailedHint'));
|
||||
|
||||
return {
|
||||
selectedSchedule,
|
||||
scheduleRunStatusOptions,
|
||||
@@ -209,6 +216,8 @@ export function useScheduleAdminRuns(
|
||||
downloadScheduleExcel,
|
||||
startScheduleColResize,
|
||||
formatDateTime,
|
||||
isScheduleRunExcelExportFailed,
|
||||
getScheduleRunFailedCountTitle,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface ScheduleCreateForm {
|
||||
schedule_type: ScheduleExecutionMode;
|
||||
data_source_type: ScheduleDataSourceType | null;
|
||||
platform_api_path: PlatformJobKey | string | null;
|
||||
/** platform_job 结构化参数(DynamicTaskParamsForm 输出,按注册表 params_schema 校验) */
|
||||
job_params: Record<string, any> | null;
|
||||
dify_agent_id: number | null;
|
||||
owner_user_id: number | null;
|
||||
wait_seconds: number;
|
||||
@@ -103,6 +105,7 @@ export function createDefaultScheduleCreateForm(): ScheduleCreateForm {
|
||||
schedule_type: 'data_pipeline',
|
||||
data_source_type: 'database',
|
||||
platform_api_path: null,
|
||||
job_params: null,
|
||||
dify_agent_id: null,
|
||||
owner_user_id: null,
|
||||
wait_seconds: 300,
|
||||
|
||||
@@ -28,6 +28,11 @@ type ShippingApiStatusPayload = {
|
||||
code?: string;
|
||||
details?: Record<string, unknown>;
|
||||
request_id?: string;
|
||||
/** 批次重试等接口返回的已发起任务数 */
|
||||
started?: number;
|
||||
/** 批次重试等接口返回的跳过任务数 */
|
||||
skipped?: number;
|
||||
batch_no?: string;
|
||||
};
|
||||
|
||||
export type ShippingChatAgentOption = {
|
||||
|
||||
@@ -380,7 +380,7 @@ watch(() => page.currentAgentId, () => {
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@workspace-action="page.handleShippingWorkspaceAction"
|
||||
@query-shortage="page.queryShippingShortageDetails"
|
||||
@retry-pending="page.retryCurrentShippingBatchPendingTasks"
|
||||
@retry-pending="page.openRetryFailedConfirm"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ChatViewOverlays.vue
|
||||
* 对话页全局弹窗与浮层:文件预览、反馈、查询预览、履历检索提示、请假 OA、删除确认、学习之窗。
|
||||
* 对话页全局弹窗与浮层:文件预览、反馈、查询预览、履历检索提示、请假 OA、删除确认、发货重试确认、学习之窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
|
||||
@@ -10,7 +10,7 @@ import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewD
|
||||
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
|
||||
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
|
||||
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import { Check, Loader2, X } from 'lucide-vue-next';
|
||||
import { nextTick } from 'vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
@@ -110,6 +110,33 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@confirm="page.handleDeleteConfirm"
|
||||
@cancel="page.closeDeleteConfirmDialog"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="page.showRetryFailedConfirmDialog"
|
||||
:title="page.t('chat.shippingNoticeUi.retryFailedConfirmTitle')"
|
||||
:message="page.t('chat.shippingNoticeUi.retryFailedConfirmMessage')"
|
||||
:confirm-text="page.t('chat.shippingNoticeUi.retryFailedConfirmAction')"
|
||||
:confirm-loading="page.retryingShippingPendingTasks"
|
||||
confirm-tone="primary"
|
||||
@confirm="page.handleRetryFailedConfirm"
|
||||
@cancel="page.closeRetryFailedConfirm"
|
||||
/>
|
||||
<div
|
||||
v-if="page.shippingToastMessage"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
>
|
||||
<div class="pointer-events-auto flex max-w-[min(92vw,28rem)] items-start gap-2 rounded-full border border-emerald-200 bg-white/95 px-4 py-2 text-sm text-emerald-800 shadow-lg backdrop-blur">
|
||||
<Check class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" />
|
||||
<span class="min-w-0 flex-1 leading-5">{{ page.shippingToastMessage }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon-ds -mr-1 shrink-0"
|
||||
:aria-label="page.t('common.close')"
|
||||
@click="page.clearShippingToast"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ChatGuideModal
|
||||
v-model:open="page.showGuideModal"
|
||||
v-model:active-guide-id="page.activeGuideId"
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* features/chat/components/ShippingBatchWorkspaceDrawer.vue
|
||||
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与统一动作入口。
|
||||
* 依赖:shippingStepper、shippingMenu、shipping.api.types、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口,执行动作仍由 useChatShipping 接管。
|
||||
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口。
|
||||
* 「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { RefreshCw, Target, X } from 'lucide-vue-next';
|
||||
|
||||
@@ -190,7 +190,7 @@ export function useChatPage() {
|
||||
}, { immediate: true });
|
||||
|
||||
const dialogs = useChatPageDialogs(messages);
|
||||
const { openDeleteConfirmDialog } = dialogs;
|
||||
const { openDeleteConfirmDialog, openRetryFailedConfirm, showShippingToast } = dialogs;
|
||||
|
||||
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
let startNewChat: () => void;
|
||||
@@ -303,6 +303,29 @@ export function useChatPage() {
|
||||
});
|
||||
resetShippingConversationState = shipping.resetShippingConversationState;
|
||||
|
||||
/**
|
||||
* Drawer「重试所有失败」点击:仅打开确认弹窗,不立刻发请求。
|
||||
*/
|
||||
const openRetryFailedConfirmDialog = () => {
|
||||
if (shipping.retryingShippingPendingTasks.value) return;
|
||||
openRetryFailedConfirm(() => confirmRetryFailedTasks());
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后执行批次失败任务重试,并以非阻塞 toast 反馈结果。
|
||||
* 核心逻辑:调用 useChatShipping.retryCurrentShippingBatchPendingTasks,成功后刷新已内置;仅补 toast。
|
||||
*/
|
||||
const confirmRetryFailedTasks = async () => {
|
||||
const result = await shipping.retryCurrentShippingBatchPendingTasks();
|
||||
if (!result) return;
|
||||
showShippingToast(
|
||||
t('chat.shippingNoticeUi.retryFailedStarted', {
|
||||
started: result.started,
|
||||
skipped: result.skipped,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
route,
|
||||
@@ -570,6 +593,12 @@ export function useChatPage() {
|
||||
deleteConfirmMessage: dialogs.deleteConfirmMessage,
|
||||
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm: dialogs.handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog: dialogs.showRetryFailedConfirmDialog,
|
||||
closeRetryFailedConfirm: dialogs.closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm: dialogs.handleRetryFailedConfirm,
|
||||
openRetryFailedConfirm: openRetryFailedConfirmDialog,
|
||||
shippingToastMessage: dialogs.shippingToastMessage,
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||||
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
|
||||
* 批次「重试所有失败」成功后不弹居中 msg.success,由页面级 toast 展示 started/skipped。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -816,25 +817,35 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return true;
|
||||
};
|
||||
|
||||
const retryCurrentShippingBatchPendingTasks = async () => {
|
||||
/**
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务。
|
||||
* 核心逻辑:调 workspace retry-pending → 刷新会话工作台/批次摘要/动作;成功反馈交给页面级非阻塞 toast,避免居中成功弹窗。
|
||||
* @returns 成功时返回 started/skipped;失败或跳过时返回 null
|
||||
*/
|
||||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||||
started: number;
|
||||
skipped: number;
|
||||
} | null> => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
if (!batchNo || retryingShippingPendingTasks.value) return false;
|
||||
if (!batchNo || retryingShippingPendingTasks.value) return null;
|
||||
if (isShippingActionBusy.value) {
|
||||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
retryingShippingPendingTasks.value = true;
|
||||
try {
|
||||
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
|
||||
await syncShippingConversationWorkspace();
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
await refreshShippingActions();
|
||||
return true;
|
||||
return {
|
||||
started: Number(result.started ?? 0),
|
||||
skipped: Number(result.skipped ?? 0),
|
||||
};
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
return false;
|
||||
return null;
|
||||
} finally {
|
||||
retryingShippingPendingTasks.value = false;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
/**
|
||||
* 对话页:删除确认弹窗、消息反馈弹窗状态。
|
||||
* features/chat/page/useChatPageDialogs.ts
|
||||
* 用途:对话页删除确认、发货「重试所有失败」确认、反馈弹窗与轻量 toast 状态。
|
||||
* 依赖:vue computed/ref、chat.types。
|
||||
* 逻辑:由 useChatPage 组装;ChatViewOverlays 绑定 DeleteConfirmDialog 与 toast 条。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
const SHIPPING_TOAST_AUTO_CLOSE_MS = 3200;
|
||||
|
||||
export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 打开删除确认弹窗,并在确认时执行待执行动作。
|
||||
* @param message - 确认说明文案
|
||||
* @param onConfirm - 用户确认后执行的回调
|
||||
*/
|
||||
const openDeleteConfirmDialog = (
|
||||
message: string,
|
||||
onConfirm: () => Promise<void> | void,
|
||||
@@ -19,21 +29,93 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
/** 关闭删除确认弹窗并清空待执行动作。 */
|
||||
const closeDeleteConfirmDialog = () => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmMessage.value = '';
|
||||
pendingDeleteAction = null;
|
||||
};
|
||||
|
||||
/** 执行删除确认回调后关闭弹窗。 */
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!pendingDeleteAction) return;
|
||||
await pendingDeleteAction();
|
||||
closeDeleteConfirmDialog();
|
||||
};
|
||||
|
||||
const showRetryFailedConfirmDialog = ref(false);
|
||||
let pendingRetryFailedAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 打开「重试所有失败」确认弹窗。
|
||||
* 核心逻辑:仅登记确认后要执行的动作,实际请求由调用方注入。
|
||||
* @param onConfirm - 用户点「确认重试」后执行的回调
|
||||
*/
|
||||
const openRetryFailedConfirm = (onConfirm: () => Promise<void> | void) => {
|
||||
pendingRetryFailedAction = onConfirm;
|
||||
showRetryFailedConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
/** 关闭重试确认弹窗并清空待执行动作。 */
|
||||
const closeRetryFailedConfirm = () => {
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
pendingRetryFailedAction = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户确认后执行重试动作;弹窗由 DeleteConfirmDialog 自行关闭。
|
||||
* 核心逻辑:取出并清空 pending,再 await 执行,避免重复确认。
|
||||
*/
|
||||
const handleRetryFailedConfirm = async () => {
|
||||
const action = pendingRetryFailedAction;
|
||||
pendingRetryFailedAction = null;
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
if (!action) return;
|
||||
await action();
|
||||
};
|
||||
|
||||
const shippingToastMessage = ref('');
|
||||
let shippingToastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
/** 清除 toast 自动关闭计时器。 */
|
||||
const clearShippingToastTimer = () => {
|
||||
if (!shippingToastTimer) return;
|
||||
clearTimeout(shippingToastTimer);
|
||||
shippingToastTimer = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 展示非阻塞顶部 toast(用于发货批量重试等轻量成功反馈)。
|
||||
* @param message - toast 正文;空字符串视为关闭
|
||||
*/
|
||||
const showShippingToast = (message: string) => {
|
||||
clearShippingToastTimer();
|
||||
const next = String(message || '').trim();
|
||||
shippingToastMessage.value = next;
|
||||
if (!next) return;
|
||||
shippingToastTimer = setTimeout(() => {
|
||||
shippingToastMessage.value = '';
|
||||
shippingToastTimer = null;
|
||||
}, SHIPPING_TOAST_AUTO_CLOSE_MS);
|
||||
};
|
||||
|
||||
/** 手动关闭发货 toast。 */
|
||||
const clearShippingToast = () => {
|
||||
clearShippingToastTimer();
|
||||
shippingToastMessage.value = '';
|
||||
};
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearShippingToastTimer();
|
||||
});
|
||||
|
||||
const showGeneralFeedbackDialog = ref(false);
|
||||
const activeFeedbackMessageIndex = ref<number | null>(null);
|
||||
|
||||
/**
|
||||
* 打开消息反馈弹窗并记录当前消息下标。
|
||||
* @param index - messages 数组下标
|
||||
*/
|
||||
const handleOpenFeedback = (index: number) => {
|
||||
activeFeedbackMessageIndex.value = index;
|
||||
showGeneralFeedbackDialog.value = true;
|
||||
@@ -61,6 +143,13 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog,
|
||||
openRetryFailedConfirm,
|
||||
closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm,
|
||||
shippingToastMessage,
|
||||
showShippingToast,
|
||||
clearShippingToast,
|
||||
showGeneralFeedbackDialog,
|
||||
activeFeedbackMessageIndex,
|
||||
handleOpenFeedback,
|
||||
|
||||
@@ -111,7 +111,7 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
});
|
||||
return ok;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.streamError.generic');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!ok) ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
if (!ok) ctx.msg.warning(ctx.t('chat.shippingInventoryUploadFailed'));
|
||||
return ok;
|
||||
};
|
||||
|
||||
@@ -108,7 +108,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
ctx.pendingShippingInventoryFile.value = null;
|
||||
ctx.pendingShippingUploadTaskId.value = '';
|
||||
void uploadInventoryForTask(normalizedTaskId, pendingFile).catch((e: unknown) => {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
});
|
||||
return true;
|
||||
@@ -283,7 +283,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
try {
|
||||
await uploadInventoryForTask(taskId, file);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
} finally {
|
||||
ctx.shippingInventorySelectionTaskId.value = '';
|
||||
|
||||
@@ -944,6 +944,7 @@
|
||||
"totalCount": "Processed",
|
||||
"successCount": "Success",
|
||||
"failedCount": "Failed",
|
||||
"excelExportFailedHint": "Inventory sources succeeded, but schedule Excel export failed",
|
||||
"wecomNotified": "WeCom notify",
|
||||
"detail": "Detail",
|
||||
"log": "Log"
|
||||
@@ -965,9 +966,20 @@
|
||||
"platformJobShippingInventory": "Shipping inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
|
||||
"shippingInventoryJobHint": "Writes batch inventory RPA export triggers on schedule; optional JSON to limit source_codes.",
|
||||
"shippingInventoryJobHint": "Fetches inventory data from configured sources on schedule; exported asynchronously by the RPA worker.",
|
||||
"shippingInventoryJobParams": "Job parameters (optional)",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"DSV360_AWSBI_BYAWSATL01\"]}",
|
||||
"shippingInventorySources": "Inventory sources",
|
||||
"shippingInventorySourcesPlaceholder": "Leave empty to export all enabled sources",
|
||||
"shippingInventorySourcesHelp": "Select the inventory sources to run; options come from the source config. Empty means all.",
|
||||
"dynamicParamsSelectPlaceholder": "Please select",
|
||||
"dynamicParamsOptionsLoading": "Loading options...",
|
||||
"dynamicParamsNoOptions": "No options available",
|
||||
"dynamicParamsAdvanced": "Advanced config (JSON, optional)",
|
||||
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
|
||||
"dynamicParamsAdvancedInvalid": "Advanced config JSON is invalid; fix it before it can be saved.",
|
||||
"dynamicParamsJsonInvalid": "JSON is invalid; fix it before it can be saved.",
|
||||
"dynamicParamsInvalid": "Fix invalid task parameters before saving.",
|
||||
"dataSourceType": "Data source type",
|
||||
"databaseDirect": "Database",
|
||||
"externalApi": "External API",
|
||||
@@ -1133,6 +1145,7 @@
|
||||
"testQueryFailed": "Test query failed",
|
||||
"configRequired": "At least one of Dify Agent, SQL config, or external API is required.",
|
||||
"platformJobRequired": "Please select a platform built-in task",
|
||||
"jobParamRequired": "Please fill in the task parameter: {field}",
|
||||
"headerLabelsJsonInvalid": "header_labels JSON format is invalid.",
|
||||
"apiHeadersJsonInvalid": "API Headers JSON format is invalid.",
|
||||
"runNowFailed": "Manual run failed",
|
||||
|
||||
@@ -22,7 +22,8 @@
|
||||
"shippingNoticeUploadDone": "Inventory file uploaded: {fileName}.",
|
||||
"shippingNoticeInventoryUploadStarted": "I selected inventory file {fileName}. Uploading it and reading the inventory columns now.",
|
||||
"shippingNoticeUploadOk": "Upload succeeded.",
|
||||
"shippingNoticeUploadFailed": "Inventory upload failed.",
|
||||
"shippingNoticeUploadFailed": "Shipping notice upload failed.",
|
||||
"shippingInventoryUploadFailed": "Inventory upload failed.",
|
||||
"shippingNoticeRefreshDone": "Current task status refreshed.",
|
||||
"shippingNoticeRetryUploadAction": "Retry freight upload",
|
||||
"shippingNoticeRetryUploadQueued": "Upload has been triggered again. Refresh later to check the result.",
|
||||
@@ -200,6 +201,10 @@
|
||||
"retryPendingDone": "Recoverable tasks have been resubmitted",
|
||||
"retryFailed": "Retry failed",
|
||||
"retrying": "Retrying...",
|
||||
"retryFailedConfirmTitle": "Retry all failed tasks?",
|
||||
"retryFailedConfirmMessage": "This will reprocess retryable failed tasks in the current batch and may trigger external freight-forwarder actions.",
|
||||
"retryFailedConfirmAction": "Confirm retry",
|
||||
"retryFailedStarted": "Retry started: {started} task(s), skipped {skipped}",
|
||||
"taskListTitle": "Task List",
|
||||
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
|
||||
"expandTaskList": "Expand task list",
|
||||
|
||||
@@ -869,9 +869,20 @@
|
||||
"platformJobShippingInventory": "Shipping inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
|
||||
"shippingInventoryJobHint": "เขียน batch inventory RPA export trigger ตาม Cron; JSON ตัวเลือกจำกัด source_codes",
|
||||
"shippingInventoryJobHint": "ดึงข้อมูลสต็อกจากแหล่งที่กำหนดตามกำหนดเวลา โดย RPA worker ส่งออกแบบอะซิงโครนัส",
|
||||
"shippingInventoryJobParams": "พารามิเตอร์ Job (ไม่บังคับ)",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"DSV360_AWSBI_BYAWSATL01\"]}",
|
||||
"shippingInventorySources": "แหล่งสต็อก",
|
||||
"shippingInventorySourcesPlaceholder": "เว้นว่างเพื่อส่งออกทุกแหล่งที่เปิดใช้งาน",
|
||||
"shippingInventorySourcesHelp": "เลือกแหล่งสต็อกที่ต้องการรัน; ตัวเลือกมาจากการตั้งค่าแหล่งสต็อก เว้นว่าง = ทั้งหมด",
|
||||
"dynamicParamsSelectPlaceholder": "กรุณาเลือก",
|
||||
"dynamicParamsOptionsLoading": "กำลังโหลดตัวเลือก...",
|
||||
"dynamicParamsNoOptions": "ไม่มีตัวเลือก",
|
||||
"dynamicParamsAdvanced": "การตั้งค่าขั้นสูง (JSON, ไม่บังคับ)",
|
||||
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
|
||||
"dynamicParamsAdvancedInvalid": "รูปแบบ JSON ของการตั้งค่าขั้นสูงไม่ถูกต้อง จะไม่ถูกบันทึกจนกว่าจะแก้ไข",
|
||||
"dynamicParamsJsonInvalid": "รูปแบบ JSON ไม่ถูกต้อง จะไม่ถูกบันทึกจนกว่าจะแก้ไข",
|
||||
"dynamicParamsInvalid": "โปรดแก้ไขพารามิเตอร์งานที่ผิดพลาดก่อนบันทึก",
|
||||
"dataSourceConfig": "แหล่งข้อมูลและการตั้งค่าการทำงาน",
|
||||
"dataSourceType": "ประเภทแหล่งข้อมูล",
|
||||
"databaseDirect": "ฐานข้อมูลโดยตรง",
|
||||
@@ -995,11 +1006,13 @@
|
||||
"limitRows": "จำกัดจำนวนแถว (limit)"
|
||||
},
|
||||
"deleteDialogTitle": "ลบตารางเวลา",
|
||||
"excelExportFailedHint": "แหล่งสต็อกสำเร็จแล้ว แต่การส่งออก Excel ของตารางเวลาล้มเหลว",
|
||||
"deleteConfirmMessage": "ยืนยันการลบตารางเวลา \"{name}\"?",
|
||||
"msg": {
|
||||
"testRunFailed": "ทดสอบการทำงานล้มเหลว",
|
||||
"configRequired": "ต้องกรอกอย่างน้อยหนึ่งรายการใน Dify Agent, SQL config หรือ external API",
|
||||
"platformJobRequired": "โปรดเลือกงานในตัวแพลตฟอร์ม",
|
||||
"jobParamRequired": "กรุณากรอกพารามิเตอร์งาน: {field}",
|
||||
"headerLabelsJsonInvalid": "รูปแบบ JSON ของ header_labels ไม่ถูกต้อง",
|
||||
"apiHeadersJsonInvalid": "รูปแบบ JSON ของ API Headers ไม่ถูกต้อง",
|
||||
"runNowFailed": "การรันด้วยตนเองล้มเหลว",
|
||||
|
||||
@@ -22,7 +22,8 @@
|
||||
"shippingNoticeUploadDone": "อัปโหลดไฟล์สต็อกแล้ว: {fileName}",
|
||||
"shippingNoticeInventoryUploadStarted": "เลือกไฟล์สต็อก {fileName} แล้ว กำลังอัปโหลดและอ่านคอลัมน์สต็อก",
|
||||
"shippingNoticeUploadOk": "อัปโหลดสำเร็จ",
|
||||
"shippingNoticeUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
|
||||
"shippingNoticeUploadFailed": "อัปโหลดใบแจ้งจัดส่งล้มเหลว",
|
||||
"shippingInventoryUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
|
||||
"shippingNoticeRefreshDone": "รีเฟรชสถานะงานปัจจุบันแล้ว",
|
||||
"shippingNoticeRetryUploadAction": "ลองอัปโหลดไปยังระบบขนส่งอีกครั้ง",
|
||||
"shippingNoticeRetryUploadQueued": "เริ่มอัปโหลดอีกครั้งแล้ว โปรดรีเฟรชภายหลังเพื่อตรวจสอบผลลัพธ์",
|
||||
@@ -200,6 +201,10 @@
|
||||
"retryPendingDone": "ส่งงานที่กู้คืนได้ใหม่แล้ว",
|
||||
"retryFailed": "ลองใหม่ไม่สำเร็จ",
|
||||
"retrying": "กำลังลองใหม่...",
|
||||
"retryFailedConfirmTitle": "ยืนยันลองงานที่ล้มเหลวทั้งหมดอีกครั้ง?",
|
||||
"retryFailedConfirmMessage": "ระบบจะเริ่มประมวลผลงานที่ล้มเหลวและลองใหม่ได้ในชุดงานปัจจุบัน และอาจไปสั่งการระบบตัวแทนขนส่งภายนอก",
|
||||
"retryFailedConfirmAction": "ยืนยันลองใหม่",
|
||||
"retryFailedStarted": "เริ่มลองใหม่แล้ว: {started} งาน ข้าม {skipped} งาน",
|
||||
"taskListTitle": "รายการงาน",
|
||||
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
|
||||
"expandTaskList": "ขยายรายการงาน",
|
||||
|
||||
@@ -924,6 +924,7 @@
|
||||
"totalCount": "处理",
|
||||
"successCount": "成功",
|
||||
"failedCount": "失败",
|
||||
"excelExportFailedHint": "库存源已成功,但排程 Excel 生成失败",
|
||||
"wecomNotified": "企微通知",
|
||||
"detail": "明细",
|
||||
"log": "日志"
|
||||
@@ -945,9 +946,20 @@
|
||||
"platformJobShippingInventory": "货代库存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 热点聚合",
|
||||
"platformJobFixedAssetsSnapshot": "固资快照",
|
||||
"shippingInventoryJobHint": "按 Cron 批量写入库存 RPA 导出 trigger;可选 JSON 参数限定 source_codes。",
|
||||
"shippingInventoryJobHint": "按计划从配置的库存源抓取库存数据,由 RPA Worker 异步导出。",
|
||||
"shippingInventoryJobParams": "Job 参数(可选)",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"DSV360_AWSBI_BYAWSATL01\"]}",
|
||||
"shippingInventorySources": "库存源",
|
||||
"shippingInventorySourcesPlaceholder": "留空则导出全部启用库存源",
|
||||
"shippingInventorySourcesHelp": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
|
||||
"dynamicParamsSelectPlaceholder": "请选择",
|
||||
"dynamicParamsOptionsLoading": "选项加载中...",
|
||||
"dynamicParamsNoOptions": "暂无可选项",
|
||||
"dynamicParamsAdvanced": "高级配置(JSON,可选)",
|
||||
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
|
||||
"dynamicParamsAdvancedInvalid": "高级配置 JSON 格式错误,修正后才会保存",
|
||||
"dynamicParamsJsonInvalid": "JSON 格式错误,修正后才会保存",
|
||||
"dynamicParamsInvalid": "请修正任务参数中的错误后再保存",
|
||||
"dataSourceType": "数据源类型",
|
||||
"databaseDirect": "数据库直联",
|
||||
"externalApi": "外部API",
|
||||
@@ -1113,6 +1125,7 @@
|
||||
"testQueryFailed": "测试查询失败",
|
||||
"configRequired": "Dify Agent、SQL 配置或外部 API 至少填写一项,否则排程执行无任何效果",
|
||||
"platformJobRequired": "请选择平台内置任务",
|
||||
"jobParamRequired": "请填写任务参数:{field}",
|
||||
"headerLabelsJsonInvalid": "header_labels JSON 格式错误,请检查",
|
||||
"apiHeadersJsonInvalid": "API Headers JSON 格式错误,请检查",
|
||||
"runNowFailed": "手动执行失败",
|
||||
|
||||
@@ -22,7 +22,8 @@
|
||||
"shippingNoticeUploadDone": "库存文件已上传:{fileName}。",
|
||||
"shippingNoticeInventoryUploadStarted": "我已选择库存文件《{fileName}》,正在上传并读取库存列名。",
|
||||
"shippingNoticeUploadOk": "上传成功。",
|
||||
"shippingNoticeUploadFailed": "库存文件上传失败。",
|
||||
"shippingNoticeUploadFailed": "发货通知上传失败。",
|
||||
"shippingInventoryUploadFailed": "库存文件上传失败。",
|
||||
"shippingNoticeRefreshDone": "已刷新当前任务状态。",
|
||||
"shippingNoticeRetryUploadAction": "重试上传货代",
|
||||
"shippingNoticeRetryUploadQueued": "已重新触发上传,请稍后刷新查看结果。",
|
||||
@@ -200,6 +201,10 @@
|
||||
"retryPendingDone": "已重新提交未完成票",
|
||||
"retryFailed": "重试失败",
|
||||
"retrying": "重试中...",
|
||||
"retryFailedConfirmTitle": "确认重试所有失败任务?",
|
||||
"retryFailedConfirmMessage": "将对当前批次中可重试的失败任务重新发起处理,可能触发外部货代系统操作。",
|
||||
"retryFailedConfirmAction": "确认重试",
|
||||
"retryFailedStarted": "已发起重试:{started} 个任务,跳过 {skipped} 个",
|
||||
"taskListTitle": "任务列表",
|
||||
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
|
||||
"expandTaskList": "展开任务列表",
|
||||
|
||||
@@ -870,9 +870,20 @@
|
||||
"platformJobShippingInventory": "貨代庫存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 熱點聚合",
|
||||
"platformJobFixedAssetsSnapshot": "固資快照",
|
||||
"shippingInventoryJobHint": "按 Cron 批量寫入庫存 RPA 匯出 trigger;可選 JSON 參數限定 source_codes。",
|
||||
"shippingInventoryJobHint": "按計畫從配置的庫存來源抓取庫存資料,由 RPA Worker 非同步匯出。",
|
||||
"shippingInventoryJobParams": "Job 參數(可選)",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
|
||||
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"DSV360_AWSBI_BYAWSATL01\"]}",
|
||||
"shippingInventorySources": "庫存來源",
|
||||
"shippingInventorySourcesPlaceholder": "留空則匯出全部啟用庫存來源",
|
||||
"shippingInventorySourcesHelp": "選擇需要執行的庫存來源;選項來自庫存來源配置,留空則全部執行。",
|
||||
"dynamicParamsSelectPlaceholder": "請選擇",
|
||||
"dynamicParamsOptionsLoading": "選項載入中...",
|
||||
"dynamicParamsNoOptions": "暫無可選項",
|
||||
"dynamicParamsAdvanced": "進階配置(JSON,可選)",
|
||||
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
|
||||
"dynamicParamsAdvancedInvalid": "進階配置 JSON 格式錯誤,修正後才會儲存",
|
||||
"dynamicParamsJsonInvalid": "JSON 格式錯誤,修正後才會儲存",
|
||||
"dynamicParamsInvalid": "請修正任務參數中的錯誤後再儲存",
|
||||
"dataSourceConfig": "資料來源與執行配置",
|
||||
"dataSourceType": "資料來源類型",
|
||||
"databaseDirect": "資料庫直連",
|
||||
@@ -996,11 +1007,13 @@
|
||||
"limitRows": "限制行數 (limit)"
|
||||
},
|
||||
"deleteDialogTitle": "刪除排程",
|
||||
"excelExportFailedHint": "庫存來源已成功,但排程 Excel 生成失敗",
|
||||
"deleteConfirmMessage": "確認刪除排程「{name}」?",
|
||||
"msg": {
|
||||
"testRunFailed": "測試執行失敗",
|
||||
"configRequired": "Dify Agent、SQL 配置或外部 API 至少填寫一項,否則排程執行無任何效果",
|
||||
"platformJobRequired": "請選擇平台內建任務",
|
||||
"jobParamRequired": "請填寫任務參數:{field}",
|
||||
"headerLabelsJsonInvalid": "header_labels JSON 格式錯誤,請檢查",
|
||||
"apiHeadersJsonInvalid": "API Headers JSON 格式錯誤,請檢查",
|
||||
"runNowFailed": "手動執行失敗",
|
||||
|
||||
@@ -22,7 +22,8 @@
|
||||
"shippingNoticeUploadDone": "庫存檔案已上傳:{fileName}。",
|
||||
"shippingNoticeInventoryUploadStarted": "我已選擇庫存檔案《{fileName}》,正在上傳並讀取庫存欄位。",
|
||||
"shippingNoticeUploadOk": "上傳成功。",
|
||||
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
|
||||
"shippingNoticeUploadFailed": "發貨通知上傳失敗。",
|
||||
"shippingInventoryUploadFailed": "庫存檔案上傳失敗。",
|
||||
"shippingNoticeRefreshDone": "已重新整理目前任務狀態。",
|
||||
"shippingNoticeRetryUploadAction": "重試上傳貨代",
|
||||
"shippingNoticeRetryUploadQueued": "已重新觸發上傳,請稍後重新整理查看結果。",
|
||||
@@ -200,6 +201,10 @@
|
||||
"retryPendingDone": "已重新提交可恢復任務",
|
||||
"retryFailed": "重試失敗",
|
||||
"retrying": "重試中...",
|
||||
"retryFailedConfirmTitle": "確認重試所有失敗任務?",
|
||||
"retryFailedConfirmMessage": "將對目前批次中可重試的失敗任務重新發起處理,可能觸發外部貨代系統操作。",
|
||||
"retryFailedConfirmAction": "確認重試",
|
||||
"retryFailedStarted": "已發起重試:{started} 個任務,跳過 {skipped} 個",
|
||||
"taskListTitle": "任務列表",
|
||||
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
|
||||
"expandTaskList": "展開任務列表",
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface ScheduleTask {
|
||||
dify_agent_id?: number | null;
|
||||
platform_api_path?: string | null;
|
||||
data_source_type?: 'database' | 'external_api' | null;
|
||||
/** platform_job 结构化参数(按注册表 params_schema 校验) */
|
||||
job_params?: Record<string, any> | null;
|
||||
kb_sync_enabled?: boolean;
|
||||
kb_group_id?: number | null;
|
||||
notify_user_ids_json: number[];
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* shared/utils/schedule-run-display.utils.ts
|
||||
* 用途:排程 run 列表展示辅助(失败计数、Excel 导出状态等)。
|
||||
* 依赖:无。
|
||||
* 逻辑:管理端 ScheduleWorkbenchPanel、工作台 ScheduleRunsPage 等复用。
|
||||
*/
|
||||
|
||||
type ScheduleRunSummaryCarrier = {
|
||||
failed_count?: number | null;
|
||||
response_summary_json?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断排程 run 是否因 Excel 汇总导出失败而标记 partial_failed(源数据可能已全部成功)。
|
||||
* 核心逻辑:读取 response_summary_json.excel_failed 或 excel_export_status=failed。
|
||||
*/
|
||||
export function isScheduleRunExcelExportFailed(run: ScheduleRunSummaryCarrier | null | undefined): boolean {
|
||||
const summary = run?.response_summary_json;
|
||||
if (!summary || typeof summary !== 'object') return false;
|
||||
if (summary.excel_failed === true) return true;
|
||||
return summary.excel_export_status === 'failed';
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成失败数列 title,含 Excel 汇总层失败说明。
|
||||
* @param run - 排程 run 记录
|
||||
* @param excelFailedHint - 已翻译的 Excel 失败提示文案
|
||||
*/
|
||||
export function getScheduleRunFailedCountTitle(
|
||||
run: ScheduleRunSummaryCarrier | null | undefined,
|
||||
excelFailedHint: string,
|
||||
): string {
|
||||
const failed = run?.failed_count ?? 0;
|
||||
if (!isScheduleRunExcelExportFailed(run)) {
|
||||
return String(failed);
|
||||
}
|
||||
return `${failed} (${excelFailedHint})`;
|
||||
}
|
||||
@@ -92,7 +92,7 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
|
||||
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
|
||||
|
||||
库存源定义见 `backend/config/shipping_inventory_sources.json`(新增 Warehouse 只改 JSON)。
|
||||
库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。
|
||||
|
||||
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
scripts/rpa/dsv_export_batch_smoke.py
|
||||
|
||||
用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.json、freight_rpa_worker。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.yaml、freight_rpa_worker。
|
||||
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
|
||||
|
||||
场景:
|
||||
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
|
||||
source_code — 三个不同 source_code(JSON 中独立配置项)
|
||||
source_code — 三个不同 source_code(YAML 中独立配置项)
|
||||
|
||||
用法:
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
scripts/rpa/dsv_export_smoke.py
|
||||
|
||||
用途:本地手动验证指定 DSV 360 库存源(默认 BYAWSATL01)的浏览器导出全流程。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.json。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.yaml。
|
||||
逻辑:加载 rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
|
||||
|
||||
用法(仓库根目录):
|
||||
@@ -20,6 +20,8 @@ import traceback
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
@@ -36,11 +38,11 @@ def _load_worker():
|
||||
|
||||
def _build_source_from_config(source_code: str) -> dict:
|
||||
"""
|
||||
从 JSON 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
|
||||
从 YAML 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
|
||||
核心逻辑:复用与 inventory_sources._build_legacy_query 相同的 query 口径。
|
||||
"""
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.json"
|
||||
payload = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
|
||||
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
raw = next(
|
||||
(item for item in (payload.get("sources") or []) if str(item.get("source_code") or "").upper() == source_code.upper()),
|
||||
None,
|
||||
|
||||
@@ -22,11 +22,15 @@ Optional:
|
||||
FREIGHT_RPA_HEADLESS=false
|
||||
FREIGHT_RPA_BROWSER_CHANNEL=msedge
|
||||
FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||||
FREIGHT_RPA_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
|
||||
FREIGHT_RPA_LOG_MAX_BYTES=10485760
|
||||
FREIGHT_RPA_LOG_BACKUP_COUNT=5
|
||||
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||||
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -37,7 +41,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, TextIO
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
@@ -68,6 +72,107 @@ def _env(name: str, default: str = "") -> str:
|
||||
return value
|
||||
|
||||
|
||||
class _TeeStream:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
文件 flush 采用行级同步,RPA 异常退出时尽量保留最后几行排障信息。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
self.encoding = getattr(console, "encoding", "utf-8")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._console.write(text)
|
||||
written = self._log_file.write(text)
|
||||
self.flush()
|
||||
return written
|
||||
|
||||
def flush(self) -> None:
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return bool(getattr(self._console, "isatty", lambda: False)())
|
||||
|
||||
|
||||
def _configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,便于排查登录、下载、回调失败。
|
||||
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
raw = _env("FREIGHT_RPA_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(raw).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / path).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_rotate_log_file_if_needed(path)
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
sys.stdout = _TeeStream(original_stdout, log_file) # type: ignore[assignment]
|
||||
sys.stderr = _TeeStream(original_stderr, log_file) # type: ignore[assignment]
|
||||
|
||||
def _close_log() -> None:
|
||||
sys.stdout = original_stdout
|
||||
sys.stderr = original_stderr
|
||||
log_file.close()
|
||||
|
||||
atexit.register(_close_log)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return path
|
||||
|
||||
|
||||
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取日志相关整数环境变量;非法值回退默认值。"""
|
||||
try:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
def _rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `FREIGHT_RPA_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`FREIGHT_RPA_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
"""
|
||||
max_bytes = _log_int_env("FREIGHT_RPA_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("FREIGHT_RPA_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
if max_bytes <= 0 or not path.is_file():
|
||||
return
|
||||
try:
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if backup_count <= 0:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
oldest = Path(f"{path}.{backup_count}")
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
src = Path(f"{path}.{index}")
|
||||
if src.exists():
|
||||
src.replace(Path(f"{path}.{index + 1}"))
|
||||
path.replace(Path(f"{path}.1"))
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""
|
||||
返回仓库内 backend 根目录。
|
||||
@@ -1880,9 +1985,10 @@ def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> Non
|
||||
def _click_dsv_view_report(page: Any) -> None:
|
||||
"""
|
||||
点击 SSRS 参数页 View Report。
|
||||
核心逻辑:report-frame 挂载后按钮可能延迟渲染,先短轮询再尝试多种点击方式。
|
||||
核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。
|
||||
"""
|
||||
selectors = (
|
||||
"#ReportViewerMain_ctl08_ctl00",
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
@@ -1890,63 +1996,63 @@ def _click_dsv_view_report(page: Any) -> None:
|
||||
)
|
||||
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
|
||||
wait_ms = max(15_000, int(_env("FREIGHT_RPA_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
|
||||
if _wait_for_visible_selector(page, "", selectors, timeout_ms=wait_ms) is None:
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
submit_deadline = time.monotonic() + 4
|
||||
while time.monotonic() < submit_deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
|
||||
@@ -2435,6 +2541,22 @@ def _wait_for_dsv_app_after_login(
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
if not auth_transition and _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
) is not None:
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||||
"[DEBUG] dsv reports nav visible after login",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
on_portal_home = _is_dsv_on_portal_home(page)
|
||||
if on_portal_home and not auth_transition:
|
||||
if on_portal_shell_seen is not None and not portal_shell_callback_fired:
|
||||
@@ -2454,6 +2576,13 @@ def _wait_for_dsv_app_after_login(
|
||||
if _has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
continue
|
||||
# [STEP] 合规/认证过渡页仅用轻量短超时探测 Reports 导航,避免与首页长轮询混淆。
|
||||
_wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
)
|
||||
time.sleep(0.25)
|
||||
continue
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
@@ -3793,11 +3922,63 @@ def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None:
|
||||
# #endregion
|
||||
|
||||
|
||||
_INVENTORY_EXCEL_MIN_BYTES = 512
|
||||
_INVENTORY_EXCEL_HEADER_MARKERS = (
|
||||
"on hand inventory",
|
||||
"supplier id",
|
||||
"aws sku",
|
||||
"sku description",
|
||||
)
|
||||
|
||||
|
||||
def _validate_inventory_excel(path: Path) -> None:
|
||||
"""
|
||||
校验 RPA 下载的库存 Excel 可被打开且具备报表基本结构。
|
||||
核心逻辑:拒绝过小/HTML 错误页伪装文件;检查前几行是否含库存报表表头特征。
|
||||
Args:
|
||||
path: 本地 Excel 路径。
|
||||
Raises:
|
||||
RuntimeError: 文件过小、非 Excel 或缺少库存报表关键表头。
|
||||
"""
|
||||
size = path.stat().st_size
|
||||
if size < _INVENTORY_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
|
||||
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("openpyxl required to validate inventory Excel") from exc
|
||||
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"downloaded file is not valid Excel: {exc}") from exc
|
||||
|
||||
try:
|
||||
worksheet = workbook.active
|
||||
if worksheet is None:
|
||||
raise RuntimeError("downloaded file is not valid Excel: missing active sheet")
|
||||
preview_lines: list[str] = []
|
||||
for row in worksheet.iter_rows(max_row=6, values_only=True):
|
||||
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
|
||||
if cells:
|
||||
preview_lines.append(" | ".join(cells).lower())
|
||||
haystack = "\n".join(preview_lines)
|
||||
title = str(worksheet.title or "").lower().replace("_", "")
|
||||
if not any(marker in haystack for marker in _INVENTORY_EXCEL_HEADER_MARKERS):
|
||||
if "inventory" not in title and "onhand" not in title:
|
||||
raise RuntimeError("downloaded file is not valid Excel: missing inventory report headers")
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
|
||||
suggested = str(download.suggested_filename or "")
|
||||
suffix = Path(suggested).suffix or ".xlsx"
|
||||
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
|
||||
download.save_as(str(dest))
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
return dest
|
||||
|
||||
|
||||
@@ -3816,6 +3997,8 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic
|
||||
warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "WH")
|
||||
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
|
||||
download.save_as(str(dest))
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
return dest
|
||||
|
||||
|
||||
@@ -4509,6 +4692,7 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_configure_file_logging()
|
||||
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
|
||||
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
|
||||
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
|
||||
|
||||
Reference in new issue
Block a user