diff --git a/.env.shared b/.env.shared index fc04ac83..ea082182 100644 --- a/.env.shared +++ b/.env.shared @@ -47,10 +47,10 @@ AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend AUTH_LOCAL_JWT_EXPIRES_HOURS=12 # WeCom -WECOM_ENABLED=false -WECOM_CORP_ID= -WECOM_AGENT_ID= -WECOM_SECRET= +WECOM_ENABLED=true +WECOM_CORP_ID=ww1ada6c11b684783e +WECOM_AGENT_ID=1000065 +WECOM_SECRET=N9a1EE6pDj_6wTpRrXmg9Vn4BdK54jb7yFmSQ0-FSwU WECOM_REDIRECT_URI= WECOM_AUTO_CREATE_USER=true WECOM_MATCH_RULES=employee_id,mobile @@ -68,7 +68,7 @@ WECOM_TRUSTED_DOMAIN= WECOM_PUBLIC_BASE_URL= WECOM_NOTIFY_ENABLED=true WECOM_NOTIFY_BASE_URL= -WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed +WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset # Common integration defaults diff --git a/.gitignore b/.gitignore index fe9cdf7e..a69ed791 100644 --- a/.gitignore +++ b/.gitignore @@ -46,7 +46,9 @@ frontend/public/WW_verify_46MjWA55y3PBRLid.txt frontend/package-lock.json # IDEs -.vscode/ +.vscode/* +!.vscode/settings.json +!.vscode/extensions.json .idea/ *.swp *.swo diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..b6df14b0 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["ms-python.python", "ms-python.vscode-pylance"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..e98726b0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,20 @@ +{ + // 后端 Python 虚拟环境:新终端自动激活,无需手动 .venv\Scripts\activate + "python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe", + "python.terminal.activateEnvironment": true, + "python.venvPath": "${workspaceFolder}/backend", + "python.venvFolders": [".venv"], + + // 可选:在终端下拉中选择「HXOPS Backend」时,直接进入 backend 并激活 venv + "terminal.integrated.profiles.windows": { + "HXOPS Backend": { + "source": "PowerShell", + "icon": "server-environment", + "args": [ + "-NoExit", + "-Command", + "Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }" + ] + } + } +} diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 703c336c..1e7bab7d 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -11,7 +11,7 @@ from app.decorators import require_admin from app.config import Config from app import db from app.env_persistence import persist_env_settings -from sqlalchemy import func, desc, inspect +from sqlalchemy import func, desc, inspect, or_ from sqlalchemy.exc import IntegrityError from datetime import datetime, timedelta import csv @@ -20,6 +20,7 @@ import re import requests import uuid from app.services.wecom_notify import send_wecom_event_message +from app.services.wecom_directory_sync import sync_wecom_userids_from_directory from app.services.dify import DifyService from app.auth_jwt import get_current_user as _get_auth_user from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status @@ -839,14 +840,63 @@ def get_table_count(table): @require_admin def list_wecom_bindings(): """ - List users with optional filter for WeCom bindings. + 分页列出用户企微绑定,支持 keyword 模糊搜索与 bound_only 筛选。 + + Query: bound_only, keyword, page, page_size + Returns: { items, total, page, page_size, pages } """ bound_only = request.args.get('bound_only', 'false').lower() == 'true' + keyword = (request.args.get('keyword') or '').strip() + page = request.args.get('page', type=int) or 1 + page_size = request.args.get('page_size', type=int) or 20 + page = max(1, page) + page_size = max(1, min(100, page_size)) + query = db.session.query(User) if bound_only: query = query.filter(User.wecom_userid.isnot(None)) - users = query.order_by(User.id.asc()).all() - return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users]) + if keyword: + pattern = f'%{keyword}%' + query = query.filter(or_( + User.username.ilike(pattern), + User.real_name.ilike(pattern), + User.employee_id.ilike(pattern), + User.wecom_userid.ilike(pattern), + )) + + total = query.count() + pages = max(1, (total + page_size - 1) // page_size) if total else 1 + if page > pages: + page = pages + + users = ( + query.order_by(User.id.asc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + items = [ + { + 'id': u.id, + 'username': u.username, + 'real_name': u.real_name, + 'employee_id': u.employee_id, + 'email': u.email, + 'role': u.role, + 'status': u.status, + 'wecom_userid': u.wecom_userid, + 'wecom_unionid': u.wecom_unionid, + 'bound': bool(u.wecom_userid), + } + for u in users + ] + return jsonify({ + 'items': items, + 'total': int(total), + 'page': page, + 'page_size': page_size, + 'pages': pages, + }) @admin_bp.route('/guides/upload', methods=['POST']) @require_admin @@ -1177,3 +1227,77 @@ def wecom_notify_metrics(): by_event[event_type] = {'sent': 0, 'failed': 0} by_event[event_type][status] = int(cnt) return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event}) + + +@admin_bp.route('/wecom/binding-stats', methods=['GET']) +@require_admin +def wecom_binding_stats(): + """ + 返回活跃用户的企微 userid 绑定统计,供管理端概览卡片使用。 + """ + total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0 + bound = ( + db.session.query(func.count(User.id)) + .filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '') + .scalar() + or 0 + ) + total_active = int(total_active) + bound = int(bound) + return jsonify( + { + 'total_active': total_active, + 'bound': bound, + 'unbound': max(total_active - bound, 0), + 'bound_rate': round(bound / total_active * 100, 2) if total_active else 0, + } + ) + + +@admin_bp.route('/wecom/sync-userids', methods=['POST']) +@require_admin +def sync_wecom_userids_admin(): + """ + 从企微通讯录按工号同步 users.wecom_userid。 + Request JSON: { "apply": false, "department_id": 1 } + """ + data = request.get_json() or {} + apply = bool(data.get('apply')) + department_id = data.get('department_id') + if department_id is not None and department_id != '': + try: + department_id = int(department_id) + except (TypeError, ValueError): + raise ValidationError('department_id must be an integer') + else: + department_id = None + try: + summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id) + current_app.logger.info( + '[wecom_sync] admin apply=%s updated=%s would_update=%s conflicts=%s', + apply, + summary.get('updated'), + summary.get('would_update'), + len(summary.get('conflicts') or []), + ) + return jsonify(summary) + except RuntimeError as exc: + message = str(exc) + if 'not configured' in message.lower(): + raise AppError( + code='SYSTEM.HTTP_ERROR', + message=message, + http_status=503, + details={'error_code': 'WECOM_NOT_CONFIGURED'}, + ) + if 'conflicts detected' in message.lower(): + raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'}) + if 'department/list failed' in message.lower() or 'user/list failed' in message.lower(): + raise AppError( + code='SYSTEM.HTTP_ERROR', + message='WeCom directory API failed. Check app contact read permissions.', + http_status=502, + details={'error_code': 'WECOM_DIRECTORY_API_FAILED', 'technical': message[:300]}, + ) + raise AppError(code='SYSTEM.INTERNAL_ERROR', message=message, http_status=500) + diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 33d0757a..9f0aebee 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -22,6 +22,8 @@ user_bp = Blueprint('user', __name__) _WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None} _WECOM_STATE_CACHE = {} _WECOM_BIND_SESSION_CACHE = {} +_PASSWORD_RESET_RATE_CACHE = {} +_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.' _ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'} _LOGIN_AUDIT_COLUMNS_CACHE = None _CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None} @@ -108,8 +110,27 @@ def _run_db_with_retry(operation, *, label: str): current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc) return operation() -def _is_wecom_configured(): - return all([current_app.config.get('WECOM_ENABLED'), current_app.config.get('WECOM_CORP_ID'), current_app.config.get('WECOM_AGENT_ID'), current_app.config.get('WECOM_SECRET')]) +def _get_wecom_config_missing_fields() -> list[str]: + """ + 列出企微集成尚未配置的环境项。 + Returns: + 缺失的配置键名列表,如 WECOM_ENABLED、WECOM_CORP_ID 等。 + """ + missing: list[str] = [] + if not current_app.config.get('WECOM_ENABLED'): + missing.append('WECOM_ENABLED') + if not _clean_str(current_app.config.get('WECOM_CORP_ID')): + missing.append('WECOM_CORP_ID') + if not _clean_str(current_app.config.get('WECOM_AGENT_ID')): + missing.append('WECOM_AGENT_ID') + if not _clean_str(current_app.config.get('WECOM_SECRET')): + missing.append('WECOM_SECRET') + return missing + + +def _is_wecom_configured() -> bool: + """企微 Corp/Agent/Secret 与总开关均已配置时返回 True。""" + return len(_get_wecom_config_missing_fields()) == 0 def _issue_casdoor_state(redirect_uri: str): exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp()) @@ -1560,6 +1581,204 @@ def change_password(): db.session.rollback() raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500) +def _get_password_reset_public_base_url() -> str: + """ + 解析密码重置外链基地址,优先公网入口配置。 + 核心逻辑:依次读取 WECOM_PUBLIC_BASE_URL / PUBLIC_BASE_URL / WECOM_NOTIFY_BASE_URL。 + Returns: + 去掉尾斜杠的基地址;均未配置时返回空字符串。 + """ + for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'): + base = _clean_str(current_app.config.get(key)) + if base: + return base.rstrip('/') + return '' + + +def _build_password_reset_url(token: str) -> str: + """ + 构造带 token 的密码重置页 URL。 + @param token: reset_token 明文 + Returns: + 完整重置链接 + Raises: + RuntimeError: 公网基地址未配置 + """ + base = _get_password_reset_public_base_url() + if not base: + raise RuntimeError('Password reset public base URL is not configured') + return f'{base}/reset-password?token={token}' + + +def _check_password_reset_rate_limit(key: str, *, window_seconds: int = 300) -> bool: + """ + 简易内存限流,防止同工号/IP 频繁触发找回密码。 + @param key: 限流键,通常为 employee_id + IP + @param window_seconds: 窗口秒数,默认 5 分钟 + Returns: + True 表示允许继续;False 表示应静默拒绝 + """ + now = datetime.utcnow() + last = _PASSWORD_RESET_RATE_CACHE.get(key) + if last and (now - last).total_seconds() < window_seconds: + return False + _PASSWORD_RESET_RATE_CACHE[key] = now + return True + + +def _sync_casdoor_password_for_reset(user: User, new_password: str): + """ + Token 重置场景下将新密码同步至 Casdoor(无旧密码校验)。 + 核心逻辑:Casdoor 已配置时调用 set-password,oldPassword 传空串(与 change-password fallback 一致)。 + @param user: 本地用户 + @param new_password: 新密码明文 + Raises: + AppError: Casdoor 策略或 IdP 同步失败 + """ + if not _is_casdoor_configured(): + return + user_owner = _casdoor_user_owner() + try: + _casdoor_set_password(user_owner, user.username, '', new_password) + except RuntimeError as exc: + if _is_casdoor_user_missing_error(str(exc)): + _raise_casdoor_user_not_in_idp(exc) + _raise_casdoor_set_password_error(exc) + + +def _password_reset_rate_key(employee_id: str) -> str: + """ + 生成找回密码限流键。 + @param employee_id: 工号 + Returns: + employee_id 与客户端 IP 组合键 + """ + client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown' + return f'{employee_id}:{client_ip}' + + +@user_bp.route('/reset-password-by-wecom', methods=['POST']) +def reset_password_by_wecom(): + """ + 通过工号 + 用户名发起找回密码,并向已绑定 wecom_userid 发送 textcard 重置链接。 + Request JSON: { "employee_id": "...", "username": "..." } + """ + if not _is_wecom_configured(): + raise AppError( + code='WECOM.RESET_NOT_CONFIGURED', + message='WeCom password reset is not configured', + http_status=503, + details={ + 'error_code': 'WECOM_RESET_NOT_CONFIGURED', + 'missing': _get_wecom_config_missing_fields(), + }, + ) + if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)): + raise AppError( + code='WECOM.NOTIFY_DISABLED', + message='WeCom notification is disabled', + http_status=503, + details={'error_code': 'WECOM_NOTIFY_DISABLED'}, + ) + if not _get_password_reset_public_base_url(): + raise AppError( + code='WECOM.RESET_URL_NOT_CONFIGURED', + message='Password reset public base URL is not configured', + http_status=503, + details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'}, + ) + + data = request.get_json() or {} + employee_id = _clean_str(data.get('employee_id')) + username = _clean_str(data.get('username')) + if not employee_id: + raise ValidationError('Employee ID is required') + if not username: + raise ValidationError('Username is required') + + rate_key = _password_reset_rate_key(employee_id) + if not _check_password_reset_rate_limit(rate_key): + current_app.logger.info( + '[password_reset] noop reason=rate_limited employee_id=%s', + employee_id, + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + + user = db.session.query(User).filter(User.employee_id == employee_id).first() + if not user: + current_app.logger.info( + '[password_reset] noop reason=user_not_found employee_id=%s', + employee_id, + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + if user.username != username: + current_app.logger.info( + '[password_reset] noop reason=username_mismatch employee_id=%s user_id=%s', + employee_id, + user.id, + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + if user.status != 'active': + current_app.logger.info( + '[password_reset] noop reason=account_inactive employee_id=%s user_id=%s', + employee_id, + user.id, + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + if not user.wecom_userid: + current_app.logger.info( + '[password_reset] noop reason=wecom_unbound employee_id=%s user_id=%s', + employee_id, + user.id, + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + + token = str(uuid.uuid4()) + user.reset_token = token + user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1) + db.session.flush() + + title = 'HXOPS 密码重置' + content = ( + '您发起了 HXOPS 密码重置请求。\n' + '请在 1 小时内点击下方按钮设置新密码。\n' + '如非本人操作,请忽略本消息。' + ) + try: + result = send_wecom_event_message( + event_type='password_reset', + user=user, + title=title, + content=content, + jump_path='/reset-password', + jump_params={'token': token}, + ) + if not result.get('ok'): + db.session.rollback() + current_app.logger.warning( + '[password_reset] wecom send failed user_id=%s employee_id=%s reason=%s trace_id=%s raw=%s', + user.id, + employee_id, + result.get('reason'), + result.get('trace_id'), + result.get('raw'), + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + + db.session.commit() + current_app.logger.info( + '[password_reset] reset link sent user_id=%s employee_id=%s trace_id=%s', + user.id, + employee_id, + result.get('trace_id'), + ) + return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE}) + except Exception as exc: + db.session.rollback() + current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc) + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500) + + @user_bp.route('/reset-password-by-email', methods=['POST']) def reset_password_request(): """ @@ -1598,11 +1817,15 @@ def reset_password_confirm(): if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow(): raise ValidationError('Invalid or expired token') try: + _sync_casdoor_password_for_reset(user, new_password) user.set_password(new_password) user.reset_token = None user.reset_token_expiry = None db.session.commit() return jsonify({'message': 'Password has been reset successfully'}) + except AppError: + db.session.rollback() + raise except Exception as e: db.session.rollback() raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500) diff --git a/backend/app/config.py b/backend/app/config.py index 32e2d6ac..7deebdc2 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -188,7 +188,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', 'task_completed,schedule_completed') + WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset') # 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/services/wecom_directory_sync.py b/backend/app/services/wecom_directory_sync.py new file mode 100644 index 00000000..664c19e9 --- /dev/null +++ b/backend/app/services/wecom_directory_sync.py @@ -0,0 +1,244 @@ +""" +backend/app/services/wecom_directory_sync.py + +用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。 +依赖:Flask current_app、SQLAlchemy db、wecom_notify._get_access_token、User 模型。 +逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。 +""" + +from __future__ import annotations + +from typing import Any + +import requests +from flask import current_app + +from app import db +from app.models import User +from app.services.wecom_notify import _get_access_token + +_PREVIEW_LIMIT = 20 + + +def _clean_str(value) -> str | None: + """Trim string-like values; empty strings become None.""" + if value is None: + return None + text = str(value).strip() + return text or None + + +def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None: + """ + 从企微成员 extattr.attrs 中读取指定扩展字段。 + @param wecom_user: user/list 返回的成员 dict + @param key: 扩展属性名 + Returns: + 字段文本或 None + """ + extattr = wecom_user.get('extattr') or {} + attrs = extattr.get('attrs') if isinstance(extattr, dict) else None + if not isinstance(attrs, list): + return None + for attr in attrs: + if not isinstance(attr, dict): + continue + if _clean_str(attr.get('name')) != key: + continue + raw = attr.get('value') + if isinstance(raw, dict): + raw = raw.get('text') or raw.get('web') or raw.get('value') + return _clean_str(raw) + return None + + +def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None: + """ + 按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。 + 核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。 + """ + userid = _clean_str(wecom_user.get('userid')) + source = _clean_str(employee_id_source) or 'userid' + if source == 'userid': + return userid + if source.startswith('extattr:'): + return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1]) + return _clean_str(wecom_user.get(source)) + + +def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]: + """ + 拉取企业微信部门列表。 + Raises: + RuntimeError: API 失败 + """ + resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/department/list', + params={'access_token': access_token}, + timeout=15, + ) + data = resp.json() or {} + if data.get('errcode') != 0: + raise RuntimeError(f'department/list failed: {data}') + departments = data.get('department') or [] + if not isinstance(departments, list): + return [] + return [item for item in departments if isinstance(item, dict)] + + +def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]: + """ + 拉取指定部门(含子部门)成员简要列表。 + @param department_id: 企微部门 ID + Returns: + user/list 返回的 userlist + """ + resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/user/list', + params={ + 'access_token': access_token, + 'department_id': department_id, + 'fetch_child': 1, + }, + timeout=30, + ) + data = resp.json() or {} + if data.get('errcode') != 0: + raise RuntimeError(f'user/list failed department_id={department_id}: {data}') + userlist = data.get('userlist') or [] + if not isinstance(userlist, list): + return [] + return [item for item in userlist if isinstance(item, dict)] + + +def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]: + """ + 汇总多个部门成员,按 wecom_userid 去重。 + Returns: + key=userid, value=成员 dict + """ + merged: dict[str, dict[str, Any]] = {} + for dept_id in department_ids: + for user in fetch_wecom_users_in_department(access_token, dept_id): + userid = _clean_str(user.get('userid')) + if userid: + merged[userid] = user + return merged + + +def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]: + """ + 执行工号 → wecom_userid 同步。 + 核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。 + @param apply: True 时提交数据库;存在 conflicts 时不写入 + @param department_id: 指定根部门 ID;None 时使用全部部门 + Returns: + 统计摘要 dict(含 conflicts、pending_updates 预览) + """ + if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'): + raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured') + + employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid' + token = _get_access_token() + + if department_id is not None: + department_ids = [department_id] + else: + departments = fetch_wecom_departments(token) + department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None] + if not department_ids: + department_ids = [1] + + wecom_users = collect_wecom_users(token, department_ids) + summary: dict[str, Any] = { + 'apply': apply, + 'employee_id_source': employee_id_source, + 'department_ids': department_ids, + 'wecom_users': len(wecom_users), + 'wecom_without_employee_id': 0, + 'local_matched': 0, + 'would_update': 0, + 'updated': 0, + 'already_bound': 0, + 'local_missing': 0, + 'conflicts': [], + 'missing_samples': [], + 'pending_updates': [], + } + + for wecom_user in wecom_users.values(): + wecom_userid = _clean_str(wecom_user.get('userid')) + wecom_unionid = _clean_str(wecom_user.get('unionid')) + employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source) + if not employee_id: + summary['wecom_without_employee_id'] += 1 + if len(summary['missing_samples']) < _PREVIEW_LIMIT: + summary['missing_samples'].append( + {'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))} + ) + continue + + local_user = db.session.query(User).filter(User.employee_id == employee_id).first() + if not local_user: + summary['local_missing'] += 1 + continue + + summary['local_matched'] += 1 + + if local_user.wecom_userid == wecom_userid: + summary['already_bound'] += 1 + continue + + conflict = None + if local_user.wecom_userid and local_user.wecom_userid != wecom_userid: + conflict = { + 'employee_id': employee_id, + 'username': local_user.username, + 'old_wecom_userid': local_user.wecom_userid, + 'new_wecom_userid': wecom_userid, + } + else: + occupied = ( + db.session.query(User) + .filter(User.wecom_userid == wecom_userid, User.id != local_user.id) + .first() + ) + if occupied: + conflict = { + 'employee_id': employee_id, + 'username': local_user.username, + 'new_wecom_userid': wecom_userid, + 'occupied_by_user_id': occupied.id, + 'occupied_by_username': occupied.username, + } + + if conflict: + summary['conflicts'].append(conflict) + continue + + summary['would_update'] += 1 + if len(summary['pending_updates']) < _PREVIEW_LIMIT: + summary['pending_updates'].append( + { + 'employee_id': employee_id, + 'username': local_user.username, + 'wecom_userid': wecom_userid, + 'name': _clean_str(wecom_user.get('name')), + } + ) + if apply: + local_user.wecom_userid = wecom_userid + if wecom_unionid: + local_user.wecom_unionid = wecom_unionid + summary['updated'] += 1 + + if summary['conflicts'] and apply: + db.session.rollback() + raise RuntimeError('Conflicts detected; resolve manually before apply') + + if apply and summary['updated'] > 0: + db.session.commit() + elif apply: + db.session.rollback() + + return summary diff --git a/backend/app/services/wecom_notify.py b/backend/app/services/wecom_notify.py index 3be09db8..6fd2bac0 100644 --- a/backend/app/services/wecom_notify.py +++ b/backend/app/services/wecom_notify.py @@ -27,8 +27,22 @@ def _get_enabled_events() -> set[str]: return set() +def _get_notify_base_url() -> str: + """ + 解析企微 textcard 跳转基地址。 + 核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。 + Returns: + 去掉尾斜杠的基地址;均未配置时返回空字符串。 + """ + for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_BASE_URL'): + raw = current_app.config.get(key) + if isinstance(raw, str) and raw.strip(): + return raw.strip().rstrip('/') + return '' + + def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str: - base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or '' + base = _get_notify_base_url() if not base: return '' base = base.rstrip('/') @@ -133,7 +147,7 @@ def send_wecom_textcard_message( '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'), + 'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com', 'btntxt': '查看详情', }, 'safe': 0, diff --git a/backend/scripts/sync_wecom_userid_by_employee_id.py b/backend/scripts/sync_wecom_userid_by_employee_id.py new file mode 100644 index 00000000..1b295063 --- /dev/null +++ b/backend/scripts/sync_wecom_userid_by_employee_id.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +""" +backend/scripts/sync_wecom_userid_by_employee_id.py + +用途:从企业微信通讯录拉取成员,按工号(employee_id)回填本地 users.wecom_userid。 +依赖:app.create_app、wecom_directory_sync.sync_wecom_userids_from_directory。 +逻辑:运维 CLI;默认 dry-run,--apply 才写库。 + +Usage: + cd backend + python scripts/sync_wecom_userid_by_employee_id.py + python scripts/sync_wecom_userid_by_employee_id.py --apply + python scripts/sync_wecom_userid_by_employee_id.py --apply --department-id 1 +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] +if str(BACKEND_ROOT) not in sys.path: + sys.path.insert(0, str(BACKEND_ROOT)) + +from app import create_app # noqa: E402 +from app.services.wecom_directory_sync import sync_wecom_userids_from_directory # noqa: E402 + + +def main() -> int: + """CLI 入口:解析参数并打印同步摘要 JSON。""" + parser = argparse.ArgumentParser(description='Sync User.wecom_userid from WeCom directory by employee_id.') + parser.add_argument('--apply', action='store_true', help='Persist changes (default: dry-run).') + parser.add_argument('--department-id', type=int, default=None, help='Root department id (default: all departments).') + args = parser.parse_args() + + env = os.getenv('FLASK_ENV', 'production') + app = create_app(env) + with app.app_context(): + summary = sync_wecom_userids_from_directory(apply=args.apply, department_id=args.department_id) + + print(json.dumps(summary, ensure_ascii=False, indent=2)) + if summary.get('conflicts'): + print('\nConflicts detected; resolve manually before --apply.', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 80d6368d..3a5393e8 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -40,7 +40,10 @@ const SchedulesPage = () => const KnowledgeBasePage = () => import("@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue"); -const WecomPage = () => import("@/features/admin/modules/wecom/WecomPage.vue"); +const WecomLayout = () => import("@/features/admin/modules/wecom/WecomLayout.vue"); +const WecomSettingsPage = () => import("@/features/admin/modules/wecom/pages/WecomSettingsPage.vue"); +const WecomBindingsPage = () => import("@/features/admin/modules/wecom/pages/WecomBindingsPage.vue"); +const WecomAuditsPage = () => import("@/features/admin/modules/wecom/pages/WecomAuditsPage.vue"); const ReportsPage = () => import("@/features/admin/modules/reports/ReportsPage.vue"); @@ -83,8 +86,29 @@ export const adminRoutes: RouteRecordRaw[] = [ { path: "wecom", name: "AdminWecom", - component: WecomPage, + component: WecomLayout, + redirect: { name: "AdminWecomSettings" }, meta: { requiresAdmin: true, adminModule: "wecom", title: "企业微信" }, + children: [ + { + path: "settings", + name: "AdminWecomSettings", + component: WecomSettingsPage, + meta: { requiresAdmin: true, adminModule: "wecom", title: "企业微信配置" }, + }, + { + path: "bindings", + name: "AdminWecomBindings", + component: WecomBindingsPage, + meta: { requiresAdmin: true, adminModule: "wecom", title: "企业微信绑定" }, + }, + { + path: "audits", + name: "AdminWecomAudits", + component: WecomAuditsPage, + meta: { requiresAdmin: true, adminModule: "wecom", title: "企业微信审计" }, + }, + ], }, { path: "approvals", diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index a221f43c..e383b655 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -130,8 +130,26 @@ export const batchDeleteAdminChatLogs = (ids: number[]) => }); // WeCom admin -export const listAdminWecomBindings = (boundOnly: boolean) => - requestJson(`/api/admin/wecom/bindings?bound_only=${boundOnly ? 'true' : 'false'}`, auth()); +export interface ListAdminWecomBindingsParams { + boundOnly?: boolean; + keyword?: string; + page?: number; + pageSize?: number; +} + +export const listAdminWecomBindings = (params: ListAdminWecomBindingsParams = {}) => { + const qs = new URLSearchParams(); + if (params.boundOnly) qs.set('bound_only', 'true'); + const keyword = params.keyword?.trim(); + if (keyword) qs.set('keyword', keyword); + if (params.page) qs.set('page', String(params.page)); + if (params.pageSize) qs.set('page_size', String(params.pageSize)); + const query = qs.toString(); + const suffix = query ? `?${query}` : ''; + return requestJson>(`/api/admin/wecom/bindings${suffix}`, auth()); +}; export const listAdminWecomLoginAudits = (query: string) => requestJson(`/api/admin/wecom/login-audits?${query}`, auth()); export const getAdminWecomSystemSettings = () => @@ -154,6 +172,14 @@ export const saveAdminWecomNotifySettings = (payload: Record) = }); export const getAdminWecomNotifyMetrics = () => requestJson('/api/admin/wecom/notify-metrics', auth()); +export const getAdminWecomBindingStats = () => + requestJson('/api/admin/wecom/binding-stats', auth()); +export const syncAdminWecomUserids = (payload: { apply: boolean; department_id?: number | null }) => + requestJson('/api/admin/wecom/sync-userids', { + method: 'POST', + ...jsonAuth(), + body: JSON.stringify(payload), + }); export const bindAdminWecomUser = (payload: Record) => requestJson('/api/admin/wecom/bind', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); export const unbindAdminWecomUser = (userId: number) => diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index aa3e2136..220c5493 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -42,10 +42,25 @@ const visibleModules = computed(() => ADMIN_MODULE_METAS.filter((item) => config.admin.modules[item.configKey] !== false), ); +const standardModules = computed(() => + visibleModules.value.filter((item) => item.id !== 'wecom'), +); + const isModuleActive = (moduleId: AdminModuleId): boolean => route.meta.adminModule === moduleId; const isReportsActive = computed(() => route.meta.adminModule === 'reports'); +const isWecomActive = computed(() => route.meta.adminModule === 'wecom'); + +const wecomSubRoutes = [ + { name: 'AdminWecomSettings', labelKey: 'admin.wecom.nav.settings' }, + { name: 'AdminWecomBindings', labelKey: 'admin.wecom.nav.bindings' }, + { name: 'AdminWecomAudits', labelKey: 'admin.wecom.nav.audits' }, +] as const; + +const navigateWecom = (routeName: string): void => { + router.push({ name: routeName }); +}; const getReportTableLabel = (table: string): string => { const i18nKey = `admin.report.tables.${table}`; @@ -70,7 +85,7 @@ const navigateReport = (table: string): void => { >