""" backend/app/services/admin/wecom_admin_service.py 用途:管理端企微绑定、配置、诊断与 OA userid 同步。 依赖:wecom_auth_service、oa_wecom_sync、env_persistence、models。 逻辑:由 api/admin/wecom.py 调用。 """ from __future__ import annotations import uuid from datetime import datetime, timedelta from typing import Any import requests from flask import current_app from sqlalchemy import func, or_ from sqlalchemy.exc import IntegrityError from app import db from app.core.config.env_persistence import persist_env_settings from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError from app.models import Agent, LoginAudit, User, WecomNotifyAudit from app.services.auth import wecom_auth_service from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa def serialize_debug_match_user(user: User) -> dict: return { 'id': user.id, 'username': user.username, 'real_name': user.real_name, 'employee_id': user.employee_id, 'phone_number': user.phone_number, 'email': user.email, 'status': user.status, 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid, } def build_match_preview(identity: dict, rules: list[str], operator: str) -> dict: bind_mode = wecom_auth_service.get_first_login_bind_mode() preview = { 'bind_mode': bind_mode, 'rules': {'fields': rules, 'operator': operator}, 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), } bound_user = None if identity.get('wecom_userid'): bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first() if not bound_user and identity.get('wecom_unionid'): bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first() if bound_user: preview['decision'] = 'already_bound' preview['bound_user'] = serialize_debug_match_user(bound_user) return preview if bind_mode == 'input_verify': preview['decision'] = 'input_verification_required' preview['allowed_fields'] = wecom_auth_service.get_first_login_input_fields() return preview matched_users, missing_fields = wecom_auth_service.find_users_by_match_rules(identity, rules, operator) preview['missing_fields'] = missing_fields preview['matched_users'] = [serialize_debug_match_user(user) for user in matched_users] if missing_fields: preview['decision'] = 'missing_match_fields' elif len(matched_users) == 1: preview['decision'] = 'matched_existing_user' elif len(matched_users) > 1: preview['decision'] = 'ambiguous_match' elif preview['auto_create_user']: preview['decision'] = 'would_auto_create_user' else: preview['decision'] = 'bind_required' return preview def debug_user_by_code(code: str) -> dict: """通过 OAuth code 拉取企微用户并返回匹配预览(管理端诊断)。""" if not wecom_auth_service.is_configured(): raise ValidationError('WeCom login is not configured') code = str(code or '').strip() if not code: raise ValidationError('code is required') access_token = wecom_auth_service.get_access_token() info_resp = requests.get( 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8, ) auth_info = info_resp.json() userid = auth_info.get('userid') or auth_info.get('UserId') openid = auth_info.get('openid') or auth_info.get('OpenId') payload = {'auth_info': auth_info} if auth_info.get('errcode') != 0: raise AppError( code='WECOM_AUTH_FAILED', message=f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}", http_status=401, details={'auth_info': auth_info}, ) if not userid: raise AppError( code='WECOM_NOT_IN_AGENT_SCOPE', message='当前 code 对应的账号不在应用可见范围内,或不是本企业成员。', http_status=401, details={'auth_info': auth_info, 'openid': openid}, ) user_resp = requests.get( 'https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': userid}, timeout=8, ) wecom_user = user_resp.json() payload['wecom_user'] = wecom_user if wecom_user.get('errcode') != 0: raise AppError( code='WECOM_USER_FETCH_FAILED', message=f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}", http_status=401, details={'auth_info': auth_info, 'wecom_user': wecom_user}, ) identity = wecom_auth_service.extract_identity(wecom_user) rules, operator = wecom_auth_service.get_match_config() payload['normalized_identity'] = identity payload['match_preview'] = build_match_preview(identity, rules, operator) return payload def list_bindings(query_params: dict[str, str]) -> dict: bound_only = query_params.get('bound_only', 'false').lower() == 'true' keyword = (query_params.get('keyword') or '').strip() try: page = int(query_params.get('page') or 1) except (TypeError, ValueError): page = 1 try: page_size = int(query_params.get('page_size') or 20) except (TypeError, ValueError): page_size = 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)) 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 { 'items': items, 'total': int(total), 'page': page, 'page_size': page_size, 'pages': pages, } def bind_user(data: dict[str, Any]) -> dict: user_id = data.get('user_id') wecom_userid = data.get('wecom_userid') wecom_unionid = data.get('wecom_unionid') if not user_id or not wecom_userid: raise ValidationError('user_id and wecom_userid are required') try: user_id = int(user_id) except (TypeError, ValueError): raise ValidationError('user_id must be integer') user = db.session.get(User, user_id) if not user: raise NotFoundError('User not found') dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() if dup: raise ValidationError(f'wecom_userid already bound to user {dup.username}') if wecom_unionid: dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() if dup_union: raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') user.wecom_userid = wecom_userid if wecom_unionid is not None: user.wecom_unionid = wecom_unionid db.session.commit() return {'status': 'ok', 'message': 'WeCom binding updated'} def unbind_user(data: dict[str, Any]) -> dict: user_id = data.get('user_id') if not user_id: raise ValidationError('user_id is required') try: user_id = int(user_id) except (TypeError, ValueError): raise ValidationError('user_id must be integer') user = db.session.get(User, user_id) if not user: raise NotFoundError('User not found') user.wecom_userid = None user.wecom_unionid = None db.session.commit() return {'status': 'ok', 'message': 'WeCom account unbound'} def provision_user(data: dict[str, Any]) -> tuple[dict, int]: create_user_flag = bool(data.get('create_user', True)) user_data = data.get('user') or {} bind_data = data.get('bind') or {} user_id = data.get('user_id') permission_updated = False wecom_userid = (bind_data.get('wecom_userid') or '').strip() wecom_unionid = (bind_data.get('wecom_unionid') or '').strip() if not wecom_userid: raise ValidationError('bind.wecom_userid is required') if create_user_flag: username = (user_data.get('username') or '').strip() if not username: raise ValidationError('user.username is required when create_user=true') if db.session.query(User).filter_by(username=username).first(): raise ValidationError('Username exists') email = (user_data.get('email') or '').strip() or None employee_id = (user_data.get('employee_id') or '').strip() or None phone_number = (user_data.get('phone_number') or '').strip() or None if email and db.session.query(User).filter_by(email=email).first(): raise ValidationError('Email already exists') if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first(): raise ValidationError('Employee ID already exists') if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first(): raise ValidationError('Phone number already exists') user = User( username=username, email=email, department=user_data.get('department'), role=user_data.get('role', 'user'), status=user_data.get('status', 'active'), real_name=user_data.get('real_name'), employee_id=employee_id, phone_number=phone_number, ) password = user_data.get('password') user.set_password(password or uuid.uuid4().hex) db.session.add(user) db.session.flush() binding_status = 'created' status_code = 201 else: if user_id is None: user_id = user_data.get('id') if user_id is None: raise ValidationError('user_id is required when create_user=false') try: user_id = int(user_id) except (TypeError, ValueError): raise ValidationError('user_id must be integer') user = db.session.get(User, user_id) if not user: raise NotFoundError('User not found') binding_status = 'updated' status_code = 200 dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() if dup: db.session.rollback() raise ValidationError(f'wecom_userid already bound to user {dup.username}') if wecom_unionid: dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() if dup_union: db.session.rollback() raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') user.wecom_userid = wecom_userid if wecom_unionid: user.wecom_unionid = wecom_unionid if 'agent_ids' in data: agent_ids = data.get('agent_ids', []) if not isinstance(agent_ids, list): db.session.rollback() raise ValidationError('agent_ids must be array') if agent_ids: try: unique_ids = sorted({int(i) for i in agent_ids}) except (TypeError, ValueError): db.session.rollback() raise ValidationError('agent_ids must be integer array') agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all() if len(agents) != len(unique_ids): db.session.rollback() raise ValidationError('Some agent_ids are invalid') user.agents = agents else: user.agents = [] permission_updated = True try: db.session.commit() except IntegrityError: db.session.rollback() raise ValidationError('Provision failed due to data uniqueness conflict') return ( { 'status': 'ok', 'user_id': user.id, 'binding': binding_status, 'permission_updated': permission_updated, }, status_code, ) def list_login_audits(query_params: dict[str, str]) -> list[dict]: source = query_params.get('source') status = query_params.get('status') try: limit = max(1, min(int(query_params.get('limit', 100)), 500)) except (TypeError, ValueError): limit = 100 query = db.session.query(LoginAudit) if source: query = query.filter(LoginAudit.source == source) if status: query = query.filter(LoginAudit.status == status) rows = query.order_by(LoginAudit.created_at.desc()).limit(limit).all() return [ { 'id': r.id, 'user_id': r.user_id, 'username': r.username, 'source': r.source, 'status': r.status, 'reason': r.reason, 'error_code': r.error_code, 'match_rules': r.match_rules, 'match_operator': r.match_operator, 'match_result': r.match_result, 'wecom_userid': r.wecom_userid, 'ip': r.ip, 'user_agent': r.user_agent, 'created_at': r.created_at.isoformat() if r.created_at else None, } for r in rows ] def serialize_notify_settings() -> dict: return { 'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)), 'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '', 'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x], } def update_notify_settings(data: dict[str, Any]) -> dict: updates = {} if 'enabled' in data: updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled')) if 'base_url' in data: updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip() if 'events' in data: events = data.get('events') or [] if isinstance(events, list): updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()]) for key, value in updates.items(): current_app.config[key] = value persist_env_settings(updates) return {'status': 'ok', 'settings': serialize_notify_settings()} def serialize_system_settings() -> dict: return { 'enabled': bool(current_app.config.get('WECOM_ENABLED', False)), 'corp_id': current_app.config.get('WECOM_CORP_ID') or '', 'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''), 'secret': current_app.config.get('WECOM_SECRET') or '', 'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '', 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), 'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile', 'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(), 'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(), 'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email', 'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid', 'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)), 'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '', 'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '', 'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '', 'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '', 'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '', 'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '', } def update_system_settings(data: dict[str, Any]) -> dict: bool_keys = { 'enabled': 'WECOM_ENABLED', 'auto_create_user': 'WECOM_AUTO_CREATE_USER', 'mobile_normalize': 'WECOM_MOBILE_NORMALIZE', } str_keys = { 'corp_id': 'WECOM_CORP_ID', 'agent_id': 'WECOM_AGENT_ID', 'secret': 'WECOM_SECRET', 'redirect_uri': 'WECOM_REDIRECT_URI', 'match_rules': 'WECOM_MATCH_RULES', 'match_operator': 'WECOM_MATCH_OPERATOR', 'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE', 'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE', 'callback_token': 'WECOM_CALLBACK_TOKEN', 'encoding_aes_key': 'WECOM_ENCODING_AES_KEY', 'callback_url': 'WECOM_CALLBACK_URL', 'homepage_url': 'WECOM_HOMEPAGE_URL', 'trusted_domain': 'WECOM_TRUSTED_DOMAIN', 'public_base_url': 'WECOM_PUBLIC_BASE_URL', } updates = {} for req_key, cfg_key in bool_keys.items(): if req_key in data: updates[cfg_key] = bool(data.get(req_key)) for req_key, cfg_key in str_keys.items(): if req_key in data: updates[cfg_key] = str(data.get(req_key) or '').strip() for key, value in updates.items(): current_app.config[key] = value if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}: current_app.config['WECOM_MATCH_OPERATOR'] = 'AND' updates['WECOM_MATCH_OPERATOR'] = 'AND' if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}: current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' persist_env_settings(updates) return {'status': 'ok', 'settings': serialize_system_settings()} def integration_manifest(*, host_url: str, host: str) -> dict: settings = serialize_system_settings() public_base = (settings.get('public_base_url') or '').rstrip('/') if not public_base: for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'): configured = current_app.config.get(key) or '' if configured: public_base = configured.rstrip('/') break if not public_base: public_base = host_url.rstrip('/') callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback' homepage_url = settings.get('homepage_url') or f'{public_base}/workspace' trusted_domain = settings.get('trusted_domain') or host.split(':')[0] return { 'public_base_url': public_base, 'callback_url': callback_url, 'callback_token': settings.get('callback_token') or '', 'encoding_aes_key': settings.get('encoding_aes_key') or '', 'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url, 'homepage_url': homepage_url, 'trusted_domain': trusted_domain, 'authorize_api': f'{public_base}/api/user/wecom/authorize-url', 'login_api': f'{public_base}/api/user/wecom/login', } def notify_metrics() -> dict: now = datetime.utcnow() from_time = now - timedelta(days=30) total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0 sent = db.session.query(func.count(WecomNotifyAudit.id)).filter( WecomNotifyAudit.created_at >= from_time, WecomNotifyAudit.status == 'sent', ).scalar() or 0 opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter( WecomNotifyAudit.created_at >= from_time, WecomNotifyAudit.opened_at.isnot(None), ).scalar() or 0 by_event_rows = ( db.session.query(WecomNotifyAudit.event_type, WecomNotifyAudit.status, func.count(WecomNotifyAudit.id)) .filter(WecomNotifyAudit.created_at >= from_time) .group_by(WecomNotifyAudit.event_type, WecomNotifyAudit.status) .all() ) by_event = {} for event_type, status, cnt in by_event_rows: if event_type not in by_event: by_event[event_type] = {'sent': 0, 'failed': 0} by_event[event_type][status] = int(cnt) return { '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, } def binding_stats() -> dict: 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 { '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, } def sync_userids(*, apply: bool) -> dict: try: summary = sync_wecom_userids_from_oa(apply=apply) current_app.logger.info( '[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s', apply, summary.get('updated'), summary.get('would_update'), len(summary.get('conflicts') or []), summary.get('local_matched'), ) return summary except RuntimeError as exc: message = str(exc) if 'conflicts detected' in message.lower(): raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'}) if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower(): raise AppError( code='SYSTEM.SERVICE_UNAVAILABLE', message='OA SQL Server driver is not available on this server', http_status=503, details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]}, ) raise AppError( code='SYSTEM.HTTP_ERROR', message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.', http_status=502, details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]}, ) except Exception as exc: current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc) raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500)