Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-21 09:41:09 +08:00
commit 0cc9f487e6
15 files changed
+269 -115

No files matched your search

+1 -1
View File
@@ -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
+18 -1
View File
@@ -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
+1 -1
View File
@@ -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'
+4 -4
View File
@@ -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])
@@ -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 = "人工判定"
+82 -26
View File
@@ -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}
@@ -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')
+1 -1
View File
@@ -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()
+2 -2
View File
@@ -10,8 +10,8 @@
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-DXNJeOLf.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CcWOFgeX.css">
<script type="module" crossorigin src="/assets/index-CRyzfl76.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BKu7TAYA.css">
</head>
<body>
<div id="app"></div>␍
+3 -3
View File
@@ -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;
}
+12 -3
View File
@@ -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) => {
</thead>
<tbody class="divide-y divide-slate-100">
<tr v-if="scheduleRunsLoading">
<td colspan="9" class="px-4 py-8 text-center text-sm text-slate-400">正在查询记录...</td>
<td colspan="10" class="px-4 py-8 text-center text-sm text-slate-400">正在查询记录...</td>
</tr>
<tr v-else-if="filteredScheduleRuns.length === 0">
<td colspan="9" class="px-4 py-8 text-center text-sm text-slate-400">暂无执行记录。</td>
<td colspan="10" class="px-4 py-8 text-center text-sm text-slate-400">暂无执行记录。</td>
</tr>
<tr
v-else
@@ -4552,6 +4553,14 @@ const handlePermissionImport = async (event: Event) => {
<td class="truncate px-4 py-2.5">{{ r.total_count }}</td>
<td class="truncate px-4 py-2.5">{{ r.success_count }}</td>
<td class="truncate px-4 py-2.5">{{ r.failed_count }}</td>
<td class="truncate px-4 py-2.5">
<span v-if="r.wecom_notified" class="inline-flex items-center gap-1 text-xs text-emerald-600">
<svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
已通知
</span>
<span v-else-if="r.wecom_notify_error" class="text-xs text-amber-500" :title="r.wecom_notify_error">异常</span>
<span v-else class="text-xs text-slate-300">-</span>
</td>
<td class="px-4 py-2.5">
<div class="flex items-center">
<a
@@ -4586,7 +4595,7 @@ const handlePermissionImport = async (event: Event) => {
v-if="expandedScheduleRunId && filteredScheduleRuns.find(x => x.id === expandedScheduleRunId)"
:key="'expanded-' + expandedScheduleRunId"
>
<td colspan="9" class="px-4 py-3 bg-slate-50/60">
<td colspan="10" class="px-4 py-3 bg-slate-50/60">
<div class="space-y-2">
<div class="flex items-center justify-between mb-2">
<h5 class="text-xs font-bold text-slate-600 uppercase">执行日志</h5>
-1
View File
@@ -594,7 +594,6 @@ const showGeneralFeedbackDialog = ref(false);
const showAgentPanel = ref(true);
const OA_BASE_URL = 'http://192.168.100.221:8888';
const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`;
const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid=';