Files
ai_academy/frontend/src/views/training/components/PlanPanel.vue
T
runny 242dd7e1a6 feat(training): 企业培训迭代:核验权限收窄、课程发布状态与培训中心改版
需求域:
- 需求导入修复内/外培训与外部讲师落库;按模板标题年入库(年-月一致)
- 核验确认收窄为「需求归属部门+经理职称角色」,越权提示联系部门经理
- 确认转月计划后自动推送讲师/课长维护;导入后自动推送部门经理核验(站内+企微)

课程域:
- 课程管理发布状态字段(迁移000154)+发布/下线;培训中心「和信课程」目录
- 需求讲师改选后回写课程管理;确认同步带出适合人员/课件/试题
- 月计划详情课件/试题更换(上传/知识库选择/题库换绑)回写课程管理,
  无关联条目的存量计划自动创建课程条目

模板与表单:
- 教育训练需求表:适合人员/内-外培训口径;部门联动课程下拉;
  适合人员/讲师按所选课程自动带出;在线提报课程下拉(本部门)自动带出分类/讲师/适合人员

页面与权限:
- 培训中心页签重组(和信课程/我的培训/我的考试),移除线上/线下页签
- 数据驾驶舱迁侧栏(职称角色之下);职称角色迁至更多工具配置中心之后
- 配置中心/职称角色对经理开放;页签「职称角色」更名「角色权限」
- 修复年度下拉空白(TDesign options 需对象数组)、月计划列表地点兜底

其他: 培训预览端口修正与 dev:training 脚本;tmp-extract-duckdb 加入 gitignore
2026-11-19 01:49:17 +08:00

1024 lines
40 KiB
Vue

