From 638fdcb7fdab403d34f1f36c61850f2f45a31a84 Mon Sep 17 00:00:00 2001 From: sophie Date: Tue, 16 Jun 2026 12:00:31 +0800 Subject: [PATCH] =?UTF-8?q?fix(admin):=20=E4=BC=81=E4=B8=9A=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E7=AE=A1=E7=90=86=E7=95=8C=E9=9D=A2=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E4=BB=8EOA=E4=B8=80=E9=94=AE=E5=90=8C=E6=AD=A5=E4=BC=81?= =?UTF-8?q?=E4=B8=9A=E5=BE=AE=E4=BF=A1ID=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/admin.py | 46 ++-- backend/app/services/oa_wecom_sync.py | 240 ++++++++++++++++++ backend/tests/test_oa_wecom_sync.py | 106 ++++++++ frontend/src/features/admin/api/admin.api.ts | 2 +- .../wecom/components/WecomSyncPanel.vue | 87 ++++--- .../modules/wecom/composables/useWecomSync.ts | 85 ++++--- .../modules/wecom/pages/WecomBindingsPage.vue | 31 +-- .../modules/wecom/pages/WecomSettingsPage.vue | 13 +- .../src/features/admin/types/wecom.types.ts | 1 + frontend/src/locales/en/admin.json | 20 +- frontend/src/locales/th/admin.json | 20 +- frontend/src/locales/zh-CN/admin.json | 20 +- frontend/src/locales/zh-TW/admin.json | 20 +- .../shared/components/DeleteConfirmDialog.vue | 10 +- frontend/src/style.css | 4 + 15 files changed, 570 insertions(+), 135 deletions(-) create mode 100644 backend/app/services/oa_wecom_sync.py create mode 100644 backend/tests/test_oa_wecom_sync.py diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 1e7bab7d..3252029f 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -20,7 +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.oa_wecom_sync import sync_wecom_userids_from_oa 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 @@ -1258,46 +1258,40 @@ def wecom_binding_stats(): @require_admin def sync_wecom_userids_admin(): """ - 从企微通讯录按工号同步 users.wecom_userid。 - Request JSON: { "apply": false, "department_id": 1 } + 从 OA userInfo_view 按工号同步 users.wecom_userid(workcode→employee_id,id→wecom_userid)。 + Request JSON: { "apply": false } """ 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) + summary = sync_wecom_userids_from_oa(apply=apply) current_app.logger.info( - '[wecom_sync] admin apply=%s updated=%s would_update=%s conflicts=%s', + '[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 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(): + if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' 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]}, + 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.INTERNAL_ERROR', message=message, http_status=500) + 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) diff --git a/backend/app/services/oa_wecom_sync.py b/backend/app/services/oa_wecom_sync.py new file mode 100644 index 00000000..998e43fc --- /dev/null +++ b/backend/app/services/oa_wecom_sync.py @@ -0,0 +1,240 @@ +""" +backend/app/services/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.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 + \ No newline at end of file diff --git a/backend/tests/test_oa_wecom_sync.py b/backend/tests/test_oa_wecom_sync.py new file mode 100644 index 00000000..b5d72fc3 --- /dev/null +++ b/backend/tests/test_oa_wecom_sync.py @@ -0,0 +1,106 @@ +"""Tests for OA userInfo_view → wecom_userid sync.""" + +from unittest.mock import patch + +import pytest + +from app.models import User +from app.services.oa_wecom_sync import sync_wecom_userids_from_oa + + +@pytest.fixture +def oa_rows_for_local_user(): + return [ + {'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'}, + ] + + +def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user): + with app.app_context(): + user = User( + username='26030025', + email='26030025@test.local', + employee_id='26030025', + real_name='sophie', + role='user', + status='active', + ) + user.set_password('test123') + from app import db + + db.session.add(user) + db.session.commit() + + with patch( + 'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes', + return_value=oa_rows_for_local_user, + ) as fetch_mock: + summary = sync_wecom_userids_from_oa(apply=False) + + fetch_mock.assert_called_once_with(['26030025']) + assert summary['local_candidates'] == 1 + assert summary['wecom_users'] == 1 + assert summary['local_matched'] == 1 + assert summary['would_update'] == 1 + assert summary['local_missing'] == 0 + assert summary['pending_updates'][0]['wecom_userid'] == '21784' + + db.session.refresh(user) + assert user.wecom_userid is None + + +def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user): + with app.app_context(): + user = User( + username='26030025', + email='26030025@test.local', + employee_id='26030025', + real_name='sophie', + role='user', + status='active', + ) + user.set_password('test123') + from app import db + + db.session.add(user) + db.session.commit() + + with patch( + 'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes', + return_value=oa_rows_for_local_user, + ): + summary = sync_wecom_userids_from_oa(apply=True) + + assert summary['updated'] == 1 + db.session.refresh(user) + assert user.wecom_userid == '21784' + + +def test_sync_wecom_userids_from_oa_local_not_in_oa(app): + with app.app_context(): + user = User( + username='missing_oa', + email='missing_oa@test.local', + employee_id='99999999', + real_name='missing', + role='user', + status='active', + ) + user.set_password('test123') + from app import db + + db.session.add(user) + db.session.commit() + + with patch( + 'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes', + return_value=[], + ) as fetch_mock: + summary = sync_wecom_userids_from_oa(apply=False) + + fetch_mock.assert_called_once_with(['99999999']) + assert summary['local_candidates'] == 1 + assert summary['wecom_users'] == 0 + assert summary['local_matched'] == 0 + assert summary['local_missing'] == 1 + \ No newline at end of file diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index e383b655..03870870 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -174,7 +174,7 @@ 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 }) => +export const syncAdminWecomUserids = (payload: { apply: boolean }) => requestJson('/api/admin/wecom/sync-userids', { method: 'POST', ...jsonAuth(), diff --git a/frontend/src/features/admin/modules/wecom/components/WecomSyncPanel.vue b/frontend/src/features/admin/modules/wecom/components/WecomSyncPanel.vue index 1768e82d..8a7d5c5c 100644 --- a/frontend/src/features/admin/modules/wecom/components/WecomSyncPanel.vue +++ b/frontend/src/features/admin/modules/wecom/components/WecomSyncPanel.vue @@ -1,7 +1,9 @@ - -