Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-05-19 17:41:55 +08:00
commit ea56e8bf65
46 files changed
+4257 -192

No files matched your search

+1 -1
View File
@@ -32,4 +32,4 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_WECOM_PROVIDER_HINT=wecom
# Gunicorn配置
GUNICORN_WORKERS=2
GUNICORN_WORKERS=10
+1 -1
View File
@@ -32,4 +32,4 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_WECOM_PROVIDER_HINT=wecom
# Gunicorn配置
GUNICORN_WORKERS=2
GUNICORN_WORKERS=20
+12 -1
View File
@@ -58,7 +58,7 @@ 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_DRIVER=ODBC Driver 18 for SQL Server
HR_SQLSERVER_ENCRYPT=no
HR_SQLSERVER_TRUST_CERT=yes
HR_SQLSERVER_TIMEOUT=10
@@ -70,3 +70,14 @@ PLM_ORACLE_SID=orcl
PLM_ORACLE_USERNAME=PLM
PLM_ORACLE_PASSWORD=PLM
ORACLE_CLIENT_LIB_DIR=oracle_client\instantclient_19_30
# 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
+1 -1
View File
@@ -31,4 +31,4 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_WECOM_PROVIDER_HINT=wecom
# Gunicorn配置
GUNICORN_WORKERS=2
GUNICORN_WORKERS=6
+58
View File
@@ -0,0 +1,58 @@
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
+6
View File
@@ -51,6 +51,8 @@ def create_app(config_name='default'):
from app.api.user import user_bp
from app.api.knowledge_base import knowledge_base_bp
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
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
@@ -64,6 +66,8 @@ def create_app(config_name='default'):
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
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')
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
@@ -71,6 +75,8 @@ def create_app(config_name='default'):
# serve the defaults baked into config.py / the image).
with app.app_context():
_apply_persisted_settings(app)
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
@app.before_request
def _sync_persisted_settings():
+181 -6
View File
@@ -7,6 +7,7 @@ backend/app/api/chat.py
"""
import io
import ipaddress
import mimetypes
import tempfile
import os
import subprocess
@@ -25,6 +26,25 @@ from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
chat_bp = Blueprint('chat', __name__)
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
def _normalize_windows_share_path(path_value: str) -> str:
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
if normalized.startswith("\\\\"):
return "\\\\" + normalized[2:].rstrip("\\")
return normalized.rstrip("\\")
def _is_allowed_share_path(target_url: str) -> bool:
normalized_target = _normalize_windows_share_path(target_url)
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
return bool(
normalized_root
and normalized_target.startswith("\\\\")
and normalized_target.lower().startswith(normalized_root.lower())
)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
@@ -35,6 +55,8 @@ def _is_allowed_preview_url(target_url: str) -> bool:
3) 私网 IP 或常见内网域名(.local/.lan)。
"""
try:
if _is_allowed_share_path(target_url):
return True
parsed = urlparse(target_url)
if parsed.scheme not in ("http", "https"):
return False
@@ -75,6 +97,25 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
normalized_path = _normalize_windows_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
return None, None, ('source file not found', 404)
file_size = os.path.getsize(normalized_path)
if max_size is not None and file_size > max_size:
return None, None, ('file too large for online preview', 413)
with open(normalized_path, 'rb') as fh:
content = fh.read()
except OSError as exc:
current_app.logger.warning("[file-preview] failed to read share path %s: %s", normalized_path, exc)
return None, None, ('failed to read source file', 502)
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
if _extract_placeholder_text(content):
guessed_type = 'text/plain; charset=utf-8'
return content, guessed_type, None
headers = {}
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
@@ -188,6 +229,24 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
return None, None, ('upstream returned invalid preview payload', 502)
return content, content_type, None
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
text = sample.decode(enc).replace('\x00', '').strip()
except Exception:
continue
if not text:
continue
lines = [line.strip() for line in text.splitlines() if line.strip()]
if not lines:
continue
first_line = lines[0][:160]
if any(token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密')):
return first_line
return ''
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将 office 文件转为 PDF
@@ -321,14 +380,86 @@ def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
if _convert_excel_via_windows_office(input_path, output_path):
with open(output_path, 'rb') as f:
return f.read()
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
def _load_excel_workbook(content: bytes, ext: str):
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
"""
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
LibreOffice 不存在时,给在线预览提供兜底转换能力。
"""
if os.name != 'nt':
return False
try:
import pythoncom
import win32com.client
except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.")
return False
app = None
workbook = None
pythoncom.CoInitialize()
try:
try:
app = win32com.client.Dispatch("KET.Application")
except Exception:
app = win32com.client.Dispatch("Excel.Application")
app.Visible = False
app.DisplayAlerts = False
workbook = app.Workbooks.Open(os.path.abspath(input_path))
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) # 51 = xlOpenXMLWorkbook (.xlsx)
workbook.Close(False)
workbook = None
app.Quit()
app = None
return os.path.exists(output_path)
except Exception as exc:
current_app.logger.warning("WPS/MS Excel conversion failed for xls preview: %s", exc)
return False
finally:
try:
if workbook is not None:
workbook.Close(False)
except Exception:
pass
try:
if app is not None:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass
def _detect_excel_format(content: bytes, ext: str) -> str:
"""
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
- OLE 复合文档头: 老式 `.xls`
- ZIP 头: `.xlsx`
"""
normalized_ext = (ext or '').strip().lower()
head = content[:8] if content else b''
if head.startswith(b'PK\x03\x04'):
return 'xlsx'
if head.startswith(b'\xD0\xCF\x11\xE0'):
return 'xls'
return normalized_ext
def _load_excel_workbook(content: bytes, ext: str):
normalized_ext = _detect_excel_format(content, ext)
if normalized_ext == 'xls':
content = _convert_excel_to_xlsx(content, normalized_ext)
content = _convert_excel_to_xlsx(content, 'xls')
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
@@ -355,6 +486,29 @@ def get_oa_employees():
return jsonify({'error': str(e)}), 500
@chat_bp.route('/oa/resolve-names', methods=['GET'])
@require_agent_permission
def resolve_oa_names():
dept_ids = request.args.get('department_ids', '').strip()
sub_ids = request.args.get('subcompany_ids', '').strip()
result = {}
try:
from app.services.oa_sqlserver import OASQLServerService
if dept_ids:
for did in dept_ids.split(','):
did = did.strip()
if did:
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
if sub_ids:
for sid in sub_ids.split(','):
sid = sid.strip()
if sid:
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
except Exception as e:
current_app.logger.error(f"[OA-ResolveNames] Query failed: {e}")
return jsonify(result)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
@@ -771,8 +925,25 @@ def preview_excel():
try:
wb = _load_excel_workbook(content, ext)
except Exception as e:
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
return jsonify({'error': 'failed to parse excel file'}), 422
detected_ext = _detect_excel_format(content or b'', ext)
current_app.logger.warning(
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
ext,
detected_ext,
len(content or b''),
name,
file_url,
e,
)
payload = {'error': 'failed to parse excel file'}
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
payload.update({
'detail': str(e),
'ext': ext,
'detected_ext': detected_ext,
'size': len(content or b''),
})
return jsonify(payload), 422
if not wb.sheetnames:
return jsonify({'error': 'workbook has no sheets'}), 422
@@ -909,9 +1080,13 @@ def preview_file_raw():
'htm': 'text/html',
}
if ext == 'pdf' and not content.startswith(b'%PDF-'):
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
from urllib.parse import quote
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
+226
View File
@@ -0,0 +1,226 @@
from __future__ import annotations
import threading
from datetime import datetime
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.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
schedule_admin_bp = Blueprint('schedule_admin', __name__)
@schedule_admin_bp.route('/schedules', methods=['GET'])
@require_admin
def get_schedules():
return jsonify(list_tasks())
@schedule_admin_bp.route('/schedules', methods=['POST'])
@require_admin
def post_schedule():
data = request.get_json(silent=True) or {}
user = get_current_user()
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type='platform_app',
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=(int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None),
platform_api_path=str(data.get('platform_api_path') or '').strip() or None,
notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
actor_id=getattr(user, 'id', None),
)
return jsonify(serialize_task(task)), 201
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
@require_admin
def get_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
return jsonify(serialize_task(task))
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
@require_admin
def patch_schedule(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 {}
user = get_current_user()
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
return jsonify(serialize_task(task))
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
@require_admin
def delete_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
from app.services.schedule.scheduler_service import request_cancel_run
running_runs = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task_id,
ScheduleRun.status == "running",
).all()
for rr in running_runs:
request_cancel_run(rr.id)
rr.status = "failed"
rr.error_message = "排程已被删除,执行中断"
rr.finished_at = datetime.utcnow()
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()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
@require_admin
def enable_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
task.enabled = True
if task.cron_expr:
try:
from croniter import croniter
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
db.session.commit()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
@require_admin
def disable_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
task.enabled = False
db.session.commit()
return jsonify({'ok': True})
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@require_admin
def run_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
return jsonify({'error': 'Not found'}), 404
user = get_current_user()
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if existing:
return jsonify({'error': '该排程正在执行中,请等待完成后再试', 'run_id': existing.id}), 409
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type='manual',
triggered_by_user_id=getattr(user, 'id', None),
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
def _background():
with app.app_context():
t = db.session.get(ScheduleTask, task_id)
r = db.session.get(ScheduleRun, run_id)
if not t or not r:
return
try:
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
except Exception as exc:
try:
r = db.session.get(ScheduleRun, run_id)
if r and r.status == 'running':
r.status = 'failed'
r.error_message = str(exc)
r.finished_at = datetime.utcnow()
db.session.commit()
except Exception:
db.session.rollback()
current_app.logger.error("[schedule-run] run_id=%s failed: %s", run_id, exc, exc_info=True)
t = threading.Thread(target=_background, daemon=True, name=f"schedule-run-{run_id}")
t.start()
fresh = db.session.get(ScheduleRun, run_id)
return jsonify(serialize_run(fresh))
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
@require_admin
def get_schedule_runs(task_id: int):
status = str(request.args.get('status') or '').strip() or None
limit = int(request.args.get('limit') or 100)
started_after = None
started_before = None
sa = request.args.get('started_after')
sb = request.args.get('started_before')
if sa:
try:
started_after = datetime.fromisoformat(sa)
except (ValueError, TypeError):
pass
if sb:
try:
started_before = datetime.fromisoformat(sb)
except (ValueError, TypeError):
pass
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
@require_admin
def get_schedule_run(run_id: int):
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
return jsonify(serialize_run(run))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
@require_admin
def get_schedule_run_excel(run_id: int):
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
if not run.excel_file_path:
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')
+6
View File
@@ -1576,11 +1576,17 @@ def submit_leave_workflow():
form_data = {
'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)),
'applicantJobTitle': _clean_str(data.get('applicantJobTitle')),
'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')),
'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')),
'applyTime': _clean_str(data.get('applyTime')),
'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
'agentUid': _clean_str(data.get('agentUid')),
'agentEmployeeId': _clean_str(data.get('agentEmployeeId')),
'agentName': _clean_str(data.get('agentName')),
'agentJobTitle': _clean_str(data.get('agentJobTitle')),
'agentDepartmentId': _clean_str(data.get('agentDepartmentId')),
'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')),
'leaveType': _clean_str(data.get('leaveType')),
'startTime': _clean_str(data.get('startTime')),
'endTime': _clean_str(data.get('endTime')),
+67
View File
@@ -0,0 +1,67 @@
from __future__ import annotations
from datetime import datetime
from flask import Blueprint, jsonify, request, send_file
from app.auth_jwt import get_current_user
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
def _require_user():
user = get_current_user()
if not user:
return None, (jsonify({'error': 'Unauthorized'}), 401)
return user, None
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
def workspace_schedule_runs():
user, err = _require_user()
if err:
return err
status = str(request.args.get('status') or '').strip() or None
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
started_after_str = request.args.get('started_after')
started_before_str = request.args.get('started_before')
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
limit = int(request.args.get('limit') or 100)
return jsonify(list_runs(
notify_user_id=user.id,
schedule_name=schedule_name,
status=status,
started_after=started_after,
started_before=started_before,
limit=limit,
))
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
def workspace_schedule_run_detail(run_id: int):
user, err = _require_user()
if err:
return err
run = get_run(run_id)
if not run:
return jsonify({'error': 'Not found'}), 404
if not can_view_run(run, user.id):
return jsonify({'error': 'Forbidden'}), 403
return jsonify(serialize_run(run))
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
def workspace_schedule_run_excel(run_id: int):
user, err = _require_user()
if err:
return err
run = get_run(run_id)
if not run:
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:
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')
+24 -2
View File
@@ -30,7 +30,7 @@ def _load_environment_files() -> str:
1. .env.shared
2. .env.<ENV_NAME>
3. .env.local (only for dev)
4. system environment variables (always highest because override=False)
4. system environment variables (always highest, never overridden)
"""
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
shared_file = _ROOT_DIR / '.env.shared'
@@ -44,7 +44,7 @@ def _load_environment_files() -> str:
if env_name == 'dev':
local_file = _ROOT_DIR / '.env.local'
if local_file.exists():
load_dotenv(local_file, override=False)
load_dotenv(local_file, override=True)
return env_name
@@ -136,6 +136,27 @@ class Config:
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
SMTP_HOST = os.getenv('SMTP_HOST', '')
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
SMTP_USER = os.getenv('SMTP_USER', '')
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')
class DevelopmentConfig(Config):
@@ -153,6 +174,7 @@ class TestingConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
SCHEDULE_WORKER_ENABLED = False
config = {
+64
View File
@@ -546,3 +546,67 @@ class WecomCallbackAudit(Base):
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ScheduleTask(Base):
__tablename__ = 'schedule_tasks'
__table_args__ = (
Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
name: Mapped[str] = mapped_column(String(128), index=True)
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
cron_expr: Mapped[str] = mapped_column(String(64))
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)
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)
next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
class ScheduleRun(Base):
__tablename__ = 'schedule_runs'
__table_args__ = (
Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'),
Index('ix_schedule_runs_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
trigger_type: Mapped[str] = mapped_column(String(16), default='cron')
triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
total_count: Mapped[int] = mapped_column(Integer, default=0)
success_count: Mapped[int] = mapped_column(Integer, default=0)
failed_count: Mapped[int] = mapped_column(Integer, default=0)
skipped_count: Mapped[int] = mapped_column(Integer, default=0)
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)
error_message: Mapped[Optional[str]] = mapped_column(Text)
excel_file_path: Mapped[Optional[str]] = mapped_column(Text)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
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)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
+202
View File
@@ -87,6 +87,208 @@ class DifyService:
return f"{base}/chat-messages"
return f"{base}/v1/chat-messages"
@staticmethod
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
def _convert(v):
if v is None:
return ""
if isinstance(v, dict):
return {kk: _convert(vv) for kk, vv in v.items()}
if isinstance(v, list):
return [_convert(i) for i in v]
return str(v)
return {k: _convert(v) for k, v in (inputs or {}).items()}
@staticmethod
def _build_workflow_url(base_url: str) -> str:
base = str(base_url or "").strip().rstrip("/")
if not base:
return "/v1/workflows/run"
if base.endswith("/v1/workflows/run"):
base = base[: -len("/v1/workflows/run")].rstrip("/")
elif base.endswith("/workflows/run"):
base = base[: -len("/workflows/run")].rstrip("/")
if base.endswith("/v1"):
return f"{base}/workflows/run"
return f"{base}/v1/workflows/run"
@staticmethod
def run_workflow_streaming(
*,
agent,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_workflow_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[workflow-streaming] start user=%s agent_id=%s url=%s",
user,
getattr(agent, "id", None),
url,
)
result: dict[str, Any] = {}
workflow_run_id: str | None = None
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
)
resp.raise_for_status()
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
if event_type == "workflow_started":
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
workflow_run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
except requests.exceptions.RequestException as exc:
if result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured",
)
elif workflow_run_id:
if current_app:
current_app.logger.warning(
"[workflow-streaming] connection dropped, polling result for run_id=%s",
workflow_run_id,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
)
else:
if current_app:
current_app.logger.error(
"[workflow-streaming] request error (no run_id): %s",
exc,
)
raise
return result if isinstance(result, dict) else {}
@staticmethod
def _poll_workflow_result(
*,
agent,
workflow_run_id: str,
max_wait: int = 300,
interval: int = 10,
) -> dict[str, Any]:
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
base = str(base_url).strip().rstrip("/")
if base.endswith("/v1/workflows/run"):
base = base[: -len("/v1/workflows/run")].rstrip("/")
elif base.endswith("/workflows/run"):
base = base[: -len("/workflows/run")].rstrip("/")
if base.endswith("/v1"):
poll_url = f"{base}/workflows/run/{workflow_run_id}"
else:
poll_url = f"{base}/v1/workflows/run/{workflow_run_id}"
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
elapsed = 0
while elapsed < max_wait:
time.sleep(interval)
elapsed += interval
try:
resp = requests.get(poll_url, headers=headers, timeout=(5, 30))
if not resp.ok:
if current_app:
current_app.logger.warning(
"[workflow-poll] status=%s url=%s",
resp.status_code, poll_url,
)
continue
data = resp.json() if resp.content else {}
status = data.get("status", "")
if current_app:
current_app.logger.info(
"[workflow-poll] run_id=%s status=%s elapsed=%ds",
workflow_run_id, status, elapsed,
)
if status in ("succeeded", "failed", "stopped"):
return data
except requests.exceptions.RequestException as exc:
if current_app:
current_app.logger.warning(
"[workflow-poll] request error: %s",
exc,
)
continue
if current_app:
current_app.logger.error(
"[workflow-poll] timed out after %ds run_id=%s",
max_wait, workflow_run_id,
)
return {}
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""
+8 -2
View File
@@ -118,6 +118,9 @@ class HRLeaveSQLServerService:
raise RuntimeError("pyodbc 未安装,无法连接 HR SQL Server") from exc
driver = os.getenv("HR_SQLSERVER_DRIVER", "").strip() or cls._pick_driver(pyodbc)
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = cls._pick_driver(pyodbc)
server = os.getenv("HR_SQLSERVER_HOST", "192.168.100.191").strip()
port = os.getenv("HR_SQLSERVER_PORT", "1433").strip()
database = os.getenv("HR_SQLSERVER_DATABASE", "NH_N8_HEXIN").strip()
@@ -133,9 +136,12 @@ class HRLeaveSQLServerService:
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
if driver != "SQL Server":
conn_str += (
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
return pyodbc.connect(conn_str, timeout=timeout)
@staticmethod
+81 -35
View File
@@ -14,6 +14,32 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
return None
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id or not row.get("found"):
return None
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
return None
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
return key, normalized
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
@@ -37,14 +63,13 @@ class IntegrationApiService:
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
public_base = ""
# For server-side lookups, always prefer the explicitly configured
# integration service endpoint when present. Falling back to the current
# request host would incorrectly call this backend itself.
if configured:
return configured
if mode != "external":
# For server-side lookups inside containers/workers, an explicit integration
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
if configured and (
not has_request_context()
or IntegrationApiService._is_loopback_url(public_base)
):
return configured
if public_base:
return public_base
if has_request_context():
@@ -113,16 +138,55 @@ class IntegrationApiService:
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code != 200:
return None
payload = resp.json()
if not isinstance(payload, dict):
return None
IntegrationApiService._cache[cache_key] = payload
return payload
if resp.status_code == 200:
payload = resp.json()
if isinstance(payload, dict):
IntegrationApiService._cache[cache_key] = payload
return payload
elif has_app_context():
current_app.logger.info(
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
resp.status_code,
)
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
batch_url = f"{base_url}/api/integration/dify-files/resolve"
batch_headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
batch_body = {
"items": [
{
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
]
}
try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code != 200:
return None
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, list):
return None
for row in data:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
if key == cache_key:
return normalized
return None
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
return None
@staticmethod
@@ -199,28 +263,10 @@ class IntegrationApiService:
for row in data:
if not isinstance(row, dict):
continue
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
if not row.get("found"):
continue
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
continue
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
+113 -18
View File
@@ -101,20 +101,35 @@ class OALeaveWorkflowService:
'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': action,
}
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
except requests.RequestException as exc:
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
try:
return ET.fromstring(response.text)
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@classmethod
def resolve_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
@@ -166,8 +181,22 @@ class OALeaveWorkflowService:
'employee_id': matched['employeeId'],
'user_id': matched['uid'],
'name': matched['name'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@classmethod
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
@@ -214,13 +243,20 @@ class OALeaveWorkflowService:
if show_node is None:
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
show_node.text = str(show_value)
# 强制将字段设为可编辑和可见,防止OA流程节点中被配置为只读导致无法写入
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is None:
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
node.text = 'true'
@classmethod
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
@@ -301,6 +337,54 @@ class OALeaveWorkflowService:
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
@@ -345,9 +429,20 @@ class OALeaveWorkflowService:
@classmethod
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
request_id = cls._parse_create_response(root)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
return {
'ok': True,
'request_id': request_id,
+100 -15
View File
@@ -21,6 +21,9 @@ class OASQLServerService:
@classmethod
def _connect(cls):
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = cls._pick_driver()
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
@@ -36,9 +39,12 @@ class OASQLServerService:
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
if driver != "SQL Server":
conn_str += (
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
return pyodbc.connect(conn_str, timeout=timeout)
@classmethod
@@ -62,10 +68,16 @@ class OASQLServerService:
# Fetch page
# Compatible with older SQL Server versions (2008/2012)
query_sql = """
SELECT id, workcode, lastname
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
departmentname, subcompanyname, jobtitlename
FROM (
SELECT id, workcode, lastname, ROW_NUMBER() OVER(ORDER BY id) as rn
FROM userInfo_view
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename,
ROW_NUMBER() OVER(ORDER BY v.id) as rn
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE 1=1
"""
if keyword:
@@ -82,9 +94,15 @@ class OASQLServerService:
items = []
for row in cursor.fetchall():
items.append({
"uid": str(row.id),
"employeeId": str(row.workcode),
"name": str(row.lastname)
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": str(row.lastname) if row.lastname is not None else "",
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
})
return {
@@ -110,10 +128,14 @@ class OASQLServerService:
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
query_sql = """
SELECT TOP 1 id, workcode, lastname
FROM userInfo_view
WHERE workcode = ? AND lastname = ?
ORDER BY id
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE v.workcode = ? AND v.lastname = ?
ORDER BY v.id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
@@ -121,12 +143,75 @@ class OASQLServerService:
return None
return {
"uid": str(row.id),
"employeeId": str(row.workcode),
"name": str(row.lastname),
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": str(row.lastname) if row.lastname is not None else "",
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_department_name(cls, department_id: str) -> str:
if not department_id or not department_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
[department_id.strip()],
)
row = cursor.fetchone()
return str(row.departmentname).strip() if row and row.departmentname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_subcompany_name(cls, subcompany_id: str) -> str:
if not subcompany_id or not subcompany_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
[subcompany_id.strip()],
)
row = cursor.fetchone()
return str(row.subcompanyname).strip() if row and row.subcompanyname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
if not jobtitle_id or not jobtitle_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return str(row.jobtitlename).strip() if row and row.jobtitlename else ""
finally:
try:
cursor.close()
finally:
connection.close()
+114 -17
View File
@@ -3,6 +3,8 @@ import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
@@ -13,6 +15,8 @@ from app.services.text2sql import Text2SQLService
class PLMOracleService:
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
_MAX_RESULT_ROWS = 50
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
@@ -184,6 +188,114 @@ select *
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
@classmethod
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
for value in (storage_id, file_path, file_id):
text = str(value or "").strip()
if not text:
continue
parts.append(text.replace("/", "\\").strip("\\"))
return "\\".join(part for part in parts if part)
@classmethod
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
def raw(column_name: str):
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return None
value = row[idx]
return None if value in (None, "") else value
file_name = str(raw("NAME") or "").strip()
if not file_name:
return "-"
storage_id = raw("STORAGEID")
file_path = raw("FILEPATH")
file_id = str(raw("ID") or "").strip()
if not storage_id or file_path is None or not file_id:
return escape(file_name)
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
return f'<a href="{preview_href}">{escape(file_name)}</a>'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
@classmethod
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return "-"
value = row[idx]
if value in (None, ""):
return "-"
upper_name = column_name.upper()
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if upper_name == "FILESIZE":
return cls._format_size(value)
if upper_name == "NAME":
return cls._render_file_name(row, index_map)
return str(value)
@classmethod
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
parts = [f"记录 {row_no}"]
for column_name in cls._SUMMARY_COLUMNS:
if column_name.upper() not in index_map:
continue
rendered = cls._render_column_value(row, column_name, index_map)
label = {
"NAME": "文件名",
"EXTENTIONNAME": "扩展名",
"FILETYPE": "文件类型",
"FILESIZE": "文件大小",
"RELATIVEPATH": "相对路径",
"LASTACCESSTIME": "最后访问时间",
}.get(column_name.upper(), column_name)
if column_name.upper() == "NAME":
parts.append(f"{label}: {rendered}")
else:
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
return " | ".join(parts)
@classmethod
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
rows_html = []
for column_name in columns:
rendered_value = cls._render_column_value(row, column_name, index_map)
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
rows_html.append(
"<tr>"
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
"</tr>"
)
summary_html = cls._build_record_summary(row, index_map, row_no)
return (
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
"<div style=\"margin-top:10px;overflow:auto;\">"
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
"<thead><tr>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
"</tr></thead>"
f"<tbody>{''.join(rows_html)}</tbody>"
"</table>"
"</div>"
"</details>"
)
@classmethod
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
if not rows:
@@ -193,29 +305,14 @@ select *
visible_rows = rows[: cls._MAX_RESULT_ROWS]
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
def pick(row: tuple, column_name: str, default: str = "-") -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return default
value = row[idx]
if column_name.upper() in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if column_name.upper() == "FILESIZE":
return cls._format_size(value)
return "-" if value in (None, "") else str(value)
lines = [
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
+ ("(仅展示前 50 条)" if overflow else "。"),
"",
"| 序号 | 文件名 | 扩展名 | 文件类型 | 文件大小 | 相对路径 | 最后访问时间 |",
"| --- | --- | --- | --- | --- | --- | --- |",
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
]
for idx, row in enumerate(visible_rows, start=1):
lines.append(
f"| {idx} | {pick(row, 'NAME')} | {pick(row, 'EXTENTIONNAME')} | {pick(row, 'FILETYPE')} | "
f"{pick(row, 'FILESIZE')} | {pick(row, 'RELATIVEPATH')} | {pick(row, 'LASTACCESSTIME')} |"
)
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
if overflow:
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
+133
View File
@@ -0,0 +1,133 @@
from __future__ import annotations
import requests
from typing import Any, Callable
from urllib.parse import urlparse
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
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
def normalize_platform_api_path(path: str | None) -> str:
value = str(path or "").strip()
if not value:
return ""
parsed = urlparse(value)
if parsed.scheme in {"http", "https"}:
return value
if not value.startswith("/"):
value = "/" + value
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")
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
if not host:
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip()
database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip()
username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip()
password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip()
driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip()
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 = (
f"DRIVER={{{driver}}};"
f"SERVER={host},{port};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
return run_rohs_doc_check_dify_job(
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"),
wait_seconds=task.wait_seconds or 120,
run_id=run.id,
)
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
"default": _run_common_executor,
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
}
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 resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
path = normalize_platform_api_path(task.platform_api_path)
if path:
lookup_key = path.lstrip("/").lower()
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
@@ -0,0 +1,52 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from openpyxl import Workbook
def _flatten_value(v: Any) -> Any:
if isinstance(v, (dict, list)):
return json.dumps(v, ensure_ascii=False)
return v
def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]:
if not details:
return None, None, 0
out_root = Path(root_dir)
out_root.mkdir(parents=True, exist_ok=True)
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)
headers: list[str] = []
for row in rows:
for k in row:
if k not in headers:
headers.append(k)
wb = Workbook()
ws = wb.active
ws.title = 'result'
ws.append(headers)
for row in rows:
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)
@@ -0,0 +1,37 @@
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>"
)
@@ -0,0 +1,129 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
return {
'id': task.id,
'schedule_no': task.schedule_no,
'name': task.name,
'schedule_type': task.schedule_type,
'owner_user_id': task.owner_user_id,
'owner_username': task.owner.username if task.owner else None,
'cron_expr': task.cron_expr,
'wait_seconds': task.wait_seconds,
'dify_agent_id': task.dify_agent_id,
'platform_api_path': task.platform_api_path,
'notify_user_ids_json': task.notify_user_ids_json or [],
'notify_enabled': bool(task.notify_enabled),
'enabled': bool(task.enabled),
'next_run_at': task.next_run_at.isoformat() if task.next_run_at else None,
'last_run_at': task.last_run_at.isoformat() if task.last_run_at else None,
'last_status': last_status,
'created_at': task.created_at.isoformat() if task.created_at else None,
'updated_at': task.updated_at.isoformat() if task.updated_at else None,
}
def serialize_run(run: ScheduleRun) -> dict:
return {
'id': run.id,
'run_no': run.run_no,
'schedule_task_id': run.schedule_task_id,
'schedule_name': run.task.name if run.task else None,
'trigger_type': run.trigger_type,
'triggered_by_user_id': run.triggered_by_user_id,
'started_at': run.started_at.isoformat() if run.started_at else None,
'finished_at': run.finished_at.isoformat() if run.finished_at else None,
'duration_ms': run.duration_ms,
'status': run.status,
'total_count': run.total_count,
'success_count': run.success_count,
'failed_count': run.failed_count,
'skipped_count': run.skipped_count,
'api_request_json': run.api_request_json,
'api_response_json': run.api_response_json,
'response_summary_json': run.response_summary_json,
'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,
'created_at': run.created_at.isoformat() if run.created_at else None,
}
def list_tasks() -> list[dict]:
latest_run_subquery = (
db.session.query(
ScheduleRun.schedule_task_id.label('task_id'),
func.max(ScheduleRun.id).label('last_run_id'),
)
.group_by(ScheduleRun.schedule_task_id)
.subquery()
)
rows = (
db.session.query(ScheduleTask, ScheduleRun.status.label('last_status'))
.options(joinedload(ScheduleTask.owner))
.outerjoin(latest_run_subquery, latest_run_subquery.c.task_id == ScheduleTask.id)
.outerjoin(ScheduleRun, ScheduleRun.id == latest_run_subquery.c.last_run_id)
.order_by(ScheduleTask.created_at.desc())
.all()
)
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
def list_runs(
*,
task_id: Optional[int] = None,
owner_user_id: Optional[int] = None,
notify_user_id: Optional[int] = None,
schedule_name: Optional[str] = None,
status: Optional[str] = None,
started_after: Optional[datetime] = None,
started_before: Optional[datetime] = None,
limit: int = 100,
) -> list[dict]:
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
if schedule_name:
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
if status:
query = query.filter(ScheduleRun.status == status)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= started_after)
if started_before is not None:
query = query.filter(ScheduleRun.started_at < started_before)
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None:
query = query.filter(
(ScheduleTask.owner_user_id == notify_user_id)
| ScheduleTask.notify_user_ids_json.cast(db.String).ilike(f'%{notify_user_id}%')
)
runs = query.order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 500))).all()
return [serialize_run(r) for r in runs]
def get_run(run_id: int) -> ScheduleRun | None:
return db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).filter(ScheduleRun.id == run_id).first()
def can_view_run(run: ScheduleRun, user_id: int) -> bool:
task = run.task
if not task:
return False
if task.owner_user_id == user_id:
return True
notify = task.notify_user_ids_json or []
return int(user_id) in {int(x) for x in notify if str(x).isdigit()}
@@ -0,0 +1,352 @@
from __future__ import annotations
import threading
import time
import uuid
from datetime import datetime
from typing import Any
from croniter import croniter
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.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()
_cancelled_runs: set[int] = set()
_cancel_lock = threading.Lock()
def request_cancel_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.add(run_id)
def is_run_cancelled(run_id: int) -> bool:
with _cancel_lock:
return run_id in _cancelled_runs
def clear_cancelled_run(run_id: int) -> None:
with _cancel_lock:
_cancelled_runs.discard(run_id)
def _generate_schedule_no() -> str:
return f"SCH{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
def _generate_run_no() -> str:
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
def create_task(
*,
name: str,
schedule_type: str,
owner_user_id: int,
cron_expr: str,
wait_seconds: int,
dify_agent_id: int | None,
platform_api_path: str | None,
notify_user_ids_json: list[int] | None,
notify_enabled: bool,
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,
schedule_type="platform_app",
owner_user_id=owner_user_id,
cron_expr=cron_expr,
wait_seconds=max(0, int(wait_seconds or 0)),
dify_agent_id=dify_agent_id,
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
notify_user_ids_json=notify_user_ids_json or [],
notify_enabled=bool(notify_enabled),
enabled=bool(enabled),
created_by=actor_id,
updated_by=actor_id,
)
if task.enabled and task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.enabled = False
db.session.add(task)
db.session.commit()
return task
def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask:
for key in [
"name",
"owner_user_id",
"cron_expr",
"wait_seconds",
"dify_agent_id",
"notify_enabled",
"enabled",
]:
if key in payload:
setattr(task, key, payload[key])
if "platform_api_path" in payload:
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
task.notify_user_ids_json = payload.get("notify_user_ids_json")
if not normalize_platform_api_path(task.platform_api_path):
raise ValueError("platform_api_path is required for platform_app")
task.schedule_type = "platform_app"
if task.enabled and task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
else:
task.next_run_at = None
task.updated_by = actor_id
db.session.commit()
return task
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
if run is None:
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if existing:
return existing
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type=trigger_type,
triggered_by_user_id=triggered_by_user_id,
started_at=datetime.utcnow(),
status="running",
)
db.session.add(run)
db.session.commit()
if task.cron_expr and trigger_type == "cron":
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
db.session.commit()
start_ts = time.time()
try:
executor = resolve_schedule_executor(task)
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
except Exception as exc:
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
if is_run_cancelled(run.id):
run.finished_at = datetime.utcnow()
run.duration_ms = int((time.time() - start_ts) * 1000)
run.status = "failed"
run.error_message = "排程已被删除,执行中断"
db.session.commit()
clear_cancelled_run(run.id)
return run
duration_ms = int((time.time() - start_ts) * 1000)
if current_app:
current_app.logger.info(
"[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
)
if total_count == 0 and not errors:
status = "success"
run.error_message = "无待处理数据"
elif failed_count == 0:
status = "success"
elif success_count == 0:
status = "failed"
else:
status = "partial_failed"
try:
file_path, 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,
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
)
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
errors.append(f"Excel导出失败: {excel_exc}")
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.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_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:
if current_app:
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
task.last_run_at = datetime.utcnow()
db.session.commit()
return run
def start_scheduler(app):
global _worker_started
with _worker_lock:
if _worker_started:
return
_worker_started = True
if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)):
return
import os
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not app.debug:
pass
else:
_worker_started = False
return
def _loop():
with app.app_context():
stale = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= datetime.utcnow(),
).all()
for t in stale:
if t.cron_expr:
try:
it = croniter(t.cron_expr, datetime.utcnow())
t.next_run_at = it.get_next(datetime)
except Exception:
t.next_run_at = None
t.enabled = False
else:
t.next_run_at = None
if stale:
db.session.commit()
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
stuck = db.session.query(ScheduleRun).filter(
ScheduleRun.status == "running",
).all()
for r in stuck:
r.status = "failed"
r.error_message = "服务重启,执行中断"
r.finished_at = datetime.utcnow()
if stuck:
db.session.commit()
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
while True:
try:
now = datetime.utcnow()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
).limit(5).with_for_update(skip_locked=True).all()
for task in due_tasks:
has_running = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",
).first()
if has_running:
if task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
db.session.commit()
continue
try:
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
except Exception as e:
current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True)
db.session.rollback()
if task.cron_expr:
try:
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.enabled = False
else:
task.next_run_at = None
db.session.commit()
except Exception:
db.session.rollback()
time.sleep(30)
t = threading.Thread(target=_loop, daemon=True, name="schedule-worker")
t.start()
@@ -0,0 +1,186 @@
from __future__ import annotations
from typing import Any
from flask import current_app
from app.services.dify import DifyService
try:
import pyodbc # type: ignore
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')
return pyodbc.connect(conn_str, timeout=15)
def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]:
conn = _connect(conn_str)
try:
cur = conn.cursor()
cur.execute(FIXED_ROHS_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]
finally:
conn.close()
def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> 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)),
)
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 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]]:
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)
details: list[dict[str, Any]] = []
success_count = 0
failed_count = 0
skipped_count = 0
errors: list[str] = []
from app.services.schedule.scheduler_service import is_run_cancelled
for idx, row in enumerate(rows):
if run_id is not None and is_run_cancelled(run_id):
item = dict(row)
item.update({"judgement": "人工判定", "reason": "排程已被删除,执行中断", "writeback_ok": False, "error": "排程已被删除,执行中断"})
skipped_count += 1
details.append(item)
continue
item = dict(row)
dify_ok = False
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_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
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 {}})
failed_count += 1
errors.append(f"Dify row_id={row.get('id')}: {err_detail}")
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,
)
judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {})
item["dify_output"] = outputs if isinstance(outputs, dict) else {}
dify_ok = True
else:
judgement = "人工判定"
reason = "未配置 Agent ID,跳过 Dify"
dify_ok = True
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")})
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)})
if dify_ok:
failed_count += 1
errors.append(f"writeback row_id={row.get('id')}: {wb_exc}")
except Exception as exc:
judgement = "人工判定"
reason = f"执行异常:{exc}"
item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(exc)})
failed_count += 1
errors.append(str(exc))
try:
writeback_rohs(
conn_str,
row_id=str(row.get("id")),
run_no=run_no,
judgement=judgement,
reason=reason,
)
item["writeback_ok"] = True
except Exception as wb_exc:
item["writeback_ok"] = False
item["error"] = f"{item.get('error', '')}; writeback failed: {wb_exc}"
details.append(item)
total_count = success_count + failed_count + skipped_count
return total_count, success_count, failed_count, skipped_count, details, errors
@@ -0,0 +1,24 @@
"""merge chatlog and schedule heads
Revision ID: c0ae052bd24e
Revises: 1ebc0253f9f6, f6d4e5f6a7b8
Create Date: 2026-05-18 16:32:50.696073
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c0ae052bd24e'
down_revision = ('1ebc0253f9f6', 'f6d4e5f6a7b8')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,24 @@
"""merge heads
Revision ID: dc9a4a2683df
Revises: 2a4b6c8d0e1f, f5c3d4e5a6b7
Create Date: 2026-05-16 15:11:20.476298
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'dc9a4a2683df'
down_revision = ('2a4b6c8d0e1f', 'f5c3d4e5a6b7')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,111 @@
"""add schedule tables
Revision ID: f3a1b2c3d4e5
Revises: f2b3c4d5e6f7
Create Date: 2026-05-15 20:30:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f3a1b2c3d4e5'
down_revision = 'f2b3c4d5e6f7'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'schedule_tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('schedule_no', sa.String(length=64), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('schedule_type', sa.String(length=32), nullable=False),
sa.Column('owner_user_id', sa.Integer(), nullable=False),
sa.Column('cron_expr', sa.String(length=64), nullable=False),
sa.Column('wait_seconds', sa.Integer(), nullable=False),
sa.Column('dify_agent_id', sa.Integer(), nullable=True),
sa.Column('notify_user_ids_json', sa.JSON(), nullable=True),
sa.Column('notify_enabled', sa.Boolean(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('next_run_at', sa.DateTime(), nullable=True),
sa.Column('last_run_at', sa.DateTime(), nullable=True),
sa.Column('created_by', sa.Integer(), nullable=True),
sa.Column('updated_by', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['created_by'], ['users.id'], ),
sa.ForeignKeyConstraint(['dify_agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['updated_by'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_schedule_tasks_enabled'), 'schedule_tasks', ['enabled'], unique=False)
op.create_index(op.f('ix_schedule_tasks_enabled_next_run'), 'schedule_tasks', ['enabled', 'next_run_at'], unique=False)
op.create_index(op.f('ix_schedule_tasks_id'), 'schedule_tasks', ['id'], unique=False)
op.create_index(op.f('ix_schedule_tasks_name'), 'schedule_tasks', ['name'], unique=False)
op.create_index(op.f('ix_schedule_tasks_next_run_at'), 'schedule_tasks', ['next_run_at'], unique=False)
op.create_index(op.f('ix_schedule_tasks_owner_user_id'), 'schedule_tasks', ['owner_user_id'], unique=False)
op.create_index(op.f('ix_schedule_tasks_schedule_no'), 'schedule_tasks', ['schedule_no'], unique=True)
op.create_table(
'schedule_runs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('run_no', sa.String(length=64), nullable=False),
sa.Column('schedule_task_id', sa.Integer(), nullable=False),
sa.Column('trigger_type', sa.String(length=16), nullable=False),
sa.Column('triggered_by_user_id', sa.Integer(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('finished_at', sa.DateTime(), nullable=True),
sa.Column('duration_ms', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('total_count', sa.Integer(), nullable=False),
sa.Column('success_count', sa.Integer(), nullable=False),
sa.Column('failed_count', sa.Integer(), nullable=False),
sa.Column('skipped_count', sa.Integer(), nullable=False),
sa.Column('response_summary_json', sa.JSON(), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('excel_file_path', sa.Text(), nullable=True),
sa.Column('excel_file_name', sa.String(length=255), nullable=True),
sa.Column('excel_file_size', sa.Integer(), nullable=True),
sa.Column('mail_sent', sa.Boolean(), nullable=False),
sa.Column('mail_sent_at', sa.DateTime(), nullable=True),
sa.Column('mail_error', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['schedule_task_id'], ['schedule_tasks.id'], ),
sa.ForeignKeyConstraint(['triggered_by_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_schedule_runs_created_at'), 'schedule_runs', ['created_at'], unique=False)
op.create_index(op.f('ix_schedule_runs_finished_at'), 'schedule_runs', ['finished_at'], unique=False)
op.create_index(op.f('ix_schedule_runs_id'), 'schedule_runs', ['id'], unique=False)
op.create_index(op.f('ix_schedule_runs_run_no'), 'schedule_runs', ['run_no'], unique=True)
op.create_index(op.f('ix_schedule_runs_schedule_task_id'), 'schedule_runs', ['schedule_task_id'], unique=False)
op.create_index(op.f('ix_schedule_runs_started_at'), 'schedule_runs', ['started_at'], unique=False)
op.create_index(op.f('ix_schedule_runs_status'), 'schedule_runs', ['status'], unique=False)
op.create_index(op.f('ix_schedule_runs_status_created'), 'schedule_runs', ['status', 'created_at'], unique=False)
op.create_index(op.f('ix_schedule_runs_task_created'), 'schedule_runs', ['schedule_task_id', 'created_at'], unique=False)
def downgrade():
op.drop_index(op.f('ix_schedule_runs_task_created'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_status_created'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_status'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_started_at'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_schedule_task_id'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_run_no'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_id'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_finished_at'), table_name='schedule_runs')
op.drop_index(op.f('ix_schedule_runs_created_at'), table_name='schedule_runs')
op.drop_table('schedule_runs')
op.drop_index(op.f('ix_schedule_tasks_schedule_no'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_owner_user_id'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_next_run_at'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_name'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_id'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_enabled_next_run'), table_name='schedule_tasks')
op.drop_index(op.f('ix_schedule_tasks_enabled'), table_name='schedule_tasks')
op.drop_table('schedule_tasks')
@@ -0,0 +1,25 @@
"""add platform_api_path to schedule_tasks
Revision ID: f4b2c3d4e5f6
Revises: f3a1b2c3d4e5
Create Date: 2026-05-16 17:20:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f4b2c3d4e5f6'
down_revision = 'f3a1b2c3d4e5'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_tasks', sa.Column('platform_api_path', sa.String(length=500), nullable=True))
def downgrade():
op.drop_column('schedule_tasks', 'platform_api_path')
@@ -0,0 +1,26 @@
"""fix schedule_tasks indexes and defaults
Revision ID: f5c3d4e5a6b7
Revises: f4b2c3d4e5f6
Create Date: 2026-06-15 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'f5c3d4e5a6b7'
down_revision = 'f4b2c3d4e5f6'
branch_labels = None
depends_on = None
def upgrade():
op.create_index(op.f('ix_schedule_tasks_dify_agent_id'), 'schedule_tasks', ['dify_agent_id'], unique=False)
op.execute("UPDATE schedule_tasks SET schedule_type = 'platform_app' WHERE schedule_type = 'dify_app'")
op.execute("UPDATE schedule_tasks SET notify_user_ids_json = '[]'::jsonb WHERE notify_user_ids_json IS NULL")
def downgrade():
op.drop_index(op.f('ix_schedule_tasks_dify_agent_id'), table_name='schedule_tasks')
@@ -0,0 +1,25 @@
"""add api request and response to schedule_runs
Revision ID: f6d4e5f6a7b8
Revises: dc9a4a2683df
Create Date: 2026-06-16 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'f6d4e5f6a7b8'
down_revision = 'dc9a4a2683df'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('schedule_runs', sa.Column('api_request_json', sa.JSON(), nullable=True))
op.add_column('schedule_runs', sa.Column('api_response_json', sa.JSON(), nullable=True))
def downgrade():
op.drop_column('schedule_runs', 'api_response_json')
op.drop_column('schedule_runs', 'api_request_json')
+1
View File
@@ -33,3 +33,4 @@ python-pptx==1.0.2
beautifulsoup4==4.14.2
lxml==6.0.2
typer==0.17.4
croniter
+87
View File
@@ -0,0 +1,87 @@
from app import db
from app.models import Agent, ScheduleRun, ScheduleTask, User
def _mk_admin():
admin = User(username='admin', email='admin@example.com', role='admin', status='active')
admin.set_password('x')
db.session.add(admin)
return admin
def _mk_user(name: str, email: str):
user = User(username=name, email=email, role='user', status='active')
user.set_password('x')
db.session.add(user)
return user
def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
with app.app_context():
_mk_admin()
owner = _mk_user('owner_u', 'owner@example.com')
notify = _mk_user('notify_u', 'notify@example.com')
other = _mk_user('other_u', 'other@example.com')
agent = Agent(name='dify-agent', dify_api_key='k', api_base_url='http://localhost:5001/v1', type='api')
db.session.add(agent)
db.session.commit()
owner_id = owner.id
notify_id = notify.id
other_id = other.id
agent_id = agent.id
create_res = client.post('/api/admin/schedules', headers=admin_headers, json={
'name': 'rohs-schedule',
'schedule_type': 'dify_app',
'owner_user_id': owner_id,
'cron_expr': '0 */30 * * *',
'wait_seconds': 5,
'dify_agent_id': agent_id,
'notify_user_ids_json': [notify_id],
'notify_enabled': True,
'enabled': True,
})
assert create_res.status_code == 201
task = create_res.get_json()
task_id = task['id']
list_res = client.get('/api/admin/schedules', headers=admin_headers)
assert list_res.status_code == 200
assert any(x['id'] == task_id for x in list_res.get_json())
with app.app_context():
run = ScheduleRun(
run_no='RUNTEST001',
schedule_task_id=task_id,
trigger_type='manual',
status='success',
total_count=1,
success_count=1,
failed_count=0,
skipped_count=0,
duration_ms=100,
mail_sent=False,
)
db.session.add(run)
db.session.commit()
run_id = run.id
owner_headers = {'X-Username': 'owner_u', 'Content-Type': 'application/json'}
notify_headers = {'X-Username': 'notify_u', 'Content-Type': 'application/json'}
other_headers = {'X-Username': 'other_u', 'Content-Type': 'application/json'}
owner_runs = client.get('/api/workspace/schedule-runs', headers=owner_headers)
assert owner_runs.status_code == 200
assert any(r['id'] == run_id for r in owner_runs.get_json())
notify_runs = client.get('/api/workspace/schedule-runs', headers=notify_headers)
assert notify_runs.status_code == 200
assert any(r['id'] == run_id for r in notify_runs.get_json())
other_runs = client.get('/api/workspace/schedule-runs', headers=other_headers)
assert other_runs.status_code == 200
assert all(r['id'] != run_id for r in other_runs.get_json())
denied = client.get(f'/api/workspace/schedule-runs/{run_id}', headers=other_headers)
assert denied.status_code == 403
+19 -16
View File
@@ -35,29 +35,32 @@
\| d072003 | int | - | 已休育儿假时数 |
\| d072004 | int | - | 未休育儿假时数 |
# OA数据对接AI知识库-请假流程相关视图
- DB:192.168.100.225:1433
- UserName:AI_Knowledge_Base_OA
- Password:hoo-thai@123_AI_OA
- UserName:AI\_Knowledge\_Base\_OA
- Password:hoo-thai\@123\_AI\_OA
- 默认数据库:ecology
## 用途:流程当前节点视图
- 视图:v_workflow_requestbase
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
| --- | --- | --- | --- |
| requestid | int | int | 流程ID |
| status | varchar | varchar(500) | 流程状态 |
| workflowid | int | int | 流程类型ID |
| nodename | varchar | varchar(1000) | 当前节点名称 |
- 视图:v\_workflow\_requestbase
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
| ---------- | ------- | ------------- | ------ |
| requestid | int | int | 流程ID |
| status | varchar | varchar(500) | 流程状态 |
| workflowid | int | int | 流程类型ID |
| nodename | varchar | varchar(1000) | 当前节点名称 |
## 用途:员工信息视图
- 视图:userInfo_view
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
| --- | --- | --- | --- |
| workcode | varchar | varchar(1000) | 员工工号 |
| lastname | varchar | varchar(1000) | 员工姓名 |
| id | int | int | 员工ID |
- 视图:userInfo\_view
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
| ----------------- | ------- | ------------- | ------ |
| workcode | varchar | varchar(1000) | 员工工号 |
| lastname | varchar | varchar(1000) | 员工姓名 |
| id | int | int | 员工ID |
| **jobtitle** | int | int | 岗位ID |
| **departmentid** | int | int | 所属部门ID |
| **subcompanyid1** | int | int | 所属分部ID |
+2 -2
View File
@@ -8,8 +8,8 @@ pnpm-debug.log*
lerna-debug.log*
node_modules
#dist
#dist-ssr
dist
dist-ssr
docs
*.local
+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-grYi-CaK.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DvLiupE9.css">
<script type="module" crossorigin src="/assets/index-CsJr350M.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bir-WxSG.css">
</head>
<body>
<div id="app"></div>␍
+97
View File
@@ -0,0 +1,97 @@
import { getAuthHeaders } from '../utils/auth';
export interface ScheduleTask {
id: number;
schedule_no: string;
name: string;
schedule_type: string;
owner_user_id: number;
owner_username?: string | null;
cron_expr: string;
wait_seconds: number;
dify_agent_id?: number | null;
platform_api_path?: string | null;
notify_user_ids_json: number[];
notify_enabled: boolean;
enabled: boolean;
next_run_at?: string | null;
last_run_at?: string | null;
last_status?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export interface ScheduleRun {
id: number;
run_no: string;
schedule_task_id: number;
schedule_name?: string | null;
trigger_type: string;
started_at?: string | null;
finished_at?: string | null;
duration_ms: number;
status: string;
total_count: number;
success_count: number;
failed_count: number;
api_request_json?: Record<string, any> | null;
api_response_json?: Record<string, any> | null;
response_summary_json?: Record<string, any> | 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;
created_at?: string | null;
}
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>) =>
fetch('/api/admin/schedules', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask>) =>
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',
headers: getAuthHeaders(),
});
export const runAdminSchedule = (id: number) =>
fetch(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
export const toggleAdminSchedule = (id: number, enabled: boolean) =>
fetch(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => {
const sp = new URLSearchParams();
if (params?.status) sp.set('status', params.status);
if (params?.started_after) sp.set('started_after', params.started_after);
if (params?.started_before) sp.set('started_before', params.started_before);
const qs = sp.toString();
return getJson<ScheduleRun[]>(`/api/admin/schedules/${taskId}/runs${qs ? '?' + qs : ''}`);
};
export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/excel`;
export const listWorkspaceScheduleRuns = (params?: { status?: string; schedule_name?: string; started_after?: string; started_before?: string }) => {
const sp = new URLSearchParams();
if (params?.status) sp.set('status', params.status);
if (params?.schedule_name) sp.set('schedule_name', params.schedule_name);
if (params?.started_after) sp.set('started_after', params.started_after);
if (params?.started_before) sp.set('started_before', params.started_before);
const qs = sp.toString();
return getJson<ScheduleRun[]>(`/api/workspace/schedule-runs${qs ? '?' + qs : ''}`);
};
export const workspaceRunExcelUrl = (runId: number) => `/api/workspace/schedule-runs/${runId}/excel`;
Binary file not shown.

After

Width:  |  Height:  |  Size: 627 KiB

+79 -17
View File
@@ -10,6 +10,7 @@
*/
import { computed, ref, watch } from 'vue';
import { marked } from 'marked';
import * as XLSX from 'xlsx';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/docx/lib/index.css';
@@ -93,7 +94,9 @@ const needsOfficeFallback = computed(() => {
* - 其余返回原始 URL,由浏览器自行处理。
*/
const iframeSrc = computed(() => {
if (!props.file?.url || !props.agentId) return '';
if (!props.file?.url) return '';
if (officeObjectUrl.value) return officeObjectUrl.value;
if (!props.agentId) return '';
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
// These formats must use the authenticated fetch -> blob flow only.
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
@@ -102,6 +105,8 @@ const iframeSrc = computed(() => {
return props.file.url;
});
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
const close = () => emit('update:modelValue', false);
const isDownloading = ref(false);
@@ -198,19 +203,34 @@ const loadPdfContent = async () => {
throw new Error(err?.error || `HTTP ${res.status}`);
}
const buf = await res.arrayBuffer();
// const head = new TextDecoder().decode(buf.slice(0, 5));
// 暂时取消对 PDF header 的强校验,因为 docx 等文件也会调用该函数生成 Blob 并渲染在 iframe 或下载中
// if (head !== '%PDF-') {
// throw new Error('Invalid PDF binary from preview API');
// }
const blob = await res.blob();
clearOfficeObjectUrl();
let type = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) type = 'application/pdf';
else if (ext.value === 'docx') type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
let fallbackType = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
};
const blob = new Blob([buf], { type });
const loadBinaryContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for binary preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const blob = await res.blob();
clearOfficeObjectUrl();
officeObjectUrl.value = URL.createObjectURL(blob);
};
@@ -277,16 +297,44 @@ const loadContent = async () => {
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
limit: '100',
});
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
excelPreview.value = data as ExcelPreviewData;
const buffer = await res.arrayBuffer();
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
@@ -297,6 +345,20 @@ const loadContent = async () => {
return;
}
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
isLoading.value = true;
try {
await loadBinaryContent();
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
} catch (e: any) {
error.value = e?.message || 'Failed to load file preview';
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value !== 'markdown') return;
isLoading.value = true;
@@ -435,7 +497,7 @@ watch(
/>
</div>
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
<img :src="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
@@ -0,0 +1,71 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
const isLoading = ref(false);
const error = ref('');
const runs = ref<ScheduleRun[]>([]);
const loadRuns = async () => {
isLoading.value = true;
error.value = '';
try {
runs.value = await listWorkspaceScheduleRuns();
} catch (e: any) {
error.value = e?.message || '加载排程记录失败';
} finally {
isLoading.value = false;
}
};
onMounted(() => {
void loadRuns();
});
</script>
<template>
<div class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
<div class="mb-4 flex items-center justify-between">
<h3 class="text-lg font-semibold text-slate-900">排程记录</h3>
<button class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-50" @click="loadRuns">
刷新
</button>
</div>
<p class="mb-3 text-xs text-slate-500">仅展示你是 owner 或在通知名单中的记录</p>
<div v-if="isLoading" class="py-6 text-sm text-slate-500">加载中...</div>
<div v-else-if="error" class="py-6 text-sm text-rose-500">{{ error }}</div>
<div v-else-if="runs.length === 0" class="py-6 text-sm text-slate-400">暂无可见记录</div>
<div v-else class="overflow-x-auto">
<table class="w-full min-w-[920px] text-sm">
<thead>
<tr class="border-b border-slate-200 text-left text-slate-500">
<th class="px-2 py-2">执行单号</th>
<th class="px-2 py-2">排程</th>
<th class="px-2 py-2">开始</th>
<th class="px-2 py-2">结束</th>
<th class="px-2 py-2">状态</th>
<th class="px-2 py-2">处理</th>
<th class="px-2 py-2">成功</th>
<th class="px-2 py-2">失败</th>
<th class="px-2 py-2">Excel</th>
</tr>
</thead>
<tbody>
<tr v-for="run in runs" :key="run.id" class="border-b border-slate-100 text-slate-700">
<td class="px-2 py-2">{{ run.run_no }}</td>
<td class="px-2 py-2">{{ run.schedule_name || '-' }}</td>
<td class="px-2 py-2">{{ run.started_at || '-' }}</td>
<td class="px-2 py-2">{{ run.finished_at || '-' }}</td>
<td class="px-2 py-2">{{ run.status }}</td>
<td class="px-2 py-2">{{ run.total_count }}</td>
<td class="px-2 py-2">{{ run.success_count }}</td>
<td class="px-2 py-2">{{ run.failed_count }}</td>
<td class="px-2 py-2">
<a class="text-brand-600 hover:underline" :href="workspaceRunExcelUrl(run.id)" target="_blank">查看Excel</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
+9 -3
View File
@@ -40,7 +40,7 @@ const normalizeResources = (resources: any): RetrieverResource[] => {
return [];
};
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重和更新
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
const list = normalizeResources(resources);
if (list.length === 0) return;
@@ -48,11 +48,17 @@ const addRetrieverResources = (msg: ChatMessage, resources: any) => {
for (const item of list) {
// 使用稳定键进行去重,避免同一条来源在多事件中重复展示
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
const exists = msg.retriever_resources.some(
const existingIndex = msg.retriever_resources.findIndex(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (!exists) {
if (existingIndex < 0) {
msg.retriever_resources.push(item);
} else {
// 存在则合并,确保后续带有 enrich 链接的字段能覆盖进去
msg.retriever_resources[existingIndex] = {
...msg.retriever_resources[existingIndex],
...item
};
}
}
};
+3 -3
View File
@@ -1000,9 +1000,9 @@ const messages = {
},
landing: {
hero: {
prefix: '释放',
highlight: '生成式 AI 的强大力量',
subtitle: '获取一套专为企业需求打造的强大 AI 智能体,安全、可扩展且智能。'
prefix: '和信精密',
highlight: 'AI智能体 应用平台',
subtitle: 'AI的世界,期望让你开心工作,快乐生活。'
},
agent: {
role: 'AI 助手'
File diff suppressed because it is too large. Load diff
+258 -30
View File
@@ -143,7 +143,9 @@ const getSourceBrief = (item: any) => {
interface SourceFileLink {
name: string;
url: string;
url?: string;
datasetId?: string;
remoteDocumentId?: string;
}
// 源文件展示配置(来自 config.ts)
@@ -208,15 +210,18 @@ const isPreferredSourceLink = (url: string) => {
return PREFERRED_SOURCE_EXTS.has(ext);
};
const isNoisySourceUrl = (url: string) => {
const isNoisySourceUrl = (_url: string) => {
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
return false;
};
const isNoisySourceName = (name: string) => {
const isNoisySourceName = (_name: string) => {
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
const n = (name || '').trim().toLowerCase();
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
return false;
};
const looksLikeFileName = (name: string) => {
@@ -226,6 +231,41 @@ const looksLikeFileName = (name: string) => {
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
for (const item of payload) {
const found = findFirstByKeys(item, keyCandidates);
if (found) return found;
}
return '';
}
if (typeof payload !== 'object') return '';
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
for (const value of Object.values(payload)) {
const found = findFirstByKeys(value, keyCandidates);
if (found) return found;
}
return '';
};
const getResourceIds = (item: any) => {
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findFirstByKeys(item, [
'remote_document_id',
'dify_document_id',
'document_id',
'doc_id',
'source_document_id',
]);
return { datasetId, remoteDocumentId };
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
@@ -275,7 +315,21 @@ const extractUrlsFromText = (text: string) => {
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const item of resources) {
const { datasetId, remoteDocumentId } = getResourceIds(item);
const directCandidates = [
item?.source_download_url,
item?.url,
@@ -290,6 +344,20 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
].filter(Boolean) as string[];
const content = getSourceContent(item);
// 直接强制从对象的顶层属性里获取文件名和链接
const forceName = item?.source_filename || item?.document_name || item?.title;
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
if (forceName) {
const key = forceName;
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
@@ -309,23 +377,29 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
// if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
// Skip links whose display name itself is noisy.
if (isNoisySourceName(name)) continue;
// 根据配置决定是否显示 MD 文件
if ( (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
// Deduplicate by name if it looks like a filename, else by name + base URL
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
if (!map.has(key)) {
map.set(key, { name, url });
}
mergeSourceLink(key, {
name,
url,
...(datasetId ? { datasetId } : {}),
...(remoteDocumentId ? { remoteDocumentId } : {}),
});
}
}
const links = Array.from(map.values());
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
// return preferred.length > 0 ? preferred : links;
return links;
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
@@ -336,19 +410,33 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
const mergeMessageLink = (key: string, nextLink: SourceFileLink) => {
const existing = map.get(key);
if (!existing) {
map.set(key, nextLink);
return;
}
map.set(key, {
...existing,
...(nextLink.url ? { url: nextLink.url } : {}),
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
});
};
for (const link of links) {
if (isChunkLikeLink(link.url)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if ( (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (isMarkdownFileName(link.name)) {
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
if (!map.has(key)) map.set(key, link);
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
mergeMessageLink(key, link);
continue;
}
if (isNoisySourceUrl(link.url) && !looksLikeFileName(link.name)) continue;
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
if (!map.has(key)) map.set(key, link);
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
mergeMessageLink(key, link);
}
};
@@ -359,7 +447,7 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
}
const links = Array.from(map.values());
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
return preferred.length > 0 ? preferred : links;
};
@@ -381,7 +469,7 @@ const shouldExpandSourceDetails = (msg: any): boolean => {
// }
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url));
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
};
const shouldRenderMessage = (msg: any): boolean => {
@@ -413,11 +501,62 @@ const shouldShowThinkingBubble = computed(() => {
});
const filePreviewVisible = ref(false);
const previewFile = ref<SourceFileLink | null>(null);
const previewFile = ref<{ name: string; url: string } | null>(null);
const openPreview = (file: SourceFileLink) => {
previewFile.value = file;
filePreviewVisible.value = true;
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string }> => {
if (file.url) {
return {
name: file.name,
url: file.url,
};
}
if (!file.datasetId || !file.remoteDocumentId) {
throw new Error('当前源文件暂未返回可预览链接');
}
const params = new URLSearchParams({
agent_id: String(agentId),
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
headers: getAuthHeaders(),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data?.error || `HTTP ${response.status}`);
}
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (!resolvedUrl) {
throw new Error('未查询到源文件下载地址');
}
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
};
};
const openPreview = async (file: SourceFileLink) => {
try {
const resolvedFile = await resolveSourceLink(file);
previewFile.value = resolvedFile;
filePreviewVisible.value = true;
} catch (error: any) {
showMessageDialog('warning', error?.message || '当前源文件暂时无法预览');
}
};
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
const rawHref = (href || '').trim();
if (!rawHref.startsWith('#plm-preview?')) return null;
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
const name = (params.get('name') || '').trim();
const url = (params.get('url') || '').trim();
if (!name || !url) return null;
return { name, url };
};
const route = useRoute();
const router = useRouter();
@@ -535,11 +674,29 @@ interface LeaveRequestFormData {
applicantName: string;
employeeId: string;
applicantUid: string;
applicantJobTitle?: string;
applicantJobTitleName?: string;
applicantDepartmentId?: string;
applicantSubCompanyId1?: string;
applicantDepartmentName?: string;
applicantSubCompanyName?: string;
applyTime: string;
fillerName: string;
fillerJobTitle?: string;
fillerJobTitleName?: string;
fillerDepartmentId?: string;
fillerSubCompanyId1?: string;
fillerDepartmentName?: string;
fillerSubCompanyName?: string;
agentUid: string;
agentEmployeeId: string;
agentName: string;
agentJobTitle?: string;
agentJobTitleName?: string;
agentDepartmentId?: string;
agentSubCompanyId1?: string;
agentDepartmentName?: string;
agentSubCompanyName?: string;
leaveType: string;
startTime: string;
endTime: string;
@@ -575,6 +732,12 @@ interface LeaveAgentOption {
uid: string;
employeeId: string;
name: string;
jobtitle?: string;
jobtitleName?: string;
departmentid?: string;
subcompanyid1?: string;
departmentName?: string;
subcompanyName?: string;
}
let leaveFlowCounter = 0;
@@ -800,6 +963,34 @@ const startLocalLeaveFlow = async (content: string) => {
};
messages.value.push(formMsg);
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(keyword)}&page=1&page_size=1&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
const data = await res.json();
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
payload.form.fillerJobTitleName = match.jobtitleName || '';
payload.form.fillerDepartmentId = match.departmentid || '';
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
payload.form.fillerDepartmentName = match.departmentName || '';
payload.form.fillerSubCompanyName = match.subcompanyName || '';
payload.form.applicantUid = match.uid || '';
payload.form.applicantJobTitle = match.jobtitle || '';
payload.form.applicantJobTitleName = match.jobtitleName || '';
payload.form.applicantDepartmentId = match.departmentid || '';
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
payload.form.applicantDepartmentName = match.departmentName || '';
payload.form.applicantSubCompanyName = match.subcompanyName || '';
}
}
}
} catch (e) {
console.error('Failed to prefill OA user info', e);
}
await saveLocalMessageToBackend(formMsg, content);
// 发送完成后刷新历史记录,确保新会话出现
@@ -810,6 +1001,13 @@ const startLocalLeaveFlow = async (content: string) => {
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const previewFile = parsePlmPreviewLink(anchor?.getAttribute('href') || '');
if (previewFile) {
event.preventDefault();
openPreview(previewFile);
return;
}
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
if (!actionElement) return;
const action = actionElement.getAttribute('data-leave-action');
@@ -890,10 +1088,22 @@ const selectLeaveAgent = (option: LeaveAgentOption) => {
payload.form.agentUid = option.uid;
payload.form.agentEmployeeId = option.employeeId;
payload.form.agentName = option.name;
payload.form.agentJobTitle = option.jobtitle;
payload.form.agentJobTitleName = option.jobtitleName;
payload.form.agentDepartmentId = option.departmentid;
payload.form.agentSubCompanyId1 = option.subcompanyid1;
payload.form.agentDepartmentName = option.departmentName;
payload.form.agentSubCompanyName = option.subcompanyName;
} else {
payload.form.applicantUid = option.uid;
payload.form.employeeId = option.employeeId;
payload.form.applicantName = option.name;
payload.form.applicantJobTitle = option.jobtitle;
payload.form.applicantJobTitleName = option.jobtitleName;
payload.form.applicantDepartmentId = option.departmentid;
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
payload.form.applicantDepartmentName = option.departmentName;
payload.form.applicantSubCompanyName = option.subcompanyName;
}
closeLeaveAgentDialog();
@@ -1552,7 +1762,7 @@ const showChatRating = ref(false);
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-slate-800 dark:text-slate-100 md:text-2xl">我今天可以怎么帮助你?</h2>
<h2 class="text-center text-xl font-medium text-slate-800 dark:text-slate-100 md:text-2xl">你好,我是和信AI数字人</h2>
</div>
<template v-for="(msg, index) in messages" :key="index">
@@ -1738,11 +1948,29 @@ const showChatRating = ref(false);
<div v-else-if="msg.type === 'leave-confirmation' && getLeaveConfirmationPayload(msg)" class="space-y-4">
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">{{ msg.content }}</div>
<div class="rounded-2xl border border-slate-200 bg-slate-50/90 p-4 dark:border-slate-700 dark:bg-slate-800/60">
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">填单人信息</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-slate-500 dark:text-slate-400">填单人:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerName || '暂无数据' }}</div>
<div><span class="text-slate-500 dark:text-slate-400">创建时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle"><span class="text-slate-500 dark:text-slate-400">填单人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId"><span class="text-slate-500 dark:text-slate-400">填单人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">填单人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-slate-200 dark:border-slate-700"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">申请人信息</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-slate-500 dark:text-slate-400">请假人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle"><span class="text-slate-500 dark:text-slate-400">申请人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId"><span class="text-slate-500 dark:text-slate-400">申请人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">申请人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-slate-200 dark:border-slate-700"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">请假信息</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-slate-500 dark:text-slate-400">代理人:</span>{{ getLeaveAgentDisplayValue(getLeaveConfirmationPayload(msg)!.form) || '未选择' }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle"><span class="text-slate-500 dark:text-slate-400">代理人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId"><span class="text-slate-500 dark:text-slate-400">代理人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId }}</div>
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">代理人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1 }}</div>
<div><span class="text-slate-500 dark:text-slate-400">假别:</span>{{ getLeaveTypeLabel(getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
<div><span class="text-slate-500 dark:text-slate-400">时长:</span>{{ formatDurationLabel(getLeaveConfirmationPayload(msg)!.form.durationHours) }}</div>
<div><span class="text-slate-500 dark:text-slate-400">开始时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.startTime.replace('T', ' ') }}</div>
@@ -1801,13 +2029,13 @@ const showChatRating = ref(false);
</div>
<div
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getSourceLinks(getDisplayRetrieverResources(msg)).length > 0)"
class="mt-2 space-y-2"
>
<!-- 带有URL链接的源文件名称,支持预览 -->
<div v-if="getMessageLinks(msg).length > 0" class="flex flex-wrap gap-2">
<div v-if="getSourceLinks(getDisplayRetrieverResources(msg)).length > 0" class="flex flex-wrap gap-2">
<button
v-for="(file, linkIndex) in getMessageLinks(msg)"
v-for="(file, linkIndex) in getSourceLinks(getDisplayRetrieverResources(msg))"
:key="`src-link-top-${linkIndex}-${file.url}`"
@click="openPreview(file)"
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100 dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-200 dark:hover:bg-brand-500/20"
+236 -16
View File
@@ -14,6 +14,7 @@ import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import loginBg from '../assets/login-bg.png';
import {
buildWecomLoginDialogContent,
@@ -50,11 +51,19 @@ import {
} from 'lucide-vue-next';
import KbWorkspaceView from './KbWorkspaceView.vue';
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference, appliedTheme } = useTheme();
const loginBackgroundStyle = {
backgroundImage: `url(${loginBg})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
};
const loadLanguagePreference = () => {
const storedLang = localStorage.getItem('hxops_lang');
@@ -758,7 +767,7 @@ const handleRegister = async () => {
}
};
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base'>('applications');
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs'>('applications');
const isProfileLoading = ref(false);
const isProfileSaving = ref(false);
const isProfileEditing = ref(false);
@@ -982,6 +991,99 @@ const navigateToKnowledgeBase = () => {
activeSidebarItem.value = 'knowledge_base';
};
const navigateToScheduleRuns = () => {
activeSidebarItem.value = 'schedule_runs';
loadWorkspaceScheduleRuns();
};
const workspaceScheduleRuns = ref<ScheduleRun[]>([]);
const workspaceScheduleLoading = ref(false);
const wsScheduleStatusFilter = ref('all');
const wsScheduleNameFilter = ref('');
const wsScheduleStartedAfter = ref('');
const wsScheduleStartedBefore = ref('');
const wsScheduleStatusOptions = [
{ value: 'all', label: '全部状态' },
{ value: 'success', label: '成功' },
{ value: 'partial_failed', label: '部分成功' },
{ value: 'failed', label: '失败' },
{ value: 'running', label: '执行中' },
];
const getWsScheduleStatusBadge = (status: string) => {
const map: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: '成功' },
partial_failed: { cls: 'bg-blue-100 text-blue-700', label: '部分成功' },
failed: { cls: 'bg-rose-100 text-rose-700', label: '失败' },
running: { cls: 'bg-amber-100 text-amber-700', label: '执行中' },
queued: { cls: 'bg-slate-100 text-slate-600', label: '排队中' },
};
return map[status] || { cls: 'bg-slate-100 text-slate-600', label: status };
};
const formatDateTime = (iso?: string | null) => {
if (!iso) return '-';
const d = new Date(iso);
if (isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
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 {
const params: { status?: string; schedule_name?: string; started_after?: string; started_before?: string } = {};
if (wsScheduleStatusFilter.value !== 'all') params.status = wsScheduleStatusFilter.value;
if (wsScheduleNameFilter.value.trim()) params.schedule_name = wsScheduleNameFilter.value.trim();
if (wsScheduleStartedAfter.value) params.started_after = new Date(wsScheduleStartedAfter.value).toISOString();
if (wsScheduleStartedBefore.value) params.started_before = new Date(wsScheduleStartedBefore.value).toISOString();
workspaceScheduleRuns.value = await listWorkspaceScheduleRuns(params);
} catch {
workspaceScheduleRuns.value = [];
} finally {
workspaceScheduleLoading.value = false;
}
};
const resetWsScheduleFilters = () => {
wsScheduleStatusFilter.value = 'all';
wsScheduleNameFilter.value = '';
wsScheduleStartedAfter.value = todayStart().slice(0, 16);
wsScheduleStartedBefore.value = todayEnd().slice(0, 16);
loadWorkspaceScheduleRuns();
};
const downloadWsScheduleExcel = async (runId: number) => {
const res = await fetch(workspaceRunExcelUrl(runId), { headers: getAuthHeaders() });
if (!res.ok) {
showMessageDialog('error', '下载 Excel 失败');
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const navigateToGeneralChat = () => {
router.push(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
@@ -1229,8 +1331,13 @@ onMounted(async () => {
</div>
<!-- Not Logged In (Login Screen) -->
<div v-else-if="!isLoggedIn" class="min-h-[calc(100vh-4rem)] flex items-center justify-center">
<div class="w-full max-w-6xl grid grid-cols-1 lg:grid-cols-2 gap-12 items-center p-4">
<div
v-else-if="!isLoggedIn"
class="relative min-h-[calc(100vh-4rem)] overflow-hidden rounded-[2rem] flex items-center justify-center"
:style="loginBackgroundStyle"
>
<div class="absolute inset-0 bg-white/55 backdrop-blur-[1px] dark:bg-slate-950/55"></div>
<div class="relative z-10 w-full max-w-6xl grid grid-cols-1 lg:grid-cols-2 gap-12 items-center p-4">
<!-- Hero Section -->
<div class="hidden lg:block space-y-8 animate-slide-up">
<!--
@@ -1242,17 +1349,17 @@ onMounted(async () => {
{{ $t('title') }}
</div>
-->
<h1 class="text-5xl font-bold text-slate-900 leading-tight">
<h1 class="text-5xl font-bold text-black leading-tight drop-shadow-sm">
{{ $t('landing.hero.prefix') }} <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">{{ $t('landing.hero.highlight') }}</span>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-[#005a9c] to-[#7a1fd0] drop-shadow-sm">{{ $t('landing.hero.highlight') }}</span>
</h1>
<p class="text-lg text-slate-600 max-w-md leading-relaxed">
<p class="text-lg text-slate-800 max-w-md leading-relaxed font-semibold drop-shadow-sm">
{{ $t('landing.hero.subtitle') }}
</p>
<!-- Announcements List -->
<div v-if="announcements.length > 0" class="bg-white/60 dark:bg-slate-900/70 backdrop-blur-sm rounded-2xl border border-slate-100 dark:border-slate-700 p-6 shadow-sm">
<h3 class="text-sm font-bold text-slate-900 mb-4 flex items-center gap-2">
<div v-if="announcements.length > 0" class="bg-white/70 dark:bg-slate-900/70 backdrop-blur-sm rounded-2xl border border-slate-200 dark:border-slate-700 p-6 shadow-sm">
<h3 class="text-sm font-bold text-slate-950 mb-4 flex items-center gap-2">
<Megaphone class="w-4 h-4 text-brand-600" />
{{ $t('login.announcements') }}
</h3>
@@ -1261,10 +1368,10 @@ onMounted(async () => {
class="group cursor-pointer hover:bg-white/50 dark:hover:bg-slate-800/70 p-2 rounded-lg transition-colors"
@click="openAnnouncement(ann)">
<div class="flex justify-between items-start gap-2">
<h4 class="text-sm font-medium text-slate-800 group-hover:text-brand-700 line-clamp-1">{{ ann.title }}</h4>
<span class="text-[10px] text-slate-400 whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
<h4 class="text-sm font-semibold text-slate-900 group-hover:text-brand-800 line-clamp-1">{{ ann.title }}</h4>
<span class="text-[10px] text-slate-500 whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
</div>
<p class="text-xs text-slate-500 line-clamp-2 mt-1">{{ ann.content }}</p>
<p class="text-xs text-slate-700 line-clamp-2 mt-1">{{ ann.content }}</p>
</div>
</div>
</div>
@@ -1294,22 +1401,22 @@ onMounted(async () => {
<Bot class="w-7 h-7" />
</div>
<h2 class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ $t('login.submit') }}</h2>
<p class="text-slate-500 dark:text-slate-400 text-sm mt-2">{{ $t('login.subtitle') }}</p>
<p class="text-slate-600 dark:text-slate-400 text-sm mt-2">{{ $t('login.subtitle') }}</p>
</div>
<div class="space-y-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.username') }}</label>
<label class="text-xs font-semibold text-slate-800 uppercase ml-1">{{ $t('login.username') }}</label>
<input v-model="loginUsername" type="text" class="input-field" :placeholder="$t('login.placeholder.username')" @keyup.enter="handleLogin" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.password') }}</label>
<label class="text-xs font-semibold text-slate-800 uppercase ml-1">{{ $t('login.password') }}</label>
<input v-model="loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="handleLogin" />
</div>
<div class="flex items-center gap-2 mt-2">
<input type="checkbox" id="rememberMe" v-model="rememberMe" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 w-4 h-4" />
<label for="rememberMe" class="text-sm text-slate-600 cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
<label for="rememberMe" class="text-sm text-slate-700 cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
</div>
<button type="button" @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
@@ -1327,7 +1434,7 @@ onMounted(async () => {
</button>
<div class="flex justify-between items-center pt-4 mt-2 border-t border-slate-100/50">
<button type="button" @click="showForgotPasswordModal = true" class="text-sm text-slate-500 hover:text-brand-600 transition-colors">
<button type="button" @click="showForgotPasswordModal = true" class="text-sm text-slate-600 hover:text-brand-700 transition-colors">
{{ $t('login.forgotPassword') }}
</button>
<!-- 点击注册 -->
@@ -1397,6 +1504,14 @@ onMounted(async () => {
<FileText class="h-4 w-4" />
<span>知识库管理</span>
</button>
<button
@click="navigateToScheduleRuns"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
:class="activeSidebarItem === 'schedule_runs' ? 'bg-brand-50 text-brand-700 shadow-sm' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'"
>
<Clock class="h-4 w-4" />
<span>排程记录</span>
</button>
<button
@click="openGeneralFeedback"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
@@ -1616,6 +1731,111 @@ onMounted(async () => {
<KbWorkspaceView :embedded="true" />
</template>
<template v-else-if="activeSidebarItem === 'schedule_runs'">
<div class="space-y-5 animate-fade-in-up">
<div class="flex items-center justify-between">
<h2 class="text-2xl font-bold text-slate-900">排程记录</h2>
<button
@click="loadWorkspaceScheduleRuns"
class="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50"
>
<RefreshCw class="h-3.5 w-3.5" />
刷新
</button>
</div>
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50/40 px-4 py-3">
<div>
<label class="mb-1 block text-xs font-medium text-slate-500">排程名称</label>
<input type="text" v-model="wsScheduleNameFilter" placeholder="输入排程名称" class="!w-[150px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-slate-500">开始时间</label>
<input type="datetime-local" step="1" v-model="wsScheduleStartedAfter" class="!w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-slate-500">结束时间</label>
<input type="datetime-local" step="1" v-model="wsScheduleStartedBefore" class="!w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-slate-500">状态</label>
<select v-model="wsScheduleStatusFilter" class="!w-[120px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white">
<option v-for="o in wsScheduleStatusOptions" :key="o.value" :value="o.value">{{ o.label }}</option>
</select>
</div>
<button
@click="loadWorkspaceScheduleRuns"
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Search class="h-3.5 w-3.5" />
查询
</button>
<button
@click="resetWsScheduleFilters"
class="rounded-xl border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50"
>
重置
</button>
</div>
<div v-if="workspaceScheduleLoading" class="py-10 text-center text-sm text-slate-400">正在加载...</div>
<div v-else-if="workspaceScheduleRuns.length === 0" class="py-10 text-center text-sm text-slate-400">暂无排程记录</div>
<div v-else class="overflow-hidden rounded-2xl border border-slate-200 bg-white">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="border-b border-slate-100 bg-slate-50/60">
<th class="px-4 py-3 text-left font-semibold text-slate-600">排程名称</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">运行编号</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">触发方式</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">开始时间</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">结束时间</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">耗时</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">状态</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">处理笔数</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">成功笔数</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">失败笔数</th>
<th class="px-4 py-3 text-left font-semibold text-slate-600">明细</th>
</tr>
</thead>
<tbody>
<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 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>
<td class="px-4 py-3">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold" :class="getWsScheduleStatusBadge(r.status).cls">
{{ getWsScheduleStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message && r.error_message !== '无待处理数据'" class="ml-1 text-xs text-slate-400" :title="r.error_message">...</span>
<span v-else-if="r.error_message === '无待处理数据'" class="ml-1 text-xs text-slate-400">(无待处理数据)</span>
</td>
<td class="px-4 py-3 text-slate-500">{{ r.total_count || 0 }}</td>
<td class="px-4 py-3 text-emerald-600 font-medium">{{ r.success_count ?? 0 }}</td>
<td class="px-4 py-3 text-rose-600 font-medium">{{ r.failed_count ?? 0 }}</td>
<td class="px-4 py-3">
<a
v-if="r.total_count > 0 && r.excel_file_name"
href="#"
@click.prevent="downloadWsScheduleExcel(r.id)"
class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-2 py-1 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50"
>
<Download class="h-3 w-3" />
下载
</a>
<span v-else class="text-xs text-slate-300">-</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<template v-else>
<div v-if="wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ wecomEntryHint }}