feat(安全培训): 新增员工安全培训相关功能

This commit is contained in:
runny committed 2026-08-12 11:56:35 +08:00
1 parent cbc3cb959f
commit 8e5c57790c
50 files changed
+3769 -87

No files matched your search

@@ -18,10 +18,14 @@ import type {
UsageReport,
UsageRangeKey,
} from '../types/report.types';
import type { TrainingConfig, TrainingConfigPayload, TrainingResourceCandidates } from '../types/training-config.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export type ShippingInventoryReadinessCheck = {
code: string;
status: 'passed' | 'pending' | 'failed' | 'stale' | 'empty';
@@ -398,6 +402,49 @@ export const saveShippingInventoryExternalMapping = (payload: Record<string, unk
export const deleteShippingInventoryExternalMapping = (id: number) => requestJson<void>(
`/api/admin/shipping-notice/external-mappings/${id}`, { method: 'DELETE', ...auth() },
);
export const listAdminTrainingConfigs = () =>
requestJson<TrainingConfig[]>('/api/admin/training-configs', auth());
export const listAdminTrainingResourceCandidates = () =>
requestJson<TrainingResourceCandidates>('/api/admin/training-configs/resource-candidates', auth());
export interface TrainingQuestionBankParseResult {
question_bank: unknown[];
parsed_count: number;
skipped_question_numbers: number[];
kb_document_version_id: number;
source_file_name: string;
version_no: number;
extraction_mode: 'pdf_text' | 'ocr' | 'ocr_fallback';
extraction_warnings: string[];
}
export const parseAdminTrainingQuestionBank = (kbDocumentVersionId: number) =>
requestJson<TrainingQuestionBankParseResult>('/api/admin/training-configs/question-bank/parse', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ kb_document_version_id: kbDocumentVersionId }),
});
export const createAdminTrainingConfig = (payload: TrainingConfigPayload) =>
requestJson<TrainingConfig>('/api/admin/training-configs', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const updateAdminTrainingConfig = (id: number, payload: TrainingConfigPayload) =>
requestJson<TrainingConfig>(`/api/admin/training-configs/${id}`, {
method: 'PUT',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const deleteAdminTrainingConfig = (id: number) =>
requestJson<{ success: boolean }>(`/api/admin/training-configs/${id}`, {
method: 'DELETE',
...auth(),
});
// Users
export const listAdminUsers = () => requestJson<AdminUserRow[]>('/api/admin/users', auth());
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import {
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
ScrollText, ExternalLink, PackageSearch,
ScrollText, ExternalLink, PackageSearch, GraduationCap,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
@@ -43,6 +43,7 @@ const iconMap: Record<AdminModuleId, Component> = {
permissions: Users,
platform_apps: AppWindow,
procurement_contract: ScrollText,
training_config: GraduationCap,
requests: ShieldCheck,
reports: BarChart2,
shipping_inventory: PackageSearch,
@@ -42,7 +42,7 @@ export interface ShippingConfigSubModuleMeta {
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports',
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config'
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -61,6 +61,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
];
@@ -38,6 +38,31 @@ const uploadError = ref('');
const deleteDialogOpen = ref(false);
const pendingDeleteGuideId = ref<number | null>(null);
const safetyVideoUsages = new Set([
'training_safety_video',
'training_safety_company_video',
'training_safety_department_video',
'training_safety_team_video',
]);
const isVideoUsage = (usage: string) => usage === 'training_video' || safetyVideoUsages.has(usage);
const isPdfUsage = (usage: string) => usage === 'training_exam_pdf' || usage === 'training_safety_pdf';
/**
* 把指南用途编码翻译成管理端可读名称。
* AI 触发时机:平台应用说明列表与弹窗下拉都依赖这层映射,新增资料用途时必须统一从这里出文案,避免表格和表单各自写死分叉。
*/
const getGuideUsageLabel = (usage: string) => {
if (usage === 'training_video') return t('admin.platformApps.trainingVideo');
if (usage === 'training_exam_pdf') return t('admin.platformApps.trainingExamPdf');
if (usage === 'training_safety_company_video') return t('admin.platformApps.trainingSafetyCompanyVideo');
if (usage === 'training_safety_department_video') return t('admin.platformApps.trainingSafetyDepartmentVideo');
if (usage === 'training_safety_team_video') return t('admin.platformApps.trainingSafetyTeamVideo');
if (usage === 'training_safety_video') return t('admin.platformApps.trainingSafetyVideo');
if (usage === 'training_safety_pdf') return t('admin.platformApps.trainingSafetyPdf');
return t('admin.platformApps.generalGuide');
};
/**
* 拉取 Agent 列表并默认选中第一项,再加载其指南。
*/
@@ -134,10 +159,10 @@ const handleFileUpload = async (event: Event) => {
form.value.file_path = res.file_path;
form.value.file_type = res.file_type;
form.value.file_size = res.file_size;
if (form.value.guide_usage === 'training_video' && res.file_type !== 'video') {
if (isVideoUsage(form.value.guide_usage) && res.file_type !== 'video') {
form.value.guide_usage = 'general';
}
if (form.value.guide_usage === 'training_exam_pdf' && res.file_type !== 'pdf') {
if (isPdfUsage(form.value.guide_usage) && res.file_type !== 'pdf') {
form.value.guide_usage = 'general';
}
if (!form.value.file_name) {
@@ -297,9 +322,7 @@ const getIcon = (type: string) => {
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
</td>
<td class="px-6 py-4 text-muted">
<span v-if="guide.guide_usage === 'training_video'">{{ t('admin.platformApps.trainingVideo') }}</span>
<span v-else-if="guide.guide_usage === 'training_exam_pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</span>
<span v-else>{{ t('admin.platformApps.generalGuide') }}</span>
<span>{{ getGuideUsageLabel(guide.guide_usage || 'general') }}</span>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
@@ -372,6 +395,11 @@ const getIcon = (type: string) => {
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
<option value="training_safety_company_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyCompanyVideo') }}</option>
<option value="training_safety_department_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyDepartmentVideo') }}</option>
<option value="training_safety_team_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyTeamVideo') }}</option>
<option value="training_safety_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyVideo') }}</option>
<option value="training_safety_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingSafetyPdf') }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
</div>
@@ -0,0 +1,553 @@
<script setup lang="ts">
/**
* features/admin/modules/training-config/TrainingConfigPage.vue
* 用途:提供培训类型、基础规则、三级学习资料、考试题库与复盘内容的一体化后台配置界面。
* 依赖:admin.api 培训配置接口、training-config.types、TrainingTypeFormModal 与通用消息/删除确认组件。
* 逻辑:左侧切换培训类型,右侧编辑完整配置;保存时将题目同步到 settings 与内嵌题目资源后提交既有 API。
*/
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
BookOpen,
CheckCircle2,
ChevronRight,
ClipboardCheck,
Edit,
FileQuestion,
FileText,
Layers3,
Library,
ListChecks,
Plus,
Save,
Settings2,
ShieldCheck,
Trash2,
Video,
} from 'lucide-vue-next';
import { useMessage } from '@/shared/composables/useMessage';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import {
createAdminTrainingConfig,
deleteAdminTrainingConfig,
listAdminTrainingConfigs,
listAdminTrainingResourceCandidates,
parseAdminTrainingQuestionBank,
updateAdminTrainingConfig,
} from '../../api/admin.api';
import type { TrainingConfig, TrainingConfigPayload, TrainingLevel } from '../../types/training-config.types';
import TrainingTypeFormModal from './components/TrainingTypeFormModal.vue';
const { t } = useI18n();
const msg = useMessage();
const configs = ref<TrainingConfig[]>([]);
const selectedId = ref<number | null>(null);
const isLoading = ref(true);
const isSaving = ref(false);
const showTypeEditor = ref(false);
const editingType = ref(false);
const deleteTarget = ref<TrainingConfig | null>(null);
const typeForm = ref({ training_type: '', name: '' });
const questionJsonText = ref('[]');
const questionSourceVersionId = ref<number | null>(null);
const isParsingQuestions = ref(false);
const questionParseMeta = ref<{ mode: string; fileName: string; skipped: number[] } | null>(null);
const candidates = ref({ guides: [], documents: [], training_exam_documents: [] } as Awaited<ReturnType<typeof listAdminTrainingResourceCandidates>>);
const selected = computed(() => configs.value.find((item) => item.id === selectedId.value) || null);
const form = ref<TrainingConfigPayload>(emptyForm());
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
const guideGroups = computed(() => {
const groupUsages = [
{ key: 'company', usage: 'training_safety_company_video' },
{ key: 'department', usage: 'training_safety_department_video' },
{ key: 'team', usage: 'training_safety_team_video' },
];
const grouped = groupUsages.map((group) => ({
key: group.key,
items: candidates.value.guides.filter((guide) => guide.guide_usage === group.usage),
}));
const groupedUsages = new Set(groupUsages.map((group) => group.usage));
grouped.push({
key: 'other',
items: candidates.value.guides.filter((guide) => !groupedUsages.has(guide.guide_usage)),
});
return grouped.filter((group) => group.items.length > 0);
});
const questionCount = computed(() => {
try {
const questions = JSON.parse(questionJsonText.value);
return Array.isArray(questions) ? questions.length : 0;
} catch {
return 0;
}
});
const activeSection = ref('basic');
const sectionItems = computed(() => [
{ id: 'basic', label: t('admin.trainingConfig.sections.basicTitle'), icon: Layers3 },
{ id: 'resources', label: t('admin.trainingConfig.sections.resourcesTitle'), icon: Library },
{ id: 'exam', label: t('admin.trainingConfig.sections.examTitle'), icon: FileQuestion },
{ id: 'review', label: t('admin.trainingConfig.sections.reviewTitle'), icon: ClipboardCheck },
]);
const publishedCount = computed(() => configs.value.filter((config) => config.status === 'published').length);
const resourceCount = computed(() => contentResources.value.length);
const configuredLevelCount = computed(() => trainingLevels.filter((level) => resourcesByLevel(level).length > 0).length);
/** 创建新增培训类型所需的完整默认配置,确保沿用后端既有字段契约。 */
function emptyForm(): TrainingConfigPayload {
return {
training_type: '',
name: '',
version: 'v1.0',
status: 'draft',
pass_score: 90,
settings: { exam_mode: 'unified', questions: [] },
resources: [],
};
}
const showDeleteConfirm = computed({
get: () => deleteTarget.value !== null,
set: (visible: boolean) => {
if (!visible) deleteTarget.value = null;
},
});
/** 将选中的服务端配置复制到编辑表单,并兼容 settings 与内嵌资源中的历史题库数据。 */
const selectConfig = (config: TrainingConfig) => {
const inlineQuestions = config.resources.find((resource) => resource.resource_type === 'inline_questions')?.inline_questions;
const questions = Array.isArray(inlineQuestions) ? inlineQuestions : Array.isArray(config.settings.questions) ? config.settings.questions : [];
selectedId.value = config.id;
form.value = {
training_type: config.training_type,
name: config.name,
version: config.version,
status: config.status,
pass_score: config.pass_score,
settings: { ...config.settings, questions },
resources: config.resources.map((resource) => ({ ...resource })),
};
questionJsonText.value = JSON.stringify(questions, null, 2);
questionSourceVersionId.value = null;
questionParseMeta.value = null;
};
/** 从已选择的员工培训知识库当前 PDF 解析题库,并将结果回填到可继续手工编辑的 JSON。 */
const parseQuestionBank = async () => {
if (!questionSourceVersionId.value) {
msg.warning(t('admin.trainingConfig.messages.questionSourceRequired'));
return;
}
isParsingQuestions.value = true;
try {
const result = await parseAdminTrainingQuestionBank(questionSourceVersionId.value);
questionJsonText.value = JSON.stringify(result.question_bank, null, 2);
questionParseMeta.value = { mode: result.extraction_mode, fileName: result.source_file_name, skipped: result.skipped_question_numbers };
msg.success(t('admin.trainingConfig.messages.parseSuccess', { count: result.parsed_count }));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.parseFailed'));
} finally {
isParsingQuestions.value = false;
}
};
/** 将 settings 中的数组字段转换为多行文本供复盘表单编辑。 */
const settingText = (key: string) => {
const value = form.value.settings[key];
return Array.isArray(value) ? value.join('\n') : String(value || '');
};
/** 将复盘区域的多行文本清洗为非空数组并写回 settings。 */
const updateSettingText = (key: string, value: string) => {
form.value.settings[key] = value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
};
const settingSummaryByStageText = (level: string) => {
const summaries = (form.value.settings.summaryByStage as Record<string, string[]>) || {};
const value = summaries[level];
return Array.isArray(value) ? value.join('\n') : String(value || '');
};
const updateSettingSummaryByStageText = (level: string, value: string) => {
if (!form.value.settings.summaryByStage) {
form.value.settings.summaryByStage = {};
}
const summaries = form.value.settings.summaryByStage as Record<string, string[]>;
summaries[level] = value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
};
/** 并行加载培训配置与可选资料,并默认打开首个培训类型。 */
const load = async () => {
isLoading.value = true;
try {
const [loadedConfigs, loadedCandidates] = await Promise.all([
listAdminTrainingConfigs(),
listAdminTrainingResourceCandidates(),
]);
configs.value = loadedConfigs;
candidates.value = loadedCandidates;
const firstConfig = configs.value[0];
if (firstConfig) selectConfig(firstConfig);
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.loadFailed'));
} finally {
isLoading.value = false;
}
};
/** 打开新增培训类型弹窗并重置类型表单。 */
const openCreate = () => {
editingType.value = false;
typeForm.value = { training_type: '', name: '' };
showTypeEditor.value = true;
};
/** 使用当前培训类型信息打开编辑弹窗。 */
const editType = () => {
if (selected.value) {
editingType.value = true;
typeForm.value = { training_type: selected.value.training_type, name: selected.value.name };
showTypeEditor.value = true;
}
};
/** 校验并新增或更新培训类型,成功后刷新列表并保持当前选中项。 */
const saveType = async () => {
const rawType = typeForm.value.training_type.trim();
typeForm.value.training_type = ({
'入职培训': 'onboarding',
'新人培训': 'onboarding',
'安全培训': 'safety',
} as Record<string, string>)[rawType] || rawType.toLowerCase();
if (!['onboarding', 'safety'].includes(typeForm.value.training_type) || !typeForm.value.name.trim()) {
msg.warning(t('admin.trainingConfig.messages.typeRequired'));
return;
}
isSaving.value = true;
try {
const existing = editingType.value ? selected.value : null;
const payload = existing ? { ...form.value, training_type: typeForm.value.training_type, name: typeForm.value.name } : {
...emptyForm(), training_type: typeForm.value.training_type, name: typeForm.value.name,
};
const saved = existing ? await updateAdminTrainingConfig(existing.id, payload) : await createAdminTrainingConfig(payload);
await load();
selectConfig(saved);
showTypeEditor.value = false;
msg.success(t('admin.trainingConfig.messages.saved'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
} finally {
isSaving.value = false;
}
};
/** 校验题目 JSON,将题库双写至兼容字段后通过既有更新接口保存完整配置。 */
const saveConfig = async () => {
if (!selected.value) return;
try {
const questions = JSON.parse(questionJsonText.value);
if (!Array.isArray(questions)) throw new Error();
form.value.settings.questions = questions;
const inlineResource = form.value.resources.find((resource) => resource.resource_type === 'inline_questions');
if (questions.length) {
if (inlineResource) inlineResource.inline_questions = questions;
else form.value.resources.push({ resource_type: 'inline_questions', title: t('admin.trainingConfig.questionBankTitle'), sort_order: 1000, inline_questions: questions });
} else if (inlineResource) {
form.value.resources = form.value.resources.filter((resource) => resource !== inlineResource);
}
} catch {
msg.warning(t('admin.trainingConfig.messages.invalidQuestions'));
return;
}
isSaving.value = true;
try {
const saved = await updateAdminTrainingConfig(selected.value.id, form.value);
await load();
selectConfig(saved);
msg.success(t('admin.trainingConfig.messages.saved'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
} finally {
isSaving.value = false;
}
};
/**
* 向指定培训级别新增一条资料绑定。
* AI 触发时机:管理员点击三级卡片内的“添加资料”时调用,新增项必须携带对应 training_level,避免员工端跨级展示。
*/
const addResource = (trainingLevel: TrainingLevel) => {
form.value.resources.push({ resource_type: 'agent_guide', training_level: trainingLevel, title: '', required_duration: 0, sort_order: form.value.resources.length });
};
/** 返回指定级别的资料,供三级卡片独立渲染与增删。 */
const resourcesByLevel = (trainingLevel: TrainingLevel) => contentResources.value.filter((resource) => resource.training_level === trainingLevel);
/** 从当前编辑表单中移除指定资料绑定。 */
const removeResource = (resource: TrainingConfigPayload['resources'][number]) => {
form.value.resources = form.value.resources.filter((item) => item !== resource);
};
/** 切换资料类型时清空旧关联主键,避免提交互斥资源字段。 */
const updateResourceType = (resource: TrainingConfigPayload['resources'][number]) => {
resource.agent_guide_id = undefined;
resource.kb_document_version_id = undefined;
};
const scrollToSection = (sectionId: string) => {
activeSection.value = sectionId;
document.getElementById(`training-section-${sectionId}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
};
/** 按发布状态返回统一的后台状态标签颜色。 */
const statusClass = (status: TrainingConfig['status']) => {
if (status === 'published') return 'alert-success';
if (status === 'archived') return 'bg-surface-strong text-muted ring-1 ring-inset ring-default';
return 'alert-warning';
};
/** 删除确认后的当前培训配置,并刷新左侧类型列表。 */
const deleteType = async () => {
if (!deleteTarget.value) return;
try {
await deleteAdminTrainingConfig(deleteTarget.value.id);
deleteTarget.value = null;
await load();
msg.success(t('admin.trainingConfig.messages.deleted'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
}
};
onMounted(() => void load());
</script>
<template>
<section class="page-shell min-h-full px-1 py-1 animate-fade-in-up">
<div class="mb-6 flex flex-col gap-1 px-1 sm:px-2">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">{{ t('admin.trainingConfig.eyebrow') }}</p>
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div>
<h1 class="page-title">{{ t('admin.trainingConfig.title') }}</h1>
<p class="section-desc mt-2 max-w-2xl leading-6">{{ t('admin.trainingConfig.subtitle') }}</p>
</div>
<div class="hidden items-center gap-2 text-xs text-slate-400 lg:flex"><ShieldCheck class="h-4 w-4 text-emerald-500" />{{ t('admin.trainingConfig.pageHint') }}</div>
</div>
</div>
<div v-if="!isLoading" class="mb-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div v-for="stat in [
{ label: t('admin.trainingConfig.stats.total'), value: configs.length, icon: Settings2, tone: 'bg-blue-50 text-blue-600' },
{ label: t('admin.trainingConfig.stats.published'), value: publishedCount, icon: CheckCircle2, tone: 'bg-emerald-50 text-emerald-600' },
{ label: t('admin.trainingConfig.stats.resources'), value: resourceCount, icon: Library, tone: 'bg-violet-50 text-violet-600' },
{ label: t('admin.trainingConfig.stats.levels'), value: configuredLevelCount, icon: Layers3, tone: 'bg-amber-50 text-amber-600' },
]" :key="stat.label" class="flex items-center gap-4 rounded-xl border border-slate-200 bg-white px-5 py-4 shadow-sm">
<span class="flex h-10 w-10 items-center justify-center rounded-xl" :class="stat.tone"><component :is="stat.icon" class="h-5 w-5" /></span>
<div><p class="text-xs font-medium text-muted">{{ stat.label }}</p><p class="mt-1 text-2xl font-bold tracking-tight text-primary">{{ stat.value }}</p></div>
</div>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-24">
<div class="h-10 w-10 animate-spin rounded-full border-b-2 border-brand-600" />
</div>
<div v-else class="grid items-start gap-5 xl:grid-cols-[248px_minmax(0,1fr)]">
<aside class="surface-panel overflow-hidden xl:sticky xl:top-6">
<div class="border-b border-subtle bg-surface-soft px-4 py-5">
<div class="flex items-center justify-between gap-3">
<div>
<h2 class="text-sm font-bold text-primary">{{ t('admin.trainingConfig.types') }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.typeCount', { count: configs.length }) }}</p>
</div>
<button class="btn-primary btn-icon" type="button" :title="t('admin.trainingConfig.addType')" @click="openCreate">
<Plus class="h-4 w-4" />
</button>
</div>
</div>
<div class="space-y-1.5 p-2.5">
<div v-if="!configs.length" class="px-3 py-10 text-center text-sm text-slate-500">{{ t('admin.trainingConfig.empty') }}</div>
<button v-for="item in configs" :key="item.id" type="button" class="group flex w-full items-center gap-3 rounded-lg border px-3 py-3 text-left transition" :class="item.id === selectedId ? 'border-brand-200 bg-brand-50 text-brand-700 shadow-sm' : 'border-transparent text-secondary hover:border-default hover:bg-surface-soft'" @click="selectConfig(item)">
<span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg" :class="item.id === selectedId ? 'bg-surface text-brand-600 shadow-sm' : 'bg-surface-strong text-muted'">
<ShieldCheck v-if="item.training_type === 'safety'" class="h-4.5 w-4.5" />
<BookOpen v-else class="h-4.5 w-4.5" />
</span>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-semibold">{{ item.name }}</span>
<span class="mt-0.5 block truncate text-xs opacity-70">{{ item.training_type }} · {{ item.version }}</span>
</span>
<ChevronRight class="h-4 w-4 shrink-0 opacity-50 transition group-hover:translate-x-0.5" />
</button>
</div>
</aside>
<main v-if="selected" class="min-w-0 space-y-5">
<header class="surface-panel px-5 py-5 md:px-7">
<div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
<div class="flex min-w-0 items-center gap-4">
<div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
<Settings2 class="h-6 w-6" />
</div>
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2.5">
<h2 class="truncate text-xl font-bold tracking-tight text-primary md:text-2xl">{{ form.name }}</h2>
<span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold ring-1 ring-inset" :class="statusClass(form.status)">
{{ t(`admin.trainingConfig.status.${form.status}`) }}
</span>
</div>
<p class="mt-1.5 text-sm text-slate-500">{{ t('admin.trainingConfig.headerMeta', { type: selected.training_type, version: form.version }) }}</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<button class="btn-secondary btn-sm" type="button" @click="editType"><Edit class="h-4 w-4" />{{ t('admin.edit') }}</button>
<button class="btn-danger btn-sm" type="button" @click="deleteTarget = selected"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
</div>
</header>
<nav class="surface-panel sticky top-2 z-10 flex gap-2 overflow-x-auto p-2" aria-label="Training configuration sections">
<button v-for="item in sectionItems" :key="item.id" type="button" class="segment-item shrink-0" :class="activeSection === item.id ? 'segment-item--active' : ''" @click="scrollToSection(item.id)">
<component :is="item.icon" class="h-4 w-4" />{{ item.label }}
</button>
</nav>
<section id="training-section-basic" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex items-start gap-3">
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-blue-50 text-blue-600"><Layers3 class="h-5 w-5" /></span>
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.basicTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.basicDesc') }}</p></div>
</div>
<div class="grid gap-x-5 gap-y-4 md:grid-cols-2 xl:grid-cols-3">
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}<input v-model="form.name" class="input-field mt-2" /></label>
<label class="label-field">{{ t('admin.trainingConfig.fields.version') }}<input v-model="form.version" class="input-field mt-2" /></label>
<label class="label-field">{{ t('admin.trainingConfig.fields.status') }}<select v-model="form.status" class="select-field mt-2"><option value="draft">{{ t('admin.trainingConfig.status.draft') }}</option><option value="published">{{ t('admin.trainingConfig.status.published') }}</option><option value="archived">{{ t('admin.trainingConfig.status.archived') }}</option></select></label>
<label class="label-field">{{ t('admin.trainingConfig.fields.passScore') }}<div class="relative mt-2"><input v-model.number="form.pass_score" type="number" min="0" max="100" class="input-field pr-10" /><span class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted">%</span></div></label>
<label class="label-field md:col-span-2 xl:col-span-2">{{ t('admin.trainingConfig.fields.examMode') }}<select v-model="form.settings.exam_mode" class="select-field mt-2"><option value="unified">{{ t('admin.trainingConfig.examMode.unified') }}</option><option value="per_level">{{ t('admin.trainingConfig.examMode.perLevel') }}</option></select></label>
</div>
</section>
<section id="training-section-resources" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div class="flex items-start gap-3">
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-violet-50 text-violet-600"><Library class="h-5 w-5" /></span>
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.resourcesTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.resourcesDesc') }}</p></div>
</div>
</div>
<div v-if="!contentResources.length" class="rounded-2xl border border-dashed border-default bg-surface-soft/50 px-5 py-10 text-center">
<Library class="mx-auto h-8 w-8 text-muted" />
<p class="mt-3 text-sm font-medium text-secondary">{{ t('admin.trainingConfig.resourcesEmpty') }}</p>
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmptyHint') }}</p>
</div>
<div class="flex flex-col gap-5">
<article
v-for="(level, levelIndex) in trainingLevels"
:key="level"
class="w-full overflow-hidden rounded-2xl border bg-surface shadow-sm"
:class="level === 'company' ? 'border-emerald-200' : level === 'department' ? 'border-blue-200' : 'border-orange-200'"
>
<div
class="flex flex-col gap-4 border-b px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
:class="level === 'company' ? 'border-emerald-200 bg-emerald-50/80' : level === 'department' ? 'border-blue-200 bg-blue-50/80' : 'border-orange-200 bg-orange-50/80'"
>
<div class="flex items-center gap-3">
<span
class="flex h-10 min-w-10 items-center justify-center rounded-xl px-2 text-sm font-bold text-white shadow-sm"
:class="level === 'company' ? 'bg-emerald-500' : level === 'department' ? 'bg-blue-500' : 'bg-orange-500'"
>L{{ levelIndex + 1 }}</span>
<div>
<h4 class="text-base font-bold text-primary">{{ t(`admin.trainingConfig.guideGroups.${level}`) }}</h4>
<div class="mt-1 flex items-center gap-1.5 text-xs font-medium text-muted">
<Library class="h-3.5 w-3.5" />
<span>{{ resourcesByLevel(level).length }}</span>
</div>
</div>
</div>
<button class="btn-secondary btn-sm self-start sm:self-auto" type="button" @click="addResource(level)"><Plus class="h-4 w-4" />{{ t('admin.trainingConfig.addResource') }}</button>
</div>
<div class="p-4 md:p-5">
<div v-if="!resourcesByLevel(level).length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmpty') }}</div>
<div v-else class="space-y-4">
<div v-for="(resource, index) in resourcesByLevel(level)" :key="resource.id || `${level}-resource-${index}`" class="rounded-lg border border-default bg-surface p-3 shadow-sm">
<div class="grid gap-x-5 gap-y-4 md:grid-cols-2 xl:grid-cols-5">
<label class="label-field">{{ t('admin.trainingConfig.resourceKind') }}<select v-model="resource.resource_type" class="select-field mt-2" @change="updateResourceType(resource)"><option value="agent_guide">{{ t('admin.trainingConfig.resourceTypes.guide') }}</option><option value="kb_document_version">{{ t('admin.trainingConfig.resourceTypes.document') }}</option></select></label>
<label class="label-field">{{ t('admin.trainingConfig.resourceFile') }}
<select v-if="resource.resource_type === 'agent_guide'" v-model.number="resource.agent_guide_id" class="select-field mt-2">
<option :value="undefined">{{ t('admin.trainingConfig.selectResource') }}</option>
<optgroup v-for="group in guideGroups" :key="group.key" :label="t(`admin.trainingConfig.guideGroups.${group.key}`)">
<option v-for="guide in group.items" :key="guide.id" :value="guide.id">{{ guide.file_name }}</option>
</optgroup>
</select>
<select v-else v-model.number="resource.kb_document_version_id" class="select-field mt-2"><option :value="undefined">{{ t('admin.trainingConfig.selectResource') }}</option><option v-for="document in candidates.documents" :key="document.id" :value="document.id">{{ document.file_name }} · v{{ document.version_no }}</option></select>
</label>
<label class="label-field">{{ t('admin.trainingConfig.resourceTitle') }}<input v-model="resource.title" class="input-field mt-2" :placeholder="t('admin.trainingConfig.resourceTitlePlaceholder')" /></label>
<label class="label-field">所需时间(分钟)<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" placeholder="0表示不限制" /></label>
<button class="flex h-10 w-full items-center justify-center gap-2 rounded-xl text-red-500 transition hover:bg-red-50 hover:text-red-600 mt-auto" type="button" :title="t('admin.delete')" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
<div v-if="resource.resource_type === 'agent_guide'" class="mt-3 flex items-center gap-2 text-xs text-muted"><Video class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.guideGroupingHint') }}</div>
<div v-else class="mt-3 flex items-center gap-2 text-xs text-muted"><FileText class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.documentVersionHint') }}</div>
</div>
</div>
</div>
</article>
</div>
</section>
<section id="training-section-exam" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex items-start justify-between gap-4">
<div class="flex items-start gap-3">
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600"><FileQuestion class="h-5 w-5" /></span>
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.examTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.examDesc') }}</p></div>
</div>
<span class="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-amber-50 px-3 py-1.5 text-xs font-semibold text-amber-700"><CheckCircle2 class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.questionCount', { count: questionCount }) }}</span>
</div>
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50/60 p-4">
<div class="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
<label class="label-field">{{ t('admin.trainingConfig.questionSource') }}<select v-model.number="questionSourceVersionId" class="select-field mt-2"><option :value="null">{{ t('admin.trainingConfig.selectQuestionSource') }}</option><option v-for="document in candidates.training_exam_documents" :key="document.id" :value="document.id">{{ document.file_name }} · v{{ document.version_no }}</option></select></label>
<button class="btn-primary btn-sm" type="button" :disabled="isParsingQuestions || !questionSourceVersionId" @click="parseQuestionBank"><FileQuestion class="h-4 w-4" />{{ isParsingQuestions ? t('admin.trainingConfig.parsingQuestions') : t('admin.trainingConfig.parseQuestions') }}</button>
</div>
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.questionSourceHint') }}</p>
<p v-if="questionParseMeta" class="mt-2 text-xs text-emerald-700">{{ t('admin.trainingConfig.parseStatus', { fileName: questionParseMeta.fileName, mode: questionParseMeta.mode }) }}<span v-if="questionParseMeta.skipped.length">{{ t('admin.trainingConfig.parseSkipped', { numbers: questionParseMeta.skipped.join(', ') }) }}</span></p>
</div>
<label class="label-field">{{ t('admin.trainingConfig.questionJson') }}<textarea v-model="questionJsonText" class="input-field mt-2 min-h-64 font-mono text-xs leading-5" spellcheck="false" /></label>
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.questionJsonHint') }}</p>
</section>
<section id="training-section-review" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex items-start gap-3">
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><ClipboardCheck class="h-5 w-5" /></span>
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.reviewTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.reviewDesc') }}</p></div>
</div>
<template v-if="form.training_type === 'safety'">
<div class="mb-5 text-sm font-semibold text-primary">分级培训总结 (按行分隔)</div>
<div class="grid gap-5 md:grid-cols-3 mb-8">
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-emerald-500" />公司级总结</span><textarea :value="settingSummaryByStageText('company')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('company', ($event.target as HTMLTextAreaElement).value)" /></label>
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-blue-500" />部门级总结</span><textarea :value="settingSummaryByStageText('department')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('department', ($event.target as HTMLTextAreaElement).value)" /></label>
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-orange-500" />班组级总结</span><textarea :value="settingSummaryByStageText('team')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('team', ($event.target as HTMLTextAreaElement).value)" /></label>
</div>
</template>
<div class="grid gap-5 md:grid-cols-2">
<label v-if="form.training_type !== 'safety'" class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.summaryPoints') }}</span><textarea :value="settingText('summary_points')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingText('summary_points', ($event.target as HTMLTextAreaElement).value)" /></label>
<label v-if="form.training_type !== 'safety'" class="label-field"><span class="flex items-center gap-2"><ListChecks class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.summaryChecklist') }}</span><textarea :value="settingText('summary_checklist')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingText('summary_checklist', ($event.target as HTMLTextAreaElement).value)" /></label>
<label class="label-field"><span class="flex items-center gap-2"><FileQuestion class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.employeeQuestions') }}</span><textarea :value="settingText('employee_chat_suggested_questions')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.oneQuestionPerLine')" @input="updateSettingText('employee_chat_suggested_questions', ($event.target as HTMLTextAreaElement).value)" /></label>
<label class="label-field"><span class="flex items-center gap-2"><FileQuestion class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.hrQuestions') }}</span><textarea :value="settingText('hr_chat_suggested_questions')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.oneQuestionPerLine')" @input="updateSettingText('hr_chat_suggested_questions', ($event.target as HTMLTextAreaElement).value)" /></label>
</div>
</section>
<div class="h-16" />
</main>
<div v-else class="flex min-h-[520px] flex-col items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-400 shadow-sm">
<Settings2 class="h-10 w-10" />
<p class="mt-4 text-sm">{{ t('admin.trainingConfig.selectHint') }}</p>
</div>
</div>
<div v-if="!isLoading && selected" class="fixed inset-x-0 bottom-0 z-20 border-t border-slate-200 bg-white/95 px-4 py-3 shadow-[0_-8px_24px_rgba(15,23,42,0.08)] backdrop-blur md:left-[var(--sidebar-width,0px)] md:px-8">
<div class="mx-auto flex max-w-[1440px] items-center justify-between gap-4">
<div class="hidden items-center gap-2 text-xs text-slate-500 sm:flex"><CheckCircle2 class="h-4 w-4 text-emerald-500" />{{ t('admin.trainingConfig.footerHint') }}</div>
<div class="ml-auto flex items-center gap-2">
<button class="btn-secondary btn-sm" type="button" @click="editType"><Edit class="h-4 w-4" />{{ t('admin.edit') }}</button>
<button class="btn-primary min-w-32" type="button" :disabled="isSaving" @click="saveConfig"><Save class="h-4 w-4" />{{ isSaving ? t('admin.trainingConfig.saving') : t('admin.save') }}</button>
</div>
</div>
</div>
<TrainingTypeFormModal :visible="showTypeEditor" :editing="editingType" :form="typeForm" :is-saving="isSaving" @close="showTypeEditor = false" @save="saveType" />
<DeleteConfirmDialog v-model="showDeleteConfirm" :message="t('admin.trainingConfig.confirmDelete')" @confirm="deleteType" />
</section>
</template>
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const props = defineProps<{
visible: boolean;
editing: boolean;
form: { training_type: string; name: string };
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ props.editing ? t('admin.trainingConfig.editType') : t('admin.trainingConfig.addType') }}</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.trainingConfig.fields.type') }}</label>
<select v-model="props.form.training_type" class="select-field text-sm">
<option value="onboarding">{{ t('chat.training.safety.tabs.onboarding') }}</option>
<option value="safety">{{ t('chat.training.safety.tabs.safety') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}</label>
<input v-model="props.form.name" type="text" class="input-field text-sm" :placeholder="t('admin.trainingConfig.fields.name')" />
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="props.isSaving" @click="emit('save')">
{{ props.isSaving ? `${t('admin.save')}...` : props.editing ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
</template>
@@ -20,6 +20,7 @@ export type AdminModuleId =
| 'platform_apps'
| 'shipping_inventory'
| 'procurement_contract'
| 'training_config'
| 'reports';
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
@@ -0,0 +1,68 @@
/**
* features/admin/types/training-config.types.ts
* 用途:约束培训配置管理页、候选资料与三级培训资源的数据结构。
* 依赖:admin.api 与 TrainingConfigPage。
* 逻辑:管理端按 training_level 保存资料,员工端发布配置沿用同一层级语义。
*/
export type TrainingConfigStatus = 'draft' | 'published' | 'archived';
export type TrainingLevel = 'company' | 'department' | 'team';
export interface TrainingConfigResource {
id?: number;
resource_type: 'agent_guide' | 'kb_document_version' | 'inline_questions';
training_level?: TrainingLevel | null;
title?: string | null;
sort_order?: number;
required_duration?: number;
agent_guide_id?: number;
kb_document_version_id?: number;
inline_questions?: unknown[];
}
export interface TrainingConfig {
id: number;
training_type: string;
name: string;
version: string;
status: TrainingConfigStatus;
pass_score: number;
settings: Record<string, unknown>;
resources: TrainingConfigResource[];
published_at?: string | null;
}
export interface TrainingConfigPayload {
training_type: string;
name: string;
version: string;
status: TrainingConfigStatus;
pass_score: number;
settings: Record<string, unknown>;
resources: TrainingConfigResource[];
}
export interface TrainingResourceCandidates {
guides: Array<{
id: number;
file_name: string;
file_type: string;
guide_usage: string;
file_url?: string;
}>;
documents: Array<{
id: number;
document_id: number;
version_no: number;
file_name: string;
status: string;
group_name: string;
}>;
training_exam_documents: Array<{
id: number;
document_id: number;
version_no: number;
file_name: string;
status: string;
group_name: string;
}>;
}
+109 -5
View File
@@ -6,11 +6,26 @@
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
import type {
SafetyProgressState,
TrainingAnswerRecord,
TrainingExamMode,
TrainingProgressRecord,
TrainingPublishedConfig,
TrainingRecord,
TrainingStage,
TrainingStats,
TrainingType,
} from '../training/training.types';
type TrainingRecordApi = {
id: number;
user_id?: number;
training_type?: TrainingType;
training_version?: string | null;
exam_mode?: TrainingExamMode;
safety_stage?: string | null;
safety_progress?: Partial<SafetyProgressState> | null;
employee_id?: string | null;
name?: string | null;
department?: string | null;
@@ -31,6 +46,32 @@ type TrainingRecordApi = {
status?: TrainingRecord['status'];
};
type TrainingConfigApi = {
id: number;
training_type?: TrainingType;
version?: string | null;
pass_score?: number | null;
settings?: Record<string, unknown> | null;
resources?: Array<{
id?: number | null;
resource_type?: string | null;
training_level?: 'company' | 'department' | 'team' | null;
agent_guide_id?: number | null;
inline_questions?: unknown[];
title?: string | null;
sort_order?: number;
required_duration?: number;
resource?: {
id?: number;
file_name?: string;
file_type?: string;
file_url?: string;
guide_usage?: string;
source_file_name?: string;
} | null;
}>;
};
type TrainingListApi = {
items: TrainingRecordApi[];
total: number;
@@ -52,13 +93,19 @@ type TrainingStatsApi = {
export interface TrainingRecordQuery {
keyword?: string;
department?: string;
status?: 'all' | 'passed' | 'failed' | 'in_progress';
status?: string;
type?: string;
page?: number;
page_size?: number;
}
export interface SaveTrainingProgressPayload {
stage: TrainingStage;
agentId?: number | null;
trainingVersion?: string | null;
examMode?: TrainingExamMode;
safetyStage?: string | null;
safetyProgress?: Partial<SafetyProgressState> | null;
currentQuestionIndex: number;
score: number;
passed: boolean;
@@ -80,9 +127,20 @@ function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): Training
: [];
}
function mapSafetyProgressState(items?: TrainingRecordApi['safety_progress']): SafetyProgressState {
return {
company: String(items?.company || 'pending'),
department: String(items?.department || 'pending'),
team: String(items?.team || 'pending'),
resource_progress: (items as any)?.resource_progress || {},
};
}
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
return {
id: data.id,
trainingType: data.training_type || 'onboarding',
trainingVersion: data.training_version || undefined,
name: String(data.name || ''),
employeeId: String(data.employee_id || ''),
department: String(data.department || ''),
@@ -92,6 +150,9 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
attempts: Number(data.attempt_count || 0),
status: data.status || 'in_progress',
stage: (data.stage || 'video') as TrainingStage,
examMode: (data.exam_mode || 'unified') as TrainingExamMode,
safetyStage: data.safety_stage ? String(data.safety_stage) as TrainingProgressRecord['safetyStage'] : null,
safetyProgress: mapSafetyProgressState(data.safety_progress),
currentQuestionIndex: Number(data.current_question_index || 0),
passed: Boolean(data.passed),
answerDetails: mapAnswerDetails(data.answer_details),
@@ -101,10 +162,41 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
};
}
function mapTrainingConfig(data: TrainingConfigApi): TrainingPublishedConfig {
return {
id: data.id,
trainingType: data.training_type || 'onboarding',
version: String(data.version || ''),
passScore: Number(data.pass_score || 0),
settings: data.settings || {},
resources: Array.isArray(data.resources)
? data.resources.map((resource) => ({
id: resource.id,
resourceType: resource.resource_type,
trainingLevel: resource.training_level,
agentGuideId: resource.agent_guide_id,
inlineQuestions: resource.inline_questions,
title: resource.title,
sortOrder: Number(resource.sort_order || 0),
requiredDuration: Number(resource.required_duration || 0),
resource: resource.resource ? {
id: resource.resource.id,
fileName: resource.resource.file_name || resource.resource.source_file_name,
fileType: resource.resource.file_type,
fileUrl: resource.resource.file_url,
guideUsage: resource.resource.guide_usage,
} : null,
}))
: [],
};
}
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
const progress = mapTrainingProgressRecord(data);
return {
id: progress.id,
trainingType: progress.trainingType,
trainingVersion: progress.trainingVersion,
name: progress.name,
employeeId: progress.employeeId,
department: progress.department,
@@ -121,26 +213,38 @@ function buildQueryString(query: TrainingRecordQuery = {}) {
if (query.keyword) params.set('keyword', query.keyword);
if (query.department) params.set('department', query.department);
if (query.status) params.set('status', query.status);
if (query.type) params.set('type', query.type);
if (query.page) params.set('page', String(query.page));
if (query.page_size) params.set('page_size', String(query.page_size));
return params.toString();
}
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${type}`, authHeaders());
return data ? mapTrainingProgressRecord(data) : null;
}
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
export async function getMyTrainingConfig(type: string = 'onboarding'): Promise<TrainingPublishedConfig | null> {
const data = await requestJson<TrainingConfigApi | null>(`/api/user/training-config?type=${encodeURIComponent(type)}`, authHeaders());
return data ? mapTrainingConfig(data) : null;
}
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload, type: string = 'onboarding'): Promise<TrainingProgressRecord> {
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
method: 'PUT',
...jsonAuthHeaders(),
body: JSON.stringify({
agent_id: payload.agentId || undefined,
stage: payload.stage,
training_version: payload.trainingVersion || undefined,
exam_mode: payload.examMode || undefined,
safety_stage: payload.safetyStage || undefined,
safety_progress: payload.safetyProgress || undefined,
current_question_index: payload.currentQuestionIndex,
score: payload.score,
passed: payload.passed,
attempt_count: payload.attemptCount,
type: type,
answer_details: payload.answerDetails.map((item) => ({
question_id: item.questionId,
selected_option_id: item.selectedOptionId,
@@ -20,11 +20,19 @@ import {
RefreshCcw,
ShieldCheck,
Target,
User,
FileText,
Video,
Lock,
XCircle,
} from 'lucide-vue-next';
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
import { getAuthHeaders } from '@/shared/utils/auth';
const props = defineProps<{
currentAgent: Record<string, unknown> | null;
currentUser: Record<string, unknown> | null;
@@ -39,9 +47,13 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
const msg = useMessage();
const workspace = reactive(props.training);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const showFilePreview = ref(false);
// 将 workspace 内部控制弹窗的状态同步给组件本地变量(如果需要,或者直接用 workspace.showVideoModal)
const showVideoModal = computed({
get: () => workspace.showVideoModal,
@@ -82,14 +94,14 @@ const handleVideoSeeking = (e: Event) => {
};
const handleVideoEnded = () => {
showVideoModal.value = false;
workspace.markVideoCompleted();
workspace.showVideoModal = false;
workspace.stopMaterialTimer();
};
const reportVideoDebugEvent = (event: Event) => {
const video = event.target as HTMLVideoElement;
// #region debug-point A-E:ios-video-runtime
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || currentPreviewVideoUrl.value || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
// #endregion
};
@@ -227,6 +239,50 @@ const examQuestionItems = computed(() => Array.from({ length: workspace.totalQue
};
}));
const canNavigateExamQuestions = computed(() => workspace.stage === 'exam');
const isMaterialCompleted = (material: any) => {
const resourceProgress = workspace.safetyProgress.resource_progress || {};
const record = resourceProgress[material.id];
return record ? !!record.completed : false;
};
const currentPreviewVideoUrl = ref('');
const handleMaterialClick = (material: any) => {
const url = material.resource?.fileUrl;
if (!url) {
msg.warning('该资料暂无可预览的文件');
return;
}
if (material.resource?.fileType === 'video') {
workspace.showVideoModal = true;
currentPreviewVideoUrl.value = url;
// 当点击视频资料时,我们应该记录正在观看的资源ID,以便后续更新进度
workspace.currentViewingMaterialId = material.id;
} else {
previewFile.value = {
name: material.title || material.resource?.fileName || '资料预览',
url: url,
actualExt: material.resource?.fileType,
};
showFilePreview.value = true;
workspace.currentViewingMaterialId = material.id;
}
workspace.startMaterialTimer(material.id);
};
const handlePreviewClose = (val: boolean) => {
showFilePreview.value = val;
if (!val) {
workspace.stopMaterialTimer();
}
};
const handleVideoModalClose = () => {
workspace.showVideoModal = false;
currentPreviewVideoUrl.value = '';
workspace.stopMaterialTimer();
};
const jumpToExamQuestion = (index: number) => {
if (!canNavigateExamQuestions.value) return;
workspace.syncExamQuestionIndex(index);
@@ -239,6 +295,21 @@ const handleStageCardClick = (stageKey: string) => {
if (!canSwitchToStage(stageKey)) return;
workspace.stage = stageKey as typeof workspace.stage;
};
// --- 安全培训相关计算属性 ---
const safetySteps = computed(() => workspace.safetyStepItems);
const currentSafetySummary = computed(() => {
return workspace.publishedSafetySummary;
});
const currentSafetyStageText = computed(() => {
if (workspace.safetyViewStage === 'company') return t('chat.training.safety.steps.company');
if (workspace.safetyViewStage === 'department') return t('chat.training.safety.steps.department');
if (workspace.safetyViewStage === 'team') return t('chat.training.safety.steps.team');
if (workspace.safetyViewStage === 'exam') return t('chat.training.safety.steps.exam');
return t('chat.training.steps.result');
});
</script>
<template>
@@ -412,7 +483,38 @@ const handleStageCardClick = (stageKey: string) => {
</div>
<div v-if="!isCompactMode && workspace.activeView === 'learner'" :class="learnerWorkspaceGridClass">
<div :class="learnerWorkspaceMainClass">
<!-- 增加顶部 Tab 切换:入职培训 / 安全培训 -->
<div class="col-span-full mb-1">
<div class="inline-flex rounded-xl border border-default bg-surface-soft p-1">
<button
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'onboarding' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'onboarding'"
>
<User class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.onboarding') }}
</button>
<button
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'safety' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'safety'"
>
<ShieldCheck class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.safety') }}
</button>
</div>
</div>
<div v-if="workspace.trainingConfigLoading" class="col-span-full rounded-2xl border border-default bg-white px-6 py-16 text-center text-secondary">
{{ $t('chat.training.noContent.loading') }}
</div>
<div v-else-if="!workspace.hasPublishedTrainingConfig" class="col-span-full rounded-2xl border border-dashed border-brand-200 bg-white px-6 py-16 text-center text-secondary">
<FileText class="mx-auto h-10 w-10 text-brand-300" />
<div class="mt-3 text-base font-semibold text-primary">{{ $t('chat.training.noContent.title') }}</div>
<div class="mt-1 text-sm">{{ $t('chat.training.noContent.description') }}</div>
</div>
<template v-else-if="workspace.learnerTab === 'onboarding'">
<div :class="learnerWorkspaceMainClass">
<div :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
<div>
@@ -666,8 +768,39 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div class="min-w-0 md:sticky md:top-3 md:self-start">
<div :class="questionNavPanelClass">
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
<!-- 流程进度面板 (仅在非考试阶段展示) -->
<div v-if="workspace.stage !== 'exam' && workspace.stage !== 'result'" :class="questionNavPanelClass">
<div class="flex items-center gap-2 mb-3">
<Target class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.progressLabel') }}</div>
</div>
<div class="space-y-2">
<div
v-for="(item, index) in stageItems"
:key="item.key"
class="flex items-center gap-3 p-2 rounded-lg border transition"
:class="[
stageStep > index + 1 ? 'border-emerald-200 bg-emerald-50/50' :
stageStep === index + 1 ? 'border-brand-300 bg-brand-50' :
'border-slate-100 bg-slate-50/50 opacity-70'
]"
>
<div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="stageStep > index + 1 ? 'bg-emerald-500 text-white' : stageStep === index + 1 ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
>
<CheckCircle2 v-if="stageStep > index + 1" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
</div>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold" :class="stageStep === index + 1 ? 'text-brand-700' : 'text-slate-700'">{{ $t(item.label) }}</div>
</div>
</div>
</div>
</div>
<!-- 考试题目面板 (在考试或结果阶段展示) -->
<div v-else :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
@@ -709,6 +842,335 @@ const handleStageCardClick = (stageKey: string) => {
</ul>
</div>
</div>
</template>
<!-- 安全培训视图 -->
<template v-else>
<div :class="learnerWorkspaceMainClass">
<!-- 进度卡片 -->
<div :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.safety.progressTitle') }}
</div>
<div class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
{{ $t('chat.training.safety.progressHint') }}
</div>
</div>
<div class="rounded-lg bg-surface-soft px-2.5 py-1 text-center">
<div class="text-xs text-muted">{{ $t('chat.training.progressPercent') }}</div>
<div class="text-base font-semibold leading-none text-primary">{{ workspace.safetyProgressPercent }}%</div>
</div>
</div>
<div class="mt-2 grid grid-cols-2 gap-1 lg:grid-cols-4">
<div
v-for="step in safetySteps"
:key="step.id"
class="cursor-pointer rounded-xl border px-2 py-1.5 transition"
:class="[
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50' :
step.status === 'active' ? 'border-brand-500 bg-brand-500 text-white shadow-sm' :
'border-default bg-surface-soft/70 opacity-60'
]"
@click="step.status !== 'locked' ? workspace.setSafetyStage(step.id as any) : null"
>
<div class="flex items-center gap-2">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-white text-brand-600' : 'bg-white text-muted'"
>
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
<PlayCircle v-else-if="step.id !== 'exam'" class="h-4 w-4" />
<Lock v-else-if="step.status === 'locked'" class="h-3 w-3" />
<ClipboardCheck v-else class="h-4 w-4" />
</div>
<div class="min-w-0">
<div class="whitespace-normal text-[12px] font-medium leading-4" :class="step.status === 'active' ? 'text-white' : 'text-primary'">{{ step.label }}</div>
<div class="text-[10px] font-medium mt-0.5" :class="step.status === 'active' ? 'text-white/80' : 'text-secondary'">
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 主内容区 -->
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex justify-between items-center">
<div>
<span class="inline-flex rounded-md bg-amber-500 px-2 py-0.5 text-xs font-semibold text-white">
{{ currentSafetyStageText }}
</span>
<span class="ml-2 text-base font-semibold text-primary">{{ $t('chat.training.safety.videoPanelSubtitle') }}</span>
</div>
<div class="text-xs font-medium text-amber-500">
{{ $t('chat.training.safety.videoPanelPassLine') }}
</div>
</div>
<div class="mt-4">
<div class="text-sm font-semibold text-primary mb-3">{{ $t('chat.training.safety.materialsTitle') }}</div>
<ul v-if="workspace.publishedTrainingMaterials.length" class="space-y-2">
<li v-for="material in workspace.publishedTrainingMaterials" :key="material.id || `${material.resourceType}-${material.sortOrder}`" class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 cursor-pointer hover:bg-slate-100 transition" @click="handleMaterialClick(material)">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary hover:text-brand-600">
<Video v-if="material.resource?.fileType === 'video'" class="h-4 w-4 text-brand-500" />
<FileText v-else class="h-4 w-4 text-slate-400" />
<span class="truncate">{{ material.title || material.resource?.fileName || $t('chat.training.safety.materials.m2') }}</span>
</div>
<div class="flex flex-col items-end gap-1">
<span class="text-xs text-secondary">{{ currentSafetyStageText }}</span>
<span v-if="material.requiredDuration" class="text-xs font-semibold" :class="isMaterialCompleted(material) ? 'text-emerald-500' : 'text-amber-500'">所需时间: {{ material.requiredDuration }} 分钟 ({{ isMaterialCompleted(material) ? '已完成' : '未完成' }})</span>
</div>
</li>
</ul>
</div>
</div>
<div v-else-if="workspace.safetyViewStage === 'exam' && workspace.currentQuestion" :class="examPanelClass">
<div class="flex flex-col gap-2.5 md:flex-row md:items-center md:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.safety.steps.exam') }}
</div>
<h3 class="mt-1 text-base font-semibold text-primary md:text-lg">
{{ $t('chat.training.exam.questionCounter', { current: workspace.currentQuestionNumber, total: workspace.totalQuestionCount }) }}
</h3>
</div>
<div class="flex flex-wrap gap-1.5 text-xs text-secondary md:text-sm">
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
</div>
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
</div>
</div>
</div>
<div class="mt-3 rounded-2xl border border-brand-100 bg-brand-50/40 p-3">
<div class="text-[15px] font-semibold leading-6 text-primary md:text-base">
{{ workspace.currentQuestion.prompt }}
</div>
</div>
<div class="mt-2.5 grid gap-2">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
type="button"
class="rounded-2xl border px-3.5 py-2 text-left text-sm leading-5 transition"
:class="[
workspace.selectedOptionId === option.id
? workspace.answerLocked
? option.id === workspace.currentQuestion.answer
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
: 'border-red-300 bg-red-50 text-red-700'
: 'border-brand-300 bg-brand-50 text-brand-700'
: workspace.answerLocked && option.id === workspace.currentQuestion.answer
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
: 'border-default bg-white text-secondary hover:border-brand-200 hover:bg-brand-50/40',
]"
@click="workspace.selectAnswer(option.id)"
>
<div class="flex items-start justify-between gap-3">
<span>{{ option.label }}</span>
<CheckCircle2
v-if="workspace.answerLocked && option.id === workspace.currentQuestion.answer"
class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500"
/>
</div>
</button>
</div>
<div
v-if="workspace.answerLocked"
class="mt-3 rounded-2xl border p-3"
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="workspace.currentFeedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.selectedAnswer', { answer: currentAnswerLabel || '--' }) }}
</div>
<div class="mt-1 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.options?.find((item) => item.id === workspace.currentQuestion?.answer)?.label || '--' }) }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ workspace.currentQuestion.explanation }}
</div>
<div class="mt-3">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.examReadyToSubmit ? workspace.submitExam() : workspace.moveToNextQuestion()"
>
<ClipboardCheck class="h-4 w-4" />
{{
workspace.examReadyToSubmit
? $t('chat.training.exam.submitPaper')
: $t('chat.training.exam.nextQuestion')
}}
</button>
</div>
</div>
</div>
<div v-else class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<div class="inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs font-semibold"
:class="workspace.isPassed ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
>
<ShieldCheck class="h-3.5 w-3.5" />
{{ workspace.isPassed ? $t('chat.training.result.passedTag') : $t('chat.training.result.failedTag') }}
</div>
<h3 class="mt-2.5 text-lg font-semibold text-primary md:text-xl">
{{ workspace.isPassed ? $t('chat.training.result.passTitle') : $t('chat.training.result.failTitle') }}
</h3>
<p class="mt-2 text-sm leading-6 text-secondary">
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore: workspace.passScore }) }}
</p>
</div>
<div class="grid grid-cols-2 gap-2 text-center">
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.scoreLabel') }}</div>
<div class="text-xl font-semibold text-primary">{{ workspace.score }}</div>
</div>
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.attemptsLabel') }}</div>
<div class="text-xl font-semibold text-primary">{{ workspace.attemptCount }}</div>
</div>
</div>
</div>
<div class="mt-3 grid gap-2.5 md:grid-cols-3">
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.correctCount') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.correctCount }}</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.wrongCount') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.wrongCount }}</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.completionDate') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.completionDate || '--' }}</div>
</div>
</div>
<div class="mt-4 flex flex-wrap gap-2.5">
<button
v-if="!workspace.isPassed"
type="button"
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.restartExam"
>
<RefreshCcw class="h-4 w-4" />
{{ $t('chat.training.result.retryExam') }}
</button>
</div>
</div>
</div>
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
<!-- 流程进度面板 (仅在非考试阶段展示) -->
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'" :class="questionNavPanelClass">
<div class="flex items-center gap-2 mb-3">
<Target class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.safety.progressTitle') }}</div>
</div>
<div class="space-y-2">
<div
v-for="(step, index) in safetySteps"
:key="step.id"
class="flex items-center gap-3 p-2 rounded-lg border transition"
:class="[
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50/50' :
step.status === 'active' ? 'border-brand-300 bg-brand-50' :
'border-slate-100 bg-slate-50/50 opacity-70'
]"
>
<div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
>
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
</div>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold" :class="step.status === 'active' ? 'text-brand-700' : 'text-slate-700'">{{ step.label }}</div>
<div class="text-[10px] text-slate-500 mt-0.5">
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 考试题目面板 (在考试阶段或结果阶段展示) -->
<div v-else :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
</div>
<div class="mt-1.5 text-[11px] leading-4.5 text-secondary">
{{ $t('chat.training.examQuestionCard.hint') }}
</div>
<div :class="questionNavGridClass">
<button
v-for="item in examQuestionItems"
:key="item.index"
type="button"
:class="[
questionNavButtonClass,
item.status === 'active'
? 'border-brand-500 bg-brand-600 text-white shadow-sm'
: item.status === 'correct'
? 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: item.status === 'wrong'
? 'border-red-200 bg-red-50 text-red-700 hover:bg-red-100'
: 'border-default bg-surface-soft text-muted hover:border-slate-300 hover:bg-slate-100',
!canNavigateExamQuestions ? 'cursor-not-allowed opacity-80' : '',
]"
:disabled="!canNavigateExamQuestions"
@click="jumpToExamQuestion(item.index)"
>
{{ item.label }}
</button>
</div>
<div class="my-2.5 h-px bg-slate-100" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
<ul class="mt-1.5 grid gap-1 text-[11px] leading-4.5 text-secondary">
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ rule }}</span>
</li>
</ul>
</div>
<!-- 培训总结 -->
<div v-if="currentSafetySummary && currentSafetySummary.length > 0" :class="questionNavPanelClass" class="bg-amber-50/50 border-amber-100">
<div class="text-sm font-semibold text-amber-900 mb-2">{{ $t('chat.training.safety.summaryTitle') }}</div>
<ul class="space-y-1.5 text-[11px] leading-4.5 text-amber-800/80">
<li v-for="(point, idx) in currentSafetySummary" :key="idx" class="flex gap-1.5">
<span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-amber-400"></span>
<span>{{ point }}</span>
</li>
</ul>
</div>
</div>
</template>
</div>
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
@@ -747,7 +1209,7 @@ const handleStageCardClick = (stageKey: string) => {
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3">
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<label>
<input
v-model="workspace.hrKeyword"
@@ -756,6 +1218,16 @@ const handleStageCardClick = (stageKey: string) => {
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
/>
</label>
<label>
<select
v-model="workspace.hrTypeFilter"
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
>
<option value="all">{{ $t('chat.training.hr.filters.allTypes') }}</option>
<option value="onboarding">{{ $t('chat.training.hr.filters.typeOnboarding') }}</option>
<option value="safety">{{ $t('chat.training.hr.filters.typeSafety') }}</option>
</select>
</label>
<label>
<select
v-model="workspace.hrStatusFilter"
@@ -840,9 +1312,9 @@ const handleStageCardClick = (stageKey: string) => {
</section>
<Teleport to="body">
<div v-if="showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="showVideoModal = false">
<div v-if="workspace.showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="handleVideoModalClose">
<div class="relative w-full max-w-4xl overflow-hidden rounded-3xl bg-black shadow-2xl">
<button @click="showVideoModal = false" class="absolute top-4 right-4 z-10 h-10 w-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition backdrop-blur-md">
<button @click="handleVideoModalClose" class="absolute top-4 right-4 z-10 h-10 w-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition backdrop-blur-md">
<XCircle class="h-6 w-6" />
</button>
<div class="aspect-video bg-black">
@@ -863,11 +1335,18 @@ const handleStageCardClick = (stageKey: string) => {
@seeking="handleVideoSeeking"
@ended="handleVideoEnded"
>
<source :src="workspace.videoUrl" type="video/mp4">
<source :src="currentPreviewVideoUrl || workspace.videoUrl" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
</div>
<FilePreviewModal
v-model="showFilePreview"
:file="previewFile"
:agent-id="workspace.currentTrainingAgentId || undefined"
:auth-headers="getAuthHeaders()"
@update:modelValue="handlePreviewClose"
/>
</Teleport>
</template>
@@ -10,33 +10,40 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
getMyTrainingConfig,
getMyTrainingProgress,
getTrainingStats,
listTrainingRecords,
saveMyTrainingProgress,
} from '@/features/chat/api/training.api';
import type {
SafetyProgressState,
TrainingAnswerRecord,
TrainingContentConfig,
TrainingExamMode,
TrainingExamTransitionFeedback,
TrainingQuestion,
TrainingQuestionOption,
TrainingProgressRecord,
TrainingPublishedConfig,
TrainingRecord,
TrainingRecordStatus,
SafetyStage,
TrainingStage,
TrainingStats,
TrainingType,
TrainingWorkspaceView,
} from '@/features/chat/training/training.types';
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
matchesTrainingAgent,
resolveTrainingContentConfig,
resolveTrainingVideoGuide,
resolveTrainingVideoUrl,
resolveSafetyTrainingVideoGuide,
type TrainingGuideLike,
} from '@/features/chat/training/trainingWorkspace.utils';
type TrainingAgentLike = {
id?: number | null;
name?: string | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
@@ -52,14 +59,19 @@ type TrainingUserLike = {
} | null;
} | null | undefined;
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
currentGuides: ComputedRef<TrainingGuideLike[]>;
}
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION: Record<TrainingType, string> = {
onboarding: 'onboarding-v1',
safety: 'safety-v1',
};
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -78,10 +90,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const msg = useMessage();
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
const currentTrainingAgentId = computed<number | null>(() => {
const parsed = Number(currentAgent.value?.id);
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
});
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
const activeView = ref<TrainingWorkspaceView>('learner');
const learnerTab = ref<TrainingType>('onboarding');
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION.onboarding);
const examMode = ref<TrainingExamMode>('unified');
const safetyStage = ref<SafetyStage>('company');
const safetyViewStage = ref<SafetyStage>('company');
const safetyProgress = ref<SafetyProgressState>({
company: 'active',
department: 'pending',
team: 'pending',
});
const stage = ref<TrainingStage>('video');
const currentQuestionIndex = ref(0);
@@ -103,10 +129,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const isHydrated = ref(false);
const hasWarnedPersistFailure = ref(false);
const hasWarnedLoadFailure = ref(false);
const publishedConfig = ref<TrainingPublishedConfig | null>(null);
const trainingConfigLoading = ref(false);
const hrKeyword = ref('');
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
const hrDepartmentFilter = ref('all');
const hrTypeFilter = ref('all');
const records = ref<TrainingRecord[]>([]);
const departmentOptions = ref<string[]>([]);
const stats = ref<TrainingStats>({
@@ -190,12 +219,42 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
questionBank: defaultQuestionBank.value,
},
booleanOptions.value,
publishedConfig.value,
));
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
const passScore = computed(() => trainingContent.value.passScore);
const hasPublishedTrainingConfig = computed(() => publishedConfig.value !== null);
const activeSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyStage.value)
? safetyStage.value as SafetyLearningStage
: null
));
const visibleSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyViewStage.value)
? safetyViewStage.value as SafetyLearningStage
: null
));
const resolveSafetyStageMaterials = (targetStage: SafetyLearningStage | null) => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => !targetStage || resource.trainingLevel === targetStage)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0));
/**
* 按当前安全培训阶段筛选已发布资料。
* AI 触发时机:员工进入公司级、部门级或班组级页面时,只展示后台绑定到当前级别的资料;入职培训仍展示全部非题库资料。
*/
const publishedTrainingMaterials = computed(() => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => learnerTab.value !== 'safety' || resource.trainingLevel === visibleSafetyLearningStage.value)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0)));
const publishedSafetySummary = computed(() => {
const summaries = publishedConfig.value?.settings?.summaryByStage;
if (!summaries || typeof summaries !== 'object') return [];
const value = (summaries as Record<string, unknown>)[safetyViewStage.value];
return Array.isArray(value) ? value.map((item) => String(item)) : [];
});
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
const totalQuestionCount = computed(() => questionBank.value.length);
@@ -213,8 +272,55 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
&& answeredCount.value >= totalQuestionCount.value
));
const canEnterResultStage = computed(() => stage.value === 'result');
const safetyProgressPercent = computed(() => {
if (safetyStage.value === 'company') return 25;
if (safetyStage.value === 'department') return 50;
if (safetyStage.value === 'team') return 75;
if (safetyStage.value === 'exam') return 90;
return 100;
});
const safetyStepItems = computed(() => {
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
{ id: 'department', labelKey: 'chat.training.safety.steps.department' },
{ id: 'team', labelKey: 'chat.training.safety.steps.team' },
{ id: 'exam', labelKey: 'chat.training.safety.steps.exam' },
];
return base.map((item) => {
let status: 'completed' | 'active' | 'pending' | 'locked' = 'pending';
if (item.id === 'company') {
status = safetyProgress.value.company === 'completed'
? 'completed'
: safetyProgress.value.company === 'active' ? 'active' : 'pending';
} else if (item.id === 'department') {
status = safetyProgress.value.department === 'completed'
? 'completed'
: safetyProgress.value.department === 'active' ? 'active' : 'pending';
} else if (item.id === 'team') {
status = safetyProgress.value.team === 'completed'
? 'completed'
: safetyProgress.value.team === 'active' ? 'active' : 'pending';
} else if (item.id === 'exam') {
status = ['exam', 'result'].includes(safetyStage.value)
? (safetyStage.value === 'exam' ? 'active' : 'completed')
: (safetyProgress.value.company === 'completed'
&& safetyProgress.value.department === 'completed'
&& safetyProgress.value.team === 'completed'
? 'pending'
: 'locked');
}
return {
id: item.id,
label: t(item.labelKey),
status,
};
});
});
const learnerProgressPercent = computed(() => {
if (learnerTab.value === 'safety') {
return safetyProgressPercent.value;
}
if (stage.value === 'video') return 25;
if (stage.value === 'summary') return 50;
if (stage.value === 'result') return 100;
@@ -353,14 +459,69 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 按安全培训目标阶段重置三级学习进度。
* AI 触发时机:当员工完成上一级学习、切换安全培训阶段,或后端恢复安全培训初始态时,需要一次性得到完整的三级状态快照。
*/
const resetSafetyProgress = (nextStage: SafetyStage = 'company') => {
const resourceProgressSnapshot = safetyProgress.value.resource_progress
? { ...safetyProgress.value.resource_progress }
: undefined;
safetyStage.value = nextStage;
safetyViewStage.value = nextStage;
if (nextStage === 'company') {
safetyProgress.value = { company: 'active', department: 'pending', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'department') {
safetyProgress.value = { company: 'completed', department: 'active', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'team') {
safetyProgress.value = { company: 'completed', department: 'completed', team: 'active', resource_progress: resourceProgressSnapshot };
return;
}
safetyProgress.value = { company: 'completed', department: 'completed', team: 'completed', resource_progress: resourceProgressSnapshot };
};
/**
* 进入安全培训考试阶段并初始化本轮考试状态。
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
*/
const enterSafetyExam = () => {
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
}
safetyStage.value = 'exam';
safetyViewStage.value = 'exam';
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
};
/**
* 把后端培训记录回填到当前工作区状态。
* AI 触发时机:页面刷新、重新进入聊天页或切换培训类型后,需要把服务端快照完整恢复到本地状态机。
*/
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
if (!record) {
trainingVersion.value = DEFAULT_TRAINING_VERSION[learnerTab.value];
examMode.value = 'unified';
resetSafetyProgress('company');
stage.value = 'video';
resetExamState();
currentJoinDate.value = null;
latestSettledResult.value = null;
return;
}
trainingVersion.value = record.trainingVersion || DEFAULT_TRAINING_VERSION[learnerTab.value];
examMode.value = record.examMode || 'unified';
if (learnerTab.value === 'safety') {
safetyStage.value = record.safetyStage || 'company';
safetyProgress.value = record.safetyProgress;
safetyViewStage.value = record.safetyStage || 'company';
}
stage.value = record.stage;
syncExamQuestionIndex(record.currentQuestionIndex);
score.value = Number(record.score || 0);
@@ -387,8 +548,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 组装当前培训工作区的持久化载荷。
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
*/
const buildProgressPayload = () => ({
stage: stage.value,
agentId: currentTrainingAgentId.value,
stage: learnerTab.value === 'safety'
? (safetyStage.value === 'exam' ? 'exam' : safetyStage.value === 'result' ? 'result' : 'summary')
: stage.value,
trainingVersion: trainingVersion.value,
examMode: examMode.value,
safetyStage: learnerTab.value === 'safety' ? safetyStage.value : null,
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
@@ -401,7 +573,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
if (!isTrainingAgent.value) return;
persistQueue = persistQueue.catch(() => undefined).then(async () => {
try {
const saved = await saveMyTrainingProgress(buildProgressPayload());
const saved = await saveMyTrainingProgress(buildProgressPayload(), learnerTab.value);
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
@@ -433,7 +605,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
try {
const record = await getMyTrainingProgress();
const record = await getMyTrainingProgress(learnerTab.value);
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
@@ -459,6 +631,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
const loadTrainingConfig = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) {
publishedConfig.value = null;
trainingConfigLoading.value = false;
return;
}
trainingConfigLoading.value = true;
try {
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
} catch (error) {
if (!(error instanceof BusinessError && error.status === 401)) {
publishedConfig.value = null;
}
} finally {
trainingConfigLoading.value = false;
}
};
const loadAdminRecords = async () => {
if (!isTrainingAgent.value || !isAdminViewer.value) return;
try {
@@ -466,6 +656,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
};
const [recordData, statsData] = await Promise.all([
listTrainingRecords(query),
@@ -494,6 +685,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hasAuthenticatedUser,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
learnerTab,
],
([agent, loggedIn]) => {
if (!matchesTrainingAgent(agent)) {
@@ -516,6 +708,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
isHydrated.value = false;
void loadTrainingConfig();
void loadTrainingProgress();
},
{ immediate: true },
@@ -528,6 +721,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrTypeFilter,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
@@ -539,11 +733,30 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (learnerTab.value === 'safety') {
if (safetyStage.value === 'company') {
resetSafetyProgress('department');
} else if (safetyStage.value === 'department') {
resetSafetyProgress('team');
} else if (safetyStage.value === 'team') {
resetSafetyProgress('exam');
enterSafetyExam();
}
void persistProgress();
return;
}
stage.value = 'summary';
void persistProgress();
};
const startExam = () => {
if (!hasPublishedTrainingConfig.value) return;
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
@@ -614,6 +827,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const submitExam = () => {
if (!examReadyToSubmit.value) return;
stage.value = 'result';
if (learnerTab.value === 'safety') {
safetyStage.value = 'result';
safetyViewStage.value = 'result';
}
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: score.value,
@@ -625,16 +842,34 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
};
const restartExam = () => {
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
stage.value = 'video';
resetExamState();
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
};
/**
* 按右侧步骤面板切换安全培训阶段。
* AI 触发时机:当员工点击安全培训流程步骤时,只允许查看当前可达阶段,
* 但绝不能因为“返回查看已完成阶段”而重置已保存的完成状态或学习记录。
*/
const setSafetyStage = (nextStage: SafetyStage) => {
if (!hasPublishedTrainingConfig.value) return;
const target = safetyStepItems.value.find((item) => item.id === nextStage);
if (!target || target.status === 'locked') return;
safetyViewStage.value = nextStage;
};
const exportRecords = async () => {
await exportTrainingRecords({
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
});
};
@@ -642,6 +877,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const parts = [
t('chat.training.chatPrompts.hrSummaryPrefix'),
`${t('chat.training.hr.filters.keywordLabel')}: ${hrKeyword.value || t('chat.training.hr.filters.noLimit')}`,
`${t('chat.training.hr.filters.typeLabel')}: ${hrTypeFilter.value === 'all' ? t('chat.training.hr.filters.allTypes') : hrTypeFilter.value === 'safety' ? t('chat.training.hr.filters.typeSafety') : t('chat.training.hr.filters.typeOnboarding')}`,
`${t('chat.training.hr.filters.statusLabel')}: ${hrStatusFilter.value === 'all' ? t('chat.training.hr.filters.allStatuses') : t(`chat.training.hr.status.${hrStatusFilter.value}`)}`,
`${t('chat.training.hr.filters.departmentLabel')}: ${hrDepartmentFilter.value === 'all' ? t('chat.training.hr.filters.allDepartments') : hrDepartmentFilter.value}`,
`${t('chat.training.hr.stats.passRate')}: ${stats.value.passRate}%`,
@@ -691,17 +927,109 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const showVideoModal = ref(false);
const currentViewingMaterialId = ref<number | null>(null);
const materialStartTime = ref<number>(0);
const startMaterialTimer = (materialId: number) => {
currentViewingMaterialId.value = materialId;
materialStartTime.value = Date.now();
};
const stopMaterialTimer = () => {
if (!currentViewingMaterialId.value || !materialStartTime.value) return;
const materialId = String(currentViewingMaterialId.value);
// 累计观看时长(秒)
const durationSeconds = Math.round((Date.now() - materialStartTime.value) / 1000);
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === materialId);
if (resource) {
if (!safetyProgress.value.resource_progress) {
safetyProgress.value.resource_progress = {};
}
const existing = safetyProgress.value.resource_progress[materialId] || { duration: 0, completed: false };
existing.duration += durationSeconds;
const reqDurationMinutes = resource.requiredDuration || 0;
if (existing.duration >= reqDurationMinutes * 60) {
existing.completed = true;
}
safetyProgress.value.resource_progress[materialId] = existing;
checkAndAdvanceStage();
}
currentViewingMaterialId.value = null;
materialStartTime.value = 0;
};
const checkAndAdvanceStage = () => {
const activeStageMaterials = learnerTab.value === 'safety'
? resolveSafetyStageMaterials(activeSafetyLearningStage.value)
: publishedTrainingMaterials.value;
if (!activeStageMaterials.length) return;
const allCompleted = activeStageMaterials.every(m => {
if (m.id == null) return true;
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
return progress?.completed;
});
if (allCompleted) {
if (learnerTab.value === 'safety') {
if (safetyStage.value === 'company') {
resetSafetyProgress('department');
} else if (safetyStage.value === 'department') {
resetSafetyProgress('team');
} else if (safetyStage.value === 'team') {
resetSafetyProgress('exam');
enterSafetyExam();
}
} else {
stage.value = 'summary';
}
void persistProgress();
} else {
void persistProgress();
}
};
const videoUrl = computed(() => {
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
if (!publishedConfig.value) return '';
const visibleGuideStage = visibleSafetyLearningStage.value || activeSafetyLearningStage.value;
const preferredGuideIds = publishedTrainingMaterials.value
.filter((resource) => resource.resourceType === 'agent_guide' && resource.agentGuideId != null)
.map((resource) => Number(resource.agentGuideId));
const uploadedGuide = learnerTab.value === 'safety'
? resolveSafetyTrainingVideoGuide(currentGuides.value, visibleGuideStage || 'company', preferredGuideIds)
: currentGuides.value.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video');
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
const configuredGuide = publishedTrainingMaterials.value
.find((resource) => resource.resourceType === 'agent_guide'
&& resource.resource?.fileType === 'video'
&& (learnerTab.value !== 'safety'
|| !visibleGuideStage
|| !SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|| resource.resource.guideUsage === SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]));
return String(configuredGuide?.resource?.fileUrl || '').trim()
|| uploadedGuideUrl;
});
return {
isTrainingAgent,
isAdminViewer,
isHydrated,
trainingConfigLoading,
hasPublishedTrainingConfig,
publishedTrainingMaterials,
publishedSafetySummary,
activeView,
learnerTab,
trainingVersion,
examMode,
safetyStage,
safetyViewStage,
safetyProgress,
safetyProgressPercent,
safetyStepItems,
stage,
currentQuestionIndex,
currentQuestionNumber,
@@ -731,8 +1059,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentUserEmployeeId,
currentUserDepartment,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrStatusFilter,
hrTypeFilter,
departmentOptions,
filteredRecords,
stats,
@@ -748,8 +1077,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
moveToNextQuestion,
submitExam,
restartExam,
setSafetyStage,
exportRecords,
showVideoModal,
videoUrl,
startMaterialTimer,
stopMaterialTimer,
currentViewingMaterialId,
currentTrainingAgentId,
};
}
@@ -1,12 +1,18 @@
/**
* features/chat/training/training.types.ts
* 用途:定义入职培训聊天工作区的题库、考试进度、HR 统计记录等共享类型。
* 依赖:被 useTrainingWorkspace 与 TrainingWorkspacePanel 共同引用。
* 逻辑:统一约束“学员考试流”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
* 用途:定义员工培训工作区的共享类型,覆盖入职培训、安全培训、考试过程和 HR 统计记录。
* 依赖:被 useTrainingWorkspace、training.api 与 TrainingWorkspacePanel 共同引用。
* 逻辑:统一约束“多培训类型学员流程”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
*/
export type TrainingType = 'onboarding' | 'safety';
export type TrainingStage = 'video' | 'summary' | 'exam' | 'result';
export type TrainingExamMode = 'unified' | 'per_level';
export type SafetyStage = 'company' | 'department' | 'team' | 'exam' | 'result';
export type TrainingWorkspaceView = 'learner' | 'admin';
export type TrainingQuestionType = 'single' | 'boolean';
@@ -32,6 +38,33 @@ export interface TrainingContentConfig {
questionBank: TrainingQuestion[];
}
export interface TrainingPublishedConfigResource {
id?: number | null;
resourceType?: string | null;
trainingLevel?: Exclude<SafetyStage, 'exam' | 'result'> | null;
agentGuideId?: number | null;
inlineQuestions?: unknown[];
title?: string | null;
sortOrder?: number;
requiredDuration?: number;
resource?: {
id?: number;
fileName?: string;
fileType?: string;
fileUrl?: string;
guideUsage?: string;
} | null;
}
export interface TrainingPublishedConfig {
id: number;
trainingType: TrainingType;
version: string;
passScore: number;
settings: Record<string, unknown>;
resources: TrainingPublishedConfigResource[];
}
export interface TrainingAnswerRecord {
questionId: string;
selectedOptionId: string;
@@ -50,8 +83,17 @@ export interface TrainingExamTransitionFeedback {
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
export interface SafetyProgressState {
company: string;
department: string;
team: string;
resource_progress?: Record<string, { duration: number; completed: boolean }>;
}
export interface TrainingRecord {
id: string | number;
trainingType?: TrainingType;
trainingVersion?: string;
name: string;
employeeId: string;
department: string;
@@ -64,6 +106,9 @@ export interface TrainingRecord {
export interface TrainingProgressRecord extends TrainingRecord {
stage: TrainingStage;
examMode: TrainingExamMode;
safetyStage: SafetyStage | null;
safetyProgress: SafetyProgressState;
currentQuestionIndex: number;
passed: boolean;
answerDetails: TrainingAnswerRecord[];
@@ -4,7 +4,7 @@
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
*/
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
import type { TrainingContentConfig, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
type TrainingAgentLike = {
name?: string | null;
@@ -24,6 +24,11 @@ export type TrainingGuideLike = {
} | null | undefined;
export const TRAINING_CONTENT_PROFILE = 'training';
export const SAFETY_STAGE_GUIDE_USAGE_MAP = {
company: 'training_safety_company_video',
department: 'training_safety_department_video',
team: 'training_safety_team_video',
} as const;
/**
* 判断当前 Agent 是否应启用培训工作区。
@@ -143,6 +148,30 @@ export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | u
);
}
/**
* 按安全培训当前级别查找对应视频指南。
* AI 触发时机:当员工在安全培训中切换“公司级 / 部门级 / 班组级”阶段时,工作区必须优先展示该级别绑定的视频,而不是沿用通用安全培训视频。
*/
export function resolveSafetyTrainingVideoGuide(
guides: TrainingGuideLike[] | null | undefined,
safetyStage: keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP | 'exam' | 'result',
preferredGuideIds: number[] = [],
): TrainingGuideLike {
const normalized = Array.isArray(guides) ? guides : [];
const stageUsage = safetyStage in SAFETY_STAGE_GUIDE_USAGE_MAP
? SAFETY_STAGE_GUIDE_USAGE_MAP[safetyStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
: null;
return (
normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video' && (!stageUsage || guide?.guide_usage === stageUsage))
|| normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video')
|| (stageUsage
? normalized.find((guide) => guide?.guide_usage === stageUsage && guide?.file_type === 'video')
: null)
|| normalized.find((guide) => guide?.guide_usage === 'training_safety_video' && guide?.file_type === 'video')
|| null
);
}
/**
* 查找培训工作区优先使用的试题 PDF。
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
@@ -163,24 +192,35 @@ export function resolveTrainingContentConfig(
agent: TrainingAgentLike,
fallback: TrainingContentConfig,
booleanOptions: TrainingQuestionOption[],
publishedConfig?: TrainingPublishedConfig | null,
): TrainingContentConfig {
if (!publishedConfig) {
return { passScore: fallback.passScore, summaryPoints: [], summaryChecklist: [], questionBank: [] };
}
const extraConfig = asRecord(agent?.extra_config);
const trainingConfig = asRecord(extraConfig.training_config);
const mergedConfig = {
...extraConfig,
...trainingConfig,
...(publishedConfig.settings || {}),
};
const publishedQuestions = (publishedConfig?.resources || [])
.filter((resource) => resource.resourceType === 'inline_questions')
.flatMap((resource) => Array.isArray(resource.inlineQuestions) ? resource.inlineQuestions : []);
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
const questionBank = normalizeQuestionBank(
mergedConfig.question_bank ?? mergedConfig.questionBank,
publishedQuestions.length
? publishedQuestions
: mergedConfig.questions ?? mergedConfig.question_bank ?? mergedConfig.questionBank,
booleanOptions,
);
return {
passScore: normalizePassScore(
mergedConfig.pass_score ?? mergedConfig.passScore,
publishedConfig?.passScore ?? mergedConfig.pass_score ?? mergedConfig.passScore,
fallback.passScore || DEFAULT_PASS_SCORE,
),
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,