diff --git a/.env.shared b/.env.shared index 7bf46bfb..791030f0 100644 --- a/.env.shared +++ b/.env.shared @@ -37,7 +37,7 @@ WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email WECOM_EMPLOYEE_ID_SOURCE=userid WECOM_MOBILE_NORMALIZE=true WECOM_NOTIFY_ENABLED=true -WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed +WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed # Common integration defaults INTEGRATION_API_MODE=local diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py index 2da7a04b..4394e4f9 100644 --- a/backend/app/api/schedule_admin.py +++ b/backend/app/api/schedule_admin.py @@ -10,7 +10,14 @@ from app import db from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig from app.auth_jwt import get_current_user from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task -from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no +from app.services.schedule.scheduler_service import ( + create_task, + run_task_now, + update_task, + _generate_run_no, + _generate_test_run_no, + _notify_schedule_run_wecom, +) from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql from app.services.schedule.srm_service import _fetch_records @@ -194,6 +201,11 @@ def test_schedule_run(task_id: int): run.status = 'success' run.finished_at = datetime.utcnow() run.error_message = '无抓取SQL,跳过外部系统数据抓取' + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc) db.session.commit() return jsonify({ "run_no": run.run_no, @@ -307,6 +319,11 @@ def test_schedule_run(task_id: int): run.excel_file_data = file_data run.excel_file_name = file_name run.excel_file_size = file_size or 0 + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc) db.session.commit() import decimal, datetime as dt diff --git a/backend/app/config.py b/backend/app/config.py index 1ccaa86e..02d563d3 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -106,7 +106,7 @@ class Config: WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL') WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL') - WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS') + WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed') # JWT/Casdoor auth configuration (phase-1 compatible rollout) AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true' diff --git a/backend/app/models.py b/backend/app/models.py index 70f58507..d01a8500 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,6 +1,6 @@ from datetime import datetime from typing import Optional, List -from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary +from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app import db from werkzeug.security import generate_password_hash, check_password_hash @@ -648,9 +648,9 @@ class ScheduleRun(Base): excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary) excel_file_name: Mapped[Optional[str]] = mapped_column(String(255)) excel_file_size: Mapped[Optional[int]] = mapped_column(Integer) - mail_sent: Mapped[bool] = mapped_column(Boolean, default=False) - mail_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime) - mail_error: Mapped[Optional[str]] = mapped_column(Text) + wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) + wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) diff --git a/backend/app/services/schedule/mail_service.py b/backend/app/services/schedule/mail_service.py deleted file mode 100644 index 9b00a92f..00000000 --- a/backend/app/services/schedule/mail_service.py +++ /dev/null @@ -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 ( - "" - "

排程执行结果

