Files
ai_academy/frontend/src/views/org-center/OrgCenter.vue
T
runny 2f1cda34da
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
feat(优化):年培训计划:已确认行的删除按钮、勾选框、批量删除均仅超级管理员可见/可用;提示文案随角色变化
课程管理:canDeleteCourse 超管不限状态/部门(已审核/已发布行可删,确认弹窗文案区分);批量删除按钮超管可见
月培训计划:已发布行的「删除」仅超管可见(普通维护角色仍只能删未发布计划),行内确认弹窗替代原 window.confirm,失败时透出后端文案
Training.vue:canManageTabs 加入 super_admin,纯超管(未兼其他角色)也能进入这三个页面执行删除
2026-11-26 17:06:37 +08:00

991 lines
36 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="org-center-page">
<!-- 页头与知识库/企业培训同构:资源图标 + 页面名称 + 副标题 -->
<header class="org-header">
<div class="org-title-row">
<div class="org-title-group">
<h2>
<ResourceIcon type="training" :size="24" />
组织架构
</h2>
</div>
</div>
<p class="org-subtitle">部门与员工档案(租户共享),业务模块(企业培训/图纸标注等)按需引用</p>
</header>
<!-- 3/7 分栏:左侧部门,右侧员工档案 -->
<div class="org-body">
<div class="org-layout">
<div class="panel-box org-layout__depts">
<div class="panel-box__header">
<span class="panel-box__title">部门</span>
<t-button theme="primary" @click="openCreateDept">新增部门</t-button>
</div>
<!-- 表格滚动区:面板满屏,表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<div class="table-scroll">
<t-table :data="pagedDepts" :columns="deptColumns" row-key="id" size="small" height="100%">
<template #op="{ row }">
<div class="op-group">
<t-button variant="text" theme="primary" size="small" @click="onEditDept(row)">修改</t-button>
<t-button variant="text" theme="danger" size="small" @click="onDeleteDept(row)">删除</t-button>
</div>
</template>
</t-table>
</div>
<!-- 共用分页(000164):默认每页 15 条 -->
<TrainingPagination v-model:current="deptPage" v-model:page-size="deptPageSize" :total="deptTotal" />
</div>
<div class="panel-box org-layout__employees">
<div class="panel-box__header">
<span class="panel-box__title">员工档案</span>
<!-- 自「职称角色」页迁入:提示 + 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>
<!-- 收编归属空间:仅空间 Owner 可见/可操作(后端路由 Owner 限定),
把登录落在个人空间的成员默认落点改回本空间 -->
<t-button v-if="canAdopt" variant="outline" @click="openAdopt">收编到本空间</t-button>
<t-button variant="outline" @click="openPicker">从平台用户添加</t-button>
<t-button theme="primary" @click="importVisible = true">批量导入</t-button>
</div>
</div>
<!-- 表格滚动区:面板满屏,表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<div class="table-scroll">
<t-table :data="pagedEmployees" :columns="employeeColumns" row-key="id" size="small" height="100%" :loading="loading">
<template #user_name="{ row }">
<t-tooltip :content="employeeName(row)" :disabled="!employeeName(row)">
<span class="employee-name">{{ employeeName(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 #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>
<t-tag v-else theme="default" variant="light" size="small">{{ row.status || '-' }}</t-tag>
</template>
<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>
</div>
<!-- 共用分页(000164):默认每页 15 条 -->
<TrainingPagination v-model:current="employeePage" v-model:page-size="employeePageSize" :total="employeeTotal" />
</div>
</div>
</div>
<!-- 部门新增/修改弹窗 -->
<t-dialog v-model:visible="deptFormVisible" :header="deptForm.id ? '修改部门' : '新增部门'" width="420">
<t-form label-width="80">
<t-form-item label="部门名称" required>
<t-input v-model="deptForm.name" />
</t-form-item>
<t-form-item label="部门编码">
<t-input v-model="deptForm.code" />
</t-form-item>
</t-form>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onSaveDept">保存</t-button>
</template>
</t-dialog>
<!-- 批量导入:每行 用户ID,工号,部门,岗位 -->
<t-dialog v-model:visible="importVisible" header="批量导入员工(每行:用户ID,工号,部门,岗位)" width="560">
<t-textarea
v-model="importText"
:autosize="{ minRows: 8 }"
placeholder="user-uuid-1,26010003,生产一部,设备技师"
/>
<div class="form-hint">
部门为必填,支持填左侧部门的名称 / 编码 / ID,未维护的部门将整批拒绝导入。
工号可留空,留空时自动取平台账号。
</div>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onImport">导入</t-button>
</template>
</t-dialog>
<!-- 从平台用户添加:选择用户 → 指定部门/岗位(工号自动取平台账号) -->
<t-dialog v-model:visible="pickerVisible" header="从平台用户添加员工档案" width="520">
<t-form label-width="80">
<t-form-item label="选择用户" required>
<t-select v-model="pickerUserIds" multiple filterable placeholder="选择平台账号(可多选)" style="width: 100%">
<t-option
v-for="u in platformUsers"
:key="u.id"
:value="u.id"
:label="`${u.username}(${u.display_name?.trim() || u.email})${u.dept_name?.trim() ? ' · ' + u.dept_name.trim() : ''}${u.in_roster ? ' · 已在名册' : ''}`"
:disabled="u.in_roster"
/>
</t-select>
</t-form-item>
<t-form-item label="部门" required>
<t-select v-model="pickerDeptId" filterable placeholder="必选,请从左侧部门中选择" style="width: 100%">
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
</t-form-item>
<t-form-item label="岗位">
<t-input v-model="pickerPost" placeholder="如 设备技师" />
</t-form-item>
</t-form>
<div class="form-hint">工号无需填写,添加时自动取平台账号;已同步部门的用户会自动带出部门,可手动调整。</div>
<template #footer>
<t-button theme="primary" :loading="saving" :disabled="!pickerUserIds.length || !pickerDeptId" @click="onPickImport">添加到名册</t-button>
</template>
</t-dialog>
<!-- 修改员工档案:部门/岗位/状态可编辑;姓名与工号随平台账号只读展示 -->
<t-dialog v-model:visible="employeeFormVisible" header="修改员工档案" width="460">
<t-form label-width="80">
<t-form-item label="姓名">
<t-input :value="employeeForm.user_name || '-'" readonly />
</t-form-item>
<t-form-item label="工号">
<t-input :value="employeeForm.employee_no || '-'" readonly />
</t-form-item>
<t-form-item label="部门" required>
<t-select v-model="employeeForm.dept_id" filterable placeholder="必选,请从左侧部门中选择" style="width: 100%">
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
</t-form-item>
<t-form-item label="岗位">
<t-input v-model="employeeForm.post" placeholder="如 设备技师" />
</t-form-item>
<t-form-item label="状态">
<t-select v-model="employeeForm.status" style="width: 100%">
<t-option value="active" label="在职" />
<t-option value="inactive" label="离职" />
</t-select>
</t-form-item>
</t-form>
<div class="form-hint">姓名与工号随平台账号维护,不在修改范围。</div>
<template #footer>
<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>
<!-- 收编到本空间:把登录落在个人空间的成员的默认落点改回本空间。
预览(归属空间不在本空间的活跃成员)→ 确认收编,与 OA 同步同两段式交互 -->
<t-dialog v-model:visible="adoptVisible" header="收编成员到本空间" width="680" :footer="false">
<div class="form-hint adopt-hint">
名单为「归属空间不在本空间」的活跃成员(首次登录自动开通个人空间后,登录会落进个人空间,看不到本空间维护的组织架构与培训数据)。
收编后其默认登录空间改为本空间,下次登录起直接进入本空间;成员关系、角色与个人空间数据均不变,成员仍可随时用左下角空间切换器改回。
</div>
<template v-if="adoptLoaded">
<div v-if="!adoptList.length" class="sync-section">
没有可收编成员:所有成员的登录默认空间都已指向本空间。
</div>
<template v-else>
<t-table
:data="adoptList"
:columns="adoptColumns"
row-key="id"
size="small"
max-height="360"
>
<template #display_name="{ row }">{{ row.display_name || '-' }}</template>
<template #home="{ row }">
{{ row.home_tenant_name || (row.home_tenant_id ? `空间 ${row.home_tenant_id}` : '无归属空间') }}
</template>
<template #in_roster="{ row }">
<t-tag v-if="row.in_roster" theme="success" variant="light" size="small">在名册</t-tag>
<t-tag v-else theme="default" variant="light" size="small">未入册</t-tag>
</template>
</t-table>
<div class="sync-footer">
<t-button variant="outline" @click="adoptVisible = false">关闭</t-button>
<t-button theme="primary" :loading="adopting" @click="onAdopt">
全部收编({{ adoptList.length }})
</t-button>
</div>
</template>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import {
adoptHomeTenant,
applyOrgWecomSync,
deleteDept,
importEmployees,
listAdoptableUsers,
listDepts,
listEmployees,
listPlatformUsers,
ORG_MODULE_TRAINING,
previewOrgWecomSync,
saveDept,
updateEmployee,
updateOrgEmployeeRoles,
updateOrgEmployeeWecomUserid,
type OrgAdoptableUser,
type OrgDept,
type OrgEmployee,
type OrgPlatformUser,
} from '@/api/org-center'
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'
import TrainingPagination from '../training/components/TrainingPagination.vue'
import { useTrainingPager } from '../training/components/useTrainingPager'
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 语义)。
const deptForm = ref({ id: '', parent_id: '', sort: 0, name: '', code: '' })
const importText = ref('')
// 用户选择器导入
const pickerVisible = ref(false)
const pickerUserIds = ref<string[]>([])
const pickerDeptId = ref('')
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
}
}
// ---- 收编到本空间(归属空间=登录默认落点;后端 Owner 限定) ----
// 仅空间 Owner 可见(与后端 g.Owner() 路由口径对齐;localStorage 只是渲染参考,
// 实际权限以服务端为准,越权点击会收到 403)。
const canAdopt = computed(() => authStore.hasRole('owner'))
const adoptVisible = ref(false)
const adoptLoaded = ref(false)
const adopting = ref(false)
const adoptList = ref<OrgAdoptableUser[]>([])
const adoptColumns = [
{ colKey: 'username', title: '工号', width: 100 },
{ colKey: 'display_name', title: '姓名', width: 110 },
{ colKey: 'email', title: '邮箱', minWidth: 160, ellipsis: true },
{ colKey: 'home', title: '当前归属空间(登录落点)', width: 180 },
{ colKey: 'in_roster', title: '名册', width: 80 },
]
const openAdopt = async () => {
adoptVisible.value = true
adoptLoaded.value = false
adoptList.value = []
try {
const res = await listAdoptableUsers()
adoptList.value = unwrap(res) || []
adoptLoaded.value = true
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '加载可收编成员失败')
}
}
const onAdopt = async () => {
if (!adoptList.value.length) return
adopting.value = true
try {
const res = await adoptHomeTenant(adoptList.value.map((u) => u.id))
const result = unwrap(res)
const skipped = result?.skipped || []
MessagePlugin.success(`已收编 ${result?.adopted ?? 0} 名成员,自下次登录起默认进入本空间`)
// 预览与收编之间成员关系可能变化(被移出/停用),逐条原因只提示首条避免刷屏。
if (skipped.length) {
const first = skipped[0]
MessagePlugin.warning(
`${skipped.length} 名成员被跳过:如 ${first.username} ${first.reason}${skipped.length > 1 ? ' 等' : ''}`,
)
}
adoptVisible.value = false
loadEmployees()
} catch (err: any) {
MessagePlugin.error(err?.response?.data?.message || '收编失败')
} finally {
adopting.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: '部门名称' },
// 000164:编码列收窄(0001 等短编码无需过宽列,原 140px 留白明显)
{ colKey: 'code', title: '编码', width: 64 },
// 窄屏下列宽超出面板时操作列随滚动固定在右侧,保证可见可点
{ colKey: 'op', title: '操作', width: 116, fixed: 'right' },
]
// 管理角色额外有「企微账号/设置角色」操作,操作列随之加宽(computed 随权限就绪刷新)
const employeeColumns = computed(() => [
{ colKey: 'employee_no', title: '工号', width: 90 },
{ 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。
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 employeeName = (row: OrgEmployee) => row.user_name || userNameMap.value[row.user_id] || ''
// ---------------------------------------------------------------------------
// 从平台用户添加:部门自动带出(000156)
// Casdoor 同步把部门编号/名称落在平台账号上(users.dept_code/dept_name);
// 选中用户后,若所选用户都带同一个部门编号且能映射到左侧组织架构部门,
// 则自动预选该部门——仍可手动改,与导入接口的部门必填校验解耦。
// ---------------------------------------------------------------------------
// 部门编号 → 组织架构部门 id(列表顺序在后,同编号后写入者胜出,与唯一索引兜底一致)。
const deptIdByCode = computed(() => {
const m: Record<string, string> = {}
for (const d of depts.value) {
const code = d.code?.trim()
if (code) m[code] = d.id
}
return m
})
watch(pickerUserIds, (ids) => {
if (!ids.length) return
const selected = platformUsers.value.filter((u) => ids.includes(u.id))
if (!selected.length) return
const codes = selected.map((u) => u.dept_code?.trim() || '')
// 有任一用户没同步到部门,或部门编号不一致 → 不自动带出,保留当前选择。
if (codes.some((c) => !c)) return
const code = codes[0]
if (codes.some((c) => c !== code)) return
const deptId = deptIdByCode.value[code]
if (deptId) pickerDeptId.value = deptId
})
// 员工列表:module_key='training' 联查职称角色展示;keyword 按姓名/工号/部门过滤。
const loadEmployees = async () => {
loading.value = true
try {
const e = await listEmployees({
module_key: ORG_MODULE_TRAINING,
keyword: keyword.value.trim() || undefined,
page_size: 500,
})
employees.value = unwrap(e)?.items || []
} finally {
loading.value = false
}
}
// 输入防抖触发查找(enter/clear 立即触发由模板回调完成)
let searchTimer: ReturnType<typeof setTimeout> | undefined
watch(keyword, () => {
clearTimeout(searchTimer)
searchTimer = setTimeout(() => loadEmployees(), 300)
})
// 共用分页(000164):部门/员工档案列表默认每页 15 条;
// 查找或增删改刷新列表后回到第 1 页
const {
page: deptPage,
pageSize: deptPageSize,
total: deptTotal,
paged: pagedDepts,
reset: resetDeptPage,
} = useTrainingPager(depts)
const {
page: employeePage,
pageSize: employeePageSize,
total: employeeTotal,
paged: pagedEmployees,
reset: resetEmployeePage,
} = useTrainingPager(employees)
watch([depts, employees], () => {
resetDeptPage()
resetEmployeePage()
})
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
}
const onSaveDept = async () => {
if (!deptForm.value.name) {
MessagePlugin.warning('请填写部门名称')
return
}
saving.value = true
try {
await saveDept(deptForm.value)
MessagePlugin.success(deptForm.value.id ? '部门已更新' : '部门已保存')
deptFormVisible.value = false
deptForm.value = { id: '', parent_id: '', sort: 0, name: '', code: '' }
loadAll()
} catch {
MessagePlugin.error('保存失败')
} finally {
saving.value = false
}
}
// 修改部门:回填当前行(带 id 走更新,并透传 parent_id/sort 防止被清空)。
const onEditDept = (row: OrgDept) => {
deptForm.value = {
id: row.id,
parent_id: row.parent_id || '',
sort: row.sort || 0,
name: row.name,
code: row.code || '',
}
deptFormVisible.value = true
}
const onDeleteDept = async (row: OrgDept) => {
if (!window.confirm(`确认删除部门「${row.name}」?`)) return
try {
await deleteDept(row.id)
MessagePlugin.success('已删除')
loadAll()
} catch {
MessagePlugin.error('删除失败')
}
}
const openPicker = async () => {
pickerVisible.value = true
try {
const res = await listPlatformUsers()
platformUsers.value = unwrap(res) || []
if (!depts.value.length) {
const d = await listDepts()
depts.value = unwrap(d) || []
}
} catch {
platformUsers.value = []
}
}
const onPickImport = async () => {
if (!pickerUserIds.value.length) return
// 部门必填:必须归属已维护的部门。
if (!pickerDeptId.value) {
MessagePlugin.warning('请选择部门')
return
}
saving.value = true
try {
// 工号 = 平台账号(username,员工编号型 IdP 同步而来),不再前缀自增生成。
const usernameMap = new Map(platformUsers.value.map((u) => [u.id, u.username]))
const items = pickerUserIds.value.map((uid) => ({
user_id: uid,
employee_no: usernameMap.get(uid) || '',
dept_id: pickerDeptId.value,
post: pickerPost.value,
}))
await importEmployees(items)
MessagePlugin.success(`已添加 ${items.length} 名员工到名册`)
pickerVisible.value = false
pickerUserIds.value = []
pickerDeptId.value = ''
loadEmployees()
} catch {
MessagePlugin.error('添加失败')
} finally {
saving.value = false
}
}
// 修改员工档案:回填当前行(姓名经 employeeName 联查兜底)。
const onEditEmployee = (row: OrgEmployee) => {
employeeForm.value = {
id: row.id,
user_name: employeeName(row),
employee_no: row.employee_no || '',
dept_id: row.dept_id || '',
post: row.post || '',
status: row.status || 'active',
}
employeeFormVisible.value = true
}
const onSaveEmployee = async () => {
// 部门必填,且必须命中左侧部门(与导入同规)。
if (!employeeForm.value.dept_id) {
MessagePlugin.warning('请选择部门')
return
}
saving.value = true
try {
await updateEmployee(employeeForm.value.id, {
dept_id: employeeForm.value.dept_id,
post: employeeForm.value.post.trim(),
status: employeeForm.value.status,
})
MessagePlugin.success('员工档案已更新')
employeeFormVisible.value = false
loadEmployees()
} catch {
MessagePlugin.error('保存失败')
} finally {
saving.value = false
}
}
// 按名称/编码/ID 把导入行里的部门解析成部门列表的 dept id。
const resolveDeptId = (raw?: string) => {
const key = (raw || '').trim()
if (!key) return ''
const hit = depts.value.find((d) => d.id === key || d.code === key || d.name === key)
return hit?.id || ''
}
const onImport = async () => {
const lines = importText.value.split('\n').map((l) => l.trim()).filter(Boolean)
if (!lines.length) {
MessagePlugin.warning('请粘贴员工行')
return
}
const items: { user_id: string; employee_no: string; dept_id: string; post: string }[] = []
const badRows: string[] = []
lines.forEach((line, i) => {
// 兼容中英文逗号(\uFF0C)与制表符拆分:用户ID,工号,部门,岗位
const [user_id, employee_no, deptRaw, post] = line.split(/[,\uFF0C\t]/).map((s) => s.trim())
const dept_id = resolveDeptId(deptRaw)
// 部门必填,且必须命中左侧部门(名称/编码/ID 均可)。
if (!user_id || !dept_id) {
badRows.push(`第 ${i + 1} 行${!user_id ? '缺少用户ID' : ''}${!user_id && !dept_id ? '、' : ''}${!dept_id ? '部门未匹配到已维护部门' : ''}`)
return
}
items.push({ user_id, employee_no: employee_no || '', dept_id, post: post || '' })
})
if (badRows.length) {
MessagePlugin.error(badRows.slice(0, 3).join(';') + (badRows.length > 3 ? ` 等 ${badRows.length} 行不合法` : ',请检查后重试'))
return
}
saving.value = true
try {
const res = await importEmployees(items)
MessagePlugin.success(`已导入 ${unwrap(res)?.imported ?? 0} 名员工`)
importVisible.value = false
importText.value = ''
loadEmployees()
} catch {
MessagePlugin.error('导入失败,请检查部门是否为已维护部门')
} finally {
saving.value = false
}
}
onMounted(() => {
loadAll()
loadProfile()
fetchRoleDict().then((d) => {
roleDict.value = d
})
})
</script>
<style lang="less" scoped>
@import (reference) '../training/training.less';
// 页面容器与页头沿用企业培训的视觉规范(知识库/工具箱同款)
.org-center-page {
.training-page-frame();
}
.org-header {
.training-header();
}
.org-body {
flex: 1;
min-height: 0;
min-width: 0;
overflow-y: auto;
overflow-x: hidden;
padding: var(--app-space-3) 0 var(--app-space-6);
}
// 分栏:部门列收窄为固定宽度(000164,原 3fr 过宽且编码列留白明显),
// 员工档案占剩余全部宽度;窄屏退化为单列。
// 满屏布局(000164 布局诉求):栅格占满页身剩余高度,两面板各自内部滚动 ——
// 面板头(标题/操作/查找)/表头/分页固定,仅表格数据区滚动;窄屏单列回退整页滚动
.org-layout {
display: grid;
grid-template-columns: 280px minmax(0, 1fr);
// 满屏关键:行高锁定为容器高(grid 行默认 auto 会被内容撑开,面板 height:100%
// 的百分比链随之失效,表头/分页固定就不生效了)
grid-template-rows: minmax(0, 1fr);
gap: 12px;
height: 100%;
min-height: 0;
@media (max-width: 900px) {
grid-template-columns: 1fr;
grid-template-rows: none;
height: auto;
}
// 000164 栅格子项收敛:员工档案表格/工具行较宽,缺省 min-width 会把
// 栅格轨道撑出视口,右侧列与操作按钮被裁掉不可见不可点;
// 收敛后表格在面板内横向滚动,操作列 fixed:right 始终可见
> .panel-box {
min-width: 0;
}
}
.panel-box {
.training-panel-box();
.org-layout & {
display: flex;
flex-direction: column;
height: 100%;
@media (max-width: 900px) {
height: auto;
}
}
// 面板头固定,表格滚动区撑满剩余高度(表格 height=100% 启用 TDesign 固定表头;
// .t-table 根也要撑满 100%,否则百分比退化为内容高、表头固定不生效)
.org-layout & > .table-scroll {
flex: 1;
min-height: 0;
> .t-table {
height: 100%;
}
}
.org-layout & > .training-pagination {
flex-shrink: 0;
}
}
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 部门行内操作按钮组
.op-group {
display: flex;
gap: 4px;
white-space: nowrap;
}
// 姓名列:最多展示 2 行,超出省略(悬停 tooltip 看全名)
.employee-name {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
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;
}
// 收编弹窗说明文案
.adopt-hint {
margin: 0 0 10px;
}
</style>