Files
ai_academy/frontend/src/views/training/components/LibraryPanel.vue
T
runny 78e9787793
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
fix(超管权限):超管也放开导入跨部门、课程审批等!
2026-11-28 15:16:55 +08:00

2182 lines
93 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="library-panel">
<!-- 课程管理(课程资产主数据):月培训计划「课程名称」从本页课程选择;
课件与试题作为课程信息的一部分在本页维护(增删改查) -->
<div class="panel-box">
<div class="panel-box__header">
<span class="panel-box__title">课程管理</span>
<div class="panel-box__actions">
<t-button v-if="canManage" theme="primary" @click="openForm()">新增课程</t-button>
<t-button v-if="canManage" variant="outline" @click="importVisible = true">批量导入</t-button>
<t-button variant="outline" :loading="exporting" @click="onExport">导出</t-button>
</div>
</div>
<!-- 查询条件:课程编号/名称/分类/类型/形式/状态。列表全量加载(page_size=500),
企业内部数据量小,分类/类型/形式/状态过滤在前端本地完成,不新增后端查询参数。 -->
<div class="library-filters">
<t-input v-model="filters.keyword" placeholder="按课程编号/名称查询" clearable style="width: 200px" />
<t-select v-model="filters.category" placeholder="按分类查询" clearable style="width: 140px">
<t-option v-for="c in categoryOptions" :key="c" :value="c" :label="c" />
</t-select>
<t-select v-model="filters.type" placeholder="按类型查询" clearable style="width: 120px">
<t-option value="required" label="必修课" />
<t-option value="elective" label="选修课" />
</t-select>
<t-select v-model="filters.mode" placeholder="按线上/线下查询" clearable style="width: 130px">
<t-option value="offline" label="线下" />
<t-option value="online" label="线上" />
</t-select>
<!-- 按状态查询(测试反馈 2026-11-26):审核状态列(待审核/已审核) -->
<t-select v-model="filters.status" placeholder="按状态查询" clearable style="width: 120px">
<t-option value="pending" label="待审核" />
<t-option value="confirmed" label="已审核" />
</t-select>
<t-button variant="text" theme="primary" size="small" @click="resetFilters">重置</t-button>
<span class="library-filter-count">共 {{ filteredItems.length }} 门</span>
<!-- 批量操作(000157):审核/删除仅课长/经理限本部门(超级管理员放开跨部门),
且普通角色仅待审核行可删 -->
<t-button
v-if="canVerify" variant="outline" theme="primary" size="small"
:disabled="!selectedKeys.length" :loading="batchSaving" @click="onBatchVerify"
>批量审核</t-button>
<t-button
v-if="canDelete" variant="outline" theme="danger" size="small"
:disabled="!selectedKeys.length" :loading="batchSaving" @click="onBatchDelete"
>批量删除</t-button>
<span v-if="selectedKeys.length" class="library-filter-count">已选 {{ selectedKeys.length }} 项</span>
</div>
<!-- 表格滚动区:面板满屏,筛选/表头/分页固定,仅数据行滚动(height=100% 启用固定表头) -->
<div class="table-scroll">
<t-table
v-model:selected-row-keys="selectedKeys"
:data="pagedItems" :columns="columns" row-key="id" size="small" height="100%" :loading="loading"
>
<template #code="{ row }">{{ row.code || '-' }}</template>
<template #name="{ row }"><span class="clamp-2">{{ row.name }}</span></template>
<template #description="{ row }">
<t-tooltip v-if="row.description" :content="row.description">
<span class="cell-ellipsis">{{ row.description }}</span>
</t-tooltip>
<span v-else>-</span>
</template>
<!-- 适合人员备注(000165):承接年/月培训计划「适合人员」,只做展示 -->
<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 #category="{ row }">
<t-tag v-if="row.category" theme="primary" variant="light" size="small">{{ row.category }}</t-tag>
<span v-else>-</span>
</template>
<template #type="{ row }">
<t-tag :theme="row.type === 'elective' ? 'default' : 'warning'" variant="light" size="small">
{{ row.type === 'elective' ? '选修课' : '必修课' }}
</t-tag>
</template>
<template #mode="{ row }">
<t-tag :theme="row.mode === 'online' ? 'primary' : 'default'" variant="light" size="small">
{{ row.mode === 'online' ? '线上' : '线下' }}
</t-tag>
</template>
<template #lecturer="{ row }">{{ lecturerText(row) }}</template>
<template #hours="{ row }">{{ row.hours ? `${row.hours} 学时` : '-' }}</template>
<template #owner_dept="{ row }">
<span v-if="row.owner_dept_name" class="cell-ellipsis" :title="row.owner_dept_name">{{ row.owner_dept_name }}</span>
<span v-else>-</span>
</template>
<template #suitable_members="{ row }">
<!-- 课程权限(000163,原「适合人员」):部门+人员展示文本 -->
<span v-if="permissionText(row)" class="cell-ellipsis" :title="permissionText(row)">{{ permissionText(row) }}</span>
<span v-else>-</span>
</template>
<template #material="{ row }">
<!-- 课件只展示有/无:有=已上传文件或已挂接知识库课件,点击直达课件管理抽屉 -->
<t-tag v-if="hasMaterial(row)" theme="success" variant="light" size="small" class="cell-link" @click="openMaterialDrawer(row)">有</t-tag>
<t-tag v-else theme="default" variant="light" size="small">无</t-tag>
</template>
<template #question="{ row }">
<!-- 试题只展示有/无:有=课程已关联题库,点击直达试题管理抽屉 -->
<t-tag v-if="(row.question_bank_count || 0) > 0" theme="success" variant="light" size="small" class="cell-link" @click="openQuestions(row)">有</t-tag>
<t-tag v-else theme="default" variant="light" size="small">无</t-tag>
</template>
<template #created_at="{ row }">{{ fmtBeijingTime(row.created_at) || '-' }}</template>
<!-- 创建人(联查 users):记录课程由谁录入 -->
<template #creator_name="{ row }">{{ row.creator_name || '-' }}</template>
<template #publish_status="{ row }">
<t-tag
:theme="row.publish_status === 'published' ? 'success' : row.publish_status === 'offline' ? 'default' : 'warning'"
variant="light" size="small"
>{{ publishStatusText(row.publish_status) }}</t-tag>
</template>
<!-- 审核状态(000157/000163):新增/编辑后待审核,课长/经理审核确认后
即自动发布(无需再点发布) -->
<template #verify_status="{ row }">
<t-tag :theme="row.verify_status === 'confirmed' ? 'success' : 'warning'" variant="light" size="small">
{{ row.verify_status === 'confirmed' ? '已审核' : '待审核' }}
</t-tag>
</template>
<template #op="{ row }">
<t-button v-if="canEditCourse(row)" variant="text" theme="primary" size="small" @click="openForm(row)">编辑</t-button>
<t-button variant="text" size="small" @click="openMaterialDrawer(row)">课件</t-button>
<t-button variant="text" size="small" @click="openQuestions(row)">试题</t-button>
<t-popconfirm
v-if="canVerifyCourse(row)"
content="审核通过后将立即发布(权限范围内的部门和人员可在培训中心/培训计划中查看),确认审核通过?" theme="primary"
@confirm="onVerify(row)"
>
<t-button variant="text" theme="primary" size="small">审核</t-button>
</t-popconfirm>
<!-- 下线(000163):下线后课程不能再被使用 —— 和信课程撤回、计划不可
再选用、已建计划学习时提示「该课程已下线」;存量培训计划保留 -->
<t-popconfirm
v-if="canManage && row.publish_status === 'published'"
content="下线后该课程不能再被使用:培训中心「和信课程」不再展示,培训计划不可再选用,已建计划学习时提示「该课程已下线」(已有培训计划不会消失)。确定下线?" theme="danger"
@confirm="onSetPublishStatus(row, 'offline')"
>
<t-button variant="text" theme="danger" size="small">下线</t-button>
</t-popconfirm>
<t-popconfirm
v-if="canDeleteCourse(row)"
:content="row.verify_status === 'pending'
? '确定删除该课程?已创建的月培训计划不受影响。'
: '该课程已审核,删除后已创建的月培训计划不受影响但课程不可恢复,确定删除?'"
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="itemPage" v-model:page-size="itemPageSize" :total="itemTotal" />
</div>
<!-- 新增/编辑课程弹窗:分类/讲师支持下拉选择或手动输入(输入即保存为新分类/外部讲师) -->
<t-dialog v-model:visible="formVisible" :header="form.id ? `编辑课程 · ${form.name || ''}` : '新增课程'" width="600">
<t-form label-width="96">
<t-form-item v-if="form.id" label="课程编号">
<t-input :value="form.code || '-'" disabled />
</t-form-item>
<t-form-item label="课程名称" required>
<t-input v-model="form.name" placeholder="请输入课程名称" />
</t-form-item>
<t-form-item label="所属部门">
<!-- 对应需求表「主办单位」:默认创建人(当前登录人)所属部门,支持修改
(000165;审核前必填,审核校验兜底;仅传部门名时服务端按组织架构解析) -->
<t-select
v-model="form.owner_dept_id" clearable filterable
placeholder="默认当前登录人所属部门,可选其他部门" style="width: 100%"
>
<t-option v-for="d in depts" :key="d.id" :value="d.id" :label="d.name" />
</t-select>
</t-form-item>
<t-form-item label="说明">
<t-textarea v-model="form.description" placeholder="课程内容简介(选填)" :autosize="{ minRows: 2 }" />
</t-form-item>
<t-form-item label="适合人员">
<!-- 备注字段(000165):承接年/月培训计划的「适合人员」信息,只做展示,
不参与课程权限过滤;支持自定义录入 -->
<t-textarea
v-model="form.post_scope" placeholder="适合人员备注(选填,仅展示;可见范围请用「课程权限」控制)"
:maxlength="500" :autosize="{ minRows: 2 }"
/>
</t-form-item>
<t-form-item label="课程权限">
<!-- 000163 课程权限(原「适合人员」):默认所属部门;可同时选择部门和
人员,部门与其下人员互斥(选了部门即覆盖其全员,不能再重复选该
部门下的人员,可选其他部门人员);「全部」=全员可见互斥项。审核
后仅所选部门和人员可在月/年培训计划、课程管理、培训中心看到该课程。
000165 复测:TDesign 收集面板选项时先取独立 t-option 再取
option-group,与模板书写顺序无关 —— 改用 options 属性直出,
数组顺序即面板顺序,「全部(全员可见)」恒为第一项 -->
<t-select
v-model="permList" :options="permPanelOptions" multiple filterable clearable
:min-collapsed-num="8"
placeholder="默认所属部门;可同时选择部门和人员(部门与其下人员互斥)" style="width: 100%"
/>
</t-form-item>
<t-form-item label="分类">
<!-- creatable:配置中心「课程分类」预设之外,可直接输入新分类并保存 -->
<t-select v-model="form.category" clearable filterable creatable placeholder="选择或输入分类,如:专业技能类/通用技能类" style="width: 100%">
<t-option v-for="c in categoryOptions" :key="c" :value="c" :label="c" />
</t-select>
</t-form-item>
<t-form-item label="类型">
<t-select v-model="form.type" style="width: 100%">
<t-option value="required" label="必修课" />
<t-option value="elective" label="选修课" />
</t-select>
</t-form-item>
<t-form-item label="线上/线下">
<t-select v-model="form.mode" style="width: 100%">
<t-option value="offline" label="线下" />
<t-option value="online" label="线上" />
</t-select>
</t-form-item>
<t-form-item label="讲师">
<!-- creatable:从员工名册选择,或直接输入外部讲师姓名(保存时自动区分) -->
<t-select v-model="form.lecturer" clearable filterable creatable placeholder="从员工名册选择,或直接输入外部讲师姓名" style="width: 100%">
<t-option v-for="o in lecturerSelectOptions" :key="o.value" :value="o.value" :label="o.label" />
</t-select>
</t-form-item>
<t-form-item label="时长(学时)">
<t-input-number v-model="form.hours" :min="0" :step="0.5" style="width: 100%" />
</t-form-item>
</t-form>
<div class="form-hint">分类选项由配置中心「课程分类」维护,支持手动输入保存;讲师可为员工名册内人员或外部讲师;所属部门与课程权限默认当前登录人所属部门,均可修改(审核时校验课程名称、所属部门、课程权限、课件必填);「适合人员」为备注字段,承接年/月培训计划的适合人员信息,仅做展示、不影响可见范围;课件上传/预览/下载经列表「课件」入口、试题经列表「试题」入口维护。</div>
<template #footer>
<t-button variant="outline" @click="formVisible = false">取消</t-button>
<t-button theme="primary" :loading="saving" @click="onSave">保存</t-button>
</template>
</t-dialog>
<!-- 批量导入弹窗:下载模板填写后上传 Excel(前端解析,所属部门/讲师按名册自动匹配) -->
<t-dialog v-model:visible="importVisible" header="批量导入课程(下载模板填写后导入)" width="620">
<div class="import-row">
<t-button variant="outline" @click="downloadTrainingTemplate(COURSE_LIBRARY_TEMPLATE_KEY)">下载课程管理导入模板</t-button>
<span class="import-file">
或上传填写好的模板 Excel:<input type="file" accept=".xlsx,.xls" @change="onImportExcel" />
</span>
</div>
<div class="form-hint">
模板列序(000165 复测,无课件收集列,课件导入后在列表「课件」入口上传维护):所属部门(第一列,下拉选择组织架构部门)/课程名称(下拉可选课程管理已有课程,新课程直接填写,不强制)/讲师(下拉选系统员工或直接输入外部姓名)/课程权限/课程分类/类型(必修课或选修课)/线上或线下/时长(学时)/课程说明/适合人员备注;
课程权限列填「全部」或部门/人员名(与课程权限下拉同口径,旧模板「适合人员」列同样兼容);适合人员备注列仅做展示说明;课程分类可填配置中心预设分类或自定义分类,导入后保存;课程编号由系统自动生成。
</div>
<template #footer>
<t-button variant="outline" @click="importVisible = false">关闭</t-button>
</template>
</t-dialog>
<!-- 课件管理抽屉:上传/知识库选择/预览/下载/移除(交互与试题维护抽屉同风格) -->
<t-drawer
v-model:visible="materialVisible"
:header="`课件管理 · ${materialCourse?.name || ''}${materialCourse?.code ? `(${materialCourse.code})` : ''}`"
size="72%"
placement="right"
attach="body"
:z-index="2600"
:footer="false"
>
<div class="bank-toolbar">
<t-radio-group :value="materialSourceMode" variant="default-filled" size="small" @change="onMaterialModeChange">
<t-radio-button value="upload">上传课件</t-radio-button>
<t-radio-button value="kb">从知识库选择</t-radio-button>
</t-radio-group>
<template v-if="materialSourceMode === 'upload'">
<!-- 000164 多课件:支持一次选择多个文件,逐个追加为课件条目(不替换既有课件) -->
<input ref="materialFileInputRef" type="file" multiple class="bank-upload-input" @change="onMaterialPicked" />
<t-button variant="outline" size="small" @click="materialFileInputRef?.click()">选择文件</t-button>
<span v-if="materialFiles.length" class="bank-file-name">已选 {{ materialFiles.length }} 个文件</span>
<span v-else class="bank-file-placeholder">未选择文件</span>
<t-button theme="primary" size="small" :loading="materialUploading" :disabled="!materialFiles.length" @click="onUploadMaterial">上传并关联课件</t-button>
</template>
<template v-else>
<t-select
v-model="materialKbDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(课件)」知识库中的课件文档"
style="width: 260px"
size="small"
>
<t-option v-for="d in kbDocs" :key="d.id" :value="d.id" :label="d.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="materialUploading" :disabled="!materialKbDocId" @click="onAttachMaterialKb">确定挂接</t-button>
</template>
</div>
<div class="form-hint">
数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;课件上传/挂接按条目追加,支持多个课件不再整体替换(000164);课件变更不回「待审核」,即时生效(000165 复测);文档类课件上传后自动同步知识库(月培训计划带出/AI 出题/对话问答共用);课程发布前必须已上传课件。
</div>
<t-table v-if="materialCourse" :data="materialRows" :columns="materialColumns" row-key="mid" size="small">
<template #size="{ row }">{{ row.size ? fmtSize(row.size) : '-' }}</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="onPreviewMaterial(row)">预览</t-button>
<t-button variant="text" theme="primary" size="small" @click="onDownloadMaterial(materialCourse, row)">下载</t-button>
<t-popconfirm content="移除后不可恢复(不影响课程审核状态),确定移除该课件?" theme="danger" @confirm="onRemoveMaterial(row)">
<t-button variant="text" theme="danger" size="small">移除</t-button>
</t-popconfirm>
</template>
</t-table>
<t-empty
v-if="materialCourse && !materialRows.length"
description="暂无课件,可在上方上传文件(可多选)或从知识库选择;课程发布前必须已上传课件"
/>
</t-drawer>
<!-- 试题管理抽屉:题库与试题随课程条目增删改查(上传 Excel/知识库导入/AI 出题) -->
<t-drawer
v-model:visible="questionsVisible"
:header="`试题管理 · ${questionsCourse?.name || ''}${questionsCourse?.code ? `(${questionsCourse.code})` : ''}`"
size="72%"
placement="right"
attach="body"
:z-index="2600"
:footer="false"
>
<div class="bank-toolbar">
<t-radio-group :value="bankSourceMode" variant="default-filled" size="small" @change="onBankModeChange">
<t-radio-button value="upload">上传试题</t-radio-button>
<t-radio-button value="kb">从知识库选择</t-radio-button>
<t-radio-button value="ai">AI课件生成试题</t-radio-button>
</t-radio-group>
<template v-if="bankSourceMode === 'upload'">
<input ref="bankFileInputRef" type="file" accept=".xlsx,.xls" class="bank-upload-input" @change="onBankFileChange" />
<t-button variant="outline" size="small" @click="bankFileInputRef?.click()">选择文件</t-button>
<span v-if="bankFile" class="bank-file-name">{{ bankFile.name }}</span>
<span v-else class="bank-file-placeholder">未选择文件</span>
<t-button theme="primary" size="small" :loading="bankImporting" :disabled="!bankFile" @click="onImportBankExcel">导入并关联题库</t-button>
</template>
<template v-else-if="bankSourceMode === 'kb'">
<t-select
v-model="bankKbDocId"
filterable
clearable
:loading="bankKbLoading"
placeholder="选择「企业培训(题库)」中的试题 Excel"
style="width: 240px"
size="small"
>
<t-option v-for="d in bankKbDocs" :key="d.id" :value="d.id" :label="d.file_name" />
</t-select>
<t-button theme="primary" size="small" :loading="bankImporting" :disabled="!bankKbDocId" @click="onImportBankKb">导入并关联题库</t-button>
</template>
<template v-else>
<t-input-number v-model="genCount" :min="1" :max="30" :step="1" size="small" style="width: 104px" />
<t-button theme="primary" size="small" :loading="genLoading" :disabled="!questionsCourse?.knowledge_id" @click="onGenerateQuestions">AI 生成试题</t-button>
</template>
<t-button variant="outline" size="small" @click="downloadTrainingTemplate(QUESTION_TEMPLATE_KEY)">下载试题模板</t-button>
</div>
<div class="form-hint">
同名题库重新导入会整体替换;解析 Excel 题目自动建题库并挂到本课程(月培训计划选课后自动具备随堂考试能力);Excel 原件同步知识库「企业培训(题库)」;课件已上传时文档同步知识库「企业培训(课件)」,支持 AI 出题与对话问答。
</div>
<t-table :data="pagedBanks" :columns="bankColumns" row-key="id" size="small" :loading="banksLoading">
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="selectBank(row)">查看试题</t-button>
<t-popconfirm content="删除题库将连带删除全部题目与试卷,确定?" theme="danger" @confirm="onDeleteBank(row)">
<t-button variant="text" theme="danger" size="small">删除题库</t-button>
</t-popconfirm>
</template>
</t-table>
<TrainingPagination v-model:current="bankPage" v-model:page-size="bankPageSize" :total="bankTotal" />
<t-empty v-if="!banksLoading && !banks.length" description="暂无题库,可在上方上传 Excel / 从知识库导入 / AI 生成" />
<template v-if="activeBank">
<div class="bank-section-title">
题库「{{ activeBank.name }}」({{ activeBank.question_count }}题)
<t-button theme="primary" variant="outline" size="small" class="bank-section-add" @click="openQuestionForm()">+ 新增试题</t-button>
</div>
<t-table :data="pagedQuestions" :columns="questionColumns" row-key="id" size="small" :loading="questionsLoading">
<template #type="{ row }">{{ questionTypeText(row.type) }}</template>
<template #stem="{ row }">
<t-tooltip v-if="row.stem" :content="row.stem">
<span class="cell-ellipsis">{{ row.stem }}</span>
</t-tooltip>
<span v-else>-</span>
</template>
<template #answer="{ row }">{{ questionAnswerText(row) }}</template>
<template #op="{ row }">
<t-button variant="text" theme="primary" size="small" @click="openQuestionForm(row)">编辑</t-button>
<t-popconfirm content="确定删除该试题?" theme="danger" @confirm="onDeleteQuestion(row)">
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
</template>
</t-table>
<TrainingPagination v-model:current="questionPage" v-model:page-size="questionPageSize" :total="questionTotal" />
<t-empty v-if="!questionsLoading && !questions.length" description="该题库暂无试题,可新增或重新导入" />
</template>
</t-drawer>
<!-- 单题新增/编辑弹窗 -->
<t-dialog
v-model:visible="questionFormVisible"
:header="questionForm.id ? '编辑试题' : '新增试题'"
width="640"
attach="body"
:z-index="3000"
>
<t-form label-width="90">
<t-form-item label="题型">
<t-radio-group v-model="questionForm.type" variant="default-filled" @change="onQuestionTypeChange">
<t-radio-button value="single">单选</t-radio-button>
<t-radio-button value="multiple">多选</t-radio-button>
<t-radio-button value="judge">判断</t-radio-button>
</t-radio-group>
</t-form-item>
<t-form-item label="题干" required>
<t-textarea v-model="questionForm.stem" placeholder="请输入题目内容" :autosize="{ minRows: 2 }" />
</t-form-item>
<t-form-item v-if="questionForm.type !== 'judge'" label="选项">
<div class="question-options">
<div v-for="(opt, oi) in questionForm.options" :key="oi" class="question-option-row">
<span class="question-option-letter">{{ letterAt(oi) }}</span>
<t-input v-model="questionForm.options[oi]" size="small" style="flex: 1; min-width: 0" />
<t-button v-if="questionForm.options.length > 2" variant="text" size="small" @click="questionForm.options.splice(oi, 1)">×</t-button>
</div>
<t-button v-if="questionForm.options.length < 6" variant="text" size="small" @click="questionForm.options.push('')">+ 选项</t-button>
</div>
</t-form-item>
<t-form-item label="答案" required>
<t-checkbox-group
v-if="questionForm.type === 'multiple'"
:value="questionForm.answer.split('').filter(Boolean)"
@change="(v: any) => (questionForm.answer = (v as string[]).slice().sort().join(''))"
>
<t-checkbox v-for="(_, oi) in questionForm.options" :key="oi" :value="letterAt(oi)">{{ letterAt(oi) }}</t-checkbox>
</t-checkbox-group>
<t-select v-else v-model="questionForm.answer" style="width: 120px">
<template v-if="questionForm.type === 'judge'">
<t-option value="A" label="对" />
<t-option value="B" label="错" />
</template>
<template v-else>
<t-option v-for="(_, oi) in questionForm.options" :key="oi" :value="letterAt(oi)" :label="letterAt(oi)" />
</template>
</t-select>
</t-form-item>
<t-form-item label="分值 / 难度">
<t-input-number v-model="questionForm.score" :min="0" :step="1" style="width: 46%" />
<t-select v-model="questionForm.difficulty" style="width: 46%; margin-left: 4%">
<t-option v-for="d in [1, 2, 3, 4, 5]" :key="d" :value="d" :label="`难度 ${d}`" />
</t-select>
</t-form-item>
<t-form-item label="知识点">
<t-input v-model="questionForm.knowledge_point" placeholder="考核点(选填)" />
</t-form-item>
<t-form-item label="解析">
<t-textarea v-model="questionForm.analysis" placeholder="答案解析(选填)" :autosize="{ minRows: 2 }" />
</t-form-item>
</t-form>
<template #footer>
<t-button variant="outline" @click="questionFormVisible = false">取消</t-button>
<t-button theme="primary" :loading="questionSaving" @click="onSaveQuestion">保存</t-button>
</template>
</t-dialog>
<!-- AI 生成试题预览:右侧抽屉,可编辑调整后「使用试题」建库 -->
<t-drawer
v-model:visible="genDrawerVisible"
header="AI 生成试题预览"
size="62%"
placement="right"
attach="body"
:z-index="3200"
>
<div class="gen-toolbar">
<span class="gen-toolbar__hint">共 {{ genQuestions.length }} 题,可编辑调整后使用</span>
<t-input v-model="genBankName" placeholder="题库名称(默认「课程名称+AI题库」)" size="small" style="width: 240px" />
</div>
<div v-for="(q, qi) in genQuestions" :key="qi" class="gen-question">
<div class="gen-question__head">
<t-select v-model="q.type" size="small" style="width: 92px" @change="onGenTypeChange(q)">
<t-option value="single" label="单选" />
<t-option value="multiple" label="多选" />
<t-option value="judge" label="判断" />
</t-select>
<t-input v-model="q.stem" placeholder="题干" size="small" style="flex: 1; min-width: 0" />
<t-button variant="text" theme="danger" size="small" @click="genQuestions.splice(qi, 1)">删除</t-button>
</div>
<div v-if="q.type !== 'judge'" class="gen-question__options">
<div v-for="(opt, oi) in q.options" :key="oi" class="gen-question__opt">
<span class="gen-question__letter">{{ letterAt(oi) }}</span>
<t-input v-model="q.options[oi]" size="small" style="flex: 1; min-width: 0" />
<t-button v-if="q.options.length > 2" variant="text" size="small" @click="q.options.splice(oi, 1)">×</t-button>
</div>
<t-button v-if="q.options.length < 6" variant="text" size="small" @click="q.options.push('')">+ 选项</t-button>
</div>
<div class="gen-question__meta">
<span v-if="q.type === 'multiple'" class="gen-question__meta-item">
多选答案:
<t-checkbox-group :value="multiAnswersOf(q)" @change="(v: any) => setMultiAnswer(q, v as string[])">
<t-checkbox v-for="(_, oi) in q.options" :key="oi" :value="letterAt(oi)">{{ letterAt(oi) }}</t-checkbox>
</t-checkbox-group>
</span>
<span v-else class="gen-question__meta-item">
答案:
<t-select v-model="q.answer" size="small" style="width: 84px">
<t-option
v-for="(_, oi) in (q.type === 'judge' ? q.options.slice(0, 2) : q.options)"
:key="oi"
:value="letterAt(oi)"
:label="letterAt(oi)"
/>
</t-select>
</span>
<span class="gen-question__meta-item">
知识点:
<t-input v-model="q.knowledge_point" size="small" style="width: 150px" />
</span>
<span class="gen-question__meta-item">
难度:
<t-select v-model="q.difficulty" size="small" style="width: 72px">
<t-option v-for="d in [1, 2, 3, 4, 5]" :key="d" :value="d" :label="`${d}`" />
</t-select>
</span>
</div>
</div>
<t-empty v-if="!genQuestions.length" description="暂无试题,可手动添加" />
<t-button variant="dashed" block class="gen-add-btn" @click="addGenQuestion">+ 手动添加试题</t-button>
<template #footer>
<t-button variant="outline" @click="genDrawerVisible = false">取消</t-button>
<t-button theme="primary" :loading="bankImporting" :disabled="!genQuestions.length" @click="onUseGeneratedQuestions">使用试题</t-button>
</template>
</t-drawer>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import * as XLSX from 'xlsx'
import { COURSE_LIBRARY_TEMPLATE_KEY, QUESTION_TEMPLATE_KEY, downloadTrainingTemplate } from '../trainingTemplates'
import { apiErrorMessage, get } from '@/utils/request'
import { fmtBeijingTime } from '@/utils/datetime'
import TrainingPagination from './TrainingPagination.vue'
import { useTrainingPager } from './useTrainingPager'
import {
attachCourseLibraryMaterialFromKb,
deleteCourseLibraryItem,
deleteQuestion,
deleteQuestionBank,
downloadCourseLibraryMaterial,
exportCourseLibrary,
fetchCourseCategories,
generateLibraryCourseQuestions,
getMyProfile,
getTrainingKnowledgeBases,
importCourseLibrary,
importGeneratedQuestionBank,
importLibraryCourseQuestionBank,
importQuestionBankFromKnowledge,
listCourseLibrary,
listDepts,
listLibraryCourseQuestionBanks,
listMembers,
listQuestions,
offlineCourseLibraryItem,
removeCourseLibraryMaterial,
saveCourseLibraryItem,
saveQuestion,
uploadCourseLibraryMaterial,
verifyCourseLibraryItems,
type TrainingDept,
type TrainingLibraryCourse,
type TrainingMember,
type TrainingQuestion,
type TrainingQuestionBank,
unwrap,
} from '@/api/training'
const props = defineProps<{ roles: string[]; admin?: boolean }>()
// 课程维护(新增/编辑/发布/导入/导出):人事/课长/讲师(roles 已按权限组展开,
// 经理经课长继承自动命中)。人事无审核/删除权限(000157)。
const canManage = computed(() => props.admin || props.roles.some((r) => r === 'hr' || r === 'supervisor' || r === 'lecturer'))
const loading = ref(false)
const saving = ref(false)
const exporting = ref(false)
const items = ref<TrainingLibraryCourse[]>([])
const members = ref<TrainingMember[]>([])
const depts = ref<TrainingDept[]>([])
// 课程分类选项 = 配置中心「课程分类」字典(fetchCourseCategories 缺失回退默认)
const configCategories = ref<string[]>([])
// 本人所在部门 id:新增课程「所属部门」默认当前登录用户所在部门(getMyProfile)
const myDeptId = ref('')
// 本人用户 id:学员「与我相关」课程的编辑权限判断(创建人/讲师为本人)
const myUserId = ref('')
// /training/members/me 联查返回的部门名(handler 000160 起填充)
const meDeptName = ref('')
// ---------------------------------------------------------------------------
// 课程权限(000163,原「适合人员」):部门 + 人员混合选择,默认所属部门;
// 部门与其下人员互斥(选了人事部即覆盖其全员,不能再选人事部下的人员,可选
// 其他部门人员);「全部」=全员可见互斥项。落库:perm_dept_ids/perm_user_ids
// 为逗号分隔 id,suitable_members 为部门名+人员名展示文本(存量口径兼容)。
// ---------------------------------------------------------------------------
const PERM_ALL = '__all__'
// 选项值编码:dept:<id> / user:<id> / PERM_ALL / 存量自由文本原值
const permList = ref<string[]>([])
// 部门选项(含 id 供互斥判定)
const permDeptOptions = computed(() =>
depts.value.map((d) => ({ value: `dept:${d.id}`, label: d.name || `部门${d.id}`, deptId: d.id })),
)
// 人员选项(含其部门 id:已选部门时该部门下人员置灰)
const permUserOptions = computed(() =>
members.value
.filter((m) => m.user_id)
.map((m) => ({
value: `user:${m.user_id}`,
label: [m.user_name || m.employee_no, m.dept_name].filter(Boolean).join(' · '),
deptId: m.dept_id || '',
})),
)
// 存量自由文本回显:permList 中既非「全部」也非 id 编码的旧值补为临时选项
const permLegacyExtras = computed(() =>
permList.value.filter((v) => v !== PERM_ALL && !v.startsWith('dept:') && !v.startsWith('user:')),
)
// 互斥置灰:「全部」已选时部门/人员全部置灰;人员选项在其所属部门已被选中时置灰
const permOptionDisabled = (o: { value: string; deptId?: string }) => {
if (permList.value.includes(PERM_ALL)) return o.value !== PERM_ALL
if (o.value.startsWith('user:') && o.deptId && permList.value.includes(`dept:${o.deptId}`)) return true
return false
}
// 下拉面板选项(000165 复测):TDesign 收集面板选项时先取独立 t-option 再取
// option-group,与模板书写顺序无关;改走 options 属性直出,数组顺序即面板
// 顺序 —— 「全部(全员可见)」恒为第一项,按部门/按人员分组随后(嵌套
// group/children 格式,组件按 children 识别分组),存量自由文本兜底最后;
// disabled 沿用互斥口径。
const permPanelOptions = computed(() => {
const deptChildren = permDeptOptions.value.map((o) => ({
label: o.label, value: o.value, disabled: permOptionDisabled(o),
}))
const userChildren = permUserOptions.value.map((o) => ({
label: o.label, value: o.value, disabled: permOptionDisabled(o),
}))
return [
{ label: '全部(全员可见)', value: PERM_ALL },
...(deptChildren.length ? [{ group: '按部门', children: deptChildren }] : []),
...(userChildren.length ? [{ group: '按人员', children: userChildren }] : []),
...permLegacyExtras.value.map((v) => ({
label: v, value: v, disabled: permList.value.includes(PERM_ALL),
})),
]
})
// 部门与其下人员互斥兜底(watch):勾选部门后自动移除该部门下已选人员;
// 「全部」与具体部门/人员互斥(勾全部清其余,勾其余移除全部)。
watch(permList, (list, prev) => {
if (list.includes(PERM_ALL) && list.length > 1) {
permList.value = (prev || []).includes(PERM_ALL) ? list.filter((v) => v !== PERM_ALL) : [PERM_ALL]
return
}
const deptIds = new Set(
list.filter((v) => v.startsWith('dept:')).map((v) => v.slice('dept:'.length)),
)
if (!deptIds.size) return
const dupUsers = list.filter((v) => {
if (!v.startsWith('user:')) return false
const opt = permUserOptions.value.find((o) => o.value === v)
return Boolean(opt?.deptId && deptIds.has(opt.deptId))
})
if (dupUsers.length) {
permList.value = list.filter((v) => !dupUsers.includes(v))
MessagePlugin.warning('所选部门已包含其下人员,已自动移除重复选择的人员')
}
})
const splitSuitable = (v: string) =>
(v || '').split(/[、,,;;]/).map((s) => s.trim()).filter(Boolean)
// 人员显示名(成员名册联查;未命中回退原始 id,避免标签显示为空)
const memberDisplayName = (userId: string) => {
const hit = members.value.find((m) => m.user_id === userId)
return hit?.user_name || hit?.employee_no || userId
}
// 行数据 → 课程权限选项值(回显):优先 perm 两列;存量课程回退解析
// suitable_members(部门名/人员名/「全部」,未命中文本原样保留)
const parsePermFromRow = (row?: TrainingLibraryCourse): string[] => {
if (!row) {
// 新增默认:课程权限 = 所属部门(创建人所在部门)
return myDeptId.value ? [`dept:${myDeptId.value}`] : []
}
const deptIds = (row.perm_dept_ids || '').split(',').map((s) => s.trim()).filter(Boolean)
const userIds = (row.perm_user_ids || '').split(',').map((s) => s.trim()).filter(Boolean)
if (deptIds.length || userIds.length) {
return [...deptIds.map((id) => `dept:${id}`), ...userIds.map((id) => `user:${id}`)]
}
const names = splitSuitable(row.suitable_members || '')
if (names.includes('全部')) return [PERM_ALL]
const out: string[] = []
for (const n of names) {
const dept = depts.value.find((d) => d.name === n)
if (dept) {
out.push(`dept:${dept.id}`)
continue
}
const member = members.value.find((m) => (m.user_name || '') === n)
if (member?.user_id) {
out.push(`user:${member.user_id}`)
continue
}
out.push(n)
}
// 000165:存量行权限为空时同样默认所属部门(优先行部门,无则当前登录人部门),
// 与「课程权限默认部门」口径一致,编辑补齐后再审核
if (!out.length) {
const fallback = row.owner_dept_id || myDeptId.value
if (fallback) out.push(`dept:${fallback}`)
}
return out
}
// permList → 落库三字段:perm_dept_ids/perm_user_ids(suitable_members 同步为
// 展示文本,兼容导出/需求模板 VLOOKUP 与存量匹配口径;「全部」=存量全员口径)
const permToFields = () => {
const deptIds: string[] = []
const userIds: string[] = []
const extraNames: string[] = []
for (const v of permList.value) {
if (v === PERM_ALL) continue
if (v.startsWith('dept:')) deptIds.push(v.slice('dept:'.length))
else if (v.startsWith('user:')) userIds.push(v.slice('user:'.length))
else extraNames.push(v)
}
const isAll = permList.value.includes(PERM_ALL)
const displayNames = [
...deptIds.map((id) => depts.value.find((d) => d.id === id)?.name || id),
...userIds.map(memberDisplayName),
...extraNames,
]
return {
perm_dept_ids: isAll ? '' : deptIds.join(','),
perm_user_ids: isAll ? '' : userIds.join(','),
suitable_members: isAll ? '全部' : displayNames.join('、'),
}
}
// 列表「课程权限」列展示文本:perm 两列解析为「部门、人员」;存量行回退原文本
const permissionText = (row: TrainingLibraryCourse) => {
if ((row.perm_dept_ids || '').trim() || (row.perm_user_ids || '').trim()) {
const deptNames = (row.perm_dept_ids || '').split(',').filter(Boolean).map((id) => depts.value.find((d) => d.id === id)?.name || id)
const userNames = (row.perm_user_ids || '').split(',').filter(Boolean).map(memberDisplayName)
return [...deptNames, ...userNames].join('、')
}
return row.suitable_members || ''
}
// 课程权限是否已设置(审核前置,000163:权限必填)
const hasPermSet = (row: TrainingLibraryCourse) =>
Boolean((row.perm_dept_ids || '').trim() || (row.perm_user_ids || '').trim() || (row.suitable_members || '').trim())
// 审核/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
// 跨部门审核/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
const canVerify = computed(() => props.roles.includes('supervisor'))
// 超级管理员职称角色(super_admin):继承全部权限组后可审批、发布、查看等所有
// 系统操作,并保留终态数据(已审核/已发布课程)删除权与课程跨部门审核权
// (后端 Delete/VerifyCourseLibraryItems 同口径放开跨部门)
const isSuperAdmin = computed(() => props.roles.includes('super_admin'))
const canDelete = computed(() => canVerify.value || isSuperAdmin.value)
// 仅本部门「待审核」课程可审核/删除;与后端 callerVerifyDeptScope 同口径:
// 无部门身份或课程所属部门与本人不一致时一律不可操作。超级管理员不限部门
// (待审核状态约束保留,与后端服务层审核校验同口径)。
const canVerifyCourse = (row: TrainingLibraryCourse) =>
(isSuperAdmin.value || canVerify.value) &&
row.verify_status === 'pending' &&
(isSuperAdmin.value ||
(Boolean(myDeptId.value) && Boolean(row.owner_dept_id) && row.owner_dept_id === myDeptId.value))
const canDeleteCourse = (row: TrainingLibraryCourse) => isSuperAdmin.value || canVerifyCourse(row)
// 编辑权限:维护角色可编辑可见课程;无维护角色的学员仅可编辑「与我相关」课程
// (本人创建或本人授课,后端兜底校验同口径)
const canEditCourse = (row: TrainingLibraryCourse) =>
canManage.value ||
(Boolean(myUserId.value) && (row.creator_id === myUserId.value || row.lecturer_id === myUserId.value))
// ---- 查询条件(编号/名称/分类/类型/形式/状态;列表全量加载,本地过滤) ----
const filters = ref({ keyword: '', category: '', type: '', mode: '', status: '' })
const resetFilters = () => {
filters.value = { keyword: '', category: '', type: '', mode: '', status: '' }
}
// 分类选项:配置中心字典 + 库内已有自定义分类(去重),供筛选与表单下拉共用
const categoryOptions = computed(() => {
const set = new Set(configCategories.value)
for (const item of items.value) {
if (item.category) set.add(item.category)
}
return [...set]
})
const filteredItems = computed(() => {
const kw = filters.value.keyword.trim().toLowerCase()
return items.value.filter((row) => {
if (kw && !`${row.code || ''} ${row.name || ''}`.toLowerCase().includes(kw)) return false
if (filters.value.category && row.category !== filters.value.category) return false
if (filters.value.type && row.type !== filters.value.type) return false
if (filters.value.mode && row.mode !== filters.value.mode) return false
if (filters.value.status && (row.verify_status || 'pending') !== filters.value.status) return false
return true
})
})
// 共用分页(000163):课程列表默认每页 15 条;查询条件变化后回到第 1 页
const {
page: itemPage,
pageSize: itemPageSize,
total: itemTotal,
paged: pagedItems,
reset: resetItemPage,
} = useTrainingPager(filteredItems)
// 查询条件变化(重置/筛选)后列表回到第 1 页
watch(filteredItems, resetItemPage)
const columns = [
// 批量勾选列(000157):配合批量审核/批量删除
{ colKey: 'row-select', type: 'multiple', width: 44 },
// 左侧列不固定(000154),列序 000165 调整:编号/名称/讲师/课件/试题/权限/
// 分类/类型/线上线下/时长/发布状态/创建时间/创建人/所属部门/说明(适合人员备注置尾)
{ colKey: 'code', title: '课程编号', width: 105 },
{ colKey: 'name', title: '课程名称', width: 170 },
{ colKey: 'lecturer', title: '讲师', width: 110 },
// 课件/试题只展示有/无:有=已上传课件或已关联题库,点击直达对应维护抽屉
{ colKey: 'material', title: '课件', width: 70 },
{ colKey: 'question', title: '试题', width: 70 },
{ colKey: 'suitable_members', title: '课程权限', width: 110 },
{ colKey: 'category', title: '分类', width: 120 },
{ colKey: 'type', title: '类型', width: 84 },
{ colKey: 'mode', title: '线上/线下', width: 92 },
{ colKey: 'hours', title: '时长', width: 84 },
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
{ colKey: 'publish_status', title: '发布状态', width: 90 },
{ colKey: 'created_at', title: '创建时间', width: 140 },
// 创建人(联查 users):记录课程录入人员
{ colKey: 'creator_name', title: '创建人', width: 96 },
{ colKey: 'owner_dept', title: '所属部门', width: 110 },
{ colKey: 'description', title: '说明', width: 200 },
// 适合人员备注(000165):承接年/月培训计划「适合人员」+ 自定义录入,只做展示
{ colKey: 'post_scope', title: '适合人员', width: 140 },
// 000165 右侧固定区再收窄:状态 72,操作 224(行内至多 5 个文本按钮,紧凑排布见样式)
{ colKey: 'verify_status', title: '状态', width: 72, fixed: 'right' },
{ colKey: 'op', title: '操作', width: 224, fixed: 'right', className: 'op-cell' },
]
const lecturerText = (row: TrainingLibraryCourse) =>
row.lecturer_name || row.lecturer_external || '-'
const loadAll = async () => {
loading.value = true
try {
const [lib, m, d, cats, me] = await Promise.all([
listCourseLibrary({ page_size: 500 }),
listMembers({ page_size: 500 }).catch(() => null),
listDepts().catch(() => null),
fetchCourseCategories(),
// 本人档案:新增课程「所属部门」默认当前登录用户所在部门
getMyProfile().catch(() => null),
])
items.value = unwrap(lib)?.items || []
members.value = (m && unwrap(m)?.items) || []
depts.value = (d && unwrap(d)) || []
configCategories.value = cats
const meBody = me && unwrap(me)
myDeptId.value = meBody?.dept_id || ''
myUserId.value = meBody?.user_id || ''
meDeptName.value = meBody?.dept_name || ''
} finally {
loading.value = false
}
}
// ---- 新增/编辑 ----
const formVisible = ref(false)
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析。
// material_name 为隐藏保留字段:课件维护移至「课件」抽屉后,编辑保存仍原值回传,
// 防止全量更新把名称登记误清(000162)。
const form = ref({
id: '',
code: '',
name: '',
owner_dept_id: '',
description: '',
suitable_members: '',
// 课程权限(000163):部门/人员 id 列表(逗号分隔),随保存落库
perm_dept_ids: '',
perm_user_ids: '',
// 适合人员备注(000165):承接年/月培训计划「适合人员」,只做展示,支持自定义录入
post_scope: '',
category: '',
type: 'required' as 'required' | 'elective',
// 新增默认「线上」(000162):线上课为常规形态;编辑随原值
mode: 'online' as 'offline' | 'online',
lecturer: '',
hours: 0,
material_name: '',
})
// ---- 「企业培训(课件)」知识库文档(课件抽屉「从知识库选择」数据源) ----
const kbDocs = ref<{ id: string; file_name: string }[]>([])
const kbDocsLoading = ref(false)
const coursewareKbRef = ref<{ id: string; name: string } | null>(null)
let kbDocsLoaded = false
// 拉取「企业培训(课件)」知识库文档列表(惰性加载一次)
const loadCoursewareKbDocs = async () => {
if (kbDocsLoaded) return
kbDocsLoading.value = true
try {
if (!coursewareKbRef.value) {
const res = await getTrainingKnowledgeBases()
coursewareKbRef.value = unwrap<any>(res)?.courseware || null
}
if (coursewareKbRef.value?.id) {
const res: any = await get(
`/api/v1/knowledge-bases/${encodeURIComponent(coursewareKbRef.value.id)}/knowledge?page=1&page_size=200`,
)
const body = res?.data ?? res
kbDocs.value = (Array.isArray(body) ? body : body?.items || []).map((it: any) => ({
id: String(it.id),
file_name: it.file_name || it.title || it.id,
}))
}
kbDocsLoaded = true
} catch {
kbDocs.value = []
} finally {
kbDocsLoading.value = false
}
}
// 讲师下拉选项:全体员工(id=平台用户 id,与课程/需求讲师字段口径一致);
// 编辑外部讲师(非 id 值)时追加临时选项避免回显裸文本丢失
const lecturerSelectOptions = computed(() => {
const base = members.value
.map((m) => ({ value: m.user_id, label: m.user_name || m.employee_no }))
.filter((o) => o.value)
const v = form.value.lecturer
if (v && !base.some((o) => o.value === v)) {
return [...base, { value: v, label: v }]
}
return base
})
const openForm = (row?: TrainingLibraryCourse) => {
form.value = {
id: row?.id || '',
code: row?.code || '',
name: row?.name || '',
// 所属部门默认当前登录人所在部门,支持修改(000165);编辑保持原部门,
// 原部门为空的存量行同样回落默认,便于补齐审核必填项
owner_dept_id: row?.owner_dept_id || myDeptId.value,
description: row?.description || '',
// 课程权限(000163):新增默认所属部门;编辑按 perm 两列回显(存量回退解析)
suitable_members: row?.suitable_members || '',
perm_dept_ids: row?.perm_dept_ids || '',
perm_user_ids: row?.perm_user_ids || '',
// 适合人员备注(000165):编辑回显,新增留空
post_scope: row?.post_scope || '',
category: row?.category || '',
type: row?.type === 'elective' ? 'elective' : 'required',
// 新增默认「线上」(000162);编辑随原值
mode: row ? (row.mode === 'online' ? 'online' : 'offline') : 'online',
lecturer: row?.lecturer_id || row?.lecturer_external || '',
hours: row?.hours || 0,
material_name: row?.material_name || '',
}
// 课程权限回显(000163):落库 id 列表 → 选项值数组;新增默认本部门
permList.value = parsePermFromRow(row)
formVisible.value = true
}
// 讲师表单值解析:命中员工 id → lecturer_id,否则视为外部讲师姓名
const resolveLecturer = (value: string) => {
if (!value) return { lecturer_id: '', lecturer_external: '' }
const hit = members.value.find((m) => m.user_id === value)
if (hit) return { lecturer_id: value, lecturer_external: '' }
return { lecturer_id: '', lecturer_external: value }
}
const onSave = async () => {
if (!form.value.name.trim()) {
MessagePlugin.warning('请填写课程名称')
return
}
saving.value = true
try {
const lecturer = resolveLecturer(form.value.lecturer.trim())
// 课程权限落库(000163):perm 两列 id 列表 + suitable_members 展示文本
const perm = permToFields()
form.value.suitable_members = perm.suitable_members
form.value.perm_dept_ids = perm.perm_dept_ids
form.value.perm_user_ids = perm.perm_user_ids
const res = await saveCourseLibraryItem({
id: form.value.id || undefined,
name: form.value.name.trim(),
owner_dept_id: form.value.owner_dept_id || undefined,
description: form.value.description.trim(),
suitable_members: form.value.suitable_members.trim(),
perm_dept_ids: form.value.perm_dept_ids,
perm_user_ids: form.value.perm_user_ids,
// 适合人员备注(000165):随保存落库
post_scope: form.value.post_scope.trim(),
category: form.value.category.trim(),
type: form.value.type,
mode: form.value.mode,
lecturer_id: lecturer.lecturer_id || undefined,
lecturer_external: lecturer.lecturer_external || undefined,
hours: form.value.hours,
// 隐藏保留字段:课件维护已移至「课件」抽屉,编辑保存原值回传防误清(000162)
material_name: form.value.material_name.trim(),
})
const saved = unwrap(res)
MessagePlugin.success(
form.value.id
? saved?.code
? `课程 ${saved.code} 已保存`
: '课程已保存'
: saved?.code
? `课程 ${saved.code} 已创建,可在「月培训计划」中引用`
: '课程已创建,可在「月培训计划」中引用',
)
formVisible.value = false
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '保存失败,请稍后重试'))
} finally {
saving.value = false
}
}
const onDelete = async (row: TrainingLibraryCourse) => {
try {
await deleteCourseLibraryItem(row.id)
MessagePlugin.success('已删除')
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '删除失败'))
}
}
// ---- 审核(000163:核验升级为审核,审核通过即自动发布;仅课长/经理限本部门,
// 超级管理员放开跨部门) ----
const selectedKeys = ref<string[]>([])
const batchSaving = ref(false)
// 审核前置校验(000165):课程名称/所属部门/课程权限/课件必填,返回首个未满足项的提示
const verifyBlockerOf = (row: TrainingLibraryCourse): string => {
if (!(row.name || '').trim()) return '未填写课程名称'
if (!(row.owner_dept_id || '').trim()) return '未设置所属部门,请先在「编辑」中设置所属部门'
if (!hasPermSet(row)) return '未设置课程权限,请先在「编辑」中设置课程权限'
if (!hasMaterial(row)) return '未上传课件,请先在列表「课件」入口上传课件'
return ''
}
const onVerify = async (row: TrainingLibraryCourse) => {
// 审核前置(000165):名称/所属部门/课程权限/课件必填,先补齐再审核
const blocker = verifyBlockerOf(row)
if (blocker) {
MessagePlugin.warning(`课程「${row.name}」${blocker}后再审核`)
return
}
try {
const res = unwrap(await verifyCourseLibraryItems([row.id]))
row.verify_status = 'confirmed'
if ((res?.auto_published || 0) > 0) {
row.publish_status = 'published'
MessagePlugin.success(`课程「${row.name}」已审核通过并自动发布,权限范围内部门和人员可在培训中心/培训计划中查看`)
} else if (res?.unpublished?.length) {
MessagePlugin.warning(`课程「${row.name}」已审核通过;尚未上传课件暂未发布,上传课件并重新审核后将自动发布`)
} else {
MessagePlugin.success(`课程「${row.name}」已审核通过`)
}
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '审核失败'))
}
}
const onBatchVerify = async () => {
// 与后端口径一致:课长/经理仅本部门待审核行提交,已审核/越权行直接跳过;
// 超级管理员跨部门放开(全部待审核行可提交)
const rows = filteredItems.value.filter(
(r) => selectedKeys.value.includes(r.id) && r.verify_status !== 'confirmed' && canVerifyCourse(r),
)
if (!rows.length) {
MessagePlugin.warning(isSuperAdmin.value ? '请先勾选待审核状态的课程' : '请先勾选本部门待审核状态的课程')
return
}
// 审核前置(000165):名称/所属部门/课程权限/课件必填,列出不满足的行并拦截
const blockers = rows
.map((r) => ({ name: r.name, reason: verifyBlockerOf(r) }))
.filter((b) => b.reason)
if (blockers.length) {
MessagePlugin.warning(
`${blockers.map((b) => `课程「${b.name}」${b.reason}`).join(';')}。请先补齐后再批量审核`,
)
return
}
batchSaving.value = true
try {
const res = unwrap(await verifyCourseLibraryItems(rows.map((r) => r.id)))
const unpublished = res?.unpublished?.length ? `,${res.unpublished.length} 门因未上传课件暂未发布` : ''
MessagePlugin.success(
`批量审核完成:成功 ${res?.verified || 0} 条${(res?.auto_published || 0) > 0 ? `,自动发布 ${res?.auto_published} 条` : ''}${unpublished}${res?.skipped ? `,跳过 ${res?.skipped} 条` : ''}`,
)
selectedKeys.value = []
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '批量审核失败'))
} finally {
batchSaving.value = false
}
}
const onBatchDelete = async () => {
// 与后端口径一致:普通角色仅本部门待审核行提交(已审核/越权行跳过);
// 超级管理员不限状态/部门(canDeleteCourse 按角色过滤,终态行可整批删除)
const rows = filteredItems.value.filter((r) => selectedKeys.value.includes(r.id) && canDeleteCourse(r))
if (!rows.length) {
MessagePlugin.warning(isSuperAdmin.value ? '请先勾选要删除的课程' : '请先勾选本部门待审核状态的课程')
return
}
batchSaving.value = true
let ok = 0
let fail = 0
try {
for (const row of rows) {
try {
await deleteCourseLibraryItem(row.id)
ok += 1
} catch {
fail += 1
}
}
MessagePlugin.success(`批量删除完成:成功 ${ok} 条${fail ? `,失败 ${fail} 条` : ''}`)
selectedKeys.value = []
loadAll()
} finally {
batchSaving.value = false
}
}
// 发布状态展示文案(000154;000163 审核即发布后,draft 仅存于未审核/未传课件课程)
const publishStatusText = (status?: string) =>
({ published: '已发布', offline: '已下线', draft: '待发布' }[status || 'draft'] || '待发布')
// 下线(000154/000163):下线后课程不能再被使用 —— 培训中心「和信课程」撤回、
// 月/年培训计划不可再选用、已建计划学习时提示「该课程已下线」;存量计划行保留。
// (发布不再单独提供:审核通过即自动发布,见 onVerify/onBatchVerify)
const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'offline') => {
try {
const updated = unwrap(await offlineCourseLibraryItem(row.id)) as TrainingLibraryCourse | null
if (updated) {
const idx = items.value.findIndex((it) => it.id === updated.id)
if (idx >= 0) items.value.splice(idx, 1, updated)
}
MessagePlugin.success(`课程「${row.name}」已下线,已从培训中心「和信课程」目录撤回,不能再被培训计划选用/学习`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '下线失败'))
}
}
// 课件下载(000164 多课件:mid 定位条目,缺省最新一条;列表「无课件」等单条
// 场景由调用方省略 mid 走默认口径)
const onDownloadMaterial = async (row: TrainingLibraryCourse | null, entry?: { mid?: string }) => {
if (!row) return
try {
// getDown 直接返回 Blob(trainingTemplates 同款消费方式)
const blob = await downloadCourseLibraryMaterial(row.id, entry?.mid || undefined)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = row.file_name || `${row.name}课件`
a.click()
URL.revokeObjectURL(url)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件下载失败'))
}
}
// ---------------------------------------------------------------------------
// 课件管理抽屉(000162):上传/知识库选择/预览/下载/移除,交互与试题抽屉同风格
// ---------------------------------------------------------------------------
const materialVisible = ref(false)
const materialCourse = ref<TrainingLibraryCourse | null>(null)
const materialUploading = ref(false)
type MaterialSourceMode = 'upload' | 'kb'
const materialSourceMode = ref<MaterialSourceMode>('upload')
const materialFileInputRef = ref<HTMLInputElement | null>(null)
// 000164 多课件:一次可选择多个文件,逐个追加为课件条目(不替换既有课件)
const materialFiles = ref<File[]>([])
const materialKbDocId = ref('')
const materialColumns = [
{ colKey: 'name', title: '课件名称', minWidth: 220 },
{ colKey: 'size', title: '大小', width: 110 },
{ colKey: 'source', title: '来源', width: 150 },
{ colKey: 'op', title: '操作', width: 190 },
]
const fmtSize = (size: number) => {
if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`
if (size >= 1024) return `${Math.round(size / 1024)} KB`
return `${size} B`
}
// 课件条目行(000164 多课件):courses.materials 逐条展示;
// 存量行(未跑回填迁移,列表为空而主字段有课件)由主字段合成一条兜底
const materialRows = computed(() => {
const c = materialCourse.value
if (!c) return []
if (c.materials?.length) {
return c.materials.map((m) => ({
mid: m.mid,
name: m.name,
size: m.size || 0,
source: m.origin === 'kb' ? '知识库文档' : m.knowledge_id ? '本地上传 · 已同步知识库' : '本地上传文件',
}))
}
if (hasMaterial(c)) {
return [
{
mid: '',
name: c.file_name || c.material_name || '知识库课件文档',
size: c.file_size || 0,
source: c.file_name ? '本地上传文件' : '知识库文档',
},
]
}
return []
})
// 抽屉内课件信息行:与列表「有」口径一致(文件或知识库文档任一存在)
const hasMaterial = (row: TrainingLibraryCourse) =>
Boolean(row.materials?.length || row.file_name || row.knowledge_id)
// 列表行原位替换:课件列表/审核状态随接口响应同步到列表与抽屉(课件变更已不回「待审核」)
const replaceLibraryRow = (updated?: TrainingLibraryCourse | null) => {
if (!updated) return
const idx = items.value.findIndex((it) => it.id === updated.id)
if (idx >= 0) items.value.splice(idx, 1, updated)
if (materialCourse.value?.id === updated.id) materialCourse.value = updated
if (questionsCourse.value?.id === updated.id) questionsCourse.value = updated
}
const openMaterialDrawer = (row: TrainingLibraryCourse) => {
materialCourse.value = row
materialVisible.value = true
materialSourceMode.value = 'upload'
materialFiles.value = []
materialKbDocId.value = ''
if (materialFileInputRef.value) materialFileInputRef.value.value = ''
}
const onMaterialModeChange = (mode: unknown) => {
materialSourceMode.value = mode as MaterialSourceMode
if (materialSourceMode.value === 'kb') void loadCoursewareKbDocs()
}
const onMaterialPicked = (e: Event) => {
const input = e.target as HTMLInputElement
materialFiles.value = Array.from(input.files || [])
}
// 上传课件(000164 多课件):多文件逐个追加为课件条目,不替换既有课件;
// 任一失败继续其余文件,结束按成功/失败汇总提示。
const onUploadMaterial = async () => {
const course = materialCourse.value
const files = materialFiles.value
if (!course || !files.length) return
materialUploading.value = true
let ok = 0
let last: TrainingLibraryCourse | null | undefined
try {
for (const file of files) {
try {
const fd = new FormData()
fd.append('file', file)
// 名称登记为空时后端以文件名兜底;文档类自动同步知识库「企业培训(课件)」
const updated = unwrap<TrainingLibraryCourse>(await uploadCourseLibraryMaterial(course.id, fd))
last = updated
ok += 1
} catch (e: any) {
MessagePlugin.error(`课件「${file.name}」上传失败:${apiErrorMessage(e, '请稍后重试')}`)
}
}
if (last) replaceLibraryRow(last)
if (ok) {
materialFiles.value = []
if (materialFileInputRef.value) materialFileInputRef.value.value = ''
MessagePlugin.success(
ok > 1
? `已追加 ${ok} 个课件,即时生效;课程保持原审核状态`
: `课件「${last?.file_name || ''}」已上传,即时生效;课程保持原审核状态`,
)
}
} finally {
materialUploading.value = false
}
}
const onAttachMaterialKb = async () => {
const course = materialCourse.value
const doc = kbDocs.value.find((d) => d.id === materialKbDocId.value)
if (!course || !doc) return
materialUploading.value = true
try {
const updated = unwrap<TrainingLibraryCourse>(
await attachCourseLibraryMaterialFromKb(course.id, { knowledge_id: doc.id }),
)
replaceLibraryRow(updated)
materialKbDocId.value = ''
MessagePlugin.success(`课件「${updated?.file_name || doc.file_name}」已挂接,即时生效;课程保持原审核状态`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件挂接失败'))
} finally {
materialUploading.value = false
}
}
// 预览(000164:mid 定位课件条目,缺省最新一条):取回 Blob 后新开页签展示
// (文件端点对安全类型 inline,浏览器按类型渲染;不可预览类型浏览器按附件
// 处理,回退下载)
const onPreviewMaterial = async (entry?: { mid?: string }) => {
const course = materialCourse.value
if (!course) return
try {
const blob = await downloadCourseLibraryMaterial(course.id, entry?.mid || undefined)
const url = URL.createObjectURL(blob)
window.open(url, '_blank')
// 延迟回收对象 URL,留足新页签加载时间
setTimeout(() => URL.revokeObjectURL(url), 60_000)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件预览失败'))
}
}
// 移除课件条目(000164:mid 定位,缺省移除最新一条;存量兜底行 mid 为空走默认口径)
const onRemoveMaterial = async (entry?: { mid?: string }) => {
const course = materialCourse.value
if (!course) return
try {
const updated = unwrap<TrainingLibraryCourse>(
await removeCourseLibraryMaterial(course.id, entry?.mid || undefined),
)
replaceLibraryRow(updated)
MessagePlugin.success('课件已移除;不影响课程审核状态')
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '课件移除失败'))
}
}
// ---- 导出(当前筛选结果,列口径与模板一致) ----
const onExport = async () => {
exporting.value = true
try {
const res = await exportCourseLibrary(filteredItems.value.map((i) => i.id))
const blob = new Blob([res.data as unknown as BlobPart], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `课程管理_${new Date().toISOString().slice(0, 10)}.xlsx`
a.click()
URL.revokeObjectURL(url)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '导出失败'))
} finally {
exporting.value = false
}
}
// ---- 批量导入(前端解析 Excel;列序 000165 复测按列表字段调整:课程名称(必填)/
// 讲师/课件收集/课程权限/课程分类/类型(必修课或选修课)/线上或线下/时长(学时)/
// 所属部门/课程说明/适合人员备注;旧口径列名 主办单位/参加人员/说明/分类/
// 线上,线下/课件 同样兼容) ----
const importVisible = ref(false)
const normType = (raw: string): 'required' | 'elective' => (/选修/.test(raw) ? 'elective' : 'required')
const normMode = (raw: string): 'offline' | 'online' => (/线上/.test(raw) ? 'online' : 'offline')
// 课件收集列的占位文案(已有课件/暂无课件/无等)是状态标记,不落名称登记
const isNoMaterial = (raw: string) => /^(已有课件|暂无课件|暂无|无课件|无)$/.test(raw)
// 表头键归一:去空白与全/半角括号、冒号等标点并转小写(兼容「课程说明(选填)」
// 「时长:(学时)」这类自定义模板变体;配置中心上传的自定义模板表头可能带修饰)
const normHeaderKey = (s: string) => String(s).trim().toLowerCase().replace(/[\s::,,、。.·()()[\]【】-]/g, '')
// 列名别名表(归一后口径):先精确命中,再按「表头包含别名」兜底,
// 覆盖内置模板/旧口径/自定义模板的常见列名变体
const IMPORT_HEADER_ALIASES: Record<string, string[]> = {
name: ['课程名称', '名称'],
dept: ['所属部门', '主办单位', '部门'],
description: ['课程说明', '说明', '课程简介', '简介'],
// 课程权限(000165 复测:模板列名由「适合人员」调整为「课程权限」,旧名兼容):
// 文本落 suitable_members(存量匹配/展示口径)
suitable: ['课程权限', '适合人员', '参加人员', '适合对象', '参训人员'],
// 适合人员备注(000165 复测:模板新增列)落 post_scope 只做展示
post: ['适合人员备注', '适合人员说明'],
category: ['课程分类', '分类'],
type: ['类型必修课或选修课', '类型'],
mode: ['线上或线下', '线上线下', '形式'],
lecturer: ['讲师姓名', '授课讲师', '培训讲师', '讲师'],
hours: ['时长学时', '时长'],
material: ['课件收集', '课件'],
}
// 按别名组从归一化行中取值:别名精确 → 表头包含别名(首个命中),未命中返回 ''
const pickImportColumn = (row: Record<string, string>, aliases: string[]) => {
for (const a of aliases) {
if (row[a]) return row[a]
}
const keys = Object.keys(row)
for (const a of aliases) {
const hit = keys.find((k) => k.includes(a))
if (hit && row[hit]) return row[hit]
}
return ''
}
const onImportExcel = 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())
// 定位含「课程名称」表头的工作表;表头键做归一(空白/全半角标点,见 normHeaderKey)
// 000165 复测:表头按名称别名「包含」匹配,不再要求精确等值 —— 模板表头带
// 修饰(如「课程名称(必填)」)或列序调整均不影响导入
const nameHeaderAliases = IMPORT_HEADER_ALIASES.name.map((a) => normHeaderKey(a))
const nameHeaderHit = (raw: unknown) => {
const k = normHeaderKey(String(raw ?? ''))
return nameHeaderAliases.some((a) => k === a || k.includes(a))
}
let dataRows: Record<string, string>[] | null = null
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(nameHeaderHit))
if (headerIdx < 0) continue
const header = (sheetRows[headerIdx] || []).map((c) => normHeaderKey(String(c)))
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
}
// 主办单位(所属部门)按部门名册匹配:名称精确 → 包含(与需求导入同口径),
// 未匹配时仍把部门名传给后端(服务端按组织架构兜底解析为 id)
const matchDept = (deptName: string) =>
depts.value.find((d) => d.name === deptName) || depts.value.find((d) => deptName.includes(d.name))
// 讲师按全部在职员工姓名精确匹配;未命中落外部讲师姓名(与需求导入同口径)
const itemsPayload: Partial<TrainingLibraryCourse>[] = []
let skippedRows = 0
let lecturerHits = 0
let externalLecturers = 0
let deptHits = 0
for (const row of dataRows) {
const name = pickImportColumn(row, IMPORT_HEADER_ALIASES.name)
if (!name) {
skippedRows += 1
continue
}
let ownerDeptId = ''
const deptName = pickImportColumn(row, IMPORT_HEADER_ALIASES.dept)
if (deptName) {
const hit = matchDept(deptName)
if (hit) {
ownerDeptId = hit.id
deptHits += 1
}
}
let lecturerId = ''
let lecturerExternal = ''
const lecturerName = pickImportColumn(row, IMPORT_HEADER_ALIASES.lecturer)
if (lecturerName) {
const hit = members.value.find((m) => (m.user_name || '') === lecturerName)
if (hit?.user_id) {
lecturerId = hit.user_id
lecturerHits += 1
} else {
lecturerExternal = lecturerName
externalLecturers += 1
}
}
const hoursRaw = Number.parseFloat(pickImportColumn(row, IMPORT_HEADER_ALIASES.hours).replace(/[^\d.]/g, ''))
const materialRaw = pickImportColumn(row, IMPORT_HEADER_ALIASES.material)
// 适合人员备注(000165 复测:模板新增列,落 post_scope 只做展示):先取备注,
// 再从行中剔除备注列,避免「适合人员」别名的包含匹配把备注误读进课程权限
const postScopeRaw = pickImportColumn(row, IMPORT_HEADER_ALIASES.post)
const rowWithoutPost: Record<string, string> = {}
Object.keys(row).forEach((k) => {
if (!k.includes('适合人员备注')) rowWithoutPost[k] = row[k]
})
// 类型/线上或线下:模板下拉列为全称表头(类型(必修课或选修课)/线上或线下),旧口径短表头同样兼容
itemsPayload.push({
name,
owner_dept_id: ownerDeptId || undefined,
owner_dept_name: deptName || undefined,
description: pickImportColumn(rowWithoutPost, IMPORT_HEADER_ALIASES.description),
suitable_members: pickImportColumn(rowWithoutPost, IMPORT_HEADER_ALIASES.suitable),
post_scope: postScopeRaw.slice(0, 500) || undefined,
category: pickImportColumn(rowWithoutPost, IMPORT_HEADER_ALIASES.category),
type: normType(pickImportColumn(rowWithoutPost, IMPORT_HEADER_ALIASES.type)),
mode: normMode(pickImportColumn(rowWithoutPost, IMPORT_HEADER_ALIASES.mode)),
lecturer_id: lecturerId || undefined,
lecturer_external: lecturerExternal || undefined,
hours: Number.isFinite(hoursRaw) && hoursRaw > 0 ? hoursRaw : 0,
material_name: isNoMaterial(materialRaw) ? '' : materialRaw,
})
}
if (!itemsPayload.length) {
MessagePlugin.warning('模板中没有可导入的课程行,请先填写课程名称')
return
}
const res = await importCourseLibrary(itemsPayload)
const imported = unwrap(res)?.imported || 0
const extras: string[] = []
if (deptHits) extras.push(`匹配所属部门 ${deptHits} 行`)
if (lecturerHits) extras.push(`匹配系统讲师 ${lecturerHits} 人`)
if (externalLecturers) extras.push(`外部讲师 ${externalLecturers} 人`)
if (skippedRows) extras.push(`另有 ${skippedRows} 行未填课程名称已跳过`)
MessagePlugin.success(`已从模板导入 ${imported} 门课程${extras.length ? `(${extras.join(';')})` : ''}`)
importVisible.value = false
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '导入失败,请检查 Excel 格式'))
}
}
// ---------------------------------------------------------------------------
// 试题管理(000153):题库与试题随课程条目维护
// ---------------------------------------------------------------------------
const questionsVisible = ref(false)
const questionsCourse = ref<TrainingLibraryCourse | null>(null)
const banks = ref<TrainingQuestionBank[]>([])
const banksLoading = ref(false)
const activeBank = ref<TrainingQuestionBank | null>(null)
const questions = ref<TrainingQuestion[]>([])
const questionsLoading = ref(false)
// 题库/试题列表分页(000163):默认每页 15 条;切换题库后试题回到第 1 页
const {
page: bankPage,
pageSize: bankPageSize,
total: bankTotal,
paged: pagedBanks,
} = useTrainingPager(banks)
const {
page: questionPage,
pageSize: questionPageSize,
total: questionTotal,
paged: pagedQuestions,
reset: resetQuestionPage,
} = useTrainingPager(questions)
const bankColumns = [
{ colKey: 'code', title: '题库编号', width: 105 },
{ colKey: 'name', title: '题库名称', minWidth: 180 },
{ colKey: 'question_count', title: '题目数', width: 80 },
{ colKey: 'created_at', title: '导入时间', width: 140 },
{ colKey: 'op', title: '操作', width: 170 },
]
const questionColumns = [
{ colKey: 'seq_no', title: '#', width: 50 },
{ colKey: 'type', title: '题型', width: 70 },
{ colKey: 'stem', title: '题干', minWidth: 220 },
{ colKey: 'answer', title: '答案', width: 90 },
{ colKey: 'score', title: '分值', width: 60 },
{ colKey: 'knowledge_point', title: '知识点', width: 130 },
{ colKey: 'op', title: '操作', width: 110 },
]
const questionTypeText = (t: string) => ({ single: '单选', multiple: '多选', judge: '判断' }[t] || t)
const questionAnswerText = (row: TrainingQuestion) => {
if (row.type === 'judge') return row.answer === 'B' ? '错' : '对'
return row.answer
}
const openQuestions = async (row: TrainingLibraryCourse) => {
questionsCourse.value = row
questionsVisible.value = true
activeBank.value = null
questions.value = []
await loadBanks()
}
const loadBanks = async () => {
const course = questionsCourse.value
if (!course) return
banksLoading.value = true
try {
const res = await listLibraryCourseQuestionBanks(course.id)
banks.value = unwrap(res) || []
// 题库增删后同步列表「试题」有/无计数(该端点即本课程全部题库)
course.question_bank_count = banks.value.length
const idx = items.value.findIndex((it) => it.id === course.id)
if (idx >= 0) items.value[idx].question_bank_count = banks.value.length
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库加载失败'))
} finally {
banksLoading.value = false
}
}
const selectBank = async (bank: TrainingQuestionBank) => {
activeBank.value = bank
questionsLoading.value = true
resetQuestionPage()
try {
const res = await listQuestions(bank.id)
questions.value = unwrap(res) || []
} catch {
questions.value = []
} finally {
questionsLoading.value = false
}
}
const onDeleteBank = async (bank: TrainingQuestionBank) => {
try {
await deleteQuestionBank(bank.id)
MessagePlugin.success('题库已删除')
if (activeBank.value?.id === bank.id) {
activeBank.value = null
questions.value = []
}
await loadBanks()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库删除失败'))
}
}
// ---- 题库导入:上传 Excel / 从知识库选择 / AI 课件生成 ----
type BankSourceMode = 'upload' | 'kb' | 'ai'
const bankSourceMode = ref<BankSourceMode>('upload')
const bankFileInputRef = ref<HTMLInputElement | null>(null)
const bankFile = ref<File | null>(null)
const bankImporting = ref(false)
const bankKbDocId = ref('')
const bankKbDocs = ref<{ id: string; file_name: string }[]>([])
const bankKbLoading = ref(false)
const bankKbRef = ref<{ id: string; name: string } | null>(null)
let bankKbDocsLoaded = false
const onBankModeChange = (mode: unknown) => {
bankSourceMode.value = mode as BankSourceMode
if (bankSourceMode.value === 'kb') void loadBankKbDocs()
}
const onBankFileChange = (e: Event) => {
const input = e.target as HTMLInputElement
bankFile.value = input.files?.[0] || null
}
const applyImportedBank = (bank: TrainingQuestionBank | undefined, message: string) => {
if (!bank) return
banks.value = [bank, ...banks.value.filter((b) => b.id !== bank.id)]
bankFile.value = null
if (bankFileInputRef.value) bankFileInputRef.value.value = ''
bankKbDocId.value = ''
void selectBank(bank)
MessagePlugin.success(message)
}
const onImportBankExcel = async () => {
const course = questionsCourse.value
const file = bankFile.value
if (!course || !file) return
bankImporting.value = true
try {
const fd = new FormData()
fd.append('file', file)
fd.append('name', file.name.replace(/\.[^.]+$/, ''))
const res = await importLibraryCourseQuestionBank(course.id, fd)
const bank = unwrap<TrainingQuestionBank>(res)
applyImportedBank(bank, `题库「${bank?.name || ''}」已导入(${bank?.question_count ?? 0} 题)并关联本课程;Excel 已同步知识库「企业培训(题库)」`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库导入失败,请检查 Excel 格式'))
} finally {
bankImporting.value = false
}
}
// 拉取「企业培训(题库)」知识库文档列表(惰性加载一次)
const loadBankKbDocs = async () => {
if (bankKbDocsLoaded) return
bankKbLoading.value = true
try {
if (!bankKbRef.value) {
const res = await getTrainingKnowledgeBases()
bankKbRef.value = unwrap<any>(res)?.question_bank || null
}
if (bankKbRef.value?.id) {
const res: any = await get(
`/api/v1/knowledge-bases/${encodeURIComponent(bankKbRef.value.id)}/knowledge?page=1&page_size=200`,
)
const body = res?.data ?? res
bankKbDocs.value = (Array.isArray(body) ? body : body?.items || []).map((it: any) => ({
id: String(it.id),
file_name: it.file_name || it.title || it.id,
}))
}
bankKbDocsLoaded = true
} catch {
bankKbDocs.value = []
} finally {
bankKbLoading.value = false
}
}
const onImportBankKb = async () => {
const course = questionsCourse.value
const doc = bankKbDocs.value.find((d) => d.id === bankKbDocId.value)
if (!course || !doc) return
bankImporting.value = true
try {
const res = await importQuestionBankFromKnowledge({
knowledge_id: doc.id,
name: doc.file_name.replace(/\.[^.]+$/, ''),
library_course_id: course.id,
})
const bank = unwrap<TrainingQuestionBank>(res)
applyImportedBank(bank, `已从知识库导入题库「${bank?.name || ''}」(${bank?.question_count ?? 0} 题)并关联本课程`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库导入失败'))
} finally {
bankImporting.value = false
}
}
// ---- AI 课件生成试题:生成 → 右侧抽屉预览编辑 → 使用试题建库 ----
// 可编辑题目模型(抽屉内逐项调整)
interface EditableQuestion {
type: 'single' | 'multiple' | 'judge'
stem: string
options: string[]
answer: string
knowledge_point: string
analysis: string
difficulty: number
}
const genCount = ref(10)
const genLoading = ref(false)
const genDrawerVisible = ref(false)
const genBankName = ref('')
const genQuestions = ref<EditableQuestion[]>([])
const letterAt = (i: number) => String.fromCharCode(65 + i)
const multiAnswersOf = (q: EditableQuestion) => q.answer.split('').filter(Boolean)
const setMultiAnswer = (q: EditableQuestion, letters: string[]) => {
q.answer = letters.slice().sort().join('')
}
// 题型切换:判断题固定对/错选项;其它题型缺选项时补空位
const onGenTypeChange = (q: EditableQuestion) => {
if (q.type === 'judge') {
q.options = ['A. 对', 'B. 错']
if (!['A', 'B'].includes(q.answer.toUpperCase())) q.answer = 'A'
} else if (!q.options.length) {
q.options = ['', '', '', '']
}
}
const addGenQuestion = () => {
genQuestions.value.push({
type: 'single',
stem: '',
options: ['', '', '', ''],
answer: '',
knowledge_point: questionsCourse.value?.name || '',
analysis: '',
difficulty: 3,
})
}
const onGenerateQuestions = async () => {
const course = questionsCourse.value
if (!course) return
if (!course.knowledge_id) {
MessagePlugin.warning('该课程课件未同步知识库,请先在「课件」入口上传课件文档后再 AI 出题')
return
}
genLoading.value = true
try {
const res = await generateLibraryCourseQuestions(course.id, { count: genCount.value })
const questions = unwrap<TrainingQuestion[]>(res) || []
genQuestions.value = questions.map((q) => ({
type: (q.type === 'multiple' ? 'multiple' : q.type === 'judge' ? 'judge' : 'single') as EditableQuestion['type'],
stem: q.stem,
options: Array.isArray(q.options) ? [...q.options] : [],
answer: q.answer || '',
knowledge_point: q.knowledge_point || '',
analysis: q.analysis || '',
difficulty: q.difficulty || 3,
}))
genDrawerVisible.value = true
MessagePlugin.success(`已生成 ${genQuestions.value.length} 道题,请在预览中检查调整后使用`)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, 'AI 生成试题失败'))
} finally {
genLoading.value = false
}
}
const onUseGeneratedQuestions = async () => {
const course = questionsCourse.value
if (!course) return
const invalid = genQuestions.value.findIndex((q) => !q.stem.trim() || !q.answer.trim())
if (invalid >= 0) {
MessagePlugin.warning(`第 ${invalid + 1} 题缺少题干或答案,请补全或删除`)
return
}
bankImporting.value = true
try {
const questions: TrainingQuestion[] = genQuestions.value.map((q) => ({
id: '',
type: q.type,
stem: q.stem.trim(),
// 选项入库统一带字母前缀(与导入/判分口径一致)
options: q.options
.map((o) => o.trim())
.filter(Boolean)
.map((o, oi) => (/^[A-Za-z][..、::]/.test(o) ? o : `${letterAt(oi)}. ${o}`)),
answer: q.answer.toUpperCase(),
score: 5,
difficulty: q.difficulty || 3,
knowledge_point: q.knowledge_point.trim() || course.name,
analysis: q.analysis.trim(),
}))
const res = await importGeneratedQuestionBank({
library_course_id: course.id,
name: genBankName.value.trim() || `${course.name}AI题库`,
questions,
})
const bank = unwrap<TrainingQuestionBank>(res)
applyImportedBank(bank, `题库「${bank?.name || ''}」已创建(${bank?.question_count ?? 0} 题)并关联本课程;试题已同步知识库「企业培训(题库)」`)
genDrawerVisible.value = false
genQuestions.value = []
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库创建失败'))
} finally {
bankImporting.value = false
}
}
// ---- 单题新增/编辑 ----
const questionFormVisible = ref(false)
const questionSaving = ref(false)
const questionForm = ref({
id: '',
type: 'single' as 'single' | 'multiple' | 'judge',
stem: '',
options: ['', '', '', ''] as string[],
answer: '',
score: 5,
difficulty: 3,
knowledge_point: '',
analysis: '',
})
const openQuestionForm = (row?: TrainingQuestion) => {
questionForm.value = {
id: row?.id || '',
type: (row?.type as 'single' | 'multiple' | 'judge') || 'single',
stem: row?.stem || '',
options: row?.options?.length ? [...row.options] : ['', '', '', ''],
answer: row?.answer || '',
score: row?.score || 5,
difficulty: row?.difficulty || 3,
knowledge_point: row?.knowledge_point || '',
analysis: row?.analysis || '',
}
questionFormVisible.value = true
}
// 题型切换:判断题固定对/错选项并重置答案;其它题型缺选项时补空位
const onQuestionTypeChange = () => {
if (questionForm.value.type === 'judge') {
questionForm.value.options = ['A. 对', 'B. 错']
questionForm.value.answer = ['A', 'B'].includes(questionForm.value.answer) ? questionForm.value.answer : 'A'
} else if (questionForm.value.options.length < 2) {
questionForm.value.options = ['', '', '', '']
questionForm.value.answer = ''
}
}
const onSaveQuestion = async () => {
const bank = activeBank.value
if (!bank) return
const q = questionForm.value
if (!q.stem.trim()) {
MessagePlugin.warning('请填写题干')
return
}
if (!q.answer) {
MessagePlugin.warning('请设置答案')
return
}
questionSaving.value = true
try {
// 选项入库统一带字母前缀(判断题固定对/错,与导入/判分口径一致)
const options =
q.type === 'judge'
? ['A. 对', 'B. 错']
: q.options
.map((o) => o.trim())
.filter(Boolean)
.map((o, oi) => (/^[A-Za-z][..、::]/.test(o) ? o : `${letterAt(oi)}. ${o}`))
const res = await saveQuestion(bank.id, {
id: q.id || undefined,
type: q.type,
stem: q.stem.trim(),
options,
answer: q.answer.toUpperCase(),
score: q.score,
difficulty: q.difficulty,
knowledge_point: q.knowledge_point.trim(),
analysis: q.analysis.trim(),
})
const saved = unwrap(res)
if (saved) {
const idx = questions.value.findIndex((it) => it.id === saved.id)
if (idx >= 0) questions.value.splice(idx, 1, saved)
else questions.value = [...questions.value, saved]
}
// 刷新题库冗余题数(后端已同步,这里回显)
await loadBanks()
if (activeBank.value) await selectBank(activeBank.value)
questionFormVisible.value = false
MessagePlugin.success(q.id ? '试题已保存' : '试题已新增')
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题保存失败'))
} finally {
questionSaving.value = false
}
}
const onDeleteQuestion = async (row: TrainingQuestion) => {
const bank = activeBank.value
if (!bank) return
try {
await deleteQuestion(bank.id, row.id)
questions.value = questions.value.filter((q) => q.id !== row.id)
await loadBanks()
MessagePlugin.success('试题已删除')
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '试题删除失败'))
}
}
onMounted(loadAll)
</script>
<style lang="less" scoped>
@import (reference) '../training.less';
.library-panel {
.panel-box {
.training-panel-box();
}
// 满屏列表布局(000164):页头固定,面板占满页身剩余高度,
// 筛选区/表头/分页固定,仅表格数据区滚动
.training-fill-panel();
}
.library-filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 12px;
}
.library-filter-count {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.form-hint {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
// 列表「有」标签可点击直达维护抽屉
.cell-link {
cursor: pointer;
}
// 000163 操作列按钮紧凑排布:缩小左右内边距并固定按钮间距,
// 使右侧固定区(状态 84 + 操作 260)收窄至够用,不再出现大片空白
/* 000165 操作列收窄至 224:行内至多 5 个文本按钮(编辑/课件/试题/审核或下线/删除),
单元格留白与按钮间距同步收紧避免换行 */
.library-panel :deep(.op-cell) {
padding: 4px 6px;
}
.library-panel :deep(.op-cell .t-button) {
padding: 0 4px;
}
.library-panel :deep(.op-cell .t-button + .t-button) {
margin-left: 6px;
}
// 批量导入弹窗:模板下载 + 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);
}
// 试题管理抽屉:导入工具行与题库/试题表格
.bank-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 10px;
}
.bank-upload-input {
display: none;
}
.bank-file-name {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
.bank-file-placeholder {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.bank-section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 0 8px;
font-weight: 600;
}
// 单题编辑:选项行(字母前缀 + 输入)
.question-options {
width: 100%;
display: flex;
flex-direction: column;
gap: 6px;
}
.question-option-row {
display: flex;
align-items: center;
gap: 8px;
}
.question-option-letter {
width: 18px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
// 说明/课件等长文本单元格:单行省略,t-tooltip 悬停显示全部
.cell-ellipsis {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
// AI 生成试题预览抽屉(与原月培训计划同款交互)
.gen-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.gen-toolbar__hint {
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
.gen-question {
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
padding: 10px;
margin-bottom: 10px;
}
.gen-question__head {
display: flex;
align-items: center;
gap: 8px;
}
.gen-question__options {
margin-top: 8px;
display: flex;
flex-direction: column;
gap: 6px;
}
.gen-question__opt {
display: flex;
align-items: center;
gap: 8px;
}
.gen-question__letter {
width: 18px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
.gen-question__meta {
margin-top: 8px;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 14px;
}
.gen-question__meta-item {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
.gen-add-btn {
margin-top: 6px;
}
</style>