" - "" - f"" - f"" - f"" - f"" - f"" - f"" - "
排程{schedule_name}
执行单号{run_no}
状态{status}
总数{total}
成功{success}
失败{failed}
" - ) diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index 5a9cf0de..cbc3324e 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -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, } diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index c325be88..5aa91556 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -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() diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py index 0b511768..bca2be78 100644 --- a/backend/app/services/schedule/srm_service.py +++ b/backend/app/services/schedule/srm_service.py @@ -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 = "人工判定" diff --git a/backend/app/services/wecom_notify.py b/backend/app/services/wecom_notify.py index 7f2cc924..3be09db8 100644 --- a/backend/app/services/wecom_notify.py +++ b/backend/app/services/wecom_notify.py @@ -1,6 +1,7 @@ from __future__ import annotations from datetime import datetime, timedelta +from io import BytesIO from urllib.parse import urlencode import uuid @@ -62,16 +63,13 @@ def _get_access_token() -> str: return data['access_token'] -def send_wecom_event_message( - *, +def _create_audit( event_type: str, user: User, title: str, content: str, - jump_path: str = '/workspace', - jump_params: dict | None = None, -) -> dict: - trace_id = uuid.uuid4().hex + trace_id: str, +) -> WecomNotifyAudit: audit = WecomNotifyAudit( event_type=event_type, status='failed', @@ -83,6 +81,83 @@ def send_wecom_event_message( content=content, ) db.session.add(audit) + return audit + + +def upload_wecom_temp_media(file_data: bytes, filename: str) -> str: + token = _get_access_token() + url = ( + f'https://qyapi.weixin.qq.com/cgi-bin/media/upload' + f'?access_token={token}&type=file' + ) + resp = requests.post( + url, + files={'media': (filename, BytesIO(file_data), 'application/octet-stream')}, + timeout=30, + ) + data = resp.json() + if data.get('errcode', 0) != 0 or not data.get('media_id'): + raise RuntimeError(f"WeCom media upload failed: {data}") + return data['media_id'] + + +def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict: + token = _get_access_token() + payload = { + 'touser': wecom_userid, + 'msgtype': 'file', + 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), + 'file': {'media_id': media_id}, + 'safe': 0, + } + resp = requests.post( + 'https://qyapi.weixin.qq.com/cgi-bin/message/send', + params={'access_token': token}, + json=payload, + timeout=8, + ) + return resp.json() + + +def send_wecom_textcard_message( + wecom_userid: str, + title: str, + description: str, + jump_url: str, +) -> dict: + token = _get_access_token() + payload = { + 'touser': wecom_userid, + 'msgtype': 'textcard', + 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), + 'textcard': { + 'title': title[:120], + 'description': (description or '')[:1024], + 'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'), + 'btntxt': '查看详情', + }, + 'safe': 0, + } + resp = requests.post( + 'https://qyapi.weixin.qq.com/cgi-bin/message/send', + params={'access_token': token}, + json=payload, + timeout=8, + ) + return resp.json() + + +def send_wecom_event_message( + *, + event_type: str, + user: User, + title: str, + content: str, + jump_path: str = '/workspace', + jump_params: dict | None = None, +) -> dict: + trace_id = uuid.uuid4().hex + audit = _create_audit(event_type, user, title, content, trace_id) if not current_app.config.get('WECOM_NOTIFY_ENABLED', True): audit.error_code = 'NOTIFY_DISABLED' @@ -100,28 +175,9 @@ def send_wecom_event_message( return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'} try: - token = _get_access_token() jump_url = _build_jump_url(jump_path, trace_id, jump_params) audit.jump_url = jump_url - payload = { - 'touser': user.wecom_userid, - 'msgtype': 'textcard', - 'agentid': int(current_app.config.get('WECOM_AGENT_ID')), - 'textcard': { - 'title': title[:120], - 'description': (content or '')[:1024], - 'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'), - 'btntxt': '查看详情', - }, - 'safe': 0, - } - resp = requests.post( - 'https://qyapi.weixin.qq.com/cgi-bin/message/send', - params={'access_token': token}, - json=payload, - timeout=8, - ) - data = resp.json() + data = send_wecom_textcard_message(user.wecom_userid, title, content, jump_url) if data.get('errcode') == 0: audit.status = 'sent' return {'ok': True, 'trace_id': trace_id} diff --git a/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py b/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py new file mode 100644 index 00000000..77c224b2 --- /dev/null +++ b/backend/migrations/versions/c1d2e3f4a5b6_replace_mail_with_wecom_notify.py @@ -0,0 +1,32 @@ +"""replace mail notify fields with wecom notify fields + +Revision ID: c1d2e3f4a5b6 +Revises: a9b0c1d2e3f4 +Create Date: 2026-05-20 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +revision = 'c1d2e3f4a5b6' +down_revision = 'a9b0c1d2e3f4' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('schedule_runs', sa.Column('wecom_notified', sa.Boolean(), nullable=True, server_default=sa.text('false'))) + op.add_column('schedule_runs', sa.Column('wecom_notified_at', sa.DateTime(), nullable=True)) + op.add_column('schedule_runs', sa.Column('wecom_notify_error', sa.Text(), nullable=True)) + op.drop_column('schedule_runs', 'mail_sent') + op.drop_column('schedule_runs', 'mail_sent_at') + op.drop_column('schedule_runs', 'mail_error') + + +def downgrade(): + op.add_column('schedule_runs', sa.Column('mail_error', sa.Text(), nullable=True)) + op.add_column('schedule_runs', sa.Column('mail_sent_at', sa.DateTime(), nullable=True)) + op.add_column('schedule_runs', sa.Column('mail_sent', sa.Boolean(), nullable=True, server_default=sa.text('false'))) + op.drop_column('schedule_runs', 'wecom_notify_error') + op.drop_column('schedule_runs', 'wecom_notified_at') + op.drop_column('schedule_runs', 'wecom_notified') diff --git a/backend/tests/test_schedule_api.py b/backend/tests/test_schedule_api.py index 18dcb061..d7672c93 100644 --- a/backend/tests/test_schedule_api.py +++ b/backend/tests/test_schedule_api.py @@ -61,7 +61,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers): failed_count=0, skipped_count=0, duration_ms=100, - mail_sent=False, + wecom_notified=False, ) db.session.add(run) db.session.commit() diff --git a/frontend/src/api/schedule.ts b/frontend/src/api/schedule.ts index 47c87af0..a3c10c29 100644 --- a/frontend/src/api/schedule.ts +++ b/frontend/src/api/schedule.ts @@ -43,9 +43,9 @@ export interface ScheduleRun { error_message?: string | null; excel_file_name?: string | null; excel_file_size?: number | null; - mail_sent: boolean; - mail_sent_at?: string | null; - mail_error?: string | null; + wecom_notified: boolean; + wecom_notified_at?: string | null; + wecom_notify_error?: string | null; created_at?: string | null; } diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index 8a07f258..eb2e18d0 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -442,6 +442,7 @@ const scheduleRunColumnDefs = ref([ { key: 'total_count', label: '处理', width: 70, min: 40 }, { key: 'success_count', label: '成功', width: 70, min: 40 }, { key: 'failed_count', label: '失败', width: 70, min: 40 }, + { key: 'wecom_notified', label: '企微通知', width: 90, min: 50 }, { key: 'detail', label: '明细', width: 90, min: 50 }, { key: 'log', label: '日志', width: 90, min: 50 }, ]); @@ -4528,10 +4529,10 @@ const handlePermissionImport = async (event: Event) => { - 正在查询记录... + 正在查询记录... - 暂无执行记录。 + 暂无执行记录。 { {{ r.total_count }} {{ r.success_count }} {{ r.failed_count }} + + + + 已通知 + + 异常 + - +
{ v-if="expandedScheduleRunId && filteredScheduleRuns.find(x => x.id === expandedScheduleRunId)" :key="'expanded-' + expandedScheduleRunId" > - +
执行日志