245 lines
8.4 KiB
Python
245 lines
8.4 KiB
Python
"""
|
||
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
|