Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-20 18:00:00 +08:00
commit 3cc556b9fd
33 files changed
+2856 -620

No files matched your search

Vendored
+212
View File
@@ -1,3 +1,152 @@
import groovy.json.JsonOutput
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
def notifyWecomDeploy(Map opts) {
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
return
}
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
def content = buildDeployNotifyMarkdown(opts)
try {
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
if (!webhookUrl) {
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
return
}
def payload = [
msgtype: 'markdown',
markdown: [content: content.markdown],
]
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
def httpCode = sh(
returnStdout: true,
script: '''
set +e
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
-X POST "$WECOM_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d @wecom-notify-payload.json)
echo "[WeCom] HTTP ${code}" >&2
cat wecom-notify-response.txt >&2 || true
echo "${code}"
'''
).trim()
def resp = readFile('wecom-notify-response.txt').trim()
if (httpCode == '200' && resp.contains('"errcode":0')) {
echo '[WeCom] 通知已发送'
} else {
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
}
}
} catch (Exception e) {
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
}
}
// PushPlus → 个人微信(方案3)。Token 存 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN,见 https://www.pushplus.plus/
def buildDeployNotifyMarkdown(Map opts) {
def envLabel = opts.envLabel ?: '部署环境'
def host = opts.host ?: '-'
def status = (opts.status ?: 'success').toString().toLowerCase()
def isSuccess = status == 'success'
def extraNote = (opts.extraNote ?: '').trim()
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
def buildLink = env.BUILD_URL ?: '-'
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
def lines = [
"## ${title}",
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
"> **提交**: `${shortCommit}`",
"> **目标主机**: ${host}",
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
]
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
lines << '> **备注**: 强制全量部署'
}
if (env.REMOTE_DRIFT_DETECTED == 'true') {
lines << '> **备注**: 远端版本漂移触发部署'
}
if (extraNote) {
lines << "> **说明**: ${extraNote}"
}
if (!isSuccess) {
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
}
return [title: title, markdown: lines.join('\n')]
}
def notifyPushPlusDeploy(Map opts) {
if ((env.DISABLE_DEPLOY_PUSHPLUS_NOTIFY ?: '').equalsIgnoreCase('true')) {
echo '[PushPlus] DISABLE_DEPLOY_PUSHPLUS_NOTIFY=true,跳过通知'
return
}
def credId = (opts.tokenCredId ?: env.PUSHPLUS_TOKEN_CRED ?: 'PUSHPLUS_DEPLOY_TOKEN').trim()
def content = buildDeployNotifyMarkdown(opts)
try {
withCredentials([string(credentialsId: credId, variable: 'PUSHPLUS_TOKEN')]) {
def token = PUSHPLUS_TOKEN?.trim()
if (!token) {
echo "[PushPlus] 凭据 ${credId} 为空,跳过通知"
return
}
def payload = [
token: token,
title: "[HxOps] ${content.title}",
content: content.markdown,
template: 'markdown',
channel: 'wechat',
]
def topic = (env.PUSHPLUS_TOPIC ?: '').trim()
if (topic) {
payload.topic = topic
}
writeFile(file: 'pushplus-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
def httpCode = sh(
returnStdout: true,
script: '''
set +e
code=$(curl -sS -o pushplus-notify-response.txt -w "%{http_code}" \
-X POST "https://www.pushplus.plus/send" \
-H "Content-Type: application/json" \
-d @pushplus-notify-payload.json)
echo "[PushPlus] HTTP ${code}" >&2
cat pushplus-notify-response.txt >&2 || true
echo "${code}"
'''
).trim()
def resp = readFile('pushplus-notify-response.txt').trim()
if (httpCode == '200' && (resp.contains('"code":200') || resp.contains('"code": 200'))) {
echo '[PushPlus] 微信通知已发送'
} else {
echo "[PushPlus] 发送可能失败,HTTP=${httpCode},响应=${resp}"
}
}
} catch (Exception e) {
echo "[PushPlus] 通知发送异常(不影响构建结果): ${e.message}"
}
}
// 企业微信 + PushPlus 微信双通道
def notifyDeployAll(Map opts) {
notifyWecomDeploy(opts)
notifyPushPlusDeploy(opts)
}
pipeline {
agent any
@@ -40,6 +189,9 @@ pipeline {
DEV_DEPLOY_ROOT = '/opt/hxops'
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
PUSHPLUS_TOPIC = 'hxops666'
}
stages {
@@ -242,6 +394,36 @@ pipeline {
}
echo "[Deploy Test] done"
}
post {
success {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为人工取消)',
)
}
}
}
}
stage('Deploy Prod') {
@@ -301,6 +483,36 @@ pipeline {
}
echo "[Deploy Prod] done"
}
post {
success {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
)
}
}
}
}
}
-58
View File
@@ -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
+2
View File
@@ -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
View File
@@ -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': '测试失败:请求异常(网络、超时或认证问题)。',
+5 -2
View File
@@ -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(
+83
View File
@@ -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,
})
+291 -1
View File
@@ -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))
+58
View File
@@ -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()
+1 -1
View File
@@ -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):
+45
View File
@@ -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))
+47 -12
View File
@@ -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,6 +341,9 @@ 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] = []
@@ -348,7 +354,8 @@ class DifyService:
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 attempt=%s",
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
request_id,
response.status_code,
response.reason,
attempt,
@@ -360,7 +367,8 @@ class DifyService:
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s attempt=%s body=%s",
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
request_id,
response.status_code,
url,
attempt,
@@ -386,9 +394,13 @@ class DifyService:
continue
event = data.get('event')
if current_app:
current_app.logger.info(
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
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')),
@@ -396,6 +408,16 @@ class DifyService:
)
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)
@@ -405,12 +427,15 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end: collected retriever resources=%s",
"[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()
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
@@ -420,6 +445,7 @@ class DifyService:
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
@@ -432,23 +458,32 @@ class DifyService:
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-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,
"[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),
latency,
data.get('conversation_id') or normalized_conversation_id,
)
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 attempt=%s: %s", attempt, e)
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
+178 -47
View File
@@ -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,
+239
View File
@@ -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)
+131 -283
View File
@@ -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
@@ -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')
+1
View File
@@ -34,3 +34,4 @@ beautifulsoup4==4.14.2
lxml==6.0.2
typer==0.17.4
croniter
pyyaml
+70
View File
@@ -266,3 +266,73 @@
1. 打通 OA userID 查询
2. 打通 workflow=652 请假单提交
3. 打通请假单状态轮询与企微通知
---
## 14. 移动端适配需求
### 14.1 项目背景
当前系统前端布局仅针对 PC 端设计,未做移动端响应式适配。员工使用手机浏览器访问时,侧边栏、导航区域等 PC 端专属布局会占用大量屏幕空间,导致核心内容区域过窄,操作体验差。需要增加移动端自动识别与适配能力。
### 14.2 需求目标
1. 系统自动检测屏幕方向,当屏幕高度大于宽度时识别为手机端并自动适配
2. 手机端未登录时仍先进入登录页面
3. 登录后默认进入通用入口 Chat 页面
4. PC 端左侧导航区域在移动端上不显示
5. 移动端右上角增加一个按钮图标
6. 点击右上角按钮进入个人管理设置页面
### 14.3 详细需求
#### MR-01 移动端自动识别
- 系统需根据 `window.innerHeight > window.innerWidth` 判定为手机竖屏状态
- 识别需实时响应屏幕方向变化(旋转屏幕时自动切换布局模式)
- 不依赖 User-Agent 判断,纯粹依据屏幕方向
#### MR-02 登录流程保留
- 手机端未登录时,仍进入现有的登录页面(WorkspaceView 登录表单)
- 登录页面在手机端需保持正常可用,登录表单居中显示
- 登录成功后自动跳转至 `/chat/{默认AgentID}` 页面
#### MR-03 登录后默认进入 Chat 页面
- 已登录用户访问根路径 `/` 时,自动重定向到 `/chat/16`(通用入口 Chat 页面)
- 未登录用户访问根路径 `/` 时,重定向到 `/workspace`(登录页)
- 受保护页面(如 `/chat/*`、`/profile`)未登录时重定向到登录页
#### MR-04 PC 端左侧导航移动端隐藏
- ChatView 的侧边栏(聊天记录、智能体列表等)在移动端完全隐藏
- WorkspaceView 的左侧导航栏(个人中心、应用管理等)在移动端完全隐藏
- 不再使用抽屉式或折叠式,直接不渲染侧边栏 DOM
#### MR-05 移动端顶部栏与右上角按钮
- ChatView 在移动端显示紧凑顶部栏,包含 AI 图标+Agent 名称,右侧显示个人设置图标按钮
- WorkspaceView 在移动端显示紧凑顶部栏,包含 AI 图标+「和信AI」标题,右侧显示个人设置图标按钮
- 使用 `UserCircle` 图标作为右上角按钮
#### MR-06 点击右上角进入个人设置页面
- 点击移动端右上角图标按钮后,路由跳转至 `/profile`(ProfileView 个人设置页面)
- ProfileView 返回按钮在移动端返回 Chat 页面,PC 端返回 Workspace 页面
### 14.4 非功能需求
- 移动端适配不能影响 PC 端现有布局和行为
- 屏幕方向变化需实时响应,无需刷新页面
- 移动端登录表单需保持可用性和可读性
### 14.5 验收标准
1. 手机竖屏访问时自动进入适配布局
2. 未登录时正确显示登录页
3. 登录后默认跳转到 Chat 页面
4. 移动端不显示 PC 端左侧导航/侧边栏
5. 移动端右上角可见个人设置图标按钮
6. 点击右上角按钮可进入个人设置页面
7. PC 端布局与行为无任何变化
@@ -349,3 +349,31 @@
- 能收到企微通知
- 流程类问题仍走知识库
- 所有操作都有日志可追踪
---
## 7. 移动端适配功能清单
### 7.1 功能总览
| 功能项 | 说明 | 状态 | 优先级 |
| --- | --- | --- | --- |
| 移动端自动识别 | 屏幕高度>宽度时判定为手机端,实时响应方向变化 | 已完成 | P0 |
| 手机端登录流程 | 未登录仍进入登录页,登录表单移动端可用 | 已完成 | P0 |
| 登录后默认进 Chat | 已登录访问根路径自动跳转 `/chat/16` | 已完成 | P0 |
| 受保护页面认证守卫 | 未登录访问受保护页面重定向到登录页 | 已完成 | P0 |
| PC 侧边栏移动端隐藏 | ChatView/WorkspaceView 侧边栏在手机端不渲染 | 已完成 | P0 |
| 移动端顶部栏 | 紧凑 header 显示 AI 图标+标题 | 已完成 | P0 |
| 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 |
| ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 |
### 7.2 验收清单
- 手机竖屏访问时自动进入适配布局
- 未登录时正确显示登录页
- 登录后默认跳转到 Chat 页面
- 移动端不显示 PC 端左侧导航/侧边栏
- 移动端右上角可见个人设置图标按钮
- 点击右上角按钮可进入个人设置页面
- PC 端布局与行为无任何变化
- 旋转屏幕后布局实时切换
+82 -2
View File
@@ -646,8 +646,88 @@ OA_STATUS_SYNC_BATCH_SIZE=100
该需求技术上完全可落地,最关键的实现路径是:
1. 聊天侧做意图路由
1.1. 聊天侧做意图路由
2. 数据侧打通 OA userID + WorkflowService + 状态查询
3. 平台侧补齐主记录表、状态日志表、轮询任务、通知模板
现有项目已经具备聊天路由、SQL Server 查询、企微通知、最小任务调度四个核心基础能力,因此本需求适合采用“增量扩展”的方式推进,而不需要重做一套独立系统。
现有项目已经具备聊天路由、SQL Server 查询、企微通知、最小任务调度四个核心基础能力,因此本需求适合采用"增量扩展"的方式推进,而不需要重做一套独立系统。
---
## 16. 移动端适配技术方案
### 16.1 设计目标
在现有 PC 端前端基础上,通过增量方式增加移动端自适应能力,不修改 PC 端的任何现有行为。
### 16.2 核心技术方案
#### 移动端识别:useIsMobile 组合函数
新增 `frontend/src/composables/useIsMobile.ts`,提供全局共享的移动端状态:
- **判定规则**:`window.innerHeight > window.innerWidth`(竖屏 = 手机)
- **实现方式**:全局单例 `ref` + `resize` 事件监听
- **声明周期管理**:引用计数自动挂载/卸载监听器,避免内存泄漏
- **实时响应**:旋转屏幕时自动切换布局模式
```typescript
// 核心逻辑
const isMobile = ref(false);
const update = () => { isMobile.value = window.innerHeight > window.innerWidth; };
```
#### 路由守卫改造
修改 `frontend/src/router/index.ts`,增加认证与默认跳转逻辑:
- 根路径 `/`:已登录 → `/chat/16`,未登录 → `/workspace`
- 受保护页面(`/chat/*`、`/profile`、`/admin`等):未登录重定向到 `/workspace`
- 公开路径白名单:`/`、`/workspace`、`/casdoor-callback`、`/reset-password`
#### ChatView 移动端适配
- 侧边栏 `aside` 添加 `v-if="!isMobile"`,移动端不渲染侧边栏 DOM
- 侧边栏遮罩层添加 `&& !isMobile` 条件
- 新增移动端顶部栏 `<header v-if="isMobile && currentAgent">`:
- 左侧:AI 图标 + Agent 名称
- 右侧:`UserCircle` 图标按钮,点击 `router.push('/profile')`
#### WorkspaceView 移动端适配
- 左侧导航 `aside` 添加 `v-if="!isMobile"`,移动端不渲染
- 新增移动端顶部栏 `<header v-if="isMobile">`:
- 左侧:AI 图标 + 「和信AI」标题
- 右侧:`User` 图标按钮,点击 `router.push('/profile')`
- 外层 `div` 包裹 grid 布局,移动端时 grid 列数为 1
#### ProfileView 移动端适配
- 引入 `useIsMobile`
- 返回按钮:手机端 → `/chat/16`,PC 端 → `/workspace`
### 16.3 新增/修改文件清单
| 文件 | 变更类型 | 说明 |
| --- | --- | --- |
| `frontend/src/composables/useIsMobile.ts` | 新增 | 移动端识别组合函数 |
| `frontend/src/views/ChatView.vue` | 修改 | 移动端隐藏侧边栏,添加顶部栏+设置按钮 |
| `frontend/src/views/WorkspaceView.vue` | 修改 | 移动端隐藏左侧导航,添加顶部栏+设置按钮 |
| `frontend/src/views/ProfileView.vue` | 修改 | 移动端返回按钮差异化路由 |
| `frontend/src/router/index.ts` | 修改 | 根路径智能跳转+认证守卫 |
### 16.4 关键设计决策
| 决策点 | 选择 | 理由 |
| --- | --- | --- |
| 移动端判定方式 | `innerHeight > innerWidth` | 不依赖 UA 字符串,纯屏幕方向判定,适配旋转 |
| 侧边栏处理方式 | `v-if` 不渲染 | 移动端无侧边栏需求,不渲染可减少 DOM 体积和事件监听 |
| 移动端设置入口 | 独立顶部栏按钮 | 不复用 PC 侧边栏底部按钮,交互更直观 |
| 状态共享方式 | 全局单例 ref | 多组件共享同一状态,避免各组件判定不一致 |
| 登录后默认页 | `/chat/16` | 移动端核心场景是聊天,直接进入 Chat 页面 |
### 16.5 不影响 PC 端的保障
- 所有移动端适配逻辑均以 `v-if="isMobile"` 或三元表达式控制,`isMobile` 在 PC 横屏时始终为 `false`
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
+2 -2
View File
@@ -10,8 +10,8 @@
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-CsJr350M.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bir-WxSG.css">
<script type="module" crossorigin src="/assets/index-g1xHTgxZ.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DMUyZ52-.css">
</head>
<body>
<div id="app"></div>␍
+66 -3
View File
@@ -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',
+32
View File
@@ -0,0 +1,32 @@
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
const isMobile = ref(false);
let listeners = 0;
const update = () => {
isMobile.value = window.innerHeight > window.innerWidth;
};
const startListening = () => {
if (listeners === 0) {
update();
window.addEventListener('resize', update);
}
listeners++;
};
const stopListening = () => {
listeners--;
if (listeners <= 0) {
listeners = 0;
window.removeEventListener('resize', update);
}
};
export function useIsMobile() {
onMounted(() => startListening());
onBeforeUnmount(() => stopListening());
return { isMobile: readonly(isMobile) };
}
+24 -2
View File
@@ -14,7 +14,8 @@ import { getStoredAuthUser } from '../utils/auth';
const routes = [
{
path: '/',
redirect: '/workspace'
name: 'Home',
component: WorkspaceView
},
{
path: '/workspace',
@@ -67,14 +68,35 @@ const router = createRouter({
routes
});
const DEFAULT_CHAT_AGENT_ID = 16;
const publicPaths = ['/', '/workspace', '/casdoor-callback', '/reset-password'];
router.beforeEach((to, _from, next) => {
const user = getStoredAuthUser();
const isLoggedIn = !!user && user.role !== 'guest';
if (to.path === '/admin') {
const user = getStoredAuthUser();
if (!user || user.role !== 'admin') {
next('/workspace');
return;
}
}
if (to.path === '/') {
if (isLoggedIn) {
next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
return;
}
next('/workspace');
return;
}
if (!isLoggedIn && !publicPaths.includes(to.path)) {
next('/workspace');
return;
}
next();
});
File diff suppressed because it is too large. Load diff
+93 -4
View File
@@ -13,17 +13,19 @@
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid } from 'lucide-vue-next';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, UserCircle, Menu } from 'lucide-vue-next';
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import { useIsMobile } from '../composables/useIsMobile';
import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth';
const { t } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const { isMobile } = useIsMobile();
const currentUser = ref(getStoredAuthUser());
const showUserDropdown = ref(false);
const userMenuRef = ref<HTMLElement | null>(null);
@@ -946,7 +948,81 @@ const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
}
};
const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
const formatLeaveBalanceNumber = (value: any) => {
if (value === null || value === undefined) return '暂无数据';
const num = Number(value);
if (Number.isNaN(num)) return String(value);
return Number.isInteger(num) ? String(num) : num.toFixed(2);
};
const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
} | null> => {
try {
const res = await fetch(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveTypeCode)}`, {
headers: getAuthHeaders(),
});
if (!res.ok) return null;
return await res.json();
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
}
};
const startLocalLeaveFlow = async (content: string) => {
const initialLeaveType = extractLeaveTypeFromIntent(content);
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
const thinkingMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: '正在查询您的假期余额,请稍候...',
};
messages.value.push(thinkingMsg);
const balance = await checkLeaveBalance(initialLeaveType);
const thinkingIndex = messages.value.indexOf(thinkingMsg);
if (thinkingIndex >= 0) {
messages.value.splice(thinkingIndex, 1);
}
if (balance && !balance.has_balance) {
const unit = initialLeaveType === '010' ? '天' : '小时';
const detailLines = [
`**${balance.leave_type_label}余额不足,暂无可用假期。**`,
'',
`| 假别 | 年度 | 可休 | 已休 | 当前剩余 |`,
`| :---: | :---: | :---: | :---: | :---: |`,
`| ${balance.leave_type_label} | ${balance.year} | ${formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
'',
'如有疑问,请联系人事部门确认假期数据。',
];
const noBalanceMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: detailLines.join('\n'),
};
messages.value.push(noBalanceMsg);
await saveLocalMessageToBackend(noBalanceMsg, content);
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
await loadHistory();
}
return;
}
}
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
@@ -954,8 +1030,10 @@ const startLocalLeaveFlow = async (content: string) => {
submitting: false,
confirmationGenerated: false,
};
messages.value.push({ role: 'user', content, type: 'text' });
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
}
const formMsg = {
role: 'assistant' as const,
type: 'leave-form' as const,
@@ -1641,12 +1719,13 @@ const showChatRating = ref(false);
<template>
<div class="relative flex h-screen overflow-hidden bg-slate-50 text-slate-800 dark:bg-slate-950 dark:text-slate-100">
<div
v-if="isSidebarOpen"
v-if="isSidebarOpen && !isMobile"
class="fixed inset-0 z-40 bg-slate-900/55 backdrop-blur-sm transition-opacity md:hidden"
@click="isSidebarOpen = false"
></div>
<aside
v-if="!isMobile"
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r bg-white transition-all duration-300 ease-in-out dark:bg-slate-950 md:relative md:translate-x-0"
:class="[
isSidebarOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
@@ -1789,6 +1868,16 @@ const showChatRating = ref(false);
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden bg-white dark:bg-slate-950">
<header v-if="isMobile && currentAgent" class="flex items-center justify-between border-b border-slate-200 px-4 py-2.5 dark:border-slate-800">
<div class="flex items-center gap-2">
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
<span class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
</div>
<button @click="router.push('/profile')" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="个人设置">
<UserCircle class="h-6 w-6" />
</button>
</header>
<div v-if="!currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
<p class="text-sm animate-pulse text-slate-500 dark:text-slate-300">{{ $t('chat.loadingAgent') }}</p>
+3 -1
View File
@@ -3,6 +3,7 @@ import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useTheme } from '../composables/useTheme';
import { useIsMobile } from '../composables/useIsMobile';
import type { ThemePreference } from '../composables/useTheme';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
@@ -25,6 +26,7 @@ const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference, appliedTheme } = useTheme();
const { isMobile } = useIsMobile();
interface ProfileForm {
id: number;
@@ -250,7 +252,7 @@ onMounted(() => {
<header class="bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-30">
<div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
<div class="flex items-center gap-4">
<button @click="router.push('/workspace')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full text-slate-500 dark:text-slate-300 transition-colors">
<button @click="router.push(isMobile ? '/chat/16' : '/workspace')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full text-slate-500 dark:text-slate-300 transition-colors">
<ChevronLeft class="w-5 h-5" />
</button>
<h1 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('profile.title') || 'My Profile' }}</h1>
+36 -18
View File
@@ -14,6 +14,7 @@ import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import { useIsMobile } from '../composables/useIsMobile';
import loginBg from '../assets/login-bg.png';
import {
@@ -58,6 +59,7 @@ const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference, appliedTheme } = useTheme();
const { isMobile } = useIsMobile();
const loginBackgroundStyle = {
backgroundImage: `url(${loginBg})`,
backgroundSize: 'cover',
@@ -1000,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: '全部状态' },
@@ -1030,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 {
@@ -1061,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();
};
@@ -1461,8 +1468,18 @@ onMounted(async () => {
</div>
<!-- Logged In Layout -->
<div v-else class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)] animate-fade-in">
<aside class="lg:sticky lg:top-0 lg:h-screen">
<div v-else class="min-h-screen animate-fade-in">
<header v-if="isMobile" class="sticky top-0 z-30 flex items-center justify-between border-b border-slate-200 bg-white px-4 py-2.5 dark:border-slate-800 dark:bg-slate-950">
<div class="flex items-center gap-2">
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
<span class="text-sm font-semibold text-slate-800 dark:text-slate-100">和信AI</span>
</div>
<button @click="router.push('/profile')" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="个人设置">
<User class="h-5 w-5" />
</button>
</header>
<div class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)]">
<aside v-if="!isMobile" class="lg:sticky lg:top-0 lg:h-screen">
<div class="flex h-full flex-col border-r border-slate-200 bg-white px-5 py-6 shadow-sm">
<div class="border-b border-slate-100 pb-6">
<div class="flex items-center gap-3">
@@ -2014,6 +2031,7 @@ onMounted(async () => {
</div>
</template>
</section>
</div>
</div>
<!-- Forgot Password Modal -->
<div v-if="showForgotPasswordModal" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">