Merge branch 'hugo' into dev
This commit is contained in:
commit
40b25ec988
21 files changed
+2185
-593
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': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
|
||||
@@ -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,285 @@ 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.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):
|
||||
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
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
run_no = f"TEST{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
||||
return jsonify({
|
||||
"run_no": run_no,
|
||||
"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.pop("_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
|
||||
|
||||
run_no = f"TEST{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
||||
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=None,
|
||||
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,
|
||||
)
|
||||
|
||||
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_no,
|
||||
"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:
|
||||
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 +297,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 +311,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 +340,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))
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ class Config:
|
||||
'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):
|
||||
|
||||
@@ -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,6 +643,7 @@ 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_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
|
||||
@@ -8,16 +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 (
|
||||
SRM_MSDS_HEADER_LABELS,
|
||||
SRM_MSDS_SQL_ALIAS_ORDER,
|
||||
SRM_ROHS_HEADER_LABELS,
|
||||
SRM_ROHS_SQL_ALIAS_ORDER,
|
||||
run_msds_doc_check_dify_job,
|
||||
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]
|
||||
|
||||
|
||||
@@ -74,7 +73,13 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
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)
|
||||
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,
|
||||
@@ -83,13 +88,21 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=(5, 60))
|
||||
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:
|
||||
@@ -99,6 +112,11 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
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
|
||||
@@ -109,56 +127,151 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
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))
|
||||
return total, success, failed, 0, details, [str(e) for e in errors if str(e).strip()]
|
||||
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_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_rohs_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
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.pop("_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=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
agent=agent,
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
def _run_srm_msds_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_msds_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
run_no=run.run_no,
|
||||
agent=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
)
|
||||
|
||||
|
||||
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
||||
"default": _run_common_executor,
|
||||
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
||||
"srm_msds_doc_check": _run_srm_msds_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)
|
||||
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"]
|
||||
return _run_common_executor
|
||||
|
||||
|
||||
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||
@@ -180,5 +293,23 @@ def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] |
|
||||
return None, None
|
||||
|
||||
|
||||
register_schedule_header("srm_rohs_doc_check", SRM_ROHS_SQL_ALIAS_ORDER, SRM_ROHS_HEADER_LABELS)
|
||||
register_schedule_header("srm_msds_doc_check", SRM_MSDS_SQL_ALIAS_ORDER, SRM_MSDS_HEADER_LABELS)
|
||||
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
|
||||
@@ -52,6 +52,7 @@ 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,
|
||||
|
||||
@@ -58,9 +58,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 +148,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()
|
||||
@@ -211,6 +215,7 @@ 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,
|
||||
|
||||
@@ -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,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
@@ -12,169 +13,6 @@ except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
FETCHD_ROHS_SQL = """
|
||||
select
|
||||
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'
|
||||
"""
|
||||
|
||||
SRM_ROHS_SQL_ALIAS_ORDER: list[str] = [
|
||||
"id",
|
||||
"supplier_code",
|
||||
"supplier_name",
|
||||
"item_code",
|
||||
"item_name",
|
||||
"material",
|
||||
"material_name",
|
||||
"third_code",
|
||||
"test_item",
|
||||
"pb",
|
||||
"cd",
|
||||
"hg",
|
||||
"cr6",
|
||||
"pbbs",
|
||||
"pbdes",
|
||||
"dbp",
|
||||
"bbp",
|
||||
"dehp",
|
||||
"dibp",
|
||||
"cl",
|
||||
"br",
|
||||
"test_date",
|
||||
"attachment",
|
||||
]
|
||||
|
||||
SRM_ROHS_HEADER_LABELS: dict[str, str] = {
|
||||
"id": "SRM系统ID",
|
||||
"supplier_code": "供应商编码",
|
||||
"supplier_name": "供应商名称",
|
||||
"item_code": "物料编码",
|
||||
"item_name": "物料名称",
|
||||
"material": "材质",
|
||||
"material_name": "材质名称",
|
||||
"third_code": "第三方编码",
|
||||
"test_item": "检测项目",
|
||||
"pb": "铅(Pb)",
|
||||
"cd": "镉(Cd)",
|
||||
"hg": "汞(Hg)",
|
||||
"cr6": "六价铬(Cr6+)",
|
||||
"pbbs": "多溴联苯(PBBs)",
|
||||
"pbdes": "多溴二苯醚(PBDEs)",
|
||||
"dbp": "邻苯二甲酸二丁酯(DBP)",
|
||||
"bbp": "邻苯二甲酸丁苄酯(BBP)",
|
||||
"dehp": "邻苯二甲酸二(2-乙基己)酯(DEHP)",
|
||||
"dibp": "邻苯二甲酸二异丁酯(DIBP)",
|
||||
"cl": "氯(Cl)",
|
||||
"br": "溴(Br)",
|
||||
"test_date": "检测日期",
|
||||
"attachment": "附件地址",
|
||||
"dify_result": "判定结果",
|
||||
"dify_message": "判定说明",
|
||||
"writeback_srm": "回写SRM",
|
||||
"writeback_err": "回写错误",
|
||||
}
|
||||
|
||||
FETCHD_MSDS_SQL = """
|
||||
select
|
||||
cc.id as cc_id,
|
||||
cc.supplier_code as supplier_code,
|
||||
cc.supplier_name as supplier_name,
|
||||
cc.material_code as material_code,
|
||||
cc.material_name as material_name,
|
||||
ccm.id as ccm_id,
|
||||
ccm.material as material,
|
||||
ccm.attachment as attachment,
|
||||
ccm.weight as weight
|
||||
from
|
||||
chemical_composition cc
|
||||
inner join chemical_composition_management ccm on
|
||||
cc.id = ccm.chemical_composition_id
|
||||
where
|
||||
cc.def1 = '7'
|
||||
and ccm.def11 is null
|
||||
order by ccm.id
|
||||
"""
|
||||
|
||||
FETCHD_MSDS_DETAIL_SQL = """
|
||||
select
|
||||
ccmb.cas_no as cas_no,
|
||||
ccmb.component_name as component_name,
|
||||
ccmb.concentration as concentration
|
||||
from
|
||||
chemical_composition_management_b ccmb
|
||||
where
|
||||
ccmb.chemical_composition_management_id = ?
|
||||
order by ccmb.id
|
||||
"""
|
||||
|
||||
SRM_MSDS_SQL_ALIAS_ORDER: list[str] = [
|
||||
"cc_id",
|
||||
"supplier_code",
|
||||
"supplier_name",
|
||||
"material_code",
|
||||
"material_name",
|
||||
"ccm_id",
|
||||
"material",
|
||||
"attachment",
|
||||
"weight",
|
||||
]
|
||||
|
||||
SRM_MSDS_DETAIL_ALIAS_ORDER: list[str] = [
|
||||
"cas_no",
|
||||
"component_name",
|
||||
"concentration",
|
||||
]
|
||||
|
||||
SRM_MSDS_HEADER_LABELS: dict[str, str] = {
|
||||
"cc_id": "SRM系统CC_ID",
|
||||
"supplier_code": "供应商编码",
|
||||
"supplier_name": "供应商名称",
|
||||
"material_code": "物料编码",
|
||||
"material_name": "物料名称",
|
||||
"ccm_id": "SRM系统CCM_ID",
|
||||
"material": "材质",
|
||||
"attachment": "附件地址",
|
||||
"weight": "重量",
|
||||
"cas_no": "CAS号",
|
||||
"component_name": "成分名称",
|
||||
"concentration": "浓度",
|
||||
"detail_text": "成分明细",
|
||||
"dify_result": "判定结果",
|
||||
"dify_message": "判定说明",
|
||||
"writeback_srm": "回写SRM",
|
||||
"writeback_err": "回写错误",
|
||||
}
|
||||
|
||||
|
||||
def _connect(conn_str: str):
|
||||
if pyodbc is None:
|
||||
raise RuntimeError("pyodbc is not installed")
|
||||
@@ -244,6 +82,40 @@ 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(
|
||||
*,
|
||||
@@ -256,17 +128,41 @@ def _run_check_job_loop(
|
||||
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]]:
|
||||
) -> 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_fn(conn_str)
|
||||
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
|
||||
@@ -290,7 +186,18 @@ def _run_check_job_loop(
|
||||
row_id_value = str(row.get(row_id_key, ""))
|
||||
|
||||
if pre_dify_fn:
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
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
|
||||
@@ -306,22 +213,41 @@ def _run_check_job_loop(
|
||||
|
||||
try:
|
||||
if use_dify:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs={
|
||||
"run_no": run_no,
|
||||
"record": record_text,
|
||||
"attachment_url": attachment_url,
|
||||
},
|
||||
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}"
|
||||
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,
|
||||
@@ -343,13 +269,30 @@ def _run_check_job_loop(
|
||||
)
|
||||
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:
|
||||
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_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,
|
||||
@@ -361,6 +304,11 @@ def _run_check_job_loop(
|
||||
except Exception as wb_exc:
|
||||
if current_app:
|
||||
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,
|
||||
@@ -381,120 +329,20 @@ def _run_check_job_loop(
|
||||
})
|
||||
failed_count += 1
|
||||
all_errors.append(str(exc))
|
||||
t_wb2 = _ts()
|
||||
try:
|
||||
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:
|
||||
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, all_errors
|
||||
|
||||
|
||||
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_ROHS_SQL)
|
||||
|
||||
|
||||
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str) -> None:
|
||||
_execute_writeback(
|
||||
conn_str,
|
||||
"UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?",
|
||||
(run_no, dify_result, dify_message, str(row_id)),
|
||||
)
|
||||
|
||||
|
||||
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(conn_str: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, SRM_ROHS_SQL_ALIAS_ORDER, SRM_ROHS_HEADER_LABELS)
|
||||
return text, item.get("attachment")
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=run_id,
|
||||
fetch_fn=fetch_rohs_records,
|
||||
build_record_fn=_build_record,
|
||||
writeback_fn=writeback_rohs,
|
||||
row_id_key="id",
|
||||
log_prefix="srm-rohs-dify",
|
||||
)
|
||||
|
||||
|
||||
def fetch_msds_records(conn_str: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_MSDS_SQL)
|
||||
|
||||
|
||||
def fetch_msds_detail_records(conn_str: str, ccm_id: str) -> list[dict[str, Any]]:
|
||||
return _fetch_records(conn_str, FETCHD_MSDS_DETAIL_SQL, params=(str(ccm_id),))
|
||||
|
||||
|
||||
def writeback_msds(conn_str: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str) -> None:
|
||||
_execute_writeback(
|
||||
conn_str,
|
||||
"UPDATE chemical_composition_management SET def11=?, def12=?, def13=? WHERE id=?",
|
||||
(run_no, dify_result, dify_message, str(row_id)),
|
||||
)
|
||||
|
||||
|
||||
def _msds_pre_dify_fn(conn_str: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = fetch_msds_detail_records(conn_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"{SRM_MSDS_HEADER_LABELS.get(dk, dk)}: {dr.get(dk, '')}" for dk in SRM_MSDS_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
|
||||
|
||||
|
||||
def _msds_build_record(conn_str: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
detail_rows = item.pop("_detail_rows", [])
|
||||
text = _build_record_text(item, SRM_MSDS_SQL_ALIAS_ORDER, SRM_MSDS_HEADER_LABELS, detail_rows, SRM_MSDS_DETAIL_ALIAS_ORDER)
|
||||
return text, item.get("attachment")
|
||||
|
||||
|
||||
def run_msds_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]]:
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=wait_seconds,
|
||||
run_id=run_id,
|
||||
fetch_fn=fetch_msds_records,
|
||||
build_record_fn=_msds_build_record,
|
||||
writeback_fn=writeback_msds,
|
||||
row_id_key="ccm_id",
|
||||
log_prefix="srm-msds-dify",
|
||||
pre_dify_fn=_msds_pre_dify_fn,
|
||||
)
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|
||||
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,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')
|
||||
@@ -34,3 +34,4 @@ beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
typer==0.17.4
|
||||
croniter
|
||||
pyyaml
|
||||
@@ -11,6 +11,7 @@ export interface ScheduleTask {
|
||||
wait_seconds: number;
|
||||
dify_agent_id?: number | null;
|
||||
platform_api_path?: string | null;
|
||||
data_source_type?: string;
|
||||
notify_user_ids_json: number[];
|
||||
notify_enabled: boolean;
|
||||
enabled: boolean;
|
||||
@@ -38,6 +39,7 @@ export interface ScheduleRun {
|
||||
api_request_json?: Record<string, any> | null;
|
||||
api_response_json?: Record<string, any> | null;
|
||||
response_summary_json?: Record<string, any> | null;
|
||||
step_logs?: StepLog[] | null;
|
||||
error_message?: string | null;
|
||||
excel_file_name?: string | null;
|
||||
excel_file_size?: number | null;
|
||||
@@ -47,25 +49,86 @@ export interface ScheduleRun {
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface StepLog {
|
||||
step: string;
|
||||
status: string;
|
||||
started_at?: string;
|
||||
finished_at?: string;
|
||||
duration_ms?: number;
|
||||
row_id?: string;
|
||||
detail?: Record<string, any>;
|
||||
}
|
||||
|
||||
async function getJson<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export const listAdminSchedules = () => getJson<ScheduleTask[]>('/api/admin/schedules');
|
||||
export const createAdminSchedule = (payload: Partial<ScheduleTask>) =>
|
||||
export const listAdminSchedules = () =>
|
||||
getJson<ScheduleTask[]>('/api/admin/schedules');
|
||||
|
||||
export const getAdminScheduleTaskConfig = (taskId: number) =>
|
||||
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
|
||||
|
||||
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
|
||||
fetch(`/api/admin/schedule-config/${taskId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
}).then(r => {
|
||||
if (!r.ok) throw new Error('Update config failed');
|
||||
return r.json();
|
||||
});
|
||||
|
||||
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
||||
fetch(`/api/admin/schedule-config/${taskId}/test-sql`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
}).then(r => {
|
||||
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test failed'); });
|
||||
return r.json();
|
||||
});
|
||||
|
||||
export interface TestScheduleRunResult {
|
||||
run_no: string;
|
||||
sql: string;
|
||||
limit: number;
|
||||
total_count: number;
|
||||
success_count: number;
|
||||
failed_count: number;
|
||||
skipped_count: number;
|
||||
details: Record<string, any>[];
|
||||
errors: string[];
|
||||
step_logs: StepLog[];
|
||||
dify_agent_id: number | null;
|
||||
}
|
||||
|
||||
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
||||
fetch(`/api/admin/schedule-config/${taskId}/test-run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
}).then(r => {
|
||||
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test run failed'); });
|
||||
return r.json() as Promise<TestScheduleRunResult>;
|
||||
});
|
||||
|
||||
export const createAdminSchedule = (payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
||||
fetch('/api/admin/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask>) =>
|
||||
|
||||
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
||||
fetch(`/api/admin/schedules/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const deleteAdminSchedule = (id: number) =>
|
||||
fetch(`/api/admin/schedules/${id}`, {
|
||||
method: 'DELETE',
|
||||
|
||||
+941
-158
File diff suppressed because it is too large.
Load diff
@@ -1002,8 +1002,25 @@ const workspaceScheduleRuns = ref<ScheduleRun[]>([]);
|
||||
const workspaceScheduleLoading = ref(false);
|
||||
const wsScheduleStatusFilter = ref('all');
|
||||
const wsScheduleNameFilter = ref('');
|
||||
const wsScheduleStartedAfter = ref('');
|
||||
const wsScheduleStartedBefore = ref('');
|
||||
const toDateTimeLocalValue = (date: Date) => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
};
|
||||
|
||||
const todayStartLocal = () => {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return toDateTimeLocalValue(d);
|
||||
};
|
||||
|
||||
const todayEndLocal = () => {
|
||||
const d = new Date();
|
||||
d.setHours(23, 59, 59, 0);
|
||||
return toDateTimeLocalValue(d);
|
||||
};
|
||||
|
||||
const wsScheduleStartedAfter = ref(todayStartLocal());
|
||||
const wsScheduleStartedBefore = ref(todayEndLocal());
|
||||
|
||||
const wsScheduleStatusOptions = [
|
||||
{ value: 'all', label: '全部状态' },
|
||||
@@ -1032,18 +1049,6 @@ const formatDateTime = (iso?: string | null) => {
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
};
|
||||
|
||||
const todayStart = () => {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.toISOString();
|
||||
};
|
||||
|
||||
const todayEnd = () => {
|
||||
const d = new Date();
|
||||
d.setHours(23, 59, 59, 0);
|
||||
return d.toISOString();
|
||||
};
|
||||
|
||||
const loadWorkspaceScheduleRuns = async () => {
|
||||
workspaceScheduleLoading.value = true;
|
||||
try {
|
||||
@@ -1063,8 +1068,8 @@ const loadWorkspaceScheduleRuns = async () => {
|
||||
const resetWsScheduleFilters = () => {
|
||||
wsScheduleStatusFilter.value = 'all';
|
||||
wsScheduleNameFilter.value = '';
|
||||
wsScheduleStartedAfter.value = todayStart().slice(0, 16);
|
||||
wsScheduleStartedBefore.value = todayEnd().slice(0, 16);
|
||||
wsScheduleStartedAfter.value = todayStartLocal();
|
||||
wsScheduleStartedBefore.value = todayEndLocal();
|
||||
loadWorkspaceScheduleRuns();
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user