""" backend/app/services/integrations/oa/wecom_sync.py 用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。 依赖:OASQLServerService、SQLAlchemy db、User 模型。 逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。 """ from __future__ import annotations from typing import Any from app import db from app.models import User from app.services.integrations.oa.sqlserver import OASQLServerService _PREVIEW_LIMIT = 20 _OA_VIEW = 'userInfo_view' _OA_IN_BATCH_SIZE = 500 def _clean_str(value) -> str | None: """ 规范化字符串;空值返回 None。 @param value: 任意输入 Returns: 去首尾空白后的字符串,或 None """ if value is None: return None text = str(value).strip() return text or None def _load_local_users_with_employee_id() -> list[tuple[User, str]]: """ 加载本地含有效工号的用户列表。 核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。 Returns: (User, employee_id) 元组列表 """ rows: list[tuple[User, str]] = [] for user in db.session.query(User).filter(User.employee_id.isnot(None)).all(): employee_id = _clean_str(user.employee_id) if not employee_id: continue rows.append((user, employee_id)) return rows def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]: """ 按工号批量查询 OA userInfo_view 中的企微 userid 映射。 核心逻辑:工号去重后分批 IN 查询,避免全表扫描。 @param workcodes: 本地 users.employee_id 列表 Returns: 每项含 workcode、wecom_userid、name Raises: RuntimeError: ODBC 连接或查询失败 """ unique_codes: list[str] = [] seen: set[str] = set() for code in workcodes: cleaned = _clean_str(code) if not cleaned or cleaned in seen: continue seen.add(cleaned) unique_codes.append(cleaned) if not unique_codes: return [] connection = OASQLServerService._connect() cursor = connection.cursor() rows: list[dict[str, str | None]] = [] try: for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE): batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE] placeholders = ','.join('?' for _ in batch) cursor.execute( f""" SELECT id, workcode, lastname FROM userInfo_view WHERE workcode IN ({placeholders}) AND id IS NOT NULL """, batch, ) for row in cursor.fetchall(): workcode = _clean_str(row.workcode) wecom_userid = _clean_str(row.id) if not workcode or not wecom_userid: continue rows.append( { 'workcode': workcode, 'wecom_userid': wecom_userid, 'name': _clean_str(row.lastname), } ) return rows finally: try: cursor.close() finally: connection.close() def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]: """ 执行 OA 工号 → wecom_userid 同步(本地用户驱动)。 核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。 @param apply: True 时提交数据库;存在 conflicts 时不写入 Returns: 统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用) Raises: RuntimeError: OA 未配置、连接失败或 apply 时存在冲突 """ local_users = _load_local_users_with_employee_id() workcodes = [employee_id for _, employee_id in local_users] oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes) summary: dict[str, Any] = { 'apply': apply, 'employee_id_source': f'oa:{_OA_VIEW}.workcode', 'department_ids': [], 'local_candidates': len(local_users), 'wecom_users': 0, 'wecom_without_employee_id': 0, 'local_matched': 0, 'would_update': 0, 'updated': 0, 'already_bound': 0, 'local_missing': 0, 'conflicts': [], 'missing_samples': [], 'pending_updates': [], } oa_by_workcode: dict[str, dict[str, str | None]] = {} duplicate_workcodes: set[str] = set() for row in oa_rows: workcode = row['workcode'] if not workcode: continue if workcode in oa_by_workcode: duplicate_workcodes.add(workcode) summary['conflicts'].append( { 'employee_id': workcode, 'username': '', 'new_wecom_userid': row['wecom_userid'], 'reason': 'duplicate_workcode_in_oa', } ) continue oa_by_workcode[workcode] = row summary['wecom_users'] = len(oa_by_workcode) for local_user, employee_id in local_users: if employee_id in duplicate_workcodes: continue oa_row = oa_by_workcode.get(employee_id) if not oa_row: summary['local_missing'] += 1 if len(summary['missing_samples']) < _PREVIEW_LIMIT: summary['missing_samples'].append( { 'employee_id': employee_id, 'username': local_user.username, } ) continue wecom_userid = oa_row['wecom_userid'] name = oa_row.get('name') if not wecom_userid: summary['wecom_without_employee_id'] += 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': name, } ) if apply: local_user.wecom_userid = wecom_userid 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