refactor(backend): 重构后端admin和schedule部分

This commit is contained in:
sophie committed 2026-07-01 13:34:29 +08:00
1 parent 9f5493185d
commit 4a14960e01
74 files changed
+5937 -3644

No files matched your search

@@ -0,0 +1,104 @@
"""
backend/app/services/schedule/import_service.py
用途:排程任务 JSON 批量导入(upsert by schedule_no)。
依赖:models、scheduler_service、sql_config。
逻辑:由 api/schedule/tasks.py import 路由调用。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ScheduleTask
from app.services.schedule.scheduler_service import create_task, update_task
from app.services.schedule.sql_config import upsert_schedule_task_config
def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None) -> dict[str, Any]:
"""
批量导入排程 JSON。
Args:
schedules: 导出文件中的 schedules 数组。
actor_id: 当前管理员 user id。
Returns:
ok、imported、skipped、errors(最多 20 条)。
Raises:
ValidationError: schedules 非 list。
"""
if not isinstance(schedules, list):
raise ValidationError('Invalid import file: schedules missing')
imported = 0
skipped = 0
errors: list[str] = []
for item in schedules:
if not isinstance(item, dict):
skipped += 1
continue
try:
name = str(item.get('name') or '').strip()
cron_expr = str(item.get('cron_expr') or '').strip()
owner_user_id = int(item.get('owner_user_id'))
if not name or not cron_expr:
raise ValueError('name or cron_expr missing')
existing = None
schedule_no = str(item.get('schedule_no') or '').strip()
if schedule_no:
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
task_payload = {
'name': name,
'schedule_type': str(item.get('schedule_type') or 'platform_app'),
'owner_user_id': owner_user_id,
'cron_expr': cron_expr,
'schedule_timezone': item.get('schedule_timezone'),
'wait_seconds': int(item.get('wait_seconds') or 0),
'dify_agent_id': item.get('dify_agent_id'),
'platform_api_path': item.get('platform_api_path'),
'notify_user_ids_json': item.get('notify_user_ids_json')
if isinstance(item.get('notify_user_ids_json'), list)
else [],
'notify_enabled': bool(item.get('notify_enabled', True)),
'enabled': bool(item.get('enabled', True)),
'data_source_type': str(item.get('data_source_type') or 'database'),
'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)),
'kb_group_id': item.get('kb_group_id'),
}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=actor_id)
existing.data_source_type = task_payload['data_source_type']
if cfg:
upsert_schedule_task_config(existing.id, cfg)
else:
task = create_task(
name=name,
schedule_type=task_payload['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=task_payload['schedule_timezone'],
wait_seconds=task_payload['wait_seconds'],
dify_agent_id=task_payload['dify_agent_id'],
platform_api_path=task_payload['platform_api_path'],
notify_user_ids_json=task_payload['notify_user_ids_json'],
notify_enabled=task_payload['notify_enabled'],
enabled=task_payload['enabled'],
actor_id=actor_id,
)
task.data_source_type = task_payload['data_source_type']
task.kb_sync_enabled = task_payload['kb_sync_enabled']
task.kb_group_id = (
int(task_payload['kb_group_id'])
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
else None
)
db.session.commit()
if cfg:
upsert_schedule_task_config(task.id, cfg)
imported += 1
except Exception as exc:
errors.append(str(exc))
skipped += 1
db.session.commit()
return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}
@@ -0,0 +1,22 @@
"""
backend/app/services/schedule/serialization.py
用途:排程域 JSON 序列化辅助(SQL 预览、测试跑结果)。
依赖:标准库 decimal/datetime。
逻辑:api/schedule/common 与 test_run_service 共用;不依赖 api 层。
"""
from __future__ import annotations
import decimal
from datetime import date, datetime, timedelta
def safe_json_value(value):
"""将 SQL 查询结果中的 Decimal/datetime 转为 JSON 可序列化类型。"""
if isinstance(value, decimal.Decimal):
return float(value)
if isinstance(value, (date, datetime)):
return value.isoformat()
if isinstance(value, timedelta):
return str(value)
return value
@@ -0,0 +1,55 @@
"""
backend/app/services/schedule/sql_preview_service.py
用途:排程抓取 SQL 预览(test-sql 业务编排)。
依赖:services/schedule、sql_config、srm_service。
逻辑:由 api/schedule/config.py 调用。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError, NotFoundError
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.serialization import safe_json_value
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id
def preview_fetch_sql(task_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
执行抓取 SQL 预览查询。
Args:
task_id: ScheduleTask 主键。
data: 可选 fetch_where_conditions、fetch_order_by、limit。
Returns:
total、showing、limit、sql、columns、rows。
Raises:
NotFoundError: 任务配置不存在。
AppError: SQL 执行失败。
"""
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
raise NotFoundError(f'Config for task {task_id} not found')
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
limit = min(int(data.get('limit') or 10), 100)
base = cfg.base_fetch_sql or cfg.fetch_sql
sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base
try:
if cfg.data_source and (not cfg.data_source.is_empty()):
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, sql)
result_rows = [{k: safe_json_value(v) for k, v in r.items()} for r in rows[:limit]]
return {
'total': len(rows),
'showing': len(result_rows),
'limit': limit,
'sql': sql,
'columns': list(result_rows[0].keys()) if result_rows else [],
'rows': result_rows,
}
except Exception as exc:
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=400, details={'sql': sql})
@@ -0,0 +1,293 @@
"""
backend/app/services/schedule/test_run_service.py
用途:排程 test-run 同步小规模试跑编排。
依赖:models、scheduler_service、excel_service、srm_service、kb_sync。
逻辑:由 api/schedule/config.py test-run 路由调用。
"""
from __future__ import annotations
import time as _time
import traceback
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.core.errors import AppError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.scheduler_service import _generate_test_run_no, _notify_schedule_run_wecom
from app.services.schedule.serialization import safe_json_value
from app.services.schedule.srm_service import (
_build_record_text,
_execute_writeback,
_fetch_records,
_run_check_job_loop,
)
from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id
def _parse_kb_sync_flag(raw_value: Any) -> bool:
if isinstance(raw_value, str):
return raw_value.strip().lower() in ('1', 'true', 'yes', 'on')
return bool(raw_value)
def _build_test_run_callbacks(cfg, test_sql: str):
"""构建 test-run 用的 fetch/writeback/pre_dify/build_record 回调。"""
def _test_fetch_fn(conn_str_arg):
return _fetch_records(conn_str_arg, test_sql)
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
test_pre_dify = None
test_build_record = None
if cfg.detail_sql:
def _test_pre_dify(conn_str_arg, item, row_id_value):
try:
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
except Exception as detail_exc:
return {
'dify_result': '人工判定',
'dify_message': f'查询成分明细失败:{detail_exc}',
'writeback_srm': False,
'writeback_err': str(detail_exc),
}
detail_lines = []
for dr in detail_rows:
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
detail_lines.append(', '.join(parts))
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
item['_detail_rows'] = detail_rows
return None
test_pre_dify = _test_pre_dify
def _test_build_with_detail(conn_str_arg, item, row_id_value):
detail_rows = item.get('_detail_rows', [])
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
return (text, item.get('attachment'))
test_build_record = _test_build_with_detail
else:
def _test_build_simple(conn_str_arg, item, row_id_value):
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
return (text, item.get('attachment'))
test_build_record = _test_build_simple
return _test_fetch_fn, _test_writeback_fn, test_pre_dify, test_build_record
def _finalize_run_status(total_count: int, success_count: int, failed_count: int, errors: list) -> str:
if total_count == 0 and (not errors):
return 'success'
if failed_count == 0:
return 'success'
if success_count == 0:
return 'failed'
return 'partial_failed'
def execute_test_run(
task_id: int,
data: dict[str, Any],
*,
triggered_by_user_id: int | None,
) -> dict[str, Any]:
"""
同步执行排程 test-run。
Args:
task_id: ScheduleTask 主键。
data: fetch_where/order、limit、kb_sync_enabled 等。
triggered_by_user_id: 触发用户 id。
Returns:
test-run API 响应 dict。
Raises:
NotFoundError: 任务或配置不存在。
AppError: 执行过程异常。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
raise NotFoundError(f'Config for task {task_id} not found')
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
limit = min(int(data.get('limit') or 3), 10)
test_kb_sync_enabled = _parse_kb_sync_flag(data.get('kb_sync_enabled', False))
base = cfg.base_fetch_sql or cfg.fetch_sql
test_sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base
if cfg.data_source and (not cfg.data_source.is_empty()):
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
agent = _resolve_dify_agent(task) if task else None
user = _resolve_schedule_user(task) if task else 'test_user'
wait_seconds = task.wait_seconds if task else 120
dify_agent_id = task.dify_agent_id if task else None
run = ScheduleRun(
run_no=_generate_test_run_no(),
schedule_task_id=task_id,
trigger_type='test',
triggered_by_user_id=triggered_by_user_id,
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
capture_dify_execution_snapshot(run, task)
db.session.commit()
if not cfg.fetch_sql:
run.status = 'success'
run.finished_at = datetime.utcnow()
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
db.session.commit()
return {
'run_no': run.run_no,
'run_id': run.id,
'sql': '',
'limit': 0,
'total_count': 0,
'success_count': 0,
'failed_count': 0,
'skipped_count': 0,
'details': [],
'errors': [],
'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}],
'dify_agent_id': dify_agent_id,
}
fetch_fn, writeback_fn, pre_dify_fn, build_record_fn = _build_test_run_callbacks(cfg, test_sql)
start_ts = _time.time()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
conn_str=conn_str,
run_no=run.run_no,
agent=agent,
user=user,
wait_seconds=wait_seconds,
run_id=run.id,
fetch_fn=fetch_fn,
build_record_fn=build_record_fn,
writeback_fn=writeback_fn,
writeback_sql=cfg.writeback_sql,
row_id_key=cfg.row_id_key,
log_prefix=cfg.log_prefix,
fetch_sql=test_sql,
max_rows=limit,
pre_dify_fn=pre_dify_fn,
dify_system_prompt=cfg.dify_system_prompt,
)
duration_ms = int((_time.time() - start_ts) * 1000)
status = _finalize_run_status(total_count, success_count, failed_count, errors)
header_order = cfg.alias_order if cfg.alias_order else None
header_labels = cfg.header_labels if cfg.header_labels else None
detail_alias_order = cfg.detail_alias_order or []
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,
detail_alias_order=detail_alias_order,
)
except Exception as excel_exc:
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
file_data, file_name, file_size = (None, None, 0)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = status
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None
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
db.session.commit()
if test_kb_sync_enabled:
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, enabled=True, process_inline=True)
db.session.refresh(run)
except Exception as kb_exc:
db.session.rollback()
db.session.refresh(run)
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
run.kb_sync_status = 'failed'
run.kb_group_id = getattr(task, 'kb_group_id', None)
run.kb_sync_error = str(kb_exc)
db.session.commit()
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
safe_details = [{k: safe_json_value(v) for k, v in item.items()} for item in details]
return {
'run_no': run.run_no,
'run_id': run.id,
'sql': test_sql,
'limit': limit,
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
'details': safe_details,
'errors': errors,
'step_logs': step_logs,
'dify_agent_id': dify_agent_id,
'dify_execution_snapshot': run.dify_execution_snapshot,
'kb_sync_status': run.kb_sync_status,
'kb_sync_error': run.kb_sync_error,
'kb_document_id': run.kb_document_id,
}
except Exception as exc:
db.session.rollback()
run = db.session.get(ScheduleRun, run.id)
duration_ms = int((_time.time() - start_ts) * 1000)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = 'failed'
run.error_message = str(exc)
db.session.commit()
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=str(exc),
http_status=400,
details={'sql': test_sql, 'traceback': traceback.format_exc()},
)