Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-05-21 10:24:20 +08:00
commit 718c5a18d2
43 files changed
+4149 -1295

No files matched your search

+2 -2
View File
@@ -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
Vendored
+212
View File
@@ -1,3 +1,152 @@
import groovy.json.JsonOutput
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
def notifyWecomDeploy(Map opts) {
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
return
}
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
def content = buildDeployNotifyMarkdown(opts)
try {
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
if (!webhookUrl) {
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
return
}
def payload = [
msgtype: 'markdown',
markdown: [content: content.markdown],
]
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
def httpCode = sh(
returnStdout: true,
script: '''
set +e
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
-X POST "$WECOM_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d @wecom-notify-payload.json)
echo "[WeCom] HTTP ${code}" >&2
cat wecom-notify-response.txt >&2 || true
echo "${code}"
'''
).trim()
def resp = readFile('wecom-notify-response.txt').trim()
if (httpCode == '200' && resp.contains('"errcode":0')) {
echo '[WeCom] 通知已发送'
} else {
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
}
}
} catch (Exception e) {
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
}
}
// PushPlus → 个人微信(方案3)。Token 存 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN,见 https://www.pushplus.plus/
def buildDeployNotifyMarkdown(Map opts) {
def envLabel = opts.envLabel ?: '部署环境'
def host = opts.host ?: '-'
def status = (opts.status ?: 'success').toString().toLowerCase()
def isSuccess = status == 'success'
def extraNote = (opts.extraNote ?: '').trim()
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
def buildLink = env.BUILD_URL ?: '-'
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
def lines = [
"## ${title}",
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
"> **提交**: `${shortCommit}`",
"> **目标主机**: ${host}",
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
]
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
lines << '> **备注**: 强制全量部署'
}
if (env.REMOTE_DRIFT_DETECTED == 'true') {
lines << '> **备注**: 远端版本漂移触发部署'
}
if (extraNote) {
lines << "> **说明**: ${extraNote}"
}
if (!isSuccess) {
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
}
return [title: title, markdown: lines.join('\n')]
}
def notifyPushPlusDeploy(Map opts) {
if ((env.DISABLE_DEPLOY_PUSHPLUS_NOTIFY ?: '').equalsIgnoreCase('true')) {
echo '[PushPlus] DISABLE_DEPLOY_PUSHPLUS_NOTIFY=true,跳过通知'
return
}
def credId = (opts.tokenCredId ?: env.PUSHPLUS_TOKEN_CRED ?: 'PUSHPLUS_DEPLOY_TOKEN').trim()
def content = buildDeployNotifyMarkdown(opts)
try {
withCredentials([string(credentialsId: credId, variable: 'PUSHPLUS_TOKEN')]) {
def token = PUSHPLUS_TOKEN?.trim()
if (!token) {
echo "[PushPlus] 凭据 ${credId} 为空,跳过通知"
return
}
def payload = [
token: token,
title: "[HxOps] ${content.title}",
content: content.markdown,
template: 'markdown',
channel: 'wechat',
]
def topic = (env.PUSHPLUS_TOPIC ?: '').trim()
if (topic) {
payload.topic = topic
}
writeFile(file: 'pushplus-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
def httpCode = sh(
returnStdout: true,
script: '''
set +e
code=$(curl -sS -o pushplus-notify-response.txt -w "%{http_code}" \
-X POST "https://www.pushplus.plus/send" \
-H "Content-Type: application/json" \
-d @pushplus-notify-payload.json)
echo "[PushPlus] HTTP ${code}" >&2
cat pushplus-notify-response.txt >&2 || true
echo "${code}"
'''
).trim()
def resp = readFile('pushplus-notify-response.txt').trim()
if (httpCode == '200' && (resp.contains('"code":200') || resp.contains('"code": 200'))) {
echo '[PushPlus] 微信通知已发送'
} else {
echo "[PushPlus] 发送可能失败,HTTP=${httpCode},响应=${resp}"
}
}
} catch (Exception e) {
echo "[PushPlus] 通知发送异常(不影响构建结果): ${e.message}"
}
}
// 企业微信 + PushPlus 微信双通道
def notifyDeployAll(Map opts) {
notifyWecomDeploy(opts)
notifyPushPlusDeploy(opts)
}
pipeline {
agent any
@@ -40,6 +189,9 @@ pipeline {
DEV_DEPLOY_ROOT = '/opt/hxops'
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
PUSHPLUS_TOPIC = 'hxops666'
}
stages {
@@ -242,6 +394,36 @@ pipeline {
}
echo "[Deploy Test] done"
}
post {
success {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyDeployAll(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为人工取消)',
)
}
}
}
}
stage('Deploy Prod') {
@@ -301,6 +483,36 @@ pipeline {
}
echo "[Deploy Prod] done"
}
post {
success {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyDeployAll(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
)
}
}
}
}
}
-58
View File
@@ -1,58 +0,0 @@
INTEGRATION_API_BASE=http://192.168.100.230:8891
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
# AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password
AUTH_LOGIN_MODE=password
# Casdoor JWT 验签三件套
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
# Casdoor OAuth
CASDOOR_BASE_URL=http://192.168.100.230:8870
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
# CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
CASDOOR_SCOPE=openid profile email
# 是否保留本地密码登录/本地JWT兼容(按你当前需求建议保留)
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
AUTH_ALLOW_LOCAL_JWT=true
AUTH_LOCAL_JWT_ISSUER=hxops-backend
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
GJL_API_BASE=https://api.siliconflow.cn/v1
GJL_MODEL=deepseek-ai/DeepSeek-V3
# HR SQL Server Configuration
HR_SQLSERVER_HOST=192.168.100.191
HR_SQLSERVER_PORT=1433
HR_SQLSERVER_DATABASE=NH_N8_HEXIN
HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr
HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR
HR_SQLSERVER_DRIVER=SQL Server
HR_SQLSERVER_ENCRYPT=no
HR_SQLSERVER_TRUST_CERT=yes
HR_SQLSERVER_TIMEOUT=10
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/hxops_db
# SRM SQL Server Configuration
SRM_SQLSERVER_HOST=192.168.55.106
SRM_SQLSERVER_PORT=1433
SRM_SQLSERVER_DATABASE=HX-SRM
SRM_SQLSERVER_USERNAME=sa
SRM_SQLSERVER_PASSWORD=sa@moreyou456
SRM_SQLSERVER_DRIVER=SQL Server
SRM_SQLSERVER_ENCRYPT=no
SRM_SQLSERVER_TRUST_CERT=yes
SRM_SQLSERVER_TIMEOUT=10
+2
View File
@@ -53,6 +53,7 @@ def create_app(config_name='default'):
from app.api.integration import integration_bp
from app.api.schedule_admin import schedule_admin_bp
from app.api.workspace_schedule import workspace_schedule_bp
from app.api.internal_jobs import internal_jobs_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
@@ -68,6 +69,7 @@ def create_app(config_name='default'):
app.register_blueprint(integration_bp, url_prefix='/api/integration')
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
+64 -22
View File
@@ -380,7 +380,7 @@ def delete_agent(id):
@require_admin
def test_agent(id):
"""
测试应用连通性与基础响应质量。
测试应用连通性。
返回:请求地址、输出信息、结果分析。
若测试通过,则自动将应用状态置为启用。
"""
@@ -446,14 +446,29 @@ def test_agent(id):
'tested_at': tested_at
}), 400
request_url = DifyService._build_chat_messages_url(base_url)
payload = {
'inputs': {},
'query': '系统连通性测试,请简短回复OK。',
'response_mode': 'blocking',
'conversation_id': '',
'user': 'admin_test'
}
extra_config = agent.extra_config or {}
dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower()
if dify_app_type not in ('chatflow', 'workflow'):
dify_app_type = 'chatflow'
if dify_app_type == 'workflow':
request_url = DifyService._build_workflow_url(base_url)
payload = {
'inputs': {
'query': '系统连通性测试,请简短回复OK。'
},
'response_mode': 'blocking',
'user': 'admin_test'
}
else:
request_url = DifyService._build_chat_messages_url(base_url)
payload = {
'inputs': {},
'query': '系统连通性测试,请简短回复OK。',
'response_mode': 'blocking',
'conversation_id': '',
'user': 'admin_test'
}
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
'Content-Type': 'application/json'
@@ -466,24 +481,49 @@ def test_agent(id):
success = False
analysis = f'测试失败:HTTP {resp.status_code}。'
# 连通性测试:仅 workflow 按“接口可达+认证通过(2xx)”判定通过
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
success = True
analysis = '测试通过:Workflow 接口可访问且认证通过。'
try:
data = resp.json()
answer = data.get('answer') if isinstance(data, dict) else None
if answer:
output_info = str(answer)[:4000]
if resp.ok and isinstance(answer, str) and answer.strip():
success = True
analysis = '测试通过:接口连通正常,已成功返回回答。'
elif resp.ok:
analysis = '测试未通过:接口可访问,但未返回有效回答。'
else:
if dify_app_type == 'workflow':
workflow_data = data.get('data') if isinstance(data, dict) else None
outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None
status = workflow_data.get('status') if isinstance(workflow_data, dict) else None
message = data.get('message') if isinstance(data, dict) else None
if message:
output_info = str(message)[:4000]
if isinstance(outputs, dict) and outputs:
output_info = str(outputs)[:4000]
elif isinstance(message, str) and message.strip():
output_info = message[:4000]
elif isinstance(data, dict):
output_info = str(data)[:4000]
if resp.ok and status in ('succeeded', 'success'):
analysis = '测试通过:Workflow 接口可访问且业务返回成功。'
elif resp.ok:
analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。'
else:
answer = data.get('answer') if isinstance(data, dict) else None
if answer:
output_info = str(answer)[:4000]
if resp.ok and isinstance(answer, str) and answer.strip():
success = True
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
elif resp.ok:
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
else:
message = data.get('message') if isinstance(data, dict) else None
if message:
output_info = str(message)[:4000]
except ValueError:
if resp.ok and raw_text.strip():
success = True
analysis = '测试通过:接口连通正常,返回了文本内容。'
if dify_app_type == 'workflow':
success = True
analysis = '测试通过:Workflow 接口可访问并返回了文本内容。'
else:
success = True
analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。'
if success and not agent.is_active:
agent.is_active = True
@@ -491,6 +531,7 @@ def test_agent(id):
return jsonify({
'success': success,
'dify_app_type': dify_app_type,
'request_url': request_url,
'output_info': output_info,
'analysis': analysis,
@@ -500,6 +541,7 @@ def test_agent(id):
except requests.RequestException as e:
return jsonify({
'success': False,
'dify_app_type': dify_app_type,
'request_url': request_url,
'output_info': str(e),
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
+5 -2
View File
@@ -11,6 +11,7 @@ import mimetypes
import tempfile
import os
import subprocess
import uuid
from urllib.parse import urlparse
import requests
@@ -738,13 +739,15 @@ def chat_completions():
conversation_id = data.get('conversation_id')
# 知识库类型
kb_type = data.get('kb_type', '企业知识库')
request_id = uuid.uuid4().hex[:12]
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info(
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
"[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
request_id,
getattr(user, 'id', None),
getattr(agent, 'id', None),
len(query or ''),
@@ -776,7 +779,7 @@ def chat_completions():
if HRLeaveSQLServerService.supports(query):
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
else:
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id)
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _run_generic_check_job
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
run_no = str(data.get("run_no") or "").strip()
schedule_task_id = data.get("schedule_task_id")
task = None
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if not task and key.isdigit():
task = db.session.get(ScheduleTask, int(key))
if not task:
task = ScheduleTask.query.filter(
ScheduleTask.platform_api_path.ilike(f"%{key}%")
).first()
if not task:
return jsonify({"error": f"No schedule task found for '{name}'"}), 404
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no).first()
if not run:
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
except Exception as exc:
run.status = "failed"
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
return jsonify({
"error": str(exc),
"traceback": traceback.format_exc(),
"summary": {"total_count": 0, "success_count": 0, "failed_count": 0, "skipped_count": 0},
}), 500
run.status = "success" if failed_count == 0 else ("failed" if success_count == 0 else "partial_failed")
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.finished_at = datetime.utcnow()
if run.started_at and run.finished_at:
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
db.session.commit()
return jsonify({
"summary": {
"total_count": total_count,
"success_count": success_count,
"failed_count": failed_count,
"skipped_count": skipped_count,
},
"details": details,
"errors": errors,
"step_logs": step_logs,
})
+376 -14
View File
@@ -7,14 +7,365 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from app.decorators import require_admin
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.auth_jwt import get_current_user
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no
from app.services.schedule.scheduler_service import (
create_task,
run_task_now,
update_task,
_generate_run_no,
_generate_test_run_no,
_notify_schedule_run_wecom,
)
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
from app.services.schedule.srm_service import _fetch_records
schedule_admin_bp = Blueprint('schedule_admin', __name__)
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
return {
"row_id_key": cfg_model.row_id_key or "id",
"log_prefix": cfg_model.log_prefix or "",
"base_fetch_sql": cfg_model.base_fetch_sql or "",
"fetch_where_conditions": cfg_model.fetch_where_conditions or "",
"fetch_order_by": cfg_model.fetch_order_by or "",
"writeback_sql": cfg_model.writeback_sql or "",
"detail_sql": cfg_model.detail_sql or "",
"alias_order": cfg_model.alias_order or [],
"detail_alias_order": cfg_model.detail_alias_order or [],
"header_labels": cfg_model.header_labels or {},
"data_source": {
"db_type": cfg_model.ds_db_type or "sqlserver",
"host": cfg_model.ds_host or "",
"port": cfg_model.ds_port or "",
"database": cfg_model.ds_database or "",
"username": cfg_model.ds_username or "",
"password": cfg_model.ds_password or "",
"driver": cfg_model.ds_driver or "",
"encrypt": cfg_model.ds_encrypt or "",
"trust_cert": cfg_model.ds_trust_cert or "",
},
"external_api": {
"url": cfg_model.api_url or "",
"method": cfg_model.api_method or "POST",
"headers": cfg_model.api_headers or {},
"body_template": cfg_model.api_body_template or "",
},
}
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
@require_admin
def get_schedule_task_config(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if not cfg_model:
return jsonify({
"data_source_type": task.data_source_type,
"config": None,
})
return jsonify({
"data_source_type": task.data_source_type,
"config": _serialize_task_config(cfg_model),
})
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
@require_admin
def update_schedule_task_config(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
data = request.get_json(silent=True) or {}
try:
if "data_source_type" in data:
task.data_source_type = str(data["data_source_type"])
db.session.commit()
config_data = data.get("config", data)
cfg = upsert_schedule_task_config(task_id, config_data)
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
return jsonify({
"data_source_type": task.data_source_type,
"config": _serialize_task_config(cfg_model) if cfg_model else None,
})
except Exception as e:
db.session.rollback()
return jsonify({"error": str(e)}), 400
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
@require_admin
def test_schedule_sql(task_id: int):
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
return jsonify({"error": f"Config for task {task_id} not found"}), 404
data = request.get_json(silent=True) or {}
custom_where = str(data.get("fetch_where_conditions") or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get("fetch_order_by") or cfg.fetch_order_by).strip()
limit = min(int(data.get("limit") or 10), 100)
base = cfg.base_fetch_sql or cfg.fetch_sql
if cfg.base_fetch_sql:
sql = _build_fetch_sql(base, custom_where, custom_order_by)
else:
sql = base
try:
from app.services.schedule import _build_srm_conn_str
import decimal, datetime
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, sql)
def _safe(v):
if isinstance(v, decimal.Decimal):
return float(v)
if isinstance(v, (datetime.date, datetime.datetime)):
return v.isoformat()
if isinstance(v, datetime.timedelta):
return str(v)
return v
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
return jsonify({
"total": len(rows),
"showing": len(result_rows),
"limit": limit,
"sql": sql,
"columns": list(result_rows[0].keys()) if result_rows else [],
"rows": result_rows,
})
except Exception as e:
return jsonify({"error": str(e), "sql": sql}), 400
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
@require_admin
def test_schedule_run(task_id: int):
import time as _time
from app.services.schedule.excel_service import export_schedule_result_excel
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
return jsonify({"error": f"Config for task {task_id} not found"}), 404
data = request.get_json(silent=True) or {}
custom_where = str(data.get("fetch_where_conditions") or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get("fetch_order_by") or cfg.fetch_order_by).strip()
limit = min(int(data.get("limit") or 3), 10)
base = cfg.base_fetch_sql or cfg.fetch_sql
if cfg.base_fetch_sql:
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
else:
test_sql = base
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
from app.services.schedule.srm_service import (
_fetch_records,
_run_check_job_loop,
_build_record_text,
_execute_writeback,
)
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
agent = _resolve_dify_agent(task) if task else None
user = _resolve_schedule_user(task) if task else "test_user"
wait_seconds = task.wait_seconds if task else 120
dify_agent_id = task.dify_agent_id if task else None
run = ScheduleRun(
run_no=_generate_test_run_no(),
schedule_task_id=task_id,
trigger_type='test',
triggered_by_user_id=getattr(get_current_user(), 'id', None),
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
if not cfg.fetch_sql:
run.status = 'success'
run.finished_at = datetime.utcnow()
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc)
db.session.commit()
return jsonify({
"run_no": run.run_no,
"run_id": run.id,
"sql": "",
"limit": 0,
"total_count": 0,
"success_count": 0,
"failed_count": 0,
"skipped_count": 0,
"details": [],
"errors": [],
"step_logs": [{"step": "no_fetch_sql", "status": "skipped", "detail": "无抓取SQL,跳过外部系统数据抓取"}],
"dify_agent_id": dify_agent_id,
})
def _test_fetch_fn(conn_str_arg):
return _fetch_records(conn_str_arg, test_sql)
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
test_pre_dify = None
test_build_record = None
if cfg.detail_sql:
def _test_pre_dify(conn_str_arg, item, row_id_value):
try:
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
except Exception as detail_exc:
return {
"dify_result": "人工判定",
"dify_message": f"查询成分明细失败:{detail_exc}",
"writeback_srm": False,
"writeback_err": str(detail_exc),
}
detail_lines = []
for dr in detail_rows:
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
detail_lines.append(", ".join(parts))
item["detail_text"] = "; ".join(detail_lines) if detail_lines else ""
item["_detail_rows"] = detail_rows
return None
test_pre_dify = _test_pre_dify
def _test_build_with_detail(conn_str_arg, item, row_id_value):
detail_rows = item.get("_detail_rows", [])
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
return text, item.get("attachment")
test_build_record = _test_build_with_detail
else:
def _test_build_simple(conn_str_arg, item, row_id_value):
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
return text, item.get("attachment")
test_build_record = _test_build_simple
start_ts = _time.time()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
conn_str=conn_str,
run_no=run.run_no,
agent=agent,
user=user,
wait_seconds=wait_seconds,
run_id=run.id,
fetch_fn=_test_fetch_fn,
build_record_fn=test_build_record,
writeback_fn=_test_writeback_fn,
writeback_sql=cfg.writeback_sql,
row_id_key=cfg.row_id_key,
log_prefix=cfg.log_prefix,
fetch_sql=test_sql,
max_rows=limit,
pre_dify_fn=test_pre_dify,
)
duration_ms = int((_time.time() - start_ts) * 1000)
if total_count == 0 and not errors:
status = 'success'
elif failed_count == 0:
status = 'success'
elif success_count == 0:
status = 'failed'
else:
status = 'partial_failed'
header_order = cfg.alias_order if cfg.alias_order else None
header_labels = cfg.header_labels if cfg.header_labels else None
detail_alias_order = cfg.detail_alias_order or []
try:
file_data, file_name, file_size = export_schedule_result_excel(
run_no=run.run_no,
summary={"status": status, "total_count": total_count, "success_count": success_count, "failed_count": failed_count, "duration_ms": duration_ms},
details=details,
header_order=header_order,
header_labels=header_labels,
detail_alias_order=detail_alias_order,
)
except Exception:
file_data, file_name, file_size = None, None, 0
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = status
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc)
db.session.commit()
import decimal, datetime as dt
def _safe(v):
if isinstance(v, decimal.Decimal):
return float(v)
if isinstance(v, (dt.date, dt.datetime)):
return v.isoformat()
if isinstance(v, dt.timedelta):
return str(v)
return v
safe_details = []
for item in details:
safe_item = {k: _safe(v) for k, v in item.items()}
safe_details.append(safe_item)
return jsonify({
"run_no": run.run_no,
"run_id": run.id,
"sql": test_sql,
"limit": limit,
"total_count": total_count,
"success_count": success_count,
"failed_count": failed_count,
"skipped_count": skipped_count,
"details": safe_details,
"errors": errors,
"step_logs": step_logs,
"dify_agent_id": dify_agent_id,
})
except Exception as e:
duration_ms = int((_time.time() - start_ts) * 1000)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
run.status = 'failed'
run.error_message = str(e)
db.session.commit()
import traceback
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
@schedule_admin_bp.route('/schedules', methods=['GET'])
@require_admin
def get_schedules():
@@ -26,6 +377,7 @@ def get_schedules():
def post_schedule():
data = request.get_json(silent=True) or {}
user = get_current_user()
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type='platform_app',
@@ -39,6 +391,15 @@ def post_schedule():
enabled=bool(data.get('enabled', True)),
actor_id=getattr(user, 'id', None),
)
task.data_source_type = data_source_type
task.platform_api_path = f"/{task.id}"
db.session.commit()
db.session.refresh(task)
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task.id, config_data)
return jsonify(serialize_task(task)), 201
@@ -59,6 +420,15 @@ def patch_schedule(task_id: int):
return jsonify({'error': 'Not found'}), 404
data = request.get_json(silent=True) or {}
user = get_current_user()
if "data_source_type" in data:
task.data_source_type = str(data["data_source_type"])
db.session.commit()
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task_id, config_data)
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
return jsonify(serialize_task(task))
@@ -83,16 +453,6 @@ def delete_schedule(task_id: int):
if running_runs:
db.session.commit()
runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).all()
for r in runs:
if r.excel_file_path:
try:
from pathlib import Path
p = Path(r.excel_file_path)
if p.exists():
p.unlink()
except Exception:
pass
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
db.session.delete(task)
db.session.commit()
@@ -218,9 +578,11 @@ def get_schedule_run(run_id: int):
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
@require_admin
def get_schedule_run_excel(run_id: int):
from io import BytesIO
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
if not run.excel_file_path:
if not run.excel_file_data:
return jsonify({'error': 'Excel not found'}), 404
return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx')
buf = BytesIO(run.excel_file_data)
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
+58
View File
@@ -1566,6 +1566,64 @@ def wecom_task_complete():
return jsonify(result), 200 if result.get('ok') else 202
@user_bp.route('/leave-balance', methods=['GET'])
def get_leave_balance():
user = _get_current_user()
if not user:
return jsonify({'error': 'Unauthorized'}), 401
leave_type_code = _clean_str(request.args.get('leave_type'))
if leave_type_code not in ('010', '408'):
return jsonify({'error': '仅支持查询年假(010)和育儿假(408)的余额'}), 400
try:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
employee_code = HRLeaveSQLServerService._get_employee_code(user)
now_year = datetime.now().year
if leave_type_code == '010':
_, record = HRLeaveSQLServerService._query_one(
view_name="VIEW_D044",
year_column="D044001",
total_column="D044005",
used_column="D044006",
remaining_column="D044007",
employee_code=employee_code,
year=now_year,
)
label = '年假'
else:
_, record = HRLeaveSQLServerService._query_one(
view_name="VIEW_D072",
year_column="d072001",
total_column="d072002",
used_column="d072003",
remaining_column="d072004",
employee_code=employee_code,
year=now_year,
)
label = '育儿假'
remaining = record.get('remaining_hours') if record else None
try:
has_balance = remaining is not None and float(remaining) > 0
except (TypeError, ValueError):
has_balance = False
return jsonify({
'leave_type_code': leave_type_code,
'leave_type_label': label,
'year': record.get('leave_year', now_year) if record else now_year,
'total_hours': record.get('total_hours') if record else None,
'used_hours': record.get('used_hours') if record else None,
'remaining_hours': remaining,
'has_balance': has_balance,
})
except Exception as exc:
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
return jsonify({'error': f'假期余额查询失败:{exc}'}), 500
@user_bp.route('/leave-workflow/submit', methods=['POST'])
def submit_leave_workflow():
user = _get_current_user()
+4 -2
View File
@@ -54,6 +54,7 @@ def workspace_schedule_run_detail(run_id: int):
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
def workspace_schedule_run_excel(run_id: int):
from io import BytesIO
user, err = _require_user()
if err:
return err
@@ -62,6 +63,7 @@ def workspace_schedule_run_excel(run_id: int):
return jsonify({'error': 'Not found'}), 404
if not can_view_run(run, user.id):
return jsonify({'error': 'Forbidden'}), 403
if not run.excel_file_path:
if not run.excel_file_data:
return jsonify({'error': 'Excel not found'}), 404
return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx')
buf = BytesIO(run.excel_file_data)
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
+2 -6
View File
@@ -106,7 +106,7 @@ class Config:
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS')
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed')
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
@@ -152,11 +152,7 @@ class Config:
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
SMTP_FROM = os.getenv('SMTP_FROM', '')
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
SCHEDULE_EXCEL_STORAGE_ROOT = os.getenv(
'SCHEDULE_EXCEL_STORAGE_ROOT',
str(_BACKEND_DIR / 'data' / 'schedules'),
)
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:8880')
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
class DevelopmentConfig(Config):
+50 -5
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
@@ -562,6 +562,7 @@ class ScheduleTask(Base):
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
@@ -574,6 +575,49 @@ class ScheduleTask(Base):
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
class ScheduleTaskConfig(Base):
__tablename__ = 'schedule_task_configs'
__table_args__ = (
UniqueConstraint('schedule_task_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
log_prefix: Mapped[str] = mapped_column(String(128), default='')
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
api_method: Mapped[str] = mapped_column(String(16), default='POST')
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config")
class ScheduleRun(Base):
@@ -599,13 +643,14 @@ class ScheduleRun(Base):
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
error_message: Mapped[Optional[str]] = mapped_column(Text)
excel_file_path: Mapped[Optional[str]] = mapped_column(Text)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
mail_sent: Mapped[bool] = mapped_column(Boolean, default=False)
mail_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
mail_error: Mapped[Optional[str]] = mapped_column(Text)
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
+137 -97
View File
@@ -23,6 +23,7 @@ chat.py (/api/chat/completions)
-> yield SSE events to frontend
"""
import json
import os
import time
import uuid
from typing import Any, List, Optional
@@ -37,6 +38,7 @@ from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
@staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
@@ -290,7 +292,7 @@ class DifyService:
return {}
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller.
@@ -329,7 +331,8 @@ class DifyService:
if current_app:
current_app.logger.info(
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
"[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
request_id,
user_id,
getattr(agent, 'id', None),
base_url,
@@ -338,117 +341,154 @@ class DifyService:
)
start_time = time.time()
first_token_at: float | None = None
message_count = 0
event_count = 0
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response status=%s reason=%s",
response.status_code,
response.reason,
)
if not response.ok and current_app:
try:
error_body = response.text[:2000]
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s payload=%s body=%s",
response.status_code,
url,
json.dumps(payload, ensure_ascii=False),
error_body,
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded_line = line.decode('utf-8')
if not decoded_line.startswith('data: '):
continue
raw_json = decoded_line[6:]
try:
data = json.loads(raw_json)
except json.JSONDecodeError:
continue
event = data.get('event')
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
data.get('conversation_id') or normalized_conversation_id,
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
request_id,
response.status_code,
response.reason,
attempt,
)
if not response.ok and current_app:
retryable = response.status_code in (404, 502, 503, 504)
try:
error_body = response.text[:2000]
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
request_id,
response.status_code,
url,
attempt,
error_body,
)
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
response.raise_for_status()
if event == 'message':
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
for line in response.iter_lines():
if not line:
continue
elif event in ('message_end', 'agent_message', 'workflow_finished'):
# Keep metadata from non-message events, but avoid appending
# intermediate workflow/agent outputs into final user answer.
if event == 'message_end' and data.get('answer'):
decoded_line = line.decode('utf-8')
if not decoded_line.startswith('data: '):
continue
raw_json = decoded_line[6:]
try:
data = json.loads(raw_json)
except json.JSONDecodeError:
continue
event = data.get('event')
event_count += 1
# Keep stream event logs behind an explicit switch to prevent
# flooding when global logger level is DEBUG.
if DifyService.VERBOSE_STREAM_LOG and current_app:
current_app.logger.debug(
"[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s",
request_id,
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
message_count += 1
if first_token_at is None:
first_token_at = time.time()
if current_app:
current_app.logger.info(
"[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s",
request_id,
int((first_token_at - start_time) * 1000),
attempt,
)
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
if current_app:
current_app.logger.info(
"[source-link] message_end: collected retriever resources=%s",
len(retriever_resources),
)
# Resolve original source file URLs from external integration API.
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end request_id=%s collected retriever_resources=%s",
request_id,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
enrich_done_at = time.time()
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
if current_app:
current_app.logger.info(
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
data.get('conversation_id') or normalized_conversation_id,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
latency,
)
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
# Pass-through SSE event (after optional enrichment).
# SSE frame delimiter must be real newlines, not literal "\n".
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
db_write_done_at = time.time()
if chat_log_id:
data['chat_log_id'] = chat_log_id
if current_app:
current_app.logger.info(
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
request_id,
latency,
int((first_token_at - start_time) * 1000) if first_token_at else None,
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
int((time.time() - message_end_started) * 1000),
int((enrich_done_at - message_end_started) * 1000),
int((db_write_done_at - db_write_started) * 1000),
event_count,
message_count,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
data.get('conversation_id') or normalized_conversation_id,
)
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception: %s", e)
error_msg = json.dumps({'event': 'error', 'message': str(e)})
yield f"data: {error_msg}\n\n"
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries:
time.sleep(attempt * 2)
continue
error_msg = json.dumps({'event': 'error', 'message': str(e)})
yield f"data: {error_msg}\n\n"
@staticmethod
def _log_chat(
+259 -74
View File
@@ -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
+96 -25
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
import io
import json
from pathlib import Path
from typing import Any
from openpyxl import Workbook
@@ -13,40 +13,111 @@ def _flatten_value(v: Any) -> Any:
return v
def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]:
_EXPORT_SKIP_KEYS = {"dify_output", "json_output", "output", "_detail_rows", "detail_text"}
def export_schedule_result_excel(
*,
run_no: str,
summary: dict,
details: list[dict],
header_order: list[str] | None = None,
header_labels: dict[str, str] | None = None,
detail_alias_order: list[str] | None = None,
) -> tuple[bytes | None, str | None, int]:
if not details:
return None, None, 0
out_root = Path(root_dir)
out_root.mkdir(parents=True, exist_ok=True)
header_order = header_order or []
header_labels = header_labels or {}
detail_alias_order = detail_alias_order or []
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
sql_headers: list[str] = []
detail_headers: list[str] = []
exec_result_headers: list[str] = []
def _append_unique(target: list[str], key: str) -> None:
if key not in target:
target.append(key)
for row in details:
if not isinstance(row, dict):
continue
for k in row.keys():
key = str(k)
if key in _EXPORT_SKIP_KEYS:
continue
if key in exec_result_order:
_append_unique(exec_result_headers, key)
else:
_append_unique(sql_headers, key)
detail_rows = row.get("_detail_rows")
if isinstance(detail_rows, list):
for dr in detail_rows:
if isinstance(dr, dict):
for dk in dr.keys():
_append_unique(detail_headers, str(dk))
ordered_sql_headers = [k for k in header_order if k in sql_headers]
other_sql_headers = [k for k in sql_headers if k not in header_order]
ordered_detail_headers = [k for k in detail_alias_order if k in detail_headers]
other_detail_headers = [k for k in detail_headers if k not in detail_alias_order]
ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers]
other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order]
all_detail_headers = ordered_detail_headers + other_detail_headers
headers = (
ordered_sql_headers
+ other_sql_headers
+ all_detail_headers
+ ordered_exec_headers
+ other_exec_headers
)
if not headers:
return None, None, 0
rows: list[dict[str, Any]] = []
for row in details:
output = row.get('dify_output')
if not isinstance(output, dict):
output = {}
entry = {k: _flatten_value(v) for k, v in output.items()}
for k in ('writeback_ok', 'error', 'judgement', 'reason'):
if k in row:
entry[k] = row[k]
rows.append(entry)
if not isinstance(row, dict):
continue
headers: list[str] = []
for row in rows:
for k in row:
if k not in headers:
headers.append(k)
base_row: dict[str, Any] = {}
for k, v in row.items():
key = str(k)
if key in _EXPORT_SKIP_KEYS:
continue
if key in {"dify_output", "json_output", "output"}:
if isinstance(v, dict):
for json_key, json_val in v.items():
base_row[str(json_key)] = _flatten_value(json_val)
continue
base_row[key] = _flatten_value(v)
detail_rows = row.get("_detail_rows")
if all_detail_headers and isinstance(detail_rows, list) and detail_rows:
for dr in detail_rows:
flat = dict(base_row)
if isinstance(dr, dict):
for dk in all_detail_headers:
flat[dk] = dr.get(dk, "")
rows.append(flat)
else:
rows.append(base_row)
wb = Workbook()
ws = wb.active
ws.title = 'result'
ws.append(headers)
ws.title = "result"
ws.append([header_labels.get(k, k) for k in headers])
for row in rows:
ws.append([row.get(k, '') for k in headers])
ws.append([row.get(k, "") for k in headers])
file_name = f'schedule_{run_no}.xlsx'
file_path = out_root / file_name
wb.save(file_path)
size = file_path.stat().st_size
return str(file_path), file_name, int(size)
buf = io.BytesIO()
wb.save(buf)
file_data = buf.getvalue()
file_name = f"schedule_{run_no}.xlsx"
return file_data, file_name, len(file_data)
@@ -1,37 +0,0 @@
from __future__ import annotations
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_schedule_mail(*, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_tls: bool, from_addr: str, to_addrs: list[str], subject: str, html_body: str) -> None:
if not to_addrs:
return
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = ', '.join(to_addrs)
msg.attach(MIMEText(html_body, 'html', 'utf-8'))
with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server:
if use_tls:
server.starttls()
if smtp_user:
server.login(smtp_user, smtp_password)
server.sendmail(from_addr, to_addrs, msg.as_string())
def build_schedule_mail_html(*, schedule_name: str, run_no: str, status: str, total: int, success: int, failed: int) -> str:
return (
"<html><body>"
"<h3>排程执行结果</h3>"
"<table border='1' cellspacing='0' cellpadding='6'>"
f"<tr><th>排程</th><td>{schedule_name}</td></tr>"
f"<tr><th>执行单号</th><td>{run_no}</td></tr>"
f"<tr><th>状态</th><td>{status}</td></tr>"
f"<tr><th>总数</th><td>{total}</td></tr>"
f"<tr><th>成功</th><td>{success}</td></tr>"
f"<tr><th>失败</th><td>{failed}</td></tr>"
"</table></body></html>"
)
@@ -52,12 +52,13 @@ def serialize_run(run: ScheduleRun) -> dict:
'api_request_json': run.api_request_json,
'api_response_json': run.api_response_json,
'response_summary_json': run.response_summary_json,
'step_logs': run.step_logs,
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'mail_sent': bool(run.mail_sent),
'mail_sent_at': run.mail_sent_at.isoformat() if run.mail_sent_at else None,
'mail_error': run.mail_error,
'wecom_notified': bool(run.wecom_notified),
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
'wecom_notify_error': run.wecom_notify_error,
'created_at': run.created_at.isoformat() if run.created_at else None,
}
@@ -11,9 +11,9 @@ from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
_worker_started = False
_worker_lock = threading.Lock()
@@ -44,6 +44,115 @@ def _generate_run_no() -> str:
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
def _generate_test_run_no() -> str:
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
_WECOM_STATUS_LABEL = {
'success': '成功',
'failed': '失败',
'partial_failed': '部分失败',
}
_WECOM_EVENT_TYPE = 'schedule_completed'
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
from app.services.wecom_notify import (
upload_wecom_temp_media,
send_wecom_file_message,
send_wecom_textcard_message,
_create_audit,
_build_jump_url,
_get_enabled_events,
)
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
if _WECOM_EVENT_TYPE not in _get_enabled_events():
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
return
user_ids = task.notify_user_ids_json or []
if not user_ids:
return
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
wecom_users = [u for u in users if u.wecom_userid]
if not wecom_users:
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
return
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
title = f'排程执行结果: {task.name}'
description = (
f'执行单号: {run.run_no}\n'
f'状态: {status_label}\n'
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
)
media_id = None
if run.excel_file_data and run.excel_file_name:
try:
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
except Exception as exc:
current_app.logger.warning(
'[wecom-schedule] media upload failed for run %s: %s',
run.run_no, exc,
)
textcard_ok_count = 0
errors = []
for u in wecom_users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
textcard_ok_count += 1
else:
audit.error_code = str(data.get('errcode'))
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
if media_id:
try:
file_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_file', u,
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
)
file_data = send_wecom_file_message(u.wecom_userid, media_id)
if file_data.get('errcode') == 0:
file_audit.status = 'sent'
else:
file_audit.error_code = str(file_data.get('errcode'))
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: file exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
else:
run.wecom_notified = False
if errors:
run.wecom_notify_error = '; '.join(errors[:5])
db.session.flush()
def create_task(
*,
name: str,
@@ -58,9 +167,6 @@ def create_task(
enabled: bool,
actor_id: int | None,
) -> ScheduleTask:
if not normalize_platform_api_path(platform_api_path):
raise ValueError("platform_api_path is required for platform_app")
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
@@ -151,11 +257,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
db.session.commit()
start_ts = time.time()
step_logs: list = []
try:
executor = resolve_schedule_executor(task)
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
except Exception as exc:
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
try:
db.session.refresh(run)
except Exception:
pass
if is_run_cancelled(run.id):
run.finished_at = datetime.utcnow()
@@ -183,7 +296,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
status = "partial_failed"
try:
file_path, file_name, file_size = export_schedule_result_excel(
cfg = get_schedule_sql_config_by_task_id(task.id)
if cfg and cfg.alias_order and cfg.header_labels:
header_order, header_labels = cfg.alias_order, cfg.header_labels
else:
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
detail_alias_order = (cfg.detail_alias_order if cfg else None) or []
file_data, file_name, file_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
"status": status,
@@ -193,12 +312,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
"duration_ms": duration_ms,
},
details=details,
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
header_order=header_order,
header_labels=header_labels,
detail_alias_order=detail_alias_order,
)
except Exception as excel_exc:
if current_app:
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
file_path, file_name, file_size = None, None, 0
file_data, file_name, file_size = None, None, 0
errors.append(f"Excel导出失败: {excel_exc}")
run.finished_at = datetime.utcnow()
@@ -208,48 +329,23 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
run.success_count = success_count
run.failed_count = failed_count
run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None
run.response_summary_json = {
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
}
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_path = file_path
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
try:
if task.notify_enabled:
users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all()
to_addrs = [u.email for u in users if u.email]
if to_addrs:
try:
send_schedule_mail(
smtp_host=str(current_app.config.get("SMTP_HOST") or ""),
smtp_port=int(current_app.config.get("SMTP_PORT") or 25),
smtp_user=str(current_app.config.get("SMTP_USER") or ""),
smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""),
use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)),
from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"),
to_addrs=to_addrs,
subject=f"排程执行结果 {task.name} {run.run_no}",
html_body=build_schedule_mail_html(
schedule_name=task.name,
run_no=run.run_no,
status=status,
total=total_count,
success=success_count,
failed=failed_count,
),
)
run.mail_sent = True
run.mail_sent_at = datetime.utcnow()
except Exception as mail_exc:
run.mail_sent = False
run.mail_error = str(mail_exc)
except Exception as mail_exc:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
if current_app:
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
task.last_run_at = datetime.utcnow()
db.session.commit()
+239
View File
@@ -0,0 +1,239 @@
from __future__ import annotations
import os
import re
from dataclasses import dataclass, field
from typing import Any
_ENV_VAR_PATTERN = re.compile(r"\$\{(\w+)\}")
def resolve_env_value(val: str) -> str:
if not val or "${" not in val:
return val
def _replacer(match: re.Match) -> str:
env_key = match.group(1)
return os.environ.get(env_key, match.group(0))
return _ENV_VAR_PATTERN.sub(_replacer, val)
@dataclass(frozen=True)
class DataSourceConfig:
db_type: str = "sqlserver"
host: str = ""
port: str = ""
database: str = ""
username: str = ""
password: str = ""
driver: str = ""
encrypt: str = ""
trust_cert: str = ""
def is_empty(self) -> bool:
return not self.host.strip()
def build_connection_string(self) -> str:
host = resolve_env_value(self.host)
port = resolve_env_value(self.port)
database = resolve_env_value(self.database)
username = resolve_env_value(self.username)
password = resolve_env_value(self.password)
if not port:
if self.db_type == "sqlserver":
port = "1433"
elif self.db_type == "postgresql":
port = "5432"
elif self.db_type == "mysql":
port = "3306"
if self.db_type == "sqlserver":
driver = resolve_env_value(self.driver) or "SQL Server"
encrypt = resolve_env_value(self.encrypt) or "no"
trust_cert = resolve_env_value(self.trust_cert) or "yes"
return (
f"DRIVER={{{driver}}};"
f"SERVER={host},{port};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
elif self.db_type == "postgresql":
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
elif self.db_type == "mysql":
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
raise ValueError(f"Unsupported db_type: {self.db_type}")
@dataclass(frozen=True)
class ExternalApiConfig:
url: str = ""
method: str = "POST"
headers: dict[str, str] = field(default_factory=dict)
body_template: str = ""
@dataclass(frozen=True)
class ScheduleSqlConfig:
description: str = ""
row_id_key: str = "id"
log_prefix: str = ""
fetch_sql: str = ""
base_fetch_sql: str = ""
fetch_where_conditions: str = ""
fetch_order_by: str = ""
writeback_sql: str = ""
detail_sql: str = ""
alias_order: list[str] = field(default_factory=list)
detail_alias_order: list[str] = field(default_factory=list)
header_labels: dict[str, str] = field(default_factory=dict)
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
data_source_type: str = "database"
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
parts = [base.strip().rstrip(";").strip()]
if where_conds.strip():
parts.append("where")
parts.append(where_conds.strip())
if order_by.strip():
parts.append(order_by.strip())
return "\n".join(parts)
def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
from app import db
from app.models import ScheduleTask
task_id = cfg_model.schedule_task_id
task = db.session.get(ScheduleTask, task_id)
base = str(cfg_model.base_fetch_sql or "")
where_conds = str(cfg_model.fetch_where_conditions or "")
order_by = str(cfg_model.fetch_order_by or "")
fetch_sql = _build_fetch_sql(base, where_conds, order_by) if base else ""
ds = DataSourceConfig(
db_type=str(cfg_model.ds_db_type or "sqlserver"),
host=str(cfg_model.ds_host or ""),
port=str(cfg_model.ds_port or ""),
database=str(cfg_model.ds_database or ""),
username=str(cfg_model.ds_username or ""),
password=str(cfg_model.ds_password or ""),
driver=str(cfg_model.ds_driver or ""),
encrypt=str(cfg_model.ds_encrypt or ""),
trust_cert=str(cfg_model.ds_trust_cert or ""),
)
ext = ExternalApiConfig(
url=str(cfg_model.api_url or ""),
method=str(cfg_model.api_method or "POST"),
headers=dict(cfg_model.api_headers or {}),
body_template=str(cfg_model.api_body_template or ""),
)
return ScheduleSqlConfig(
description=str(task.name if task else ""),
row_id_key=str(cfg_model.row_id_key or "id"),
log_prefix=str(cfg_model.log_prefix or ""),
fetch_sql=fetch_sql,
base_fetch_sql=base,
fetch_where_conditions=where_conds,
fetch_order_by=order_by,
writeback_sql=str(cfg_model.writeback_sql or ""),
detail_sql=str(cfg_model.detail_sql or ""),
alias_order=list(cfg_model.alias_order or []),
detail_alias_order=list(cfg_model.detail_alias_order or []),
header_labels=dict(cfg_model.header_labels or {}),
data_source=ds,
external_api=ext,
data_source_type=str(task.data_source_type if task else "database"),
)
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
key = name.strip().lower()
task = None
if key.isdigit():
task = db.session.get(ScheduleTask, int(key))
if not task:
task = ScheduleTask.query.filter(
ScheduleTask.platform_api_path.ilike(f"%{key}%")
).first()
if not task:
return None
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if not cfg_model:
return None
return _config_from_model(cfg_model)
def get_schedule_sql_config_by_task_id(task_id: int) -> ScheduleSqlConfig | None:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if not cfg_model:
return None
return _config_from_model(cfg_model)
def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
from app.models import ScheduleTask, ScheduleTaskConfig
results: dict[str, ScheduleSqlConfig] = {}
configs = ScheduleTaskConfig.query.all()
for cfg_model in configs:
key = str(cfg_model.schedule_task_id)
results[key] = _config_from_model(cfg_model)
return results
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if not cfg_model:
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
db.session.add(cfg_model)
for k, v in data.items():
if k == "data_source" and isinstance(v, dict):
cfg_model.ds_db_type = str(v.get("db_type", "sqlserver"))
cfg_model.ds_host = str(v.get("host", ""))
cfg_model.ds_port = str(v.get("port", ""))
cfg_model.ds_database = str(v.get("database", ""))
cfg_model.ds_username = str(v.get("username", ""))
cfg_model.ds_password = str(v.get("password", ""))
cfg_model.ds_driver = str(v.get("driver", "")) if v.get("driver") else None
cfg_model.ds_encrypt = str(v.get("encrypt", "")) if v.get("encrypt") else None
cfg_model.ds_trust_cert = str(v.get("trust_cert", "")) if v.get("trust_cert") else None
elif k == "external_api" and isinstance(v, dict):
cfg_model.api_url = str(v.get("url", ""))
cfg_model.api_method = str(v.get("method", "POST"))
cfg_model.api_headers = dict(v.get("headers", {}))
cfg_model.api_body_template = str(v.get("body_template", ""))
elif k in ("row_id_key", "log_prefix"):
setattr(cfg_model, k, str(v) if v is not None else "")
elif k in ("base_fetch_sql", "fetch_where_conditions", "fetch_order_by",
"writeback_sql", "detail_sql"):
setattr(cfg_model, k, str(v) if v is not None else None)
elif k in ("alias_order", "detail_alias_order"):
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
elif k == "header_labels":
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
db.session.commit()
db.session.refresh(cfg_model)
return _config_from_model(cfg_model)
+265 -103
View File
@@ -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
+82 -26
View File
@@ -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}
@@ -0,0 +1,62 @@
"""add_schedule_task_config_and_data_source_type
Revision ID: 9f3438dc97ca
Revises: a1b2c3d4e5f6
Create Date: 2026-05-20 13:42:57.822050
"""
from alembic import op
import sqlalchemy as sa
revision = '9f3438dc97ca'
down_revision = 'a1b2c3d4e5f6'
branch_labels = None
depends_on = None
def upgrade():
op.create_table('schedule_task_configs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('schedule_task_id', sa.Integer(), nullable=False),
sa.Column('row_id_key', sa.String(length=64), nullable=False),
sa.Column('log_prefix', sa.String(length=128), nullable=False),
sa.Column('base_fetch_sql', sa.Text(), nullable=True),
sa.Column('fetch_where_conditions', sa.Text(), nullable=True),
sa.Column('fetch_order_by', sa.String(length=500), nullable=True),
sa.Column('writeback_sql', sa.Text(), nullable=True),
sa.Column('detail_sql', sa.Text(), nullable=True),
sa.Column('alias_order', sa.JSON(), nullable=True),
sa.Column('detail_alias_order', sa.JSON(), nullable=True),
sa.Column('header_labels', sa.JSON(), nullable=True),
sa.Column('ds_db_type', sa.String(length=32), nullable=False),
sa.Column('ds_host', sa.String(length=255), nullable=True),
sa.Column('ds_port', sa.String(length=64), nullable=True),
sa.Column('ds_database', sa.String(length=128), nullable=True),
sa.Column('ds_username', sa.String(length=128), nullable=True),
sa.Column('ds_password', sa.String(length=255), nullable=True),
sa.Column('api_url', sa.String(length=500), nullable=True),
sa.Column('api_method', sa.String(length=16), nullable=False),
sa.Column('api_headers', sa.JSON(), nullable=True),
sa.Column('api_body_template', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['schedule_task_id'], ['schedule_tasks.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('schedule_task_id')
)
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_schedule_task_configs_schedule_task_id'), ['schedule_task_id'], unique=False)
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.add_column(sa.Column('data_source_type', sa.String(length=32), nullable=False, server_default='database'))
def downgrade():
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.drop_column('data_source_type')
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_schedule_task_configs_schedule_task_id'))
op.drop_table('schedule_task_configs')
@@ -0,0 +1,23 @@
"""add step_logs to schedule_runs
Revision ID: a1b2c3d4e5f6
Revises: c0ae052bd24e
Create Date: 2026-05-19 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'a1b2c3d4e5f6'
down_revision = 'c0ae052bd24e'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_runs', sa.Column('step_logs', sa.JSON(), nullable=True))
def downgrade():
op.drop_column('schedule_runs', 'step_logs')
@@ -0,0 +1,26 @@
"""store excel in database instead of local filesystem
Revision ID: a9b0c1d2e3f4
Revises: f8b9c0d1e2f3
Create Date: 2026-05-20 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'a9b0c1d2e3f4'
down_revision = ('b7a1c2d3e4f5', 'f8b9c0d1e2f3')
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
batch_op.add_column(sa.Column('excel_file_data', sa.LargeBinary(), nullable=True))
batch_op.drop_column('excel_file_path')
def downgrade() -> None:
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
batch_op.add_column(sa.Column('excel_file_path', sa.Text(), nullable=True))
batch_op.drop_column('excel_file_data')
@@ -0,0 +1,27 @@
"""add ds_driver encrypt trust_cert
Revision ID: b7a1c2d3e4f5
Revises: 9f3438dc97ca
Create Date: 2026-05-20 18:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'b7a1c2d3e4f5'
down_revision = '9f3438dc97ca'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_task_configs', sa.Column('ds_driver', sa.String(length=128), nullable=True))
op.add_column('schedule_task_configs', sa.Column('ds_encrypt', sa.String(length=16), nullable=True))
op.add_column('schedule_task_configs', sa.Column('ds_trust_cert', sa.String(length=16), nullable=True))
def downgrade():
op.drop_column('schedule_task_configs', 'ds_trust_cert')
op.drop_column('schedule_task_configs', 'ds_encrypt')
op.drop_column('schedule_task_configs', 'ds_driver')
@@ -0,0 +1,32 @@
"""replace mail notify fields with wecom notify fields
Revision ID: c1d2e3f4a5b6
Revises: a9b0c1d2e3f4
Create Date: 2026-05-20 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'c1d2e3f4a5b6'
down_revision = 'a9b0c1d2e3f4'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_runs', sa.Column('wecom_notified', sa.Boolean(), nullable=True, server_default=sa.text('false')))
op.add_column('schedule_runs', sa.Column('wecom_notified_at', sa.DateTime(), nullable=True))
op.add_column('schedule_runs', sa.Column('wecom_notify_error', sa.Text(), nullable=True))
op.drop_column('schedule_runs', 'mail_sent')
op.drop_column('schedule_runs', 'mail_sent_at')
op.drop_column('schedule_runs', 'mail_error')
def downgrade():
op.add_column('schedule_runs', sa.Column('mail_error', sa.Text(), nullable=True))
op.add_column('schedule_runs', sa.Column('mail_sent_at', sa.DateTime(), nullable=True))
op.add_column('schedule_runs', sa.Column('mail_sent', sa.Boolean(), nullable=True, server_default=sa.text('false')))
op.drop_column('schedule_runs', 'wecom_notify_error')
op.drop_column('schedule_runs', 'wecom_notified_at')
op.drop_column('schedule_runs', 'wecom_notified')
@@ -0,0 +1,71 @@
"""ensure agents table has primary key on id
Revision ID: f7a8b9c0d1e2
Revises: f6d4e5f6a7b8
Create Date: 2026-05-20 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'f7a8b9c0d1e2'
down_revision = 'f6d4e5f6a7b8'
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'agents' not in inspector.get_table_names():
return
pk = inspector.get_pk_constraint('agents') or {}
constrained_columns = pk.get('constrained_columns') or []
if constrained_columns:
return
duplicate_count = conn.execute(
sa.text(
"""
SELECT COUNT(*)
FROM (
SELECT id
FROM agents
GROUP BY id
HAVING COUNT(*) > 1
) t
"""
)
).scalar_one()
if duplicate_count > 0:
raise RuntimeError(
"Cannot add PRIMARY KEY to agents.id because duplicate id values exist. "
"Please deduplicate agents.id first, then rerun migration."
)
null_count = conn.execute(
sa.text("SELECT COUNT(*) FROM agents WHERE id IS NULL")
).scalar_one()
if null_count > 0:
raise RuntimeError(
"Cannot add PRIMARY KEY to agents.id because NULL id values exist. "
"Please fix NULL ids first, then rerun migration."
)
op.execute('ALTER TABLE agents ADD CONSTRAINT agents_pkey PRIMARY KEY (id)')
def downgrade():
conn = op.get_bind()
inspector = sa.inspect(conn)
if 'agents' not in inspector.get_table_names():
return
pk = inspector.get_pk_constraint('agents') or {}
pk_name = pk.get('name')
cols = pk.get('constrained_columns') or []
if pk_name == 'agents_pkey' and cols == ['id']:
op.drop_constraint('agents_pkey', 'agents', type_='primary')
@@ -0,0 +1,21 @@
"""merge heads after agents pk fix
Revision ID: f8b9c0d1e2f3
Revises: c0ae052bd24e, f7a8b9c0d1e2
Create Date: 2026-05-20 00:30:00.000000
"""
revision = 'f8b9c0d1e2f3'
down_revision = ('c0ae052bd24e', 'f7a8b9c0d1e2')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
+1
View File
@@ -34,3 +34,4 @@ beautifulsoup4==4.14.2
lxml==6.0.2
typer==0.17.4
croniter
pyyaml
+1 -1
View File
@@ -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()
+70
View File
@@ -266,3 +266,73 @@
1. 打通 OA userID 查询
2. 打通 workflow=652 请假单提交
3. 打通请假单状态轮询与企微通知
---
## 14. 移动端适配需求
### 14.1 项目背景
当前系统前端布局仅针对 PC 端设计,未做移动端响应式适配。员工使用手机浏览器访问时,侧边栏、导航区域等 PC 端专属布局会占用大量屏幕空间,导致核心内容区域过窄,操作体验差。需要增加移动端自动识别与适配能力。
### 14.2 需求目标
1. 系统自动检测屏幕方向,当屏幕高度大于宽度时识别为手机端并自动适配
2. 手机端未登录时仍先进入登录页面
3. 登录后默认进入通用入口 Chat 页面
4. PC 端左侧导航区域在移动端上不显示
5. 移动端右上角增加一个按钮图标
6. 点击右上角按钮进入个人管理设置页面
### 14.3 详细需求
#### MR-01 移动端自动识别
- 系统需根据 `window.innerHeight > window.innerWidth` 判定为手机竖屏状态
- 识别需实时响应屏幕方向变化(旋转屏幕时自动切换布局模式)
- 不依赖 User-Agent 判断,纯粹依据屏幕方向
#### MR-02 登录流程保留
- 手机端未登录时,仍进入现有的登录页面(WorkspaceView 登录表单)
- 登录页面在手机端需保持正常可用,登录表单居中显示
- 登录成功后自动跳转至 `/chat/{默认AgentID}` 页面
#### MR-03 登录后默认进入 Chat 页面
- 已登录用户访问根路径 `/` 时,自动重定向到 `/chat/16`(通用入口 Chat 页面)
- 未登录用户访问根路径 `/` 时,重定向到 `/workspace`(登录页)
- 受保护页面(如 `/chat/*`、`/profile`)未登录时重定向到登录页
#### MR-04 PC 端左侧导航移动端隐藏
- ChatView 的侧边栏(聊天记录、智能体列表等)在移动端完全隐藏
- WorkspaceView 的左侧导航栏(个人中心、应用管理等)在移动端完全隐藏
- 不再使用抽屉式或折叠式,直接不渲染侧边栏 DOM
#### MR-05 移动端顶部栏与右上角按钮
- ChatView 在移动端显示紧凑顶部栏,包含 AI 图标+Agent 名称,右侧显示个人设置图标按钮
- WorkspaceView 在移动端显示紧凑顶部栏,包含 AI 图标+「和信AI」标题,右侧显示个人设置图标按钮
- 使用 `UserCircle` 图标作为右上角按钮
#### MR-06 点击右上角进入个人设置页面
- 点击移动端右上角图标按钮后,路由跳转至 `/profile`(ProfileView 个人设置页面)
- ProfileView 返回按钮在移动端返回 Chat 页面,PC 端返回 Workspace 页面
### 14.4 非功能需求
- 移动端适配不能影响 PC 端现有布局和行为
- 屏幕方向变化需实时响应,无需刷新页面
- 移动端登录表单需保持可用性和可读性
### 14.5 验收标准
1. 手机竖屏访问时自动进入适配布局
2. 未登录时正确显示登录页
3. 登录后默认跳转到 Chat 页面
4. 移动端不显示 PC 端左侧导航/侧边栏
5. 移动端右上角可见个人设置图标按钮
6. 点击右上角按钮可进入个人设置页面
7. PC 端布局与行为无任何变化
@@ -349,3 +349,31 @@
- 能收到企微通知
- 流程类问题仍走知识库
- 所有操作都有日志可追踪
---
## 7. 移动端适配功能清单
### 7.1 功能总览
| 功能项 | 说明 | 状态 | 优先级 |
| --- | --- | --- | --- |
| 移动端自动识别 | 屏幕高度>宽度时判定为手机端,实时响应方向变化 | 已完成 | P0 |
| 手机端登录流程 | 未登录仍进入登录页,登录表单移动端可用 | 已完成 | P0 |
| 登录后默认进 Chat | 已登录访问根路径自动跳转 `/chat/16` | 已完成 | P0 |
| 受保护页面认证守卫 | 未登录访问受保护页面重定向到登录页 | 已完成 | P0 |
| PC 侧边栏移动端隐藏 | ChatView/WorkspaceView 侧边栏在手机端不渲染 | 已完成 | P0 |
| 移动端顶部栏 | 紧凑 header 显示 AI 图标+标题 | 已完成 | P0 |
| 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 |
| ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 |
### 7.2 验收清单
- 手机竖屏访问时自动进入适配布局
- 未登录时正确显示登录页
- 登录后默认跳转到 Chat 页面
- 移动端不显示 PC 端左侧导航/侧边栏
- 移动端右上角可见个人设置图标按钮
- 点击右上角按钮可进入个人设置页面
- PC 端布局与行为无任何变化
- 旋转屏幕后布局实时切换
+82 -2
View File
@@ -646,8 +646,88 @@ OA_STATUS_SYNC_BATCH_SIZE=100
该需求技术上完全可落地,最关键的实现路径是:
1. 聊天侧做意图路由
1.1. 聊天侧做意图路由
2. 数据侧打通 OA userID + WorkflowService + 状态查询
3. 平台侧补齐主记录表、状态日志表、轮询任务、通知模板
现有项目已经具备聊天路由、SQL Server 查询、企微通知、最小任务调度四个核心基础能力,因此本需求适合采用“增量扩展”的方式推进,而不需要重做一套独立系统。
现有项目已经具备聊天路由、SQL Server 查询、企微通知、最小任务调度四个核心基础能力,因此本需求适合采用"增量扩展"的方式推进,而不需要重做一套独立系统。
---
## 16. 移动端适配技术方案
### 16.1 设计目标
在现有 PC 端前端基础上,通过增量方式增加移动端自适应能力,不修改 PC 端的任何现有行为。
### 16.2 核心技术方案
#### 移动端识别:useIsMobile 组合函数
新增 `frontend/src/composables/useIsMobile.ts`,提供全局共享的移动端状态:
- **判定规则**:`window.innerHeight > window.innerWidth`(竖屏 = 手机)
- **实现方式**:全局单例 `ref` + `resize` 事件监听
- **声明周期管理**:引用计数自动挂载/卸载监听器,避免内存泄漏
- **实时响应**:旋转屏幕时自动切换布局模式
```typescript
// 核心逻辑
const isMobile = ref(false);
const update = () => { isMobile.value = window.innerHeight > window.innerWidth; };
```
#### 路由守卫改造
修改 `frontend/src/router/index.ts`,增加认证与默认跳转逻辑:
- 根路径 `/`:已登录 → `/chat/16`,未登录 → `/workspace`
- 受保护页面(`/chat/*`、`/profile`、`/admin`等):未登录重定向到 `/workspace`
- 公开路径白名单:`/`、`/workspace`、`/casdoor-callback`、`/reset-password`
#### ChatView 移动端适配
- 侧边栏 `aside` 添加 `v-if="!isMobile"`,移动端不渲染侧边栏 DOM
- 侧边栏遮罩层添加 `&& !isMobile` 条件
- 新增移动端顶部栏 `<header v-if="isMobile && currentAgent">`:
- 左侧:AI 图标 + Agent 名称
- 右侧:`UserCircle` 图标按钮,点击 `router.push('/profile')`
#### WorkspaceView 移动端适配
- 左侧导航 `aside` 添加 `v-if="!isMobile"`,移动端不渲染
- 新增移动端顶部栏 `<header v-if="isMobile">`:
- 左侧:AI 图标 + 「和信AI」标题
- 右侧:`User` 图标按钮,点击 `router.push('/profile')`
- 外层 `div` 包裹 grid 布局,移动端时 grid 列数为 1
#### ProfileView 移动端适配
- 引入 `useIsMobile`
- 返回按钮:手机端 → `/chat/16`,PC 端 → `/workspace`
### 16.3 新增/修改文件清单
| 文件 | 变更类型 | 说明 |
| --- | --- | --- |
| `frontend/src/composables/useIsMobile.ts` | 新增 | 移动端识别组合函数 |
| `frontend/src/views/ChatView.vue` | 修改 | 移动端隐藏侧边栏,添加顶部栏+设置按钮 |
| `frontend/src/views/WorkspaceView.vue` | 修改 | 移动端隐藏左侧导航,添加顶部栏+设置按钮 |
| `frontend/src/views/ProfileView.vue` | 修改 | 移动端返回按钮差异化路由 |
| `frontend/src/router/index.ts` | 修改 | 根路径智能跳转+认证守卫 |
### 16.4 关键设计决策
| 决策点 | 选择 | 理由 |
| --- | --- | --- |
| 移动端判定方式 | `innerHeight > innerWidth` | 不依赖 UA 字符串,纯屏幕方向判定,适配旋转 |
| 侧边栏处理方式 | `v-if` 不渲染 | 移动端无侧边栏需求,不渲染可减少 DOM 体积和事件监听 |
| 移动端设置入口 | 独立顶部栏按钮 | 不复用 PC 侧边栏底部按钮,交互更直观 |
| 状态共享方式 | 全局单例 ref | 多组件共享同一状态,避免各组件判定不一致 |
| 登录后默认页 | `/chat/16` | 移动端核心场景是聊天,直接进入 Chat 页面 |
### 16.5 不影响 PC 端的保障
- 所有移动端适配逻辑均以 `v-if="isMobile"` 或三元表达式控制,`isMobile` 在 PC 横屏时始终为 `false`
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
+2 -2
View File
@@ -10,8 +10,8 @@
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-CsJr350M.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bir-WxSG.css">
<script type="module" crossorigin src="/assets/index-CRyzfl76.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BKu7TAYA.css">
</head>
<body>
<div id="app"></div>␍
+70 -6
View File
@@ -11,6 +11,7 @@ export interface ScheduleTask {
wait_seconds: number;
dify_agent_id?: number | null;
platform_api_path?: string | null;
data_source_type?: string;
notify_user_ids_json: number[];
notify_enabled: boolean;
enabled: boolean;
@@ -38,34 +39,97 @@ export interface ScheduleRun {
api_request_json?: Record<string, any> | null;
api_response_json?: Record<string, any> | null;
response_summary_json?: Record<string, any> | null;
step_logs?: StepLog[] | null;
error_message?: string | null;
excel_file_name?: string | null;
excel_file_size?: number | null;
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<string, any>;
}
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
return (await res.json()) as T;
}
export const listAdminSchedules = () => getJson<ScheduleTask[]>('/api/admin/schedules');
export const createAdminSchedule = (payload: Partial<ScheduleTask>) =>
export const listAdminSchedules = () =>
getJson<ScheduleTask[]>('/api/admin/schedules');
export const getAdminScheduleTaskConfig = (taskId: number) =>
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
fetch(`/api/admin/schedule-config/${taskId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) throw new Error('Update config failed');
return r.json();
});
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
fetch(`/api/admin/schedule-config/${taskId}/test-sql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test failed'); });
return r.json();
});
export interface TestScheduleRunResult {
run_no: string;
run_id: number;
sql: string;
limit: number;
total_count: number;
success_count: number;
failed_count: number;
skipped_count: number;
details: Record<string, any>[];
errors: string[];
step_logs: StepLog[];
dify_agent_id: number | null;
}
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
fetch(`/api/admin/schedule-config/${taskId}/test-run`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
}).then(r => {
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test run failed'); });
return r.json() as Promise<TestScheduleRunResult>;
});
export const createAdminSchedule = (payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
fetch('/api/admin/schedules', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask>) =>
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
fetch(`/api/admin/schedules/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
export const deleteAdminSchedule = (id: number) =>
fetch(`/api/admin/schedules/${id}`, {
method: 'DELETE',
+32
View File
@@ -0,0 +1,32 @@
import { ref, onMounted, onBeforeUnmount, readonly } from 'vue';
const isMobile = ref(false);
let listeners = 0;
const update = () => {
isMobile.value = window.innerHeight > window.innerWidth;
};
const startListening = () => {
if (listeners === 0) {
update();
window.addEventListener('resize', update);
}
listeners++;
};
const stopListening = () => {
listeners--;
if (listeners <= 0) {
listeners = 0;
window.removeEventListener('resize', update);
}
};
export function useIsMobile() {
onMounted(() => startListening());
onBeforeUnmount(() => stopListening());
return { isMobile: readonly(isMobile) };
}
+24 -8
View File
@@ -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();
});
File diff suppressed because it is too large. Load diff
+324 -55
View File
@@ -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<HTMLElement | null>(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<HTMLElement | null>(null);
@@ -34,6 +51,7 @@ const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null;
let wasThinking = false;
marked.setOptions({
gfm: true,
@@ -571,54 +589,80 @@ const copiedIndex = ref<number | null>(null);
const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string }>>([]);
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 = `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>正在登录OA系统...</title></head>
<body>
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">正在登录OA系统,请稍候...</p>
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
<input type="hidden" name="loginid" value="${username}" />
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '&quot;')}" />
<input type="hidden" name="gopage" value="${gopage}" />
<input type="hidden" name="logintype" value="1" />
</form>
<script>document.getElementById('oaLoginForm').submit();<\/script>
</body>
</html>
`;
const fields = {
loginid: OA_AUTO_LOGIN_USERNAME,
userpassword: OA_AUTO_LOGIN_PASSWORD,
gopage,
logintype: '1',
};
Object.entries(fields).forEach(([name, value]) => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
});
document.body.appendChild(form);
window.setTimeout(() => {
form.submit();
document.body.removeChild(form);
}, 0);
popup.document.open();
popup.document.write(formHtml);
popup.document.close();
};
const openOALeaveRequestDirectly = () => {
openOAAutoLoginPage(OA_LEAVE_APPLY_PATH);
const employeeId = currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
showMessageDialog('warning', '没有工号信息无法登录OA系统!');
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
showOALoginDialog.value = true;
};
const confirmOALogin = () => {
if (!oaLoginPassword.value.trim()) {
showMessageDialog('warning', '请输入OA登录密码!');
return;
}
// 记住密码到 localStorage
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
showOALoginDialog.value = false;
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
};
const cancelOALogin = () => {
showOALoginDialog.value = false;
};
const openOARequestDirectly = (requestId: string) => {
@@ -627,7 +671,16 @@ const openOARequestDirectly = (requestId: string) => {
showMessageDialog('warning', '当前未获取到 OA 单据编号,暂时无法打开单据详情。');
return;
}
openOAAutoLoginPage(`${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`, `hxops-oa-request-${normalizedRequestId}`);
const employeeId = currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
showMessageDialog('warning', '没有工号信息无法登录OA系统!');
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
showOALoginDialog.value = true;
};
const activeFeedbackMessageIndex = ref<number | null>(null);
@@ -943,7 +996,81 @@ const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
}
};
const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
const formatLeaveBalanceNumber = (value: any) => {
if (value === null || value === undefined) return '暂无数据';
const num = Number(value);
if (Number.isNaN(num)) return String(value);
return Number.isInteger(num) ? String(num) : num.toFixed(2);
};
const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
} | null> => {
try {
const res = await fetch(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveTypeCode)}`, {
headers: getAuthHeaders(),
});
if (!res.ok) return null;
return await res.json();
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
}
};
const startLocalLeaveFlow = async (content: string) => {
const initialLeaveType = extractLeaveTypeFromIntent(content);
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
const thinkingMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: '正在查询您的假期余额,请稍候...',
};
messages.value.push(thinkingMsg);
const balance = await checkLeaveBalance(initialLeaveType);
const thinkingIndex = messages.value.indexOf(thinkingMsg);
if (thinkingIndex >= 0) {
messages.value.splice(thinkingIndex, 1);
}
if (balance && !balance.has_balance) {
const unit = initialLeaveType === '010' ? '天' : '小时';
const detailLines = [
`**${balance.leave_type_label}余额不足,暂无可用假期。**`,
'',
`| 假别 | 年度 | 可休 | 已休 | 当前剩余 |`,
`| :---: | :---: | :---: | :---: | :---: |`,
`| ${balance.leave_type_label} | ${balance.year} | ${formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
'',
'如有疑问,请联系人事部门确认假期数据。',
];
const noBalanceMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: detailLines.join('\n'),
};
messages.value.push(noBalanceMsg);
await saveLocalMessageToBackend(noBalanceMsg, content);
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
await loadHistory();
}
return;
}
}
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
@@ -951,8 +1078,10 @@ const startLocalLeaveFlow = async (content: string) => {
submitting: false,
confirmationGenerated: false,
};
messages.value.push({ role: 'user', content, type: 'text' });
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
messages.value.push({ role: 'user', content, type: 'text' });
}
const formMsg = {
role: 'assistant' as const,
type: 'leave-form' as const,
@@ -1125,6 +1254,29 @@ const scrollChatToBottom = async () => {
});
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
await nextTick();
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return;
const el = container.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scheduleScrollChatToBottom = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
@@ -1265,7 +1417,6 @@ const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return;
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = '';
if (isStrongLeaveIntent(content)) {
@@ -1275,11 +1426,9 @@ const handleSend = async (textOrEvent?: string | Event) => {
await sendMessage(content, agentId, selectedKb.value);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
} else if (conversationId.value) {
// Check if current conversation is in history, if not, reload
const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
@@ -1535,15 +1684,45 @@ const loadAgent = async () => {
}
};
const loadUserAgents = async () => {
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (res.ok) {
const agents = await res.json();
userAgents.value = Array.isArray(agents) ? agents.filter((a: any) => a.id !== agentId) : [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
}
} catch (e) {
userAgents.value = [];
showAgentPanel.value = false;
}
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === agentId) return;
const url = router.resolve(`/chat/${agent.id}`).href;
window.open(url, '_blank');
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true });
window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile();
await loadAgent();
await loadUserAgents();
await loadHistory();
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
@@ -1557,6 +1736,8 @@ onMounted(async () => {
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
document.removeEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.removeEventListener('touchstart', handleMobileAgentPopoverClickOutside);
window.removeEventListener('resize', syncViewportWidth);
stopBrowserResize();
if (scrollToBottomFrame !== null) {
@@ -1574,7 +1755,13 @@ watch(
conversationId: conversationId.value || '',
}),
() => {
scheduleScrollChatToBottom();
if (wasThinking && !isThinking.value) {
wasThinking = false;
scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollChatToBottom();
}
},
{ deep: false },
);
@@ -1589,12 +1776,13 @@ const showChatRating = ref(false);
<template>
<div class="relative flex h-screen overflow-hidden bg-slate-50 text-slate-800 dark:bg-slate-950 dark:text-slate-100">
<div
v-if="isSidebarOpen"
v-if="isSidebarOpen && !isMobile"
class="fixed inset-0 z-40 bg-slate-900/55 backdrop-blur-sm transition-opacity md:hidden"
@click="isSidebarOpen = false"
></div>
<aside
v-if="!isMobile"
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r bg-white transition-all duration-300 ease-in-out dark:bg-slate-950 md:relative md:translate-x-0"
:class="[
isSidebarOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
@@ -1630,7 +1818,7 @@ const showChatRating = ref(false);
<div class="flex items-center justify-between p-4">
<div class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div>
<span class="font-bold text-slate-800 dark:text-slate-100">Hxops Alagent</span>
<span class="font-bold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
</div>
<button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<PanelLeftClose class="h-5 w-5" />
@@ -1680,21 +1868,23 @@ const showChatRating = ref(false);
</div>
<div class="mt-auto flex flex-col p-4">
<!-- Upgrade card disabled for now. Keep code for future rollout.
<div class="mb-4 rounded-2xl border border-brand-100 bg-brand-50/70 p-4 dark:border-brand-500/20 dark:bg-brand-900/10">
<div class="mb-2 flex items-center gap-1 font-bold text-brand-700 dark:text-brand-300">
<Crown class="h-4 w-4" /> 专业版
<div v-if="userAgents.length > 0 && showAgentPanel" class="mb-4 rounded-2xl border border-slate-200 bg-slate-50/70 p-3 dark:border-slate-700 dark:bg-slate-800/60">
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-500 dark:text-slate-400">
<LayoutGrid class="h-3.5 w-3.5" /> 智能体
</div>
<div class="grid grid-cols-2 gap-1.5">
<button
v-for="agent in userAgents"
:key="agent.id"
@click="switchToAgent(agent)"
class="flex items-center justify-center gap-1.5 rounded-xl px-2 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-white hover:shadow-sm dark:text-slate-200 dark:hover:bg-slate-700/50 truncate"
>
<div v-if="agent.icon_url" class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat" :style="{ backgroundImage: `url(${agent.icon_url})` }"></div>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600 dark:bg-brand-900/30 dark:text-brand-400">{{ agent.name.charAt(0) }}</div>
<span class="truncate">{{ agent.name }}</span>
</button>
</div>
<ul class="mb-3 space-y-1 text-[11px] text-slate-600 dark:text-slate-300">
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 统一Agent知识库入口</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 优化Chat界面及交互</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 修改文档预览bug等</li>
</ul>
<button class="w-full rounded-xl bg-brand-600 py-2 text-xs font-medium text-white shadow-md shadow-brand-500/20 transition-colors hover:bg-brand-700 dark:bg-brand-500 dark:hover:bg-brand-400">
🚀 升级说明
</button>
</div>
-->
<!-- Bottom Icons -->
<div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef">
@@ -1722,6 +1912,7 @@ const showChatRating = ref(false);
</div>
<div class="flex gap-3">
<button @click="userAgents.length === 0 ? undefined : (showAgentPanel = !showAgentPanel)" :class="showAgentPanel && userAgents.length > 0 ? 'text-brand-600 dark:text-brand-400' : ''" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" :title="userAgents.length === 0 ? '暂无可用智能体' : (showAgentPanel ? '收起智能体' : '展开智能体')"><LayoutGrid class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button>
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button>
@@ -1734,6 +1925,38 @@ const showChatRating = ref(false);
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden bg-white dark:bg-slate-950">
<header v-if="isMobile && currentAgent" class="flex items-center justify-between border-b border-slate-200 px-4 py-2.5 dark:border-slate-800">
<div class="flex items-center gap-2">
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
<span class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
</div>
<div class="flex items-center gap-1">
<button @click="toggleMobileAgentPopover" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="智能体">
<LayoutGrid class="h-5 w-5" />
</button>
<button @click="router.push('/workspace?view=history')" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="历史记录">
<History class="h-5 w-5" />
</button>
</div>
<div v-if="showMobileAgentPopover" ref="mobileAgentPopoverRef" class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-slate-200 bg-white p-3 shadow-xl dark:border-slate-700 dark:bg-slate-800">
<div class="mb-2 text-xs font-medium text-slate-400">智能体</div>
<div class="grid grid-cols-2 gap-2">
<button
v-for="agent in userAgents"
:key="agent.id"
@click="switchToAgent(agent); showMobileAgentPopover = false"
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover:bg-slate-100 dark:hover:bg-slate-700"
>
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600 dark:bg-brand-900/30">
{{ agent.name.charAt(0) }}
</div>
<span class="w-full truncate text-xs font-medium text-slate-700 dark:text-slate-200">{{ agent.name }}</span>
</button>
</div>
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-slate-400">暂无其他智能体</div>
</div>
</header>
<div v-if="!currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
<p class="text-sm animate-pulse text-slate-500 dark:text-slate-300">{{ $t('chat.loadingAgent') }}</p>
@@ -1768,6 +1991,7 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>
@@ -2415,6 +2639,51 @@ const showChatRating = ref(false);
</div>
</div>
<!-- OA 登录对话框 -->
<Teleport to="body">
<div v-if="showOALoginDialog" class="fixed inset-0 z-[9999] flex items-center justify-center">
<div class="absolute inset-0 bg-black/40" @click="cancelOALogin"></div>
<div class="relative w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-800">
<h3 class="mb-4 text-center text-lg font-bold text-slate-800 dark:text-slate-100">登录OA系统</h3>
<div class="space-y-4">
<label class="block space-y-1.5">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">工号</span>
<input
v-model="oaLoginEmployeeId"
type="text"
disabled
class="w-full rounded-xl border border-slate-200 bg-slate-100 px-3 py-2.5 text-sm text-slate-600 outline-none dark:border-slate-600 dark:bg-slate-700 dark:text-slate-300"
/>
</label>
<label class="block space-y-1.5">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">密码</span>
<input
v-model="oaLoginPassword"
type="password"
placeholder="请输入OA登录密码"
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-400 focus:ring-2 focus:ring-brand-100 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-100 dark:focus:border-brand-500 dark:focus:ring-brand-500/20"
@keyup.enter="confirmOALogin"
/>
</label>
</div>
<div class="mt-6 flex items-center justify-end gap-3">
<button
@click="cancelOALogin"
class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-700"
>
取消
</button>
<button
@click="confirmOALogin"
class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700 dark:bg-brand-500 dark:hover:bg-brand-600"
>
确认登录
</button>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
-483
View File
@@ -1,483 +0,0 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useTheme } from '../composables/useTheme';
import type { ThemePreference } from '../composables/useTheme';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import { getAuthHeaders } from '../utils/auth';
import {
User,
Mail,
Building,
CreditCard,
Shield,
Globe,
LogOut,
Save,
ChevronLeft,
X,
Palette
} from 'lucide-vue-next';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference, appliedTheme } = useTheme();
interface ProfileForm {
id: number;
username: string;
real_name: string;
email: string;
phone_number: string;
department: string;
role: string;
employee_id: string;
language: string;
theme_preference: ThemePreference;
}
// State
const isLoading = ref(true);
const isSaving = ref(false);
const user = ref<ProfileForm>({
id: 0,
username: '',
real_name: '',
email: '',
phone_number: '',
department: '',
role: '',
employee_id: '',
language: 'zh-CN',
theme_preference: 'system' as ThemePreference
});
const originalProfile = ref<ProfileForm | null>(null);
const isEditing = ref(false);
const passwordForm = ref({
current: '',
new: '',
confirm: ''
});
const themeOptions: Array<{ value: ThemePreference; label: () => string }> = [
{ value: 'light', label: () => t('theme.light') || 'Light' },
{ value: 'dark', label: () => t('theme.dark') || 'Dark' },
{ value: 'system', label: () => t('theme.system') || 'Follow System' },
];
const hasUnsavedChanges = computed(() => {
if (!originalProfile.value) return false;
return (
user.value.real_name !== originalProfile.value.real_name ||
user.value.phone_number !== originalProfile.value.phone_number ||
user.value.language !== originalProfile.value.language ||
user.value.theme_preference !== originalProfile.value.theme_preference ||
user.value.email !== originalProfile.value.email ||
user.value.employee_id !== originalProfile.value.employee_id ||
user.value.department !== originalProfile.value.department
);
});
const captureOriginalProfile = () => {
originalProfile.value = { ...user.value };
};
const startEditing = () => {
isEditing.value = true;
};
const cancelEditing = () => {
if (originalProfile.value) {
user.value = { ...originalProfile.value };
locale.value = user.value.language;
setThemePreference(user.value.theme_preference);
}
isEditing.value = false;
};
// Methods
const fetchProfile = async () => {
isLoading.value = true;
try {
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
if (res.ok) {
const data = await res.json();
user.value = { ...user.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) {
setThemePreference(data.theme_preference);
} else {
user.value.theme_preference = appliedTheme.value;
}
captureOriginalProfile();
isEditing.value = false;
} else {
console.error('Failed to load profile');
}
} catch (e) {
console.error(e);
} finally {
isLoading.value = false;
}
};
const showPasswordModal = ref(false);
const parseErrorMessage = async (res: Response) => {
try {
const data = await res.json();
return data?.error || data?.message || '';
} catch {
try {
return await res.text();
} catch {
return '';
}
}
};
const handleSaveProfile = async () => {
if (!hasUnsavedChanges.value) {
isEditing.value = false;
return;
}
const payload = {
real_name: user.value.real_name,
phone_number: user.value.phone_number,
language: user.value.language,
theme_preference: user.value.theme_preference,
email: user.value.email,
employee_id: user.value.employee_id,
department: user.value.department
};
// Apply UI state first so theme switch always takes effect immediately.
locale.value = user.value.language;
setThemePreference(user.value.theme_preference);
try {
isSaving.value = true;
let res = await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload)
});
if (!res.ok) {
// Backward compatibility: older backend may not support theme_preference yet.
const fallbackPayload = {
real_name: user.value.real_name,
phone_number: user.value.phone_number,
language: user.value.language,
email: user.value.email,
employee_id: user.value.employee_id,
department: user.value.department
};
res = await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(fallbackPayload)
});
}
if (!res.ok) {
const message = await parseErrorMessage(res);
showMessageDialog('error', message || 'Failed to save profile');
return;
}
showMessageDialog('success', t('profile.saveSuccess') || 'Profile saved successfully');
captureOriginalProfile();
isEditing.value = false;
} catch (e) {
console.error(e);
showMessageDialog('error', 'Failed to save profile');
} finally {
isSaving.value = false;
}
};
const handleChangePassword = async () => {
if (passwordForm.value.new !== passwordForm.value.confirm) {
showMessageDialog('warning', t('profile.passwordMismatch') || 'Passwords do not match');
return;
}
try {
const res = await fetch('/api/user/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
current_password: passwordForm.value.current,
new_password: passwordForm.value.new
})
});
const data = await res.json();
if (res.ok) {
showMessageDialog('success', t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} else {
showMessageDialog('error', data.error || 'Failed to change password');
}
} catch (e) {
console.error(e);
showMessageDialog('error', 'Error changing password');
}
};
const handleLogout = () => {
localStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_user');
sessionStorage.removeItem('hxops_wecom_state');
router.replace('/');
};
onMounted(() => {
fetchProfile();
});
</script>
<template>
<div class="min-h-screen bg-slate-50 dark:bg-slate-950 pb-20">
<!-- Header -->
<header class="bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-30">
<div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
<div class="flex items-center gap-4">
<button @click="router.push('/workspace')" class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full text-slate-500 dark:text-slate-300 transition-colors">
<ChevronLeft class="w-5 h-5" />
</button>
<h1 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('profile.title') || 'My Profile' }}</h1>
</div>
<div class="flex items-center gap-2">
<ThemeToggleButton />
<button @click="handleLogout" class="text-sm font-medium text-red-600 hover:text-red-700 flex items-center gap-2 px-3 py-1.5 hover:bg-red-50 rounded-lg transition-colors">
<LogOut class="w-4 h-4" />
<span class="hidden sm:inline">{{ $t('workspace.logout') }}</span>
</button>
</div>
</div>
</header>
<main class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div v-if="isLoading" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else class="grid grid-cols-1 lg:grid-cols-3 gap-8">
<!-- Left Column: User Card -->
<div class="lg:col-span-1 space-y-6">
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-700 p-6 text-center">
<div class="w-24 h-24 bg-brand-100 rounded-full mx-auto flex items-center justify-center text-brand-600 mb-4 text-3xl font-bold">
{{ user.real_name ? user.real_name.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase() }}
</div>
<h2 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ user.real_name || user.username }}</h2>
<p class="text-slate-500 dark:text-slate-400 text-sm mt-1">{{ user.email }}</p>
<div class="mt-4 inline-flex items-center px-3 py-1 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 text-xs font-medium">
{{ user.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}
</div>
</div>
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-700 p-6">
<h3 class="font-semibold text-slate-900 dark:text-slate-100 mb-4 flex items-center gap-2">
<Shield class="w-4 h-4 text-brand-500" />
{{ $t('profile.security') || 'Security' }}
</h3>
<button @click="showPasswordModal = true" class="btn-primary w-full py-2 text-sm flex items-center justify-center gap-2">
<Shield class="w-4 h-4" />
{{ $t('profile.changePassword') || 'Change Password' }}
</button>
</div>
</div>
<!-- Right Column: Details & Settings -->
<div class="lg:col-span-2 space-y-6">
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-700 p-4">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div>
<div class="text-sm font-semibold text-slate-900 dark:text-slate-100">
{{ isEditing ? ($t('profile.edit') || 'Edit') : ($t('profile.personalInfo') || 'Personal Information') }}
</div>
<div class="text-xs text-slate-500 dark:text-slate-400">
{{ isEditing ? ($t('profile.unsavedChanges') || 'You have unsaved changes') : ($t('profile.editHint') || 'Switch to edit mode to update profile details') }}
</div>
</div>
<div class="flex items-center gap-2">
<button v-if="!isEditing" @click="startEditing" class="btn-secondary text-sm px-4 py-2">
{{ $t('profile.edit') || 'Edit' }}
</button>
<template v-else>
<button @click="cancelEditing" class="btn-secondary text-sm px-4 py-2">
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button
@click="handleSaveProfile"
:disabled="isSaving || !hasUnsavedChanges"
class="btn-primary text-sm px-4 py-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
<Save class="w-4 h-4" />
<span>{{ isSaving ? 'Saving...' : ($t('workspace.save') || 'Save') }}</span>
</button>
</template>
</div>
</div>
</div>
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-700 p-6 md:p-8">
<div class="flex justify-between items-center mb-6">
<h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
<User class="w-5 h-5 text-brand-500" />
{{ $t('profile.personalInfo') || 'Personal Information' }}
</h3>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<User class="w-3.5 h-3.5" /> {{ $t('login.username') }}
</label>
<div class="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 text-sm font-medium cursor-not-allowed">
{{ user.username }}
</div>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<CreditCard class="w-3.5 h-3.5" /> {{ $t('register.fields.employeeId') || 'Employee ID' }}
</label>
<input v-if="isEditing" v-model="user.employee_id" type="text" class="input-field" />
<div v-else class="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 text-sm font-medium">
{{ user.employee_id || '-' }}
</div>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<User class="w-3.5 h-3.5" /> {{ $t('register.fields.realName') || 'Real Name' }}
</label>
<input v-if="isEditing" v-model="user.real_name" type="text" class="input-field" />
<div v-else class="p-2.5 bg-white dark:bg-slate-900 rounded-lg text-slate-900 dark:text-slate-100 border border-transparent text-sm font-medium">
{{ user.real_name || '-' }}
</div>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<Building class="w-3.5 h-3.5" /> {{ $t('profile.department') || 'Department' }}
</label>
<input v-if="isEditing" v-model="user.department" type="text" class="input-field" />
<div v-else class="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 text-sm font-medium">
{{ user.department || '-' }}
</div>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<Mail class="w-3.5 h-3.5" /> {{ $t('register.email') }}
</label>
<input v-if="isEditing" v-model="user.email" type="email" class="input-field" />
<div v-else class="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 text-sm font-medium">
{{ user.email }}
</div>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase flex items-center gap-1.5 mb-1.5">
<Globe class="w-3.5 h-3.5" /> {{ $t('register.fields.phone') || 'Phone' }}
</label>
<input v-if="isEditing" v-model="user.phone_number" type="text" class="input-field" />
<div v-else class="p-2.5 bg-white dark:bg-slate-900 rounded-lg text-slate-900 dark:text-slate-100 border border-transparent text-sm font-medium">
{{ user.phone_number || '-' }}
</div>
</div>
</div>
</div>
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-700 p-6 md:p-8">
<h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 mb-6 flex items-center gap-2">
<Globe class="w-5 h-5 text-brand-500" />
{{ $t('profile.preferences') || 'Preferences' }}
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="text-xs font-medium text-slate-500 uppercase mb-1.5 block">{{ $t('profile.language') || 'Language' }}</label>
<select
v-model="user.language"
:disabled="!isEditing"
class="input-field appearance-none bg-no-repeat bg-right pr-8"
:class="{ 'bg-slate-50 dark:bg-slate-800': !isEditing }"
>
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase mb-1.5 flex items-center gap-1.5">
<Palette class="w-3.5 h-3.5" /> {{ $t('theme.label') || 'Theme' }}
</label>
<div class="grid grid-cols-3 gap-2">
<button
v-for="item in themeOptions"
:key="item.value"
type="button"
:disabled="!isEditing"
@click="user.theme_preference = item.value"
class="px-3 py-2 rounded-lg border text-xs font-medium transition-colors"
:class="user.theme_preference === item.value
? 'border-brand-500 bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-200'
: 'border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-600 dark:text-slate-300'"
>
{{ item.label() }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<div v-if="showPasswordModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 dark:bg-slate-950/70 backdrop-blur-sm p-4">
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-xl w-full max-w-md p-6 animate-fade-in-up border border-slate-200 dark:border-slate-700">
<div class="flex justify-between items-center mb-6">
<h3 class="text-lg font-bold text-slate-900 dark:text-slate-100">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
<button @click="showPasswordModal = false" class="p-1 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors">
<X class="w-5 h-5 text-slate-500 dark:text-slate-300" />
</button>
</div>
<form @submit.prevent="handleChangePassword" class="space-y-4">
<div>
<label class="text-xs font-medium text-slate-500 uppercase">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
<input v-model="passwordForm.current" type="password" class="input-field mt-1" required />
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase">{{ $t('profile.newPassword') || 'New Password' }}</label>
<input v-model="passwordForm.new" type="password" class="input-field mt-1" required />
</div>
<div>
<label class="text-xs font-medium text-slate-500 uppercase">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
<input v-model="passwordForm.confirm" type="password" class="input-field mt-1" required />
</div>
<div class="flex gap-3 pt-2">
<button type="button" @click="showPasswordModal = false" class="flex-1 px-4 py-2 border border-slate-200 dark:border-slate-700 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 font-medium transition-colors">
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button type="submit" class="flex-1 btn-primary py-2 text-sm">
{{ $t('profile.changePassword') || 'Update' }}
</button>
</div>
</form>
</div>
</div>
</template>
+225 -65
View File
@@ -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<ScheduleRun[]>([]);
const workspaceScheduleLoading = ref(false);
const wsScheduleStatusFilter = ref('all');
const wsScheduleNameFilter = ref('');
const wsScheduleStartedAfter = ref('');
const wsScheduleStartedBefore = ref('');
const toDateTimeLocalValue = (date: Date) => {
const pad = (n: number) => String(n).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
const todayStartLocal = () => {
const d = new Date();
d.setHours(0, 0, 0, 0);
return toDateTimeLocalValue(d);
};
const todayEndLocal = () => {
const d = new Date();
d.setHours(23, 59, 59, 0);
return toDateTimeLocalValue(d);
};
const wsScheduleStartedAfter = ref(todayStartLocal());
const wsScheduleStartedBefore = ref(todayEndLocal());
const wsScheduleStatusOptions = [
{ value: 'all', label: '全部状态' },
@@ -1030,18 +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<ChatHistoryItem[]>([]);
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 () => {
<!--
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-brand-50 text-brand-600 text-sm font-medium border border-brand-100">
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
</span>
{{ $t('title') }}
@@ -1461,8 +1542,15 @@ onMounted(async () => {
</div>
<!-- Logged In Layout -->
<div v-else class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)] animate-fade-in">
<aside class="lg:sticky lg:top-0 lg:h-screen">
<div v-else class="min-h-screen animate-fade-in">
<header v-if="isMobile" class="sticky top-0 z-30 flex items-center justify-between border-b border-slate-200 bg-white px-4 py-2.5 dark:border-slate-800 dark:bg-slate-950">
<div class="flex items-center gap-2">
<button @click="router.push('/chat/16')" class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20" title="返回聊天">AI</button>
<span class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ mobileTabTitle }}</span>
</div>
</header>
<div class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)]">
<aside v-if="!isMobile" class="lg:sticky lg:top-0 lg:h-screen">
<div class="flex h-full flex-col border-r border-slate-200 bg-white px-5 py-6 shadow-sm">
<div class="border-b border-slate-100 pb-6">
<div class="flex items-center gap-3">
@@ -1470,7 +1558,7 @@ onMounted(async () => {
<Bot class="h-6 w-6" />
</div>
<div class="min-w-0">
<div class="text-2xl font-extrabold tracking-tight text-[#14213d]">Hxops</div>
<div class="text-2xl font-extrabold tracking-tight text-[#14213d]">和信AI</div>
<div class="truncate text-xs font-medium text-slate-400">
{{ currentUser?.username }} / {{ currentUser?.role }}
</div>
@@ -1560,8 +1648,44 @@ onMounted(async () => {
</div>
</aside>
<section class="min-w-0 space-y-6 bg-gray-50 px-4 py-6 md:px-6 md:py-8 lg:px-8">
<template v-if="activeSidebarItem === 'profile'">
<section class="min-w-0 space-y-6 bg-gray-50 px-4 py-6 md:px-6 md:py-8 lg:px-8" :class="isMobile ? 'pb-20' : ''">
<template v-if="activeSidebarItem === 'history'">
<div class="space-y-3">
<div v-if="isLoadingHistories" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else-if="chatHistories.length === 0" class="flex flex-col items-center justify-center py-20 text-slate-400">
<Bot class="h-10 w-10 mb-2" />
<p class="text-sm">暂无历史会话</p>
</div>
<div v-else>
<button
v-for="item in chatHistories"
:key="item.id"
@click="router.push(`/chat/${item.agent_id || 16}?conversation_id=${item.conversation_id}`)"
class="w-full rounded-2xl border border-slate-200 bg-white p-3 text-left transition-colors hover:border-brand-300 hover:bg-brand-50/50 dark:border-slate-700 dark:bg-slate-800 dark:hover:border-brand-600 mb-2"
:class="isMobile ? 'p-2.5 rounded-xl' : ''"
>
<div class="flex items-start gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-50 text-xs font-bold text-brand-600 dark:bg-brand-900/30" :class="isMobile ? 'h-7 w-7 text-[10px]' : ''">
{{ (item.agent_name || 'AI').charAt(0) }}
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate text-sm font-medium text-slate-800 dark:text-slate-100">{{ item.title || '未命名对话' }}</span>
</div>
<div class="mt-0.5 flex items-center gap-2 text-xs text-slate-400">
<span>{{ item.agent_name || '' }}</span>
<span>{{ new Date(item.created_at).toLocaleDateString() }}</span>
</div>
</div>
</div>
</button>
</div>
</div>
</template>
<template v-else-if="activeSidebarItem === 'profile'">
<div v-if="isProfileLoading" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
@@ -1570,48 +1694,64 @@ onMounted(async () => {
<div class="rounded-3xl border border-slate-200 bg-white px-6 py-6 shadow-sm md:px-8">
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600">
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="isMobile ? 'h-14 w-14 text-2xl' : ''">
{{ (profileUser.real_name || profileUser.username || 'U').charAt(0).toUpperCase() }}
</div>
<div class="grid flex-1 grid-cols-1 gap-x-12 gap-y-3 text-left sm:grid-cols-2">
<div>
<div class="text-lg font-semibold text-slate-900">{{ profileUser.username || '-' }}</div>
<div class="grid flex-1 text-left" :class="isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
<div :class="isMobile ? '' : ''">
<div :class="isMobile ? 'text-xs text-slate-400' : 'text-lg font-semibold text-slate-900'">{{ isMobile ? '姓名' : (profileUser.username || '-') }}</div>
<div v-if="isMobile" class="text-sm font-medium text-slate-900 truncate">{{ profileUser.real_name || profileUser.username || '-' }}</div>
</div>
<div>
<div class="text-lg font-semibold text-slate-900">{{ profileUser.employee_id || '-' }}</div>
<div :class="isMobile ? 'text-xs text-slate-400' : 'text-lg font-semibold text-slate-900'">{{ isMobile ? '工号' : (profileUser.employee_id || '-') }}</div>
<div v-if="isMobile" class="text-sm font-medium text-slate-900 truncate">{{ profileUser.employee_id || '-' }}</div>
</div>
<div>
<div class="text-lg font-semibold text-slate-900">{{ profileUser.department || '-' }}</div>
<div :class="isMobile ? 'text-xs text-slate-400' : 'text-lg font-semibold text-slate-900'">{{ isMobile ? '部门' : (profileUser.department || '-') }}</div>
<div v-if="isMobile" class="text-sm font-medium text-slate-900 truncate">{{ profileUser.department || '-' }}</div>
</div>
<div>
<div class="text-lg font-semibold text-slate-900">
{{ profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}
</div>
<div :class="isMobile ? 'text-xs text-slate-400' : 'text-lg font-semibold text-slate-900'">{{ isMobile ? '角色' : (profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
<div v-if="isMobile" class="text-sm font-medium text-slate-900 truncate">{{ profileUser.role === 'admin' ? ($t('profile.roleAdmin') || '管理员') : ($t('profile.roleUser') || '用户') }}</div>
</div>
<div class="sm:col-span-2">
<div class="break-all text-lg font-semibold text-slate-900">{{ profileUser.email || '-' }}</div>
<div :class="isMobile ? 'col-span-2' : 'sm:col-span-2'">
<div :class="isMobile ? 'text-xs text-slate-400' : 'break-all text-lg font-semibold text-slate-900'">{{ isMobile ? '邮箱' : (profileUser.email || '-') }}</div>
<div v-if="isMobile" class="text-sm font-medium text-slate-900 truncate">{{ profileUser.email || '-' }}</div>
</div>
</div>
</div>
<button @click="showPasswordModal = true" class="btn-primary shrink-0 self-start px-6 py-3 text-base lg:ml-6">
<div v-if="!isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
<button @click="showPasswordModal = true" class="btn-primary px-6 py-3 text-base">
修改密码
</button>
</div>
</div>
<div v-if="isMobile" class="mt-4 flex items-center justify-center gap-4">
<button @click="showPasswordModal = true" class="btn-primary flex-1 py-2.5 text-sm text-center">
修改密码
</button>
<button @click="handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950">
退出登录
</button>
</div>
</div>
<div class="space-y-6">
<div class="rounded-3xl border border-slate-200 bg-white p-8 shadow-sm">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 class="flex items-center gap-3 text-3xl font-bold text-slate-900">
<User class="h-6 w-6 text-brand-500" />
<div class="rounded-3xl border border-slate-200 bg-white p-8 shadow-sm" :class="isMobile ? 'p-4' : ''">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="isMobile ? 'mb-4 gap-2' : ''">
<div class="flex items-center" :class="isMobile ? 'w-full justify-center gap-2' : ''">
<h3 class="flex items-center gap-3 text-3xl font-bold text-slate-900" :class="isMobile ? 'text-lg gap-2' : ''">
<User class="h-6 w-6 text-brand-500" :class="isMobile ? 'h-4 w-4' : ''" />
基本信息
</h3>
<p class="mt-2 text-sm text-slate-500">
{{ isProfileEditing ? '可直接修改并保存个人资料' : '切换到编辑模式以更新个人资料' }}
</p>
<button v-if="isMobile && !isProfileEditing" @click="startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
编辑
</button>
</div>
<div class="flex items-center gap-2">
<p v-if="!isMobile" class="mt-2 text-sm text-slate-500">
{{ isProfileEditing ? '可直接修改并保存个人资料' : '切换到编辑模式以更新个人资料' }}
</p>
<div v-if="!isMobile" class="flex items-center gap-2">
<button v-if="!isProfileEditing" @click="startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
编辑
</button>
@@ -1630,57 +1770,57 @@ onMounted(async () => {
</template>
</div>
</div>
<div class="grid grid-cols-1 gap-5 md:grid-cols-2">
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="isMobile ? 'gap-3' : ''">
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> 用户名
</label>
<div class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<div class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.username || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<CreditCard class="h-4 w-4" /> 工号
</label>
<input v-if="isProfileEditing" v-model="profileUser.employee_id" type="text" class="input-field h-[58px]" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<input v-if="isProfileEditing" v-model="profileUser.employee_id" type="text" class="input-field" :class="isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.employee_id || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> 真实姓名
</label>
<input v-if="isProfileEditing" v-model="profileUser.real_name" type="text" class="input-field h-[58px]" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<input v-if="isProfileEditing" v-model="profileUser.real_name" type="text" class="input-field" :class="isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.real_name || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<Building class="h-4 w-4" /> 部门
</label>
<input v-if="isProfileEditing" v-model="profileUser.department" type="text" class="input-field h-[58px]" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<input v-if="isProfileEditing" v-model="profileUser.department" type="text" class="input-field" :class="isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.department || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<Mail class="h-4 w-4" /> 邮箱
</label>
<input v-if="isProfileEditing" v-model="profileUser.email" type="email" class="input-field h-[58px]" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<input v-if="isProfileEditing" v-model="profileUser.email" type="email" class="input-field" :class="isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.email || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500">
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-slate-500" :class="isMobile ? 'text-xs mb-1' : ''">
<Globe class="h-4 w-4" /> 手机号
</label>
<input v-if="isProfileEditing" v-model="profileUser.phone_number" type="text" class="input-field h-[58px]" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700">
<input v-if="isProfileEditing" v-model="profileUser.phone_number" type="text" class="input-field" :class="isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-lg font-medium text-slate-700" :class="isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ profileUser.phone_number || '-' }}
</div>
</div>
@@ -1801,7 +1941,7 @@ onMounted(async () => {
<tr v-for="r in workspaceScheduleRuns" :key="r.id" class="border-b border-slate-50 transition-colors hover:bg-slate-50/50">
<td class="px-4 py-3 font-medium text-slate-900">{{ r.schedule_name || '-' }}</td>
<td class="px-4 py-3 text-slate-500 font-mono text-xs">{{ r.run_no }}</td>
<td class="px-4 py-3 text-slate-500">{{ r.trigger_type === 'manual' ? '手动' : '定时' }}</td>
<td class="px-4 py-3 text-slate-500">{{ r.trigger_type === 'manual' ? '手动' : r.trigger_type === 'test' ? '测试' : '定时' }}</td>
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ formatDateTime(r.started_at) }}</td>
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ formatDateTime(r.finished_at) }}</td>
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ r.duration_ms != null ? (r.duration_ms >= 1000 ? (r.duration_ms / 1000).toFixed(1) + 's' : r.duration_ms + 'ms') : '-' }}</td>
@@ -2014,6 +2154,26 @@ onMounted(async () => {
</div>
</template>
</section>
</div>
<nav v-if="isMobile" class="fixed bottom-0 left-0 right-0 z-40 border-t border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950 safe-bottom">
<div class="flex h-14 items-center justify-around">
<button
v-for="tab in ([
{ key: 'applications', icon: LayoutGrid, label: '应用管理' },
{ key: 'history', icon: Bot, label: '历史会话' },
{ key: 'profile', icon: User, label: '我的' },
] as const)"
:key="tab.key"
@click="mobileTabActive = tab.key"
class="flex flex-1 flex-col items-center justify-center gap-0.5 py-1 transition-colors"
:class="mobileTabActive === tab.key ? 'text-brand-600 dark:text-brand-400' : 'text-slate-400 dark:text-slate-500'"
>
<component :is="tab.icon" class="h-5 w-5" />
<span class="text-[10px] font-medium">{{ tab.label }}</span>
</button>
</div>
</nav>
</div>
<!-- Forgot Password Modal -->
<div v-if="showForgotPasswordModal" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">