Files
ai_academy/frontend/src/views/training/components/CoursePanel.vue
T
runny ce24d4b9cb
deploy-hxtesting / build-and-deploy (push) Successful in 1m8s
月培训计划增加批量删除、批量发布功能
2026-11-27 01:52:44 +08:00

2374 lines
100 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="course-panel">
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">月度培训计划</span>
<div class="panel-box__actions">
<!-- 000163:线上线下经弹窗内「形式」切换,只保留一个创建入口 -->
<t-button theme="primary" @click="openCreate('offline')">创建月度计划</t-button>
</div>
</div>
<!-- 查询条件:名称/讲师/培训月份/状态。计划列表全量加载(page_size=100),
企业内部数据量小,过滤在前端本地完成,不新增后端查询参数。
000163:默认只看当月(计划培训/授课时间任一命中),月份可多选,清空=全部数据。 -->
<div class="course-filters">
<t-input v-model="filters.keyword" placeholder="按计划名称查询" clearable style="width: 200px" />
<t-select v-if="!isLecturerOnly" v-model="filters.lecturerId" placeholder="按讲师查询" clearable style="width: 150px">
<t-option v-for="l in lecturers" :key="l.id" :value="l.id" :label="l.name" />
</t-select>
<t-select
v-model="filters.months"
multiple
clearable
filterable
collapse-tags
:min-collapsed-num="2"
placeholder="按培训月份筛选(可多选,清空为全部)"
style="width: 280px"
>
<t-option v-for="m in monthOptions" :key="m" :value="m" :label="monthLabel(m)" />
</t-select>
<t-select v-model="filters.status" placeholder="按状态查询" clearable style="width: 130px">
<t-option v-for="opt in STATUS_OPTIONS" :key="opt.value" :value="opt.value" :label="opt.label" />
</t-select>
<t-button variant="text" theme="primary" size="small" @click="resetFilters">重置</t-button>
<span class="course-filter-count">共 {{ filteredCourses.length }} 门</span>
<!-- 批量发布/批量删除(000165 复测):仅维护角色可见;已发布行不可勾选(删除仅超管),
勾选禁用口径见 courseSelectionDisabledKeys -->
<t-button
v-if="canManage" theme="primary" variant="outline" size="small"
:disabled="!selectedCourseKeys.length" :loading="batchSaving" @click="onBatchPublish"
>批量发布</t-button>
<t-button
v-if="canManage || isSuperAdmin" theme="danger" variant="outline" size="small"
:disabled="!selectedCourseKeys.length" :loading="batchSaving" @click="onBatchDelete"
>批量删除</t-button>
<span v-if="selectedCourseKeys.length" class="course-filter-count">已选 {{ selectedCourseKeys.length }} 项</span>
</div>
<!-- 表格滚动区:面板满屏,筛选/表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<div class="table-scroll">
<t-table
v-model:selected-row-keys="selectedCourseKeys"
:data="pagedCourses" :columns="courseColumns" row-key="id" size="small" height="100%"
:loading="loading" :disabled-row-keys="courseSelectionDisabledKeys"
>
<template #plan_code="{ row }">{{ row.plan_code || '-' }}</template>
<template #name="{ row }">
<span class="course-name-link clamp-2" title="点击前往培训签到" @click="goSignTab(row)">{{ row.name }}</span>
<!-- 课程已下线(000163):关联课程管理条目 offline 时标注(计划行保留,
学习入口提示「该课程已下线」) -->
<t-tag v-if="row.library_offline" theme="danger" variant="outline" size="small" class="offline-flag">课程已下线</t-tag>
</template>
<template #mode="{ row }">
<t-tag :theme="row.mode === 'online' ? 'primary' : 'default'" variant="light" size="small" :class="{ 'course-tag-offline': row.mode !== 'online' }">
{{ row.mode === 'online' ? '线上' : '线下' }}
</t-tag>
</template>
<template #type="{ row }">{{ typeText(row.type) }}</template>
<template #reporter="{ row }"><span class="clamp-2">{{ row.reporter_dept_name || '-' }}</span></template>
<template #teachTime="{ row }"><span class="clamp-2">{{ teachTimeText(row) }}</span></template>
<template #plannedTime="{ row }"><span class="clamp-2">{{ row.planned_time || '-' }}</span></template>
<template #lecturer="{ row }">{{ lectNameMap[row.lecturer_id] || row.lecturer_name || row.lecturer_external || '-' }}</template>
<template #location="{ row }"><span class="clamp-2">{{ courseLocation(row) || '-' }}</span></template>
<template #expected="{ row }">{{ row.actual_count ?? 0 }}/{{ row.expected_count ?? 0 }} 人</template>
<template #learnStatus="{ row }">
<t-tag
:theme="learnStatusTheme(row.learning_status)"
variant="light" size="small" class="status-link"
@click="goStudyStatus(row, 'learning')"
>{{ learnStatusText(row.learning_status) }}</t-tag>
</template>
<template #examStatus="{ row }">
<t-tag
:theme="examStatusTheme(row.exam_status)"
variant="light" size="small" class="status-link"
@click="goStudyStatus(row, 'exam')"
>{{ examStatusText(row.exam_status) }}</t-tag>
</template>
<template #status="{ row }">
<t-tag :theme="statusTheme(row.status)" variant="light" size="small">{{ statusText(row.status) }}</t-tag>
</template>
<template #op="{ row }">
<t-button
v-if="canManage && row.status !== 'published'"
variant="text" theme="primary" size="small" :disabled="saving"
@click="onPublish(row)"
>发布</t-button>
<t-button variant="text" size="small" @click="openDetail(row)">调整</t-button>
<t-button variant="text" size="small" @click="openChangeLogs(row)">记录</t-button>
<!-- 已发布计划仅超级管理员职称角色可删(后端 DeleteCourse 同口径兜底);
普通维护角色仅可删未发布计划 -->
<t-popconfirm
v-if="isSuperAdmin || (canManage && row.status !== 'published')"
content="确定删除该培训计划?" theme="danger" @confirm="onDelete(row)"
>
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
</template>
</t-table>
</div>
<!-- 共用分页(000163):默认每页 15 条 -->
<TrainingPagination v-model:current="coursePage" v-model:page-size="coursePageSize" :total="courseTotal" />
</div>
<!-- 创建计划:课程名称从课程管理选择(带出并锁定课程信息),仅维护授课安排六字段 -->
<t-dialog v-model:visible="formVisible" header="创建月度计划" width="720">
<t-form label-width="100">
<t-form-item label="计划编号">
<t-input value="保存后自动生成" disabled />
</t-form-item>
<t-form-item label="课程名称" required>
<!-- 关联课程管理:从课程管理选择课程,带出类型/形式/讲师/所属部门并锁定(新课程请先在「课程管理」维护) -->
<t-select
v-model="form.library_course_id"
clearable
filterable
placeholder="从课程管理选择课程"
style="width: 100%"
@change="onLibraryCourseChange"
>
<t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" />
</t-select>
<div class="bank-hint">选择后带出课程信息且不可修改,仅可调整下方授课安排;还没有课程?<a class="template-link" href="javascript:void(0)" @click.prevent="goLibrary">前往「课程管理」新增</a></div>
</t-form-item>
<t-form-item label="形式">
<!-- 计划「形式」独立字段(000162):指本次培训线上办还是线下办,与课程
主数据的线上课/线下课口径不同,不随所选课程带出,可在此切换 -->
<t-radio-group v-model="form.mode" variant="default-filled" size="small">
<t-radio-button value="offline">线下(集中授课)</t-radio-button>
<t-radio-button value="online">线上(自主学习)</t-radio-button>
</t-radio-group>
</t-form-item>
<t-form-item label="类型">
<t-input :value="formTypeDisplay" disabled />
</t-form-item>
<t-form-item label="讲师">
<t-input :value="lecturerDisplay(form.lecturer_id)" disabled placeholder="随课程带出,在「课程管理」中维护" />
</t-form-item>
<t-form-item label="所属部门">
<t-input :value="deptNamesOf(form.dept_ids)" disabled placeholder="随课程带出" />
</t-form-item>
<!-- 课程资产侧信息随所选课程带出(000156);000163 起课件/试题可在创建时
上传/更换(回写课程管理主数据并作为本次培训课件/试题,000165 复测起
课件/试题变更不再回「待审核」,课程保持已审核可直接发布) -->
<t-form-item label="适合人员">
<t-input :value="formLibraryCourse?.suitable_members || '-'" disabled placeholder="随所选课程带出" />
</t-form-item>
<t-form-item label="课件">
<div class="asset-row">
<!-- 000165 复测:file_name 恒镜像最新一条课件,上传/更换后名称跟随变更 -->
<t-input
:value="formLibraryCourse?.file_name || formLibraryCourse?.material_name || '-'"
disabled
placeholder="随所选课程带出,可上传/更换"
class="asset-value"
/>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="formMaterialInput?.click()"
>上传课件</t-button>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="openFormKbCourseware"
>知识库</t-button>
<input ref="formMaterialInput" type="file" class="hidden-file-input" @change="onFormChangeMaterial" />
</div>
<div v-if="formKbCoursewareVisible" class="asset-relink">
<t-select
v-model="formKbCoursewareDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(课件)」知识库文档作为课件"
style="flex: 1"
>
<t-option v-for="doc in kbCoursewareDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formKbCoursewareDocId" @click="onFormAttachKbCourseware">确定</t-button>
</div>
<div class="bank-hint">课件上传/更换后自动回写课程管理并作为本次培训课件,无需重新审核,保存后可直接发布计划</div>
</t-form-item>
<t-form-item label="试题">
<div class="asset-row">
<t-input
:value="formCourseBanksText"
disabled
placeholder="随所选课程带出,可更换"
class="asset-value"
/>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="formRelinkVisible = !formRelinkVisible"
>更换试题</t-button>
<t-button
variant="outline" size="small" :disabled="!form.library_course_id"
:loading="formAssetSaving" @click="openFormKbBank"
>知识库</t-button>
</div>
<div v-if="formRelinkVisible" class="asset-relink">
<t-select
v-model="formRelinkBankId"
filterable
clearable
placeholder="选择题库替换该课程当前试题"
style="flex: 1"
>
<t-option
v-for="b in allBanks"
:key="b.id"
:value="b.id"
:label="`${b.name}(${b.question_count}题)`"
/>
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formRelinkBankId" @click="onFormRelinkBank">确认更换</t-button>
</div>
<div v-if="formKbBankVisible" class="asset-relink">
<t-select
v-model="formKbBankDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(题库)」知识库文档解析建题库"
style="flex: 1"
>
<t-option v-for="doc in kbBankDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="formAssetSaving" :disabled="!formKbBankDocId" @click="onFormImportKbBank">确定</t-button>
</div>
</t-form-item>
<t-form-item label="学时 / 学分">
<t-input-number v-model="form.hours" :min="0" :step="0.5" :disabled="!form.library_course_id" style="width: 48%" />
<t-input-number v-model="form.credits" :min="0" :step="0.5" :disabled="!form.library_course_id" style="width: 48%; margin-left: 4%" />
</t-form-item>
<t-form-item v-if="form.mode === 'offline'" label="授课时间">
<!-- format 同时决定输入显示与时间面板列数(只出时:分,不出秒) -->
<t-date-picker v-model="form.start_at" enable-time-picker format="YYYY-MM-DD HH:mm" style="width: 100%" />
</t-form-item>
<t-form-item v-if="form.mode === 'offline'" label="授课地点">
<t-input v-model="form.location" placeholder="如:3号厂房 · 二楼培训室" />
</t-form-item>
<t-form-item v-if="form.mode === 'offline'" label="学员通知">
<t-select v-model="form.notify_mode" style="width: 100%">
<t-option value="immediate" label="名单/课件就绪后立即推送" />
<t-option value="day_before" label="开课前 1 天推送" />
</t-select>
<div class="bank-hint">推送内容:上课时间、地点与讲师;课件未上传时不会推送,上传后自动补推。</div>
</t-form-item>
<t-form-item v-if="form.mode === 'online'" label="学习期限">
<t-select v-model="form.deadlineDays" style="width: 100%">
<t-option :value="7" label="发布后 7 天内完成" />
<t-option :value="14" label="发布后 14 天内完成" />
<t-option :value="30" label="发布后 30 天内完成" />
</t-select>
</t-form-item>
<!-- 参加人员:按人员/部门/岗位三种方式选择,保存写入场次学员名单并同步 post_scope -->
<t-form-item label="参加人员">
<div style="width: 100%">
<t-radio-group v-model="formParticipantMode" variant="default-filled" size="small" class="participant-mode">
<t-radio-button value="member">按人员</t-radio-button>
<t-radio-button value="dept">按部门</t-radio-button>
<t-radio-button value="post">按岗位</t-radio-button>
</t-radio-group>
<t-select
v-if="formParticipantMode === 'member'"
v-model="formParticipantIds"
multiple
filterable
clearable
placeholder="从员工名册选择参加人员"
style="width: 100%"
>
<t-option v-for="m in members" :key="m.id" :value="m.id" :label="m.user_name || m.employee_no" />
</t-select>
<t-select
v-else-if="formParticipantMode === 'dept'"
v-model="formParticipantDeptIds"
multiple
clearable
placeholder="选择部门,自动带入部门全部员工"
style="width: 100%"
>
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
<t-select
v-else
v-model="formParticipantPostIds"
multiple
filterable
clearable
placeholder="选择岗位,自动带入该岗位全部员工"
style="width: 100%"
>
<t-option v-for="p in postOptions" :key="p" :value="p" :label="p" />
</t-select>
<div class="form-hint">
已选 {{ resolvedFormMembers.length }} 名员工<template v-if="resolvedFormMembers.length">:{{ resolvedFormMembers.map((m) => m.user_name || m.employee_no).join('、') }}</template>;推送与应培人员以本名单为准
</div>
</div>
</t-form-item>
</t-form>
<div class="form-hint">发布后将自动生成计划与学员名单(线下计划含签到码),并推送讲师与学员通知;课程信息随所选课程带出,课件/试题可在本弹窗上传/更换(自动同步课程管理并作为本次培训课件/试题,无需重新审核,保存后可直接发布)。</div>
<template #footer>
<t-button variant="outline" :loading="saving" @click="onSaveDraft">暂存草稿</t-button>
<t-button theme="primary" :loading="saving" @click="onSave">保存并发布</t-button>
</template>
</t-dialog>
<!-- 计划调整:计划编号展示 + 课程名称/讲师(000161 可调整,讲师改动回写课程管理并重置待审核) + 六项授课安排维护 -->
<t-dialog v-model:visible="sessionsVisible" :header="`计划调整 · ${activeCourse?.name || ''}`" width="760" :footer="false">
<t-form label-width="90" class="detail-form">
<t-form-item label="计划编号">
<t-input :value="activeCourse?.plan_code || '-'" disabled />
</t-form-item>
<t-form-item label="课程名称">
<!-- 000161 可切换关联课程:改选即换 library_course_id,名称/类型随新课程带出
(形式为计划侧独立字段,000162 起不随课程联动);讲师改动保存后回写
课程管理并重置待审核,发布前须重新审核 -->
<t-select
v-model="editForm.library_course_id"
:disabled="!canManage"
clearable
filterable
placeholder="从课程管理选择课程(带出课程信息)"
style="width: 100%"
@change="onDetailLibraryCourseChange"
>
<t-option v-for="c in libraryCourses" :key="c.id" :value="c.id" :label="`${c.name}${c.category ? `(${c.category})` : ''}`" />
</t-select>
</t-form-item>
<t-form-item label="形式">
<!-- 计划「形式」独立字段(000162):可改线下/线上,不随所选课程带出 -->
<t-radio-group v-model="editForm.mode" variant="default-filled" size="small" :disabled="!canManage">
<t-radio-button value="offline">线下(集中授课)</t-radio-button>
<t-radio-button value="online">线上(自主学习)</t-radio-button>
</t-radio-group>
</t-form-item>
<t-form-item label="类型">
<t-input :value="formTypeDisplay" disabled />
</t-form-item>
<t-form-item label="讲师">
<!-- 000161 计划侧可改讲师:名册选择或直接输入外部讲师姓名 -->
<t-select
v-model="editForm.lecturer_id"
:disabled="!canManage"
clearable
filterable
creatable
placeholder="从讲师名册选择或直接输入外部讲师姓名"
style="width: 100%"
>
<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="所属部门">
<t-input :value="deptNamesOf(editForm.dept_ids)" disabled placeholder="随课程带出" />
</t-form-item>
<t-form-item label="学时 / 学分">
<t-input-number v-model="editForm.hours" :min="0" :step="0.5" :disabled="!canManage" style="width: 48%" />
<t-input-number v-model="editForm.credits" :min="0" :step="0.5" :disabled="!canManage" style="width: 48%; margin-left: 4%" />
</t-form-item>
<template v-if="editForm.mode === 'offline'">
<t-form-item label="授课时间">
<t-date-picker v-model="editForm.start_at" enable-time-picker format="YYYY-MM-DD HH:mm" :disabled="!canManage" style="width: 100%" />
</t-form-item>
<t-form-item label="授课地点">
<t-input v-model="editForm.location" :disabled="!canManage" placeholder="如:3号厂房 · 二楼培训室" />
</t-form-item>
<t-form-item label="学员通知">
<t-select v-model="editForm.notify_mode" :disabled="!canManage" style="width: 100%">
<t-option value="immediate" label="名单/课件就绪后立即推送" />
<t-option value="day_before" label="开课前 1 天推送" />
</t-select>
</t-form-item>
</template>
<t-form-item v-else label="授课时间">
<t-input value="长期(线上计划随时可学)" disabled />
</t-form-item>
<!-- 参加人员与场次学员名单合一:按人员/部门/岗位三种方式选择,保存后写入场次学员名单(计入应到人数) -->
<t-form-item label="参加人员">
<div style="width: 100%">
<t-radio-group v-model="participantMode" variant="default-filled" size="small" class="participant-mode">
<t-radio-button value="member">按人员</t-radio-button>
<t-radio-button value="dept">按部门</t-radio-button>
<t-radio-button value="post">按岗位</t-radio-button>
</t-radio-group>
<t-select
v-if="participantMode === 'member'"
v-model="demandSync.participantIds"
multiple
filterable
clearable
:disabled="!canManage"
placeholder="从员工名册选择参加人员"
style="width: 100%"
>
<t-option v-for="m in members" :key="m.id" :value="m.id" :label="m.user_name || m.employee_no" />
</t-select>
<t-select
v-else-if="participantMode === 'dept'"
v-model="participantDeptIds"
multiple
clearable
:disabled="!canManage"
placeholder="选择部门,自动带入部门全部员工"
style="width: 100%"
>
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
<t-select
v-else
v-model="participantPostIds"
multiple
filterable
clearable
:disabled="!canManage"
placeholder="选择岗位,自动带入该岗位全部员工"
style="width: 100%"
>
<t-option v-for="p in postOptions" :key="p" :value="p" :label="p" />
</t-select>
<div class="form-hint">
已选 {{ resolvedParticipantMembers.length }} 名员工<template v-if="resolvedParticipantMembers.length">:{{ resolvedParticipantMembers.map((m) => m.user_name || m.employee_no).join('、') }}</template>;推送与应培人员以本名单为准
</div>
</div>
</t-form-item>
<!-- 其余同步字段:有值才回显,只读展示 -->
<t-form-item v-if="activeCourse?.lecturer_external" label="外部讲师">
<t-input :value="activeCourse.lecturer_external" disabled placeholder="来自需求确认同步" />
</t-form-item>
<t-form-item v-if="activeCourse?.train_type" label="内/外培训">
<t-input :value="activeCourse.train_type" disabled placeholder="来自需求确认同步" />
</t-form-item>
<t-form-item v-if="activeCourse?.plant" label="厂区">
<t-input :value="activeCourse.plant" disabled placeholder="来自需求确认同步" />
</t-form-item>
<!-- 课程资产侧信息(000156):随所选课程带出;课件/试题支持更换,更换后回写课程管理对应课程 -->
<t-form-item label="适合人员">
<t-input :value="activeLibraryCourse?.suitable_members || '-'" disabled placeholder="随所选课程带出(课程管理维护)" />
</t-form-item>
<t-form-item label="课件">
<div class="asset-row">
<!-- 000165 复测:file_name 恒镜像最新一条课件,上传/更换后名称跟随变更;
material_name 为旧「名称登记」仅兜底 -->
<t-input
:value="activeLibraryCourse?.file_name || activeLibraryCourse?.material_name || '-'"
disabled
placeholder="随所选课程带出(课程管理维护)"
class="asset-value"
/>
<t-button
v-if="canManage"
variant="outline" size="small" :loading="assetSaving"
@click="materialInput?.click()"
>上传课件</t-button>
<t-button
v-if="canManage"
variant="outline" size="small" :disabled="assetSaving"
@click="openKbCourseware"
>知识库</t-button>
<input
ref="materialInput"
type="file"
class="hidden-file-input"
@change="onChangeMaterial"
/>
</div>
<div v-if="kbCoursewareVisible" class="asset-relink">
<t-select
v-model="kbCoursewareDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(课件)」知识库文档作为课件"
style="flex: 1"
>
<t-option v-for="doc in kbCoursewareDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="assetSaving" :disabled="!kbCoursewareDocId" @click="onAttachKbCourseware">确定</t-button>
</div>
</t-form-item>
<t-form-item label="试题">
<div class="asset-row">
<t-input
:value="courseBanksText"
disabled
placeholder="随所选课程带出(课程管理维护)"
class="asset-value"
/>
<t-button
v-if="canManage"
variant="outline" size="small" :disabled="assetSaving"
@click="relinkVisible = !relinkVisible"
>更换试题</t-button>
<t-button
v-if="canManage"
variant="outline" size="small" :disabled="assetSaving"
@click="openKbBank"
>知识库</t-button>
</div>
<div v-if="relinkVisible" class="asset-relink">
<t-select
v-model="relinkBankId"
filterable
clearable
placeholder="选择题库替换该课程当前试题"
style="flex: 1"
>
<t-option
v-for="b in allBanks"
:key="b.id"
:value="b.id"
:label="`${b.name}(${b.question_count}题)`"
/>
</t-select>
<t-button theme="primary" size="small" :loading="assetSaving" :disabled="!relinkBankId" @click="onRelinkBank">确认更换</t-button>
</div>
<div v-if="kbBankVisible" class="asset-relink">
<t-select
v-model="kbBankDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(题库)」知识库文档解析建题库"
style="flex: 1"
>
<t-option v-for="doc in kbBankDocs" :key="doc.id" :value="doc.id" :label="doc.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="assetSaving" :disabled="!kbBankDocId" @click="onImportKbBank">确定</t-button>
</div>
</t-form-item>
<t-form-item v-if="activeCourse?.remark" label="备注">
<t-textarea :value="activeCourse.remark" disabled placeholder="来自需求确认同步" :autosize="{ minRows: 1 }" />
</t-form-item>
</t-form>
<!-- 保存计划信息:统一提交授课安排六字段(课件与试题在「课程管理」维护) -->
<div v-if="canManage" class="detail-save-bar">
<t-button theme="primary" :loading="detailSaving" @click="onSaveDetail">保存计划信息</t-button>
<span class="form-hint detail-save-hint">提交授课时间/地点/通知方式/参加人员/学时/学分;每次保存自动记录修改版本(列表「记录」查看),授课时间修改将同步最近一场排期,参加人员保存后同步为场次学员名单;课件与试题可在此「更换」,更换后自动同步课程管理</span>
</div>
</t-dialog>
<!-- 计划修改记录:每次保存的版本与字段级变更明细 -->
<t-dialog v-model:visible="changeLogsVisible" :header="`计划修改记录 · ${changeLogCourse?.name || ''}`" width="640" :footer="false">
<t-table :data="pagedChangeLogs" :columns="changeLogColumns" row-key="id" size="small" :loading="changeLogsLoading">
<template #changes="{ row }">
<div v-for="(c, idx) in row.changes || []" :key="idx" class="change-line">
{{ c.label }}:{{ c.old || '—' }} → {{ c.new || '—' }}
</div>
</template>
<template #operator="{ row }">{{ operatorName(row.operator_id) }}</template>
<template #created_at="{ row }">{{ fmtTime(row.created_at) }}</template>
</t-table>
<TrainingPagination v-model:current="changeLogPage" v-model:page-size="changeLogPageSize" :total="changeLogTotal" />
<t-empty v-if="!changeLogsLoading && !changeLogs.length" description="暂无修改记录;计划信息每次保存后自动留痕" />
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import {
attachCourseLibraryMaterialFromKb,
deleteCourse,
getTrainingKnowledgeBases,
importQuestionBankFromKnowledge,
linkLibraryCourseQuestionBank,
listCourseChangeLogs,
listCourseLibrary,
listCourses,
listDepts,
listLecturers,
listLibraryCourseQuestionBanks,
listMaterials,
listMembers,
listQuestionBanks,
listSessions,
publishCourse,
saveCourse,
saveCourseLibraryItem,
saveSession,
setEnrollments,
uploadCourseLibraryMaterial,
type TrainingCourse,
type TrainingCourseChangeLog,
type TrainingCourseSession,
type TrainingDept,
type TrainingKnowledgeBases,
type TrainingLibraryCourse,
type TrainingLecturerOption,
type TrainingMember,
type TrainingQuestionBank,
unwrap,
} from '@/api/training'
import { fmtBeijingTime } from '@/utils/datetime'
import { apiErrorMessage, get } from '@/utils/request'
import TrainingPagination from './TrainingPagination.vue'
import { plannedMonthSortKey, useTrainingPager } from './useTrainingPager'
const props = defineProps<{ roles: string[]; admin?: boolean }>()
// 课程维护:人事/课长/讲师(roles 已按权限组展开,经理经课长继承自动命中);
// 纯讲师的课程列表范围由后端按 lecturer_id 强制收窄。
const canManage = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor' || r === 'lecturer'))
// 超级管理员职称角色(super_admin):已发布计划的终态删除权唯一入口
// (roles 已按权限组展开,自定义角色继承「超级管理员」权限组后同样命中)
const isSuperAdmin = computed(() => props.roles.includes('super_admin'))
// 纯讲师视角隐藏「按讲师查询」筛选(列表已固定为自己的课程)
const isLecturerOnly = computed(() => !canManage.value || (props.roles.includes('lecturer') && !props.roles.some((r) => r === 'hr' || r === 'supervisor' || r === 'exec')))
const router = useRouter()
// 学习/考试状态列点击 → 学习考试页对应页签(课程学习情况/课程考试情况)并预选该课程
const goStudyStatus = (row: TrainingCourse, section: 'learning' | 'exam') => {
router.push({ path: '/platform/training/study', query: { section, courseId: row.id } })
}
// 课程名称点击 → 培训签到页,携带 courseId 自动选中该课程的场次
const goSignTab = (row: TrainingCourse) => {
router.push({ path: '/platform/training/sign', query: { courseId: row.id } })
}
const loading = ref(false)
const saving = ref(false)
const courses = ref<TrainingCourse[]>([])
const depts = ref<TrainingDept[]>([])
const members = ref<TrainingMember[]>([])
const sessions = ref<TrainingCourseSession[]>([])
const lecturers = ref<TrainingLecturerOption[]>([])
// 课程管理条目(课程资产主数据):创建/编辑计划的「课程名称」下拉数据源
const libraryCourses = ref<TrainingLibraryCourse[]>([])
// 题库总表(课程资产侧试题,000156):随课程条目挂接,详情/创建弹窗按条目过滤展示
const allBanks = ref<TrainingQuestionBank[]>([])
// 随 library_course_id 关联的课程资产(000156):适合人员/课件/试题,
// 月计划详情仅展示;课件/试题支持更换,更换后回写课程管理对应课程
const assetSaving = ref(false)
const courseBanks = ref<TrainingQuestionBank[]>([])
const banksLoading = ref(false)
const relinkVisible = ref(false)
const relinkBankId = ref('')
const materialInput = ref<HTMLInputElement | null>(null)
const libraryCourseOf = (libraryCourseId?: string) =>
libraryCourseId ? libraryCourses.value.find((c) => c.id === libraryCourseId) : undefined
// 详情弹窗当前课程 / 创建弹窗所选课程的资产条目
const activeLibraryCourse = computed(() => libraryCourseOf(editForm.value.library_course_id))
const formLibraryCourse = computed(() => libraryCourseOf(form.value.library_course_id))
const banksTextOf = (libraryCourseId?: string) => {
const list = allBanks.value.filter((b) => b.library_course_id && b.library_course_id === libraryCourseId)
return list.length ? list.map((b) => `${b.name}(${b.question_count}题)`).join('、') : '-'
}
const courseBanksText = computed(() =>
courseBanks.value.length
? courseBanks.value.map((b) => `${b.name}(${b.question_count}题)`).join('、')
: '-',
)
const formCourseBanksText = computed(() => banksTextOf(form.value.library_course_id))
// 拉取课程条目当前挂接的题库(详情弹窗打开/换选课程时)
const loadCourseBanks = async (libraryCourseId?: string) => {
courseBanks.value = []
relinkBankId.value = ''
relinkVisible.value = false
if (!libraryCourseId) return
banksLoading.value = true
try {
courseBanks.value = (unwrap(await listLibraryCourseQuestionBanks(libraryCourseId)) || []) as TrainingQuestionBank[]
} catch {
/* 失败保持空态,展示「-」 */
} finally {
banksLoading.value = false
}
}
// 计划未关联课程管理条目时(000158):按计划名称自动创建课程管理条目(草稿)
// 并挂接回写,使课件/试题维护入口对存量计划(线下/线上同样适用)可用
const ensureLibraryCourse = async (): Promise<TrainingLibraryCourse | null> => {
const existing = activeLibraryCourse.value
if (existing) return existing
const row = activeCourse.value
if (!row) return null
const name = (editForm.value.name || row.name || '').trim()
if (!name) {
MessagePlugin.warning('缺少课程名称,无法维护课件/试题')
return null
}
// 000165 复测:先按课程名匹配既有条目并补挂(回写计划),同名课程已存在时
// 不再另建重复空条目,课件/试题维护落到正确课程
const byName = libraryCourses.value.find((c) => c.name === name)
if (byName) {
editForm.value.library_course_id = byName.id
activeCourse.value = { ...row, library_course_id: byName.id }
await saveCourse(detailSavePayload({ ...row, library_course_id: byName.id }))
return byName
}
assetSaving.value = true
try {
const created = unwrap(await saveCourseLibraryItem({
name,
owner_dept_id: editForm.value.dept_ids?.[0] || '',
lecturer_id: editForm.value.lecturer_id || '',
mode: editForm.value.mode === 'online' ? 'online' : 'offline',
type: editForm.value.type === 'elective' ? 'elective' : 'required',
hours: editForm.value.hours || 0,
description: row.description || '',
// 适合人员备注(000165):计划参加人员名单同步为课程管理「适合人员」展示
post_scope: (row.post_scope || '').slice(0, 500),
})) as TrainingLibraryCourse | null
if (!created) throw new Error('create library course failed')
replaceLibraryCourse(created)
editForm.value.library_course_id = created.id
// 关联回写计划(全量载荷,避免部分字段被零值覆盖)
activeCourse.value = { ...row, library_course_id: created.id }
await saveCourse(detailSavePayload({ ...row, library_course_id: created.id }))
MessagePlugin.success(`已自动创建课程管理条目「${name}」并挂接该计划,后续课件/试题将同步维护`)
return created
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '自动创建课程管理条目失败'))
return null
} finally {
assetSaving.value = false
}
}
// 更换课件(000156):上传文件直接回写课程管理条目(material/file 同步知识库 fail-open)
const onChangeMaterial = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
// 无关联条目时自动按计划名称创建(000158),再上传课件
const lc = await ensureLibraryCourse()
if (!lc) return
assetSaving.value = true
try {
const fd = new FormData()
fd.append('file', file)
const updated = unwrap(await uploadCourseLibraryMaterial(lc.id, fd)) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
MessagePlugin.success(`课件已更换为「${updated?.file_name || updated?.material_name || file.name}」,已同步到课程管理「${lc.name}」`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件更换失败,请稍后重试'))
} finally {
assetSaving.value = false
}
}
// 更换试题(000156):所选题库整体替换该课程条目的题库,回写课程管理
const onRelinkBank = async () => {
const lc = await ensureLibraryCourse()
if (!lc || !relinkBankId.value) {
if (lc && !relinkBankId.value) MessagePlugin.warning('请先选择要挂接的题库')
return
}
assetSaving.value = true
try {
courseBanks.value = (unwrap(await linkLibraryCourseQuestionBank(lc.id, relinkBankId.value)) || []) as TrainingQuestionBank[]
// 同步本地题库总表的挂接关系:原挂本课程的解挂,新选中的标记挂接
const linked = new Set(courseBanks.value.map((b) => b.id))
allBanks.value = allBanks.value.map((b) => {
if (b.library_course_id === lc.id) return { ...b, library_course_id: linked.has(b.id) ? b.id : '' }
if (b.id === relinkBankId.value) return { ...b, library_course_id: lc.id }
return b
})
relinkVisible.value = false
relinkBankId.value = ''
MessagePlugin.success('试题已更换,已同步到课程管理对应课程')
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
assetSaving.value = false
}
}
// 课程条目资产更新后替换本地缓存(下拉标签与展示同步刷新)
const replaceLibraryCourse = (updated?: TrainingLibraryCourse | null) => {
if (!updated) return
const idx = libraryCourses.value.findIndex((c) => c.id === updated.id)
if (idx >= 0) libraryCourses.value.splice(idx, 1, updated)
else libraryCourses.value = [...libraryCourses.value, updated]
}
// 详情打开回源课程管理(000165 复测):本地列表缓存可能滞后(课件/试题刚在
// 课程管理或另一计划里更新过),按课程名拉取最新条目替换缓存,课件/试题/适合
// 人员展示与后续上传落点都跟随最新数据;计划未挂接条目时按名称补挂(回写
// library_course_id),试题列表一并刷新。失败保持本地缓存展示,不阻断详情打开。
const refreshDetailLibraryCourse = async (row: TrainingCourse) => {
if (!canManage.value || !row.name) return
try {
const res = unwrap(await listCourseLibrary({ keyword: row.name, page_size: 20 }))
const items = ((unwrap(res)?.items as TrainingLibraryCourse[]) || [])
const hit = items.find((c) => c.id && c.id === row.library_course_id) || items.find((c) => c.name === row.name)
if (!hit) return
replaceLibraryCourse(hit)
if (!row.library_course_id && editForm.value.library_course_id !== hit.id) {
editForm.value.library_course_id = hit.id
activeCourse.value = { ...row, library_course_id: hit.id }
}
loadCourseBanks(editForm.value.library_course_id || '')
} catch {
/* 回源失败保持本地缓存展示 */
}
}
// ---- 从知识库选择课件/试题(000158):与课程管理同口径(课件 from-kb 挂载,
// 试题 KB 文档解析建题库挂课程条目),月计划详情「知识库」入口 ----
const kbRefs = ref<TrainingKnowledgeBases>({ courseware: null, question_bank: null })
const kbDocsCache = ref<Record<string, { id: string; file_name: string }[]>>({})
const kbDocsLoading = ref(false)
const kbCoursewareVisible = ref(false)
const kbCoursewareDocId = ref('')
const kbBankVisible = ref(false)
const kbBankDocId = ref('')
const kbCoursewareDocs = computed(() => kbDocsCache.value[kbRefs.value.courseware?.id || ''] || [])
const kbBankDocs = computed(() => kbDocsCache.value[kbRefs.value.question_bank?.id || ''] || [])
// 知识库文档列表(按 kb id 缓存,惰性加载;与 LibraryPanel 选课件的接口口径一致)
const loadKbDocs = async (kind: 'courseware' | 'question_bank') => {
const kb = kbRefs.value[kind]
if (!kb?.id) return
if (kbDocsCache.value[kb.id]) return
kbDocsLoading.value = true
try {
const res: any = await get(`/api/v1/knowledge-bases/${encodeURIComponent(kb.id)}/knowledge?page=1&page_size=200`)
const body = res?.data ?? res
kbDocsCache.value = {
...kbDocsCache.value,
[kb.id]: (Array.isArray(body) ? body : body?.items || []).map((it: any) => ({
id: String(it.id),
file_name: it.file_name || it.title || it.id,
})),
}
} catch {
/* 失败保持空态 */
} finally {
kbDocsLoading.value = false
}
}
const ensureKbRefs = async () => {
if (kbRefs.value.courseware || kbRefs.value.question_bank) return
try {
kbRefs.value = (unwrap(await getTrainingKnowledgeBases()) as TrainingKnowledgeBases) || {
courseware: null,
question_bank: null,
}
} catch {
/* 知识库摘要失败:文档列表为空,提示不可选 */
}
}
const openKbCourseware = async () => {
kbCoursewareVisible.value = !kbCoursewareVisible.value
kbBankVisible.value = false
if (!kbCoursewareVisible.value) return
await ensureKbRefs()
await loadKbDocs('courseware')
}
// 从知识库「企业培训(课件)」选文档挂为课件(回写课程管理,与上传同口径)
const onAttachKbCourseware = async () => {
const lc = await ensureLibraryCourse()
const doc = kbCoursewareDocs.value.find((d) => d.id === kbCoursewareDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库课件文档')
return
}
assetSaving.value = true
try {
const updated = unwrap(await attachCourseLibraryMaterialFromKb(lc.id, { knowledge_id: doc.id })) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
kbCoursewareVisible.value = false
kbCoursewareDocId.value = ''
MessagePlugin.success(`课件已更换为知识库文档「${doc.file_name}」,已同步到课程管理「${lc.name}」`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件更换失败,请稍后重试'))
} finally {
assetSaving.value = false
}
}
const openKbBank = async () => {
kbBankVisible.value = !kbBankVisible.value
kbCoursewareVisible.value = false
if (!kbBankVisible.value) return
await ensureKbRefs()
await loadKbDocs('question_bank')
}
// 从知识库「企业培训(题库)」文档解析建题库并挂当前课程条目(回写课程管理)
const onImportKbBank = async () => {
const lc = await ensureLibraryCourse()
const doc = kbBankDocs.value.find((d) => d.id === kbBankDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库题库文档')
return
}
assetSaving.value = true
try {
const bank = unwrap(await importQuestionBankFromKnowledge({
knowledge_id: doc.id,
name: doc.file_name.replace(/\.[^.]+$/, ''),
library_course_id: lc.id,
})) as TrainingQuestionBank | null
kbBankVisible.value = false
kbBankDocId.value = ''
if (bank) allBanks.value = [bank, ...allBanks.value.filter((b) => b.id !== bank.id)]
await loadCourseBanks(lc.id)
MessagePlugin.success(`试题已更换为知识库题库「${bank?.name || doc.file_name}」,已同步到课程管理「${lc.name}」`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
assetSaving.value = false
}
}
const formVisible = ref(false)
const sessionsVisible = ref(false)
const activeCourse = ref<TrainingCourse | null>(null)
// ---- 创建弹窗课件/试题维护(000163):与调整弹窗同口径,直接回写课程管理
// 主数据并作为本次培训课件/试题;000165 复测起课件/试题变更不再置「待审核」,
// 课程保持已审核,保存后可直接发布 ----
const formAssetSaving = ref(false)
const formMaterialInput = ref<HTMLInputElement | null>(null)
const formKbCoursewareVisible = ref(false)
const formKbCoursewareDocId = ref('')
const formRelinkVisible = ref(false)
const formRelinkBankId = ref('')
const formKbBankVisible = ref(false)
const formKbBankDocId = ref('')
// 创建弹窗目标课程条目:未选课程时按钮已禁用,这里兜底提示
const requireFormLibraryCourse = (): TrainingLibraryCourse | null => {
const lc = formLibraryCourse.value
if (!lc) MessagePlugin.warning('请先从课程管理选择课程')
return lc || null
}
const openFormKbCourseware = async () => {
formKbCoursewareVisible.value = !formKbCoursewareVisible.value
formKbBankVisible.value = false
if (!formKbCoursewareVisible.value) return
await ensureKbRefs()
await loadKbDocs('courseware')
}
const openFormKbBank = async () => {
formKbBankVisible.value = !formKbBankVisible.value
formKbCoursewareVisible.value = false
if (!formKbBankVisible.value) return
await ensureKbRefs()
await loadKbDocs('question_bank')
}
// 上传课件:文件直接回写课程管理条目(名称登记为空时后端以文件名兜底)
const onFormChangeMaterial = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
const lc = requireFormLibraryCourse()
if (!lc || !file) return
formAssetSaving.value = true
try {
const fd = new FormData()
fd.append('file', file)
const updated = unwrap(await uploadCourseLibraryMaterial(lc.id, fd)) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
MessagePlugin.success(`课件已上传到课程「${lc.name}」并作为本次培训课件(追加不替换),无需重新审核,保存后可直接发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件上传失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 从知识库选文档挂为课件(与上传同口径,课件变更不回「待审核」)
const onFormAttachKbCourseware = async () => {
const lc = requireFormLibraryCourse()
const doc = kbCoursewareDocs.value.find((d) => d.id === formKbCoursewareDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库课件文档')
return
}
formAssetSaving.value = true
try {
const updated = unwrap(await attachCourseLibraryMaterialFromKb(lc.id, { knowledge_id: doc.id })) as TrainingLibraryCourse | null
replaceLibraryCourse(updated)
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
MessagePlugin.success(`课件「${doc.file_name}」已挂接为课程「${lc.name}」最新课件(原课件保留),无需重新审核,保存后可直接发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 更换试题:所选题库整体替换该课程条目的题库(后端同步重置审核状态)
const onFormRelinkBank = async () => {
const lc = requireFormLibraryCourse()
if (!lc || !formRelinkBankId.value) {
if (lc && !formRelinkBankId.value) MessagePlugin.warning('请先选择要挂接的题库')
return
}
formAssetSaving.value = true
try {
const banks = (unwrap(await linkLibraryCourseQuestionBank(lc.id, formRelinkBankId.value)) || []) as TrainingQuestionBank[]
// 同步本地题库总表的挂接关系(与调整弹窗 onRelinkBank 同口径)
const linked = new Set(banks.map((b) => b.id))
allBanks.value = allBanks.value.map((b) => {
if (b.library_course_id === lc.id) return { ...b, library_course_id: linked.has(b.id) ? b.id : '' }
if (b.id === formRelinkBankId.value) return { ...b, library_course_id: lc.id }
return b
})
formRelinkVisible.value = false
formRelinkBankId.value = ''
MessagePlugin.success(`试题已更换到课程「${lc.name}」并作为本次培训试题,无需重新审核,保存后可直接发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 从知识库题库文档解析建题库并挂当前所选课程条目(后端同步重置审核状态)
const onFormImportKbBank = async () => {
const lc = requireFormLibraryCourse()
const doc = kbBankDocs.value.find((d) => d.id === formKbBankDocId.value)
if (!lc || !doc) {
if (lc && !doc) MessagePlugin.warning('请先选择知识库题库文档')
return
}
formAssetSaving.value = true
try {
const bank = unwrap(await importQuestionBankFromKnowledge({
knowledge_id: doc.id,
name: doc.file_name.replace(/\.[^.]+$/, ''),
library_course_id: lc.id,
})) as TrainingQuestionBank | null
formKbBankVisible.value = false
formKbBankDocId.value = ''
if (bank) allBanks.value = [bank, ...allBanks.value.filter((b) => b.id !== bank.id)]
MessagePlugin.success(`试题已更换为知识库题库「${bank?.name || doc.file_name}」,无需重新审核,保存后可直接发布计划`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题更换失败,请稍后重试'))
} finally {
formAssetSaving.value = false
}
}
// 讲师只读展示:员工名册映射姓名,外部讲师直接显示
const lecturerDisplay = (lecturerId: string) => {
if (lecturerId) {
const byUserId = members.value.find((m) => m.user_id === lecturerId)
if (byUserId) return byUserId.user_name || byUserId.employee_no
const byRoster = lecturers.value.find((l) => l.id === lecturerId)
if (byRoster) return byRoster.name
return lecturerId
}
const row = activeCourse.value
return row?.lecturer_external || '-'
}
// 部门 id 集合 → 名称(随课程管理「所属部门」带出,只读展示)
const deptNamesOf = (ids: string[] | undefined) => {
const list = (ids || []).map((id) => depts.value.find((d) => d.id === id)?.name || id).filter(Boolean)
return list.length ? list.join('、') : '-'
}
// 适用部门「全部」哨兵已随部门选择字段移除(部门随课程管理带出并锁定)
// [2026-11 需求] 「适用部门」变化 → 自动同步「参加人员」:
// 保留手动增选的人员,把旧部门集合自动带入的成员替换为新部门集合的成员
// (取消部门即移出其人员,新增部门即并入其人员),实际推送与应培名单以「参加人员」为准。
const syncParticipantsOnDeptChange = (prevDeptIds: string[], nextDeptIds: string[], currentIds: string[]): string[] => {
const prevSet = new Set(prevDeptIds)
const nextSet = new Set(nextDeptIds)
const prevDeptMemberIds = new Set(members.value.filter((m) => prevSet.has(m.dept_id)).map((m) => m.id))
const nextDeptMemberIds = members.value.filter((m) => nextSet.has(m.dept_id)).map((m) => m.id)
const kept = currentIds.filter((id) => !prevDeptMemberIds.has(id))
return [...new Set([...kept, ...nextDeptMemberIds])]
}
// 详情弹窗的课程信息编辑表单(随打开预填,保存走 saveCourse):
// 课程名称/类型/讲师/所属部门随课程管理锁定只读,仅维护六项授课安排字段
const detailSaving = ref(false)
const editForm = ref({
library_course_id: '',
name: '',
mode: 'offline' as 'offline' | 'online',
type: 'required',
hours: 2,
credits: 1,
lecturer_id: '',
dept_ids: [] as string[],
start_at: '',
location: '',
notify_mode: 'immediate' as 'immediate' | 'day_before',
})
// 类型只读展示(创建弹窗用 form,详情弹窗用 editForm)
const formTypeDisplay = computed(() => {
const base = sessionsVisible.value ? editForm.value.type : form.value.type
return base === 'elective' ? '选修课' : '必修课'
})
// 需求确认同步的参加人员(与场次学员名单合一):按人员/部门/岗位三种方式选择,
// 统一解析为员工 id;initialIds 记录打开时的解析结果,仅在实际变化时才写名单,
// 避免误清人工维护的名单
const demandSync = ref({ participantIds: [] as string[], initialIds: [] as string[] })
const participantMode = ref<'member' | 'dept' | 'post'>('member')
const participantDeptIds = ref<string[]>([])
const participantPostIds = ref<string[]>([])
// 名单「按岗位」选项:名册中的实际岗位去重
const postOptions = computed(() => [...new Set(members.value.map((m) => m.post).filter(Boolean))])
// 按当前选择方式(人员/部门/岗位)解析出去重后的参加员工
const resolvedParticipantMembers = computed<TrainingMember[]>(() => {
const ids = new Set(demandSync.value.participantIds)
for (const m of members.value) {
if (participantDeptIds.value.includes(m.dept_id)) ids.add(m.id)
if (m.post && participantPostIds.value.includes(m.post)) ids.add(m.id)
}
return members.value.filter((m) => ids.has(m.id))
})
// 课程修改版本记录(列表「记录」入口打开时拉取)
const changeLogs = ref<TrainingCourseChangeLog[]>([])
const changeLogsVisible = ref(false)
const changeLogsLoading = ref(false)
const changeLogCourse = ref<TrainingCourse | null>(null)
const openChangeLogs = async (row: TrainingCourse) => {
changeLogCourse.value = row
changeLogsVisible.value = true
changeLogsLoading.value = true
resetChangeLogPage()
try {
const res = await listCourseChangeLogs(row.id)
changeLogs.value = unwrap(res) || []
} catch {
changeLogs.value = []
} finally {
changeLogsLoading.value = false
}
}
// 操作人展示:operator_id 为平台用户 id,经名册映射姓名
const operatorName = (operatorId: string) =>
members.value.find((m) => m.user_id === operatorId)?.user_name || operatorId.slice(0, 8)
const form = ref({
library_course_id: '',
name: '',
mode: 'offline' as 'offline' | 'online',
type: 'required',
hours: 2,
credits: 1,
start_at: '',
location: '',
// 学员开课通知方式(2026-11 推学员): immediate=名单/课件就绪即推(默认)
notify_mode: 'immediate' as 'immediate' | 'day_before',
lecturer_id: '',
deadlineDays: 7,
dept_ids: [] as string[],
description: '',
})
// 从课程管理选择课程:带出课程信息(名称/类型/讲师/学时/所属部门/说明)并锁定,
// 计划侧仅维护授课安排(学时学分/时间/地点/通知/参加人员);
// 「形式」为计划侧独立字段(000162),不随所选课程带出,由表单自行选择
const onLibraryCourseChange = (libraryCourseId: unknown) => {
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
form.value.name = lc?.name || ''
form.value.type = lc?.type === 'elective' ? 'elective' : 'required'
form.value.hours = lc?.hours || form.value.hours
form.value.lecturer_id = lc?.lecturer_id || ''
form.value.description = lc?.description || ''
form.value.dept_ids = lc?.owner_dept_id ? [lc.owner_dept_id] : []
// 换选课程后重置课件/试题维护的临时选择状态(000163)
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
formRelinkVisible.value = false
formRelinkBankId.value = ''
formKbBankVisible.value = false
formKbBankDocId.value = ''
}
// 「前往课程管理」:切到课程管理子页(同页内由 Training 按路由 tab 切换面板)
const goLibrary = () => {
formVisible.value = false
router.push('/platform/training/library')
}
// ---- 创建弹窗:参加人员(与详情弹窗同构,按人员/部门/岗位) ----
const formParticipantMode = ref<'member' | 'dept' | 'post'>('member')
const formParticipantIds = ref<string[]>([])
const formParticipantDeptIds = ref<string[]>([])
const formParticipantPostIds = ref<string[]>([])
// 按当前选择方式解析出的参加员工(与详情弹窗 resolvedParticipantMembers 同口径)
const resolvedFormMembers = computed<TrainingMember[]>(() => {
const ids = new Set(formParticipantIds.value)
for (const m of members.value) {
if (formParticipantDeptIds.value.includes(m.dept_id)) ids.add(m.id)
if (m.post && formParticipantPostIds.value.includes(m.post)) ids.add(m.id)
}
return members.value.filter((m) => ids.has(m.id))
})
const resetFormParticipants = () => {
formParticipantMode.value = 'member'
formParticipantIds.value = []
formParticipantDeptIds.value = []
formParticipantPostIds.value = []
}
// [2026-11 需求] 创建弹窗:「适用部门」变化自动带入/移出部门人员到「参加人员」。
// 按部门/按岗位的既有选择先固化为具体名单(保留不丢),选择方式切回「按人员」便于增删。
watch(
() => form.value.dept_ids,
(next, prev) => {
if (!formVisible.value || !next) return
formParticipantIds.value = syncParticipantsOnDeptChange(prev || [], next, resolvedFormMembers.value.map((m) => m.id))
formParticipantDeptIds.value = []
formParticipantPostIds.value = []
formParticipantMode.value = 'member'
},
)
// 详情弹窗同理;openDetail 预填表单时抑制一次,避免覆盖按 post_scope 回显的名单
const suppressDetailDeptWatch = ref(false)
watch(
() => editForm.value.dept_ids,
(next, prev) => {
if (!sessionsVisible.value || suppressDetailDeptWatch.value || !next) return
demandSync.value.participantIds = syncParticipantsOnDeptChange(prev || [], next, resolvedParticipantMembers.value.map((m) => m.id))
participantDeptIds.value = []
participantPostIds.value = []
participantMode.value = 'member'
},
)
const courseColumns = [
// 批量勾选列(000165 复测):配合批量发布/批量删除
{ colKey: 'row-select', type: 'multiple', width: 44 },
// 左侧列不固定(000154):计划编号/课程名称随横向滚动,状态/操作仍固定右侧
// 000165 复测列序:授课时间/计划培训时间前移至课程名称之后,讲师/地点次之,
// 形式/类型/学时/上报部门后移(关注信息优先)
{ colKey: 'plan_code', title: '计划编号', width: 125 },
{ colKey: 'name', title: '课程名称', width: 170 },
{ colKey: 'teachTime', title: '授课时间', width: 130 },
{ colKey: 'plannedTime', title: '计划培训时间', width: 150 },
{ colKey: 'lecturer', title: '讲师', width: 100 },
{ colKey: 'location', title: '地点', width: 110 },
{ colKey: 'expected', title: '实/应人数', width: 90 },
{ colKey: 'mode', title: '形式', width: 70 },
{ colKey: 'type', title: '类型', width: 70 },
{ colKey: 'hours', title: '学时', width: 60 },
{ colKey: 'reporter', title: '上报部门', width: 110 },
{ colKey: 'learnStatus', title: '学习状态', width: 90 },
{ colKey: 'examStatus', title: '考试状态', width: 90 },
{ colKey: 'status', title: '状态', width: 80, fixed: 'right' },
{ colKey: 'op', title: '操作', width: 180, fixed: 'right' },
]
// ---- 查询条件(名称/讲师/培训月份/状态;列表全量加载,本地过滤) ----
const STATUS_OPTIONS = [
{ value: 'draft', label: '草稿' },
{ value: 'pending', label: '待审' },
{ value: 'published', label: '已发布' },
{ value: 'archived', label: '已归档' },
]
// 当月(YYYY-MM,000163):默认只展示计划培训/授课时间任一命中当月的计划
const now = new Date()
const currentMonthKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
const filters = ref({
keyword: '',
lecturerId: '' as string | '',
status: '',
// 培训月份多选(000163):默认当月;清空 = 全部数据
months: [currentMonthKey] as string[],
})
const resetFilters = () => {
filters.value = { keyword: '', lecturerId: '', status: '', months: [currentMonthKey] }
resetCoursePage()
}
// 月份归一:「YYYY-M」/「YYYY-MM-DD HH:mm」等统一取 YYYY-MM;无法解析返回空
const monthKeyOf = (value: string | null | undefined): string => {
const m = (value || '').trim().match(/^(\d{4})-(\d{1,2})/)
return m ? `${m[1]}-${String(Number(m[2])).padStart(2, '0')}` : ''
}
// 月份下拉展示:2026-11 → 2026年11月
const monthLabel = (key: string) => {
const m = key.match(/^(\d{4})-(\d{2})$/)
return m ? `${m[1]}年${Number(m[2])}月` : key
}
// 计划的培训月份集合(000163):计划培训时间 + 授课时间(含最近场次回退)任一命中即算
const courseMonthKeys = (row: TrainingCourse): string[] => {
const keys = [monthKeyOf(row.planned_time), monthKeyOf(row.teach_time), monthKeyOf(teachDateValue(row))]
return [...new Set(keys.filter(Boolean))]
}
// 月份筛选选项:当月 + 计划数据中实际出现的月份,倒序展示
const monthOptions = computed(() => {
const set = new Set<string>([currentMonthKey])
for (const row of courses.value) {
for (const k of courseMonthKeys(row)) set.add(k)
}
return [...set].sort().reverse()
})
// 授课时间过滤口径与列展示一致:teach_time(具体时间/期望月份)优先,否则最近场次开始时间,
// 统一归一为 YYYY-MM-DD 后做字符串范围比较。
const teachDateValue = (row: TrainingCourse): string | null => {
if (row.teach_time) {
if (/^\d{4}-\d{2}$/.test(row.teach_time)) return `${row.teach_time}-01`
const shown = fmtBeijingTime(row.teach_time)
return shown ? shown.replaceAll('/', '-').slice(0, 10) : null
}
const list = courseSessions.value[row.id] || []
const nearest = list.find((s) => s.status === 'scheduled' && s.start_at) || list.find((s) => s.start_at) || list[0]
if (!nearest?.start_at) return null
const shown = fmtBeijingTime(nearest.start_at)
return shown ? shown.replaceAll('/', '-').slice(0, 10) : null
}
// 计划培训时间排序键:计划培训时间优先,缺失时回退授课时间(含最近场次)
const courseSortKey = (row: TrainingCourse): number => {
const pk = plannedMonthSortKey(row.planned_time)
if (pk >= 0) return pk
return plannedMonthSortKey(row.teach_time || teachDateValue(row))
}
const filteredCourses = computed(() => {
const kw = filters.value.keyword.trim().toLowerCase()
const months = filters.value.months || []
const list = courses.value.filter((row) => {
if (kw && !(row.name || '').toLowerCase().includes(kw)) return false
if (filters.value.lecturerId && row.lecturer_id !== filters.value.lecturerId) return false
if (filters.value.status && row.status !== filters.value.status) return false
// 000163 月份筛选:计划培训时间/授课时间任一命中所选月份即可;清空 = 全部数据。
// 未填计划/授课时间的计划(如暂存草稿)无月份可命中,始终展示,
// 避免默认当月视图下刚暂存的草稿“看不见”
if (months.length) {
const keys = courseMonthKeys(row)
if (keys.length && !months.some((m) => keys.includes(m))) return false
}
return true
})
// 000163:按计划培训时间倒序(缺失计划培训时间的行按授课时间,均无则排最后)
return list.slice().sort((a, b) => courseSortKey(b) - courseSortKey(a))
})
// 共用分页(000163):计划列表默认每页 15 条
const {
page: coursePage,
pageSize: coursePageSize,
total: courseTotal,
paged: pagedCourses,
reset: resetCoursePage,
} = useTrainingPager(filteredCourses)
// 计划修改记录弹窗分页(000163)
const {
page: changeLogPage,
pageSize: changeLogPageSize,
total: changeLogTotal,
paged: pagedChangeLogs,
reset: resetChangeLogPage,
} = useTrainingPager(changeLogs)
const statusText = (s: string) => ({ draft: '草稿', pending: '待审', published: '已发布', archived: '已归档' }[s] || s)
const statusTheme = (s: string) => ({ draft: 'default', pending: 'warning', published: 'success', archived: 'default' }[s] || 'default')
const fmtTime = (raw: string | null) => fmtBeijingTime(raw) || '待定'
const typeText = (t: string) => ({ required: '必修', elective: '选修' }[t] || t)
// 学习/考试状态列文案与配色(口径与后端聚合一致,点击跳转学习考试页对应页签)
const learnStatusText = (s: string) => ({ not_started: '未学习', learning: '学习中', learned: '已学习' }[s] || '未学习')
const learnStatusTheme = (s: string) => ({ learning: 'warning', learned: 'success' }[s] || 'default')
const examStatusText = (s: string) => ({ not_started: '未考试', taking: '考试中', taken: '已考试' }[s] || '未考试')
const examStatusTheme = (s: string) => ({ taking: 'warning', taken: 'success' }[s] || 'default')
// 展示映射:讲师 id→姓名 / 课程→最近排期地点
const lectNameMap = computed(() => {
const m: Record<string, string> = {}
for (const l of lecturers.value) m[l.id] = l.name
return m
})
const courseSessions = computed(() => {
const map: Record<string, TrainingCourseSession[]> = {}
for (const s of sessions.value) {
(map[s.course_id] ||= []).push(s)
}
return map
})
const courseLocation = (row: TrainingCourse) => {
const list = courseSessions.value[row.id] || []
const nearest = list.find((s) => s.status === 'scheduled' && s.location) || list.find((s) => s.location) || list[0]
// 场次未排地点或尚未建场次(如需求确认草稿、参加人员未匹配到员工)时,
// 回退课程自身地点(来自需求确认同步落库的 course.location)
return nearest?.location || row.location || ''
}
// 最靠前的有效场次(带授课时间或地点):发布前置校验与列表展示同口径用
// (课程级授课时间/地点为空的存量草稿,场次已排期即视为已维护,2026-11-26)
const firstUsableSession = (row: TrainingCourse) => {
const list = courseSessions.value[row.id] || []
return (
list.find((s) => s.status === 'scheduled' && (s.start_at || s.location)) ||
list.find((s) => s.start_at || s.location) ||
null
)
}
// 授课时间展示:期望月份默认值(YYYY-MM)→「2026/11」;具体时间 → 北京时间无秒;线上课默认「长期」
const teachTimeText = (row: TrainingCourse) => {
if (row.mode === 'online') return row.teach_time ? teachTimeDisplay(row.teach_time) : '长期'
if (row.teach_time) return teachTimeDisplay(row.teach_time)
const list = courseSessions.value[row.id] || []
const nearest = list.find((s) => s.status === 'scheduled' && s.start_at) || list.find((s) => s.start_at) || list[0]
return nearest?.start_at ? fmtTime(nearest.start_at) : '-'
}
const teachTimeDisplay = (value: string) => {
if (/^\d{4}-\d{2}$/.test(value)) return value.replace('-', '/')
return fmtBeijingTime(value) || value
}
const loadAll = async () => {
loading.value = true
try {
const [c, d, m, l, s, lib, banks] = await Promise.all([
listCourses({ page_size: 100 }),
listDepts(),
listMembers({ page_size: 500 }),
listLecturers().catch(() => []),
listSessions({ year: 0, month: 0 }).catch(() => []),
// scope=plan(000163):创建月度计划选课口径 —— 维护角色可选全部部门课程,
// 不再按本部门收窄(后端对纯学员/无维护角色调用方仍按原范围收窄)
listCourseLibrary({ page_size: 500, scope: 'plan' }).catch(() => null),
listQuestionBanks({ page_size: 200 }).catch(() => null),
])
courses.value = unwrap(c)?.items || []
depts.value = unwrap(d) || []
members.value = unwrap(m)?.items || []
lecturers.value = (l && unwrap(l)) || []
sessions.value = (s && unwrap(s)) || []
libraryCourses.value = (lib && unwrap(lib)?.items) || []
allBanks.value = (banks && unwrap(banks)?.items) || []
} finally {
loading.value = false
}
}
const openCreate = (mode: 'offline' | 'online') => {
form.value = {
library_course_id: '', name: '', mode, type: 'required', hours: 2, credits: 1,
start_at: '', location: '', notify_mode: 'immediate', lecturer_id: '', deadlineDays: 7, dept_ids: [],
description: '',
}
resetFormParticipants()
// 重置课件/试题维护临时状态(000163),避免上一次打开的残留选择
formKbCoursewareVisible.value = false
formKbCoursewareDocId.value = ''
formRelinkVisible.value = false
formRelinkBankId.value = ''
formKbBankVisible.value = false
formKbBankDocId.value = ''
formVisible.value = true
}
// 创建计划保存载荷(000163 抽取复用):「保存并发布」与「暂存草稿」共用;
// 参加人员随载荷落 post_scope,发布后由场次名单同步
const buildSavePayload = () => ({
name: form.value.name,
mode: form.value.mode,
type: form.value.type,
hours: form.value.hours,
credits: form.value.credits,
dept_ids: form.value.dept_ids,
lecturer_id: form.value.lecturer_id || undefined,
teach_time: teachTimeOf(form.value),
// 000163 根因修复:授课地点须随课程落库(此前只写到场次,发布校验读
// course.location 恒为空,导致「已填授课地点仍提示需先设置授课地点」)
location: form.value.mode === 'offline' ? form.value.location.trim() : '',
// 000163:计划培训时间默认取授课时间所在月份(YYYY-MM)
planned_time: form.value.start_at ? form.value.start_at.slice(0, 7) : '',
post_scope: resolvedFormMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
// 课程管理关联(服务端据此带出并锁定课程信息,自动生成计划编号)
library_course_id: form.value.library_course_id,
description: form.value.description,
})
const onSave = async () => {
if (!form.value.library_course_id || !form.value.name) {
MessagePlugin.warning('请从课程管理选择课程(课程名称必选)')
return
}
// 000163 根因修复:此前「保存并发布」直接调发布接口,后端校验不过时前端只
// 报笼统的「保存失败」且不刷新列表(草稿其实已落库),表现为“无法创建月度计划”。
// 现与后端 PublishCourse 同口径,在提交前逐项拦截并给出明确提示。
const selectedLib = libraryCourses.value.find((c) => c.id === form.value.library_course_id)
// 000163:课程须已审核(审核通过即自动发布);未审核时发布被后端拦截,这里提前提示
if (selectedLib && selectedLib.verify_status !== 'confirmed') {
MessagePlugin.warning(
`课程「${selectedLib.name}」尚未审核,请先联系所属部门课长/经理在「课程管理」中审核(审核通过即发布)后再创建发布`,
)
return
}
// 讲师随课程管理锁定:线下计划缺讲师时提示先在课程管理维护
if (form.value.mode === 'offline' && !form.value.lecturer_id) {
MessagePlugin.warning('当前课程未指定讲师,请先前往「课程管理」维护讲师后再创建线下计划')
return
}
// 线下计划另需授课时间/授课地点(后端发布校验同口径)
if (form.value.mode === 'offline') {
if (!form.value.start_at) {
MessagePlugin.warning('线下计划请先设置授课时间')
return
}
if (!form.value.location.trim()) {
MessagePlugin.warning('线下计划请先设置授课地点')
return
}
}
// 线上计划须已登记课件(名称登记/文件/知识库文档任一,随课程管理带出)
if (form.value.mode === 'online' && !(selectedLib?.material_name || selectedLib?.file_name || selectedLib?.knowledge_id)) {
MessagePlugin.warning('线上计划发布前需先在「课程管理」为该课程登记课件资料(上传课件/从知识库选择)')
return
}
// 参加人员必填(后端发布校验:post_scope 与场次名单任一非空)
const selectedMembers = resolvedFormMembers.value
if (!selectedMembers.length) {
MessagePlugin.warning('请先选择参加人员(推送与应培人员以「参加人员」名单为准)')
return
}
saving.value = true
try {
const res = await saveCourse(buildSavePayload())
const course = unwrap(res)
if (!course) throw new Error('save failed')
// 线下课同步创建场次;线上课创建「线上」名单挂靠场次。
const sessionOpts = {
mode: form.value.mode,
lecturerId: form.value.lecturer_id || undefined,
startAt: form.value.start_at,
location: form.value.location,
hours: form.value.hours,
}
let rosterSession: TrainingCourseSession | undefined
if (form.value.mode === 'offline') {
const sessionRes = await saveSession({
course_id: course.id,
start_at: form.value.start_at ? new Date(form.value.start_at).toISOString() : '',
end_at: form.value.start_at ? new Date(new Date(form.value.start_at).getTime() + form.value.hours * 3600 * 1000).toISOString() : '',
location: form.value.location,
capacity: 0,
lecturer_id: form.value.lecturer_id || undefined,
// [2026-11 推学员] 学员开课通知方式随排课落库
notify_mode: form.value.notify_mode,
})
rosterSession = unwrap(sessionRes) || undefined
await refreshSessionCache()
} else {
rosterSession = await ensureCourseSession(course.id, sessionOpts)
}
// [2026-11 需求] 学员名单以「参加人员」为准:实际推送与应培人员按「参加人员」落名单
if (selectedMembers.length) {
const session = rosterSession || await ensureCourseSession(course.id, sessionOpts)
if (session) await setEnrollments(session.id, selectedMembers.map((m) => m.id))
}
// 000163 根因修复:发布与保存拆开处理 —— 发布校验不过时草稿已落库,
// 透出真实原因并刷新列表,草稿可在列表「调整」完善后再点「发布」。
try {
await publishCourse(course.id)
} catch (e: any) {
MessagePlugin.warning(
`计划已保存为草稿(计划编号 ${course.plan_code || '自动生成'}),发布失败:${apiErrorMessage(e, '请完善计划信息后再发布')};可在列表「调整」完善后点击「发布」`,
)
formVisible.value = false
resetFormParticipants()
loadAll()
return
}
MessagePlugin.success(
course.plan_code
? `计划 ${course.plan_code} 已保存并发布,讲师与学员通知已生成`
: '计划已保存并发布,讲师与学员通知已生成',
)
formVisible.value = false
resetFormParticipants()
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
} finally {
saving.value = false
}
}
// 暂存草稿(000163):此前按钮只关闭弹窗未落库,填写内容全部丢失;现按草稿
// 状态保存计划(不建场次/名单、不发布),可稍后在列表「调整」完善后「发布」。
// 草稿只要求选到课程,其余授课安排可留空待补。
const onSaveDraft = async () => {
if (!form.value.library_course_id || !form.value.name) {
MessagePlugin.warning('请从课程管理选择课程(课程名称必选)')
return
}
saving.value = true
try {
const res = await saveCourse(buildSavePayload())
const course = unwrap(res)
if (!course) throw new Error('save failed')
MessagePlugin.success(
course.plan_code
? `计划 ${course.plan_code} 已暂存为草稿,可在列表「调整」完善后点击「发布」`
: '计划已暂存为草稿,可在列表「调整」完善后点击「发布」',
)
formVisible.value = false
resetFormParticipants()
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '暂存失败,请稍后重试'))
} finally {
saving.value = false
}
}
const onPublish = async (row: TrainingCourse) => {
// 与后端同口径的前置校验(000161):线上必须有课件;线下须有讲师(外部姓名
// 亦可)/授课时间/授课地点;两者均须已设置参加人员且关联课程已审核
if (row.mode === 'online') {
try {
const res = await listMaterials(row.id)
if (!(unwrap(res) || []).length) {
// 计划未自带课件时回退课程管理课件(名称登记/文件/知识库文档,
// 000156 随所选课程带出,详情弹窗「更换」也回写主数据)与后端同口径
const lc = libraryCourses.value.find((c) => c.id === (row.library_course_id || ''))
const hasLibCourseware = !!(lc?.material_name || lc?.file_name || lc?.knowledge_id)
if (!hasLibCourseware) {
MessagePlugin.warning(`「${row.name}」是线上计划,发布前需先登记课件资料`)
return
}
}
} catch {
/* 查询失败时交由后端校验兜底 */
}
} else {
if (!row.lecturer_id && !row.lecturer_external) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中指定讲师`)
return
}
// 授课时间/地点与列表展示同口径(场次排期优先,课程级字段兜底):存量草稿
// 课程级字段为空但场次已排期时不再误报「未设置」(2026-11-26 复测修复,
// 后端 PublishCourse 同口径兜底)
const session = firstUsableSession(row)
if (!row.teach_time && !session?.start_at) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课时间`)
return
}
if (!courseLocation(row)) {
MessagePlugin.warning(`「${row.name}」是线下计划,发布前需先在「调整」中设置授课地点`)
return
}
}
if (!row.post_scope) {
MessagePlugin.warning(`「${row.name}」发布前需先在「调整」中设置参加人员`)
return
}
try {
await publishCourse(row.id)
MessagePlugin.success('已发布')
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '发布失败'))
}
}
const onDelete = async (row: TrainingCourse) => {
try {
await deleteCourse(row.id)
MessagePlugin.success('已删除')
loadAll()
} catch (e: any) {
// 已发布计划仅超级管理员可删,后端拦截时透出统一文案
MessagePlugin.error(apiErrorMessage(e, '删除失败'))
}
}
// ---- 批量发布/批量删除(000165 复测):与课程管理批量审核同口径 —— 前端循环
// 单条接口,逐条透出失败原因;勾选禁用与行内按钮权限同口径 ----
const selectedCourseKeys = ref<string[]>([])
const batchSaving = ref(false)
// 已发布计划:普通维护角色不可再发布也不可删,勾选置灰(仅超管可勾选后删除)
const courseSelectionDisabledKeys = computed(() =>
isSuperAdmin.value ? [] : filteredCourses.value.filter((r) => r.status === 'published').map((r) => r.id),
)
const onBatchPublish = async () => {
// 仅可发布未发布行(已发布行跳过);线上课课件/线下课讲师/时间/地点/参加人员
// 等业务校验由后端 PublishCourse 逐条兜底,失败行透出原因
const rows = filteredCourses.value.filter(
(r) => selectedCourseKeys.value.includes(r.id) && r.status !== 'published',
)
if (!rows.length) {
MessagePlugin.warning('请先勾选待发布状态的计划')
return
}
batchSaving.value = true
let ok = 0
const failed: string[] = []
try {
for (const row of rows) {
try {
await publishCourse(row.id)
ok += 1
} catch (e: any) {
failed.push(`「${row.name}」${apiErrorMessage(e, '发布失败')}`)
}
}
if (ok) MessagePlugin.success(`批量发布完成:成功 ${ok} 条${failed.length ? `,失败 ${failed.length} 条` : ''}`)
if (failed.length) {
// 失败原因逐条透出(最多展示 3 条,避免长提示刷屏)
MessagePlugin.warning(failed.slice(0, 3).join(';') + (failed.length > 3 ? ` 等 ${failed.length} 条失败` : ''))
}
selectedCourseKeys.value = []
loadAll()
} finally {
batchSaving.value = false
}
}
const onBatchDelete = async () => {
// 删除口径与行内按钮一致:已发布计划仅超级管理员可删(普通维护角色仅未发布行),
// 非超管勾选面板已把已发布行置灰;后端 DeleteCourse 逐条兜底
const rows = filteredCourses.value.filter((r) => selectedCourseKeys.value.includes(r.id))
if (!rows.length) {
MessagePlugin.warning('请先勾选要删除的计划')
return
}
batchSaving.value = true
let ok = 0
const failed: string[] = []
try {
for (const row of rows) {
try {
await deleteCourse(row.id)
ok += 1
} catch (e: any) {
failed.push(`「${row.name}」${apiErrorMessage(e, '删除失败')}`)
}
}
if (ok) MessagePlugin.success(`批量删除完成:成功 ${ok} 条${failed.length ? `,失败 ${failed.length} 条` : ''}`)
if (failed.length) {
MessagePlugin.warning(failed.slice(0, 3).join(';') + (failed.length > 3 ? ` 等 ${failed.length} 条失败` : ''))
}
selectedCourseKeys.value = []
loadAll()
} finally {
batchSaving.value = false
}
}
const openDetail = async (row: TrainingCourse) => {
activeCourse.value = row
sessionsVisible.value = true
// 预填表单触发 dept_ids watcher,先抑制,避免自动带入覆盖 post_scope 回显的名单
suppressDetailDeptWatch.value = true
void nextTick(() => (suppressDetailDeptWatch.value = false))
// 预填课程信息编辑表单(课程名称/类型/讲师/部门随课程管理锁定,仅授课安排可改)
editForm.value = {
library_course_id: row.library_course_id || '',
name: row.name,
mode: row.mode,
type: row.type,
hours: row.hours,
credits: row.credits,
lecturer_id: row.lecturer_id || '',
dept_ids: [...((row.dept_ids as unknown as string[]) || [])],
start_at: '',
location: '',
notify_mode: 'immediate',
}
// 课程资产侧信息(000156):适合人员/课件/试题随 library_course_id 展示
loadCourseBanks(row.library_course_id || '')
// 000165 复测:打开详情即回源课程管理最新信息(他人刚更新的课件/试题名称跟随变更);
// 计划未挂接条目时按课程名补挂既有条目,避免资产维护另建重复空条目
void refreshDetailLibraryCourse(row)
// 授课时间回填:优先课程授课时间(期望月份默认值 YYYY-MM 展开为当月 1 日),否则回退最近场次排期
const list = courseSessions.value[row.id] || []
const nearest = list.find((s) => s.status === 'scheduled' && s.start_at) || list.find((s) => s.start_at) || list[0]
if (row.mode === 'offline' && row.teach_time) {
editForm.value.start_at = teachTimeToPicker(row.teach_time)
} else if (nearest) {
editForm.value.start_at = fmtPicker(nearest.start_at)
}
if (nearest) {
editForm.value.location = nearest.location || ''
editForm.value.notify_mode = nearest.notify_mode === 'day_before' ? 'day_before' : 'immediate'
}
// 需求确认同步值:计划培训时间/授课地点默认带入可编辑的授课时间/授课地点(场次未排期时);
// 参加人员按姓名匹配员工预选(与场次学员名单合一),选择方式重置为按人员
const participantNames = (row.post_scope || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
const matchedIds = members.value
.filter((m) => participantNames.includes(m.user_name || ''))
.map((m) => m.id)
// [2026-11 需求] 参加人员为空但已选「适用部门」时,打开即自动带入部门人员
// (推送与应培名单以「参加人员」为准,带入后可增删)
const deptIds = (row.dept_ids as unknown as string[]) || []
const prefillIds = matchedIds.length || participantNames.length
? matchedIds
: deptIds.length ? members.value.filter((m) => deptIds.includes(m.dept_id)).map((m) => m.id) : []
demandSync.value = { participantIds: prefillIds, initialIds: [] }
participantMode.value = 'member'
participantDeptIds.value = []
participantPostIds.value = []
// 初始解析结果(按人员模式下与预选一致),保存时据此判断选择是否变化
demandSync.value.initialIds = resolvedParticipantMembers.value.map((m) => m.id)
if (row.mode === 'offline' && !editForm.value.start_at && row.planned_time) {
editForm.value.start_at = `${(row.planned_time || '').slice(0, 10)} 00:00`
}
if (row.mode === 'offline' && !editForm.value.location && row.location) {
editForm.value.location = row.location
}
// 线上课/无场次课程:懒建名单挂靠场次,使「场次与学员名单」对线上线下都可用
if (!list.length) {
await ensureCourseSession(row.id, {
mode: row.mode,
lecturerId: row.lecturer_id || undefined,
location: row.mode === 'online' ? '线上' : '',
hours: row.hours,
})
}
}
// 详情弹窗(未关联课程管理的计划)选定课程:带出课程信息并锁定(形式除外,
// 000162 计划形式独立可改),适用部门变化经 watcher 自动同步参加人员名单
const onDetailLibraryCourseChange = (libraryCourseId: unknown) => {
const lc = libraryCourses.value.find((c) => c.id === libraryCourseId)
editForm.value.name = lc?.name || ''
editForm.value.type = lc?.type === 'elective' ? 'elective' : 'required'
editForm.value.hours = lc?.hours || editForm.value.hours
editForm.value.lecturer_id = lc?.lecturer_id || ''
editForm.value.dept_ids = lc?.owner_dept_id ? [lc.owner_dept_id] : []
// 课程资产侧信息随换选刷新(适合人员/课件/试题,000156)
loadCourseBanks(editForm.value.library_course_id)
}
// t-date-picker(带时间)的回显格式
const fmtPicker = (iso: string | null) => {
if (!iso) return ''
const d = new Date(iso)
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
}
// 月份粒度的授课时间(YYYY-MM,需求期望月份默认值)展开为日期选择器可用的当月 1 日
const teachTimeToPicker = (value: string) =>
/^\d{4}-\d{2}$/.test(value) ? `${value}-01 09:00:00` : value
// 授课时间入库格式:线下取日期选择器(去秒),线上留空(长期)
const teachTimeOf = (form: { mode: string; start_at: string }) => {
if (form.mode !== 'offline' || !form.start_at) return ''
const parts = form.start_at.split(':')
return parts.length > 2 ? parts.slice(0, 2).join(':') : form.start_at
}
// 课程修改记录列
const changeLogColumns = [
{ colKey: 'changes', title: '变更明细' },
{ colKey: 'operator', title: '操作人', width: 110 },
{ colKey: 'created_at', title: '修改时间', width: 170 },
]
// ---- 场次与学员名单(线上线下通用) ----
const refreshSessionCache = async () => {
try {
const res = await listSessions({ year: 0, month: 0 })
sessions.value = unwrap(res) || []
} catch {
/* 保持旧缓存 */
}
}
// 确保课程存在可挂学员名单的场次:
// 线上课默认创建「线上」场次;线下课按时间/地点创建。已有场次直接返回第一场。
const ensureCourseSession = async (
courseId: string,
opts: { mode: string; lecturerId?: string; startAt?: string; location?: string; hours?: number },
) => {
const existing = courseSessions.value[courseId] || []
if (existing.length) return existing[0]
const offline = opts.mode === 'offline'
await saveSession({
course_id: courseId,
start_at: offline && opts.startAt ? new Date(opts.startAt).toISOString() : '',
end_at: offline && opts.startAt ? new Date(new Date(opts.startAt).getTime() + (opts.hours || 0) * 3600 * 1000).toISOString() : '',
location: offline ? (opts.location || '') : '线上',
capacity: 0,
lecturer_id: opts.lecturerId || undefined,
})
await refreshSessionCache()
return (courseSessions.value[courseId] || [])[0]
}
// 保存课程信息:基础信息走 saveCourse;线下课的授课时间/地点同步最近一场排期(无则创建);
// 学员名单以「参加人员」为准同步(适用部门选择时已自动带入,可增删)。
// 详情保存载荷(000158 抽取复用):UpdateCourse 为全量列更新,未编辑字段必须
// 回填原值,否则 tags/material_ids 会写 NULL,status/exam_enabled 会被零值覆盖。
// 000161 讲师解析:名册 id 直接用;非名册值(creatable 直接输入)按外部讲师姓名落库
const resolveDetailLecturer = (row: TrainingCourse) => {
const v = (editForm.value.lecturer_id || '').trim()
if (!v) return { lecturerId: '', external: row.lecturer_external || '' }
if (lecturers.value.some((l) => l.id === v)) return { lecturerId: v, external: '' }
return { lecturerId: '', external: v }
}
const detailSavePayload = (row: TrainingCourse) => {
const lecturer = resolveDetailLecturer(row)
return ({
id: row.id,
code: row.code,
name: editForm.value.name,
mode: editForm.value.mode,
type: editForm.value.type,
hours: editForm.value.hours,
credits: editForm.value.credits,
exam_enabled: row.exam_enabled,
dept_ids: editForm.value.dept_ids,
lecturer_id: lecturer.lecturerId || undefined,
// 参加人员:详情表单可编辑,保存随课程信息落库并同步场次学员名单
post_scope: resolvedParticipantMembers.value.map((m) => m.user_name || m.employee_no).join('、'),
description: row.description,
material_ids: row.material_ids,
tags: row.tags,
status: row.status,
teach_time: teachTimeOf(editForm.value),
planned_time: row.planned_time || '',
// 其余需求确认同步字段原样透传(详情表单不编辑,防止保存时被零值覆盖丢失)
train_type: row.train_type || '',
plant: row.plant || '',
// 000163:授课地点随课程落库(发布校验读 course.location;此前只写场次,
// 「调整」里改了授课地点发布仍提示未设置)
location: editForm.value.mode === 'offline'
? (editForm.value.location.trim() || row.location || '')
: (row.location || ''),
session_count: row.session_count || 0,
// 000161 讲师计划侧可改:名册 id 或外部讲师姓名
lecturer_external: lecturer.external,
remark: row.remark || '',
// 课程管理关联(000161 可切换;切换后类型/形式随新课程带出)
library_course_id: editForm.value.library_course_id || row.library_course_id || '',
})
}
const onSaveDetail = async () => {
const row = activeCourse.value
if (!row) return
// 线下计划须指定讲师(名册 id 或外部姓名;发布时后端也会强制校验)
const lecturer = resolveDetailLecturer(row)
if (editForm.value.mode === 'offline' && !lecturer.lecturerId && !lecturer.external) {
MessagePlugin.warning('线下计划需先指定讲师(从名册选择或输入外部讲师姓名)')
return
}
detailSaving.value = true
try {
// 参加人员名单按解析结果变化同步(见下方 setEnrollments)
const selectedMembers = resolvedParticipantMembers.value
const resolvedIds = selectedMembers.map((m) => m.id)
const rosterChanged =
resolvedIds.length !== demandSync.value.initialIds.length ||
resolvedIds.some((id) => !demandSync.value.initialIds.includes(id))
await saveCourse(detailSavePayload(row))
const sessionOpts = {
mode: editForm.value.mode,
lecturerId: lecturer.lecturerId || undefined,
startAt: editForm.value.start_at,
location: editForm.value.location,
hours: editForm.value.hours,
}
if (editForm.value.mode === 'offline' && (editForm.value.start_at || editForm.value.location)) {
const existing = (courseSessions.value[row.id] || [])[0]
await saveSession({
id: existing?.id,
course_id: row.id,
start_at: editForm.value.start_at ? new Date(editForm.value.start_at).toISOString() : '',
end_at: editForm.value.start_at ? new Date(new Date(editForm.value.start_at).getTime() + editForm.value.hours * 3600 * 1000).toISOString() : '',
location: editForm.value.location,
capacity: existing?.capacity ?? 0,
lecturer_id: lecturer.lecturerId || undefined,
// [2026-11 推学员] 编辑排课时同步通知方式
notify_mode: editForm.value.notify_mode,
})
await refreshSessionCache()
} else {
await ensureCourseSession(row.id, sessionOpts)
}
// [2026-11 需求] 学员名单以「参加人员」为准(与场次学员名单合一):
// 选择有变化即按选中员工覆盖名单(含清空);未变化且有选中时幂等重写,
// 兜底补齐历史课程空的名单(ReplaceEnrollments 对保留成员不重置状态)
if (rosterChanged || resolvedIds.length) {
const session = await ensureCourseSession(row.id, sessionOpts)
if (session) {
await setEnrollments(session.id, resolvedIds)
await refreshSessionCache()
}
}
MessagePlugin.success(
(row.plan_code ? `计划 ${row.plan_code} 已保存` : '计划信息已保存') +
(rosterChanged || resolvedIds.length ? ',学员名单已按「参加人员」同步' : ''),
)
sessionsVisible.value = false
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
} finally {
detailSaving.value = false
}
}
// 「维护课程」直达:工作台「我的课程」讲师卡片携 ?courseId= 跳入,
// 列表加载完成后自动打开该课的计划详情弹窗(找不到对应计划则停留在列表)。
// route 做可空防御:预览 harness 等无路由挂载场景不阻断面板渲染。
const route = useRoute()
const openDetailFromRoute = () => {
const id = String(route?.query?.courseId || '')
if (!id) return
const row = courses.value.find((c) => c.id === id)
if (row) openDetail(row)
}
onMounted(async () => {
await loadAll()
openDetailFromRoute()
})
// 已在本页时从工作台再点另一门课(query 变化但组件不重挂载)
watch(() => route?.query?.courseId, openDetailFromRoute)
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.panel-box {
.training-panel-box();
}
// 表单项内提示文案(bank-hint/form-hint)统一另起一行展示在控件下方
.course-panel {
.training-form-hints-below();
}
// 满屏列表布局(000164):页头固定,面板占满页身剩余高度,
// 筛选区/表头/分页固定,仅表格数据区滚动
.course-panel {
.training-fill-panel();
}
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 关联题库:下拉 + 试题模板下载指引
.bank-field {
width: 100%;
}
// 课程详情弹窗:信息编辑区与场次区分隔
.detail-form {
margin-bottom: 6px;
padding-bottom: 12px;
border-bottom: 1px solid var(--td-component-stroke);
}
.detail-section-title {
margin: 6px 0 8px;
font-weight: 600;
font-size: var(--app-text-md);
}
.detail-save-hint {
margin-top: 0;
margin-left: 10px;
}
// 关联课件行:形式标签 + 名称 + 知识库同步标记
.material-row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 0;
border-bottom: 1px dashed var(--td-component-stroke);
}
.material-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--app-text-md);
}
.material-add-bar {
margin-top: 8px;
}
// 学员名单弹窗:选择方式页签 + 预览
.roster-mode {
margin-bottom: 10px;
}
.roster-preview {
margin-top: 8px;
}
// 名单明细:将写入的员工 tag 列表,超出滚动
.roster-detail {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-height: 132px;
overflow-y: auto;
padding: 2px 0;
}
.roster-tag {
flex-shrink: 0;
}
// 关联题库:题库 Excel 上传行与模式区
.bank-picker-body {
margin-top: 8px;
}
.bank-upload-row {
display: flex;
align-items: center;
gap: 8px;
min-height: 32px;
}
.bank-upload-input {
display: none;
}
.bank-upload-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-text-color-primary);
font-size: var(--app-text-sm);
}
.bank-upload-placeholder {
flex: 1;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// AI 生成试题抽屉:工具条 + 可编辑题目卡片
.gen-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
&__hint {
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
}
.gen-question {
padding: 10px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
margin-bottom: 10px;
&__head {
display: flex;
align-items: center;
gap: 8px;
}
&__options {
margin-top: 8px;
display: flex;
flex-direction: column;
gap: 6px;
}
&__opt {
display: flex;
align-items: center;
gap: 8px;
}
&__letter {
flex-shrink: 0;
width: 20px;
font-weight: 600;
color: var(--td-text-color-secondary);
}
&__meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-top: 8px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
&__meta-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
}
.gen-add-btn {
margin-top: 4px;
}
// 弹窗底部保存条
.detail-save-bar {
display: flex;
align-items: center;
gap: 10px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--td-component-stroke);
}
.detail-save-hint {
margin-top: 0;
flex: 1;
}
// 课程资产行(000156):课件/试题展示 + 「更换」按钮一行排布;
// 隐藏的原生 file input 供「更换课件」触发系统选择框
.asset-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.asset-value {
flex: 1;
}
.asset-relink {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
margin-top: 8px;
}
.hidden-file-input {
display: none;
}
// 列表行高固定两行:超长文案(课程名称/部门/地点)双行截断
// 修改记录弹窗:字段级变更明细行
.change-line {
padding: 2px 0;
font-size: var(--app-text-md);
overflow-wrap: anywhere;
}
// 列表单元格内容垂直居中:用行内级 -webkit-inline-box 承接两行截断,
// 配合下方 .t-table__cell 的 vertical-align: middle,单行/双行内容均随行居中
.clamp-2 {
display: -webkit-inline-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-all;
line-height: 1.5;
vertical-align: middle;
}
// 学习/考试状态 tag 可点击跳转学习考试页
.status-link {
cursor: pointer;
&:hover {
opacity: 0.85;
}
}
// 课程名称可点击 → 培训签到页(与状态 tag 同款可点击观感,品牌色区分)
.course-name-link {
cursor: pointer;
color: var(--td-brand-color);
&:hover {
text-decoration: underline;
}
}
// 课程已下线标签(000163):紧跟课程名称,警示已下线课程不可再学习
.offline-flag {
margin-left: 6px;
}
.course-panel :deep(.t-table .t-table__cell) {
vertical-align: middle;
}
.bank-hint {
margin-top: 6px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.template-link {
color: var(--td-brand-color);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.session-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 4px;
border-bottom: 1px solid var(--td-component-border);
&__actions { display: flex; gap: 8px; }
}
.muted { color: var(--td-text-color-placeholder); font-size: var(--app-text-sm); }
/* 课程资产库查询条件行(名称/讲师/培训时间/状态) */
.course-filters {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
margin: 4px 0 12px;
}
.course-filter-count {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
}
</style>