Merge branch 'dev' into test
This commit is contained in:
commit
abd200c735
10 files changed
+194
-76
No files matched your search
@@ -10,7 +10,7 @@ from app import db
|
|||||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||||
from app.auth_jwt import get_current_user
|
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.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
|
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no
|
||||||
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.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.services.schedule.srm_service import _fetch_records
|
||||||
|
|
||||||
@@ -140,6 +140,9 @@ def test_schedule_sql(task_id: int):
|
|||||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def test_schedule_run(task_id: int):
|
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)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
return jsonify({'error': 'Not found'}), 404
|
||||||
@@ -176,10 +179,25 @@ def test_schedule_run(task_id: int):
|
|||||||
wait_seconds = task.wait_seconds if task else 120
|
wait_seconds = task.wait_seconds if task else 120
|
||||||
dify_agent_id = task.dify_agent_id if task else None
|
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',
|
||||||
|
)
|
||||||
|
db.session.add(run)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
if not cfg.fetch_sql:
|
if not cfg.fetch_sql:
|
||||||
run_no = f"TEST{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
run.status = 'success'
|
||||||
|
run.finished_at = datetime.utcnow()
|
||||||
|
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||||
|
db.session.commit()
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"run_no": run_no,
|
"run_no": run.run_no,
|
||||||
|
"run_id": run.id,
|
||||||
"sql": "",
|
"sql": "",
|
||||||
"limit": 0,
|
"limit": 0,
|
||||||
"total_count": 0,
|
"total_count": 0,
|
||||||
@@ -222,7 +240,7 @@ def test_schedule_run(task_id: int):
|
|||||||
test_pre_dify = _test_pre_dify
|
test_pre_dify = _test_pre_dify
|
||||||
|
|
||||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||||
detail_rows = item.pop("_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)
|
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
|
test_build_record = _test_build_with_detail
|
||||||
@@ -232,16 +250,15 @@ def test_schedule_run(task_id: int):
|
|||||||
return text, item.get("attachment")
|
return text, item.get("attachment")
|
||||||
test_build_record = _test_build_simple
|
test_build_record = _test_build_simple
|
||||||
|
|
||||||
run_no = f"TEST{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
start_ts = _time.time()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
|
||||||
conn_str=conn_str,
|
conn_str=conn_str,
|
||||||
run_no=run_no,
|
run_no=run.run_no,
|
||||||
agent=agent,
|
agent=agent,
|
||||||
user=user,
|
user=user,
|
||||||
wait_seconds=wait_seconds,
|
wait_seconds=wait_seconds,
|
||||||
run_id=None,
|
run_id=run.id,
|
||||||
fetch_fn=_test_fetch_fn,
|
fetch_fn=_test_fetch_fn,
|
||||||
build_record_fn=test_build_record,
|
build_record_fn=test_build_record,
|
||||||
writeback_fn=_test_writeback_fn,
|
writeback_fn=_test_writeback_fn,
|
||||||
@@ -253,6 +270,45 @@ def test_schedule_run(task_id: int):
|
|||||||
pre_dify_fn=test_pre_dify,
|
pre_dify_fn=test_pre_dify,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||||
|
if total_count == 0 and not errors:
|
||||||
|
status = 'success'
|
||||||
|
elif failed_count == 0:
|
||||||
|
status = 'success'
|
||||||
|
elif success_count == 0:
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
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()
|
||||||
|
|
||||||
import decimal, datetime as dt
|
import decimal, datetime as dt
|
||||||
def _safe(v):
|
def _safe(v):
|
||||||
if isinstance(v, decimal.Decimal):
|
if isinstance(v, decimal.Decimal):
|
||||||
@@ -269,7 +325,8 @@ def test_schedule_run(task_id: int):
|
|||||||
safe_details.append(safe_item)
|
safe_details.append(safe_item)
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"run_no": run_no,
|
"run_no": run.run_no,
|
||||||
|
"run_id": run.id,
|
||||||
"sql": test_sql,
|
"sql": test_sql,
|
||||||
"limit": limit,
|
"limit": limit,
|
||||||
"total_count": total_count,
|
"total_count": total_count,
|
||||||
@@ -282,6 +339,12 @@ def test_schedule_run(task_id: int):
|
|||||||
"dify_agent_id": dify_agent_id,
|
"dify_agent_id": dify_agent_id,
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
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(e)
|
||||||
|
db.session.commit()
|
||||||
import traceback
|
import traceback
|
||||||
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
|
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
|
||||||
|
|
||||||
@@ -373,16 +436,6 @@ def delete_schedule(task_id: int):
|
|||||||
if running_runs:
|
if running_runs:
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).all()
|
|
||||||
for r in runs:
|
|
||||||
if r.excel_file_path:
|
|
||||||
try:
|
|
||||||
from pathlib import Path
|
|
||||||
p = Path(r.excel_file_path)
|
|
||||||
if p.exists():
|
|
||||||
p.unlink()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||||
db.session.delete(task)
|
db.session.delete(task)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -508,9 +561,11 @@ def get_schedule_run(run_id: int):
|
|||||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule_run_excel(run_id: int):
|
def get_schedule_run_excel(run_id: int):
|
||||||
|
from io import BytesIO
|
||||||
run = get_run(run_id)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
return jsonify({'error': 'Not found'}), 404
|
||||||
if not run.excel_file_path:
|
if not run.excel_file_data:
|
||||||
return jsonify({'error': 'Excel not found'}), 404
|
return jsonify({'error': 'Excel not found'}), 404
|
||||||
return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx')
|
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')
|
||||||
@@ -54,6 +54,7 @@ def workspace_schedule_run_detail(run_id: int):
|
|||||||
|
|
||||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||||
def workspace_schedule_run_excel(run_id: int):
|
def workspace_schedule_run_excel(run_id: int):
|
||||||
|
from io import BytesIO
|
||||||
user, err = _require_user()
|
user, err = _require_user()
|
||||||
if err:
|
if err:
|
||||||
return err
|
return err
|
||||||
@@ -62,6 +63,7 @@ def workspace_schedule_run_excel(run_id: int):
|
|||||||
return jsonify({'error': 'Not found'}), 404
|
return jsonify({'error': 'Not found'}), 404
|
||||||
if not can_view_run(run, user.id):
|
if not can_view_run(run, user.id):
|
||||||
return jsonify({'error': 'Forbidden'}), 403
|
return jsonify({'error': 'Forbidden'}), 403
|
||||||
if not run.excel_file_path:
|
if not run.excel_file_data:
|
||||||
return jsonify({'error': 'Excel not found'}), 404
|
return jsonify({'error': 'Excel not found'}), 404
|
||||||
return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx')
|
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')
|
||||||
@@ -152,10 +152,6 @@ class Config:
|
|||||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||||
SCHEDULE_EXCEL_STORAGE_ROOT = os.getenv(
|
|
||||||
'SCHEDULE_EXCEL_STORAGE_ROOT',
|
|
||||||
str(_BACKEND_DIR / 'data' / 'schedules'),
|
|
||||||
)
|
|
||||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint
|
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
from app import db
|
from app import db
|
||||||
from werkzeug.security import generate_password_hash, check_password_hash
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
@@ -645,7 +645,7 @@ class ScheduleRun(Base):
|
|||||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
excel_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||||
mail_sent: Mapped[bool] = mapped_column(Boolean, default=False)
|
mail_sent: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
|||||||
@@ -233,7 +233,7 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
|
|||||||
pre_dify_fn = _pre_dify
|
pre_dify_fn = _pre_dify
|
||||||
|
|
||||||
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||||
detail_rows = item.pop("_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)
|
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")
|
||||||
build_record_fn = _build_with_detail
|
build_record_fn = _build_with_detail
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
@@ -13,75 +13,101 @@ def _flatten_value(v: Any) -> Any:
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
_EXPORT_SKIP_KEYS = {"dify_output", "json_output", "output", "_detail_rows", "detail_text"}
|
||||||
|
|
||||||
|
|
||||||
def export_schedule_result_excel(
|
def export_schedule_result_excel(
|
||||||
*,
|
*,
|
||||||
run_no: str,
|
run_no: str,
|
||||||
summary: dict,
|
summary: dict,
|
||||||
details: list[dict],
|
details: list[dict],
|
||||||
root_dir: str,
|
|
||||||
header_order: list[str] | None = None,
|
header_order: list[str] | None = None,
|
||||||
header_labels: dict[str, str] | None = None,
|
header_labels: dict[str, str] | None = None,
|
||||||
) -> tuple[str | None, str | None, int]:
|
detail_alias_order: list[str] | None = None,
|
||||||
|
) -> tuple[bytes | None, str | None, int]:
|
||||||
if not details:
|
if not details:
|
||||||
return None, None, 0
|
return None, None, 0
|
||||||
|
|
||||||
out_root = Path(root_dir)
|
|
||||||
out_root.mkdir(parents=True, exist_ok=True)
|
|
||||||
|
|
||||||
header_order = header_order or []
|
header_order = header_order or []
|
||||||
header_labels = header_labels or {}
|
header_labels = header_labels or {}
|
||||||
|
detail_alias_order = detail_alias_order or []
|
||||||
|
|
||||||
rows: list[dict[str, Any]] = []
|
|
||||||
sql_headers: list[str] = []
|
|
||||||
json_headers: list[str] = []
|
|
||||||
exec_result_headers: list[str] = []
|
|
||||||
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
|
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
|
||||||
|
|
||||||
|
sql_headers: list[str] = []
|
||||||
|
detail_headers: list[str] = []
|
||||||
|
exec_result_headers: list[str] = []
|
||||||
|
|
||||||
def _append_unique(target: list[str], key: str) -> None:
|
def _append_unique(target: list[str], key: str) -> None:
|
||||||
if key not in target:
|
if key not in target:
|
||||||
target.append(key)
|
target.append(key)
|
||||||
|
|
||||||
def _collect_json_headers(obj: Any) -> None:
|
|
||||||
if isinstance(obj, dict):
|
|
||||||
for k in obj.keys():
|
|
||||||
_append_unique(json_headers, str(k))
|
|
||||||
|
|
||||||
for row in details:
|
for row in details:
|
||||||
if not isinstance(row, dict):
|
if not isinstance(row, dict):
|
||||||
continue
|
continue
|
||||||
|
for k in row.keys():
|
||||||
flat_row: dict[str, Any] = {}
|
|
||||||
for k, v in row.items():
|
|
||||||
key = str(k)
|
key = str(k)
|
||||||
if key in {"dify_output", "json_output", "output"}:
|
if key in _EXPORT_SKIP_KEYS:
|
||||||
_collect_json_headers(v)
|
|
||||||
if isinstance(v, dict):
|
|
||||||
for json_key, json_val in v.items():
|
|
||||||
flat_row[str(json_key)] = _flatten_value(json_val)
|
|
||||||
continue
|
continue
|
||||||
flat_row[key] = _flatten_value(v)
|
|
||||||
if key in exec_result_order:
|
if key in exec_result_order:
|
||||||
_append_unique(exec_result_headers, key)
|
_append_unique(exec_result_headers, key)
|
||||||
else:
|
else:
|
||||||
_append_unique(sql_headers, key)
|
_append_unique(sql_headers, key)
|
||||||
|
detail_rows = row.get("_detail_rows")
|
||||||
|
if isinstance(detail_rows, list):
|
||||||
|
for dr in detail_rows:
|
||||||
|
if isinstance(dr, dict):
|
||||||
|
for dk in dr.keys():
|
||||||
|
_append_unique(detail_headers, str(dk))
|
||||||
|
|
||||||
rows.append(flat_row)
|
|
||||||
|
|
||||||
if not rows:
|
|
||||||
return None, None, 0
|
|
||||||
|
|
||||||
ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers]
|
|
||||||
other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order]
|
|
||||||
ordered_sql_headers = [k for k in header_order if k in sql_headers]
|
ordered_sql_headers = [k for k in header_order if k in sql_headers]
|
||||||
other_sql_headers = [k for k in sql_headers if k not in header_order]
|
other_sql_headers = [k for k in sql_headers if k not in header_order]
|
||||||
|
ordered_detail_headers = [k for k in detail_alias_order if k in detail_headers]
|
||||||
|
other_detail_headers = [k for k in detail_headers if k not in detail_alias_order]
|
||||||
|
ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers]
|
||||||
|
other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order]
|
||||||
|
|
||||||
|
all_detail_headers = ordered_detail_headers + other_detail_headers
|
||||||
|
|
||||||
headers = (
|
headers = (
|
||||||
ordered_sql_headers
|
ordered_sql_headers
|
||||||
+ other_sql_headers
|
+ other_sql_headers
|
||||||
+ [k for k in json_headers if k not in sql_headers and k not in exec_result_headers]
|
+ all_detail_headers
|
||||||
+ ordered_exec_headers
|
+ ordered_exec_headers
|
||||||
+ other_exec_headers
|
+ other_exec_headers
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if not headers:
|
||||||
|
return None, None, 0
|
||||||
|
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
for row in details:
|
||||||
|
if not isinstance(row, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
base_row: dict[str, Any] = {}
|
||||||
|
for k, v in row.items():
|
||||||
|
key = str(k)
|
||||||
|
if key in _EXPORT_SKIP_KEYS:
|
||||||
|
continue
|
||||||
|
if key in {"dify_output", "json_output", "output"}:
|
||||||
|
if isinstance(v, dict):
|
||||||
|
for json_key, json_val in v.items():
|
||||||
|
base_row[str(json_key)] = _flatten_value(json_val)
|
||||||
|
continue
|
||||||
|
base_row[key] = _flatten_value(v)
|
||||||
|
|
||||||
|
detail_rows = row.get("_detail_rows")
|
||||||
|
if all_detail_headers and isinstance(detail_rows, list) and detail_rows:
|
||||||
|
for dr in detail_rows:
|
||||||
|
flat = dict(base_row)
|
||||||
|
if isinstance(dr, dict):
|
||||||
|
for dk in all_detail_headers:
|
||||||
|
flat[dk] = dr.get(dk, "")
|
||||||
|
rows.append(flat)
|
||||||
|
else:
|
||||||
|
rows.append(base_row)
|
||||||
|
|
||||||
wb = Workbook()
|
wb = Workbook()
|
||||||
ws = wb.active
|
ws = wb.active
|
||||||
ws.title = "result"
|
ws.title = "result"
|
||||||
@@ -90,9 +116,8 @@ def export_schedule_result_excel(
|
|||||||
for row in rows:
|
for row in rows:
|
||||||
ws.append([row.get(k, "") for k in headers])
|
ws.append([row.get(k, "") for k in headers])
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
file_data = buf.getvalue()
|
||||||
file_name = f"schedule_{run_no}.xlsx"
|
file_name = f"schedule_{run_no}.xlsx"
|
||||||
file_path = out_root / file_name
|
return file_data, file_name, len(file_data)
|
||||||
wb.save(file_path)
|
|
||||||
size = file_path.stat().st_size
|
|
||||||
return str(file_path), file_name, int(size)
|
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ from flask import current_app
|
|||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask, User
|
from app.models import ScheduleRun, ScheduleTask, User
|
||||||
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
||||||
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
|
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
|
||||||
|
|
||||||
@@ -44,6 +45,10 @@ def _generate_run_no() -> str:
|
|||||||
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_test_run_no() -> str:
|
||||||
|
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
||||||
|
|
||||||
|
|
||||||
def create_task(
|
def create_task(
|
||||||
*,
|
*,
|
||||||
name: str,
|
name: str,
|
||||||
@@ -187,8 +192,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
status = "partial_failed"
|
status = "partial_failed"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||||
file_path, file_name, file_size = export_schedule_result_excel(
|
if cfg and cfg.alias_order and cfg.header_labels:
|
||||||
|
header_order, header_labels = cfg.alias_order, cfg.header_labels
|
||||||
|
else:
|
||||||
|
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
||||||
|
detail_alias_order = (cfg.detail_alias_order if cfg else None) or []
|
||||||
|
file_data, file_name, file_size = export_schedule_result_excel(
|
||||||
run_no=run.run_no,
|
run_no=run.run_no,
|
||||||
summary={
|
summary={
|
||||||
"status": status,
|
"status": status,
|
||||||
@@ -198,14 +208,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
"duration_ms": duration_ms,
|
"duration_ms": duration_ms,
|
||||||
},
|
},
|
||||||
details=details,
|
details=details,
|
||||||
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
|
||||||
header_order=header_order,
|
header_order=header_order,
|
||||||
header_labels=header_labels,
|
header_labels=header_labels,
|
||||||
|
detail_alias_order=detail_alias_order,
|
||||||
)
|
)
|
||||||
except Exception as excel_exc:
|
except Exception as excel_exc:
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
||||||
file_path, file_name, file_size = None, None, 0
|
file_data, file_name, file_size = None, None, 0
|
||||||
errors.append(f"Excel导出失败: {excel_exc}")
|
errors.append(f"Excel导出失败: {excel_exc}")
|
||||||
|
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
@@ -222,7 +232,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
"platform_api_path": task.platform_api_path,
|
"platform_api_path": task.platform_api_path,
|
||||||
}
|
}
|
||||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||||
run.excel_file_path = file_path
|
run.excel_file_data = file_data
|
||||||
run.excel_file_name = file_name
|
run.excel_file_name = file_name
|
||||||
run.excel_file_size = file_size or 0
|
run.excel_file_size = file_size or 0
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""store excel in database instead of local filesystem
|
||||||
|
|
||||||
|
Revision ID: a9b0c1d2e3f4
|
||||||
|
Revises: f8b9c0d1e2f3
|
||||||
|
Create Date: 2026-05-20 00:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = 'a9b0c1d2e3f4'
|
||||||
|
down_revision = ('b7a1c2d3e4f5', 'f8b9c0d1e2f3')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('excel_file_data', sa.LargeBinary(), nullable=True))
|
||||||
|
batch_op.drop_column('excel_file_path')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('excel_file_path', sa.Text(), nullable=True))
|
||||||
|
batch_op.drop_column('excel_file_data')
|
||||||
@@ -93,6 +93,7 @@ export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_cond
|
|||||||
|
|
||||||
export interface TestScheduleRunResult {
|
export interface TestScheduleRunResult {
|
||||||
run_no: string;
|
run_no: string;
|
||||||
|
run_id: number;
|
||||||
sql: string;
|
sql: string;
|
||||||
limit: number;
|
limit: number;
|
||||||
total_count: number;
|
total_count: number;
|
||||||
|
|||||||
@@ -856,17 +856,20 @@ const openTestRunDialog = async (s: ScheduleTask) => {
|
|||||||
|
|
||||||
const handleTestRun = async () => {
|
const handleTestRun = async () => {
|
||||||
const s = testRunSchedule.value;
|
const s = testRunSchedule.value;
|
||||||
if (!s?.platform_api_path) return;
|
if (!s?.id) return;
|
||||||
const name = s.platform_api_path.replace(/^\//, '').toLowerCase();
|
|
||||||
testRunLoading.value = true;
|
testRunLoading.value = true;
|
||||||
testRunResult.value = null;
|
testRunResult.value = null;
|
||||||
try {
|
try {
|
||||||
const result = await testAdminScheduleRun(Number(name), {
|
const result = await testAdminScheduleRun(s.id, {
|
||||||
fetch_where_conditions: testRunWhere.value,
|
fetch_where_conditions: testRunWhere.value,
|
||||||
fetch_order_by: testRunOrderBy.value,
|
fetch_order_by: testRunOrderBy.value,
|
||||||
limit: testRunLimit.value,
|
limit: testRunLimit.value,
|
||||||
});
|
});
|
||||||
testRunResult.value = result;
|
testRunResult.value = result;
|
||||||
|
await loadSchedules();
|
||||||
|
if (s.id) {
|
||||||
|
await viewScheduleRuns(s.id);
|
||||||
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
showMessageDialog('error', `测试执行失败: ${e?.message || e}`);
|
showMessageDialog('error', `测试执行失败: ${e?.message || e}`);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
Reference in new issue
Block a user