diff --git a/.env.shared b/.env.shared index d448d4de..791030f0 100644 --- a/.env.shared +++ b/.env.shared @@ -37,7 +37,7 @@ WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email WECOM_EMPLOYEE_ID_SOURCE=userid WECOM_MOBILE_NORMALIZE=true WECOM_NOTIFY_ENABLED=true -WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed +WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed # Common integration defaults INTEGRATION_API_MODE=local @@ -77,7 +77,7 @@ 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_DRIVER=ODBC Driver 18 for SQL Server SRM_SQLSERVER_ENCRYPT=no SRM_SQLSERVER_TRUST_CERT=yes SRM_SQLSERVER_TIMEOUT=10 \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index d3351a7e..88ff599b 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -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: '阶段已中止(可能为未确认生产部署或人工取消)', + ) + } + } + } } } diff --git a/backend/.env b/backend/.env deleted file mode 100644 index a8c7b996..00000000 --- a/backend/.env +++ /dev/null @@ -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 \ No newline at end of file diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 72e91ed8..f8837109 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -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 diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 0bdb06e2..62007689 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -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': '测试失败:请求异常(网络、超时或认证问题)。', diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index c61350c1..37231092 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -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( diff --git a/backend/app/api/internal_jobs.py b/backend/app/api/internal_jobs.py new file mode 100644 index 00000000..4ee597ee --- /dev/null +++ b/backend/app/api/internal_jobs.py @@ -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('/', 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, + }) diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py index f442465f..4394e4f9 100644 --- a/backend/app/api/schedule_admin.py +++ b/backend/app/api/schedule_admin.py @@ -7,14 +7,365 @@ from flask import Blueprint, current_app, jsonify, request, send_file from app.decorators import require_admin from app import db -from app.models import ScheduleRun, ScheduleTask +from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig from app.auth_jwt import get_current_user from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task -from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no +from app.services.schedule.scheduler_service import ( + create_task, + run_task_now, + update_task, + _generate_run_no, + _generate_test_run_no, + _notify_schedule_run_wecom, +) +from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql +from app.services.schedule.srm_service import _fetch_records schedule_admin_bp = Blueprint('schedule_admin', __name__) +def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict: + return { + "row_id_key": cfg_model.row_id_key or "id", + "log_prefix": cfg_model.log_prefix or "", + "base_fetch_sql": cfg_model.base_fetch_sql or "", + "fetch_where_conditions": cfg_model.fetch_where_conditions or "", + "fetch_order_by": cfg_model.fetch_order_by or "", + "writeback_sql": cfg_model.writeback_sql or "", + "detail_sql": cfg_model.detail_sql or "", + "alias_order": cfg_model.alias_order or [], + "detail_alias_order": cfg_model.detail_alias_order or [], + "header_labels": cfg_model.header_labels or {}, + "data_source": { + "db_type": cfg_model.ds_db_type or "sqlserver", + "host": cfg_model.ds_host or "", + "port": cfg_model.ds_port or "", + "database": cfg_model.ds_database or "", + "username": cfg_model.ds_username or "", + "password": cfg_model.ds_password or "", + "driver": cfg_model.ds_driver or "", + "encrypt": cfg_model.ds_encrypt or "", + "trust_cert": cfg_model.ds_trust_cert or "", + }, + "external_api": { + "url": cfg_model.api_url or "", + "method": cfg_model.api_method or "POST", + "headers": cfg_model.api_headers or {}, + "body_template": cfg_model.api_body_template or "", + }, + } + + +@schedule_admin_bp.route('/schedule-config/', 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/', 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//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//test-run', methods=['POST']) +@require_admin +def test_schedule_run(task_id: int): + import time as _time + from app.services.schedule.excel_service import export_schedule_result_excel + + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + cfg = get_schedule_sql_config_by_task_id(task_id) + if not cfg: + return jsonify({"error": f"Config for task {task_id} not found"}), 404 + + data = request.get_json(silent=True) or {} + custom_where = str(data.get("fetch_where_conditions") or cfg.fetch_where_conditions).strip() + custom_order_by = str(data.get("fetch_order_by") or cfg.fetch_order_by).strip() + limit = min(int(data.get("limit") or 3), 10) + + base = cfg.base_fetch_sql or cfg.fetch_sql + if cfg.base_fetch_sql: + test_sql = _build_fetch_sql(base, custom_where, custom_order_by) + else: + test_sql = base + + from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user + from app.services.schedule.srm_service import ( + _fetch_records, + _run_check_job_loop, + _build_record_text, + _execute_writeback, + ) + + if cfg.data_source and not cfg.data_source.is_empty(): + conn_str = cfg.data_source.build_connection_string() + else: + conn_str = _build_srm_conn_str() + + agent = _resolve_dify_agent(task) if task else None + user = _resolve_schedule_user(task) if task else "test_user" + wait_seconds = task.wait_seconds if task else 120 + dify_agent_id = task.dify_agent_id if task else None + + run = ScheduleRun( + run_no=_generate_test_run_no(), + schedule_task_id=task_id, + trigger_type='test', + triggered_by_user_id=getattr(get_current_user(), 'id', None), + started_at=datetime.utcnow(), + status='running', + ) + db.session.add(run) + db.session.commit() + + if not cfg.fetch_sql: + run.status = 'success' + run.finished_at = datetime.utcnow() + run.error_message = '无抓取SQL,跳过外部系统数据抓取' + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc) + db.session.commit() + return jsonify({ + "run_no": run.run_no, + "run_id": run.id, + "sql": "", + "limit": 0, + "total_count": 0, + "success_count": 0, + "failed_count": 0, + "skipped_count": 0, + "details": [], + "errors": [], + "step_logs": [{"step": "no_fetch_sql", "status": "skipped", "detail": "无抓取SQL,跳过外部系统数据抓取"}], + "dify_agent_id": dify_agent_id, + }) + + def _test_fetch_fn(conn_str_arg): + return _fetch_records(conn_str_arg, test_sql) + + def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message): + _execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id))) + + test_pre_dify = None + test_build_record = None + + if cfg.detail_sql: + def _test_pre_dify(conn_str_arg, item, row_id_value): + try: + detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),)) + except Exception as detail_exc: + return { + "dify_result": "人工判定", + "dify_message": f"查询成分明细失败:{detail_exc}", + "writeback_srm": False, + "writeback_err": str(detail_exc), + } + detail_lines = [] + for dr in detail_rows: + parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order] + detail_lines.append(", ".join(parts)) + item["detail_text"] = "; ".join(detail_lines) if detail_lines else "" + item["_detail_rows"] = detail_rows + return None + test_pre_dify = _test_pre_dify + + def _test_build_with_detail(conn_str_arg, item, row_id_value): + detail_rows = item.get("_detail_rows", []) + text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order) + return text, item.get("attachment") + test_build_record = _test_build_with_detail + else: + def _test_build_simple(conn_str_arg, item, row_id_value): + text = _build_record_text(item, cfg.alias_order, cfg.header_labels) + return text, item.get("attachment") + test_build_record = _test_build_simple + + start_ts = _time.time() + try: + total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop( + conn_str=conn_str, + run_no=run.run_no, + agent=agent, + user=user, + wait_seconds=wait_seconds, + run_id=run.id, + fetch_fn=_test_fetch_fn, + build_record_fn=test_build_record, + writeback_fn=_test_writeback_fn, + writeback_sql=cfg.writeback_sql, + row_id_key=cfg.row_id_key, + log_prefix=cfg.log_prefix, + fetch_sql=test_sql, + max_rows=limit, + pre_dify_fn=test_pre_dify, + ) + + duration_ms = int((_time.time() - start_ts) * 1000) + if total_count == 0 and not errors: + status = 'success' + elif failed_count == 0: + status = 'success' + elif success_count == 0: + status = 'failed' + else: + status = 'partial_failed' + + header_order = cfg.alias_order if cfg.alias_order else None + header_labels = cfg.header_labels if cfg.header_labels else None + detail_alias_order = cfg.detail_alias_order or [] + try: + file_data, file_name, file_size = export_schedule_result_excel( + run_no=run.run_no, + summary={"status": status, "total_count": total_count, "success_count": success_count, "failed_count": failed_count, "duration_ms": duration_ms}, + details=details, + header_order=header_order, + header_labels=header_labels, + detail_alias_order=detail_alias_order, + ) + except Exception: + file_data, file_name, file_size = None, None, 0 + + run.finished_at = datetime.utcnow() + run.duration_ms = duration_ms + run.status = status + run.total_count = total_count + run.success_count = success_count + run.failed_count = failed_count + run.skipped_count = skipped_count + run.step_logs = step_logs if step_logs else None + run.error_message = "; ".join(errors[:3]) if errors else None + run.excel_file_data = file_data + run.excel_file_name = file_name + run.excel_file_size = file_size or 0 + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc) + db.session.commit() + + import decimal, datetime as dt + def _safe(v): + if isinstance(v, decimal.Decimal): + return float(v) + if isinstance(v, (dt.date, dt.datetime)): + return v.isoformat() + if isinstance(v, dt.timedelta): + return str(v) + return v + + safe_details = [] + for item in details: + safe_item = {k: _safe(v) for k, v in item.items()} + safe_details.append(safe_item) + + return jsonify({ + "run_no": run.run_no, + "run_id": run.id, + "sql": test_sql, + "limit": limit, + "total_count": total_count, + "success_count": success_count, + "failed_count": failed_count, + "skipped_count": skipped_count, + "details": safe_details, + "errors": errors, + "step_logs": step_logs, + "dify_agent_id": dify_agent_id, + }) + except Exception as e: + duration_ms = int((_time.time() - start_ts) * 1000) + run.finished_at = datetime.utcnow() + run.duration_ms = duration_ms + run.status = 'failed' + run.error_message = str(e) + db.session.commit() + import traceback + return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400 + + @schedule_admin_bp.route('/schedules', methods=['GET']) @require_admin def get_schedules(): @@ -26,6 +377,7 @@ def get_schedules(): def post_schedule(): data = request.get_json(silent=True) or {} user = get_current_user() + data_source_type = str(data.get('data_source_type') or 'database') task = create_task( name=str(data.get('name') or '').strip(), schedule_type='platform_app', @@ -39,6 +391,15 @@ def post_schedule(): enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None), ) + task.data_source_type = data_source_type + task.platform_api_path = f"/{task.id}" + db.session.commit() + db.session.refresh(task) + + config_data = data.get('config') + if config_data: + upsert_schedule_task_config(task.id, config_data) + return jsonify(serialize_task(task)), 201 @@ -59,6 +420,15 @@ def patch_schedule(task_id: int): return jsonify({'error': 'Not found'}), 404 data = request.get_json(silent=True) or {} user = get_current_user() + + if "data_source_type" in data: + task.data_source_type = str(data["data_source_type"]) + db.session.commit() + + config_data = data.get('config') + if config_data: + upsert_schedule_task_config(task_id, config_data) + task = update_task(task, payload=data, actor_id=getattr(user, 'id', None)) return jsonify(serialize_task(task)) @@ -83,16 +453,6 @@ def delete_schedule(task_id: int): if running_runs: db.session.commit() - runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).all() - for r in runs: - if r.excel_file_path: - try: - from pathlib import Path - p = Path(r.excel_file_path) - if p.exists(): - p.unlink() - except Exception: - pass db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False) db.session.delete(task) db.session.commit() @@ -218,9 +578,11 @@ def get_schedule_run(run_id: int): @schedule_admin_bp.route('/schedule-runs//excel', methods=['GET']) @require_admin def get_schedule_run_excel(run_id: int): + from io import BytesIO run = get_run(run_id) if not run: return jsonify({'error': 'Not found'}), 404 - if not run.excel_file_path: + if not run.excel_file_data: return jsonify({'error': 'Excel not found'}), 404 - return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx') + buf = BytesIO(run.excel_file_data) + return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 4dbe6fbb..99d2f0a6 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -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() diff --git a/backend/app/api/workspace_schedule.py b/backend/app/api/workspace_schedule.py index 0bbd65fb..6936405f 100644 --- a/backend/app/api/workspace_schedule.py +++ b/backend/app/api/workspace_schedule.py @@ -54,6 +54,7 @@ def workspace_schedule_run_detail(run_id: int): @workspace_schedule_bp.route('/schedule-runs//excel', methods=['GET']) def workspace_schedule_run_excel(run_id: int): + from io import BytesIO user, err = _require_user() if err: return err @@ -62,6 +63,7 @@ def workspace_schedule_run_excel(run_id: int): return jsonify({'error': 'Not found'}), 404 if not can_view_run(run, user.id): return jsonify({'error': 'Forbidden'}), 403 - if not run.excel_file_path: + if not run.excel_file_data: return jsonify({'error': 'Excel not found'}), 404 - return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx') + buf = BytesIO(run.excel_file_data) + return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') diff --git a/backend/app/config.py b/backend/app/config.py index de35ce13..02d563d3 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -106,7 +106,7 @@ class Config: WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL') WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL') - WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS') + WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed') # JWT/Casdoor auth configuration (phase-1 compatible rollout) AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true' @@ -152,11 +152,7 @@ class Config: SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '') SMTP_FROM = os.getenv('SMTP_FROM', '') SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true' - SCHEDULE_EXCEL_STORAGE_ROOT = os.getenv( - 'SCHEDULE_EXCEL_STORAGE_ROOT', - str(_BACKEND_DIR / 'data' / 'schedules'), - ) - INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:8880') + INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052') class DevelopmentConfig(Config): diff --git a/backend/app/models.py b/backend/app/models.py index 1a937fd1..d01a8500 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,6 +1,6 @@ from datetime import datetime from typing import Optional, List -from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint +from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app import db from werkzeug.security import generate_password_hash, check_password_hash @@ -562,6 +562,7 @@ class ScheduleTask(Base): wait_seconds: Mapped[int] = mapped_column(Integer, default=0) dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True) platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + data_source_type: Mapped[str] = mapped_column(String(32), default='database') notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[]) notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True) enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True) @@ -574,6 +575,49 @@ class ScheduleTask(Base): owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id]) dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id]) + config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan") + + +class ScheduleTaskConfig(Base): + __tablename__ = 'schedule_task_configs' + __table_args__ = ( + UniqueConstraint('schedule_task_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True) + + row_id_key: Mapped[str] = mapped_column(String(64), default='id') + log_prefix: Mapped[str] = mapped_column(String(128), default='') + + base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[]) + detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[]) + header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={}) + + ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver') + ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + + api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + api_method: Mapped[str] = mapped_column(String(16), default='POST') + api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={}) + api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config") class ScheduleRun(Base): @@ -599,13 +643,14 @@ class ScheduleRun(Base): api_request_json: Mapped[Optional[dict]] = mapped_column(JSON) api_response_json: Mapped[Optional[dict]] = mapped_column(JSON) response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON) + step_logs: Mapped[Optional[list]] = mapped_column(JSON) error_message: Mapped[Optional[str]] = mapped_column(Text) - excel_file_path: Mapped[Optional[str]] = mapped_column(Text) + excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary) excel_file_name: Mapped[Optional[str]] = mapped_column(String(255)) excel_file_size: Mapped[Optional[int]] = mapped_column(Integer) - mail_sent: Mapped[bool] = mapped_column(Boolean, default=False) - mail_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime) - mail_error: Mapped[Optional[str]] = mapped_column(Text) + wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) + wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index d9da0000..c9390516 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -23,6 +23,7 @@ chat.py (/api/chat/completions) -> yield SSE events to frontend """ import json +import os import time import uuid from typing import Any, List, Optional @@ -37,6 +38,7 @@ from app.services.integration_api import IntegrationApiService class DifyService: """Dify service wrapper.""" + VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on") @staticmethod def _normalize_dify_conversation_id(conversation_id: str | None) -> str: @@ -290,7 +292,7 @@ class DifyService: return {} @staticmethod - def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): + def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None): """ 主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE Stream chat completion from Dify and relay SSE events to caller. @@ -329,7 +331,8 @@ class DifyService: if current_app: current_app.logger.info( - "[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s", + "[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s", + request_id, user_id, getattr(agent, 'id', None), base_url, @@ -338,117 +341,154 @@ class DifyService: ) start_time = time.time() + first_token_at: float | None = None + message_count = 0 + event_count = 0 full_answer: List[str] = [] retriever_resources: List[Any] = [] attribution_parts: List[str] = [] - try: - with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response: - if current_app: - current_app.logger.info( - "[chat-stream] dify response status=%s reason=%s", - response.status_code, - response.reason, - ) - if not response.ok and current_app: - try: - error_body = response.text[:2000] - except Exception: - error_body = "" - current_app.logger.error( - "[chat-stream] dify bad response status=%s url=%s payload=%s body=%s", - response.status_code, - url, - json.dumps(payload, ensure_ascii=False), - error_body, - ) - response.raise_for_status() - - for line in response.iter_lines(): - if not line: - continue - - decoded_line = line.decode('utf-8') - if not decoded_line.startswith('data: '): - continue - - raw_json = decoded_line[6:] - try: - data = json.loads(raw_json) - except json.JSONDecodeError: - continue - - event = data.get('event') + max_retries = 3 + for attempt in range(1, max_retries + 1): + try: + with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response: if current_app: current_app.logger.info( - "[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s", - event, - len(data.get('answer', '') or ''), - bool(data.get('metadata')), - data.get('conversation_id') or normalized_conversation_id, + "[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s", + request_id, + response.status_code, + response.reason, + attempt, ) + if not response.ok and current_app: + retryable = response.status_code in (404, 502, 503, 504) + try: + error_body = response.text[:2000] + except Exception: + error_body = "" + current_app.logger.error( + "[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s", + request_id, + response.status_code, + url, + attempt, + error_body, + ) + if retryable and attempt < max_retries: + time.sleep(attempt * 2) + continue + response.raise_for_status() - if event == 'message': - full_answer.append(data.get('answer', '')) - DifyService._collect_metadata(retriever_resources, attribution_parts, data) + for line in response.iter_lines(): + if not line: + continue - elif event in ('message_end', 'agent_message', 'workflow_finished'): - # Keep metadata from non-message events, but avoid appending - # intermediate workflow/agent outputs into final user answer. - if event == 'message_end' and data.get('answer'): + decoded_line = line.decode('utf-8') + if not decoded_line.startswith('data: '): + continue + + raw_json = decoded_line[6:] + try: + data = json.loads(raw_json) + except json.JSONDecodeError: + continue + + event = data.get('event') + event_count += 1 + # Keep stream event logs behind an explicit switch to prevent + # flooding when global logger level is DEBUG. + if DifyService.VERBOSE_STREAM_LOG and current_app: + current_app.logger.debug( + "[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s", + request_id, + event, + len(data.get('answer', '') or ''), + bool(data.get('metadata')), + data.get('conversation_id') or normalized_conversation_id, + ) + + if event == 'message': + message_count += 1 + if first_token_at is None: + first_token_at = time.time() + if current_app: + current_app.logger.info( + "[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s", + request_id, + int((first_token_at - start_time) * 1000), + attempt, + ) full_answer.append(data.get('answer', '')) - DifyService._collect_metadata(retriever_resources, attribution_parts, data) + DifyService._collect_metadata(retriever_resources, attribution_parts, data) - if event == 'message_end': - if current_app: - current_app.logger.info( - "[source-link] message_end: collected retriever resources=%s", - len(retriever_resources), - ) - # Resolve original source file URLs from external integration API. - DifyService._enrich_retriever_resources_with_source_urls(retriever_resources) + elif event in ('message_end', 'agent_message', 'workflow_finished'): + if event == 'message_end' and data.get('answer'): + full_answer.append(data.get('answer', '')) + DifyService._collect_metadata(retriever_resources, attribution_parts, data) - metadata = data.get('metadata') or {} - metadata['retriever_resources'] = retriever_resources - data['metadata'] = metadata - data['retriever_resources'] = retriever_resources + if event == 'message_end': + message_end_started = time.time() + if current_app: + current_app.logger.info( + "[source-link] message_end request_id=%s collected retriever_resources=%s", + request_id, + len(retriever_resources), + ) + DifyService._enrich_retriever_resources_with_source_urls(retriever_resources) + enrich_done_at = time.time() - latency = int((time.time() - start_time) * 1000) - usage = metadata.get('usage', {}) or {} + metadata = data.get('metadata') or {} + metadata['retriever_resources'] = retriever_resources + data['metadata'] = metadata + data['retriever_resources'] = retriever_resources - with current_app.app_context(): - chat_log_id = DifyService._log_chat( - user_id=user_id, - agent_id=agent.id, - conversation_id=data.get('conversation_id') or normalized_conversation_id, - query=query, - answer=''.join(full_answer), - tokens=usage.get('total_tokens', 0), - latency=latency, - retriever_resources=retriever_resources, - attribution_parts=attribution_parts, - ) - if chat_log_id: - data['chat_log_id'] = chat_log_id - if current_app: - current_app.logger.info( - "[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s", - data.get('conversation_id') or normalized_conversation_id, - len(''.join(full_answer)), - len(retriever_resources), - len(attribution_parts), - latency, - ) + latency = int((time.time() - start_time) * 1000) + usage = metadata.get('usage', {}) or {} - # Pass-through SSE event (after optional enrichment). - # SSE frame delimiter must be real newlines, not literal "\n". - yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" + db_write_started = time.time() + with current_app.app_context(): + chat_log_id = DifyService._log_chat( + user_id=user_id, + agent_id=agent.id, + conversation_id=data.get('conversation_id') or normalized_conversation_id, + query=query, + answer=''.join(full_answer), + tokens=usage.get('total_tokens', 0), + latency=latency, + retriever_resources=retriever_resources, + attribution_parts=attribution_parts, + ) + db_write_done_at = time.time() + if chat_log_id: + data['chat_log_id'] = chat_log_id + if current_app: + current_app.logger.info( + "[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s", + request_id, + latency, + int((first_token_at - start_time) * 1000) if first_token_at else None, + int((message_end_started - first_token_at) * 1000) if first_token_at else None, + int((time.time() - message_end_started) * 1000), + int((enrich_done_at - message_end_started) * 1000), + int((db_write_done_at - db_write_started) * 1000), + event_count, + message_count, + len(''.join(full_answer)), + len(retriever_resources), + len(attribution_parts), + data.get('conversation_id') or normalized_conversation_id, + ) - except requests.exceptions.RequestException as e: - if current_app: - current_app.logger.exception("[chat-stream] request exception: %s", e) - error_msg = json.dumps({'event': 'error', 'message': str(e)}) - yield f"data: {error_msg}\n\n" + yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" + break + except requests.exceptions.RequestException as e: + if current_app: + current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e) + if attempt < max_retries: + time.sleep(attempt * 2) + continue + error_msg = json.dumps({'event': 'error', 'message': str(e)}) + yield f"data: {error_msg}\n\n" @staticmethod def _log_chat( diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index 574dc892..bc1fbdad 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -8,9 +8,15 @@ from flask import current_app from app import db from app.models import Agent, ScheduleRun, ScheduleTask -from app.services.schedule.srm_service import run_rohs_doc_check_dify_job +from app.services.schedule.sql_config import ( + get_schedule_sql_config, + get_schedule_sql_config_by_task_id, + get_all_schedule_sql_configs, + upsert_schedule_task_config, + ScheduleSqlConfig, +) -ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]] +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult] @@ -26,59 +32,7 @@ def normalize_platform_api_path(path: str | None) -> str: return value -def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - endpoint = normalize_platform_api_path(task.platform_api_path) - if not endpoint: - raise RuntimeError("platform_api_path is missing") - - base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/") - url = endpoint if endpoint.startswith("http://") or endpoint.startswith("https://") else (f"{base}{endpoint}" if base else endpoint) - - payload = { - "run_no": run.run_no, - "schedule_task_id": task.id, - "schedule_name": task.name, - "dify_agent_id": task.dify_agent_id, - } - - run.api_request_json = payload - db.session.commit() - - try: - resp = requests.post(url, json=payload, timeout=(5, 60)) - resp.raise_for_status() - data = resp.json() if resp.content else {} - except requests.RequestException as e: - data = {} - if e.response is not None: - try: - data = e.response.json() - except Exception: - data = {"error_text": e.response.text} - else: - data = {"error": str(e)} - run.api_response_json = data - db.session.commit() - raise e - - run.api_response_json = data - db.session.commit() - - summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {} - details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else [] - errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else [] - - total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1)) - success = int(summary.get("success_count") if summary.get("success_count") is not None else total) - failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success)) - return total, success, failed, 0, details, [str(e) for e in errors if str(e).strip()] - - -def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None - if task.dify_agent_id and (not agent or not agent.dify_api_key): - raise RuntimeError("dify_agent_id is invalid or key is missing") - +def _build_srm_conn_str() -> str: host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip() if not host: raise RuntimeError("SRM_SQLSERVER_HOST is not configured") @@ -91,7 +45,7 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower() trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower() - conn_str = ( + return ( f"DRIVER={{{driver}}};" f"SERVER={host},{port};" f"DATABASE={database};" @@ -101,33 +55,264 @@ def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> Sc f"TrustServerCertificate={trust_cert};" ) - return run_rohs_doc_check_dify_job( + +def _resolve_dify_agent(task: ScheduleTask): + agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None + if task.dify_agent_id and (not agent or not agent.dify_api_key): + raise RuntimeError("dify_agent_id is invalid or key is missing") + return agent + + +def _resolve_schedule_user(task: ScheduleTask) -> str: + return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system") + + +def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + endpoint = normalize_platform_api_path(task.platform_api_path) + if not endpoint: + raise RuntimeError("platform_api_path is missing") + + base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/") + if endpoint.startswith("http://") or endpoint.startswith("https://"): + url = endpoint + elif base: + name = endpoint.lstrip("/") + url = f"{base}/api/internal/jobs/{name}" + else: + url = endpoint + + payload = { + "run_no": run.run_no, + "schedule_task_id": task.id, + "schedule_name": task.name, + "dify_agent_id": task.dify_agent_id, + } + + step_logs: list[dict[str, Any]] = [] + + run.api_request_json = payload + db.session.commit() + + try: + timeout = max(5, (task.wait_seconds or 120) + 30) + resp = requests.post(url, json=payload, timeout=(5, timeout)) + resp.raise_for_status() + data = resp.json() if resp.content else {} + step_logs.append({ + "step": "call_internal_api", + "status": "success", + "detail": {"url": url, "status_code": resp.status_code}, + }) + except requests.RequestException as e: + data = {} + if e.response is not None: + try: + data = e.response.json() + except Exception: + data = {"error_text": e.response.text} + else: + data = {"error": str(e)} + step_logs.append({ + "step": "call_internal_api", + "status": "failed", + "detail": {"url": url, "error": str(e)}, + }) + run.api_response_json = data + db.session.commit() + raise e + + run.api_response_json = data + db.session.commit() + + summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {} + details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else [] + errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else [] + remote_step_logs = data.get("step_logs") if isinstance(data, dict) and isinstance(data.get("step_logs"), list) else [] + + total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1)) + success = int(summary.get("success_count") if summary.get("success_count") is not None else total) + failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success)) + skipped = int(summary.get("skipped_count") if summary.get("skipped_count") is not None else 0) + + if remote_step_logs: + step_logs.extend(remote_step_logs) + + return total, success, failed, skipped, details, [str(e) for e in errors if str(e).strip()], step_logs + + +def _run_external_api_job(task: ScheduleTask, run: ScheduleRun, cfg: ScheduleSqlConfig) -> ScheduleExecuteResult: + import requests as http_requests + + ext = cfg.external_api + if not ext.url: + return 0, 0, 0, 0, [], ["external_api url is empty"], [] + + step_logs: list[dict[str, Any]] = [] + step_logs.append({"step": "call_external_api", "status": "started", "url": ext.url, "method": ext.method}) + + try: + headers = dict(ext.headers) if ext.headers else {} + body = ext.body_template or "{}" + resp = http_requests.request( + method=ext.method, + url=ext.url, + headers=headers, + data=body, + timeout=120, + ) + step_logs.append({"step": "call_external_api", "status": "completed", "status_code": resp.status_code}) + if not resp.ok: + return 0, 0, 0, 1, [], [f"external API returned {resp.status_code}: {resp.text[:500]}"], step_logs + try: + result_data = resp.json() + except Exception: + result_data = {"raw": resp.text[:2000]} + + total = 1 + details = [result_data] if isinstance(result_data, dict) else (result_data if isinstance(result_data, list) else [{"raw": str(result_data)}]) + step_logs.append({"step": "call_external_api", "status": "success", "total": total}) + return total, total, 0, 0, details, [], step_logs + except Exception as e: + step_logs.append({"step": "call_external_api", "status": "error", "error": str(e)}) + return 0, 0, 1, 0, [], [str(e)], step_logs + + +def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + from app.services.schedule.srm_service import ( + _run_check_job_loop, + _fetch_records, + _execute_writeback, + _build_record_text, + ) + + cfg = get_schedule_sql_config_by_task_id(task.id) + if not cfg: + return 0, 0, 0, 0, [], [], [] + + if cfg.data_source_type == "external_api": + return _run_external_api_job(task, run, cfg) + + if not cfg.fetch_sql: + return 0, 0, 0, 0, [], [], [] + + if cfg.data_source and not cfg.data_source.is_empty(): + conn_str = cfg.data_source.build_connection_string() + else: + conn_str = _build_srm_conn_str() + agent = _resolve_dify_agent(task) + user = _resolve_schedule_user(task) + has_detail = bool(cfg.detail_sql) + + def fetch_fn(cs: str): + return _fetch_records(cs, cfg.fetch_sql) + + def writeback_fn(cs: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str): + _execute_writeback(cs, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id))) + + pre_dify_fn = None + build_record_fn = None + + if has_detail: + def _pre_dify(cs: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None: + try: + detail_rows = _fetch_records(cs, cfg.detail_sql, params=(str(row_id_value),)) + except Exception as detail_exc: + return { + "dify_result": "人工判定", + "dify_message": f"查询成分明细失败:{detail_exc}", + "writeback_srm": False, + "writeback_err": str(detail_exc), + } + detail_summary_lines: list[str] = [] + for dr in detail_rows: + parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order] + detail_summary_lines.append(", ".join(parts)) + item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else "" + item["_detail_rows"] = detail_rows + return None + pre_dify_fn = _pre_dify + + def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]: + detail_rows = item.get("_detail_rows", []) + text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order) + return text, item.get("attachment") + build_record_fn = _build_with_detail + else: + def _build_simple(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]: + text = _build_record_text(item, cfg.alias_order, cfg.header_labels) + return text, item.get("attachment") + build_record_fn = _build_simple + + return _run_check_job_loop( conn_str=conn_str, run_no=run.run_no, agent=agent, - user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"), + user=user, wait_seconds=task.wait_seconds or 120, run_id=run.id, + fetch_fn=fetch_fn, + build_record_fn=build_record_fn, + writeback_fn=writeback_fn, + writeback_sql=cfg.writeback_sql, + row_id_key=cfg.row_id_key, + log_prefix=cfg.log_prefix, + fetch_sql=cfg.fetch_sql, + pre_dify_fn=pre_dify_fn, ) -_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = { - "default": _run_common_executor, - "srm_rohs_doc_check": _run_srm_rohs_doc_check_executor, -} - - -def register_schedule_executor(name: str, executor: ScheduleExecutor) -> None: - key = str(name or "").strip().lower() - if not key: - raise ValueError("executor name is required") - _SCHEDULE_EXECUTOR_REGISTRY[key] = executor +def list_registered_api_paths() -> list[dict[str, str]]: + from app.models import ScheduleTask + results: list[dict[str, str]] = [] + tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all() + for t in tasks: + results.append({"value": t.platform_api_path, "label": t.name or str(t.id)}) + return results def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor: - path = normalize_platform_api_path(task.platform_api_path) + dst = getattr(task, "data_source_type", None) or "database" + if dst in ("database", "external_api"): + return _run_generic_check_job + return _run_common_executor + + +_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {} + + +def register_schedule_header(name: str, header_order: list[str], header_labels: dict[str, str]) -> None: + key = str(name or "").strip().lower() + if not key: + raise ValueError("header name is required") + _SCHEDULE_HEADER_REGISTRY[key] = (header_order, header_labels) + + +def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] | None, dict[str, str] | None]: + path = normalize_platform_api_path(platform_api_path) if path: - lookup_key = path.lstrip("/").lower() - if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY: - return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key] - return _SCHEDULE_EXECUTOR_REGISTRY["default"] + key = path.lstrip("/").lower() + if key in _SCHEDULE_HEADER_REGISTRY: + return _SCHEDULE_HEADER_REGISTRY[key] + return None, None + + +def _register_headers_from_config() -> None: + _SCHEDULE_HEADER_REGISTRY.clear() + for name, cfg in get_all_schedule_sql_configs().items(): + if cfg.alias_order and cfg.header_labels: + register_schedule_header(name, cfg.alias_order, cfg.header_labels) + + +def reload_config() -> dict[str, Any]: + _register_headers_from_config() + return {"reloaded": []} + + +_HEADERS_LOADED = False + + +def ensure_headers_loaded() -> None: + global _HEADERS_LOADED + if not _HEADERS_LOADED: + _register_headers_from_config() + _HEADERS_LOADED = True diff --git a/backend/app/services/schedule/excel_service.py b/backend/app/services/schedule/excel_service.py index 831b694e..9a5b45b6 100644 --- a/backend/app/services/schedule/excel_service.py +++ b/backend/app/services/schedule/excel_service.py @@ -1,7 +1,7 @@ from __future__ import annotations +import io import json -from pathlib import Path from typing import Any from openpyxl import Workbook @@ -13,40 +13,111 @@ def _flatten_value(v: Any) -> Any: return v -def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]: +_EXPORT_SKIP_KEYS = {"dify_output", "json_output", "output", "_detail_rows", "detail_text"} + + +def export_schedule_result_excel( + *, + run_no: str, + summary: dict, + details: list[dict], + header_order: list[str] | None = None, + header_labels: dict[str, str] | None = None, + detail_alias_order: list[str] | None = None, +) -> tuple[bytes | None, str | None, int]: if not details: return None, None, 0 - out_root = Path(root_dir) - out_root.mkdir(parents=True, exist_ok=True) + header_order = header_order or [] + header_labels = header_labels or {} + detail_alias_order = detail_alias_order or [] + + exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"] + + sql_headers: list[str] = [] + detail_headers: list[str] = [] + exec_result_headers: list[str] = [] + + def _append_unique(target: list[str], key: str) -> None: + if key not in target: + target.append(key) + + for row in details: + if not isinstance(row, dict): + continue + for k in row.keys(): + key = str(k) + if key in _EXPORT_SKIP_KEYS: + continue + if key in exec_result_order: + _append_unique(exec_result_headers, key) + else: + _append_unique(sql_headers, key) + detail_rows = row.get("_detail_rows") + if isinstance(detail_rows, list): + for dr in detail_rows: + if isinstance(dr, dict): + for dk in dr.keys(): + _append_unique(detail_headers, str(dk)) + + ordered_sql_headers = [k for k in header_order if k in sql_headers] + other_sql_headers = [k for k in sql_headers if k not in header_order] + ordered_detail_headers = [k for k in detail_alias_order if k in detail_headers] + other_detail_headers = [k for k in detail_headers if k not in detail_alias_order] + ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers] + other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order] + + all_detail_headers = ordered_detail_headers + other_detail_headers + + headers = ( + ordered_sql_headers + + other_sql_headers + + all_detail_headers + + ordered_exec_headers + + other_exec_headers + ) + + if not headers: + return None, None, 0 rows: list[dict[str, Any]] = [] for row in details: - output = row.get('dify_output') - if not isinstance(output, dict): - output = {} - entry = {k: _flatten_value(v) for k, v in output.items()} - for k in ('writeback_ok', 'error', 'judgement', 'reason'): - if k in row: - entry[k] = row[k] - rows.append(entry) + if not isinstance(row, dict): + continue - headers: list[str] = [] - for row in rows: - for k in row: - if k not in headers: - headers.append(k) + base_row: dict[str, Any] = {} + for k, v in row.items(): + key = str(k) + if key in _EXPORT_SKIP_KEYS: + continue + if key in {"dify_output", "json_output", "output"}: + if isinstance(v, dict): + for json_key, json_val in v.items(): + base_row[str(json_key)] = _flatten_value(json_val) + continue + base_row[key] = _flatten_value(v) + + detail_rows = row.get("_detail_rows") + if all_detail_headers and isinstance(detail_rows, list) and detail_rows: + for dr in detail_rows: + flat = dict(base_row) + if isinstance(dr, dict): + for dk in all_detail_headers: + flat[dk] = dr.get(dk, "") + rows.append(flat) + else: + rows.append(base_row) wb = Workbook() ws = wb.active - ws.title = 'result' - ws.append(headers) + ws.title = "result" + ws.append([header_labels.get(k, k) for k in headers]) for row in rows: - ws.append([row.get(k, '') for k in headers]) + ws.append([row.get(k, "") for k in headers]) - file_name = f'schedule_{run_no}.xlsx' - file_path = out_root / file_name - wb.save(file_path) - size = file_path.stat().st_size - return str(file_path), file_name, int(size) + buf = io.BytesIO() + wb.save(buf) + file_data = buf.getvalue() + file_name = f"schedule_{run_no}.xlsx" + return file_data, file_name, len(file_data) diff --git a/backend/app/services/schedule/mail_service.py b/backend/app/services/schedule/mail_service.py deleted file mode 100644 index 9b00a92f..00000000 --- a/backend/app/services/schedule/mail_service.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -import smtplib -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText - - -def send_schedule_mail(*, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_tls: bool, from_addr: str, to_addrs: list[str], subject: str, html_body: str) -> None: - if not to_addrs: - return - msg = MIMEMultipart('alternative') - msg['Subject'] = subject - msg['From'] = from_addr - msg['To'] = ', '.join(to_addrs) - msg.attach(MIMEText(html_body, 'html', 'utf-8')) - - with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server: - if use_tls: - server.starttls() - if smtp_user: - server.login(smtp_user, smtp_password) - server.sendmail(from_addr, to_addrs, msg.as_string()) - - -def build_schedule_mail_html(*, schedule_name: str, run_no: str, status: str, total: int, success: int, failed: int) -> str: - return ( - "" - "

