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

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

@@ -1,37 +0,0 @@
from __future__ import annotations
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_schedule_mail(*, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_tls: bool, from_addr: str, to_addrs: list[str], subject: str, html_body: str) -> None:
if not to_addrs:
return
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = ', '.join(to_addrs)
msg.attach(MIMEText(html_body, 'html', 'utf-8'))
with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server:
if use_tls:
server.starttls()
if smtp_user:
server.login(smtp_user, smtp_password)
server.sendmail(from_addr, to_addrs, msg.as_string())
def build_schedule_mail_html(*, schedule_name: str, run_no: str, status: str, total: int, success: int, failed: int) -> str:
return (
"<html><body>"
"<h3>排程执行结果</h3>"
"<table border='1' cellspacing='0' cellpadding='6'>"
f"<tr><th>排程</th><td>{schedule_name}</td></tr>"
f"<tr><th>执行单号</th><td>{run_no}</td></tr>"
f"<tr><th>状态</th><td>{status}</td></tr>"
f"<tr><th>总数</th><td>{total}</td></tr>"
f"<tr><th>成功</th><td>{success}</td></tr>"
f"<tr><th>失败</th><td>{failed}</td></tr>"
"</table></body></html>"
)
@@ -56,9 +56,9 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'mail_sent': bool(run.mail_sent),
'mail_sent_at': run.mail_sent_at.isoformat() if run.mail_sent_at else None,
'mail_error': run.mail_error,
'wecom_notified': bool(run.wecom_notified),
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
'wecom_notify_error': run.wecom_notify_error,
'created_at': run.created_at.isoformat() if run.created_at else None,
}
@@ -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()
+2 -2
View File
@@ -45,8 +45,8 @@ def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]:
dify_result = str(data.get("dify_result") or data.get("result") or "人工判定").strip()
dify_message = str(data.get("dify_message") or data.get("message") or data.get("messge") or "").strip()
dify_result = str(data.get("dify_result")).strip()
dify_message = str(data.get("dify_message")).strip()
if dify_result not in {"合格", "不合格", "人工判定"}:
dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |")
dify_result = "人工判定"