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

+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