fix: 统一异常处理

This commit is contained in:
sophie committed 2026-05-30 17:06:32 +08:00
1 parent 4daf8dfcaa
commit 0c5cfcaa4a
21 files changed
+2124 -4218

No files matched your search

+180 -652
View File
File diff suppressed because it is too large. Load diff
+128 -421
View File
File diff suppressed because it is too large. Load diff
+30 -194
View File
@@ -3,136 +3,59 @@ backend/app/api/integration.py
文件用途:知识库外部集成查询接口
"""
from __future__ import annotations
from pathlib import Path
from flask import Blueprint, abort, current_app, jsonify, request, send_file
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from app import db
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
integration_bp = Blueprint('integration', __name__)
def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
if not configured:
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
if configured != incoming:
return jsonify({'error': 'Unauthorized'}), 401
raise UnauthorizedError('Unauthorized')
return None
def _integration_base_url() -> str:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
return explicit
return request.host_url.rstrip('/')
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
return None
return next((item for item in versions if item.is_current), versions[0])
def _document_query():
return (
db.session.query(KbDocument)
.options(
joinedload(KbDocument.group),
joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records),
)
.filter(KbDocument.is_deleted.is_(False))
)
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
def _serialize_integration_document(
document: KbDocument,
*,
version: KbDocumentVersion | None = None,
sync_record: KbDifySyncRecord | None = None,
):
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
version = version or _current_version(document)
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (
next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None)
or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)
)
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
base_url = _integration_base_url()
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
markdown_download_url = (
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
if version.cleaned_file_path or version.cleaned_preview_path
else None
)
return {
'document_id': document.id,
'knowledge_base': {
'id': document.group.id if document.group else None,
'name': document.group.name if document.group else None,
'department_id': document.group.department_id if document.group else None,
'dify_dataset_id': document.group.dify_dataset_id if document.group else None,
},
'title': document.title,
'source_filename': version.source_file_name,
'source_ext': version.source_file_ext,
'file_name': version.source_file_name,
'version_id': version.id,
'version_no': version.version_no,
'convert_status': version.status,
'sync_status': sync_record.status if sync_record else None,
'uploaded_at': version.created_at.isoformat() if version.created_at else None,
'converted_at': version.converted_at.isoformat() if version.converted_at else None,
'download_url_expires_at': None,
'source_download_url': source_download_url,
'markdown_download_url': markdown_download_url,
'markdown_download_url_expires_at': None,
'markdown_public_url': markdown_download_url,
'dify': {
'dataset_id': sync_record.dataset_id if sync_record else (document.group.dify_dataset_id if document.group else None),
'remote_document_id': sync_record.remote_document_id if sync_record else None,
'status': sync_record.status if sync_record else None,
'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None,
},
}
markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
return {
'id': group.id,
'knowledge_base_id': group.id,
'name': group.name,
'description': group.description,
'department_id': group.department_id,
'dify_dataset_id': group.dify_dataset_id,
'document_count': int(document_count or 0),
'created_at': group.created_at.isoformat() if group.created_at else None,
'updated_at': group.updated_at.isoformat() if group.updated_at else None,
}
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
def _list_files_payload(
*,
knowledge_base_id: int | None = None,
department_id: int | None = None,
file_name: str | None = None,
) -> list[dict]:
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
normalized_file_name = str(file_name or '').strip().lower()
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
if knowledge_base_id is not None:
query = query.filter(KbDocument.group_id == knowledge_base_id)
if department_id is not None:
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
documents = query.all()
payload = []
for document in documents:
@@ -140,25 +63,22 @@ def _list_files_payload(
if not version:
continue
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower():
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
continue
payload.append(_serialize_integration_document(document, version=version))
return payload
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
if kind == 'source':
path = Path(version.source_file_path)
filename = version.source_file_name or f'document-{version.document_id}'
return path, filename
return (path, filename)
preferred = version.cleaned_file_path or version.cleaned_preview_path
if not preferred:
abort(409, description='Markdown not ready.')
path = Path(preferred)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return path, filename
return (path, filename)
@integration_bp.before_request
def _verify_integration_access():
@@ -167,138 +87,66 @@ def _verify_integration_access():
return result
return None
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
def get_file_detail(file_id: int):
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
raise NotFoundError('Document not found.')
return jsonify(_serialize_integration_document(document))
@integration_bp.route('/knowledge-bases', methods=['GET'])
def list_knowledge_bases():
department_id = request.args.get('department_id', type=int)
q = str(request.args.get('q') or '').strip()
document_counts = (
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
.filter(KbDocument.is_deleted.is_(False))
.group_by(KbDocument.group_id)
.subquery()
)
query = (
db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
.filter(KbGroup.is_active.is_(True))
.order_by(KbGroup.name.asc())
)
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
if department_id is not None:
query = query.filter(KbGroup.department_id == department_id)
if q:
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
rows = query.all()
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
@integration_bp.route('/files', methods=['GET'])
def list_files():
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
department_id = request.args.get('department_id', type=int)
file_name = request.args.get('file_name')
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
department_id=department_id,
file_name=file_name,
)})
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
def list_files_for_knowledge_base(knowledge_base_id: int):
return jsonify({'data': _list_files_payload(
knowledge_base_id=knowledge_base_id,
file_name=request.args.get('file_name'),
)})
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
@integration_bp.route('/dify-file', methods=['GET'])
def get_file_detail_by_dify():
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
if not remote_document_id:
return jsonify({'error': 'remote_document_id is required'}), 400
record_query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
raise ValidationError('remote_document_id is required')
record_query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
if dataset_id:
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
record = record_query.first()
version = record.document_version if record else None
document = version.document if version else None
if not document:
return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404
raise NotFoundError('No local file mapping found for the given Dify document.')
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
@integration_bp.route('/dify-files/resolve', methods=['POST'])
def resolve_files_by_dify():
data = request.get_json(silent=True) or {}
items = data.get('items') if isinstance(data.get('items'), list) else []
if not items:
return jsonify({'data': []})
remote_ids = sorted({
str(item.get('remote_document_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()
})
dataset_ids = sorted({
str(item.get('dataset_id') or '').strip()
for item in items
if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()
})
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
if not remote_ids:
return jsonify({'data': []})
query = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(
joinedload(KbDifySyncRecord.document_version)
.joinedload(KbDocumentVersion.document)
.joinedload(KbDocument.group),
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id.in_(remote_ids),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
)
query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
if dataset_ids:
query = query.filter(
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
)
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
records = query.all()
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
records_by_remote: dict[str, KbDifySyncRecord] = {}
@@ -306,7 +154,6 @@ def resolve_files_by_dify():
key = (record.dataset_id, record.remote_document_id)
records_by_key.setdefault(key, record)
records_by_remote.setdefault(record.remote_document_id, record)
payload = []
for item in items:
if not isinstance(item, dict):
@@ -320,30 +167,19 @@ def resolve_files_by_dify():
record = records_by_remote.get(requested_remote_document_id)
version = record.document_version if record else None
document = version.document if version else None
payload.append({
'request': {
'dataset_id': requested_dataset_id,
'remote_document_id': requested_remote_document_id,
},
'found': bool(document),
'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None,
})
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
return jsonify({'data': payload})
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
def download_file(file_id: int):
kind = str(request.args.get('kind') or 'md').strip().lower()
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return jsonify({'error': 'Document not found.'}), 404
raise NotFoundError('Document not found.')
version = _current_version(document)
if not version:
return jsonify({'error': 'No version found.'}), 404
raise NotFoundError('No version found.')
path, filename = _resolve_download_path(version, kind)
if not path.exists():
return jsonify({'error': 'File not found on disk.'}), 404
return send_file(path, as_attachment=True, download_name=filename)
raise NotFoundError('File not found on disk.')
return send_file(path, as_attachment=True, download_name=filename)
+10 -43
View File
@@ -1,71 +1,49 @@
from __future__ import annotations
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _run_generic_check_job
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
run_no = str(data.get("run_no") or "").strip()
schedule_task_id = data.get("schedule_task_id")
run_no = str(data.get('run_no') or '').strip()
schedule_task_id = data.get('schedule_task_id')
task = None
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if not task and key.isdigit():
task = db.session.get(ScheduleTask, int(key))
if not task:
task = ScheduleTask.query.filter(
ScheduleTask.platform_api_path.ilike(f"%{key}%")
).first()
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
if not task:
return jsonify({"error": f"No schedule task found for '{name}'"}), 404
raise NotFoundError(f"No schedule task found for '{name}'")
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no).first()
if not run:
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
except Exception as exc:
run.status = "failed"
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
return jsonify({
"error": str(exc),
"traceback": traceback.format_exc(),
"summary": {"total_count": 0, "success_count": 0, "failed_count": 0, "skipped_count": 0},
}), 500
run.status = "success" if failed_count == 0 else ("failed" if success_count == 0 else "partial_failed")
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}})
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
@@ -75,15 +53,4 @@ def run_internal_job(name: str):
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
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,
})
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})
File diff suppressed because it is too large. Load diff
+80 -321
View File
@@ -1,138 +1,83 @@
from __future__ import annotations
import threading
from datetime import datetime
from flask import Blueprint, current_app, jsonify, request, send_file
from flask import Response
from io import BytesIO
import json
from app.decorators import require_admin
from app import db
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.auth_jwt import get_current_user
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
from app.services.schedule.scheduler_service import (
create_task,
run_task_now,
update_task,
_generate_run_no,
_generate_test_run_no,
_notify_schedule_run_wecom,
)
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
from app.services.schedule.srm_service import _fetch_records
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
schedule_admin_bp = Blueprint('schedule_admin', __name__)
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
payload = serialize_task(task)
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
return payload
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
return {
"row_id_key": cfg_model.row_id_key or "id",
"log_prefix": cfg_model.log_prefix or "",
"base_fetch_sql": cfg_model.base_fetch_sql or "",
"fetch_where_conditions": cfg_model.fetch_where_conditions or "",
"fetch_order_by": cfg_model.fetch_order_by or "",
"writeback_sql": cfg_model.writeback_sql or "",
"detail_sql": cfg_model.detail_sql or "",
"alias_order": cfg_model.alias_order or [],
"detail_alias_order": cfg_model.detail_alias_order or [],
"header_labels": cfg_model.header_labels or {},
"data_source": {
"db_type": cfg_model.ds_db_type or "sqlserver",
"host": cfg_model.ds_host or "",
"port": cfg_model.ds_port or "",
"database": cfg_model.ds_database or "",
"username": cfg_model.ds_username or "",
"password": cfg_model.ds_password or "",
"driver": cfg_model.ds_driver or "",
"encrypt": cfg_model.ds_encrypt or "",
"trust_cert": cfg_model.ds_trust_cert or "",
},
"external_api": {
"url": cfg_model.api_url or "",
"method": cfg_model.api_method or "POST",
"headers": cfg_model.api_headers or {},
"body_template": cfg_model.api_body_template or "",
},
"dify_system_prompt": cfg_model.dify_system_prompt or "",
}
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
@require_admin
def get_schedule_task_config(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if not cfg_model:
return jsonify({
"data_source_type": task.data_source_type,
"config": None,
})
return jsonify({
"data_source_type": task.data_source_type,
"config": _serialize_task_config(cfg_model),
})
return jsonify({'data_source_type': task.data_source_type, 'config': None})
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
@require_admin
def update_schedule_task_config(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
if "data_source_type" in data:
task.data_source_type = str(data["data_source_type"])
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
config_data = data.get("config", data)
config_data = data.get('config', data)
cfg = upsert_schedule_task_config(task_id, config_data)
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,
})
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
except Exception as e:
db.session.rollback()
return jsonify({"error": str(e)}), 400
raise ValidationError(str(e))
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
@require_admin
def test_schedule_sql(task_id: int):
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
return jsonify({"error": f"Config for task {task_id} not found"}), 404
raise NotFoundError(f'Config for task {task_id} not found')
data = request.get_json(silent=True) or {}
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)
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
if cfg.base_fetch_sql:
sql = _build_fetch_sql(base, custom_where, custom_order_by)
else:
sql = base
try:
from app.services.schedule import _build_srm_conn_str
import decimal, datetime
if cfg.data_source and not cfg.data_source.is_empty():
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)
def _safe(v):
if isinstance(v, decimal.Decimal):
return float(v)
@@ -142,75 +87,46 @@ def test_schedule_sql(task_id: int):
return str(v)
return v
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
return jsonify({
"total": len(rows),
"showing": len(result_rows),
"limit": limit,
"sql": sql,
"columns": list(result_rows[0].keys()) if result_rows else [],
"rows": result_rows,
})
return jsonify({'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 e:
return jsonify({"error": str(e), "sql": sql}), 400
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
@require_admin
def test_schedule_run(task_id: int):
import time as _time
from app.services.schedule.excel_service import export_schedule_result_excel
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
return jsonify({"error": f"Config for task {task_id} not found"}), 404
raise NotFoundError(f'Config for task {task_id} not found')
data = request.get_json(silent=True) or {}
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)
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)
base = cfg.base_fetch_sql or cfg.fetch_sql
if cfg.base_fetch_sql:
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
else:
test_sql = base
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
from app.services.schedule.srm_service import (
_fetch_records,
_run_check_job_loop,
_build_record_text,
_execute_writeback,
)
if cfg.data_source and not cfg.data_source.is_empty():
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
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"
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=getattr(get_current_user(), 'id', None),
started_at=datetime.utcnow(),
status='running',
)
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), 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()
@@ -219,86 +135,49 @@ def test_schedule_run(task_id: int):
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)
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
db.session.commit()
return jsonify({
"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,
})
return jsonify({'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})
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),
}
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
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", [])
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")
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")
return (text, item.get('attachment'))
test_build_record = _test_build_simple
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=_test_fetch_fn,
build_record_fn=test_build_record,
writeback_fn=_test_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=test_pre_dify,
dify_system_prompt=cfg.dify_system_prompt,
)
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=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_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=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
duration_ms = int((_time.time() - start_ts) * 1000)
if total_count == 0 and not errors:
if total_count == 0 and (not errors):
status = 'success'
elif failed_count == 0:
status = 'success'
@@ -306,22 +185,13 @@ def test_schedule_run(task_id: int):
status = 'failed'
else:
status = 'partial_failed'
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,
)
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:
file_data, file_name, file_size = None, None, 0
file_data, file_name, file_size = (None, None, 0)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = status
@@ -330,7 +200,7 @@ def test_schedule_run(task_id: int):
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.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
@@ -338,10 +208,10 @@ def test_schedule_run(task_id: int):
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)
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
db.session.commit()
import decimal, datetime as dt
def _safe(v):
if isinstance(v, decimal.Decimal):
return float(v)
@@ -350,27 +220,11 @@ def test_schedule_run(task_id: int):
if isinstance(v, dt.timedelta):
return str(v)
return v
safe_details = []
for item in details:
safe_item = {k: _safe(v) for k, v in item.items()}
safe_details.append(safe_item)
return jsonify({
"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,
})
return jsonify({'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})
except Exception as e:
duration_ms = int((_time.time() - start_ts) * 1000)
run.finished_at = datetime.utcnow()
@@ -379,35 +233,24 @@ def test_schedule_run(task_id: int):
run.error_message = str(e)
db.session.commit()
import traceback
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
@schedule_admin_bp.route('/schedules', methods=['GET'])
@require_admin
def get_schedules():
return jsonify(list_tasks())
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
@require_admin
def export_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
payload = {
"schema_version": 1,
"exported_at": datetime.utcnow().isoformat(),
"schedules": [_serialize_task_for_export(task, cfg_model)],
}
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
body = json.dumps(payload, ensure_ascii=False, indent=2)
filename = f"{(task.schedule_no or f'schedule_{task.id}')}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
return Response(
body,
mimetype='application/json; charset=utf-8',
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
)
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
@require_admin
@@ -415,13 +258,11 @@ def import_schedules():
data = request.get_json(silent=True) or {}
schedules = data.get('schedules')
if not isinstance(schedules, list):
return jsonify({'error': 'Invalid import file: schedules missing'}), 400
raise ValidationError('Invalid import file: schedules missing')
user = get_current_user()
imported = 0
skipped = 0
errors: list[str] = []
for item in schedules:
if not isinstance(item, dict):
skipped += 1
@@ -432,46 +273,19 @@ def import_schedules():
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,
'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'),
}
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, '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')}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
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,
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=getattr(user, 'id', None),
)
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, 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=getattr(user, 'id', None))
task.data_source_type = task_payload['data_source_type']
db.session.commit()
if cfg:
@@ -480,15 +294,8 @@ def import_schedules():
except Exception as exc:
errors.append(str(exc))
skipped += 1
db.session.commit()
return jsonify({
'ok': True,
'imported': imported,
'skipped': skipped,
'errors': errors[:20],
})
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
@schedule_admin_bp.route('/schedules', methods=['POST'])
@require_admin
@@ -496,24 +303,11 @@ def post_schedule():
data = request.get_json(silent=True) or {}
user = get_current_user()
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type='platform_app',
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=(int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None),
platform_api_path=str(data.get('platform_api_path') or '').strip() or None,
notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
actor_id=getattr(user, 'id', None),
)
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
task.data_source_type = data_source_type
task.platform_api_path = f"/{task.id}"
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task.id, config_data)
@@ -522,79 +316,64 @@ def post_schedule():
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
return jsonify(serialize_task(task)), 201
return (jsonify(serialize_task(task)), 201)
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
@require_admin
def get_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
return jsonify(serialize_task(task))
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
@require_admin
def patch_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
user = get_current_user()
if "data_source_type" in data:
task.data_source_type = str(data["data_source_type"])
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task_id, config_data)
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
if not task.dify_agent_id:
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()
return jsonify(serialize_task(task))
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
@require_admin
def delete_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
from app.services.schedule.scheduler_service import request_cancel_run
running_runs = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task_id,
ScheduleRun.status == "running",
).all()
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
for rr in running_runs:
request_cancel_run(rr.id)
rr.status = "failed"
rr.error_message = "排程已被删除,执行中断"
rr.status = 'failed'
rr.error_message = '排程已被删除,执行中断'
rr.finished_at = datetime.utcnow()
if running_runs:
db.session.commit()
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
db.session.delete(task)
db.session.commit()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
@require_admin
def enable_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
task.enabled = True
if task.cron_expr:
try:
@@ -606,44 +385,29 @@ def enable_schedule(task_id: int):
db.session.commit()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
@require_admin
def disable_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
task.enabled = False
db.session.commit()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@require_admin
def run_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
user = get_current_user()
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
if existing:
return jsonify({'error': '该排程正在执行中,请等待完成后再试', 'run_id': existing.id}), 409
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type='manual',
triggered_by_user_id=getattr(user, 'id', None),
started_at=datetime.utcnow(),
status='running',
)
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
db.session.add(run)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
@@ -665,15 +429,12 @@ def run_schedule(task_id: int):
db.session.commit()
except Exception:
db.session.rollback()
current_app.logger.error("[schedule-run] run_id=%s failed: %s", run_id, exc, exc_info=True)
t = threading.Thread(target=_background, daemon=True, name=f"schedule-run-{run_id}")
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
t.start()
fresh = db.session.get(ScheduleRun, run_id)
return jsonify(serialize_run(fresh))
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
@require_admin
def get_schedule_runs(task_id: int):
@@ -695,24 +456,22 @@ def get_schedule_runs(task_id: int):
pass
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
@require_admin
def get_schedule_run(run_id: int):
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
return jsonify(serialize_run(run))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
@require_admin
def get_schedule_run_excel(run_id: int):
from io import BytesIO
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
if not run.excel_file_data:
return jsonify({'error': 'Excel not found'}), 404
raise NotFoundError('Excel not found')
buf = BytesIO(run.excel_file_data)
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
+244 -1049
View File
File diff suppressed because it is too large. Load diff
+13 -33
View File
@@ -1,27 +1,20 @@
from __future__ import annotations
from datetime import datetime
from flask import Blueprint, jsonify, request, send_file
from app.auth_jwt import get_current_user
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
def _require_user():
user = get_current_user()
if not user:
return None, (jsonify({'error': 'Unauthorized'}), 401)
return user, None
raise UnauthorizedError()
return user
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
def workspace_schedule_runs():
user, err = _require_user()
if err:
return err
user = _require_user()
status = str(request.args.get('status') or '').strip() or None
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
started_after_str = request.args.get('started_after')
@@ -29,41 +22,28 @@ def workspace_schedule_runs():
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
limit = int(request.args.get('limit') or 100)
return jsonify(list_runs(
notify_user_id=user.id,
schedule_name=schedule_name,
status=status,
started_after=started_after,
started_before=started_before,
limit=limit,
))
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
def workspace_schedule_run_detail(run_id: int):
user, err = _require_user()
if err:
return err
user = _require_user()
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
if not can_view_run(run, user.id):
return jsonify({'error': 'Forbidden'}), 403
raise ForbiddenError('Forbidden')
return jsonify(serialize_run(run))
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
def workspace_schedule_run_excel(run_id: int):
from io import BytesIO
user, err = _require_user()
if err:
return err
user = _require_user()
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
raise NotFoundError('Not found')
if not can_view_run(run, user.id):
return jsonify({'error': 'Forbidden'}), 403
raise ForbiddenError('Forbidden')
if not run.excel_file_data:
return jsonify({'error': 'Excel not found'}), 404
raise NotFoundError('Excel not found')
buf = BytesIO(run.excel_file_data)
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')