1.将职称角色中的“从OA同步企微账号”及设置角色、“员工与部门在「组织架构」中统一维护,此处仅配置职称角色”迁移到组织架构页面中, 2.平台新增成员自动添加到“组织架构”页面自动匹配对应部门; 3.在“组织架构”页面可直接设置角色 4.“组织架构”页面职称按名称、工号、部门查找员工 5.新增成员默认放在最上面按时间倒序排列 6.所有登录平台的用户直接默认打开AI对话页面 7.页面3、4中的”AIDO“改为”和信智汇学院“
This commit is contained in:
1 parent
196478114c
commit
8f225ecea9
26 files changed
+644
-406
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>AIDO</title>
|
||||
<title>和信智汇学院</title>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||
|
||||
@@ -119,12 +119,12 @@ const persistOIDCLoginResponse = async (response: any) => {
|
||||
if (result.ok) MessagePlugin.success(t('inviteRegister.joined'))
|
||||
else MessagePlugin.warning(t('inviteRegister.invalidBody'))
|
||||
// 会话已有效,无论 token 是否兑换成功都进入应用。
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
const handleGlobalOIDCCallback = async () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
import type { WecomSyncSummary } from '@/api/training'
|
||||
|
||||
// 组织中心(租户级共享组织架构)API 封装,对应后端 /api/v1/org/*(routes_org.go)。
|
||||
// 部门/员工档案归租户所有;业务模块(企业培训/图纸标注/物料检核...)通过
|
||||
@@ -115,6 +116,27 @@ export interface OrgUpdateEmployee {
|
||||
export const updateEmployee = (id: string, payload: OrgUpdateEmployee) =>
|
||||
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}`, payload)
|
||||
|
||||
// ---- 职称角色 / 企微账号(自培训域迁入组织架构页;/org 域别名路由复用培训
|
||||
// handler,角色绑定仍写 module_key='training';权限细控 HR/经理在 handler 内) ----
|
||||
|
||||
/** 设置员工职称角色(学员为全员隐式角色,由后端保留,前端保存时一并带上)。 */
|
||||
export const updateOrgEmployeeRoles = (id: string, roles: string[]) =>
|
||||
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/roles`, { roles })
|
||||
|
||||
/** 维护员工企微账号(培训提醒推送目标;留空即解绑)。 */
|
||||
export const updateOrgEmployeeWecomUserid = (id: string, wecomUserid: string) =>
|
||||
put<{ success: boolean; data: OrgEmployee }>(`${base}/employees/${enc(id)}/wecom-userid`, {
|
||||
wecom_userid: wecomUserid,
|
||||
})
|
||||
|
||||
/** 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式,预览只读)。 */
|
||||
export const previewOrgWecomSync = () =>
|
||||
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/preview`)
|
||||
|
||||
/** OA 同步写入(无冲突时才落库,返回写入统计)。 */
|
||||
export const applyOrgWecomSync = () =>
|
||||
post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/apply`)
|
||||
|
||||
// ---- 模块角色绑定 ----
|
||||
|
||||
export const listModuleMembers = (moduleKey: OrgModuleKey) =>
|
||||
|
||||
@@ -1312,7 +1312,7 @@ export const NOTIFY_TEXT_TEMPLATES_RULE_KEY = 'notify_text_templates'
|
||||
export const DEFAULT_DEMAND_COLLECT_TITLE = '【培训需求收集】{year}年度培训计划收集'
|
||||
export const DEFAULT_DEMAND_COLLECT_CONTENT =
|
||||
'请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:' +
|
||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||
'可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录和信智汇学院 → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。'
|
||||
|
||||
/** 读取年培训计划收集推送文案模板(配置中心 notify_text_templates;字段为空/
|
||||
* 拉取失败回落内置默认,与后端 parseNotifyTextTemplates 同口径)。 */
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// ===== AIDO 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
||||
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入
|
||||
// ===== 和信智汇学院 文字 Logo:渐变流光 + 呼吸辉光 + 脉冲光点 =====
|
||||
// 侧边栏(menu.vue)与登录页(Login.vue)共用,由 main.ts 全局引入。
|
||||
// 品牌名由「AIDO」更名而来:中文六个字,字号/字距相应收窄以适配
|
||||
// 260px 展开侧栏(logo 与搜索/折叠图标同行)与登录页左上角。
|
||||
.aido-logo {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@@ -16,12 +18,12 @@
|
||||
}
|
||||
|
||||
&__text {
|
||||
font-family: 'Trebuchet MS', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
font-size: 27px;
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', sans-serif;
|
||||
font-size: 19px;
|
||||
line-height: 1.15;
|
||||
font-weight: 800;
|
||||
font-style: italic;
|
||||
letter-spacing: 2.5px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
letter-spacing: 1px;
|
||||
background-image:
|
||||
linear-gradient(110deg, rgba(255, 255, 255, 0) 42%, rgba(255, 255, 255, 0.85) 50%, rgba(255, 255, 255, 0) 58%),
|
||||
linear-gradient(95deg, #07c05f 0%, #0bbf9a 35%, #10b4c8 65%, #3b82f6 100%);
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
<div class="aside_rail">
|
||||
<!-- 展开时:Logo + 搜索/折叠按钮同行 -->
|
||||
<div class="logo_row" v-if="!uiStore.sidebarCollapsed">
|
||||
<div class="logo_box" @click="router.push('/platform/knowledge-bases')" style="cursor: pointer;">
|
||||
<span class="aido-logo" aria-label="AIDO" title="AIDO">
|
||||
<span class="aido-logo__text">AIDO</span>
|
||||
<div class="logo_box" @click="router.push('/platform/creatChat')" style="cursor: pointer;">
|
||||
<span class="aido-logo" aria-label="和信智汇学院" title="和信智汇学院">
|
||||
<span class="aido-logo__text">和信智汇学院</span>
|
||||
<span class="aido-logo__dot"></span>
|
||||
</span>
|
||||
<sup v-if="isLiteEdition" class="lite-badge">Lite</sup>
|
||||
@@ -605,12 +605,12 @@ const moreToolItems = computed<MenuItem[]>(() => {
|
||||
const items = MORE_TOOLS_ORDER
|
||||
.map(path => all.find((item: MenuItem) => item.path === path))
|
||||
.filter((item): item is MenuItem => !!item);
|
||||
// 末位固定追加「配置中心」「职称角色」「组织架构」;「共享空间」还原至最底
|
||||
// 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底
|
||||
// (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐)
|
||||
// 职称角色(000159):自「企业培训」分组迁入,置于配置中心之后
|
||||
const MEMBERS_TOOL_ITEM: MenuItem = { title: '职称角色', icon: 'training', path: 'training/members' };
|
||||
// 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由
|
||||
// /platform/training/members 由路由重定向兜底
|
||||
const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations');
|
||||
return [...items, RULES_TOOL_ITEM, MEMBERS_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
||||
return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])];
|
||||
});
|
||||
|
||||
// 菜单图标统一映射:顶层项与「更多工具」子项共用
|
||||
@@ -645,9 +645,9 @@ const TRAINING_TABS: { key: string; title: string }[] = [
|
||||
];
|
||||
const TRAINING_GROUP_TITLE = '企业培训';
|
||||
|
||||
// 分组展开状态(记忆用户偏好,默认展开),交互与「更多工具」一致
|
||||
// 分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
|
||||
const TRAINING_OPEN_KEY = 'academy_training_open';
|
||||
const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) !== 'false');
|
||||
const trainingOpen = ref(localStorage.getItem(TRAINING_OPEN_KEY) === 'true');
|
||||
const toggleTraining = () => {
|
||||
trainingOpen.value = !trainingOpen.value;
|
||||
localStorage.setItem(TRAINING_OPEN_KEY, String(trainingOpen.value));
|
||||
@@ -669,9 +669,9 @@ const isTrainingTabActive = (tab: string): boolean => {
|
||||
return (String(route.params.tab || 'dashboard')) === tab;
|
||||
};
|
||||
|
||||
// 「更多工具」分组展开状态(记忆用户偏好,默认展开)
|
||||
// 「更多工具」分组展开状态(记忆用户偏好,默认收起;用户手动展开后记忆为展开)
|
||||
const MORE_TOOLS_OPEN_KEY = 'academy_moretools_open';
|
||||
const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) !== 'false');
|
||||
const moreToolsOpen = ref(localStorage.getItem(MORE_TOOLS_OPEN_KEY) === 'true');
|
||||
const toggleMoreTools = () => {
|
||||
moreToolsOpen.value = !moreToolsOpen.value;
|
||||
localStorage.setItem(MORE_TOOLS_OPEN_KEY, String(moreToolsOpen.value));
|
||||
|
||||
@@ -2970,7 +2970,7 @@ export default {
|
||||
haveAccount: 'Already have an account?',
|
||||
backToLogin: 'Back to Login',
|
||||
loginHint: 'Sign in to continue, or create an account below if this is your first time.',
|
||||
firstTime: 'New to AIDO?',
|
||||
firstTime: 'New to 和信智汇学院?',
|
||||
registerSuccess: 'Registration successful. Please sign in',
|
||||
registerFailed: 'Registration failed',
|
||||
subtitle: 'AI assistant, ReAct agents and Wiki knowledge base — an AI-driven enterprise architecture upgrade',
|
||||
|
||||
@@ -2970,7 +2970,7 @@ export default {
|
||||
haveAccount: 'すでにアカウントをお持ちですか?',
|
||||
backToLogin: 'ログインに戻る',
|
||||
loginHint: 'ログインして続行してください。初めての方は下からアカウントを作成できます。',
|
||||
firstTime: 'AIDOは初めてですか?',
|
||||
firstTime: '和信智汇学院は初めてですか?',
|
||||
registerSuccess: '登録が完了しました。ログインしてください',
|
||||
registerFailed: '登録に失敗しました',
|
||||
subtitle: 'AIアシスタント、ReActエージェント、Wikiナレッジベース — AI駆動のエンタープライズアーキテクチャアップグレード',
|
||||
|
||||
@@ -6262,7 +6262,7 @@ export default {
|
||||
haveAccount: '이미 계정이 있으신가요?',
|
||||
backToLogin: '로그인으로 돌아가기',
|
||||
loginHint: '로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.',
|
||||
firstTime: 'AIDO가 처음이신가요?',
|
||||
firstTime: '和信智汇学院이 처음이신가요?',
|
||||
registerSuccess: '가입이 완료되었습니다. 로그인해주세요',
|
||||
registerFailed: '가입 실패',
|
||||
subtitle: 'AI 어시스턴트, ReAct 에이전트, Wiki 지식베이스 — AI 기반 엔터프라이즈 아키텍처 업그레이드',
|
||||
|
||||
@@ -6262,7 +6262,7 @@ export default {
|
||||
haveAccount: 'Уже есть аккаунт?',
|
||||
backToLogin: 'Вернуться ко входу',
|
||||
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
|
||||
firstTime: 'Впервые в AIDO?',
|
||||
firstTime: 'Впервые в 和信智汇学院?',
|
||||
registerSuccess: 'Регистрация завершена. Войдите в систему',
|
||||
registerFailed: 'Ошибка регистрации',
|
||||
subtitle: 'ИИ-ассистент, ReAct-агенты и Wiki-база знаний — корпоративная архитектура нового уровня на базе ИИ',
|
||||
|
||||
@@ -6263,7 +6263,7 @@ export default {
|
||||
haveAccount: '已有账户?',
|
||||
backToLogin: '返回登录',
|
||||
loginHint: '登录以继续使用;首次使用请在下方创建账户。',
|
||||
firstTime: '首次使用 AIDO?',
|
||||
firstTime: '首次使用 和信智汇学院?',
|
||||
registerSuccess: '注册成功,请登录',
|
||||
registerFailed: '注册失败',
|
||||
subtitle: 'AI智能助手、ReAct 智能体与 Wiki 知识库,AI驱动的企业架构升级',
|
||||
|
||||
@@ -6263,7 +6263,7 @@ export default {
|
||||
haveAccount: '已有帳戶?',
|
||||
backToLogin: '返回登入',
|
||||
loginHint: '登入以繼續使用;首次使用請在下方建立帳戶。',
|
||||
firstTime: '首次使用 AIDO?',
|
||||
firstTime: '首次使用 和信智汇学院?',
|
||||
registerSuccess: '註冊成功,請登入',
|
||||
registerFailed: '註冊失敗',
|
||||
subtitle: 'AI智能助理、ReAct 智能體與 Wiki 知識庫,AI驅動的企業架構升級',
|
||||
|
||||
@@ -27,6 +27,7 @@ function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
|
||||
to.path === '/' ||
|
||||
to.path === '/platform' ||
|
||||
to.path === '/platform/knowledge-bases' ||
|
||||
to.path === '/platform/creatChat' ||
|
||||
to.name === 'knowledgeBaseList'
|
||||
)
|
||||
}
|
||||
@@ -46,7 +47,8 @@ const router = createRouter({
|
||||
routes: [
|
||||
{
|
||||
path: "/",
|
||||
redirect: "/platform/knowledge-bases",
|
||||
// 登录用户默认打开 AI 对话页(首页口径,与登录成功跳转一致)
|
||||
redirect: "/platform/creatChat",
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
@@ -94,7 +96,7 @@ const router = createRouter({
|
||||
{
|
||||
path: "/platform",
|
||||
name: "Platform",
|
||||
redirect: "/platform/knowledge-bases",
|
||||
redirect: "/platform/creatChat",
|
||||
component: () => import("../views/platform/index.vue"),
|
||||
meta: { requiresInit: true, requiresAuth: true },
|
||||
children: [
|
||||
@@ -156,12 +158,18 @@ const router = createRouter({
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
{
|
||||
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/职称角色/配置中心)
|
||||
// 企业培训:子页(工作台/培训计划/培训课程/培训签到/学习考试/配置中心)
|
||||
// 收纳为侧栏「企业培训」分组的子项,tab 取自路径参数,缺省重定向到工作台。
|
||||
path: "training",
|
||||
name: "training",
|
||||
redirect: "/platform/training/dashboard"
|
||||
},
|
||||
{
|
||||
// 职称角色页已并入「组织架构」页维护(员工/角色/企微账号一处维护),
|
||||
// 旧链接与书签兜底重定向。
|
||||
path: "training/members",
|
||||
redirect: "/platform/org-center"
|
||||
},
|
||||
{
|
||||
path: "training/:tab",
|
||||
name: "trainingTab",
|
||||
@@ -368,7 +376,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
}
|
||||
}
|
||||
if (authStore.hasValidTenant) {
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
@@ -377,9 +385,9 @@ router.beforeEach(async (to, from, next) => {
|
||||
|
||||
// 如果访问的是登录页面或初始化页面,直接放行
|
||||
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
|
||||
// 如果已登录用户访问登录页面,重定向到知识库列表页面
|
||||
// 如果已登录用户访问登录页面,重定向到首页(AI 对话)
|
||||
if (to.path === '/login' && authStore.isLoggedIn) {
|
||||
next(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
next(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||
return
|
||||
}
|
||||
next()
|
||||
@@ -431,7 +439,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
const requiredCapability = to.meta.requiredCapability as DeploymentCapabilityKey | undefined
|
||||
if (requiredCapability && !deploymentCapabilities.isSupported(requiredCapability)) {
|
||||
MessagePlugin.warning(i18n.global.t('settings.capabilityUnavailable'))
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -441,7 +449,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
// the bounce. This is UI-only; the server enforces the real check.
|
||||
if (to.meta.requiresSystemAdmin === true) {
|
||||
if (!authStore.isSystemAdmin) {
|
||||
next('/platform/knowledge-bases')
|
||||
next('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@
|
||||
|
||||
<!-- Logo - Top Left -->
|
||||
<a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')">
|
||||
<span class="aido-logo" aria-label="AIDO">
|
||||
<span class="aido-logo__text">AIDO</span>
|
||||
<span class="aido-logo" aria-label="和信智汇学院">
|
||||
<span class="aido-logo__text">和信智汇学院</span>
|
||||
<span class="aido-logo__dot"></span>
|
||||
</span>
|
||||
</a>
|
||||
@@ -611,7 +611,7 @@ const persistLoginResponse = async (response: any, skipRedirect = false) => {
|
||||
await authStore.refreshFromAuthMe()
|
||||
await nextTick()
|
||||
if (skipRedirect) return
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
router.replace(authStore.hasValidTenant ? '/platform/creatChat' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||
@@ -694,7 +694,7 @@ const acceptAndEnter = async (token: string) => {
|
||||
} finally {
|
||||
loading.value = false
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +852,7 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
if (authStore.isLoggedIn) {
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace('/platform/creatChat')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,29 @@
|
||||
<div class="panel-box org-layout__employees">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">员工档案</span>
|
||||
<div style="display: flex; gap: 8px">
|
||||
<!-- 自「职称角色」页迁入:提示 + OA 同步入口(管理角色可见) -->
|
||||
<div class="org-employees__actions">
|
||||
<span class="org-employees__hint">员工与部门在本页统一维护,职称角色与企微账号可直接配置</span>
|
||||
<t-input
|
||||
v-model="keyword"
|
||||
class="org-employees__search"
|
||||
clearable
|
||||
placeholder="按姓名 / 工号 / 部门查找"
|
||||
@enter="loadEmployees"
|
||||
@clear="loadEmployees"
|
||||
>
|
||||
<template #prefixIcon><t-icon name="search" /></template>
|
||||
</t-input>
|
||||
<t-button
|
||||
v-if="canManage"
|
||||
variant="outline"
|
||||
theme="primary"
|
||||
:loading="syncing"
|
||||
class="oa-sync-btn"
|
||||
@click="onPreviewSync"
|
||||
>
|
||||
从OA同步企微账号
|
||||
</t-button>
|
||||
<t-button variant="outline" @click="openPicker">从平台用户添加</t-button>
|
||||
<t-button theme="primary" @click="importVisible = true">批量导入</t-button>
|
||||
</div>
|
||||
@@ -46,6 +68,12 @@
|
||||
</t-tooltip>
|
||||
</template>
|
||||
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
||||
<template #wecom_userid="{ row }">
|
||||
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
|
||||
</template>
|
||||
<template #roles="{ row }">
|
||||
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
|
||||
</template>
|
||||
<template #status="{ row }">
|
||||
<t-tag v-if="row.status === 'active'" theme="success" variant="light" size="small">在职</t-tag>
|
||||
<t-tag v-else-if="row.status === 'inactive'" theme="danger" variant="light" size="small">离职</t-tag>
|
||||
@@ -54,6 +82,8 @@
|
||||
<template #op="{ row }">
|
||||
<div class="op-group">
|
||||
<t-button variant="text" theme="primary" size="small" @click="onEditEmployee(row)">修改</t-button>
|
||||
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
|
||||
<t-button v-if="canManage" variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-table>
|
||||
@@ -150,6 +180,68 @@
|
||||
<t-button theme="primary" :loading="saving" @click="onSaveEmployee">保存</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- 绑定企微账号(培训提醒推送目标;自职称角色页迁入) -->
|
||||
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
|
||||
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
|
||||
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
|
||||
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
|
||||
<template v-if="syncSummary">
|
||||
<div class="sync-stats">
|
||||
<span>本地员工 {{ syncSummary.local_candidates }}</span>
|
||||
<span>OA 命中 {{ syncSummary.local_matched }}</span>
|
||||
<span>已一致 {{ syncSummary.already_bound }}</span>
|
||||
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
|
||||
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
|
||||
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
|
||||
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
|
||||
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
|
||||
{{ cf.employee_no }} {{ cf.user_name || '' }}:
|
||||
{{ conflictText(cf) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="syncSummary.would_update" class="sync-section">
|
||||
<div class="sync-section__title">将写入(最多展示 20 条)</div>
|
||||
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
|
||||
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
|
||||
无需更新:绑定已一致或 OA 无匹配数据。
|
||||
</div>
|
||||
|
||||
<div class="sync-footer">
|
||||
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
|
||||
theme="primary" :loading="syncing" @click="onApplySync">
|
||||
确认写入
|
||||
</t-button>
|
||||
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- 设置职称角色(自职称角色页迁入;绑定写 module_key='training') -->
|
||||
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
|
||||
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
|
||||
<t-select v-model="roleSelection" multiple style="width: 100%">
|
||||
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
|
||||
</t-select>
|
||||
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="savingRoles" @click="onSaveRoles">保存</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -157,26 +249,45 @@
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
applyOrgWecomSync,
|
||||
deleteDept,
|
||||
importEmployees,
|
||||
listDepts,
|
||||
listEmployees,
|
||||
listPlatformUsers,
|
||||
ORG_MODULE_TRAINING,
|
||||
previewOrgWecomSync,
|
||||
saveDept,
|
||||
updateEmployee,
|
||||
updateOrgEmployeeRoles,
|
||||
updateOrgEmployeeWecomUserid,
|
||||
type OrgDept,
|
||||
type OrgEmployee,
|
||||
type OrgPlatformUser,
|
||||
} from '@/api/org-center'
|
||||
import { unwrap } from '@/api/training'
|
||||
import {
|
||||
expandRoles,
|
||||
fetchRoleDict,
|
||||
getMyProfile,
|
||||
roleLabelOf,
|
||||
unwrap,
|
||||
type TrainingRoleDef,
|
||||
type WecomSyncConflict,
|
||||
type WecomSyncSummary,
|
||||
} from '@/api/training'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const depts = ref<OrgDept[]>([])
|
||||
const employees = ref<OrgEmployee[]>([])
|
||||
const platformUsers = ref<OrgPlatformUser[]>([])
|
||||
|
||||
// 员工查找(需求:按名称/工号/部门);keyword 走后端 ListEmployees 的过滤。
|
||||
const keyword = ref('')
|
||||
|
||||
const deptFormVisible = ref(false)
|
||||
const importVisible = ref(false)
|
||||
// id 为空表示新增,否则为修改(后端 saveDept 的 upsert 语义)。
|
||||
@@ -193,6 +304,119 @@ const pickerPost = ref('')
|
||||
const employeeFormVisible = ref(false)
|
||||
const employeeForm = ref({ id: '', user_name: '', employee_no: '', dept_id: '', post: '', status: 'active' })
|
||||
|
||||
// ---- 职称角色 / 企微账号(自培训域「职称角色」页迁入) ----
|
||||
|
||||
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
|
||||
const roleDict = ref<TrainingRoleDef[]>([])
|
||||
// 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护)
|
||||
const rawRoles = ref<string[]>([])
|
||||
const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value))
|
||||
const canManage = computed(
|
||||
() => authStore.hasRole('admin') || myRoles.value.some((r) => r === 'hr' || r === 'exec'),
|
||||
)
|
||||
|
||||
const rolesVisible = ref(false)
|
||||
const activeEmployee = ref<OrgEmployee | null>(null)
|
||||
const roleSelection = ref<string[]>([])
|
||||
const savingRoles = ref(false)
|
||||
|
||||
const wecomVisible = ref(false)
|
||||
const activeWecomEmployee = ref<OrgEmployee | null>(null)
|
||||
const wecomInput = ref('')
|
||||
const savingWecom = ref(false)
|
||||
|
||||
// OA 同步(工号 → 企微 userid,预览→写入两段式)
|
||||
const syncVisible = ref(false)
|
||||
const syncing = ref(false)
|
||||
const syncSummary = ref<WecomSyncSummary | null>(null)
|
||||
|
||||
const conflictText = (cf: WecomSyncConflict) => {
|
||||
switch (cf.reason) {
|
||||
case 'duplicate_workcode_in_oa':
|
||||
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
|
||||
case 'bound_to_different_userid':
|
||||
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
|
||||
case 'userid_occupied':
|
||||
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
|
||||
default:
|
||||
return cf.reason
|
||||
}
|
||||
}
|
||||
|
||||
const onPreviewSync = async () => {
|
||||
syncing.value = true
|
||||
try {
|
||||
const res = await previewOrgWecomSync()
|
||||
syncSummary.value = unwrap(res) ?? null
|
||||
syncVisible.value = true
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const onApplySync = async () => {
|
||||
syncing.value = true
|
||||
try {
|
||||
const res = await applyOrgWecomSync()
|
||||
const summary = unwrap(res)
|
||||
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
|
||||
syncVisible.value = false
|
||||
loadEmployees()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '写入失败')
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openRoles = (row: OrgEmployee) => {
|
||||
activeEmployee.value = row
|
||||
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
|
||||
rolesVisible.value = true
|
||||
}
|
||||
|
||||
const onSaveRoles = async () => {
|
||||
if (!activeEmployee.value) return
|
||||
savingRoles.value = true
|
||||
try {
|
||||
// 学员角色为全员隐式默认,保存时总是带回去(与后端口径一致)。
|
||||
await updateOrgEmployeeRoles(activeEmployee.value.id, [...roleSelection.value, 'trainee'])
|
||||
MessagePlugin.success('角色已更新')
|
||||
rolesVisible.value = false
|
||||
loadEmployees()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||
} finally {
|
||||
savingRoles.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openWecom = (row: OrgEmployee) => {
|
||||
activeWecomEmployee.value = row
|
||||
wecomInput.value = row.wecom_userid || ''
|
||||
wecomVisible.value = true
|
||||
}
|
||||
|
||||
const onSaveWecom = async () => {
|
||||
if (!activeWecomEmployee.value) return
|
||||
savingWecom.value = true
|
||||
try {
|
||||
await updateOrgEmployeeWecomUserid(activeWecomEmployee.value.id, wecomInput.value.trim())
|
||||
MessagePlugin.success('企微账号已更新')
|
||||
wecomVisible.value = false
|
||||
loadEmployees()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||
} finally {
|
||||
savingWecom.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
|
||||
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
|
||||
|
||||
const deptColumns = [
|
||||
{ colKey: 'name', title: '部门名称' },
|
||||
{ colKey: 'code', title: '编码', width: 140 },
|
||||
@@ -200,15 +424,18 @@ const deptColumns = [
|
||||
{ colKey: 'op', title: '操作', width: 140, fixed: 'right' },
|
||||
]
|
||||
|
||||
const employeeColumns = [
|
||||
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
|
||||
const employeeColumns = computed(() => [
|
||||
{ colKey: 'employee_no', title: '工号', width: 90 },
|
||||
{ colKey: 'user_name', title: '姓名' },
|
||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
||||
{ colKey: 'post', title: '岗位', width: 140 },
|
||||
{ colKey: 'status', title: '状态', width: 76 },
|
||||
// 列总宽超出面板宽度时固定在右侧,避免"修改"按钮被横向滚动挤出可视区
|
||||
{ colKey: 'op', title: '操作', width: 84, fixed: 'right' },
|
||||
]
|
||||
{ colKey: 'user_name', title: '姓名', width: 110 },
|
||||
{ colKey: 'dept_name', title: '部门', width: 100 },
|
||||
{ colKey: 'post', title: '岗位', width: 120 },
|
||||
{ colKey: 'wecom_userid', title: '企微账号', width: 110 },
|
||||
{ colKey: 'roles', title: '职称角色' },
|
||||
{ colKey: 'status', title: '状态', width: 70 },
|
||||
// 列总宽超出面板宽度时固定在右侧,避免操作按钮被横向滚动挤出可视区
|
||||
{ colKey: 'op', title: '操作', width: canManage.value ? 200 : 84, fixed: 'right' },
|
||||
])
|
||||
|
||||
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
||||
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不回退展示用户ID。
|
||||
@@ -249,23 +476,53 @@ watch(pickerUserIds, (ids) => {
|
||||
if (deptId) pickerDeptId.value = deptId
|
||||
})
|
||||
|
||||
const loadAll = async () => {
|
||||
// 员工列表:module_key='training' 联查职称角色展示;keyword 按姓名/工号/部门过滤。
|
||||
const loadEmployees = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
||||
const [d, e, u] = await Promise.all([
|
||||
listDepts(),
|
||||
listEmployees({ page_size: 500 }),
|
||||
listPlatformUsers().catch(() => null),
|
||||
])
|
||||
depts.value = unwrap(d) || []
|
||||
const e = await listEmployees({
|
||||
module_key: ORG_MODULE_TRAINING,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
page_size: 500,
|
||||
})
|
||||
employees.value = unwrap(e)?.items || []
|
||||
platformUsers.value = unwrap(u) || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 输入防抖触发查找(enter/clear 立即触发由模板回调完成)
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(keyword, () => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => loadEmployees(), 300)
|
||||
})
|
||||
|
||||
const loadAll = async () => {
|
||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
||||
const [d, u] = await Promise.all([
|
||||
listDepts(),
|
||||
listPlatformUsers().catch(() => null),
|
||||
])
|
||||
depts.value = unwrap(d) || []
|
||||
platformUsers.value = unwrap(u) || []
|
||||
await loadEmployees()
|
||||
}
|
||||
|
||||
// 本人职称角色(人事/经理/空间管理员可维护;口径与培训页 canManageConfig 一致)
|
||||
const loadProfile = async () => {
|
||||
try {
|
||||
const res = await getMyProfile() as any
|
||||
const member: OrgEmployee | undefined = res?.data?.data || res?.data
|
||||
if (member) {
|
||||
rawRoles.value = (member.roles as unknown as string[]) || ['trainee']
|
||||
}
|
||||
} catch {
|
||||
// 取不到档案按纯学员兜底:仅隐藏维护入口,不影响页面其余功能。
|
||||
rawRoles.value = ['trainee']
|
||||
}
|
||||
}
|
||||
|
||||
const openCreateDept = () => {
|
||||
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
|
||||
deptFormVisible.value = true
|
||||
@@ -349,7 +606,7 @@ const onPickImport = async () => {
|
||||
pickerVisible.value = false
|
||||
pickerUserIds.value = []
|
||||
pickerDeptId.value = ''
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('添加失败')
|
||||
} finally {
|
||||
@@ -385,7 +642,7 @@ const onSaveEmployee = async () => {
|
||||
})
|
||||
MessagePlugin.success('员工档案已更新')
|
||||
employeeFormVisible.value = false
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('保存失败')
|
||||
} finally {
|
||||
@@ -430,7 +687,7 @@ const onImport = async () => {
|
||||
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
|
||||
importVisible.value = false
|
||||
importText.value = ''
|
||||
loadAll()
|
||||
loadEmployees()
|
||||
} catch {
|
||||
MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
|
||||
} finally {
|
||||
@@ -438,7 +695,13 @@ const onImport = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadAll)
|
||||
onMounted(() => {
|
||||
loadAll()
|
||||
loadProfile()
|
||||
fetchRoleDict().then((d) => {
|
||||
roleDict.value = d
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -498,4 +761,51 @@ onMounted(loadAll)
|
||||
word-break: break-all;
|
||||
line-height: 1.4;
|
||||
}
|
||||
// 员工面板头部工具条:提示文案 + 查找框 + 动作按钮(窄屏折行)
|
||||
.org-employees__actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
}
|
||||
.org-employees__hint {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
.org-employees__search {
|
||||
width: 200px;
|
||||
}
|
||||
.oa-sync-btn {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.role-tag {
|
||||
margin-right: 4px;
|
||||
}
|
||||
.wecom-missing {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
.sync-stats {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
|
||||
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
|
||||
}
|
||||
.sync-section {
|
||||
margin-bottom: 12px;
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
|
||||
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
|
||||
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
|
||||
}
|
||||
.sync-footer {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
</style>
|
||||
@@ -60,11 +60,6 @@
|
||||
<t-empty v-else class="training-empty" description="培训签到仅课长/经理/人事/讲师可见" />
|
||||
</template>
|
||||
<StudyPanel v-else-if="activeTab === 'study'" :roles="myRoles" :admin="isAdmin" />
|
||||
<template v-else-if="activeTab === 'members'">
|
||||
<!-- 职称角色对经理开放(000159):与配置中心「角色权限」页签同口径 -->
|
||||
<MemberPanel v-if="canManageConfig" />
|
||||
<t-empty v-else class="training-empty" description="职称角色维护仅人事/经理可见" />
|
||||
</template>
|
||||
<template v-else-if="activeTab === 'rules'">
|
||||
<!-- 配置中心对经理开放(000158):经理与人事同权查看/维护培训规则 -->
|
||||
<RulePanel v-if="canManageConfig" />
|
||||
@@ -86,7 +81,6 @@ import PlanPanel from './components/PlanPanel.vue'
|
||||
import CoursePanel from './components/CoursePanel.vue'
|
||||
import LibraryPanel from './components/LibraryPanel.vue'
|
||||
import SignPanel from './components/SignPanel.vue'
|
||||
import MemberPanel from './components/MemberPanel.vue'
|
||||
import StudyPanel from './components/StudyPanel.vue'
|
||||
import RulePanel from './components/RulePanel.vue'
|
||||
import { expandRoles, fetchRoleDict, getMyProfile, roleLabelOf, type TrainingMember, type TrainingRoleDef } from '@/api/training'
|
||||
@@ -102,7 +96,7 @@ const TRAINING_TABS_META: Record<string, { title: string; desc: string }> = {
|
||||
library: { title: '课程管理', desc: '课程资产库维护:编号/课程名称/说明/分类/类型/线上线下/讲师/时长/课件/试题' },
|
||||
sign: { title: '培训签到', desc: '签到码生成、签到明细复核与佐证导出' },
|
||||
study: { title: '学习考试', desc: '我的课程学习、课程学习情况、课程考试情况与 AI 课程分析' },
|
||||
members: { title: '职称角色', desc: '名册来自「组织架构」,此处维护员工职称角色' },
|
||||
// members(职称角色)已并入「组织架构」页维护,路由 /platform/training/members 重定向过去
|
||||
rules: { title: '配置中心', desc: '培训业务规则在线配置,改配置不改代码' },
|
||||
}
|
||||
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
<template>
|
||||
<div class="member-panel">
|
||||
<!-- 员工档案(名册来自组织架构)+ 职称角色 -->
|
||||
<div class="panel-box member-layout__members">
|
||||
<div class="panel-box__header">
|
||||
<span class="panel-box__title">员工档案</span>
|
||||
<div class="member-panel__hint">
|
||||
员工与部门在「<a class="member-panel__link" @click="goOrgCenter">组织架构</a>」中统一维护,此处仅配置职称角色
|
||||
<t-button variant="outline" theme="primary" size="small" :loading="syncing" class="oa-sync-btn" @click="onPreviewSync">
|
||||
从OA同步企微账号
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<t-table :data="members" :columns="memberColumns" row-key="id" size="small" :loading="loading">
|
||||
<template #user_name="{ row }">
|
||||
<t-tooltip :content="memberName(row)" :disabled="!memberName(row)">
|
||||
<span class="member-name">{{ memberName(row) || '-' }}</span>
|
||||
</t-tooltip>
|
||||
</template>
|
||||
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
|
||||
<template #wecom_userid="{ row }">
|
||||
<span :class="row.wecom_userid ? '' : 'wecom-missing'">{{ row.wecom_userid || '未绑定' }}</span>
|
||||
</template>
|
||||
<template #roles="{ row }">
|
||||
<t-tag v-for="r in row.roles || []" :key="r" variant="light" size="small" class="role-tag">{{ roleText(r) }}</t-tag>
|
||||
</template>
|
||||
<template #op="{ row }">
|
||||
<t-button variant="text" theme="primary" size="small" @click="openWecom(row)">企微账号</t-button>
|
||||
<t-button variant="text" theme="primary" size="small" @click="openRoles(row)">设置角色</t-button>
|
||||
</template>
|
||||
</t-table>
|
||||
</div>
|
||||
|
||||
<t-dialog v-model:visible="wecomVisible" header="绑定企微账号" width="460">
|
||||
<t-input v-model="wecomInput" placeholder="企微 userid(管理后台→通讯录→成员详情→账号)" />
|
||||
<div class="form-hint">培训提醒推送到该企微账号;留空保存即解绑。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="savingWecom" @click="onSaveWecom">保存</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<!-- OA 同步预览:统计 + 冲突清单 + 待写入样本;无冲突才允许确认写入 -->
|
||||
<t-dialog v-model:visible="syncVisible" header="OA 企微账号同步" width="640" :footer="false">
|
||||
<template v-if="syncSummary">
|
||||
<div class="sync-stats">
|
||||
<span>本地员工 {{ syncSummary.local_candidates }}</span>
|
||||
<span>OA 命中 {{ syncSummary.local_matched }}</span>
|
||||
<span>已一致 {{ syncSummary.already_bound }}</span>
|
||||
<span class="sync-stats__main">待写入 {{ syncSummary.would_update }}</span>
|
||||
<span :class="syncSummary.conflict_count ? 'sync-stats__danger' : ''">冲突 {{ syncSummary.conflict_count }}</span>
|
||||
<span>OA 未找到 {{ syncSummary.local_missing }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="syncSummary.conflict_count" class="sync-section sync-section--danger">
|
||||
<div class="sync-section__title">冲突({{ syncSummary.conflict_count }})——存在冲突时不写入</div>
|
||||
<div v-for="(cf, i) in syncSummary.conflicts" :key="i" class="sync-row">
|
||||
{{ cf.employee_no }} {{ cf.user_name || '' }}:
|
||||
{{ conflictText(cf) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="syncSummary.would_update" class="sync-section">
|
||||
<div class="sync-section__title">将写入(最多展示 20 条)</div>
|
||||
<div v-for="(p, i) in syncSummary.pending_updates" :key="i" class="sync-row">
|
||||
{{ p.employee_no }} {{ p.user_name || p.name }} → 企微账号 {{ p.wecom_userid }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!syncSummary.conflict_count && !syncSummary.would_update" class="sync-section">
|
||||
无需更新:绑定已一致或 OA 无匹配数据。
|
||||
</div>
|
||||
|
||||
<div class="sync-footer">
|
||||
<t-button :disabled="syncSummary.conflict_count > 0 || syncSummary.would_update === 0"
|
||||
theme="primary" :loading="syncing" @click="onApplySync">
|
||||
确认写入
|
||||
</t-button>
|
||||
<t-button variant="outline" @click="syncVisible = false">关闭</t-button>
|
||||
</div>
|
||||
</template>
|
||||
</t-dialog>
|
||||
|
||||
<t-dialog v-model:visible="rolesVisible" header="设置职称角色" width="460">
|
||||
<!-- 选项来自配置中心角色字典(role_dict):系统角色 + 自定义角色 -->
|
||||
<t-select v-model="roleSelection" multiple style="width: 100%">
|
||||
<t-option v-for="r in roleDict" :key="r.key" :value="r.key" :label="r.label" />
|
||||
</t-select>
|
||||
<div class="form-hint">学员角色为全员默认,无需选择;角色与权限在「配置中心」维护。</div>
|
||||
<template #footer>
|
||||
<t-button theme="primary" :loading="saving" @click="onSaveRoles">保存</t-button>
|
||||
</template>
|
||||
</t-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import {
|
||||
fetchRoleDict,
|
||||
listMembers,
|
||||
listPlatformUsers,
|
||||
roleLabelOf,
|
||||
updateMemberRoles,
|
||||
updateMemberWecomUserid,
|
||||
applyWecomUseridSync,
|
||||
previewWecomUseridSync,
|
||||
type PlatformUser,
|
||||
type TrainingMember,
|
||||
type TrainingRoleDef,
|
||||
type WecomSyncConflict,
|
||||
type WecomSyncSummary,
|
||||
unwrap,
|
||||
} from '@/api/training'
|
||||
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const members = ref<TrainingMember[]>([])
|
||||
const platformUsers = ref<PlatformUser[]>([])
|
||||
// 角色字典(配置中心 role_dict):弹窗选项与角色标签文案的来源
|
||||
const roleDict = ref<TrainingRoleDef[]>([])
|
||||
|
||||
const rolesVisible = ref(false)
|
||||
const activeMember = ref<TrainingMember | null>(null)
|
||||
const roleSelection = ref<string[]>([])
|
||||
|
||||
// 企微账号绑定(培训提醒推送目标)
|
||||
const wecomVisible = ref(false)
|
||||
const activeWecomMember = ref<TrainingMember | null>(null)
|
||||
const wecomInput = ref('')
|
||||
const savingWecom = ref(false)
|
||||
|
||||
// OA 同步(工号 → 企微 userid,预览→写入两段式)
|
||||
const syncVisible = ref(false)
|
||||
const syncing = ref(false)
|
||||
const syncSummary = ref<WecomSyncSummary | null>(null)
|
||||
|
||||
const conflictText = (cf: WecomSyncConflict) => {
|
||||
switch (cf.reason) {
|
||||
case 'duplicate_workcode_in_oa':
|
||||
return `OA 中存在重复工号(企微账号 ${cf.new_wecom_userid}),请先在 OA 侧处理`
|
||||
case 'bound_to_different_userid':
|
||||
return `已绑定 ${cf.existing_wecom_userid},与 OA(${cf.new_wecom_userid})不一致,需人工确认`
|
||||
case 'userid_occupied':
|
||||
return `企微账号 ${cf.new_wecom_userid} 已被 ${cf.occupied_by_employee || '其他员工'} 占用`
|
||||
default:
|
||||
return cf.reason
|
||||
}
|
||||
}
|
||||
|
||||
const onPreviewSync = async () => {
|
||||
syncing.value = true
|
||||
try {
|
||||
const res = await previewWecomUseridSync()
|
||||
syncSummary.value = unwrap(res) ?? null
|
||||
syncVisible.value = true
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || 'OA 连接失败,请检查 OA_SQLSERVER_* 配置')
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const onApplySync = async () => {
|
||||
syncing.value = true
|
||||
try {
|
||||
const res = await applyWecomUseridSync()
|
||||
const summary = unwrap(res)
|
||||
MessagePlugin.success(`已写入 ${summary?.updated ?? 0} 条企微绑定`)
|
||||
syncVisible.value = false
|
||||
loadAll()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '写入失败')
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const memberColumns = [
|
||||
{ colKey: 'employee_no', title: '工号', width: 100 },
|
||||
{ colKey: 'user_name', title: '姓名' },
|
||||
{ colKey: 'dept_name', title: '部门', width: 110 },
|
||||
{ colKey: 'post', title: '岗位', width: 140 },
|
||||
{ colKey: 'wecom_userid', title: '企微账号', width: 120 },
|
||||
{ colKey: 'roles', title: '职称角色', width: 260 },
|
||||
{ colKey: 'op', title: '操作', width: 170 },
|
||||
]
|
||||
|
||||
// 角色 tag 文案取字典短名,字典外(trainee/已删角色)回退固定文案或 key
|
||||
const roleText = (r: string) => roleLabelOf(r, roleDict.value, true)
|
||||
|
||||
// 跳转组织架构页(部门/员工档案的唯一维护入口)
|
||||
const goOrgCenter = () => router.push('/platform/org-center')
|
||||
|
||||
// 姓名 = 真实姓名(来自 OIDC displayName claim):优先取后端联查的 user_name,
|
||||
// 再用平台用户表的 display_name / username 兜底;都取不到展示「-」,不再回退展示用户ID。
|
||||
const userNameMap = computed(() => {
|
||||
const m: Record<string, string> = {}
|
||||
for (const u of platformUsers.value) m[u.id] = u.display_name?.trim() || u.username
|
||||
return m
|
||||
})
|
||||
const memberName = (row: TrainingMember) => row.user_name || userNameMap.value[row.user_id] || ''
|
||||
|
||||
const loadAll = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
// 平台用户一并拉取,用于姓名兜底联查(user_id → 用户名)。
|
||||
const [m, u] = await Promise.all([
|
||||
listMembers({ page_size: 500 }),
|
||||
listPlatformUsers().catch(() => null),
|
||||
])
|
||||
members.value = unwrap(m)?.items || []
|
||||
platformUsers.value = unwrap(u) || []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openRoles = (row: TrainingMember) => {
|
||||
activeMember.value = row
|
||||
roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee')
|
||||
rolesVisible.value = true
|
||||
}
|
||||
|
||||
const openWecom = (row: TrainingMember) => {
|
||||
activeWecomMember.value = row
|
||||
wecomInput.value = row.wecom_userid || ''
|
||||
wecomVisible.value = true
|
||||
}
|
||||
|
||||
const onSaveWecom = async () => {
|
||||
if (!activeWecomMember.value) return
|
||||
savingWecom.value = true
|
||||
try {
|
||||
await updateMemberWecomUserid(activeWecomMember.value.id, wecomInput.value.trim())
|
||||
MessagePlugin.success('企微账号已更新')
|
||||
wecomVisible.value = false
|
||||
loadAll()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||
} finally {
|
||||
savingWecom.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const onSaveRoles = async () => {
|
||||
if (!activeMember.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
await updateMemberRoles(activeMember.value.id, [...roleSelection.value, 'trainee'])
|
||||
MessagePlugin.success('角色已更新')
|
||||
rolesVisible.value = false
|
||||
loadAll()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.response?.data?.message || '保存失败')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadAll()
|
||||
fetchRoleDict().then((d) => {
|
||||
roleDict.value = d
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@import (reference) '../training.less';
|
||||
|
||||
.panel-box {
|
||||
.training-panel-box();
|
||||
}
|
||||
|
||||
.member-panel__hint {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.member-panel__link {
|
||||
color: var(--td-brand-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.role-tag { margin-right: 4px; }
|
||||
.wecom-missing { color: var(--td-text-color-placeholder); }
|
||||
.oa-sync-btn { margin-left: 12px; }
|
||||
.sync-stats {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
.sync-stats__main { color: var(--td-brand-color); font-weight: 600; }
|
||||
.sync-stats__danger { color: var(--td-error-color); font-weight: 600; }
|
||||
}
|
||||
.sync-section {
|
||||
margin-bottom: 12px;
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
.sync-section__title { font-weight: 600; margin-bottom: 6px; }
|
||||
.sync-row { padding: 2px 0; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
|
||||
&.sync-section--danger .sync-section__title { color: var(--td-error-color); }
|
||||
}
|
||||
.sync-footer { display: flex; gap: 8px; justify-content: flex-end; }
|
||||
.form-hint {
|
||||
margin-top: 8px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
// 姓名列:最多展示 2 行,超出省略(悬停 tooltip 看全名)
|
||||
.member-name {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
word-break: break-all;
|
||||
line-height: 1.4;
|
||||
}
|
||||
</style>
|
||||
@@ -65,15 +65,25 @@ func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, i
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
|
||||
// users/org_depts 联查在此一并挂上:keyword 需要按姓名/部门名过滤,且 Count
|
||||
// 与列表共用同一过滤,联查必须两边一致(users/org_depts 对档案均为 1:1,
|
||||
// 不影响 Count 语义)。
|
||||
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
|
||||
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).Where("org_employees.tenant_id = ?", tenantID)
|
||||
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
||||
Where("org_employees.tenant_id = ?", tenantID).
|
||||
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
||||
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
||||
if q != nil {
|
||||
if q.DeptID != "" {
|
||||
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
||||
}
|
||||
if q.Keyword != "" {
|
||||
tx = tx.Where("org_employees.employee_no ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
||||
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
||||
// 按姓名/工号/部门名/岗位模糊查找;姓名取真实姓名(display_name)
|
||||
// 回退平台账号(username),与列表展示口径一致。
|
||||
tx = tx.Where(
|
||||
"org_employees.employee_no ILIKE ? OR COALESCE(NULLIF(u.display_name, ''), u.username, '') ILIKE ? "+
|
||||
"OR COALESCE(dp.name, '') ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
||||
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
||||
}
|
||||
}
|
||||
return tx
|
||||
@@ -102,9 +112,7 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
|
||||
tx := filter().
|
||||
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
||||
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
||||
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`).
|
||||
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
||||
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
||||
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`)
|
||||
if moduleKey != "" {
|
||||
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
||||
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
|
||||
@@ -112,8 +120,9 @@ func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64
|
||||
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
|
||||
}
|
||||
var employees []*types.OrgEmployee
|
||||
// 新增成员置顶(时间倒序):最新建档/导入的员工排在列表最前。
|
||||
err := tx.
|
||||
Order("org_employees.created_at ASC").
|
||||
Order("org_employees.created_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).
|
||||
Find(&employees).Error
|
||||
return employees, total, err
|
||||
@@ -141,6 +150,27 @@ func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// InsertEmployeesIfAbsent 自动入册专用:成员加入空间时补建员工档案。
|
||||
// 与 UpsertEmployees(导入语义,整行覆盖)不同,本方法只补空不覆盖——
|
||||
// 已有档案的工号/部门仅在为空时用新值回填(如 Casdoor 后同步到部门),
|
||||
// 人工维护过(或 OA 同步)的字段一律保留。
|
||||
func (r *orgCenterRepository) InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||
if len(employees) == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
||||
DoUpdates: clause.Assignments(map[string]interface{}{
|
||||
// 档案已有工号/部门时不覆盖(空串/空 id 视为未维护,由新值补齐)。
|
||||
"employee_no": gorm.Expr("COALESCE(NULLIF(org_employees.employee_no, ''), EXCLUDED.employee_no)"),
|
||||
"dept_id": gorm.Expr("COALESCE(NULLIF(org_employees.dept_id, ''), EXCLUDED.dept_id)"),
|
||||
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
||||
}),
|
||||
}).
|
||||
Create(&employees).Error
|
||||
}
|
||||
|
||||
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
|
||||
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
||||
if len(employees) == 0 {
|
||||
@@ -244,6 +274,26 @@ func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantI
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// GetRosterUserInfos resolves the roster-relevant user fields (平台账号 + Casdoor
|
||||
// 同步部门) for the given user IDs within the tenant — source for auto-creating
|
||||
// employee profiles when members join (EnsureEmployeesForUsers 的取数口径与
|
||||
// GetUsernamesByUserIDs 一致:本空间 active 成员)。
|
||||
func (r *orgCenterRepository) GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var users []*types.TrainingUserInfo
|
||||
err := r.db.WithContext(ctx).
|
||||
Table("users u").
|
||||
Select("u.id, u.username, u.dept_code, u.dept_name").
|
||||
Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+
|
||||
"AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID).
|
||||
Where("u.id IN ?", userIDs).
|
||||
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
||||
Scan(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 模块角色绑定
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
@@ -161,6 +162,66 @@ func firstDuplicateEmployeeNo(employees []*types.OrgEmployee) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// EnsureEmployeesForUsers 成员加入空间时自动入册(需求:平台新增成员自动添加
|
||||
// 到组织架构并匹配部门):按平台账号补建员工档案,部门按 Casdoor 同步字段
|
||||
// 自动匹配(dept_code 精确命中优先,dept_name 兜底;匹配范式与 Casdoor 同步
|
||||
// syncDepts 一致:小写去空格精确匹配)。档案已存在的成员跳过(仅补空),人工
|
||||
// 维护字段不被覆盖。fail-open:入册是成员加入的伴生动作,失败只记日志,
|
||||
// 不阻断成员关系本身。
|
||||
func (s *orgCenterService) EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error {
|
||||
if len(userIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
users, err := s.repo.GetRosterUserInfos(ctx, tenantID, userIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return nil
|
||||
}
|
||||
depts, err := s.repo.ListDepts(ctx, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byCode := make(map[string]string, len(depts))
|
||||
byName := make(map[string]string, len(depts))
|
||||
for _, d := range depts {
|
||||
if code := strings.ToLower(strings.TrimSpace(d.Code)); code != "" {
|
||||
byCode[code] = d.ID
|
||||
}
|
||||
if name := strings.ToLower(strings.TrimSpace(d.Name)); name != "" {
|
||||
if _, exists := byName[name]; !exists {
|
||||
byName[name] = d.ID // 首见优先,与 ListDepts 的 sort/created_at 序一致
|
||||
}
|
||||
}
|
||||
}
|
||||
employees := make([]*types.OrgEmployee, 0, len(users))
|
||||
for _, u := range users {
|
||||
deptID := ""
|
||||
if code := strings.ToLower(strings.TrimSpace(u.DeptCode)); code != "" {
|
||||
deptID = byCode[code]
|
||||
}
|
||||
if deptID == "" {
|
||||
if name := strings.ToLower(strings.TrimSpace(u.DeptName)); name != "" {
|
||||
deptID = byName[name]
|
||||
}
|
||||
}
|
||||
employees = append(employees, &types.OrgEmployee{
|
||||
ID: orgCenterNewID(),
|
||||
TenantID: tenantID,
|
||||
UserID: u.ID,
|
||||
EmployeeNo: u.Username, // 工号 = 平台账号(与导入回填同约定)
|
||||
DeptID: deptID, // 未匹配到已维护部门时留空,可后续手动修改
|
||||
Status: "active",
|
||||
})
|
||||
}
|
||||
if err := s.repo.InsertEmployeesIfAbsent(ctx, employees); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "[OrgCenter] members auto-rostered, tenant=%d count=%d", tenantID, len(employees))
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateEmployee updates one employee profile.
|
||||
func (s *orgCenterService) UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error) {
|
||||
if employee.ID == "" {
|
||||
|
||||
@@ -79,6 +79,7 @@ type tenantMemberService struct {
|
||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||
userRepo interfaces.UserRepository // optional; used to clear stale home-tenant pointers
|
||||
tokenRepo interfaces.AuthTokenRepository // optional; used to revoke sessions after removal
|
||||
org interfaces.OrgCenterService // optional; 成员加入时自动入册组织架构(见 ensureOrgRoster)
|
||||
}
|
||||
|
||||
// NewTenantMemberService constructs the service. Wired up via the DI
|
||||
@@ -100,12 +101,28 @@ func NewTenantMemberService(
|
||||
audit interfaces.AuditLogService,
|
||||
userRepo interfaces.UserRepository,
|
||||
tokenRepo interfaces.AuthTokenRepository,
|
||||
org interfaces.OrgCenterService,
|
||||
) interfaces.TenantMemberService {
|
||||
return &tenantMemberService{
|
||||
repo: repo,
|
||||
audit: audit,
|
||||
userRepo: userRepo,
|
||||
tokenRepo: tokenRepo,
|
||||
org: org,
|
||||
}
|
||||
}
|
||||
|
||||
// ensureOrgRoster 成员加入空间后自动补建组织架构员工档案(fail-open)。
|
||||
// 需求:平台新增成员自动添加到「组织架构」并按同步部门(dept_code/dept_name)
|
||||
// 自动匹配;对已是成员的用户同样触发(存量自愈),重复调用由
|
||||
// InsertEmployeesIfAbsent 的仅补空 upsert 幂等兜底,人工维护字段不受影响。
|
||||
func (s *tenantMemberService) ensureOrgRoster(ctx context.Context, userID string, tenantID uint64) {
|
||||
if s.org == nil || userID == "" || tenantID == 0 {
|
||||
return
|
||||
}
|
||||
if err := s.org.EnsureEmployeesForUsers(ctx, tenantID, []string{userID}); err != nil {
|
||||
logger.Warnf(ctx, "[OrgCenter] auto-roster failed (member join continues): user=%s tenant=%d err=%v",
|
||||
userID, tenantID, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +188,8 @@ func (s *tenantMemberService) AddMember(
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
// 已是成员:仍补一次入册(存量成员档案缺失时的自愈口)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return nil, ErrMembershipAlreadyExists
|
||||
}
|
||||
member := &types.TenantMember{
|
||||
@@ -201,6 +220,8 @@ func (s *tenantMemberService) AddMember(
|
||||
TargetUserID: userID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
})
|
||||
// 成员关系落库后自动入册组织架构(新增成员自动添加到名册并匹配部门)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return member, nil
|
||||
}
|
||||
|
||||
@@ -218,6 +239,7 @@ func (s *tenantMemberService) EnsureOwner(
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return existing, nil
|
||||
}
|
||||
member := &types.TenantMember{
|
||||
@@ -239,12 +261,15 @@ func (s *tenantMemberService) EnsureOwner(
|
||||
logger.Infof(ctx,
|
||||
"EnsureOwner lost race for user=%s tenant=%d, returning winning row (role=%s)",
|
||||
userID, tenantID, winner.Role)
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return winner, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Bootstrapped owner membership for user=%s tenant=%d", userID, tenantID)
|
||||
// 注册建空间的 Owner 同样自动入册(个人空间名册含创建者本人)。
|
||||
s.ensureOrgRoster(ctx, userID, tenantID)
|
||||
return member, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -272,7 +272,7 @@ func newServiceWithRepo() (interfaces.TenantMemberService, *fakeTenantMemberRepo
|
||||
// tests pre-date PR 6 and exercise membership invariants only. The
|
||||
// service's audit and RemoveMember-cleanup hooks are nil-safe, so
|
||||
// passing nil keeps existing coverage intact without forcing stubs.
|
||||
return NewTenantMemberService(r, nil, nil, nil), r
|
||||
return NewTenantMemberService(r, nil, nil, nil, nil), r
|
||||
}
|
||||
|
||||
// cleanupUserRepo is a minimal UserRepository used to assert that
|
||||
@@ -359,7 +359,7 @@ func TestTenantMemberService_RemoveMember_ClearsStaleHomeAndRevokesTokens(t *tes
|
||||
},
|
||||
}}
|
||||
tokenRepo := &cleanupTokenRepo{}
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||
@@ -396,7 +396,7 @@ func TestTenantMemberService_RemoveMember_RevokesTokensEvenWhenHomeUnchanged(t *
|
||||
"contrib": {ID: "contrib", TenantID: 1},
|
||||
}}
|
||||
tokenRepo := &cleanupTokenRepo{}
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo)
|
||||
svc := NewTenantMemberService(memberRepo, nil, userRepo, tokenRepo, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := svc.EnsureOwner(ctx, "owner", 7); err != nil {
|
||||
|
||||
@@ -337,7 +337,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterMemoryRoutes(v1, params.MemoryHandler, rbacGuards)
|
||||
RegisterAutomationRoutes(v1, params.AutomationHandler, rbacGuards)
|
||||
RegisterTrainingRoutes(v1, params.TrainingHandler, rbacGuards)
|
||||
RegisterOrgRoutes(v1, params.OrgCenterHandler, rbacGuards)
|
||||
RegisterOrgRoutes(v1, params.OrgCenterHandler, params.TrainingHandler, rbacGuards)
|
||||
RegisterChunkerDebugRoutes(v1, rbacGuards)
|
||||
|
||||
// Fail fast if any declared API-key policy points at a route
|
||||
|
||||
@@ -2,6 +2,7 @@ package router
|
||||
|
||||
import (
|
||||
"academy/internal/handler/orgcenter"
|
||||
"academy/internal/handler/training"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -11,7 +12,12 @@ import (
|
||||
// - 空间 RBAC 把关:读 Viewer+,写 Contributor+;
|
||||
// - 业务模块语义(职称角色等)由各模块自己的接口细控,本组不感知;
|
||||
// - 不对 API Key 开放(组织数据面向登录用户,默认拒绝)。
|
||||
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards) {
|
||||
//
|
||||
// th 为培训域 handler,可空:职称角色/企微账号维护自培训域迁入组织架构页后,
|
||||
// /org 域提供同名写接口(直接复用培训 handler —— 其 requireRoles 基于
|
||||
// callerTenantID 做角色细控,与 org 域租户口径一致,且不经培训域的
|
||||
// TrainingTenantResolution 租户回落,跨空间 HR 在组织架构页操作不会错绑租户)。
|
||||
func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, th *training.Handler, g *rbacGuards) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
@@ -28,6 +34,17 @@ func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, g *rbacGuards)
|
||||
orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers)
|
||||
orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees)
|
||||
|
||||
// ---- 职称角色 / 企微账号(培训域语义,handler 内 requireRoles(HR,经理) 细控) ----
|
||||
// 职称角色页(培训 members 子页)迁入组织架构页后的 /org 域别名路由:
|
||||
// 复用培训 handler,角色绑定仍写 module_key='training' 的 org_module_members。
|
||||
if th != nil {
|
||||
orgGroup.PUT("/employees/:id/roles", g.Contributor(), th.UpdateMemberRoles)
|
||||
orgGroup.PUT("/employees/:id/wecom-userid", g.Contributor(), th.UpdateMemberWecomUserid)
|
||||
// wecom-userid-sync 从 OA 目录按工号批量拉取企微 userid(预览→写入两段式)。
|
||||
orgGroup.POST("/employees/wecom-userid-sync/preview", g.Contributor(), th.SyncWecomUseridsPreview)
|
||||
orgGroup.POST("/employees/wecom-userid-sync/apply", g.Contributor(), th.SyncWecomUseridsApply)
|
||||
}
|
||||
|
||||
// ---- 模块角色绑定 ----
|
||||
orgGroup.GET("/modules/:module_key/members", h.ListModuleMembers)
|
||||
orgGroup.PUT("/modules/:module_key/members/:employee_id", g.Contributor(), h.PutModuleMember)
|
||||
|
||||
@@ -22,6 +22,9 @@ type OrgCenterRepository interface {
|
||||
GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error)
|
||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
||||
UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error
|
||||
// InsertEmployeesIfAbsent 成员加入时自动入册:按 (tenant, user_id) 补建,
|
||||
// 仅回填为空的工号/部门,不覆盖人工维护字段。
|
||||
InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error
|
||||
UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error
|
||||
DeleteEmployee(ctx context.Context, tenantID uint64, id string) error
|
||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||
@@ -30,6 +33,8 @@ type OrgCenterRepository interface {
|
||||
ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error)
|
||||
// GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。
|
||||
GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error)
|
||||
// GetRosterUserInfos 指定成员的入册所需字段(平台账号 + 同步部门)。
|
||||
GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error)
|
||||
|
||||
// ---- 模块角色绑定 ----
|
||||
GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error)
|
||||
@@ -52,6 +57,9 @@ type OrgCenterService interface {
|
||||
GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error)
|
||||
// ImportEmployees 批量导入(部门必填且必须命中本租户部门;按 tenant+user_id upsert)。
|
||||
ImportEmployees(ctx context.Context, tenantID uint64, employees []*types.OrgEmployee) (int, error)
|
||||
// EnsureEmployeesForUsers 成员加入空间时自动入册:按平台账号补建员工档案,
|
||||
// 部门按同步字段(dept_code 优先/dept_name 兜底)自动匹配;fail-open 不阻断入伙。
|
||||
EnsureEmployeesForUsers(ctx context.Context, tenantID uint64, userIDs []string) error
|
||||
UpdateEmployee(ctx context.Context, tenantID uint64, employee *types.OrgEmployee) (*types.OrgEmployee, error)
|
||||
CountEmployees(ctx context.Context, tenantID uint64) (int64, error)
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Migration: 000161_org_roster_backfill (down)
|
||||
-- 数据回填不可逆:回填行与此前人工/导入维护的员工档案无法区分(仅补空语义
|
||||
-- 下老档案也可能被回填工号/部门),回滚不做删除,保留数据。
|
||||
-- 如确需清理,请按 created_at 与迁移执行时间自行定位处理。
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000161] down is a no-op (backfilled roster rows are kept).'; END $$;
|
||||
@@ -0,0 +1,58 @@
|
||||
-- Migration: 000161_org_roster_backfill
|
||||
-- 存量平台成员一次性自动补入「组织架构」员工名册(需求:平台新增成员自动
|
||||
-- 添加到组织架构并自动匹配对应部门)。此后新加入空间的成员由
|
||||
-- tenantMemberService 的 ensureOrgRoster 挂钩实时入册(service/orgcenter.go
|
||||
-- EnsureEmployeesForUsers),本迁移负责把迁移前就已加入空间的存量成员补齐:
|
||||
-- - 工号 employee_no = 平台账号 users.username(与导入回填同约定);
|
||||
-- - 部门按 Casdoor 同步字段自动匹配:users.dept_code 命中 org_depts.code
|
||||
-- 优先,dept_name 命中 org_depts.name 兜底(小写去空格,各自 LATERAL 取
|
||||
-- sort/created_at 序首行);匹配不到已维护部门时 dept_id 留空,由管理员
|
||||
-- 在组织架构页手动调整;
|
||||
-- - ON CONFLICT (tenant_id, user_id) DO NOTHING:已有档案(含软删行)一律
|
||||
-- 不动,不覆盖任何人工/OA 同步字段,迁移幂等可重放。
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000161] Backfilling org_employees for existing tenant members...'; END $$;
|
||||
|
||||
INSERT INTO org_employees
|
||||
(id, tenant_id, user_id, employee_no, dept_id, post, lecturer_rate, wecom_userid, status, created_at, updated_at)
|
||||
SELECT
|
||||
gen_random_uuid()::text,
|
||||
tm.tenant_id,
|
||||
tm.user_id,
|
||||
u.username,
|
||||
COALESCE(dc.id, dn.id, ''),
|
||||
'',
|
||||
0,
|
||||
'',
|
||||
'active',
|
||||
NOW(),
|
||||
NOW()
|
||||
FROM tenant_members tm
|
||||
JOIN users u
|
||||
ON u.id = tm.user_id
|
||||
AND u.is_active = TRUE
|
||||
AND u.deleted_at IS NULL
|
||||
-- 部门编号精确命中优先(dept_code 同步自 IdP,与 syncDepts 匹配口径一致)
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT d.id
|
||||
FROM org_depts d
|
||||
WHERE d.tenant_id = tm.tenant_id
|
||||
AND d.deleted_at IS NULL
|
||||
AND d.code <> ''
|
||||
AND lower(btrim(d.code)) = lower(btrim(u.dept_code))
|
||||
ORDER BY d.sort ASC, d.created_at ASC
|
||||
LIMIT 1
|
||||
) dc ON u.dept_code <> ''
|
||||
-- 名称兜底:仅在编号未命中时参与,避免同名的编号部门抢占
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT d.id
|
||||
FROM org_depts d
|
||||
WHERE d.tenant_id = tm.tenant_id
|
||||
AND d.deleted_at IS NULL
|
||||
AND lower(btrim(d.name)) = lower(btrim(u.dept_name))
|
||||
ORDER BY d.sort ASC, d.created_at ASC
|
||||
LIMIT 1
|
||||
) dn ON u.dept_name <> '' AND dc.id IS NULL
|
||||
WHERE tm.status = 'active'
|
||||
AND tm.deleted_at IS NULL
|
||||
ON CONFLICT (tenant_id, user_id) DO NOTHING;
|
||||
Reference in new issue
Block a user