排程管理新增企微通知功能(消息以及文件推送)

This commit is contained in:
hugo committed 2026-05-21 09:33:51 +08:00
1 parent 88051db91e
commit 8da487aac6
13 files changed
+267 -112

No files matched your search

@@ -14,7 +14,6 @@ from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
_worker_started = False
_worker_lock = threading.Lock()
@@ -49,6 +48,111 @@ def _generate_test_run_no() -> str:
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
_WECOM_STATUS_LABEL = {
'success': '成功',
'failed': '失败',
'partial_failed': '部分失败',
}
_WECOM_EVENT_TYPE = 'schedule_completed'
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
from app.services.wecom_notify import (
upload_wecom_temp_media,
send_wecom_file_message,
send_wecom_textcard_message,
_create_audit,
_build_jump_url,
_get_enabled_events,
)
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
if _WECOM_EVENT_TYPE not in _get_enabled_events():
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
return
user_ids = task.notify_user_ids_json or []
if not user_ids:
return
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
wecom_users = [u for u in users if u.wecom_userid]
if not wecom_users:
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
return
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
title = f'排程执行结果: {task.name}'
description = (
f'执行单号: {run.run_no}\n'
f'状态: {status_label}\n'
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
)
media_id = None
if run.excel_file_data and run.excel_file_name:
try:
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
except Exception as exc:
current_app.logger.warning(
'[wecom-schedule] media upload failed for run %s: %s',
run.run_no, exc,
)
textcard_ok_count = 0
errors = []
for u in wecom_users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
textcard_ok_count += 1
else:
audit.error_code = str(data.get('errcode'))
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
if media_id:
try:
file_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_file', u,
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
)
file_data = send_wecom_file_message(u.wecom_userid, media_id)
if file_data.get('errcode') == 0:
file_audit.status = 'sent'
else:
file_audit.error_code = str(file_data.get('errcode'))
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: file exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
else:
run.wecom_notified = False
if errors:
run.wecom_notify_error = '; '.join(errors[:5])
db.session.flush()
def create_task(
*,
name: str,
@@ -238,36 +342,10 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
try:
if task.notify_enabled:
users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all()
to_addrs = [u.email for u in users if u.email]
if to_addrs:
try:
send_schedule_mail(
smtp_host=str(current_app.config.get("SMTP_HOST") or ""),
smtp_port=int(current_app.config.get("SMTP_PORT") or 25),
smtp_user=str(current_app.config.get("SMTP_USER") or ""),
smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""),
use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)),
from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"),
to_addrs=to_addrs,
subject=f"排程执行结果 {task.name} {run.run_no}",
html_body=build_schedule_mail_html(
schedule_name=task.name,
run_no=run.run_no,
status=status,
total=total_count,
success=success_count,
failed=failed_count,
),
)
run.mail_sent = True
run.mail_sent_at = datetime.utcnow()
except Exception as mail_exc:
run.mail_sent = False
run.mail_error = str(mail_exc)
except Exception as mail_exc:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
if current_app:
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
task.last_run_at = datetime.utcnow()
db.session.commit()