<template>
<div class="plan-panel">
<!-- 年度需求收集(按年度切换查看收集汇总) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title plan-title-row">
年度需求收集
<!-- 年份下拉用 t-option 槽渲染:TDesign :options 需 {label,value} 对象,
直接传 number[] 会渲染空白选项(无法选中) -->
<t-select
v-model="selectedYear"
class="year-select"
@change="onYearChange"
>
<t-option v-for="y in yearOptions" :key="y" :value="y" :label="String(y)" />
</t-select>
</span>
<div class="panel-box__actions">
<t-button v-if="canManage" theme="primary" @click="openCollect">收集下年度计划</t-button>
<t-button variant="outline" @click="onOpenDemandForm">在线提报需求</t-button>
<t-button v-if="canManage" variant="outline" @click="importDemandsVisible = true">批量导入</t-button>
</div>
</div>
<!-- 搜索:状态 / 部门 / 课程名称模糊;批量确认(仅本部门经理)/删除与查询条件同行 -->
<div class="demand-search">
<t-select v-model="demandSearch.state" clearable placeholder="状态" style="width: 110px">
<t-option label="待核验" value="pending" />
<t-option label="已确认" value="confirmed" />
<t-option label="已修正" value="fixed" />
</t-select>
<t-select v-model="demandSearch.dept_id" clearable filterable placeholder="部门" style="width: 150px">
<t-option v-for="d in depts" :key="d.id" :label="d.name" :value="d.id" />
</t-select>
<t-input
v-model="demandSearch.keyword"
clearable
placeholder="课程名称模糊搜索"
style="width: 200px"
@enter="loadDemands"
/>
<t-button variant="outline" @click="loadDemands">查询</t-button>
<t-button variant="outline" @click="onResetDemandSearch">重置</t-button>
<t-button v-if="canConfirm" theme="primary" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchConfirm">批量确认</t-button>
<t-button v-if="canManage" theme="danger" variant="outline" :disabled="!selectedDemandKeys.length" :loading="batchSaving" @click="onBatchDelete">批量删除</t-button>
<span class="demand-selected-hint">已选 {{ selectedDemandKeys.length }} 项(可批量确认/删除未确认需求)</span>
</div>
<t-table
v-model:selected-row-keys="selectedDemandKeys"
:data="demands"
:columns="demandColumns"
row-key="id"
size="small"
:loading="loading"
>
<template #dept_name="{ row }">{{ row.dept_name || '-' }}</template>
<template #code="{ row }">
<t-tooltip v-if="row.code" :content="row.code">
<span class="cell-ellipsis">{{ row.code }}</span>
</t-tooltip>
<span v-else>-</span>
</template>
<template #lecturer_name="{ row }">{{ row.lecturer_name || '-' }}</template>
<!-- 计划培训月份入库格式「YYYY-M」(如 2027-1),原样展示 -->
<template #planned_time="{ row }">{{ row.planned_time || '-' }}</template>
<template #location="{ row }">{{ row.location || '-' }}</template>
<!-- 适合人员/备注可能很长:单行省略,悬停浮出全部内容 -->
<template #post_scope="{ row }">
<t-tooltip v-if="row.post_scope" :content="row.post_scope">
<span class="cell-ellipsis">{{ row.post_scope }}</span>
</t-tooltip>
<span v-else>-</span>
</template>
<template #remark="{ row }">
<t-tooltip v-if="row.remark" :content="row.remark">
<span class="cell-ellipsis">{{ row.remark }}</span>
</t-tooltip>
<span v-else>-</span>
</template>
<template #check_status="{ row }">
<t-tag v-if="row.check_status === 'passed'" theme="success" variant="light" size="small">已确认</t-tag>
<t-tag v-else-if="row.check_status === 'pending'" theme="warning" variant="light" size="small">待核验</t-tag>
<t-tag v-else theme="default" variant="light" size="small">已修正</t-tag>
</template>
<template #op="{ row }">
<template v-if="row.status !== 'confirmed'">
<t-button
v-if="canConfirm"
variant="text" theme="primary" size="small" @click="onConfirmDemand(row)"
>确认</t-button>
<t-button
variant="text" theme="primary" size="small" @click="onEditDemand(row)"
>编辑</t-button>
<t-popconfirm content="确定删除该条需求?" theme="danger" @confirm="onDeleteDemand(row)">
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
</template>
</template>
</t-table>
</div>
<!-- 提报需求弹窗(编辑态复用:部门按提报人自动获取) -->
<t-dialog v-model:visible="demandFormVisible" :header="demandDialogTitle" width="560">
<t-form :data="demandForm" label-width="90" @submit="onSaveDemand">
<t-form-item v-if="demandForm.id" label="编号" name="code">
<t-input :value="demandCodeDisplay" disabled />
</t-form-item>
<t-form-item label="课程名称" name="course_name" required>
<!-- 000156:从课程管理选择本部门课程(自动带出分类/讲师/适合人员),也可直接填写新课程 -->
<t-select
v-model="demandForm.course_name"
clearable
filterable
creatable
:loading="libraryLoading"
placeholder="从课程管理选择本部门课程,或直接填写新课程"
style="width: 100%"
@change="onDemandCourseChange"
>
<t-option
v-for="c in deptCourseOptions"
:key="c.id"
:value="c.name"
:label="`${c.name}${c.category ? `(${c.category})` : ''}`"
/>
</t-select>
</t-form-item>
<t-form-item label="分类" name="category">
<t-input :value="demandForm.category" disabled placeholder="随所选课程自动带出" />
</t-form-item>
<t-form-item label="所属部门" name="dept_id">
<t-input :value="deptDisplay" disabled placeholder="提交时按提报人所在部门自动获取" />
</t-form-item>
<t-form-item label="适合人员" name="post_scope">
<t-input v-model="demandForm.post_scope" placeholder="可填写多个适合人员,用、或,分隔(选填)" />
</t-form-item>
<t-form-item label="计划培训月份" name="planned_month">
<t-select
v-model="demandForm.planned_month"
clearable
placeholder="选填,只需选到月份;确认后同步到培训课程"
style="width: 100%"
>
<t-option v-for="m in 12" :key="m" :label="`${m} 月`" :value="m" />
</t-select>
</t-form-item>
<t-form-item label="内/外培训" name="train_type">
<!-- 下拉选择(000154):内部/外部,清空即未选择 -->
<t-select v-model="demandForm.train_type" clearable placeholder="从下拉选择内部或外部(选填)" style="width: 100%">
<t-option label="内部" value="内部" />
<t-option label="外部" value="外部" />
</t-select>
</t-form-item>
<t-form-item label="厂区" name="plant">
<t-input v-model="demandForm.plant" placeholder="如:三厂(选填)" />
</t-form-item>
<t-form-item label="地点" name="location">
<t-input v-model="demandForm.location" placeholder="如:教育训练室(选填)" />
</t-form-item>
<t-form-item label="培训次数" name="session_count">
<t-input-number v-model="demandForm.session_count" :min="1" :step="1" style="width: 100%" />
</t-form-item>
<t-form-item label="讲师" name="lecturer">
<!-- creatable:可直接输入外部讲师姓名(非系统员工),提交时解析为 id 或外部姓名 -->
<t-select
v-model="demandForm.lecturer"
clearable
filterable
creatable
placeholder="选填,从讲师名册选择或直接输入外部讲师姓名"
>
<t-option v-for="l in lecturers" :key="l.id" :label="l.name" :value="l.id" />
</t-select>
</t-form-item>
<t-form-item label="备注" name="remark">
<t-textarea v-model="demandForm.remark" :autosize="{ minRows: 2 }" />
</t-form-item>
</t-form>
<template #footer>
<t-button variant="outline" @click="demandFormVisible = false">取消</t-button>
<t-button theme="primary" :loading="saving" @click="onSaveDemand">提交</t-button>
</template>
</t-dialog>
<!-- 批量导入需求弹窗:粘贴行(课程名称,人数,课时)或下载模板后上传 Excel -->
<t-dialog v-model:visible="importDemandsVisible" header="批量导入需求(下载模板填写后导入)" width="620">
<div class="import-row">
<t-button variant="outline" @click="onDownloadDemandTemplate">下载教育训练需求表模板</t-button>
<span class="import-file">
或上传填写好的模板 Excel:<input type="file" accept=".xlsx,.xls" @change="onImportDemandExcel" />
</span>
</div>
<t-textarea
v-model="importDemandsText"
:autosize="{ minRows: 6 }"
placeholder="或粘贴需求行:课程名称[,计划培训月份如 3] (支持中英文逗号)"
/>
<div class="form-hint">模板列对应:编号/部门/课程名称/适合人员/地点/培訓費用/内/外培训(内部或外部,下拉选择)/计划培训月份(1~12,下拉选择)/讲师/备注;适合人员可填多人(、/,分隔),讲师可填系统员工(按姓名自动匹配并带出部门)或外部讲师姓名;导入后统一为「待核验」,由部门经理核验确认。</div>
<template #footer>
<t-button theme="primary" :loading="saving" @click="onImportDemands">导入粘贴内容</t-button>
</template>
</t-dialog>
<!-- 收集下年度计划:发送模板 + 推送人员(默认各课长,可增删),确认后站内+企微批量推送 -->
<t-dialog v-model:visible="collectVisible" :header="`收集下年度计划(${nextYear})`" width="560">
<div class="collect-section-title">发送模板</div>
<div class="collect-template-row">
<span class="collect-template-name">教育训练需求表模板(填写后经「批量导入」上传,或「在线提报需求」逐条填写)</span>
<t-button variant="outline" size="small" @click="onDownloadDemandTemplate">下载模板</t-button>
</div>
<div class="collect-section-title">发送人员</div>
<t-select
v-model="collectForm.userIds"
multiple
filterable
clearable
placeholder="默认各课长,可修改添加删除"
style="width: 100%"
:loading="membersLoading"
>
<t-option v-for="m in members" :key="m.user_id" :value="m.user_id" :label="memberLabel(m)" />
</t-select>
<div class="form-hint">默认勾选各课长;可自行添加或移除推送人员。</div>
<div class="collect-section-title">通知内容</div>
<t-textarea v-model="collectForm.content" :autosize="{ minRows: 3 }" />
<template #footer>
<t-button variant="outline" @click="collectVisible = false">取消</t-button>
<t-button theme="primary" :loading="collectSending" @click="onSendCollect">确认推送</t-button>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import * as XLSX from 'xlsx'
import { DEMAND_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
import { apiErrorMessage } from '@/utils/request'
import {
broadcastTrainingNotification,
confirmDemand,
deleteDemand,
getMyProfile,
importDemands,
listCourseLibrary,
listDemandYears,
listDemands,
listDepts,
listLecturers,
listMembers,
saveDemand,
type TrainingDept,
type TrainingDemand,
type TrainingLibraryCourse,
type TrainingLecturerOption,
type TrainingMember,
unwrap,
} from '@/api/training'
const props = defineProps<{ roles: string[]; admin?: boolean }>()
// 计划管理(录入/推送/排课):人事/课长(roles 已按权限组展开,经理自动命中课长)
const canManage = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor'))
// 核验确认入口:经理职称角色可见(空间管理员直通,便于授权引导);
// 实际可确认范围按行校验(本部门+经理,000154),越权点击统一提示联系部门经理。
const canConfirm = computed(() => props.admin || props.roles.some((r) => r === 'exec'))
// 行级确认权限:需求归属部门=本人所在部门,且本人具有经理职称角色。
const canConfirmDemand = (row: TrainingDemand) =>
canConfirm.value && Boolean(row.dept_id) && row.dept_id === myDeptId.value
const now = new Date()
const currentYear = now.getFullYear()
// 年度需求收集:年份下拉为需求库实际年份(降序),默认展示最新一年(无数据回退当前年)
const selectedYear = ref(currentYear)
const yearOptions = ref<number[]>([])
const onYearChange = () => loadDemands()
const loading = ref(false)
const saving = ref(false)
const demands = ref<TrainingDemand[]>([])
// 表单/搜索数据源:部门树、讲师名册、课程管理条目(课程名称下拉,000156)
const depts = ref<TrainingDept[]>([])
const lecturers = ref<TrainingLecturerOption[]>([])
const libraryCourses = ref<TrainingLibraryCourse[]>([])
const libraryLoading = ref(false)
const myDeptName = ref('')
// 本人所在部门 id:行级确认权限校验用(需求归属部门须与本人一致)
const myDeptId = ref('')
// 本部门课程(000156):课程名称下拉仅列所属部门课程——新建按提报人部门,
// 编辑按需求归属部门(人事代改他部门需求时同样联动);部门为空回退全部课程
const deptCourseOptions = computed(() => {
const deptId = demandForm.value.id
? demands.value.find((d) => d.id === demandForm.value.id)?.dept_id || myDeptId.value
: myDeptId.value
return deptId
? libraryCourses.value.filter((c) => c.owner_dept_id === deptId)
: libraryCourses.value
})
const demandFormVisible = ref(false)
const importDemandsVisible = ref(false)
const importDemandsText = ref('')
// 搜索条件:已确认按人工确认(status)过滤,待核验/已修正按规则校验状态(check_status)
const demandSearch = ref({ state: '', dept_id: '', keyword: '' })
const demandForm = ref({
id: '',
course_name: '',
// 分类随所选课程自动带出(000156),确认后经需求→课程同步落到课程侧标签
category: '',
// 计划培训月份(1~12,选填):提交时与收集年度合成 planned_time「YYYY-M」
planned_month: '' as '' | number,
session_count: 1,
train_type: '',
plant: '',
location: '',
post_scope: '',
// lecturer 表单值:讲师名册 id 或直接输入的外部讲师姓名,提交时解析
lecturer: '',
remark: '',
})
// 选定课程自动带出(000156):分类/适合人员/讲师随课程回填,均可再改;
// 改选讲师保存后由后端同步回写课程管理(课程管理讲师随需求追加为所选人员)
const onDemandCourseChange = (name: unknown) => {
const course = libraryCourses.value.find((c) => c.name === name)
if (!course) return
demandForm.value.category = course.category || ''
if (course.suitable_members) demandForm.value.post_scope = course.suitable_members
const lecturerValue = course.lecturer_id || course.lecturer_external || ''
if (lecturerValue) {
if (!lecturers.value.some((l) => l.id === lecturerValue)) {
lecturers.value = [...lecturers.value, { id: lecturerValue, name: course.lecturer_name || lecturerValue }]
}
demandForm.value.lecturer = lecturerValue
}
}
// 讲师解析:名册 id 直接用;名册姓名映射为对应 id;否则作为外部讲师姓名落 lecturer_external
const resolveLecturer = (value: string): { lecturer_id: string; lecturer_external: string } => {
const v = (value || '').trim()
if (!v) return { lecturer_id: '', lecturer_external: '' }
if (lecturers.value.some((l) => l.id === v)) return { lecturer_id: v, lecturer_external: '' }
const byName = lecturers.value.find((l) => l.name === v)
if (byName) return { lecturer_id: byName.id, lecturer_external: '' }
return { lecturer_id: '', lecturer_external: v }
}
const demandDialogTitle = computed(() => (demandForm.value.id ? '编辑培训需求' : '在线提报培训需求'))
// 编辑态展示年计划编号(服务端生成,不可改)
const demandCodeDisplay = computed(() => {
const row = demands.value.find((d) => d.id === demandForm.value.id)
return row?.code || '-'
})
const deptMap = computed(() => {
const m: Record<string, string> = {}
for (const d of depts.value) m[d.id] = d.name
return m
})
// 表单部门展示:编辑时回显该需求归属部门,新建时展示提报人所在部门
const deptDisplay = computed(() => {
if (demandForm.value.id) {
const row = demands.value.find((d) => d.id === demandForm.value.id)
if (row?.dept_name) return row.dept_name
}
return myDeptName.value
})
const demandColumns = [
{ colKey: 'row-select', type: 'multiple', width: 44, disabled: ({ row }: { row: TrainingDemand }) => row.status === 'confirmed' },
// 年计划编号(AP-<year>-####,创建时由服务端生成)
{ colKey: 'code', title: '编号', width: 130 },
{ colKey: 'course_name', title: '课程名称' },
{ colKey: 'dept_name', title: '部门', width: 100 },
{ colKey: 'post_scope', title: '适合人员', width: 140 },
{ colKey: 'lecturer_name', title: '讲师', width: 100 },
{ colKey: 'planned_time', title: '计划培训月份', width: 110 },
{ colKey: 'train_type', title: '内/外培训', width: 90 },
{ colKey: 'location', title: '地点', width: 100 },
{ colKey: 'remark', title: '备注', minWidth: 140 },
// 状态/操作固定在列表右侧,横向滚动时始终可见
{ colKey: 'check_status', title: '状态', width: 84, fixed: 'right' },
{ colKey: 'op', title: '操作', width: 160, fixed: 'right' },
]
// 批量确认/删除(仅作用于未确认需求,已确认行不可勾选)
const selectedDemandKeys = ref<string[]>([])
const batchSaving = ref(false)
const onBatchConfirm = async () => {
const rows = demands.value.filter((d) => selectedDemandKeys.value.includes(d.id) && d.status !== 'confirmed')
if (!rows.length) {
MessagePlugin.warning('请先勾选未确认的需求')
return
}
// 000154:批量确认仅作用于本人可确认的需求(本部门+经理),越权行全部跳过
const allowed = rows.filter(canConfirmDemand)
if (!allowed.length) {
MessagePlugin.warning('暂无权限,请联系部门经理~')
return
}
batchSaving.value = true
let ok = 0
let fail = 0
try {
for (const row of allowed) {
try {
await confirmDemand(row.id)
ok += 1
} catch {
fail += 1
}
}
const skipped = rows.length - allowed.length
MessagePlugin.success(
`批量确认完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''}` +
`${skipped ? `,跳过 ${skipped} 条非本部门需求` : ''};已确认需求已自动生成草稿课程到培训课程`,
)
selectedDemandKeys.value = []
loadAll()
} finally {
batchSaving.value = false
}
}
const onBatchDelete = async () => {
const rows = demands.value.filter((d) => selectedDemandKeys.value.includes(d.id) && d.status !== 'confirmed')
if (!rows.length) {
MessagePlugin.warning('请先勾选未确认的需求')
return
}
batchSaving.value = true
let ok = 0
let fail = 0
try {
for (const row of rows) {
try {
await deleteDemand(row.id)
ok += 1
} catch {
fail += 1
}
}
MessagePlugin.success(`批量删除完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''}`)
selectedDemandKeys.value = []
loadAll()
} finally {
batchSaving.value = false
}
}
// 组装需求列表查询:全部条件走后端过滤(年度/状态/部门/课程名称模糊)
const buildDemandQuery = () => {
const q: Record<string, unknown> = { year: selectedYear.value, page_size: 100 }
const s = demandSearch.value
if (s.state === 'confirmed') q.status = 'confirmed'
else if (s.state) q.check_status = s.state
if (s.dept_id) q.dept_id = s.dept_id
const kw = s.keyword.trim()
if (kw) q.keyword = kw
return q
}
const loadDemands = async () => {
const d = await listDemands(buildDemandQuery())
demands.value = unwrap(d)?.items || []
}
// 年份下拉数据源:需求库实际年份(降序)。resetSelection=true 时默认选中最新一年
// (首次进入);后续刷新仅在当前选中年份已无数据时回退最新,避免打断用户选择。
const loadDemandYears = async (resetSelection = false) => {
try {
const years = unwrap<number[]>(await listDemandYears()) || []
yearOptions.value = years
if (years.length && (resetSelection || !years.includes(selectedYear.value))) {
selectedYear.value = years[0]
}
} catch {
/* 年份拉取失败保留当前选择,列表按当前年份照常查询 */
}
}
const onResetDemandSearch = () => {
demandSearch.value = { state: '', dept_id: '', keyword: '' }
loadDemands()
}
// 表单下拉与提报人部门(一次性加载,失败不阻塞主列表)
const loadFormOptions = async () => {
libraryLoading.value = true
try {
const [d, l, me, lib] = await Promise.all([
listDepts(),
listLecturers(),
getMyProfile(),
listCourseLibrary({ page_size: 500 }).catch(() => null),
])
depts.value = unwrap(d) || []
lecturers.value = unwrap(l) || []
libraryCourses.value = (lib && unwrap(lib))?.items || []
const member = unwrap(me)
if (member?.dept_id) {
myDeptId.value = member.dept_id
myDeptName.value = deptMap.value[member.dept_id] || ''
}
} catch {
/* 忽略:仅影响下拉可选项 */
} finally {
libraryLoading.value = false
}
}
const loadAll = async (resetYearSelection = false) => {
loading.value = true
try {
await loadDemandYears(resetYearSelection)
await loadDemands()
} finally {
loading.value = false
}
}
const onOpenDemandForm = () => {
demandForm.value = {
id: '',
course_name: '',
category: '',
planned_month: '',
session_count: 1,
train_type: '',
plant: '',
location: '',
post_scope: '',
lecturer: '',
remark: '',
}
demandFormVisible.value = true
}
// 计划培训月份回显:从「YYYY-M」取月份;旧日期格式(YYYY-MM-DD)无法映射月份留空
const plannedMonthOfValue = (value: string): '' | number => {
const m = (value || '').trim().match(/^\d{4}-(\d{1,2})$/)
const month = m ? Number(m[1]) : 0
return month >= 1 && month <= 12 ? month : ''
}
// 编辑旧数据兜底:原计划培训时间为旧日期格式且未重新选择月份时,保存保留原值
const editOriginalPlanned = ref({ planned_time: '', expect_month: 0 })
const onEditDemand = (row: TrainingDemand) => {
// 讲师回显:系统员工(id)或外部姓名;不在名册的值追加临时选项避免显示裸 ID
const lecturerValue = row.lecturer_id || row.lecturer_external || ''
if (lecturerValue && !lecturers.value.some((l) => l.id === lecturerValue)) {
lecturers.value = [...lecturers.value, { id: lecturerValue, name: row.lecturer_name || lecturerValue }]
}
editOriginalPlanned.value = {
planned_time: row.planned_time || '',
expect_month: row.expect_month || 0,
}
demandForm.value = {
id: row.id,
course_name: row.course_name,
category: row.category || '',
planned_month: plannedMonthOfValue(row.planned_time || ''),
session_count: row.session_count || 1,
train_type: row.train_type || '',
plant: row.plant || '',
location: row.location || '',
post_scope: row.post_scope || '',
lecturer: lecturerValue,
remark: row.remark || '',
}
demandFormVisible.value = true
}
const onSaveDemand = async () => {
if (!demandForm.value.course_name) {
MessagePlugin.warning('请填写课程名称')
return
}
saving.value = true
try {
// 计划培训月份与收集年度合成「YYYY-M」入库,并回填期望月份;
// 编辑旧数据且未选月份时保留原计划培训值;讲师解析为 id 或外部姓名
const { lecturer, planned_month, ...rest } = demandForm.value
const month = Number(planned_month) || 0
const isEdit = Boolean(demandForm.value.id)
await saveDemand({
...rest,
...resolveLecturer(lecturer),
planned_time: month
? `${selectedYear.value}-${month}`
: (isEdit ? editOriginalPlanned.value.planned_time : ''),
expect_month: month || (isEdit ? editOriginalPlanned.value.expect_month : 0) || undefined,
year: selectedYear.value,
})
MessagePlugin.success(demandForm.value.id ? '需求已更新' : '需求已提交,待核验')
demandFormVisible.value = false
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '提交失败,请稍后重试'))
} finally {
saving.value = false
}
}
const onDeleteDemand = async (row: TrainingDemand) => {
try {
await deleteDemand(row.id)
MessagePlugin.success('需求已删除')
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '删除失败(已确认或无权限)'))
}
}
const onImportDemands = async () => {
const lines = importDemandsText.value.split('\n').map((l) => l.trim()).filter(Boolean)
if (!lines.length) {
MessagePlugin.warning('请粘贴需求行')
return
}
const items: Partial<TrainingDemand>[] = []
const skipped: string[] = []
lines.forEach((line, idx) => {
// 兼容中英文逗号(\uFF0C)与制表符拆分:课程名称[,计划培训月份]
const parts = line.split(/[,\uFF0C\t]/).map((s) => s.trim())
const courseName = parts[0] || ''
if (!courseName) {
skipped.push(String(idx + 1))
return
}
const { planned, month } = plannedMonthFromValue(parts[1] || '', selectedYear.value)
items.push({
course_name: courseName,
year: selectedYear.value,
planned_time: planned || undefined,
expect_month: month || undefined,
})
})
if (!items.length) {
MessagePlugin.warning('没有可导入的需求行,请用逗号分隔各字段(支持中英文逗号)')
return
}
saving.value = true
try {
await importDemands(items)
MessagePlugin.success(`已导入 ${items.length} 条需求`)
if (skipped.length) MessagePlugin.warning(`第 ${skipped.join('、')} 行缺少课程名称,已跳过`)
importDemandsVisible.value = false
importDemandsText.value = ''
loadAll()
} catch {
MessagePlugin.error('导入失败,请检查格式')
} finally {
saving.value = false
}
}
// ---- 教育训练需求表模板导入(docs/moban,经 /templates/ 下发) ----
// 模板表头:编号/部门/课程名称/适合人员/地点/培訓費用/内/外培训/计划培训月份(1~12)/讲师/备注,
// 讲师按员工档案姓名匹配(带出部门)、非系统员工落外部讲师姓名,计划培训月份按「收集年度-月份」入库。
const onDownloadDemandTemplate = () => downloadTrainingTemplate(DEMAND_TEMPLATE_KEY)
// 计划培训月份解析:兼容 1~12 纯月份数字(1、12月)与旧日期格式(2027-1、
// 2026/6/8、2026年6月8日等取其月份);年份统一取收集年度(模板标题年),
// 入库 planned_time=「YYYY-M」(如 2027-1);无法解析返回空。
const plannedMonthFromValue = (raw: string, fallbackYear: number): { planned: string; month: number } => {
const v = (raw || '').trim()
if (!v) return { planned: '', month: 0 }
const full = v.match(/^20\d{2}[-/.年]\s*(\d{1,2})/)
if (full) {
const month = Number(full[1])
if (month >= 1 && month <= 12) return { planned: `${fallbackYear}-${month}`, month }
}
const monthOnly = v.match(/^(\d{1,2})\s*月?$/)
if (monthOnly) {
const month = Number(monthOnly[1])
if (month >= 1 && month <= 12) return { planned: `${fallbackYear}-${month}`, month }
}
return { planned: '', month: 0 }
}
// 模板 Excel 列取值:新「计划培训月份」列优先,兼容旧「计划培训时间」列模板
const plannedMonthFromRow = (row: Record<string, string>, fallbackYear: number) =>
plannedMonthFromValue((row['计划培训月份'] || row['计划培训时间'] || '').trim(), fallbackYear)
const onImportDemandExcel = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
try {
const wb = XLSX.read(await file.arrayBuffer())
// 定位含「课程名称」表头的工作表(模板首两行为公司/表题合并单元格);
// 表头键做空白归一(兼容「地 点」等内含空格的列名,否则该列会被静默丢弃)
let dataRows: Record<string, string>[] | null = null
// 模板标题年(000157):标题行「2027 年度教育训练需求表」的年份优先于年份下拉——
// 模板面向下一年度收集,导入按标题年入库(需求年份与计划培训「年-月」一致)
let titleYear = selectedYear.value
for (const name of wb.SheetNames) {
const sheetRows = XLSX.utils.sheet_to_json<string[]>(wb.Sheets[name], { header: 1, raw: false, defval: '' })
const headerIdx = sheetRows.findIndex((r) => r.some((c) => String(c).trim() === '课程名称'))
if (headerIdx < 0) continue
for (const r of sheetRows.slice(0, Math.max(headerIdx, 1))) {
const hit = (r || []).map((c) => String(c)).find((s) => /20\d{2}/.test(s) && s.includes('年'))
const m = hit?.match(/20\d{2}/)
if (m) {
titleYear = Number(m[0])
break
}
}
const header = (sheetRows[headerIdx] || []).map((c) => String(c).trim().replace(/\s+/g, ''))
dataRows = sheetRows.slice(headerIdx + 1).map((arr) => {
const row: Record<string, string> = {}
header.forEach((h, i) => {
if (h) row[h] = String(arr[i] ?? '').trim()
})
return row
})
break
}
if (!dataRows) {
MessagePlugin.error('未找到「课程名称」表头,请使用下载的教育训练需求表模板填写')
return
}
const items: Partial<TrainingDemand>[] = []
let skippedRows = 0
let lecturerHits = 0
let externalLecturers = 0
let deptFromLecturer = 0
// 讲师按**全部在职员工**姓名匹配(不限于讲师名册;名单即 openCollect 的员工档案),
// 匹配不到的姓名作为外部讲师落 lecturer_external,列表讲师列照常显示
const ensureMembers = async () => {
if (members.value.length) return
membersLoading.value = true
try {
const res = await listMembers({ page_size: 500 })
members.value = unwrap(res)?.items || []
} catch {
/* 拉取失败时按空名册处理,讲师全部按外部姓名落库 */
} finally {
membersLoading.value = false
}
}
await ensureMembers()
dataRows.forEach((row) => {
const courseName = (row['课程名称'] || '').trim()
if (!courseName) {
skippedRows += 1
return
}
// 部门单位(收集模板)/主办单位(旧版)/部门(需求表模板)按部门名册匹配;未匹配留空
let deptId = ''
let deptMatched = false
const deptName = (row['部门单位'] || row['主办单位'] || row['部门'] || '').trim()
if (deptName) {
const hit = depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
if (hit) {
deptId = hit.id
deptMatched = true
}
}
// 讲师:员工档案姓名精确匹配→关联并在列表带出姓名,行内部门未匹配时带出讲师部门;
// 非系统员工→落外部讲师姓名,讲师列照常显示
let lecturerId = ''
let lecturerExternal = ''
const lecturerName = (row['培训讲师'] || row['讲师'] || '').trim()
if (lecturerName) {
const hit = members.value.find((m) => m.user_name === lecturerName)
if (hit && hit.user_id) {
lecturerId = hit.user_id
lecturerHits += 1
if (!deptMatched && hit.dept_id) {
deptId = hit.dept_id
deptFromLecturer += 1
}
} else {
lecturerExternal = lecturerName
externalLecturers += 1
}
}
// 计划培训月份:新「计划培训月份」列(1~12)优先,兼容旧「计划培训时间」列;
// 年份取模板标题年(000157),入库「YYYY-M」并回填期望月份
const plannedMonth = plannedMonthFromRow(row, titleYear)
items.push({
course_name: courseName,
year: titleYear,
plant: (row['厂区'] || '').trim(),
session_count: Number.parseInt(row['次数'] || '') || 1,
location: (row['地点'] || '').trim(),
post_scope: (row['适合人员'] || row['参加人员'] || '').trim(),
train_type: (row['内/外培训'] || row['內/外培訓'] || '').trim(),
lecturer_id: lecturerId,
lecturer_external: lecturerExternal || undefined,
dept_id: deptId,
planned_time: plannedMonth.planned || undefined,
expect_month: plannedMonth.month || undefined,
remark: (row['备注'] || '').trim(),
})
})
if (!items.length) {
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
return
}
saving.value = true
try {
const imported = unwrap(await importDemands(items)) as { imported: number; notified?: number } | null
MessagePlugin.success(
`已从模板导入 ${items.length} 条需求(${titleYear}年度)` +
(lecturerHits || externalLecturers
? `,讲师匹配 ${lecturerHits} 人${externalLecturers ? `,外部讲师 ${externalLecturers} 人` : ''}`
: '') +
(deptFromLecturer ? `(其中 ${deptFromLecturer} 条部门按讲师带出)` : '') +
(skippedRows ? `,另有 ${skippedRows} 行未填课程名称已跳过` : '') +
(imported?.notified ? `,已推送 ${imported.notified} 位部门经理核验` : ''),
)
importDemandsVisible.value = false
// 导入年份与当前查看年份不同(模板为下一年度)时切到导入年份展示
if (titleYear !== selectedYear.value) selectedYear.value = titleYear
loadAll()
} catch {
MessagePlugin.error('导入失败,请稍后重试')
} finally {
saving.value = false
}
} catch {
MessagePlugin.error('Excel 解析失败,请使用下载的模板填写后上传')
}
}
const onConfirmDemand = async (row: TrainingDemand) => {
// 000154:仅需求归属部门的经理可确认,其余人员点击统一提示
if (!canConfirmDemand(row)) {
MessagePlugin.warning('暂无权限,请联系部门经理~')
return
}
try {
await confirmDemand(row.id)
MessagePlugin.success('已确认,草稿课程已自动生成到培训课程')
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '操作失败'))
}
}
// ---- 收集下年度计划:发送模板 + 推送人员 + 站内/企微通知批量推送 ----
const nextYear = currentYear + 1
const collectVisible = ref(false)
const collectSending = ref(false)
const members = ref<TrainingMember[]>([])
const membersLoading = ref(false)
const collectForm = ref({ userIds: [] as string[], content: '' })
// 推送人员下拉展示:姓名/工号 · 岗位 · 部门
const memberLabel = (m: TrainingMember) =>
[m.user_name || m.employee_no, m.post, m.dept_name].filter(Boolean).join(' · ') || m.id.slice(0, 8)
// 默认推送人员:各课长(supervisor;存量文员 clerk 经别名按课长对待)
const DEFAULT_COLLECT_ROLES = ['supervisor']
const defaultCollectUserIds = () =>
members.value
.filter((m) =>
(m.roles || []).some((r) => DEFAULT_COLLECT_ROLES.includes(r === 'clerk' ? 'supervisor' : r)),
)
.map((m) => m.user_id)
const openCollect = async () => {
collectForm.value.content =
`请各部门于 ${nextYear} 年 1 月 31 日前,登录 AIDO → 企业培训 → 培训计划 → 年度需求收集,` +
`提报 ${nextYear} 年度培训需求:可在线逐条提报,或下载「教育训练需求表模板」批量填写后导入。`
collectVisible.value = true
// 名册只拉一次;每次打开按默认角色重置推送人员(支持在此基础上增删)
if (!members.value.length) {
membersLoading.value = true
try {
const res = await listMembers({ page_size: 500 })
members.value = unwrap(res)?.items || []
} catch {
/* 拉取失败时保留空态,可手动搜索添加 */
} finally {
membersLoading.value = false
}
}
collectForm.value.userIds = defaultCollectUserIds()
}
const onSendCollect = async () => {
if (!collectForm.value.userIds.length) {
MessagePlugin.warning('请至少选择一位推送人员')
return
}
collectSending.value = true
try {
const res = await broadcastTrainingNotification({
user_ids: collectForm.value.userIds,
scene: 'demand_collect',
title: `【培训需求收集】${nextYear}年度培训计划收集`,
content: collectForm.value.content,
ref_type: 'plan',
ref_id: String(nextYear),
})
MessagePlugin.success(`已推送通知 ${unwrap(res)?.sent ?? 0} 人(站内 + 企业微信;未绑定企微的同事仅站内送达,可在配置中心查看推送记录)`)
collectVisible.value = false
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '推送失败,请稍后重试'))
} finally {
collectSending.value = false
}
}
onMounted(() => {
// 首次进入:年份默认选中需求库最新一年并展示该年数据
loadAll(true)
loadFormOptions()
})
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.panel-box {
.training-panel-box();
&+.panel-box {
margin-top: 12px;
}
}
// 已确认行不做整行置灰:t-table 行选择列 disabled 命中时会加 __row--disabled
// 类(整行 text-color-disabled),业务上已确认行仅禁止勾选,文字保持正常色
:deep(.t-table__row--disabled) {
color: var(--td-text-color-primary);
}
// 标题行内嵌年度切换下拉
.plan-title-row {
display: inline-flex;
align-items: center;
gap: 10px;
}
.year-select {
width: 108px;
}
.demand-search {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.demand-selected-hint {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 批量导入弹窗:模板下载 + Excel 上传一行排布
.import-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 10px;
}
.import-file {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 收集下年度计划弹窗:分区标题与模板行
.collect-section-title {
margin: 10px 0 8px;
font-weight: 600;
font-size: var(--app-text-md);
}
.collect-template-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border: 1px dashed var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
}
.collect-template-name {
flex: 1;
min-width: 0;
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
// 适合人员/备注等长文本单元格:单行省略,t-tooltip 悬停显示全部
.cell-ellipsis {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>