Files
ai_academy/frontend/src/views/training/components/LibraryPanel.vue
T
runny 80deef9c53
deploy-hxtesting / build-and-deploy (push) Failing after 0s
feat(training): 课程管理新增核验状态流转与权限细化(000157)
核验状态(verify_status,迁移 000157):
- 新字段 pending 待核验(初始)/confirmed 已确认,附核验人/核验时间审计列,存量数据回填待核验
- 新增/导入/编辑(含重新上传课件)一律重置为待核验,原核验结论作废
- 发布前置校验:课程发布、月培训计划「发布/保存并发布」关联课程必须已确认,否则友好提示核验入口

核验/删除权限(仅本部门课长/经理):
- 新端点 POST /training/course-library/verify 单个/批量共用,越权/已确认行跳过不阻断
- 核验与删除严格按课长身份所在部门收窄,人事/讲师/学员/空间管理员均无跨部门操作权
- 删除仅限待核验状态(已确认课程不可删,须走核验流程)

列表数据范围与页签:
- 课程管理列表按角色注入过滤:人事/空间管理员全部,课长/经理本部门,讲师/学员仅「与我相关」(本人创建或本人授课)
- 课程管理页签对学员开放;无维护角色用户仅可编辑本人创建/授课课程(不可新增)

前端:
- 发布状态「草稿」文案改为「待发布」;新增「状态」列固定右侧置于操作列前
- 列表勾选 + 批量核验/批量删除(仅本部门待核验行提交);发布按钮前置核验校验未核验友好提示;按钮按角色/部门/状态动态显隐
2026-11-21 11:00:58 +08:00

