Merge branch 'test' into prod
This commit is contained in:
commit
718c5a18d2
43 files changed
+4149
-1295
No files matched your search
@@ -1,58 +0,0 @@
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
# Casdoor JWT 验签三件套
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor OAuth
|
||||
CASDOOR_BASE_URL=http://192.168.100.230:8870
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
|
||||
# 是否保留本地密码登录/本地JWT兼容(按你当前需求建议保留)
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
|
||||
# HR SQL Server Configuration
|
||||
HR_SQLSERVER_HOST=192.168.100.191
|
||||
HR_SQLSERVER_PORT=1433
|
||||
HR_SQLSERVER_DATABASE=NH_N8_HEXIN
|
||||
HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr
|
||||
HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR
|
||||
HR_SQLSERVER_DRIVER=SQL Server
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
|
||||
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/hxops_db
|
||||
|
||||
# SRM SQL Server Configuration
|
||||
SRM_SQLSERVER_HOST=192.168.55.106
|
||||
SRM_SQLSERVER_PORT=1433
|
||||
SRM_SQLSERVER_DATABASE=HX-SRM
|
||||
SRM_SQLSERVER_USERNAME=sa
|
||||
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
||||
SRM_SQLSERVER_DRIVER=SQL Server
|
||||
SRM_SQLSERVER_ENCRYPT=no
|
||||
SRM_SQLSERVER_TRUST_CERT=yes
|
||||
SRM_SQLSERVER_TIMEOUT=10
|
||||
@@ -53,6 +53,7 @@ def create_app(config_name='default'):
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
@@ -68,6 +69,7 @@ def create_app(config_name='default'):
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
|
||||
+64
-22
@@ -380,7 +380,7 @@ def delete_agent(id):
|
||||
@require_admin
|
||||
def test_agent(id):
|
||||
"""
|
||||
测试应用连通性与基础响应质量。
|
||||
测试应用连通性。
|
||||
返回:请求地址、输出信息、结果分析。
|
||||
若测试通过,则自动将应用状态置为启用。
|
||||
"""
|
||||
@@ -446,14 +446,29 @@ def test_agent(id):
|
||||
'tested_at': tested_at
|
||||
}), 400
|
||||
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'conversation_id': '',
|
||||
'user': 'admin_test'
|
||||
}
|
||||
extra_config = agent.extra_config or {}
|
||||
dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
dify_app_type = 'chatflow'
|
||||
|
||||
if dify_app_type == 'workflow':
|
||||
request_url = DifyService._build_workflow_url(base_url)
|
||||
payload = {
|
||||
'inputs': {
|
||||
'query': '系统连通性测试,请简短回复OK。'
|
||||
},
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test'
|
||||
}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'conversation_id': '',
|
||||
'user': 'admin_test'
|
||||
}
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
'Content-Type': 'application/json'
|
||||
@@ -466,24 +481,49 @@ def test_agent(id):
|
||||
success = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
|
||||
# 连通性测试:仅 workflow 按“接口可达+认证通过(2xx)”判定通过
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
success = True
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
|
||||
try:
|
||||
data = resp.json()
|
||||
answer = data.get('answer') if isinstance(data, dict) else None
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
success = True
|
||||
analysis = '测试通过:接口连通正常,已成功返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:接口可访问,但未返回有效回答。'
|
||||
else:
|
||||
if dify_app_type == 'workflow':
|
||||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||||
outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None
|
||||
status = workflow_data.get('status') if isinstance(workflow_data, dict) else None
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if message:
|
||||
output_info = str(message)[:4000]
|
||||
if isinstance(outputs, dict) and outputs:
|
||||
output_info = str(outputs)[:4000]
|
||||
elif isinstance(message, str) and message.strip():
|
||||
output_info = message[:4000]
|
||||
elif isinstance(data, dict):
|
||||
output_info = str(data)[:4000]
|
||||
if resp.ok and status in ('succeeded', 'success'):
|
||||
analysis = '测试通过:Workflow 接口可访问且业务返回成功。'
|
||||
elif resp.ok:
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。'
|
||||
else:
|
||||
answer = data.get('answer') if isinstance(data, dict) else None
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
success = True
|
||||
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
|
||||
else:
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if message:
|
||||
output_info = str(message)[:4000]
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
success = True
|
||||
analysis = '测试通过:接口连通正常,返回了文本内容。'
|
||||
if dify_app_type == 'workflow':
|
||||
success = True
|
||||
analysis = '测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
else:
|
||||
success = True
|
||||
analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
|
||||
if success and not agent.is_active:
|
||||
agent.is_active = True
|
||||
@@ -491,6 +531,7 @@ def test_agent(id):
|
||||
|
||||
return jsonify({
|
||||
'success': success,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
@@ -500,6 +541,7 @@ def test_agent(id):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(e),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
|
||||
@@ -11,6 +11,7 @@ import mimetypes
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
@@ -738,13 +739,15 @@ def chat_completions():
|
||||
conversation_id = data.get('conversation_id')
|
||||
# 知识库类型
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
|
||||
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
current_app.logger.info(
|
||||
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
|
||||
"[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
|
||||
request_id,
|
||||
getattr(user, 'id', None),
|
||||
getattr(agent, 'id', None),
|
||||
len(query or ''),
|
||||
@@ -776,7 +779,7 @@ def chat_completions():
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
|
||||
else:
|
||||
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
|
||||
generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id)
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
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
|
||||
|
||||
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")
|
||||
|
||||
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()
|
||||
if not task:
|
||||
return jsonify({"error": f"No schedule task found for '{name}'"}), 404
|
||||
|
||||
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',
|
||||
)
|
||||
db.session.add(run)
|
||||
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.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")
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
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,
|
||||
})
|
||||
@@ -7,14 +7,365 @@ from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
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
|
||||
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
|
||||
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
|
||||
|
||||
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 "",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@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
|
||||
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),
|
||||
})
|
||||
|
||||
|
||||
@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
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if "data_source_type" in data:
|
||||
task.data_source_type = str(data["data_source_type"])
|
||||
db.session.commit()
|
||||
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,
|
||||
})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
|
||||
@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
|
||||
|
||||
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)
|
||||
|
||||
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():
|
||||
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)
|
||||
if isinstance(v, (datetime.date, datetime.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
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,
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e), "sql": sql}), 400
|
||||
|
||||
|
||||
@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
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
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():
|
||||
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=getattr(get_current_user(), 'id', None),
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
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 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),
|
||||
}
|
||||
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
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
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
|
||||
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()
|
||||
|
||||
import decimal, datetime as dt
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
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,
|
||||
})
|
||||
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
|
||||
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
@@ -26,6 +377,7 @@ def get_schedules():
|
||||
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',
|
||||
@@ -39,6 +391,15 @@ def post_schedule():
|
||||
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}"
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task.id, config_data)
|
||||
|
||||
return jsonify(serialize_task(task)), 201
|
||||
|
||||
|
||||
@@ -59,6 +420,15 @@ def patch_schedule(task_id: int):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
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"])
|
||||
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))
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@@ -83,16 +453,6 @@ def delete_schedule(task_id: int):
|
||||
if running_runs:
|
||||
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.delete(task)
|
||||
db.session.commit()
|
||||
@@ -218,9 +578,11 @@ def get_schedule_run(run_id: int):
|
||||
@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
|
||||
if not run.excel_file_path:
|
||||
if not run.excel_file_data:
|
||||
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')
|
||||
@@ -1566,6 +1566,64 @@ def wecom_task_complete():
|
||||
return jsonify(result), 200 if result.get('ok') else 202
|
||||
|
||||
|
||||
@user_bp.route('/leave-balance', methods=['GET'])
|
||||
def get_leave_balance():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
leave_type_code = _clean_str(request.args.get('leave_type'))
|
||||
if leave_type_code not in ('010', '408'):
|
||||
return jsonify({'error': '仅支持查询年假(010)和育儿假(408)的余额'}), 400
|
||||
|
||||
try:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
employee_code = HRLeaveSQLServerService._get_employee_code(user)
|
||||
now_year = datetime.now().year
|
||||
|
||||
if leave_type_code == '010':
|
||||
_, record = HRLeaveSQLServerService._query_one(
|
||||
view_name="VIEW_D044",
|
||||
year_column="D044001",
|
||||
total_column="D044005",
|
||||
used_column="D044006",
|
||||
remaining_column="D044007",
|
||||
employee_code=employee_code,
|
||||
year=now_year,
|
||||
)
|
||||
label = '年假'
|
||||
else:
|
||||
_, record = HRLeaveSQLServerService._query_one(
|
||||
view_name="VIEW_D072",
|
||||
year_column="d072001",
|
||||
total_column="d072002",
|
||||
used_column="d072003",
|
||||
remaining_column="d072004",
|
||||
employee_code=employee_code,
|
||||
year=now_year,
|
||||
)
|
||||
label = '育儿假'
|
||||
|
||||
remaining = record.get('remaining_hours') if record else None
|
||||
try:
|
||||
has_balance = remaining is not None and float(remaining) > 0
|
||||
except (TypeError, ValueError):
|
||||
has_balance = False
|
||||
|
||||
return jsonify({
|
||||
'leave_type_code': leave_type_code,
|
||||
'leave_type_label': label,
|
||||
'year': record.get('leave_year', now_year) if record else now_year,
|
||||
'total_hours': record.get('total_hours') if record else None,
|
||||
'used_hours': record.get('used_hours') if record else None,
|
||||
'remaining_hours': remaining,
|
||||
'has_balance': has_balance,
|
||||
})
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
|
||||
return jsonify({'error': f'假期余额查询失败:{exc}'}), 500
|
||||
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
|
||||
@@ -54,6 +54,7 @@ def workspace_schedule_run_detail(run_id: int):
|
||||
|
||||
@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
|
||||
@@ -62,6 +63,7 @@ def workspace_schedule_run_excel(run_id: int):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
if not can_view_run(run, user.id):
|
||||
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 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')
|
||||
@@ -106,7 +106,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
@@ -152,11 +152,7 @@ class Config:
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
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:8880')
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
|
||||
+50
-5
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
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, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
@@ -562,6 +562,7 @@ class ScheduleTask(Base):
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
@@ -574,6 +575,49 @@ class ScheduleTask(Base):
|
||||
|
||||
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
|
||||
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ScheduleTaskConfig(Base):
|
||||
__tablename__ = 'schedule_task_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schedule_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
|
||||
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
|
||||
log_prefix: Mapped[str] = mapped_column(String(128), default='')
|
||||
|
||||
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
|
||||
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
|
||||
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config")
|
||||
|
||||
|
||||
class ScheduleRun(Base):
|
||||
@@ -599,13 +643,14 @@ class ScheduleRun(Base):
|
||||
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
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_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
mail_sent: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
mail_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
mail_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||
|
||||
+137
-97
@@ -23,6 +23,7 @@ chat.py (/api/chat/completions)
|
||||
-> yield SSE events to frontend
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, List, Optional
|
||||
@@ -37,6 +38,7 @@ from app.services.integration_api import IntegrationApiService
|
||||
|
||||
class DifyService:
|
||||
"""Dify service wrapper."""
|
||||
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
|
||||
@@ -290,7 +292,7 @@ class DifyService:
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None):
|
||||
"""
|
||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||
Stream chat completion from Dify and relay SSE events to caller.
|
||||
@@ -329,7 +331,8 @@ class DifyService:
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
|
||||
"[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
|
||||
request_id,
|
||||
user_id,
|
||||
getattr(agent, 'id', None),
|
||||
base_url,
|
||||
@@ -338,117 +341,154 @@ class DifyService:
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
first_token_at: float | None = None
|
||||
message_count = 0
|
||||
event_count = 0
|
||||
full_answer: List[str] = []
|
||||
retriever_resources: List[Any] = []
|
||||
attribution_parts: List[str] = []
|
||||
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] dify response status=%s reason=%s",
|
||||
response.status_code,
|
||||
response.reason,
|
||||
)
|
||||
if not response.ok and current_app:
|
||||
try:
|
||||
error_body = response.text[:2000]
|
||||
except Exception:
|
||||
error_body = "<failed to read response body>"
|
||||
current_app.logger.error(
|
||||
"[chat-stream] dify bad response status=%s url=%s payload=%s body=%s",
|
||||
response.status_code,
|
||||
url,
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
error_body,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
for line in response.iter_lines():
|
||||
if not line:
|
||||
continue
|
||||
|
||||
decoded_line = line.decode('utf-8')
|
||||
if not decoded_line.startswith('data: '):
|
||||
continue
|
||||
|
||||
raw_json = decoded_line[6:]
|
||||
try:
|
||||
data = json.loads(raw_json)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event = data.get('event')
|
||||
max_retries = 3
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
|
||||
event,
|
||||
len(data.get('answer', '') or ''),
|
||||
bool(data.get('metadata')),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
|
||||
request_id,
|
||||
response.status_code,
|
||||
response.reason,
|
||||
attempt,
|
||||
)
|
||||
if not response.ok and current_app:
|
||||
retryable = response.status_code in (404, 502, 503, 504)
|
||||
try:
|
||||
error_body = response.text[:2000]
|
||||
except Exception:
|
||||
error_body = "<failed to read response body>"
|
||||
current_app.logger.error(
|
||||
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
|
||||
request_id,
|
||||
response.status_code,
|
||||
url,
|
||||
attempt,
|
||||
error_body,
|
||||
)
|
||||
if retryable and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
response.raise_for_status()
|
||||
|
||||
if event == 'message':
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
for line in response.iter_lines():
|
||||
if not line:
|
||||
continue
|
||||
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
# Keep metadata from non-message events, but avoid appending
|
||||
# intermediate workflow/agent outputs into final user answer.
|
||||
if event == 'message_end' and data.get('answer'):
|
||||
decoded_line = line.decode('utf-8')
|
||||
if not decoded_line.startswith('data: '):
|
||||
continue
|
||||
|
||||
raw_json = decoded_line[6:]
|
||||
try:
|
||||
data = json.loads(raw_json)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event = data.get('event')
|
||||
event_count += 1
|
||||
# Keep stream event logs behind an explicit switch to prevent
|
||||
# flooding when global logger level is DEBUG.
|
||||
if DifyService.VERBOSE_STREAM_LOG and current_app:
|
||||
current_app.logger.debug(
|
||||
"[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s",
|
||||
request_id,
|
||||
event,
|
||||
len(data.get('answer', '') or ''),
|
||||
bool(data.get('metadata')),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
message_count += 1
|
||||
if first_token_at is None:
|
||||
first_token_at = time.time()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s",
|
||||
request_id,
|
||||
int((first_token_at - start_time) * 1000),
|
||||
attempt,
|
||||
)
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
if event == 'message_end':
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] message_end: collected retriever resources=%s",
|
||||
len(retriever_resources),
|
||||
)
|
||||
# Resolve original source file URLs from external integration API.
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
if event == 'message_end' and data.get('answer'):
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
metadata = data.get('metadata') or {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
if event == 'message_end':
|
||||
message_end_started = time.time()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] message_end request_id=%s collected retriever_resources=%s",
|
||||
request_id,
|
||||
len(retriever_resources),
|
||||
)
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
enrich_done_at = time.time()
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
metadata = data.get('metadata') or {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
with current_app.app_context():
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=''.join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
len(''.join(full_answer)),
|
||||
len(retriever_resources),
|
||||
len(attribution_parts),
|
||||
latency,
|
||||
)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
|
||||
# Pass-through SSE event (after optional enrichment).
|
||||
# SSE frame delimiter must be real newlines, not literal "\n".
|
||||
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
db_write_started = time.time()
|
||||
with current_app.app_context():
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=''.join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
db_write_done_at = time.time()
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
|
||||
request_id,
|
||||
latency,
|
||||
int((first_token_at - start_time) * 1000) if first_token_at else None,
|
||||
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
|
||||
int((time.time() - message_end_started) * 1000),
|
||||
int((enrich_done_at - message_end_started) * 1000),
|
||||
int((db_write_done_at - db_write_started) * 1000),
|
||||
event_count,
|
||||
message_count,
|
||||
len(''.join(full_answer)),
|
||||
len(retriever_resources),
|
||||
len(attribution_parts),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if current_app:
|
||||
current_app.logger.exception("[chat-stream] request exception: %s", e)
|
||||
error_msg = json.dumps({'event': 'error', 'message': str(e)})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
break
|
||||
except requests.exceptions.RequestException as e:
|
||||
if current_app:
|
||||
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
|
||||
if attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
error_msg = json.dumps({'event': 'error', 'message': str(e)})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
|
||||
@staticmethod
|
||||
def _log_chat(
|
||||
|
||||
@@ -8,9 +8,15 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.srm_service import run_rohs_doc_check_dify_job
|
||||
from app.services.schedule.sql_config import (
|
||||
get_schedule_sql_config,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
get_all_schedule_sql_configs,
|
||||
upsert_schedule_task_config,
|
||||
ScheduleSqlConfig,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||
|
||||
|
||||
@@ -26,59 +32,7 @@ def normalize_platform_api_path(path: str | None) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
endpoint = normalize_platform_api_path(task.platform_api_path)
|
||||
if not endpoint:
|
||||
raise RuntimeError("platform_api_path is missing")
|
||||
|
||||
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
|
||||
url = endpoint if endpoint.startswith("http://") or endpoint.startswith("https://") else (f"{base}{endpoint}" if base else endpoint)
|
||||
|
||||
payload = {
|
||||
"run_no": run.run_no,
|
||||
"schedule_task_id": task.id,
|
||||
"schedule_name": task.name,
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=(5, 60))
|
||||
resp.raise_for_status()
|
||||
data = resp.json() if resp.content else {}
|
||||
except requests.RequestException as e:
|
||||
data = {}
|
||||
if e.response is not None:
|
||||
try:
|
||||
data = e.response.json()
|
||||
except Exception:
|
||||
data = {"error_text": e.response.text}
|
||||
else:
|
||||
data = {"error": str(e)}
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
raise e
|
||||
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
|
||||
summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {}
|
||||
details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else []
|
||||
errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else []
|
||||
|
||||
total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1))
|
||||
success = int(summary.get("success_count") if summary.get("success_count") is not None else total)
|
||||
failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success))
|
||||
return total, success, failed, 0, details, [str(e) for e in errors if str(e).strip()]
|
||||
|
||||
|
||||
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
||||
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
||||
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
||||
|
||||
def _build_srm_conn_str() -> str:
|
||||
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
|
||||
if not host:
|
||||
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
|
||||
@@ -91,7 +45,7 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower()
|
||||
trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower()
|
||||
|
||||
conn_str = (
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={host},{port};"
|
||||
f"DATABASE={database};"
|
||||
@@ -101,33 +55,264 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
|
||||
return run_rohs_doc_check_dify_job(
|
||||
|
||||
def _resolve_dify_agent(task: ScheduleTask):
|
||||
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
||||
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
||||
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
||||
return agent
|
||||
|
||||
|
||||
def _resolve_schedule_user(task: ScheduleTask) -> str:
|
||||
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
|
||||
|
||||
|
||||
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
endpoint = normalize_platform_api_path(task.platform_api_path)
|
||||
if not endpoint:
|
||||
raise RuntimeError("platform_api_path is missing")
|
||||
|
||||
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
|
||||
if endpoint.startswith("http://") or endpoint.startswith("https://"):
|
||||
url = endpoint
|
||||
elif base:
|
||||
name = endpoint.lstrip("/")
|
||||
url = f"{base}/api/internal/jobs/{name}"
|
||||
else:
|
||||
url = endpoint
|
||||
|
||||
payload = {
|
||||
"run_no": run.run_no,
|
||||
"schedule_task_id": task.id,
|
||||
"schedule_name": task.name,
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
timeout = max(5, (task.wait_seconds or 120) + 30)
|
||||
resp = requests.post(url, json=payload, timeout=(5, timeout))
|
||||
resp.raise_for_status()
|
||||
data = resp.json() if resp.content else {}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "success",
|
||||
"detail": {"url": url, "status_code": resp.status_code},
|
||||
})
|
||||
except requests.RequestException as e:
|
||||
data = {}
|
||||
if e.response is not None:
|
||||
try:
|
||||
data = e.response.json()
|
||||
except Exception:
|
||||
data = {"error_text": e.response.text}
|
||||
else:
|
||||
data = {"error": str(e)}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "failed",
|
||||
"detail": {"url": url, "error": str(e)},
|
||||
})
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
raise e
|
||||
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
|
||||
summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {}
|
||||
details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else []
|
||||
errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else []
|
||||
remote_step_logs = data.get("step_logs") if isinstance(data, dict) and isinstance(data.get("step_logs"), list) else []
|
||||
|
||||
total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1))
|
||||
success = int(summary.get("success_count") if summary.get("success_count") is not None else total)
|
||||
failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success))
|
||||
skipped = int(summary.get("skipped_count") if summary.get("skipped_count") is not None else 0)
|
||||
|
||||
if remote_step_logs:
|
||||
step_logs.extend(remote_step_logs)
|
||||
|
||||
return total, success, failed, skipped, details, [str(e) for e in errors if str(e).strip()], step_logs
|
||||
|
||||
|
||||
def _run_external_api_job(task: ScheduleTask, run: ScheduleRun, cfg: ScheduleSqlConfig) -> ScheduleExecuteResult:
|
||||
import requests as http_requests
|
||||
|
||||
ext = cfg.external_api
|
||||
if not ext.url:
|
||||
return 0, 0, 0, 0, [], ["external_api url is empty"], []
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
step_logs.append({"step": "call_external_api", "status": "started", "url": ext.url, "method": ext.method})
|
||||
|
||||
try:
|
||||
headers = dict(ext.headers) if ext.headers else {}
|
||||
body = ext.body_template or "{}"
|
||||
resp = http_requests.request(
|
||||
method=ext.method,
|
||||
url=ext.url,
|
||||
headers=headers,
|
||||
data=body,
|
||||
timeout=120,
|
||||
)
|
||||
step_logs.append({"step": "call_external_api", "status": "completed", "status_code": resp.status_code})
|
||||
if not resp.ok:
|
||||
return 0, 0, 0, 1, [], [f"external API returned {resp.status_code}: {resp.text[:500]}"], step_logs
|
||||
try:
|
||||
result_data = resp.json()
|
||||
except Exception:
|
||||
result_data = {"raw": resp.text[:2000]}
|
||||
|
||||
total = 1
|
||||
details = [result_data] if isinstance(result_data, dict) else (result_data if isinstance(result_data, list) else [{"raw": str(result_data)}])
|
||||
step_logs.append({"step": "call_external_api", "status": "success", "total": total})
|
||||
return total, total, 0, 0, details, [], step_logs
|
||||
except Exception as e:
|
||||
step_logs.append({"step": "call_external_api", "status": "error", "error": str(e)})
|
||||
return 0, 0, 1, 0, [], [str(e)], step_logs
|
||||
|
||||
|
||||
def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
from app.services.schedule.srm_service import (
|
||||
_run_check_job_loop,
|
||||
_fetch_records,
|
||||
_execute_writeback,
|
||||
_build_record_text,
|
||||
)
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source_type == "external_api":
|
||||
return _run_external_api_job(task, run, cfg)
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
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)
|
||||
user = _resolve_schedule_user(task)
|
||||
has_detail = bool(cfg.detail_sql)
|
||||
|
||||
def fetch_fn(cs: str):
|
||||
return _fetch_records(cs, cfg.fetch_sql)
|
||||
|
||||
def writeback_fn(cs: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str):
|
||||
_execute_writeback(cs, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
|
||||
pre_dify_fn = None
|
||||
build_record_fn = None
|
||||
|
||||
if has_detail:
|
||||
def _pre_dify(cs: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = _fetch_records(cs, 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_summary_lines: list[str] = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_summary_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
return None
|
||||
pre_dify_fn = _pre_dify
|
||||
|
||||
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
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")
|
||||
build_record_fn = _build_with_detail
|
||||
else:
|
||||
def _build_simple(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_simple
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run.run_no,
|
||||
agent=agent,
|
||||
user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"),
|
||||
user=user,
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
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=cfg.fetch_sql,
|
||||
pre_dify_fn=pre_dify_fn,
|
||||
)
|
||||
|
||||
|
||||
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
||||
"default": _run_common_executor,
|
||||
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
||||
}
|
||||
|
||||
|
||||
def register_schedule_executor(name: str, executor: ScheduleExecutor) -> None:
|
||||
key = str(name or "").strip().lower()
|
||||
if not key:
|
||||
raise ValueError("executor name is required")
|
||||
_SCHEDULE_EXECUTOR_REGISTRY[key] = executor
|
||||
def list_registered_api_paths() -> list[dict[str, str]]:
|
||||
from app.models import ScheduleTask
|
||||
results: list[dict[str, str]] = []
|
||||
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
|
||||
for t in tasks:
|
||||
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
|
||||
return results
|
||||
|
||||
|
||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||
path = normalize_platform_api_path(task.platform_api_path)
|
||||
dst = getattr(task, "data_source_type", None) or "database"
|
||||
if dst in ("database", "external_api"):
|
||||
return _run_generic_check_job
|
||||
return _run_common_executor
|
||||
|
||||
|
||||
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||
|
||||
|
||||
def register_schedule_header(name: str, header_order: list[str], header_labels: dict[str, str]) -> None:
|
||||
key = str(name or "").strip().lower()
|
||||
if not key:
|
||||
raise ValueError("header name is required")
|
||||
_SCHEDULE_HEADER_REGISTRY[key] = (header_order, header_labels)
|
||||
|
||||
|
||||
def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] | None, dict[str, str] | None]:
|
||||
path = normalize_platform_api_path(platform_api_path)
|
||||
if path:
|
||||
lookup_key = path.lstrip("/").lower()
|
||||
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
|
||||
key = path.lstrip("/").lower()
|
||||
if key in _SCHEDULE_HEADER_REGISTRY:
|
||||
return _SCHEDULE_HEADER_REGISTRY[key]
|
||||
return None, None
|
||||
|
||||
|
||||
def _register_headers_from_config() -> None:
|
||||
_SCHEDULE_HEADER_REGISTRY.clear()
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
_register_headers_from_config()
|
||||
return {"reloaded": []}
|
||||
|
||||
|
||||
_HEADERS_LOADED = False
|
||||
|
||||
|
||||
def ensure_headers_loaded() -> None:
|
||||
global _HEADERS_LOADED
|
||||
if not _HEADERS_LOADED:
|
||||
_register_headers_from_config()
|
||||
_HEADERS_LOADED = True
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
@@ -13,40 +13,111 @@ def _flatten_value(v: Any) -> Any:
|
||||
return v
|
||||
|
||||
|
||||
def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]:
|
||||
_EXPORT_SKIP_KEYS = {"dify_output", "json_output", "output", "_detail_rows", "detail_text"}
|
||||
|
||||
|
||||
def export_schedule_result_excel(
|
||||
*,
|
||||
run_no: str,
|
||||
summary: dict,
|
||||
details: list[dict],
|
||||
header_order: list[str] | None = None,
|
||||
header_labels: dict[str, str] | None = None,
|
||||
detail_alias_order: list[str] | None = None,
|
||||
) -> tuple[bytes | None, str | None, int]:
|
||||
if not details:
|
||||
return None, None, 0
|
||||
|
||||
out_root = Path(root_dir)
|
||||
out_root.mkdir(parents=True, exist_ok=True)
|
||||
header_order = header_order or []
|
||||
header_labels = header_labels or {}
|
||||
detail_alias_order = detail_alias_order or []
|
||||
|
||||
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:
|
||||
if key not in target:
|
||||
target.append(key)
|
||||
|
||||
for row in details:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
for k in row.keys():
|
||||
key = str(k)
|
||||
if key in _EXPORT_SKIP_KEYS:
|
||||
continue
|
||||
if key in exec_result_order:
|
||||
_append_unique(exec_result_headers, key)
|
||||
else:
|
||||
_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))
|
||||
|
||||
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]
|
||||
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 = (
|
||||
ordered_sql_headers
|
||||
+ other_sql_headers
|
||||
+ all_detail_headers
|
||||
+ ordered_exec_headers
|
||||
+ other_exec_headers
|
||||
)
|
||||
|
||||
if not headers:
|
||||
return None, None, 0
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in details:
|
||||
output = row.get('dify_output')
|
||||
if not isinstance(output, dict):
|
||||
output = {}
|
||||
entry = {k: _flatten_value(v) for k, v in output.items()}
|
||||
for k in ('writeback_ok', 'error', 'judgement', 'reason'):
|
||||
if k in row:
|
||||
entry[k] = row[k]
|
||||
rows.append(entry)
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
|
||||
headers: list[str] = []
|
||||
for row in rows:
|
||||
for k in row:
|
||||
if k not in headers:
|
||||
headers.append(k)
|
||||
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()
|
||||
ws = wb.active
|
||||
ws.title = 'result'
|
||||
ws.append(headers)
|
||||
ws.title = "result"
|
||||
ws.append([header_labels.get(k, k) for k in headers])
|
||||
|
||||
for row in rows:
|
||||
ws.append([row.get(k, '') for k in headers])
|
||||
ws.append([row.get(k, "") for k in headers])
|
||||
|
||||
file_name = f'schedule_{run_no}.xlsx'
|
||||
file_path = out_root / file_name
|
||||
wb.save(file_path)
|
||||
size = file_path.stat().st_size
|
||||
return str(file_path), file_name, int(size)
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
file_data = buf.getvalue()
|
||||
file_name = f"schedule_{run_no}.xlsx"
|
||||
return file_data, file_name, len(file_data)
|
||||
@@ -1,37 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import smtplib
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
|
||||
def send_schedule_mail(*, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_tls: bool, from_addr: str, to_addrs: list[str], subject: str, html_body: str) -> None:
|
||||
if not to_addrs:
|
||||
return
|
||||
msg = MIMEMultipart('alternative')
|
||||
msg['Subject'] = subject
|
||||
msg['From'] = from_addr
|
||||
msg['To'] = ', '.join(to_addrs)
|
||||
msg.attach(MIMEText(html_body, 'html', 'utf-8'))
|
||||
|
||||
with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server:
|
||||
if use_tls:
|
||||
server.starttls()
|
||||
if smtp_user:
|
||||
server.login(smtp_user, smtp_password)
|
||||
server.sendmail(from_addr, to_addrs, msg.as_string())
|
||||
|
||||
|
||||
def build_schedule_mail_html(*, schedule_name: str, run_no: str, status: str, total: int, success: int, failed: int) -> str:
|
||||
return (
|
||||
"<html><body>"
|
||||
"<h3>排程执行结果</h3>"
|
||||
"<table border='1' cellspacing='0' cellpadding='6'>"
|
||||
f"<tr><th>排程</th><td>{schedule_name}</td></tr>"
|
||||
f"<tr><th>执行单号</th><td>{run_no}</td></tr>"
|
||||
f"<tr><th>状态</th><td>{status}</td></tr>"
|
||||
f"<tr><th>总数</th><td>{total}</td></tr>"
|
||||
f"<tr><th>成功</th><td>{success}</td></tr>"
|
||||
f"<tr><th>失败</th><td>{failed}</td></tr>"
|
||||
"</table></body></html>"
|
||||
)
|
||||
@@ -52,12 +52,13 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
'api_request_json': run.api_request_json,
|
||||
'api_response_json': run.api_response_json,
|
||||
'response_summary_json': run.response_summary_json,
|
||||
'step_logs': run.step_logs,
|
||||
'error_message': run.error_message,
|
||||
'excel_file_name': run.excel_file_name,
|
||||
'excel_file_size': run.excel_file_size,
|
||||
'mail_sent': bool(run.mail_sent),
|
||||
'mail_sent_at': run.mail_sent_at.isoformat() if run.mail_sent_at else None,
|
||||
'mail_error': run.mail_error,
|
||||
'wecom_notified': bool(run.wecom_notified),
|
||||
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
|
||||
'wecom_notify_error': run.wecom_notify_error,
|
||||
'created_at': run.created_at.isoformat() if run.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor
|
||||
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.mail_service import build_schedule_mail_html, send_schedule_mail
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
@@ -44,6 +44,115 @@ def _generate_run_no() -> str:
|
||||
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()}"
|
||||
|
||||
|
||||
_WECOM_STATUS_LABEL = {
|
||||
'success': '成功',
|
||||
'failed': '失败',
|
||||
'partial_failed': '部分失败',
|
||||
}
|
||||
|
||||
_WECOM_EVENT_TYPE = 'schedule_completed'
|
||||
|
||||
|
||||
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
from app.services.wecom_notify import (
|
||||
upload_wecom_temp_media,
|
||||
send_wecom_file_message,
|
||||
send_wecom_textcard_message,
|
||||
_create_audit,
|
||||
_build_jump_url,
|
||||
_get_enabled_events,
|
||||
)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return
|
||||
|
||||
if _WECOM_EVENT_TYPE not in _get_enabled_events():
|
||||
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
|
||||
return
|
||||
|
||||
user_ids = task.notify_user_ids_json or []
|
||||
if not user_ids:
|
||||
return
|
||||
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
wecom_users = [u for u in users if u.wecom_userid]
|
||||
if not wecom_users:
|
||||
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
|
||||
return
|
||||
|
||||
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
|
||||
title = f'排程执行结果: {task.name}'
|
||||
description = (
|
||||
f'执行单号: {run.run_no}\n'
|
||||
f'状态: {status_label}\n'
|
||||
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
|
||||
)
|
||||
|
||||
media_id = None
|
||||
if run.excel_file_data and run.excel_file_name:
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
'[wecom-schedule] media upload failed for run %s: %s',
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
textcard_ok_count = 0
|
||||
errors = []
|
||||
|
||||
for u in wecom_users:
|
||||
trace_id = uuid.uuid4().hex
|
||||
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
|
||||
|
||||
try:
|
||||
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
|
||||
audit.jump_url = jump_url
|
||||
|
||||
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
textcard_ok_count += 1
|
||||
else:
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
|
||||
|
||||
if media_id:
|
||||
try:
|
||||
file_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_file', u,
|
||||
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
|
||||
)
|
||||
file_data = send_wecom_file_message(u.wecom_userid, media_id)
|
||||
if file_data.get('errcode') == 0:
|
||||
file_audit.status = 'sent'
|
||||
else:
|
||||
file_audit.error_code = str(file_data.get('errcode'))
|
||||
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: file exception={exc}')
|
||||
|
||||
if textcard_ok_count > 0:
|
||||
run.wecom_notified = True
|
||||
run.wecom_notified_at = datetime.utcnow()
|
||||
else:
|
||||
run.wecom_notified = False
|
||||
|
||||
if errors:
|
||||
run.wecom_notify_error = '; '.join(errors[:5])
|
||||
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def create_task(
|
||||
*,
|
||||
name: str,
|
||||
@@ -58,9 +167,6 @@ def create_task(
|
||||
enabled: bool,
|
||||
actor_id: int | None,
|
||||
) -> ScheduleTask:
|
||||
if not normalize_platform_api_path(platform_api_path):
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
@@ -151,11 +257,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
db.session.commit()
|
||||
|
||||
start_ts = time.time()
|
||||
step_logs: list = []
|
||||
try:
|
||||
executor = resolve_schedule_executor(task)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
|
||||
except Exception as exc:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
||||
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
|
||||
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_run_cancelled(run.id):
|
||||
run.finished_at = datetime.utcnow()
|
||||
@@ -183,7 +296,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
status = "partial_failed"
|
||||
|
||||
try:
|
||||
file_path, file_name, file_size = export_schedule_result_excel(
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
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,
|
||||
summary={
|
||||
"status": status,
|
||||
@@ -193,12 +312,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
"duration_ms": duration_ms,
|
||||
},
|
||||
details=details,
|
||||
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
||||
header_order=header_order,
|
||||
header_labels=header_labels,
|
||||
detail_alias_order=detail_alias_order,
|
||||
)
|
||||
except Exception as excel_exc:
|
||||
if current_app:
|
||||
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}")
|
||||
|
||||
run.finished_at = datetime.utcnow()
|
||||
@@ -208,48 +329,23 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
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.response_summary_json = {
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
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_size = file_size or 0
|
||||
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all()
|
||||
to_addrs = [u.email for u in users if u.email]
|
||||
if to_addrs:
|
||||
try:
|
||||
send_schedule_mail(
|
||||
smtp_host=str(current_app.config.get("SMTP_HOST") or ""),
|
||||
smtp_port=int(current_app.config.get("SMTP_PORT") or 25),
|
||||
smtp_user=str(current_app.config.get("SMTP_USER") or ""),
|
||||
smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""),
|
||||
use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)),
|
||||
from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"),
|
||||
to_addrs=to_addrs,
|
||||
subject=f"排程执行结果 {task.name} {run.run_no}",
|
||||
html_body=build_schedule_mail_html(
|
||||
schedule_name=task.name,
|
||||
run_no=run.run_no,
|
||||
status=status,
|
||||
total=total_count,
|
||||
success=success_count,
|
||||
failed=failed_count,
|
||||
),
|
||||
)
|
||||
run.mail_sent = True
|
||||
run.mail_sent_at = datetime.utcnow()
|
||||
except Exception as mail_exc:
|
||||
run.mail_sent = False
|
||||
run.mail_error = str(mail_exc)
|
||||
except Exception as mail_exc:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
|
||||
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
|
||||
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
_ENV_VAR_PATTERN = re.compile(r"\$\{(\w+)\}")
|
||||
|
||||
|
||||
def resolve_env_value(val: str) -> str:
|
||||
if not val or "${" not in val:
|
||||
return val
|
||||
|
||||
def _replacer(match: re.Match) -> str:
|
||||
env_key = match.group(1)
|
||||
return os.environ.get(env_key, match.group(0))
|
||||
|
||||
return _ENV_VAR_PATTERN.sub(_replacer, val)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataSourceConfig:
|
||||
db_type: str = "sqlserver"
|
||||
host: str = ""
|
||||
port: str = ""
|
||||
database: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
driver: str = ""
|
||||
encrypt: str = ""
|
||||
trust_cert: str = ""
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not self.host.strip()
|
||||
|
||||
def build_connection_string(self) -> str:
|
||||
host = resolve_env_value(self.host)
|
||||
port = resolve_env_value(self.port)
|
||||
database = resolve_env_value(self.database)
|
||||
username = resolve_env_value(self.username)
|
||||
password = resolve_env_value(self.password)
|
||||
|
||||
if not port:
|
||||
if self.db_type == "sqlserver":
|
||||
port = "1433"
|
||||
elif self.db_type == "postgresql":
|
||||
port = "5432"
|
||||
elif self.db_type == "mysql":
|
||||
port = "3306"
|
||||
|
||||
if self.db_type == "sqlserver":
|
||||
driver = resolve_env_value(self.driver) or "SQL Server"
|
||||
encrypt = resolve_env_value(self.encrypt) or "no"
|
||||
trust_cert = resolve_env_value(self.trust_cert) or "yes"
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={host},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
elif self.db_type == "postgresql":
|
||||
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
|
||||
elif self.db_type == "mysql":
|
||||
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
|
||||
raise ValueError(f"Unsupported db_type: {self.db_type}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExternalApiConfig:
|
||||
url: str = ""
|
||||
method: str = "POST"
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
body_template: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleSqlConfig:
|
||||
description: str = ""
|
||||
row_id_key: str = "id"
|
||||
log_prefix: str = ""
|
||||
fetch_sql: str = ""
|
||||
base_fetch_sql: str = ""
|
||||
fetch_where_conditions: str = ""
|
||||
fetch_order_by: str = ""
|
||||
writeback_sql: str = ""
|
||||
detail_sql: str = ""
|
||||
alias_order: list[str] = field(default_factory=list)
|
||||
detail_alias_order: list[str] = field(default_factory=list)
|
||||
header_labels: dict[str, str] = field(default_factory=dict)
|
||||
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
||||
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
||||
data_source_type: str = "database"
|
||||
|
||||
|
||||
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
||||
parts = [base.strip().rstrip(";").strip()]
|
||||
if where_conds.strip():
|
||||
parts.append("where")
|
||||
parts.append(where_conds.strip())
|
||||
if order_by.strip():
|
||||
parts.append(order_by.strip())
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask
|
||||
|
||||
task_id = cfg_model.schedule_task_id
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
|
||||
base = str(cfg_model.base_fetch_sql or "")
|
||||
where_conds = str(cfg_model.fetch_where_conditions or "")
|
||||
order_by = str(cfg_model.fetch_order_by or "")
|
||||
fetch_sql = _build_fetch_sql(base, where_conds, order_by) if base else ""
|
||||
|
||||
ds = DataSourceConfig(
|
||||
db_type=str(cfg_model.ds_db_type or "sqlserver"),
|
||||
host=str(cfg_model.ds_host or ""),
|
||||
port=str(cfg_model.ds_port or ""),
|
||||
database=str(cfg_model.ds_database or ""),
|
||||
username=str(cfg_model.ds_username or ""),
|
||||
password=str(cfg_model.ds_password or ""),
|
||||
driver=str(cfg_model.ds_driver or ""),
|
||||
encrypt=str(cfg_model.ds_encrypt or ""),
|
||||
trust_cert=str(cfg_model.ds_trust_cert or ""),
|
||||
)
|
||||
|
||||
ext = ExternalApiConfig(
|
||||
url=str(cfg_model.api_url or ""),
|
||||
method=str(cfg_model.api_method or "POST"),
|
||||
headers=dict(cfg_model.api_headers or {}),
|
||||
body_template=str(cfg_model.api_body_template or ""),
|
||||
)
|
||||
|
||||
return ScheduleSqlConfig(
|
||||
description=str(task.name if task else ""),
|
||||
row_id_key=str(cfg_model.row_id_key or "id"),
|
||||
log_prefix=str(cfg_model.log_prefix or ""),
|
||||
fetch_sql=fetch_sql,
|
||||
base_fetch_sql=base,
|
||||
fetch_where_conditions=where_conds,
|
||||
fetch_order_by=order_by,
|
||||
writeback_sql=str(cfg_model.writeback_sql or ""),
|
||||
detail_sql=str(cfg_model.detail_sql or ""),
|
||||
alias_order=list(cfg_model.alias_order or []),
|
||||
detail_alias_order=list(cfg_model.detail_alias_order or []),
|
||||
header_labels=dict(cfg_model.header_labels or {}),
|
||||
data_source=ds,
|
||||
external_api=ext,
|
||||
data_source_type=str(task.data_source_type if task else "database"),
|
||||
)
|
||||
|
||||
|
||||
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
key = name.strip().lower()
|
||||
task = None
|
||||
if key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
if not task:
|
||||
task = ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
||||
).first()
|
||||
if not task:
|
||||
return None
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_schedule_sql_config_by_task_id(task_id: int) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
results: dict[str, ScheduleSqlConfig] = {}
|
||||
configs = ScheduleTaskConfig.query.all()
|
||||
for cfg_model in configs:
|
||||
key = str(cfg_model.schedule_task_id)
|
||||
results[key] = _config_from_model(cfg_model)
|
||||
return results
|
||||
|
||||
|
||||
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
||||
db.session.add(cfg_model)
|
||||
|
||||
for k, v in data.items():
|
||||
if k == "data_source" and isinstance(v, dict):
|
||||
cfg_model.ds_db_type = str(v.get("db_type", "sqlserver"))
|
||||
cfg_model.ds_host = str(v.get("host", ""))
|
||||
cfg_model.ds_port = str(v.get("port", ""))
|
||||
cfg_model.ds_database = str(v.get("database", ""))
|
||||
cfg_model.ds_username = str(v.get("username", ""))
|
||||
cfg_model.ds_password = str(v.get("password", ""))
|
||||
cfg_model.ds_driver = str(v.get("driver", "")) if v.get("driver") else None
|
||||
cfg_model.ds_encrypt = str(v.get("encrypt", "")) if v.get("encrypt") else None
|
||||
cfg_model.ds_trust_cert = str(v.get("trust_cert", "")) if v.get("trust_cert") else None
|
||||
elif k == "external_api" and isinstance(v, dict):
|
||||
cfg_model.api_url = str(v.get("url", ""))
|
||||
cfg_model.api_method = str(v.get("method", "POST"))
|
||||
cfg_model.api_headers = dict(v.get("headers", {}))
|
||||
cfg_model.api_body_template = str(v.get("body_template", ""))
|
||||
elif k in ("row_id_key", "log_prefix"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else "")
|
||||
elif k in ("base_fetch_sql", "fetch_where_conditions", "fetch_order_by",
|
||||
"writeback_sql", "detail_sql"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else None)
|
||||
elif k in ("alias_order", "detail_alias_order"):
|
||||
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
||||
elif k == "header_labels":
|
||||
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
||||
|
||||
db.session.commit()
|
||||
db.session.refresh(cfg_model)
|
||||
return _config_from_model(cfg_model)
|
||||
@@ -1,8 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
@@ -11,54 +13,20 @@ except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
FIXED_ROHS_SQL = """
|
||||
select
|
||||
TOP(100)
|
||||
t2.supplier_code as supplier_code,
|
||||
t2.supplier_name as supplier_name,
|
||||
t2.material_code as item_code,
|
||||
t2.material_name as item_name,
|
||||
t1.id as id,
|
||||
t1.material as material,
|
||||
t1.material_name as material_name,
|
||||
t1.third_code as third_code,
|
||||
t1.test_item as test_item,
|
||||
t1.pb as pb,
|
||||
t1.cd as cd,
|
||||
t1.hg as hg,
|
||||
t1.cr6 as cr6,
|
||||
t1.pbbs as pbbs,
|
||||
t1.pbdes as pbdes,
|
||||
t1.dbp as dbp,
|
||||
t1.bbp as bbp,
|
||||
t1.dehp as dehp,
|
||||
t1.dibp as dibp,
|
||||
t1.cl as cl,
|
||||
t1.br as br,
|
||||
COALESCE(CONVERT(VARCHAR(19), t1.test_date, 120), '1970-01-01 00:00:00') as test_date,
|
||||
'http://srm.well-trust.com:8090/hexin-boot/sys/common/static/' + COALESCE(t1.attachment, '') as attachment
|
||||
from
|
||||
control_harmful_substances t1,
|
||||
control_harmful t2
|
||||
where
|
||||
1 = 1
|
||||
and t1.control_harmful_id = t2.id
|
||||
and t1.def11 is null
|
||||
and t2.def1 = '7'
|
||||
"""
|
||||
|
||||
|
||||
def _connect(conn_str: str):
|
||||
if pyodbc is None:
|
||||
raise RuntimeError('pyodbc is not installed')
|
||||
raise RuntimeError("pyodbc is not installed")
|
||||
return pyodbc.connect(conn_str, timeout=15)
|
||||
|
||||
|
||||
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(FIXED_ROHS_SQL)
|
||||
if params:
|
||||
cur.execute(sql, params)
|
||||
else:
|
||||
cur.execute(sql)
|
||||
cols = [c[0] for c in cur.description]
|
||||
rows = cur.fetchall()
|
||||
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
||||
@@ -66,121 +34,315 @@ def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
conn.close()
|
||||
|
||||
|
||||
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> None:
|
||||
def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?",
|
||||
(run_no, judgement, reason, str(row_id)),
|
||||
)
|
||||
cur.execute(sql, params)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]:
|
||||
judgement = str(data.get("judgement") or data.get("result") or "人工判定").strip()
|
||||
reason = str(data.get("reason") or "").strip()
|
||||
if judgement not in {"合格", "不合格", "人工判定"}:
|
||||
reason = (reason + " | 返回值异常:" + judgement).strip(" |")
|
||||
judgement = "人工判定"
|
||||
return judgement, reason
|
||||
def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]:
|
||||
dify_result = str(data.get("dify_result")).strip()
|
||||
dify_message = str(data.get("dify_message")).strip()
|
||||
if dify_result not in {"合格", "不合格", "人工判定"}:
|
||||
dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |")
|
||||
dify_result = "人工判定"
|
||||
return dify_result, dify_message
|
||||
|
||||
|
||||
def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user: str = "schedule_system", wait_seconds: int = 120, run_id: int | None = None) -> tuple[int, int, int, int, list[dict[str, Any]], list[str]]:
|
||||
def _build_record_text(
|
||||
item: dict[str, Any],
|
||||
alias_order: list[str],
|
||||
header_labels: dict[str, str],
|
||||
detail_rows: list[dict[str, Any]] | None = None,
|
||||
detail_alias_order: list[str] | None = None,
|
||||
) -> str:
|
||||
lines: list[str] = []
|
||||
for key in alias_order:
|
||||
label = header_labels.get(key, key)
|
||||
value = item.get(key)
|
||||
text = "" if value is None else str(value)
|
||||
lines.append(f"{label}: {text}")
|
||||
if detail_rows and detail_alias_order:
|
||||
lines.append("成分明细:")
|
||||
for idx, dr in enumerate(detail_rows, 1):
|
||||
detail_parts: list[str] = []
|
||||
for dk in detail_alias_order:
|
||||
dl = header_labels.get(dk, dk)
|
||||
dv = dr.get(dk)
|
||||
detail_parts.append(f"{dl}: {'' if dv is None else str(dv)}")
|
||||
lines.append(f" [{idx}] " + ", ".join(detail_parts))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
RecordBuilder = Callable[[str, dict[str, Any], str], tuple[str, str | None]]
|
||||
WritebackFunc = Callable[..., None]
|
||||
PreDifyFunc = Callable[[str, dict[str, Any], str], dict[str, Any] | None]
|
||||
|
||||
_MAX_STEP_LOGS_PER_ROW = 200
|
||||
_MAX_DIFY_RESPONSE_LEN = 4000
|
||||
|
||||
|
||||
def _ts() -> str:
|
||||
return datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
def _make_step(
|
||||
step: str,
|
||||
status: str,
|
||||
started_at: str,
|
||||
finished_at: str,
|
||||
row_id: str | None = None,
|
||||
**extra: Any,
|
||||
) -> dict[str, Any]:
|
||||
entry: dict[str, Any] = {
|
||||
"step": step,
|
||||
"status": status,
|
||||
"started_at": started_at,
|
||||
"finished_at": finished_at,
|
||||
"duration_ms": int((datetime.fromisoformat(finished_at) - datetime.fromisoformat(started_at)).total_seconds() * 1000),
|
||||
}
|
||||
if row_id:
|
||||
entry["row_id"] = row_id
|
||||
entry.update(extra)
|
||||
return entry
|
||||
|
||||
|
||||
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
||||
|
||||
|
||||
def _run_check_job_loop(
|
||||
*,
|
||||
conn_str: str,
|
||||
run_no: str,
|
||||
agent,
|
||||
user: str,
|
||||
wait_seconds: int,
|
||||
run_id: int | None,
|
||||
fetch_fn: Callable[[str], list[dict[str, Any]]],
|
||||
build_record_fn: RecordBuilder,
|
||||
writeback_fn: WritebackFunc,
|
||||
writeback_sql: str = "",
|
||||
row_id_key: str,
|
||||
log_prefix: str,
|
||||
fetch_sql: str = "",
|
||||
max_rows: int = 0,
|
||||
pre_dify_fn: PreDifyFunc | None = None,
|
||||
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||
|
||||
use_dify = agent is not None
|
||||
if use_dify and not getattr(agent, "dify_api_key", None):
|
||||
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
||||
|
||||
rows = fetch_rohs_records(conn_str)
|
||||
total_count = len(rows)
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
t0 = _ts()
|
||||
try:
|
||||
rows = fetch_fn(conn_str)
|
||||
if max_rows > 0:
|
||||
rows = rows[:max_rows]
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"success",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "row_count": len(rows)},
|
||||
))
|
||||
except Exception as fetch_exc:
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"failed",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "error": str(fetch_exc)},
|
||||
))
|
||||
raise
|
||||
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
skipped_count = 0
|
||||
errors: list[str] = []
|
||||
all_errors: list[str] = []
|
||||
|
||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||
for idx, row in enumerate(rows):
|
||||
for row in rows:
|
||||
if run_id is not None and is_run_cancelled(run_id):
|
||||
item = dict(row)
|
||||
item.update({"judgement": "人工判定", "reason": "排程已被删除,执行中断", "writeback_ok": False, "error": "排程已被删除,执行中断"})
|
||||
item.update({
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": "排程已被删除,执行中断",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": "排程已被删除,执行中断",
|
||||
})
|
||||
skipped_count += 1
|
||||
details.append(item)
|
||||
continue
|
||||
|
||||
item = dict(row)
|
||||
row_id_value = str(row.get(row_id_key, ""))
|
||||
|
||||
if pre_dify_fn:
|
||||
t_pre = _ts()
|
||||
try:
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
except Exception as pre_exc:
|
||||
pre_result = {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"pre_dify执行异常:{pre_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(pre_exc),
|
||||
}
|
||||
step_logs.append(_make_step("pre_dify", "failed", t_pre, _ts(), row_id=row_id_value, detail={"error": str(pre_exc)}))
|
||||
|
||||
if pre_result is not None:
|
||||
item.update(pre_result)
|
||||
failed_count += 1
|
||||
all_errors.append(pre_result.get("writeback_err", ""))
|
||||
details.append(item)
|
||||
continue
|
||||
|
||||
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
|
||||
|
||||
dify_ok = False
|
||||
dify_result = "人工判定"
|
||||
dify_message = ""
|
||||
|
||||
try:
|
||||
if use_dify:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs={"inputs": {"run_no": run_no, "records": item}},
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
dify_inputs = {
|
||||
"run_no": run_no,
|
||||
"record": record_text,
|
||||
"attachment_url": attachment_url,
|
||||
}
|
||||
t_dify = _ts()
|
||||
try:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs=dify_inputs,
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
except Exception as dify_exc:
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"error": str(dify_exc),
|
||||
}))
|
||||
raise
|
||||
|
||||
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
|
||||
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
||||
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
|
||||
|
||||
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
|
||||
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
|
||||
judgement = "人工判定"
|
||||
reason = f"Dify执行失败:{err_detail}"
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": err_detail, "dify_output": dify_res if isinstance(dify_res, dict) else {}})
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"Dify执行失败:{err_detail}"
|
||||
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"response": _truncate_str(str(dify_res)),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
}))
|
||||
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": err_detail,
|
||||
})
|
||||
failed_count += 1
|
||||
errors.append(f"Dify row_id={row.get('id')}: {err_detail}")
|
||||
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
|
||||
details.append(item)
|
||||
continue
|
||||
else:
|
||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[srm-dify] judgement=%s reason=%s",
|
||||
outputs.get("judgement") if isinstance(outputs, dict) else None,
|
||||
outputs.get("reason") if isinstance(outputs, dict) else None,
|
||||
"[%s] %s=%s dify_result=%s dify_message=%s",
|
||||
log_prefix, log_prefix, row_id_value,
|
||||
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
|
||||
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
|
||||
)
|
||||
judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {})
|
||||
item["dify_output"] = outputs if isinstance(outputs, dict) else {}
|
||||
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
|
||||
dify_ok = True
|
||||
|
||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
||||
"response": {
|
||||
"status": dify_status,
|
||||
"dify_result": dify_result,
|
||||
"dify_message": _truncate_str(dify_message),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
},
|
||||
}))
|
||||
else:
|
||||
judgement = "人工判定"
|
||||
reason = "未配置 Agent ID,跳过 Dify"
|
||||
dify_result = "人工判定"
|
||||
dify_message = "未配置 Agent ID,跳过 Dify"
|
||||
dify_ok = True
|
||||
|
||||
wb_sql = writeback_sql
|
||||
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
||||
t_wb = _ts()
|
||||
try:
|
||||
writeback_rohs(
|
||||
conn_str,
|
||||
row_id=str(row.get("id")),
|
||||
run_no=run_no,
|
||||
judgement=judgement,
|
||||
reason=reason,
|
||||
)
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": item.get("error")})
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": True,
|
||||
"writeback_err": item.get("writeback_err"),
|
||||
})
|
||||
if dify_ok:
|
||||
success_count += 1
|
||||
except Exception as wb_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[srm-dify] writeback failed row_id=%s error=%s", row.get("id"), wb_exc)
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(wb_exc)})
|
||||
current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc)
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
"error": str(wb_exc),
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(wb_exc),
|
||||
})
|
||||
if dify_ok:
|
||||
failed_count += 1
|
||||
errors.append(f"writeback row_id={row.get('id')}: {wb_exc}")
|
||||
all_errors.append(f"writeback {log_prefix}={row_id_value}: {wb_exc}")
|
||||
except Exception as exc:
|
||||
judgement = "人工判定"
|
||||
reason = f"执行异常:{exc}"
|
||||
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(exc)})
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"执行异常:{exc}"
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(exc),
|
||||
})
|
||||
failed_count += 1
|
||||
errors.append(str(exc))
|
||||
all_errors.append(str(exc))
|
||||
t_wb2 = _ts()
|
||||
try:
|
||||
writeback_rohs(
|
||||
conn_str,
|
||||
row_id=str(row.get("id")),
|
||||
run_no=run_no,
|
||||
judgement=judgement,
|
||||
reason=reason,
|
||||
)
|
||||
item["writeback_ok"] = True
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
|
||||
item["writeback_srm"] = True
|
||||
except Exception as wb_exc:
|
||||
item["writeback_ok"] = False
|
||||
item["error"] = f"{item.get('error', '')}; writeback failed: {wb_exc}"
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb2, _ts(), row_id=row_id_value, detail={"error": str(wb_exc), "note": "fallback writeback also failed"}))
|
||||
item["writeback_srm"] = False
|
||||
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
||||
|
||||
details.append(item)
|
||||
|
||||
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
|
||||
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
|
||||
|
||||
total_count = success_count + failed_count + skipped_count
|
||||
return total_count, success_count, failed_count, skipped_count, details, errors
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlencode
|
||||
import uuid
|
||||
|
||||
@@ -62,16 +63,13 @@ def _get_access_token() -> str:
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
def _create_audit(
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
) -> dict:
|
||||
trace_id = uuid.uuid4().hex
|
||||
trace_id: str,
|
||||
) -> WecomNotifyAudit:
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
@@ -83,6 +81,83 @@ def send_wecom_event_message(
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
return audit
|
||||
|
||||
|
||||
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
|
||||
token = _get_access_token()
|
||||
url = (
|
||||
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
|
||||
f'?access_token={token}&type=file'
|
||||
)
|
||||
resp = requests.post(
|
||||
url,
|
||||
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode', 0) != 0 or not data.get('media_id'):
|
||||
raise RuntimeError(f"WeCom media upload failed: {data}")
|
||||
return data['media_id']
|
||||
|
||||
|
||||
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'file',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'file': {'media_id': media_id},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
) -> dict:
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
@@ -100,28 +175,9 @@ def send_wecom_event_message(
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
token = _get_access_token()
|
||||
jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = jump_url
|
||||
payload = {
|
||||
'touser': user.wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (content or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
data = send_wecom_textcard_message(user.wecom_userid, title, content, jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
"""add_schedule_task_config_and_data_source_type
|
||||
|
||||
Revision ID: 9f3438dc97ca
|
||||
Revises: a1b2c3d4e5f6
|
||||
Create Date: 2026-05-20 13:42:57.822050
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '9f3438dc97ca'
|
||||
down_revision = 'a1b2c3d4e5f6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('schedule_task_configs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('schedule_task_id', sa.Integer(), nullable=False),
|
||||
sa.Column('row_id_key', sa.String(length=64), nullable=False),
|
||||
sa.Column('log_prefix', sa.String(length=128), nullable=False),
|
||||
sa.Column('base_fetch_sql', sa.Text(), nullable=True),
|
||||
sa.Column('fetch_where_conditions', sa.Text(), nullable=True),
|
||||
sa.Column('fetch_order_by', sa.String(length=500), nullable=True),
|
||||
sa.Column('writeback_sql', sa.Text(), nullable=True),
|
||||
sa.Column('detail_sql', sa.Text(), nullable=True),
|
||||
sa.Column('alias_order', sa.JSON(), nullable=True),
|
||||
sa.Column('detail_alias_order', sa.JSON(), nullable=True),
|
||||
sa.Column('header_labels', sa.JSON(), nullable=True),
|
||||
sa.Column('ds_db_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('ds_host', sa.String(length=255), nullable=True),
|
||||
sa.Column('ds_port', sa.String(length=64), nullable=True),
|
||||
sa.Column('ds_database', sa.String(length=128), nullable=True),
|
||||
sa.Column('ds_username', sa.String(length=128), nullable=True),
|
||||
sa.Column('ds_password', sa.String(length=255), nullable=True),
|
||||
sa.Column('api_url', sa.String(length=500), nullable=True),
|
||||
sa.Column('api_method', sa.String(length=16), nullable=False),
|
||||
sa.Column('api_headers', sa.JSON(), nullable=True),
|
||||
sa.Column('api_body_template', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['schedule_task_id'], ['schedule_tasks.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('schedule_task_id')
|
||||
)
|
||||
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_schedule_task_configs_schedule_task_id'), ['schedule_task_id'], unique=False)
|
||||
|
||||
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('data_source_type', sa.String(length=32), nullable=False, server_default='database'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
|
||||
batch_op.drop_column('data_source_type')
|
||||
|
||||
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_schedule_task_configs_schedule_task_id'))
|
||||
|
||||
op.drop_table('schedule_task_configs')
|
||||
@@ -0,0 +1,23 @@
|
||||
"""add step_logs to schedule_runs
|
||||
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises: c0ae052bd24e
|
||||
Create Date: 2026-05-19 12:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a1b2c3d4e5f6'
|
||||
down_revision = 'c0ae052bd24e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('schedule_runs', sa.Column('step_logs', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('schedule_runs', 'step_logs')
|
||||
@@ -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')
|
||||
@@ -0,0 +1,27 @@
|
||||
"""add ds_driver encrypt trust_cert
|
||||
|
||||
Revision ID: b7a1c2d3e4f5
|
||||
Revises: 9f3438dc97ca
|
||||
Create Date: 2026-05-20 18:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'b7a1c2d3e4f5'
|
||||
down_revision = '9f3438dc97ca'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('schedule_task_configs', sa.Column('ds_driver', sa.String(length=128), nullable=True))
|
||||
op.add_column('schedule_task_configs', sa.Column('ds_encrypt', sa.String(length=16), nullable=True))
|
||||
op.add_column('schedule_task_configs', sa.Column('ds_trust_cert', sa.String(length=16), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('schedule_task_configs', 'ds_trust_cert')
|
||||
op.drop_column('schedule_task_configs', 'ds_encrypt')
|
||||
op.drop_column('schedule_task_configs', 'ds_driver')
|
||||
@@ -0,0 +1,32 @@
|
||||
"""replace mail notify fields with wecom notify fields
|
||||
|
||||
Revision ID: c1d2e3f4a5b6
|
||||
Revises: a9b0c1d2e3f4
|
||||
Create Date: 2026-05-20 00:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'c1d2e3f4a5b6'
|
||||
down_revision = 'a9b0c1d2e3f4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('schedule_runs', sa.Column('wecom_notified', sa.Boolean(), nullable=True, server_default=sa.text('false')))
|
||||
op.add_column('schedule_runs', sa.Column('wecom_notified_at', sa.DateTime(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('wecom_notify_error', sa.Text(), nullable=True))
|
||||
op.drop_column('schedule_runs', 'mail_sent')
|
||||
op.drop_column('schedule_runs', 'mail_sent_at')
|
||||
op.drop_column('schedule_runs', 'mail_error')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.add_column('schedule_runs', sa.Column('mail_error', sa.Text(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('mail_sent_at', sa.DateTime(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('mail_sent', sa.Boolean(), nullable=True, server_default=sa.text('false')))
|
||||
op.drop_column('schedule_runs', 'wecom_notify_error')
|
||||
op.drop_column('schedule_runs', 'wecom_notified_at')
|
||||
op.drop_column('schedule_runs', 'wecom_notified')
|
||||
@@ -0,0 +1,71 @@
|
||||
"""ensure agents table has primary key on id
|
||||
|
||||
Revision ID: f7a8b9c0d1e2
|
||||
Revises: f6d4e5f6a7b8
|
||||
Create Date: 2026-05-20 00:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'f7a8b9c0d1e2'
|
||||
down_revision = 'f6d4e5f6a7b8'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
conn = op.get_bind()
|
||||
inspector = sa.inspect(conn)
|
||||
|
||||
if 'agents' not in inspector.get_table_names():
|
||||
return
|
||||
|
||||
pk = inspector.get_pk_constraint('agents') or {}
|
||||
constrained_columns = pk.get('constrained_columns') or []
|
||||
if constrained_columns:
|
||||
return
|
||||
|
||||
duplicate_count = conn.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM (
|
||||
SELECT id
|
||||
FROM agents
|
||||
GROUP BY id
|
||||
HAVING COUNT(*) > 1
|
||||
) t
|
||||
"""
|
||||
)
|
||||
).scalar_one()
|
||||
if duplicate_count > 0:
|
||||
raise RuntimeError(
|
||||
"Cannot add PRIMARY KEY to agents.id because duplicate id values exist. "
|
||||
"Please deduplicate agents.id first, then rerun migration."
|
||||
)
|
||||
|
||||
null_count = conn.execute(
|
||||
sa.text("SELECT COUNT(*) FROM agents WHERE id IS NULL")
|
||||
).scalar_one()
|
||||
if null_count > 0:
|
||||
raise RuntimeError(
|
||||
"Cannot add PRIMARY KEY to agents.id because NULL id values exist. "
|
||||
"Please fix NULL ids first, then rerun migration."
|
||||
)
|
||||
|
||||
op.execute('ALTER TABLE agents ADD CONSTRAINT agents_pkey PRIMARY KEY (id)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
conn = op.get_bind()
|
||||
inspector = sa.inspect(conn)
|
||||
if 'agents' not in inspector.get_table_names():
|
||||
return
|
||||
|
||||
pk = inspector.get_pk_constraint('agents') or {}
|
||||
pk_name = pk.get('name')
|
||||
cols = pk.get('constrained_columns') or []
|
||||
if pk_name == 'agents_pkey' and cols == ['id']:
|
||||
op.drop_constraint('agents_pkey', 'agents', type_='primary')
|
||||
@@ -0,0 +1,21 @@
|
||||
"""merge heads after agents pk fix
|
||||
|
||||
Revision ID: f8b9c0d1e2f3
|
||||
Revises: c0ae052bd24e, f7a8b9c0d1e2
|
||||
Create Date: 2026-05-20 00:30:00.000000
|
||||
|
||||
"""
|
||||
|
||||
|
||||
revision = 'f8b9c0d1e2f3'
|
||||
down_revision = ('c0ae052bd24e', 'f7a8b9c0d1e2')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -34,3 +34,4 @@ beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
typer==0.17.4
|
||||
croniter
|
||||
pyyaml
|
||||
@@ -61,7 +61,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
duration_ms=100,
|
||||
mail_sent=False,
|
||||
wecom_notified=False,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
Reference in new issue
Block a user