Merge branch 'dev' into hugo

This commit is contained in:
hugo committed 2026-06-16 13:32:30 +08:00
commit 7544361c05
15 files changed
+570 -135

No files matched your search

+20 -26
View File
@@ -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)
+240
View File
@@ -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␍
␍
+106
View File
@@ -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␍
␍
+1 -1
View File
@@ -174,7 +174,7 @@ export const getAdminWecomNotifyMetrics = () =>
requestJson<any>('/api/admin/wecom/notify-metrics', auth());
export const getAdminWecomBindingStats = () =>
requestJson<import('@/features/admin/types/wecom.types').WecomBindingStats>('/api/admin/wecom/binding-stats', auth());
export const syncAdminWecomUserids = (payload: { apply: boolean; department_id?: number | null }) =>
export const syncAdminWecomUserids = (payload: { apply: boolean }) =>
requestJson<import('@/features/admin/types/wecom.types').WecomSyncSummary>('/api/admin/wecom/sync-userids', {
method: 'POST',
...jsonAuth(),
@@ -1,7 +1,9 @@
<script setup lang="ts">
/**
* features/admin/modules/wecom/components/WecomSyncPanel.vue
* 企微通讯录 userid 一键同步面板(预览 + 确认写入)。
* OA userInfo_view 工号→wecom_userid 同步面板(预览 + 确认写入)。
* 依赖:useWecomSync、WECOM_ADMIN_KEY.refreshWecomData。
* 逻辑:绑定管理页调用;先扫本地工号,再按 IN 查 OA userInfo_view 匹配写入。
*/
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -15,13 +17,14 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
const { wecomSystemSettings, refreshWecomData } = inject(WECOM_ADMIN_KEY)!;
const { refreshWecomData } = inject(WECOM_ADMIN_KEY)!;
const {
departmentId,
isSyncing,
previewSummary,
showApplyConfirm,
canApplySync,
applyBlockHint,
previewSync,
requestApplySync,
confirmApplySync,
@@ -38,53 +41,57 @@ const {
<div>
<h3 class="font-semibold text-primary">{{ t('admin.wecom.sync.title') }}</h3>
<p class="mt-1 text-sm text-muted">{{ t('admin.wecom.sync.desc') }}</p>
<p class="mt-2 text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">
{{ t('admin.wecom.sync.permissionNote') }}
<p class="mt-2 text-xs text-sky-900 bg-sky-50 border border-sky-100 rounded-lg px-3 py-2">
{{ t('admin.wecom.sync.oaSourceNote') }}
</p>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
<div>
<label class="mb-1.5 block text-xs text-muted">{{ t('admin.wecom.sync.employeeIdSource') }}</label>
<input
:value="wecomSystemSettings.employee_id_source"
readonly
class="input-field bg-surface-soft"
/>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.oaWorkcodeField') }}</div>
<div class="mt-1 font-mono text-primary">userInfo_view.workcode</div>
</div>
<div>
<label class="mb-1.5 block text-xs text-muted">{{ t('admin.wecom.sync.departmentId') }}</label>
<input
v-model="departmentId"
:placeholder="t('admin.wecom.sync.departmentIdPlaceholder')"
class="input-field"
/>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.oaWecomIdField') }}</div>
<div class="mt-1 font-mono text-primary">userInfo_view.id</div>
</div>
</div>
<div class="flex flex-wrap gap-2">
<button type="button" class="btn-secondary inline-flex items-center gap-2" :disabled="isSyncing" @click="previewSync">
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isSyncing }" />
{{ t('admin.wecom.sync.preview') }}
</button>
<button
type="button"
class="btn-primary"
:disabled="isSyncing || !previewSummary || (previewSummary.conflicts?.length || 0) > 0 || (previewSummary.would_update || 0) <= 0"
@click="requestApplySync"
>
{{ t('admin.wecom.sync.apply') }}
</button>
<div class="space-y-2">
<div class="flex flex-wrap gap-2">
<button
type="button"
class="inline-flex items-center gap-2"
:class="isSyncing ? 'btn-secondary opacity-60' : 'btn-primary'"
:disabled="isSyncing"
@click="previewSync"
>
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isSyncing }" />
{{ t('admin.wecom.sync.preview') }}
</button>
<button
type="button"
:class="canApplySync && !isSyncing ? 'btn-primary' : 'btn-secondary opacity-60'"
:disabled="isSyncing"
:title="applyBlockHint || undefined"
@click="requestApplySync"
>
{{ t('admin.wecom.sync.apply') }}
</button>
</div>
<p v-if="applyBlockHint && !isSyncing" class="text-xs text-muted">
{{ applyBlockHint }}
</p>
</div>
<div v-if="previewSummary" class="rounded-xl border border-subtle bg-surface-soft p-4 space-y-3 text-sm">
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
<div>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.wecomUsers') }}</div>
<div class="font-semibold text-primary">{{ previewSummary.wecom_users }}</div>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.localCandidates') }}</div>
<div class="font-semibold text-primary">{{ previewSummary.local_candidates }}</div>
</div>
<div>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.localMatched') }}</div>
<div class="text-xs text-muted">{{ t('admin.wecom.sync.stats.oaMatched') }}</div>
<div class="font-semibold text-primary">{{ previewSummary.local_matched }}</div>
</div>
<div>
@@ -99,6 +106,10 @@ const {
</div>
</div>
<div v-if="previewSummary.local_missing > 0" class="text-xs text-muted">
{{ t('admin.wecom.sync.localMissingHint', { count: previewSummary.local_missing }) }}
</div>
<div v-if="previewSummary.pending_updates?.length" class="overflow-x-auto">
<table class="admin-table min-w-full">
<thead>
@@ -111,7 +122,10 @@ const {
<tbody>
<tr v-for="row in previewSummary.pending_updates" :key="`${row.employee_id}-${row.wecom_userid}`">
<td class="px-3 py-2 text-xs">{{ row.employee_id }}</td>
<td class="px-3 py-2 text-xs">{{ row.username }}</td>
<td class="px-3 py-2 text-xs">
{{ row.username }}
<span v-if="row.name" class="text-muted"> · {{ row.name }}</span>
</td>
<td class="px-3 py-2 text-xs font-mono">{{ row.wecom_userid }}</td>
</tr>
</tbody>
@@ -137,7 +151,10 @@ const {
<DeleteConfirmDialog
v-model="showApplyConfirm"
:title="t('admin.wecom.sync.applyConfirmTitle')"
:message="t('admin.wecom.sync.applyConfirm', { count: previewSummary?.would_update || 0 })"
:confirm-text="t('admin.wecom.sync.applyConfirmButton')"
confirm-tone="primary"
@confirm="confirmApplySync"
/>
</div>
@@ -1,50 +1,76 @@
/**
* features/admin/modules/wecom/composables/useWecomSync.ts
* 企微通讯录 userid 同步:预览 dry-run 与确认写入。
* OA userInfo_view → 本地 wecom_userid 同步:预览 dry-run 与确认写入。
*/
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { syncAdminWecomUserids } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { WecomSyncSummary } from '@/features/admin/types/wecom.types';
/** 确认写入被拦截的原因(用于按钮样式与提示文案) */
export type WecomSyncApplyBlockReason = 'preview_first' | 'preview_failed' | 'conflicts' | 'nothing';
export function useWecomSync(options?: { onApplied?: () => void | Promise<void> }) {
const { t } = useI18n();
const msg = useMessage();
const departmentId = ref('');
const isSyncing = ref(false);
const previewSummary = ref<WecomSyncSummary | null>(null);
const showApplyConfirm = ref(false);
const previewAttempted = ref(false);
const previewFailed = ref(false);
/**
* 解析可选部门 ID;空字符串表示同步全部部门。
* @returns number | null 合法值;false 表示格式非法
* 判断当前是否允许打开确认写入弹窗。
*/
const parseDepartmentId = (): number | null | false => {
const raw = departmentId.value.trim();
if (!raw) return null;
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed <= 0) {
return false;
}
return parsed;
};
const canApplySync = computed(() => {
if (!previewSummary.value) return false;
if ((previewSummary.value.conflicts || []).length > 0) return false;
return (previewSummary.value.would_update || 0) > 0;
});
/**
* 预览同步结果(dry-run,不写库)。
* 确认写入不可用时的原因,用于按钮旁提示。
*/
const applyBlockReason = computed((): WecomSyncApplyBlockReason | null => {
if (canApplySync.value) return null;
if (previewFailed.value || (previewAttempted.value && !previewSummary.value)) {
return 'preview_failed';
}
if (!previewSummary.value) return 'preview_first';
if ((previewSummary.value.conflicts || []).length > 0) return 'conflicts';
return 'nothing';
});
/**
* 与 applyBlockReason 对应的界面提示文案。
*/
const applyBlockHint = computed(() => {
const reason = applyBlockReason.value;
if (!reason) return '';
const keyMap: Record<WecomSyncApplyBlockReason, string> = {
preview_first: 'admin.wecom.sync.applyHintPreviewFirst',
preview_failed: 'admin.wecom.sync.applyHintPreviewFailed',
conflicts: 'admin.wecom.sync.applyHintConflicts',
nothing: 'admin.wecom.sync.applyHintNothing',
};
return t(keyMap[reason]);
});
/**
* 预览 OA 同步结果(dry-run,不写库)。
*/
const previewSync = async (): Promise<void> => {
const deptId = parseDepartmentId();
if (deptId === false) {
msg.warning(t('admin.wecom.sync.invalidDepartmentId'));
return;
}
isSyncing.value = true;
previewAttempted.value = true;
previewFailed.value = false;
try {
previewSummary.value = await syncAdminWecomUserids({ apply: false, department_id: deptId });
previewSummary.value = await syncAdminWecomUserids({ apply: false });
msg.success(t('admin.wecom.sync.previewDone'));
} catch (e) {
previewSummary.value = null;
previewFailed.value = true;
console.error(e);
msg.error((e as Error).message || t('admin.wecom.sync.previewFailed'));
} finally {
@@ -53,9 +79,14 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
};
/**
* 打开确认写入对话框;需先预览且无冲突。
* 打开确认写入对话框;不可写入时弹出对应提示。
*/
const requestApplySync = (): void => {
if (isSyncing.value) return;
if (previewFailed.value || (previewAttempted.value && !previewSummary.value)) {
msg.warning(t('admin.wecom.sync.previewFirstAfterFail'));
return;
}
if (!previewSummary.value) {
msg.warning(t('admin.wecom.sync.previewFirst'));
return;
@@ -75,14 +106,9 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
* 确认后将预览结果写入数据库。
*/
const confirmApplySync = async (): Promise<void> => {
const deptId = parseDepartmentId();
if (deptId === false) {
msg.warning(t('admin.wecom.sync.invalidDepartmentId'));
return;
}
isSyncing.value = true;
try {
const summary = await syncAdminWecomUserids({ apply: true, department_id: deptId });
const summary = await syncAdminWecomUserids({ apply: true });
previewSummary.value = summary;
showApplyConfirm.value = false;
msg.success(t('admin.wecom.sync.applyDone', { count: summary.updated || 0 }));
@@ -96,10 +122,11 @@ export function useWecomSync(options?: { onApplied?: () => void | Promise<void>
};
return {
departmentId,
isSyncing,
previewSummary,
showApplyConfirm,
canApplySync,
applyBlockHint,
previewSync,
requestApplySync,
confirmApplySync,
@@ -1,31 +1,18 @@
<script setup lang="ts">
/**
* features/admin/modules/wecom/pages/WecomBindingsPage.vue
* 企微快速绑定与绑定列表(搜索 + 服务端分页)。
* 依赖:WECOM_ADMIN_KEY、PaginationBar、lucide-vue-next。
* 逻辑:inject 父级 useWecomAdmin 状态;列表区复用 PaginationBar。
* 企微 OA 同步、快速绑定与绑定列表(搜索 + 服务端分页)。
* 依赖:WECOM_ADMIN_KEY、WecomSyncPanel、PaginationBar。
*/
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { Link2, Search, Unlink2 } from 'lucide-vue-next';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import WecomOverviewCards from '../components/WecomOverviewCards.vue';
import WecomSyncPanel from '../components/WecomSyncPanel.vue';
import { WECOM_ADMIN_KEY } from '../wecom.context';
const { t } = useI18n();
const {
wecomBindUserQuery,
@@ -62,15 +49,19 @@ const {
unbindWecomUserByAdmin,
refreshWecomData,
} = inject(WECOM_ADMIN_KEY)!;
const onSyncApplied = async (): Promise<void> => {
await refreshWecomData();
};
</script>
<template>
<div class="space-y-6">
<WecomOverviewCards />
<WecomSyncPanel @applied="onSyncApplied" />
<p class="text-sm text-muted">{{ t('admin.wecom.bindingsHint') }}</p>
@@ -1,13 +1,12 @@
<script setup lang="ts">
/**
* features/admin/modules/wecom/pages/WecomSettingsPage.vue
* 企微系统配置、通讯录同步、通知与集成复制。
* 企微系统配置、通知与集成复制。
*/
import { inject, ref } from 'vue';
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp } from 'lucide-vue-next';
import WecomOverviewCards from '../components/WecomOverviewCards.vue';
import WecomSyncPanel from '../components/WecomSyncPanel.vue';
import { WECOM_ADMIN_KEY } from '../wecom.context';
const { t } = useI18n();
@@ -25,17 +24,11 @@ const {
saveWecomNotifySettings,
copyText,
} = inject(WECOM_ADMIN_KEY)!;
const overviewRefreshKey = ref(0);
const onSyncApplied = (): void => {
overviewRefreshKey.value += 1;
};
</script>
<template>
<div class="space-y-6">
<WecomOverviewCards :refresh-key="overviewRefreshKey" />
<WecomSyncPanel @applied="onSyncApplied" />
<WecomOverviewCards />
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
@@ -110,6 +110,7 @@ export interface WecomSyncSummary {
apply: boolean;
employee_id_source: string;
department_ids: number[];
local_candidates: number;
wecom_users: number;
wecom_without_employee_id: number;
local_matched: number;
+17 -3
View File
@@ -252,20 +252,31 @@
"hintDesc": "Users without wecom_userid cannot receive WeCom reset links"
},
"sync": {
"title": "Directory Sync",
"desc": "Pull WeCom members and backfill users.wecom_userid by employee ID for reset and notifications.",
"title": "OA Binding Sync",
"desc": "Backfill users.wecom_userid from OA userInfo_view by employee ID for reset and notifications.",
"permissionNote": "Requires contact read and message send permissions on the WeCom app.",
"oaSourceNote": "Source: OA SQL Server (ecology.userInfo_view). workcode → employee_id, id → wecom_userid. Configure OA_SQLSERVER_* env vars.",
"oaWorkcodeField": "Employee ID field (→ employee_id)",
"oaWecomIdField": "WeCom ID field (→ wecom_userid)",
"employeeIdSource": "Employee ID source",
"departmentId": "Root department ID (optional)",
"departmentIdPlaceholder": "Leave empty for all departments",
"preview": "Preview sync",
"apply": "Apply changes",
"previewDone": "Preview completed. Review results before applying.",
"previewFailed": "Preview sync failed",
"previewFailed": "Preview sync failed. Check OA SQL Server connection and OA_SQLSERVER_* settings.",
"previewFirst": "Please preview sync results first",
"previewFirstAfterFail": "Preview failed. Check OA database connection and env vars, then preview again.",
"applyHintPreviewFirst": "Click Preview sync first; apply is available after a successful preview.",
"applyHintPreviewFailed": "Preview did not succeed. Check OA SQL Server (OA_SQLSERVER_*) and network access.",
"applyHintConflicts": "Conflicts detected. Resolve them before applying.",
"applyHintNothing": "Nothing to update in the preview; apply is not needed.",
"localMissingHint": "{count} local employee IDs were not found in OA and will be skipped",
"conflictsBlockApply": "Conflicts detected. Resolve them before applying.",
"nothingToUpdate": "Nothing to update",
"applyConfirmTitle": "Confirm binding write",
"applyConfirm": "Write {count} userid bindings to the database?",
"applyConfirmButton": "Confirm write",
"applyDone": "Successfully updated {count} bindings",
"applyFailed": "Failed to apply sync results",
"invalidDepartmentId": "Department ID must be a positive integer",
@@ -274,6 +285,9 @@
"occupiedBy": "userid already used by {user}",
"stats": {
"wecomUsers": "WeCom members",
"oaRows": "OA rows",
"localCandidates": "Local with employee ID",
"oaMatched": "OA matched",
"localMatched": "Local matched",
"wouldUpdate": "Would update",
"conflicts": "Conflicts"
+17 -3
View File
@@ -252,20 +252,31 @@
"hintDesc": "ผู้ใช้ที่ไม่มี wecom_userid จะไม่ได้รับลิงก์รีเซ็ตผ่าน WeCom"
},
"sync": {
"title": "ซิงค์สมุดรายชื่อ",
"desc": "ดึงสมาชิก WeCom และเติม users.wecom_userid ตามรหัสพนักงาน",
"title": "ซิงค์ OA Binding",
"desc": "เติม users.wecom_userid จาก OA userInfo_view ตามรหัสพนักงาน",
"permissionNote": "แอป WeCom ต้องมีสิทธิ์อ่านสมุดรายชื่อและส่งข้อความ",
"oaSourceNote": "แหล่งข้อมูล: OA SQL Server (ecology.userInfo_view) workcode → employee_id, id → wecom_userid ตั้งค่า OA_SQLSERVER_*",
"oaWorkcodeField": "ฟิลด์รหัสพนักงาน (→ employee_id)",
"oaWecomIdField": "ฟิลด์ WeCom ID (→ wecom_userid)",
"employeeIdSource": "แหล่งรหัสพนักงาน",
"departmentId": "รหัสแผนกราก (ไม่บังคับ)",
"departmentIdPlaceholder": "เว้นว่างเพื่อซิงค์ทุกแผนก",
"preview": "ดูตัวอย่าง",
"apply": "ยืนยันเขียน",
"previewDone": "ดูตัวอย่างเสร็จแล้ว โปรดตรวจสอบก่อนยืนยัน",
"previewFailed": "ดูตัวอย่างล้มเหลว",
"previewFailed": "ดูตัวอย่างล้มเหลว ตรวจการเชื่อมต่อ OA และ OA_SQLSERVER_*",
"previewFirst": "โปรดดูตัวอย่างก่อน",
"previewFirstAfterFail": "ดูตัวอย่างล้มเหลว ตรวจการเชื่อมต่อ OA และ env แล้วลองใหม่",
"applyHintPreviewFirst": "กดดูตัวอย่างก่อน จึงจะยืนยันเขียนได้หลังสำเร็จ",
"applyHintPreviewFailed": "ดูตัวอย่างไม่สำเร็จ ตรวจ OA SQL Server (OA_SQLSERVER_*) และเครือข่าย",
"applyHintConflicts": "พบความขัดแย้ง โปรดแก้ไขก่อนยืนยันเขียน",
"applyHintNothing": "ไม่มีรายการที่ต้องอัปเดต ไม่จำเป็นต้องยืนยันเขียน",
"localMissingHint": "มี {count} รหัสพนักงานในระบบที่ไม่พบใน OA จะข้าม",
"conflictsBlockApply": "พบความขัดแย้ง โปรดแก้ไขก่อนยืนยัน",
"nothingToUpdate": "ไม่มีรายการที่ต้องอัปเดต",
"applyConfirmTitle": "ยืนยันการเขียนข้อมูลผูกมัด",
"applyConfirm": "ยืนยันเขียน {count} รายการลงฐานข้อมูล?",
"applyConfirmButton": "ยืนยันเขียน",
"applyDone": "อัปเดต {count} รายการสำเร็จ",
"applyFailed": "ยืนยันการซิงค์ล้มเหลว",
"invalidDepartmentId": "รหัสแผนกต้องเป็นจำนวนเต็มบวก",
@@ -274,6 +285,9 @@
"occupiedBy": "userid ถูกใช้โดย {user} แล้ว",
"stats": {
"wecomUsers": "สมาชิก WeCom",
"oaRows": "แถว OA",
"localCandidates": "ผู้ใช้ที่มีรหัสพนักงาน",
"oaMatched": "จับคู่ OA",
"localMatched": "จับคู่ในระบบ",
"wouldUpdate": "จะอัปเดต",
"conflicts": "ขัดแย้ง"
+17 -3
View File
@@ -253,20 +253,31 @@
"hintDesc": "未绑定 wecom_userid 的用户无法接收企微重置链接"
},
"sync": {
"title": "通讯录同步",
"desc": "从企业微信通讯录按工号回填 users.wecom_userid,用于找回密码与通知触达。",
"title": "OA 绑定同步",
"desc": "从 OA 数据库 userInfo_view 按工号回填 users.wecom_userid,用于找回密码与通知触达。",
"permissionNote": "需在企微后台为自建应用开通「通讯录读」与「发送应用消息」权限。",
"oaSourceNote": "数据源:OA SQL Server(ecology.userInfo_view)。工号字段 workcode 对应本地 employee_id,id 写入 wecom_userid。连接参数见环境变量 OA_SQLSERVER_*。",
"oaWorkcodeField": "工号字段(→ employee_id)",
"oaWecomIdField": "企微 ID 字段(→ wecom_userid)",
"employeeIdSource": "当前工号来源",
"departmentId": "根部门 ID(可选)",
"departmentIdPlaceholder": "留空表示全部部门",
"preview": "预览同步",
"apply": "确认写入",
"previewDone": "预览完成,请确认结果后再写入",
"previewFailed": "预览同步失败",
"previewFailed": "预览同步失败,请检查 OA 数据库连接与 OA_SQLSERVER_* 配置",
"previewFirst": "请先预览同步结果",
"previewFirstAfterFail": "预览同步失败,请检查 OA 数据库连接与环境变量后再预览",
"applyHintPreviewFirst": "请先点击「预览同步」,成功后再确认写入",
"applyHintPreviewFailed": "预览未成功,无法写入。请检查 OA SQL Server 连接(OA_SQLSERVER_*)与网络",
"applyHintConflicts": "存在冲突,请先处理冲突明细后再写入",
"applyHintNothing": "预览结果无待更新项,无需写入",
"localMissingHint": "有 {count} 个本地工号在 OA 中未找到,不会写入",
"conflictsBlockApply": "存在冲突,请先人工处理后再写入",
"nothingToUpdate": "没有需要更新的绑定",
"applyConfirmTitle": "确认写入绑定",
"applyConfirm": "确认将 {count} 条 userid 绑定写入数据库?",
"applyConfirmButton": "确认写入",
"applyDone": "已成功更新 {count} 条绑定",
"applyFailed": "写入同步结果失败",
"invalidDepartmentId": "部门 ID 必须为正整数",
@@ -275,6 +286,9 @@
"occupiedBy": "userid 已被用户 {user} 占用",
"stats": {
"wecomUsers": "企微成员",
"oaRows": "OA 记录",
"localCandidates": "本地有工号",
"oaMatched": "OA 匹配",
"localMatched": "本地匹配",
"wouldUpdate": "待更新",
"conflicts": "冲突"
+17 -3
View File
@@ -252,20 +252,31 @@
"hintDesc": "未綁定 wecom_userid 的用戶無法接收企微重設連結"
},
"sync": {
"title": "通訊錄同步",
"desc": "從企業微信通訊錄按工號回填 users.wecom_userid。",
"title": "OA 綁定同步",
"desc": "從 OA 資料庫 userInfo_view 按工號回填 users.wecom_userid。",
"permissionNote": "需在企微後台開通「通訊錄讀」與「發送應用消息」權限。",
"oaSourceNote": "資料源:OA SQL Server(ecology.userInfo_view)。workcode → employee_id,id → wecom_userid。連線參數見 OA_SQLSERVER_*。",
"oaWorkcodeField": "工號欄位(→ employee_id)",
"oaWecomIdField": "企微 ID 欄位(→ wecom_userid)",
"employeeIdSource": "當前工號來源",
"departmentId": "根部門 ID(可選)",
"departmentIdPlaceholder": "留空表示全部部門",
"preview": "預覽同步",
"apply": "確認寫入",
"previewDone": "預覽完成,請確認結果後再寫入",
"previewFailed": "預覽同步失敗",
"previewFailed": "預覽同步失敗,請檢查 OA 資料庫連線與 OA_SQLSERVER_* 配置",
"previewFirst": "請先預覽同步結果",
"previewFirstAfterFail": "預覽同步失敗,請檢查 OA 資料庫連線與環境變數後再預覽",
"applyHintPreviewFirst": "請先點擊「預覽同步」,成功後再確認寫入",
"applyHintPreviewFailed": "預覽未成功,無法寫入。請檢查 OA SQL Server(OA_SQLSERVER_*)與網路",
"applyHintConflicts": "存在衝突,請先處理衝突明細後再寫入",
"applyHintNothing": "預覽結果無待更新項,無需寫入",
"localMissingHint": "有 {count} 個本地工號在 OA 中未找到,不會寫入",
"conflictsBlockApply": "存在衝突,請先人工處理後再寫入",
"nothingToUpdate": "沒有需要更新的綁定",
"applyConfirmTitle": "確認寫入綁定",
"applyConfirm": "確認將 {count} 條 userid 綁定寫入資料庫?",
"applyConfirmButton": "確認寫入",
"applyDone": "已成功更新 {count} 條綁定",
"applyFailed": "寫入同步結果失敗",
"invalidDepartmentId": "部門 ID 必須為正整數",
@@ -274,6 +285,9 @@
"occupiedBy": "userid 已被用戶 {user} 占用",
"stats": {
"wecomUsers": "企微成員",
"oaRows": "OA 記錄",
"localCandidates": "本地有工號",
"oaMatched": "OA 匹配",
"localMatched": "本地匹配",
"wouldUpdate": "待更新",
"conflicts": "衝突"
@@ -1,7 +1,7 @@
<script setup lang="ts">
/**
* shared/components/DeleteConfirmDialog.vue
* 通用删除确认弹窗。
* 通用确认弹窗(默认删除场景,可通过 title / confirmTone 用于其它确认)。
*/
import { computed, onBeforeUnmount, watch } from 'vue';
@@ -14,6 +14,8 @@ interface Props {
confirmText?: string;
cancelText?: string;
confirmLoading?: boolean;
/** danger 用于删除;primary 用于写入等非破坏性确认 */
confirmTone?: 'danger' | 'primary';
}
const props = withDefaults(defineProps<Props>(), {
@@ -22,6 +24,7 @@ const props = withDefaults(defineProps<Props>(), {
confirmText: '',
cancelText: '',
confirmLoading: false,
confirmTone: 'danger',
});
const emit = defineEmits<{
@@ -36,6 +39,9 @@ const resolvedTitle = computed(() => props.title || t('common.deleteDialog.defau
const resolvedMessage = computed(() => props.message || t('common.deleteDialog.defaultMessage'));
const resolvedCancelText = computed(() => props.cancelText || t('common.deleteDialog.cancel'));
const resolvedConfirmText = computed(() => props.confirmText || t('common.deleteDialog.confirm'));
const confirmButtonClass = computed(() =>
props.confirmTone === 'primary' ? 'btn-primary btn-sm' : 'btn-danger btn-sm'
);
const closeDialog = () => {
emit('update:modelValue', false);
@@ -100,7 +106,7 @@ onBeforeUnmount(() => {
</button>
<button
type="button"
class="btn-danger btn-sm"
:class="confirmButtonClass"
:disabled="confirmLoading"
@click="handleConfirm"
>
+4
View File
@@ -43,6 +43,10 @@
.btn {
@apply px-4 py-2 rounded-xl font-medium transition-all duration-200 active:scale-95 flex items-center justify-center gap-2;
}
.btn:disabled {
@apply opacity-50 cursor-not-allowed pointer-events-none active:scale-100;
}
.btn-primary {
@apply btn bg-brand-600 text-white hover:bg-brand-700 shadow-lg shadow-brand-500/20 hover:shadow-brand-500/30;