排程执行结果

" - "" - f"" - f"" - f"" - f"" - f"" - f"" - "
排程{schedule_name}
执行单号{run_no}
状态{status}
总数{total}
成功{success}
失败{failed}
" - ) diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index 1bec1258..cbc3324e 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -52,12 +52,13 @@ def serialize_run(run: ScheduleRun) -> dict: 'api_request_json': run.api_request_json, 'api_response_json': run.api_response_json, 'response_summary_json': run.response_summary_json, + 'step_logs': run.step_logs, 'error_message': run.error_message, 'excel_file_name': run.excel_file_name, 'excel_file_size': run.excel_file_size, - 'mail_sent': bool(run.mail_sent), - 'mail_sent_at': run.mail_sent_at.isoformat() if run.mail_sent_at else None, - 'mail_error': run.mail_error, + 'wecom_notified': bool(run.wecom_notified), + 'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None, + 'wecom_notify_error': run.wecom_notify_error, 'created_at': run.created_at.isoformat() if run.created_at else None, } diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 5e17454c..5aa91556 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -11,9 +11,9 @@ from flask import current_app from app import db from app.models import ScheduleRun, ScheduleTask, User -from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor +from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header +from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id from app.services.schedule.excel_service import export_schedule_result_excel -from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail _worker_started = False _worker_lock = threading.Lock() @@ -44,6 +44,115 @@ def _generate_run_no() -> str: return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}" +def _generate_test_run_no() -> str: + return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}" + + +_WECOM_STATUS_LABEL = { + 'success': '成功', + 'failed': '失败', + 'partial_failed': '部分失败', +} + +_WECOM_EVENT_TYPE = 'schedule_completed' + + +def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: + from app.services.wecom_notify import ( + upload_wecom_temp_media, + send_wecom_file_message, + send_wecom_textcard_message, + _create_audit, + _build_jump_url, + _get_enabled_events, + ) + + if not current_app.config.get('WECOM_NOTIFY_ENABLED', True): + run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false' + return + + if _WECOM_EVENT_TYPE not in _get_enabled_events(): + run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled' + return + + user_ids = task.notify_user_ids_json or [] + if not user_ids: + return + + users = db.session.query(User).filter(User.id.in_(user_ids)).all() + wecom_users = [u for u in users if u.wecom_userid] + if not wecom_users: + run.wecom_notify_error = 'no wecom_userid bound users in notify list' + return + + status_label = _WECOM_STATUS_LABEL.get(run.status, run.status) + title = f'排程执行结果: {task.name}' + description = ( + f'执行单号: {run.run_no}\n' + f'状态: {status_label}\n' + f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}' + ) + + media_id = None + if run.excel_file_data and run.excel_file_name: + try: + media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name) + except Exception as exc: + current_app.logger.warning( + '[wecom-schedule] media upload failed for run %s: %s', + run.run_no, exc, + ) + + textcard_ok_count = 0 + errors = [] + + for u in wecom_users: + trace_id = uuid.uuid4().hex + jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'}) + + try: + audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id) + audit.jump_url = jump_url + + data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url) + if data.get('errcode') == 0: + audit.status = 'sent' + textcard_ok_count += 1 + else: + audit.error_code = str(data.get('errcode')) + audit.error_message = str(data.get('errmsg', 'unknown'))[:255] + errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}') + except Exception as exc: + errors.append(f'{u.real_name or u.username}: textcard exception={exc}') + + if media_id: + try: + file_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_file', u, + title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex, + ) + file_data = send_wecom_file_message(u.wecom_userid, media_id) + if file_data.get('errcode') == 0: + file_audit.status = 'sent' + else: + file_audit.error_code = str(file_data.get('errcode')) + file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255] + errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}') + except Exception as exc: + errors.append(f'{u.real_name or u.username}: file exception={exc}') + + if textcard_ok_count > 0: + run.wecom_notified = True + run.wecom_notified_at = datetime.utcnow() + else: + run.wecom_notified = False + + if errors: + run.wecom_notify_error = '; '.join(errors[:5]) + + db.session.flush() + + def create_task( *, name: str, @@ -58,9 +167,6 @@ def create_task( enabled: bool, actor_id: int | None, ) -> ScheduleTask: - if not normalize_platform_api_path(platform_api_path): - raise ValueError("platform_api_path is required for platform_app") - task = ScheduleTask( schedule_no=_generate_schedule_no(), name=name, @@ -151,11 +257,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: db.session.commit() start_ts = time.time() + step_logs: list = [] try: executor = resolve_schedule_executor(task) - total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run) + total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run) except Exception as exc: total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)] + step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}] + + try: + db.session.refresh(run) + except Exception: + pass if is_run_cancelled(run.id): run.finished_at = datetime.utcnow() @@ -183,7 +296,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: status = "partial_failed" try: - file_path, file_name, file_size = export_schedule_result_excel( + cfg = get_schedule_sql_config_by_task_id(task.id) + if cfg and cfg.alias_order and cfg.header_labels: + header_order, header_labels = cfg.alias_order, cfg.header_labels + else: + header_order, header_labels = resolve_schedule_header(task.platform_api_path) + detail_alias_order = (cfg.detail_alias_order if cfg else None) or [] + file_data, file_name, file_size = export_schedule_result_excel( run_no=run.run_no, summary={ "status": status, @@ -193,12 +312,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: "duration_ms": duration_ms, }, details=details, - root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(), + header_order=header_order, + header_labels=header_labels, + detail_alias_order=detail_alias_order, ) except Exception as excel_exc: if current_app: current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc) - file_path, file_name, file_size = None, None, 0 + file_data, file_name, file_size = None, None, 0 errors.append(f"Excel导出失败: {excel_exc}") run.finished_at = datetime.utcnow() @@ -208,48 +329,23 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: run.success_count = success_count run.failed_count = failed_count run.skipped_count = skipped_count + run.step_logs = step_logs if step_logs else None run.response_summary_json = { "errors": errors[:20], "schedule_type": task.schedule_type, "platform_api_path": task.platform_api_path, } run.error_message = "; ".join(errors[:3]) if errors else None - run.excel_file_path = file_path + run.excel_file_data = file_data run.excel_file_name = file_name run.excel_file_size = file_size or 0 try: if task.notify_enabled: - users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all() - to_addrs = [u.email for u in users if u.email] - if to_addrs: - try: - send_schedule_mail( - smtp_host=str(current_app.config.get("SMTP_HOST") or ""), - smtp_port=int(current_app.config.get("SMTP_PORT") or 25), - smtp_user=str(current_app.config.get("SMTP_USER") or ""), - smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""), - use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)), - from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"), - to_addrs=to_addrs, - subject=f"排程执行结果 {task.name} {run.run_no}", - html_body=build_schedule_mail_html( - schedule_name=task.name, - run_no=run.run_no, - status=status, - total=total_count, - success=success_count, - failed=failed_count, - ), - ) - run.mail_sent = True - run.mail_sent_at = datetime.utcnow() - except Exception as mail_exc: - run.mail_sent = False - run.mail_error = str(mail_exc) - except Exception as mail_exc: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: if current_app: - current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc) + current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc) task.last_run_at = datetime.utcnow() db.session.commit() diff --git a/backend/app/services/schedule/sql_config.py b/backend/app/services/schedule/sql_config.py new file mode 100644 index 00000000..4bacf476 --- /dev/null +++ b/backend/app/services/schedule/sql_config.py @@ -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) diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py index 30dd89b8..bca2be78 100644 --- a/backend/app/services/schedule/srm_service.py +++ b/backend/app/services/schedule/srm_service.py @@ -1,8 +1,10 @@ from __future__ import annotations -from typing import Any +from datetime import datetime +from typing import Any, Callable from flask import current_app + from app.services.dify import DifyService try: @@ -11,54 +13,20 @@ except Exception: # pragma: no cover pyodbc = None -FIXED_ROHS_SQL = """ -select - TOP(100) - t2.supplier_code as supplier_code, - t2.supplier_name as supplier_name, - t2.material_code as item_code, - t2.material_name as item_name, - t1.id as id, - t1.material as material, - t1.material_name as material_name, - t1.third_code as third_code, - t1.test_item as test_item, - t1.pb as pb, - t1.cd as cd, - t1.hg as hg, - t1.cr6 as cr6, - t1.pbbs as pbbs, - t1.pbdes as pbdes, - t1.dbp as dbp, - t1.bbp as bbp, - t1.dehp as dehp, - t1.dibp as dibp, - t1.cl as cl, - t1.br as br, - COALESCE(CONVERT(VARCHAR(19), t1.test_date, 120), '1970-01-01 00:00:00') as test_date, - 'http://srm.well-trust.com:8090/hexin-boot/sys/common/static/' + COALESCE(t1.attachment, '') as attachment -from - control_harmful_substances t1, - control_harmful t2 -where - 1 = 1 - and t1.control_harmful_id = t2.id - and t1.def11 is null - and t2.def1 = '7' -""" - - def _connect(conn_str: str): if pyodbc is None: - raise RuntimeError('pyodbc is not installed') + raise RuntimeError("pyodbc is not installed") return pyodbc.connect(conn_str, timeout=15) -def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]: +def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]: conn = _connect(conn_str) try: cur = conn.cursor() - cur.execute(FIXED_ROHS_SQL) + if params: + cur.execute(sql, params) + else: + cur.execute(sql) cols = [c[0] for c in cur.description] rows = cur.fetchall() return [{cols[i]: row[i] for i in range(len(cols))} for row in rows] @@ -66,121 +34,315 @@ def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]: conn.close() -def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> None: +def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None: conn = _connect(conn_str) try: cur = conn.cursor() - cur.execute( - "UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?", - (run_no, judgement, reason, str(row_id)), - ) + cur.execute(sql, params) conn.commit() finally: conn.close() -def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]: - judgement = str(data.get("judgement") or data.get("result") or "人工判定").strip() - reason = str(data.get("reason") or "").strip() - if judgement not in {"合格", "不合格", "人工判定"}: - reason = (reason + " | 返回值异常:" + judgement).strip(" |") - judgement = "人工判定" - return judgement, reason +def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]: + dify_result = str(data.get("dify_result")).strip() + dify_message = str(data.get("dify_message")).strip() + if dify_result not in {"合格", "不合格", "人工判定"}: + dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |") + dify_result = "人工判定" + return dify_result, dify_message -def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user: str = "schedule_system", wait_seconds: int = 120, run_id: int | None = None) -> tuple[int, int, int, int, list[dict[str, Any]], list[str]]: +def _build_record_text( + item: dict[str, Any], + alias_order: list[str], + header_labels: dict[str, str], + detail_rows: list[dict[str, Any]] | None = None, + detail_alias_order: list[str] | None = None, +) -> str: + lines: list[str] = [] + for key in alias_order: + label = header_labels.get(key, key) + value = item.get(key) + text = "" if value is None else str(value) + lines.append(f"{label}: {text}") + if detail_rows and detail_alias_order: + lines.append("成分明细:") + for idx, dr in enumerate(detail_rows, 1): + detail_parts: list[str] = [] + for dk in detail_alias_order: + dl = header_labels.get(dk, dk) + dv = dr.get(dk) + detail_parts.append(f"{dl}: {'' if dv is None else str(dv)}") + lines.append(f" [{idx}] " + ", ".join(detail_parts)) + return "\n".join(lines) + + +RecordBuilder = Callable[[str, dict[str, Any], str], tuple[str, str | None]] +WritebackFunc = Callable[..., None] +PreDifyFunc = Callable[[str, dict[str, Any], str], dict[str, Any] | None] + +_MAX_STEP_LOGS_PER_ROW = 200 +_MAX_DIFY_RESPONSE_LEN = 4000 + + +def _ts() -> str: + return datetime.utcnow().isoformat() + + +def _make_step( + step: str, + status: str, + started_at: str, + finished_at: str, + row_id: str | None = None, + **extra: Any, +) -> dict[str, Any]: + entry: dict[str, Any] = { + "step": step, + "status": status, + "started_at": started_at, + "finished_at": finished_at, + "duration_ms": int((datetime.fromisoformat(finished_at) - datetime.fromisoformat(started_at)).total_seconds() * 1000), + } + if row_id: + entry["row_id"] = row_id + entry.update(extra) + return entry + + +def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str: + if len(s) <= max_len: + return s + return s[:max_len] + f"...[truncated, total {len(s)} chars]" + + +def _run_check_job_loop( + *, + conn_str: str, + run_no: str, + agent, + user: str, + wait_seconds: int, + run_id: int | None, + fetch_fn: Callable[[str], list[dict[str, Any]]], + build_record_fn: RecordBuilder, + writeback_fn: WritebackFunc, + writeback_sql: str = "", + row_id_key: str, + log_prefix: str, + fetch_sql: str = "", + max_rows: int = 0, + pre_dify_fn: PreDifyFunc | None = None, +) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]: + from app.services.schedule.scheduler_service import is_run_cancelled + use_dify = agent is not None if use_dify and not getattr(agent, "dify_api_key", None): raise RuntimeError("dify_agent_id is set, but Dify api key is missing") - rows = fetch_rohs_records(conn_str) - total_count = len(rows) + step_logs: list[dict[str, Any]] = [] + + t0 = _ts() + try: + rows = fetch_fn(conn_str) + if max_rows > 0: + rows = rows[:max_rows] + step_logs.append(_make_step( + "fetch_srm", + "success", + t0, _ts(), + detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "row_count": len(rows)}, + )) + except Exception as fetch_exc: + step_logs.append(_make_step( + "fetch_srm", + "failed", + t0, _ts(), + detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "error": str(fetch_exc)}, + )) + raise + details: list[dict[str, Any]] = [] success_count = 0 failed_count = 0 skipped_count = 0 - errors: list[str] = [] + all_errors: list[str] = [] - from app.services.schedule.scheduler_service import is_run_cancelled - for idx, row in enumerate(rows): + for row in rows: if run_id is not None and is_run_cancelled(run_id): item = dict(row) - item.update({"judgement": "人工判定", "reason": "排程已被删除,执行中断", "writeback_ok": False, "error": "排程已被删除,执行中断"}) + item.update({ + "dify_result": "人工判定", + "dify_message": "排程已被删除,执行中断", + "writeback_srm": False, + "writeback_err": "排程已被删除,执行中断", + }) skipped_count += 1 details.append(item) continue + item = dict(row) + row_id_value = str(row.get(row_id_key, "")) + + if pre_dify_fn: + t_pre = _ts() + try: + pre_result = pre_dify_fn(conn_str, item, row_id_value) + except Exception as pre_exc: + pre_result = { + "dify_result": "人工判定", + "dify_message": f"pre_dify执行异常:{pre_exc}", + "writeback_srm": False, + "writeback_err": str(pre_exc), + } + step_logs.append(_make_step("pre_dify", "failed", t_pre, _ts(), row_id=row_id_value, detail={"error": str(pre_exc)})) + + if pre_result is not None: + item.update(pre_result) + failed_count += 1 + all_errors.append(pre_result.get("writeback_err", "")) + details.append(item) + continue + + record_text, attachment_url = build_record_fn(conn_str, item, row_id_value) + dify_ok = False + dify_result = "人工判定" + dify_message = "" + try: if use_dify: - dify_res = DifyService.run_workflow_streaming( - agent=agent, - inputs={"inputs": {"run_no": run_no, "records": item}}, - user=user, - timeout=(5, max(300, int(wait_seconds))), - ) + dify_inputs = { + "run_no": run_no, + "record": record_text, + "attachment_url": attachment_url, + } + t_dify = _ts() + try: + dify_res = DifyService.run_workflow_streaming( + agent=agent, + inputs=dify_inputs, + user=user, + timeout=(5, max(300, int(wait_seconds))), + ) + except Exception as dify_exc: + step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={ + "request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)}, + "error": str(dify_exc), + })) + raise + dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None + workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None + if dify_status == "failed" or (dify_error and not dify_res.get("outputs")): err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}" - judgement = "人工判定" - reason = f"Dify执行失败:{err_detail}" - item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": err_detail, "dify_output": dify_res if isinstance(dify_res, dict) else {}}) + dify_result = "人工判定" + dify_message = f"Dify执行失败:{err_detail}" + + step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={ + "request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)}, + "response": _truncate_str(str(dify_res)), + "workflow_run_id": workflow_run_id, + })) + + item.update({ + "dify_result": dify_result, + "dify_message": dify_message, + "writeback_srm": False, + "writeback_err": err_detail, + }) failed_count += 1 - errors.append(f"Dify row_id={row.get('id')}: {err_detail}") + all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}") + details.append(item) + continue else: outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res if current_app: current_app.logger.info( - "[srm-dify] judgement=%s reason=%s", - outputs.get("judgement") if isinstance(outputs, dict) else None, - outputs.get("reason") if isinstance(outputs, dict) else None, + "[%s] %s=%s dify_result=%s dify_message=%s", + log_prefix, log_prefix, row_id_value, + (outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None, + (outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None, ) - judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {}) - item["dify_output"] = outputs if isinstance(outputs, dict) else {} + dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {}) dify_ok = True + + step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={ + "request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)}, + "response": { + "status": dify_status, + "dify_result": dify_result, + "dify_message": _truncate_str(dify_message), + "workflow_run_id": workflow_run_id, + }, + })) else: - judgement = "人工判定" - reason = "未配置 Agent ID,跳过 Dify" + dify_result = "人工判定" + dify_message = "未配置 Agent ID,跳过 Dify" dify_ok = True + wb_sql = writeback_sql + wb_params = (run_no, dify_result, dify_message, str(row_id_value)) + t_wb = _ts() try: - writeback_rohs( - conn_str, - row_id=str(row.get("id")), - run_no=run_no, - judgement=judgement, - reason=reason, - ) - item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": item.get("error")}) + writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message) + step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={ + "sql": _truncate_str(wb_sql, 500), + "params": [str(p) for p in wb_params], + })) + item.update({ + "dify_result": dify_result, + "dify_message": dify_message, + "writeback_srm": True, + "writeback_err": item.get("writeback_err"), + }) if dify_ok: success_count += 1 except Exception as wb_exc: if current_app: - current_app.logger.error("[srm-dify] writeback failed row_id=%s error=%s", row.get("id"), wb_exc) - item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(wb_exc)}) + current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc) + step_logs.append(_make_step("writeback_srm", "failed", t_wb, _ts(), row_id=row_id_value, detail={ + "sql": _truncate_str(wb_sql, 500), + "params": [str(p) for p in wb_params], + "error": str(wb_exc), + })) + item.update({ + "dify_result": dify_result, + "dify_message": dify_message, + "writeback_srm": False, + "writeback_err": str(wb_exc), + }) if dify_ok: failed_count += 1 - errors.append(f"writeback row_id={row.get('id')}: {wb_exc}") + all_errors.append(f"writeback {log_prefix}={row_id_value}: {wb_exc}") except Exception as exc: - judgement = "人工判定" - reason = f"执行异常:{exc}" - item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(exc)}) + dify_result = "人工判定" + dify_message = f"执行异常:{exc}" + item.update({ + "dify_result": dify_result, + "dify_message": dify_message, + "writeback_srm": False, + "writeback_err": str(exc), + }) failed_count += 1 - errors.append(str(exc)) + all_errors.append(str(exc)) + t_wb2 = _ts() try: - writeback_rohs( - conn_str, - row_id=str(row.get("id")), - run_no=run_no, - judgement=judgement, - reason=reason, - ) - item["writeback_ok"] = True + writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message) + step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"})) + item["writeback_srm"] = True except Exception as wb_exc: - item["writeback_ok"] = False - item["error"] = f"{item.get('error', '')}; writeback failed: {wb_exc}" + step_logs.append(_make_step("writeback_srm", "failed", t_wb2, _ts(), row_id=row_id_value, detail={"error": str(wb_exc), "note": "fallback writeback also failed"})) + item["writeback_srm"] = False + item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}" + details.append(item) + if len(step_logs) > _MAX_STEP_LOGS_PER_ROW: + step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW] + total_count = success_count + failed_count + skipped_count - return total_count, success_count, failed_count, skipped_count, details, errors + return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs diff --git a/backend/app/services/wecom_notify.py b/backend/app/services/wecom_notify.py index 7f2cc924..3be09db8 100644 --- a/backend/app/services/wecom_notify.py +++ b/backend/app/services/wecom_notify.py @@ -1,6 +1,7 @@ from __future__ import annotations from datetime import datetime, timedelta +from io import BytesIO from urllib.parse import urlencode import uuid @@ -62,16 +63,13 @@ def _get_access_token() -> str: return data['access_token'] -def send_wecom_event_message( - *, +def _create_audit( event_type: str, user: User, title: str, content: str, - jump_path: str = '/workspace', - jump_params: dict | None = None, -) -> dict: - trace_id = uuid.uuid4().hex + trace_id: str, +) -> WecomNotifyAudit: audit = WecomNotifyAudit( event_type=event_type, status='failed', @@ -83,6 +81,83 @@ def send_wecom_event_message( content=content, ) db.session.add(audit) + return audit + + +def upload_wecom_temp_media(file_data: bytes, filename: str) -> str: + token = _get_access_token() + url = ( + f'https://qyapi.weixin.qq.com/cgi-bin/media/upload' + f'?access_token={token}&type=file' + ) + resp = requests.post( + url, + files={'media': (filename, BytesIO(file_data), 'application/octet-stream')}, + timeout=30, + ) + data = resp.json() + if data.get('errcode', 0) != 0 or not data.get('media_id'): + raise RuntimeError(f"WeCom media upload failed: {data}") + return data['media_id'] + + +def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict: + token = _get_access_token() + payload = { + 'touser': wecom_userid, + 'msgtype': 'file', + 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), + 'file': {'media_id': media_id}, + 'safe': 0, + } + resp = requests.post( + 'https://qyapi.weixin.qq.com/cgi-bin/message/send', + params={'access_token': token}, + json=payload, + timeout=8, + ) + return resp.json() + + +def send_wecom_textcard_message( + wecom_userid: str, + title: str, + description: str, + jump_url: str, +) -> dict: + token = _get_access_token() + payload = { + 'touser': wecom_userid, + 'msgtype': 'textcard', + 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), + 'textcard': { + 'title': title[:120], + 'description': (description or '')[:1024], + 'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'), + 'btntxt': '查看详情', + }, + 'safe': 0, + } + resp = requests.post( + 'https://qyapi.weixin.qq.com/cgi-bin/message/send', + params={'access_token': token}, + json=payload, + timeout=8, + ) + return resp.json() + + +def send_wecom_event_message( + *, + event_type: str, + user: User, + title: str, + content: str, + jump_path: str = '/workspace', + jump_params: dict | None = None, +) -> dict: + trace_id = uuid.uuid4().hex + audit = _create_audit(event_type, user, title, content, trace_id) if not current_app.config.get('WECOM_NOTIFY_ENABLED', True): audit.error_code = 'NOTIFY_DISABLED' @@ -100,28 +175,9 @@ def send_wecom_event_message( return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'} try: - token = _get_access_token() jump_url = _build_jump_url(jump_path, trace_id, jump_params) audit.jump_url = jump_url - payload = { - 'touser': user.wecom_userid, - 'msgtype': 'textcard', - 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), - 'textcard': { - 'title': title[:120], - 'description': (content or '')[:1024], - 'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'), - 'btntxt': '查看详情', - }, - 'safe': 0, - } - resp = requests.post( - 'https://qyapi.weixin.qq.com/cgi-bin/message/send', - params={'access_token': token}, - json=payload, - timeout=8, - ) - data = resp.json() + data = send_wecom_textcard_message(user.wecom_userid, title, content, jump_url) if data.get('errcode') == 0: audit.status = 'sent' return {'ok': True, 'trace_id': trace_id} diff --git a/backend/data/schedules/schedule_RUN202605180636031839.xlsx b/backend/data/schedules/schedule_RUN202605180636031839.xlsx deleted file mode 100644 index 7b8577e8..00000000 Binary files a/backend/data/schedules/schedule_RUN202605180636031839.xlsx and /dev/null differ diff --git a/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx b/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx deleted file mode 100644 index 55c6370c..00000000 Binary files a/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx and /dev/null differ diff --git a/backend/migrations/versions/9f3438dc97ca_add_schedule_task_config_and_data_.py b/backend/migrations/versions/9f3438dc97ca_add_schedule_task_config_and_data_.py new file mode 100644 index 00000000..f5bd7ab3 --- /dev/null +++ b/backend/migrations/versions/9f3438dc97ca_add_schedule_task_config_and_data_.py @@ -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') diff --git a/backend/migrations/versions/a1b2c3d4e5f6_add_step_logs_to_schedule_runs.py b/backend/migrations/versions/a1b2c3d4e5f6_add_step_logs_to_schedule_runs.py new file mode 100644 index 00000000..2acae098 --- /dev/null +++ b/backend/migrations/versions/a1b2c3d4e5f6_add_step_logs_to_schedule_runs.py @@ -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') diff --git a/backend/migrations/versions/a9b0c1d2e3f4_store_excel_in_database.py b/backend/migrations/versions/a9b0c1d2e3f4_store_excel_in_database.py new file mode 100644 index 00000000..b4fb1454 --- /dev/null +++ b/backend/migrations/versions/a9b0c1d2e3f4_store_excel_in_database.py @@ -0,0 +1,26 @@ +"""store excel in database instead of local filesystem + +Revision ID: a9b0c1d2e3f4 +Revises: f8b9c0d1e2f3 +Create Date: 2026-05-20 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +revision = 'a9b0c1d2e3f4' +down_revision = ('b7a1c2d3e4f5', 'f8b9c0d1e2f3') +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.add_column(sa.Column('excel_file_data', sa.LargeBinary(), nullable=True)) + batch_op.drop_column('excel_file_path') + + +def downgrade() -> None: + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.add_column(sa.Column('excel_file_path', sa.Text(), nullable=True)) + batch_op.drop_column('excel_file_data') diff --git a/backend/migrations/versions/b7a1c2d3e4f5_add_ds_driver_encrypt_trust_cert.py b/backend/migrations/versions/b7a1c2d3e4f5_add_ds_driver_encrypt_trust_cert.py new file mode 100644 index 00000000..80295e16 --- /dev/null +++ b/backend/migrations/versions/b7a1c2d3e4f5_add_ds_driver_encrypt_trust_cert.py @@ -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') diff --git a/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py b/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py new file mode 100644 index 00000000..77c224b2 --- /dev/null +++ b/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py @@ -0,0 +1,32 @@ +"""replace mail notify fields with wecom notify fields + +Revision ID: c1d2e3f4a5b6 +Revises: a9b0c1d2e3f4 +Create Date: 2026-05-20 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +revision = 'c1d2e3f4a5b6' +down_revision = 'a9b0c1d2e3f4' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('schedule_runs', sa.Column('wecom_notified', sa.Boolean(), nullable=True, server_default=sa.text('false'))) + op.add_column('schedule_runs', sa.Column('wecom_notified_at', sa.DateTime(), nullable=True)) + op.add_column('schedule_runs', sa.Column('wecom_notify_error', sa.Text(), nullable=True)) + op.drop_column('schedule_runs', 'mail_sent') + op.drop_column('schedule_runs', 'mail_sent_at') + op.drop_column('schedule_runs', 'mail_error') + + +def downgrade(): + op.add_column('schedule_runs', sa.Column('mail_error', sa.Text(), nullable=True)) + op.add_column('schedule_runs', sa.Column('mail_sent_at', sa.DateTime(), nullable=True)) + op.add_column('schedule_runs', sa.Column('mail_sent', sa.Boolean(), nullable=True, server_default=sa.text('false'))) + op.drop_column('schedule_runs', 'wecom_notify_error') + op.drop_column('schedule_runs', 'wecom_notified_at') + op.drop_column('schedule_runs', 'wecom_notified') diff --git a/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py b/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py new file mode 100644 index 00000000..12b96795 --- /dev/null +++ b/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py @@ -0,0 +1,71 @@ +"""ensure agents table has primary key on id + +Revision ID: f7a8b9c0d1e2 +Revises: f6d4e5f6a7b8 +Create Date: 2026-05-20 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'f7a8b9c0d1e2' +down_revision = 'f6d4e5f6a7b8' +branch_labels = None +depends_on = None + + +def upgrade(): + conn = op.get_bind() + inspector = sa.inspect(conn) + + if 'agents' not in inspector.get_table_names(): + return + + pk = inspector.get_pk_constraint('agents') or {} + constrained_columns = pk.get('constrained_columns') or [] + if constrained_columns: + return + + duplicate_count = conn.execute( + sa.text( + """ + SELECT COUNT(*) + FROM ( + SELECT id + FROM agents + GROUP BY id + HAVING COUNT(*) > 1 + ) t + """ + ) + ).scalar_one() + if duplicate_count > 0: + raise RuntimeError( + "Cannot add PRIMARY KEY to agents.id because duplicate id values exist. " + "Please deduplicate agents.id first, then rerun migration." + ) + + null_count = conn.execute( + sa.text("SELECT COUNT(*) FROM agents WHERE id IS NULL") + ).scalar_one() + if null_count > 0: + raise RuntimeError( + "Cannot add PRIMARY KEY to agents.id because NULL id values exist. " + "Please fix NULL ids first, then rerun migration." + ) + + op.execute('ALTER TABLE agents ADD CONSTRAINT agents_pkey PRIMARY KEY (id)') + + +def downgrade(): + conn = op.get_bind() + inspector = sa.inspect(conn) + if 'agents' not in inspector.get_table_names(): + return + + pk = inspector.get_pk_constraint('agents') or {} + pk_name = pk.get('name') + cols = pk.get('constrained_columns') or [] + if pk_name == 'agents_pkey' and cols == ['id']: + op.drop_constraint('agents_pkey', 'agents', type_='primary') diff --git a/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py b/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py new file mode 100644 index 00000000..3d0a16fb --- /dev/null +++ b/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py @@ -0,0 +1,21 @@ +"""merge heads after agents pk fix + +Revision ID: f8b9c0d1e2f3 +Revises: c0ae052bd24e, f7a8b9c0d1e2 +Create Date: 2026-05-20 00:30:00.000000 + +""" + + +revision = 'f8b9c0d1e2f3' +down_revision = ('c0ae052bd24e', 'f7a8b9c0d1e2') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/requirements.txt b/backend/requirements.txt index 9faa1cc1..3c85df56 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -34,3 +34,4 @@ beautifulsoup4==4.14.2 lxml==6.0.2 typer==0.17.4 croniter +pyyaml diff --git a/backend/tests/test_schedule_api.py b/backend/tests/test_schedule_api.py index 18dcb061..d7672c93 100644 --- a/backend/tests/test_schedule_api.py +++ b/backend/tests/test_schedule_api.py @@ -61,7 +61,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers): failed_count=0, skipped_count=0, duration_ms=100, - mail_sent=False, + wecom_notified=False, ) db.session.add(run) db.session.commit() diff --git a/docs/demand(需求).md b/docs/demand.md similarity index 73% rename from docs/demand(需求).md rename to docs/demand.md index 77f02776..eb592514 100644 --- a/docs/demand(需求).md +++ b/docs/demand.md @@ -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 端布局与行为无任何变化 diff --git a/docs/funclist(功能清单).md b/docs/funclist.md similarity index 84% rename from docs/funclist(功能清单).md rename to docs/funclist.md index ff52554f..ae726b9d 100644 --- a/docs/funclist(功能清单).md +++ b/docs/funclist.md @@ -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 端布局与行为无任何变化 +- 旋转屏幕后布局实时切换 diff --git a/docs/tec(技术架构).md b/docs/tec.md similarity index 85% rename from docs/tec(技术架构).md rename to docs/tec.md index 410dafd5..eb8f5cea 100644 --- a/docs/tec(技术架构).md +++ b/docs/tec.md @@ -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` 条件 +- 新增移动端顶部栏 `
`: + - 左侧:AI 图标 + Agent 名称 + - 右侧:`UserCircle` 图标按钮,点击 `router.push('/profile')` + +#### WorkspaceView 移动端适配 + +- 左侧导航 `aside` 添加 `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 变更 diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 013c29fa..37024f90 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -10,8 +10,8 @@ AI工作台 - - + +
diff --git a/frontend/src/api/schedule.ts b/frontend/src/api/schedule.ts index d4e9a326..a3c10c29 100644 --- a/frontend/src/api/schedule.ts +++ b/frontend/src/api/schedule.ts @@ -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,34 +39,97 @@ export interface ScheduleRun { api_request_json?: Record | null; api_response_json?: Record | null; response_summary_json?: Record | null; + step_logs?: StepLog[] | null; error_message?: string | null; excel_file_name?: string | null; excel_file_size?: number | null; - mail_sent: boolean; - mail_sent_at?: string | null; - mail_error?: string | null; + wecom_notified: boolean; + wecom_notified_at?: string | null; + wecom_notify_error?: string | null; 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; +} + async function getJson(url: string): Promise { 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('/api/admin/schedules'); -export const createAdminSchedule = (payload: Partial) => +export const listAdminSchedules = () => + getJson('/api/admin/schedules'); + +export const getAdminScheduleTaskConfig = (taskId: number) => + getJson<{ data_source_type: string; config: Record | null }>(`/api/admin/schedule-config/${taskId}`); + +export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record) => + 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; + run_id: number; + sql: string; + limit: number; + total_count: number; + success_count: number; + failed_count: number; + skipped_count: number; + details: Record[]; + 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; + }); + +export const createAdminSchedule = (payload: Partial & { config?: Record }) => fetch('/api/admin/schedules', { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify(payload), }); -export const updateAdminSchedule = (id: number, payload: Partial) => + +export const updateAdminSchedule = (id: number, payload: Partial & { config?: Record }) => 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', diff --git a/frontend/src/composables/useIsMobile.ts b/frontend/src/composables/useIsMobile.ts new file mode 100644 index 00000000..2b746070 --- /dev/null +++ b/frontend/src/composables/useIsMobile.ts @@ -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) }; +} diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 2613e8f1..2af810a5 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -4,7 +4,6 @@ import { createRouter, createWebHistory } from 'vue-router'; import WorkspaceView from '../views/WorkspaceView.vue'; import ChatView from '../views/ChatView.vue'; import AdminView from '../views/AdminView.vue'; -import ProfileView from '../views/ProfileView.vue'; import ResetPasswordView from '../views/ResetPasswordView.vue'; import KbWorkspaceView from '../views/KbWorkspaceView.vue'; import KbAdminView from '../views/KbAdminView.vue'; @@ -14,7 +13,8 @@ import { getStoredAuthUser } from '../utils/auth'; const routes = [ { path: '/', - redirect: '/workspace' + name: 'Home', + component: WorkspaceView }, { path: '/workspace', @@ -26,11 +26,6 @@ const routes = [ name: 'CasdoorCallback', component: WorkspaceView }, - { - path: '/profile', - name: 'Profile', - component: ProfileView - }, { path: '/reset-password', name: 'ResetPassword', @@ -67,14 +62,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(); }); diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index e1ea1342..eb2e18d0 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -20,7 +20,7 @@ import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useRe import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog'; import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom'; import { getAuthHeaders } from '../utils/auth'; -import { listAdminSchedules, createAdminSchedule, updateAdminSchedule, deleteAdminSchedule, toggleAdminSchedule, runAdminSchedule, listAdminScheduleRuns, type ScheduleTask, type ScheduleRun } from '../api/schedule'; +import { listAdminSchedules, createAdminSchedule, updateAdminSchedule, deleteAdminSchedule, toggleAdminSchedule, runAdminSchedule, listAdminScheduleRuns, getAdminScheduleTaskConfig, testAdminScheduleSql, testAdminScheduleRun, type ScheduleTask, type ScheduleRun, type TestScheduleRunResult } from '../api/schedule'; import { ArrowLeft, // Save, @@ -46,8 +46,14 @@ import { Unlink2, RefreshCw, CircleHelp, - Pause, - Play + Eye, + ChevronDown, + ChevronUp, + Edit3, + Power, + PowerOff, + Rocket, + FlaskConical } from 'lucide-vue-next'; import * as XLSX from 'xlsx'; @@ -94,6 +100,7 @@ interface AgentRow { is_active: boolean; description?: string; type: 'api' | 'iframe'; + dify_app_type?: 'chatflow' | 'workflow'; api_base_url?: string; extra_config?: Record; iframe_url?: string; // Frontend helper property @@ -248,6 +255,7 @@ const newAgent = ref>({ dify_api_key: '', description: '', type: 'api', + dify_app_type: 'chatflow', api_base_url: '', iframe_url: '', is_active: true @@ -418,6 +426,7 @@ const wecomSystemSettings = ref({ }); const wecomIntegrationManifest = ref(null); const schedules = ref([]); +const schedulesLoaded = ref(false); void schedulesLoaded; const selectedScheduleRuns = ref([]); const scheduleLoading = ref(false); const scheduleRunsLoading = ref(false); @@ -425,6 +434,47 @@ const selectedScheduleId = ref(null); const scheduleRunStatusFilter = ref<'all' | string>('all'); const scheduleRunStartedAfter = ref(''); const scheduleRunStartedBefore = ref(''); +const scheduleRunColumnDefs = ref([ + { key: 'run_no', label: '执行单号', width: 280, min: 60 }, + { key: 'started_at', label: '开始时间', width: 190, min: 60 }, + { key: 'finished_at', label: '结束时间', width: 190, min: 60 }, + { key: 'status', label: '状态', width: 130, min: 50 }, + { key: 'total_count', label: '处理', width: 70, min: 40 }, + { key: 'success_count', label: '成功', width: 70, min: 40 }, + { key: 'failed_count', label: '失败', width: 70, min: 40 }, + { key: 'wecom_notified', label: '企微通知', width: 90, min: 50 }, + { key: 'detail', label: '明细', width: 90, min: 50 }, + { key: 'log', label: '日志', width: 90, min: 50 }, +]); +const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null); + +const onScheduleColResizeMove = (event: MouseEvent) => { + const state = resizingScheduleCol.value; + if (!state) return; + const def = scheduleRunColumnDefs.value[state.index]; + if (!def) return; + const delta = event.clientX - state.startX; + def.width = Math.max(def.min, state.startWidth + delta); +}; + +const stopScheduleColResize = () => { + if (!resizingScheduleCol.value) return; + resizingScheduleCol.value = null; + window.removeEventListener('mousemove', onScheduleColResizeMove); + window.removeEventListener('mouseup', stopScheduleColResize); +}; + +const startScheduleColResize = (index: number, event: MouseEvent) => { + const def = scheduleRunColumnDefs.value[index]; + if (!def) return; + resizingScheduleCol.value = { + index, + startX: event.clientX, + startWidth: def.width, + }; + window.addEventListener('mousemove', onScheduleColResizeMove); + window.addEventListener('mouseup', stopScheduleColResize); +}; const scheduleViewMode = ref<'overview' | 'workbench'>('overview'); const showScheduleCreateModal = ref(false); const scheduleCreateSaving = ref(false); @@ -432,6 +482,7 @@ const scheduleEditingId = ref(null); const scheduleCreateForm = ref({ name: '', platform_api_path: '', + data_source_type: 'database' as 'database' | 'external_api', dify_agent_id: null as number | null, owner_user_id: null as number | null, wait_seconds: 300, @@ -439,6 +490,7 @@ const scheduleCreateForm = ref({ notify_user_ids_json: [] as number[], enabled: true, }); +const scheduleConfigCollapsed = ref(true); const scheduleCronDesigner = ref({ mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly', every_minutes: 30, @@ -597,6 +649,7 @@ const resetScheduleCreateForm = () => { scheduleCreateForm.value = { name: '', platform_api_path: '', + data_source_type: 'database', dify_agent_id: null, owner_user_id: null, wait_seconds: 300, @@ -604,6 +657,32 @@ const resetScheduleCreateForm = () => { notify_user_ids_json: [], enabled: true, }; + scheduleSqlEditForm.value = { + base_fetch_sql: '', + fetch_where_conditions: '', + fetch_order_by: '', + detail_sql: '', + writeback_sql: '', + row_id_key: 'id', + log_prefix: '', + alias_order_str: '', + detail_alias_order_str: '', + header_labels_str: '{}', + ds_db_type: 'sqlserver', + ds_host: '', + ds_port: '', + ds_database: '', + ds_username: '', + ds_password: '', + ds_driver: '', + ds_encrypt: '', + ds_trust_cert: '', + api_url: '', + api_method: 'POST', + api_headers_str: '{}', + api_body_template: '', + }; + scheduleTestResult.value = null; scheduleCronDesigner.value = { mode: 'every_minutes', every_minutes: 30, @@ -618,12 +697,14 @@ const resetScheduleCreateForm = () => { const openScheduleCreateModal = async () => { resetScheduleCreateForm(); + scheduleConfigCollapsed.value = true; await Promise.all([loadAgents(), loadUsers()]); showScheduleCreateModal.value = true; }; const openScheduleEditModal = async (task: ScheduleTask) => { await Promise.all([loadAgents(), loadUsers()]); + scheduleConfigCollapsed.value = true; scheduleEditingId.value = task.id; scheduleCreateForm.value = { name: task.name || '', @@ -634,7 +715,69 @@ const openScheduleEditModal = async (task: ScheduleTask) => { notify_enabled: !!task.notify_enabled, notify_user_ids_json: task.notify_user_ids_json || [], enabled: !!task.enabled, + data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api', }; + + try { + const result = await getAdminScheduleTaskConfig(task.id); + const cfg = result.config; + scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api'; + if (cfg) { + scheduleSqlEditForm.value = { + base_fetch_sql: cfg.base_fetch_sql || '', + fetch_where_conditions: cfg.fetch_where_conditions || '', + fetch_order_by: cfg.fetch_order_by || '', + detail_sql: cfg.detail_sql || '', + writeback_sql: cfg.writeback_sql || '', + row_id_key: cfg.row_id_key || 'id', + log_prefix: cfg.log_prefix || '', + alias_order_str: (cfg.alias_order || []).join(','), + detail_alias_order_str: (cfg.detail_alias_order || []).join(','), + header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}', + ds_db_type: cfg.data_source?.db_type || 'sqlserver', + ds_host: cfg.data_source?.host || '', + ds_port: cfg.data_source?.port || '', + ds_database: cfg.data_source?.database || '', + ds_username: cfg.data_source?.username || '', + ds_password: cfg.data_source?.password || '', + ds_driver: cfg.data_source?.driver || '', + ds_encrypt: cfg.data_source?.encrypt || '', + ds_trust_cert: cfg.data_source?.trust_cert || '', + api_url: cfg.external_api?.url || '', + api_method: cfg.external_api?.method || 'POST', + api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}', + api_body_template: cfg.external_api?.body_template || '', + }; + } + } catch { + scheduleSqlEditForm.value = { + base_fetch_sql: '', + fetch_where_conditions: '', + fetch_order_by: '', + detail_sql: '', + writeback_sql: '', + row_id_key: 'id', + log_prefix: '', + alias_order_str: '', + detail_alias_order_str: '', + header_labels_str: '{}', + ds_db_type: 'sqlserver', + ds_host: '', + ds_port: '', + ds_database: '', + ds_username: '', + ds_password: '', + ds_driver: '', + ds_encrypt: '', + ds_trust_cert: '', + api_url: '', + api_method: 'POST', + api_headers_str: '{}', + api_body_template: '', + }; + } + + scheduleTestResult.value = null; parseCronExprToDesigner(task.cron_expr); showScheduleCreateModal.value = true; }; @@ -670,6 +813,71 @@ 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 expandedScheduleRunId = ref(null); + +const stepLabelMap: Record = { + fetch_srm: '抓取外部系统数据', + call_dify: '调用Dify服务', + writeback_srm: '回写外部系统数据', + call_internal_api: '调用内部API', + pre_dify: 'Dify前处理', +}; +const stepStatusMap: Record = { + success: { cls: 'bg-emerald-100 text-emerald-700', label: '成功' }, + failed: { cls: 'bg-rose-100 text-rose-700', label: '失败' }, +}; + +const showTestRunDialog = ref(false); +const testRunSchedule = ref(null); +const testRunWhere = ref(''); +const testRunOrderBy = ref(''); +const testRunBaseFetchSql = ref(''); +const testRunLimit = ref(3); +const testRunLoading = ref(false); +const testRunResult = ref(null); + +const openTestRunDialog = async (s: ScheduleTask) => { + testRunSchedule.value = s; + try { + const result = await getAdminScheduleTaskConfig(s.id); + const cfg = result.config; + testRunWhere.value = cfg?.fetch_where_conditions || ''; + testRunOrderBy.value = cfg?.fetch_order_by || ''; + testRunBaseFetchSql.value = cfg?.base_fetch_sql || ''; + } catch { + testRunWhere.value = ''; + testRunOrderBy.value = ''; + testRunBaseFetchSql.value = ''; + } + testRunLimit.value = 3; + testRunResult.value = null; + testRunLoading.value = false; + showTestRunDialog.value = true; +}; + +const handleTestRun = async () => { + const s = testRunSchedule.value; + if (!s?.id) return; + testRunLoading.value = true; + testRunResult.value = null; + try { + const result = await testAdminScheduleRun(s.id, { + fetch_where_conditions: testRunWhere.value, + fetch_order_by: testRunOrderBy.value, + limit: testRunLimit.value, + }); + testRunResult.value = result; + await loadSchedules(); + if (s.id) { + await viewScheduleRuns(s.id); + } + } catch (e: any) { + showMessageDialog('error', `测试执行失败: ${e?.message || e}`); + } finally { + testRunLoading.value = false; + } +}; + const filteredScheduleRuns = computed(() => { if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value; return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value); @@ -719,30 +927,163 @@ const loadSchedules = async () => { } }; +const scheduleSqlEditForm = ref({ + base_fetch_sql: '', + fetch_where_conditions: '', + fetch_order_by: '', + detail_sql: '', + writeback_sql: '', + row_id_key: 'id', + log_prefix: '', + alias_order_str: '', + detail_alias_order_str: '', + header_labels_str: '{}', + ds_db_type: 'sqlserver', + ds_host: '', + ds_port: '', + ds_database: '', + ds_username: '', + ds_password: '', + ds_driver: '', + ds_encrypt: '', + ds_trust_cert: '', + api_url: '', + api_method: 'POST', + api_headers_str: '{}', + api_body_template: '', +}); +const scheduleSqlSaving = ref(false); void scheduleSqlSaving; +const scheduleTestLoading = ref(false); +const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null); + +const handleTestScheduleSql = async () => { + const taskId = scheduleEditingId.value; + if (!taskId) return; + + scheduleTestLoading.value = true; + scheduleTestResult.value = null; + try { + const result = await testAdminScheduleSql(taskId, { + fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions, + fetch_order_by: scheduleSqlEditForm.value.fetch_order_by, + limit: 10, + }); + scheduleTestResult.value = result; + } catch (e: any) { + showMessageDialog('error', `测试查询失败: ${e?.message || e}`); + } finally { + scheduleTestLoading.value = false; + } +}; + +const scheduleNotifyDropdownOpen = ref(false); + +const getUserName = (uid: number) => { + const u = users.value.find(x => x.id === uid); + return u ? (u.real_name || u.username) : String(uid); +}; + +const toggleNotifyUser = (uid: number) => { + const list = scheduleCreateForm.value.notify_user_ids_json; + if (list.includes(uid)) { + scheduleCreateForm.value.notify_user_ids_json = list.filter((id: number) => id !== uid); + } else { + scheduleCreateForm.value.notify_user_ids_json = [...list, uid]; + } +}; + +const removeNotifyUser = (uid: number) => { + scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid); +}; + const createSchedule = async () => { if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return; - scheduleCreateSaving.value = true; - const payload: Partial = { - name: scheduleCreateForm.value.name, - schedule_type: 'platform_app', - owner_user_id: scheduleCreateForm.value.owner_user_id, - cron_expr: scheduleCronPreview.value, - wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)), - dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined, - platform_api_path: scheduleCreateForm.value.platform_api_path?.trim() || undefined, - notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [], - notify_enabled: scheduleCreateForm.value.notify_enabled, - enabled: scheduleCreateForm.value.enabled, - }; - const res = scheduleEditingId.value - ? await updateAdminSchedule(scheduleEditingId.value, payload) - : await createAdminSchedule(payload); + + const dst = scheduleCreateForm.value.data_source_type; + const hasAgent = !!scheduleCreateForm.value.dify_agent_id; + const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim(); + const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim(); + if (!hasAgent && !hasSql && !hasApi) { + showMessageDialog('error', 'Dify Agent、SQL 配置或外部 API 至少填写一项,否则排程执行无任何效果'); + return; + } + + let headerLabels: Record = {}; try { + headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}'); + } catch { + showMessageDialog('error', 'header_labels JSON 格式错误,请检查'); + return; + } + let apiHeaders: Record = {}; + if (dst === 'external_api') { + try { + apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}'); + } catch { + showMessageDialog('error', 'API Headers JSON 格式错误,请检查'); + return; + } + } + const aliasOrder = scheduleSqlEditForm.value.alias_order_str.split(',').map(s => s.trim()).filter(Boolean); + const detailAliasOrder = scheduleSqlEditForm.value.detail_alias_order_str.split(',').map(s => s.trim()).filter(Boolean); + + const configPayload: Record = { + base_fetch_sql: scheduleSqlEditForm.value.base_fetch_sql, + fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions, + fetch_order_by: scheduleSqlEditForm.value.fetch_order_by, + detail_sql: scheduleSqlEditForm.value.detail_sql, + writeback_sql: scheduleSqlEditForm.value.writeback_sql, + row_id_key: scheduleSqlEditForm.value.row_id_key || 'id', + log_prefix: scheduleSqlEditForm.value.log_prefix, + alias_order: aliasOrder, + detail_alias_order: detailAliasOrder, + header_labels: headerLabels, + data_source: scheduleSqlEditForm.value.ds_host.trim() ? { + db_type: scheduleSqlEditForm.value.ds_db_type, + host: scheduleSqlEditForm.value.ds_host, + port: scheduleSqlEditForm.value.ds_port, + database: scheduleSqlEditForm.value.ds_database, + username: scheduleSqlEditForm.value.ds_username, + password: scheduleSqlEditForm.value.ds_password, + driver: scheduleSqlEditForm.value.ds_driver, + encrypt: scheduleSqlEditForm.value.ds_encrypt, + trust_cert: scheduleSqlEditForm.value.ds_trust_cert, + } : undefined, + external_api: scheduleSqlEditForm.value.api_url.trim() ? { + url: scheduleSqlEditForm.value.api_url, + method: scheduleSqlEditForm.value.api_method, + headers: apiHeaders, + body_template: scheduleSqlEditForm.value.api_body_template, + } : undefined, + }; + + scheduleCreateSaving.value = true; + try { + const payload: any = { + name: scheduleCreateForm.value.name, + schedule_type: 'platform_app', + owner_user_id: scheduleCreateForm.value.owner_user_id, + cron_expr: scheduleCronPreview.value, + wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)), + dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined, + notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [], + notify_enabled: scheduleCreateForm.value.notify_enabled, + enabled: scheduleCreateForm.value.enabled, + data_source_type: dst, + config: configPayload, + }; + let res: Response; + if (scheduleEditingId.value) { + res = await updateAdminSchedule(scheduleEditingId.value, payload); + } else { + res = await createAdminSchedule(payload); + } + if (res.ok) { let createdId: number | null = null; try { - const payload = await res.clone().json(); - createdId = payload?.id ?? payload?.schedule?.id ?? null; + const resultData = await res.clone().json(); + createdId = resultData?.id ?? resultData?.schedule?.id ?? null; } catch { createdId = null; } @@ -1848,6 +2189,7 @@ const selectAgent = (agent: AgentRow) => { // Deep clone and ensure all fields are present newAgent.value = { ...agent, + dify_app_type: (agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow') as 'chatflow' | 'workflow', // Show existing API key while editing selected row. dify_api_key: agent.dify_api_key || '', iframe_url: agent.extra_config?.iframe_url || '' @@ -1863,6 +2205,7 @@ const resetAgentForm = () => { dify_api_key: '', description: '', type: 'api', + dify_app_type: 'chatflow', api_base_url: '', iframe_url: '', is_active: true @@ -1933,7 +2276,13 @@ const createAgent = async () => { } isSaving.value = true; - const extra_config = newAgent.value.iframe_url ? { iframe_url: newAgent.value.iframe_url } : {}; + const extra_config: Record = {}; + if (newAgent.value.type === 'iframe' && newAgent.value.iframe_url) { + extra_config.iframe_url = newAgent.value.iframe_url; + } + if (newAgent.value.type === 'api') { + extra_config.dify_app_type = newAgent.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow'; + } let res; try { @@ -3465,6 +3814,16 @@ const handlePermissionImport = async (event: Event) => { - diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 4a3dd363..cfaee995 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -13,17 +13,34 @@ 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 } 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, History } 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 showMobileAgentPopover = ref(false); +const mobileAgentPopoverRef = ref(null); + +const handleMobileAgentPopoverClickOutside = (e: MouseEvent | TouchEvent) => { + if (mobileAgentPopoverRef.value && !mobileAgentPopoverRef.value.contains(e.target as Node)) { + showMobileAgentPopover.value = false; + } +}; + +const toggleMobileAgentPopover = () => { + showMobileAgentPopover.value = !showMobileAgentPopover.value; + if (showMobileAgentPopover.value) { + loadUserAgents(); + } +}; const currentUser = ref(getStoredAuthUser()); const showUserDropdown = ref(false); const userMenuRef = ref(null); @@ -34,6 +51,7 @@ const kbMenuRef = ref(null); const kbOptions = ['企业知识库', 'ERP知识库']; const chatScrollContainer = ref(null); let scrollToBottomFrame: number | null = null; +let wasThinking = false; marked.setOptions({ gfm: true, @@ -571,54 +589,80 @@ const copiedIndex = ref(null); const { messages, isThinking, conversationId, sendMessage } = useChat(); const input = ref(''); const currentAgent = ref(null); +const userAgents = ref>([]); const showGeneralFeedbackDialog = ref(false); +const showAgentPanel = ref(true); -const OA_BASE_URL = 'http://oa.well-trust.com:8888'; -const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`; +const OA_BASE_URL = 'http://192.168.100.221:8888'; const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`; const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid='; const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid='; -const OA_AUTO_LOGIN_USERNAME = '26040006'; -const OA_AUTO_LOGIN_PASSWORD = '26040006'; const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request'; -const openOAAutoLoginPage = (gopage: string, target = OA_AUTO_LOGIN_TARGET) => { - const popup = window.open(OA_LOGIN_URL, target); +// OA 登录对话框状态 +const OA_PASSWORD_STORAGE_KEY = 'hxops_oa_login_password'; +const showOALoginDialog = ref(false); +const oaLoginEmployeeId = ref(''); +const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || ''); +const oaLoginGopage = ref(''); +const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET); + +const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => { + // 直接在弹出窗口内写入自动提交表单,避免跨窗口时序问题 + const popup = window.open('about:blank', target); if (!popup) { showMessageDialog('warning', '浏览器拦截了 OA 页面,请允许弹出窗口后重试。'); return; } - const form = document.createElement('form'); - form.action = OA_VERIFY_LOGIN_URL; - form.method = 'POST'; - form.target = target; - form.style.display = 'none'; + const formHtml = ` + + + 正在登录OA系统... + +

正在登录OA系统,请稍候...

+
+ + + + +
+ - - diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index 221f99cc..8ca258fe 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -5,7 +5,7 @@ * 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口 */ import { ref, onMounted, computed, watch, nextTick } from 'vue'; -import { useRouter } from 'vue-router'; +import { useRouter, useRoute } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { config } from '../config'; import { useTheme } from '../composables/useTheme'; @@ -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 { @@ -57,7 +58,9 @@ import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next'; const { t, locale } = useI18n(); const { showMessageDialog } = useGlobalMessageDialog(); const router = useRouter(); +const route = useRoute(); const { setThemePreference, appliedTheme } = useTheme(); +const { isMobile } = useIsMobile(); const loginBackgroundStyle = { backgroundImage: `url(${loginBg})`, backgroundSize: 'cover', @@ -316,7 +319,7 @@ const fetchHome = async () => { defaultSections.forEach(d => { if (!backendIds.has(d.id)) { if (config.workspace.modules[mapKey(d.id) as keyof typeof config.workspace.modules] === false) { - return; +return; } merged.push(d); } @@ -767,7 +770,7 @@ const handleRegister = async () => { } }; -const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs'>('applications'); +const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs' | 'history'>('applications'); const isProfileLoading = ref(false); const isProfileSaving = ref(false); const isProfileEditing = ref(false); @@ -810,6 +813,31 @@ const hasProfileUnsavedChanges = computed(() => { ); }); +const mobileTabActive = computed({ + get: () => { + if (activeSidebarItem.value === 'profile') return 'profile'; + if (activeSidebarItem.value === 'history') return 'history'; + return 'applications'; + }, + set: (tab: 'applications' | 'profile' | 'history') => { + if (tab === 'profile') { + activeSidebarItem.value = 'profile'; + if (!profileUser.value.id) fetchProfile(); + } else if (tab === 'history') { + activeSidebarItem.value = 'history'; + if (chatHistories.value.length === 0) loadChatHistories(); + } else { + activeSidebarItem.value = 'applications'; + } + }, +}); + +const mobileTabTitle = computed(() => { + if (mobileTabActive.value === 'profile') return '我的'; + if (mobileTabActive.value === 'history') return '历史会话'; + return '应用管理'; +}); + const handleLogout = () => { localStorage.removeItem('hxops_user'); sessionStorage.removeItem('hxops_user'); @@ -1000,8 +1028,25 @@ const workspaceScheduleRuns = ref([]); 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 +1075,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 +1094,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(); }; @@ -1084,6 +1117,43 @@ const downloadWsScheduleExcel = async (runId: number) => { URL.revokeObjectURL(url); }; +interface ChatHistoryItem { + id: number; + conversation_id: string; + title: string; + agent_id?: number; + agent_name?: string; + created_at: string; +} +const chatHistories = ref([]); +const isLoadingHistories = ref(false); + +const loadChatHistories = async () => { + isLoadingHistories.value = true; + try { + const res = await fetch('/api/agents', { headers: getAuthHeaders() }); + if (!res.ok) { isLoadingHistories.value = false; return; } + const agentList = await res.json(); + const allHistories: ChatHistoryItem[] = []; + await Promise.all( + (Array.isArray(agentList) ? agentList : []).map(async (agent: any) => { + try { + const hRes = await fetch(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() }); + if (hRes.ok) { + const sessions = await hRes.json(); + for (const s of sessions) { + allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name }); + } + } + } catch {} + }) + ); + allHistories.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); + chatHistories.value = allHistories; + } catch {} + isLoadingHistories.value = false; +}; + const navigateToGeneralChat = () => { router.push(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`); }; @@ -1297,6 +1367,17 @@ onMounted(async () => { if (currentUser.value && currentUser.value.role !== 'guest') { await fetchHome(); await handleWecomDeeplinkContext(); + const viewParam = route.query.view as string; + const validViews: string[] = ['profile', 'applications', 'feedback', 'updates', 'knowledge_base', 'schedule_runs', 'history']; + if (viewParam && validViews.includes(viewParam)) { + activeSidebarItem.value = viewParam as typeof activeSidebarItem.value; + if (viewParam === 'profile' && !profileUser.value.id) { + await fetchProfile(); + } + if (viewParam === 'history') { + await loadChatHistories(); + } + } } else { await fetchPublicAgents(); isLoading.value = false; @@ -1343,7 +1424,7 @@ onMounted(async () => { -
-