1726 lines
69 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>
<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>
<t-table
v-model:selected-row-keys="selectedKeys"
:data="filteredItems" :columns="columns" row-key="id" size="small" :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>
<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 }">
<span v-if="row.suitable_members" class="cell-ellipsis" :title="row.suitable_members">{{ row.suitable_members }}</span>
<span v-else>-</span>
</template>
<template #material="{ row }">
<span v-if="row.material_name" class="clamp-2" :title="row.material_name">{{ row.material_name }}</span>
<span v-else>-</span>
<t-tag v-if="row.file_name" theme="success" variant="light" size="small" class="material-file-tag">附件</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):新增/编辑后待核验,课长/经理核验确认后方可发布 -->
<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="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>
<t-popconfirm
v-if="canManage && row.publish_status !== 'published'"
content="发布后该课程进入培训中心「和信课程」目录(本部门可见)。" theme="primary"
@confirm="onSetPublishStatus(row, 'published')"
>
<t-button variant="text" theme="primary" size="small">发布</t-button>
</t-popconfirm>
<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="仅待核验状态的课程可删除,确定删除该课程?已创建的月培训计划不受影响。" theme="danger" @confirm="onDelete(row)"
>
<t-button variant="text" theme="danger" size="small">删除</t-button>
</t-popconfirm>
<t-button v-if="row.file_name" variant="text" size="small" @click="onDownloadMaterial(row)">下载课件</t-button>
</template>
</t-table>
</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="所属部门">
<!-- 对应需求表「主办单位」:从组织架构部门选择(批量导入按部门名匹配) -->
<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="适合人员">
<!-- 对应需求表「参加人员」:自由文本,如:财会人员 -->
<t-input v-model="form.suitable_members" placeholder="适合参加的人员(选填),如:财会人员" />
</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-item label="课件">
<div class="material-field">
<t-input v-model="form.material_name" placeholder="课件名称登记,多个用、分隔(选填)" />
<div class="material-upload-row">
<input ref="materialInputRef" type="file" class="material-upload-input" @change="onMaterialFileChange" />
<t-button variant="outline" size="small" @click="materialInputRef?.click()">上传课件文件</t-button>
<t-button variant="outline" size="small" :loading="kbDocsLoading" @click="toggleKbDocSelect">从知识库选择</t-button>
<template v-if="pendingMaterialFile">
<span class="material-file-name">{{ pendingMaterialFile.name }}</span>
<t-button variant="text" size="small" @click="clearPendingMaterialFile">移除</t-button>
</template>
<template v-else-if="pendingKbDoc">
<span class="material-file-name">{{ pendingKbDoc.name }}</span>
<t-button variant="text" size="small" @click="clearPendingKbDoc">移除</t-button>
</template>
<template v-else-if="form.file_name && !form.clear_file">
<span class="material-file-name">{{ form.file_name }}</span>
<t-button variant="text" size="small" @click="form.clear_file = true">移除</t-button>
</template>
<span v-else class="material-placeholder">未选择课件(可选;上传文档自动同步知识库,也可从知识库选择已有课件)</span>
</div>
<!-- 知识库文档下拉:点击「从知识库选择」展开(数据源:企业培训(课件)) -->
<div v-if="kbSelectVisible" class="material-upload-row">
<t-select
v-model="pendingKbDocId"
filterable
clearable
:loading="kbDocsLoading"
placeholder="选择「企业培训(课件)」知识库中的课件文档"
style="flex: 1; min-width: 0"
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" :disabled="!pendingKbDocId" @click="confirmKbDoc">确定</t-button>
<t-button variant="text" size="small" @click="kbSelectVisible = false">收起</t-button>
</div>
<div v-if="kbSelectVisible" class="form-hint">
数据来源:知识库「{{ coursewareKbRef?.name || '企业培训(课件)' }}」共 {{ kbDocs.length }} 个文档;保存后与上传课件同口径(下载/月培训计划带出/AI 出题共用)。
</div>
</div>
</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">
模板列对应:所属部门/课程名称(必填)/课程说明/适合人员/课程分类/类型(必修课或选修课)/线上或线下/讲师/时长(学时)/课件收集(已有课件或暂无课件);
所属部门、课程分类、类型、线上或线下、讲师、课件收集在模板中支持下拉选择(讲师可选系统员工或直接输入外部姓名);分类可填配置中心预设分类或自定义分类,导入后保存;课程编号由系统自动生成。
</div>
<template #footer>
<t-button variant="outline" @click="importVisible = false">关闭</t-button>
</template>
</t-dialog>
<!-- 试题管理抽屉:题库与试题随课程条目增删改查(上传 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="banks" :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>
<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="questions" :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>
<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 } 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 {
attachCourseLibraryMaterialFromKb,
deleteCourseLibraryItem,
deleteQuestion,
deleteQuestionBank,
downloadCourseLibraryMaterial,
exportCourseLibrary,
fetchCourseCategories,
generateLibraryCourseQuestions,
getMyProfile,
getTrainingKnowledgeBases,
importCourseLibrary,
importGeneratedQuestionBank,
importLibraryCourseQuestionBank,
importQuestionBankFromKnowledge,
listCourseLibrary,
listDepts,
listLibraryCourseQuestionBanks,
listMembers,
listQuestions,
offlineCourseLibraryItem,
publishCourseLibraryItem,
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('')
// 核验/删除权限(000157):严格限「本部门课长/经理」——人事/空间管理员一律无
// 跨部门核验/删除权(roles 已按权限组展开,经理经课长继承自动命中 supervisor)。
const canVerify = computed(() => props.roles.includes('supervisor'))
const canDelete = canVerify
// 仅本部门「待核验」课程可核验/删除;与后端 callerVerifyDeptScope 同口径:
// 无部门身份或课程所属部门与本人不一致时一律不可操作。
const canVerifyCourse = (row: TrainingLibraryCourse) =>
canVerify.value &&
row.verify_status === 'pending' &&
Boolean(myDeptId.value) &&
Boolean(row.owner_dept_id) &&
row.owner_dept_id === myDeptId.value
const canDeleteCourse = canVerifyCourse
// 编辑权限:维护角色可编辑可见课程;无维护角色的学员仅可编辑「与我相关」课程
// (本人创建或本人授课,后端兜底校验同口径)
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: '' })
const resetFilters = () => {
filters.value = { keyword: '', category: '', type: '', mode: '' }
}
// 分类选项:配置中心字典 + 库内已有自定义分类(去重),供筛选与表单下拉共用
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
return true
})
})
const columns = [
// 批量勾选列(000157):配合批量核验/批量删除
{ colKey: 'row-select', type: 'multiple', width: 44 },
// 左侧列不固定(000154):课程编号/课程名称随横向滚动,操作仍固定右侧
{ colKey: 'code', title: '课程编号', width: 105 },
{ colKey: 'name', title: '课程名称', width: 170 },
{ colKey: 'owner_dept', title: '所属部门', width: 110 },
{ colKey: 'description', title: '说明', width: 200 },
{ colKey: 'suitable_members', title: '适合人员', width: 110 },
{ colKey: 'category', title: '分类', width: 120 },
{ colKey: 'type', title: '类型', width: 84 },
{ colKey: 'mode', title: '线上/线下', width: 92 },
{ colKey: 'lecturer', title: '讲师', width: 110 },
{ colKey: 'hours', title: '时长', width: 84 },
{ colKey: 'material', title: '课件', minWidth: 150 },
// 发布状态(000154):已发布的课程进入培训中心「和信课程」目录
{ colKey: 'publish_status', title: '发布状态', width: 90 },
{ colKey: 'created_at', title: '创建时间', width: 140 },
// 创建人(联查 users):记录课程录入人员
{ colKey: 'creator_name', title: '创建人', width: 96 },
// 核验状态(000157):固定右侧置于操作列前
{ colKey: 'verify_status', title: '状态', width: 90, fixed: 'right' },
{ colKey: 'op', title: '操作', width: 340, fixed: 'right' },
]
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 || ''
} finally {
loading.value = false
}
}
// ---- 新增/编辑 ----
const formVisible = ref(false)
// lecturer 表单值:id(名册内)/姓名(外部讲师,creatable 直接输入);保存时解析
const form = ref({
id: '',
code: '',
name: '',
owner_dept_id: '',
description: '',
suitable_members: '',
category: '',
type: 'required' as 'required' | 'elective',
mode: 'offline' as 'offline' | 'online',
lecturer: '',
hours: 0,
material_name: '',
file_name: '',
clear_file: false,
})
// 待上传课件文件(保存成功后随行上传)
const materialInputRef = ref<HTMLInputElement | null>(null)
const pendingMaterialFile = ref<File | null>(null)
const onMaterialFileChange = (e: Event) => {
const input = e.target as HTMLInputElement
pendingMaterialFile.value = input.files?.[0] || null
input.value = ''
// 上传文件与知识库课件二选一:选择文件即清掉已选知识库文档
clearPendingKbDoc()
}
const clearPendingMaterialFile = () => {
pendingMaterialFile.value = null
if (materialInputRef.value) materialInputRef.value.value = ''
}
// ---- 从知识库选择课件(企业培训(课件)) ----
const kbSelectVisible = ref(false)
const pendingKbDocId = ref('')
const pendingKbDoc = ref<{ id: string; name: string } | null>(null)
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 toggleKbDocSelect = async () => {
kbSelectVisible.value = !kbSelectVisible.value
if (kbSelectVisible.value) await loadCoursewareKbDocs()
}
// 拉取「企业培训(课件)」知识库文档列表(惰性加载一次)
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
}
}
const confirmKbDoc = () => {
const doc = kbDocs.value.find((d) => d.id === pendingKbDocId.value)
if (!doc) {
MessagePlugin.warning('请先选择知识库课件文档')
return
}
pendingKbDoc.value = { id: doc.id, name: doc.file_name }
// 与上传文件互斥:选定知识库文档即清掉待上传文件与已有文件移除标记
clearPendingMaterialFile()
form.value.clear_file = false
kbSelectVisible.value = false
}
const clearPendingKbDoc = () => {
pendingKbDoc.value = null
pendingKbDocId.value = ''
}
// 讲师下拉选项:全体员工(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) => {
clearPendingMaterialFile()
clearPendingKbDoc()
kbSelectVisible.value = false
form.value = {
id: row?.id || '',
code: row?.code || '',
name: row?.name || '',
// 新增默认当前登录用户所在部门;编辑保持原部门
owner_dept_id: row?.owner_dept_id || (row ? '' : myDeptId.value),
description: row?.description || '',
suitable_members: row?.suitable_members || '',
category: row?.category || '',
type: row?.type === 'elective' ? 'elective' : 'required',
mode: row?.mode === 'online' ? 'online' : 'offline',
lecturer: row?.lecturer_id || row?.lecturer_external || '',
hours: row?.hours || 0,
material_name: row?.material_name || '',
file_name: row?.file_name || '',
clear_file: false,
}
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())
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(),
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,
material_name: form.value.material_name.trim(),
clear_file: form.value.clear_file || undefined,
})
const saved = unwrap(res)
// 待上传课件文件:条目已落库后随行上传(名称登记为空时后端以文件名兜底;
// 文档类自动同步知识库「企业培训(课件)」,支持 AI 对话与出题)
if (pendingMaterialFile.value && saved?.id) {
const fd = new FormData()
fd.append('file', pendingMaterialFile.value)
await uploadCourseLibraryMaterial(saved.id, fd)
}
// 从知识库选择的课件:保存后挂接知识库文档(与上传同步同口径)
if (pendingKbDoc.value && saved?.id) {
await attachCourseLibraryMaterialFromKb(saved.id, { knowledge_id: pendingKbDoc.value.id })
}
MessagePlugin.success(
form.value.id
? saved?.code
? `课程 ${saved.code} 已保存`
: '课程已保存'
: saved?.code
? `课程 ${saved.code} 已创建,可在「月培训计划」中引用`
: '课程已创建,可在「月培训计划」中引用',
)
formVisible.value = false
clearPendingMaterialFile()
clearPendingKbDoc()
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, '删除失败'))
}
}
// ---- 核验(000157):待核验 → 已确认,单个/批量共用核验端点(仅课长/经理限本部门) ----
const selectedKeys = ref<string[]>([])
const batchSaving = ref(false)
const onVerify = async (row: TrainingLibraryCourse) => {
try {
await verifyCourseLibraryItems([row.id])
row.verify_status = 'confirmed'
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('请先勾选本部门待核验状态的课程')
return
}
batchSaving.value = true
try {
const { verified, skipped } = unwrap(await verifyCourseLibraryItems(rows.map((r) => r.id)))
MessagePlugin.success(`批量核验完成:成功 ${verified} 条${skipped ? `,跳过 ${skipped} 条` : ''}`)
selectedKeys.value = []
loadAll()
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '批量核验失败'))
} finally {
batchSaving.value = false
}
}
const onBatchDelete = async () => {
// 与后端口径一致:仅本部门待核验行提交(已确认/越权行跳过)
const rows = filteredItems.value.filter((r) => selectedKeys.value.includes(r.id) && canDeleteCourse(r))
if (!rows.length) {
MessagePlugin.warning('请先勾选本部门待核验状态的课程')
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;000157 起草稿文案调整为「待发布」)
const publishStatusText = (status?: string) =>
({ published: '已发布', offline: '已下线', draft: '待发布' }[status || 'draft'] || '待发布')
// 发布/下线(000154):发布后进入培训中心「和信课程」目录,下线即从目录撤回
const onSetPublishStatus = async (row: TrainingLibraryCourse, status: 'published' | 'offline') => {
// 发布前置校验(000157):仅「已确认」课程可发布(后端兜底同样拦截)
if (status === 'published' && row.verify_status !== 'confirmed') {
MessagePlugin.warning('该课程尚未核验,请先由本部门课长/经理核验确认后再发布')
return
}
try {
const updated = unwrap(
status === 'published' ? await publishCourseLibraryItem(row.id) : 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(
status === 'published'
? `课程「${row.name}」已发布,可在培训中心「和信课程」目录查看`
: `课程「${row.name}」已下线,已从培训中心「和信课程」目录撤回`,
)
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, status === 'published' ? '发布失败' : '下线失败'))
}
}
const onDownloadMaterial = async (row: TrainingLibraryCourse) => {
try {
// getDown 直接返回 Blob(trainingTemplates 同款消费方式)
const blob = await downloadCourseLibraryMaterial(row.id)
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, '课件下载失败'))
}
}
// ---- 导出(当前筛选结果,列口径与模板一致) ----
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;列:所属部门/课程名称/课程说明/适合人员/课程分类/
// 类型(必修课或选修课)/线上或线下/讲师/时长(学时)/课件收集;旧口径列名
// 主办单位/参加人员/说明/分类/线上,线下/课件 同样兼容) ----
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: ['课程说明', '说明', '课程简介', '简介'],
suitable: ['适合人员', '参加人员', '适合对象', '参训人员'],
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)
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((c) => normHeaderKey(String(c)) === '课程名称'))
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)
// 类型/线上或线下:模板下拉列为全称表头(类型(必修课或选修课)/线上或线下),旧口径短表头同样兼容
itemsPayload.push({
name,
owner_dept_id: ownerDeptId || undefined,
owner_dept_name: deptName || undefined,
description: pickImportColumn(row, IMPORT_HEADER_ALIASES.description),
suitable_members: pickImportColumn(row, IMPORT_HEADER_ALIASES.suitable),
category: pickImportColumn(row, IMPORT_HEADER_ALIASES.category),
type: normType(pickImportColumn(row, IMPORT_HEADER_ALIASES.type)),
mode: normMode(pickImportColumn(row, 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)
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) || []
} catch (e: any) {
MessagePlugin.error(apiErrorMessage(e, '题库加载失败'))
} finally {
banksLoading.value = false
}
}
const selectBank = async (bank: TrainingQuestionBank) => {
activeBank.value = bank
questionsLoading.value = true
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();
}
}
.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);
}
// 课件字段:名称登记 + 文件上传行
.material-field {
width: 100%;
}
.material-upload-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.material-upload-input {
display: none;
}
.material-file-name {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
}
.material-placeholder {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
.material-file-tag {
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>