Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # .env.dev # .env.test # backend/app/api/__init__.py # docs/funclist.md # frontend/src/features/chat/composables/useChatPage.ts
This commit is contained in:
commit
f72c1c9f0e
101 files changed
+11163
-334
No files matched your search
@@ -650,6 +650,7 @@ export function useChat() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAssetHistory.ts
|
||||
* 用途:管理固定资产履历检索、友好提示与文件预览跳转。
|
||||
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
|
||||
* 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口;
|
||||
* 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { searchAssetHistoryFiles } from '../api/chat.api';
|
||||
import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types';
|
||||
import type { ComputedRef } from 'vue';
|
||||
|
||||
interface UseChatAssetHistoryOptions {
|
||||
agentId: ComputedRef<number>;
|
||||
openPreview: (file: SourceFileLink) => Promise<void>;
|
||||
warn: (message: string) => void;
|
||||
}
|
||||
|
||||
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
|
||||
const open = ref(false);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const assetId = ref('');
|
||||
const assetName = ref('');
|
||||
const items = ref<AssetHistoryFileItem[]>([]);
|
||||
|
||||
const close = () => {
|
||||
open.value = false;
|
||||
loading.value = false;
|
||||
error.value = '';
|
||||
items.value = [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 检索资产履历并直接打开最佳预览结果。
|
||||
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
|
||||
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
|
||||
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
|
||||
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
|
||||
*/
|
||||
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
|
||||
const normalizedAssetId = String(nextAssetId || '').trim();
|
||||
const normalizedAssetName = String(nextAssetName || '').trim();
|
||||
if (loading.value) {
|
||||
return;
|
||||
}
|
||||
if (!normalizedAssetId && !normalizedAssetName) {
|
||||
options.warn('当前资产缺少可用于检索履历的编号或名称');
|
||||
return;
|
||||
}
|
||||
|
||||
assetId.value = normalizedAssetId;
|
||||
assetName.value = normalizedAssetName;
|
||||
open.value = false;
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
items.value = [];
|
||||
try {
|
||||
const result = await searchAssetHistoryFiles(options.agentId.value, {
|
||||
asset_id: normalizedAssetId,
|
||||
asset_name: normalizedAssetName,
|
||||
});
|
||||
items.value = Array.isArray(result?.items) ? result.items : [];
|
||||
const bestMatch = items.value[0];
|
||||
if (!bestMatch) {
|
||||
const displayName = normalizedAssetId || normalizedAssetName;
|
||||
options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`);
|
||||
return;
|
||||
}
|
||||
await openHistoryFilePreview(bestMatch);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '检索资产履历失败';
|
||||
error.value = message;
|
||||
options.warn(`履历查询失败:${message}`);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开履历文件预览。
|
||||
* AI 触发时机:当用户在“资产履历”列表里点击某一条“查看履历”时调用。
|
||||
* 核心逻辑:先关闭履历候选列表弹窗,避免与文件预览弹窗叠层冲突,再交给聊天页通用预览器处理。
|
||||
* 参数约束:必须传入带有 name/url 的有效履历文件项,url 必须是后端允许代理的共享盘路径。
|
||||
*/
|
||||
const openHistoryFilePreview = async (item: AssetHistoryFileItem) => {
|
||||
close();
|
||||
await options.openPreview({
|
||||
name: item.name,
|
||||
url: item.url,
|
||||
actualExt: item.actual_ext,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
open,
|
||||
loading,
|
||||
error,
|
||||
assetId,
|
||||
assetName,
|
||||
items,
|
||||
close,
|
||||
openHistory,
|
||||
openHistoryFilePreview,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface AgentGuide {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
guide_usage?: string;
|
||||
file_url?: string;
|
||||
file_path?: string;
|
||||
remark?: string;
|
||||
@@ -42,8 +43,9 @@ export function useChatGuides(options: UseChatGuidesOptions) {
|
||||
guides.value = [];
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
const first = guides.value[0];
|
||||
const openModal = (guideId?: number | null) => {
|
||||
const preferred = guideId ? guides.value.find((g) => g.id === guideId) : null;
|
||||
const first = preferred || guides.value[0];
|
||||
if (!first) return;
|
||||
activeGuideId.value = first.id;
|
||||
showModal.value = true;
|
||||
|
||||
@@ -25,8 +25,10 @@ import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
@@ -106,6 +108,7 @@ export function useChatPage() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
@@ -164,6 +167,11 @@ export function useChatPage() {
|
||||
openPreview,
|
||||
parsePlmPreviewLink,
|
||||
} = sourceFiles;
|
||||
const assetHistory = useChatAssetHistory({
|
||||
agentId: currentAgentId,
|
||||
openPreview,
|
||||
warn: (text) => msg.warning(text),
|
||||
});
|
||||
|
||||
watch(currentAgentId, (id) => {
|
||||
chatStore.setCurrentAgentId(id > 0 ? id : null);
|
||||
@@ -342,6 +350,7 @@ export function useChatPage() {
|
||||
const training = useTrainingWorkspace({
|
||||
currentAgent: computed(() => agent.currentAgent.value),
|
||||
currentUser: computed(() => currentUser.value),
|
||||
currentGuides: computed(() => chatGuides.guides.value),
|
||||
pushLocalAssistantMessage,
|
||||
pushLocalUserMessage,
|
||||
});
|
||||
@@ -353,6 +362,7 @@ export function useChatPage() {
|
||||
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
|
||||
parsePlmPreviewLink,
|
||||
openPreview,
|
||||
openAssetHistory: assetHistory.openHistory,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
getSourceLinks,
|
||||
@@ -479,6 +489,7 @@ export function useChatPage() {
|
||||
isThinking,
|
||||
shippingActionBusy,
|
||||
conversationId,
|
||||
viewId,
|
||||
input,
|
||||
browser,
|
||||
queryPreview,
|
||||
@@ -492,6 +503,7 @@ export function useChatPage() {
|
||||
queryPreviewLoading: queryPreview.loading,
|
||||
queryPreviewError: queryPreview.error,
|
||||
queryPreviewState: queryPreview.state,
|
||||
assetHistory,
|
||||
...agent,
|
||||
agentGuides: chatGuides.guides,
|
||||
showGuideModal: chatGuides.showModal,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingProgress,
|
||||
@@ -15,6 +17,8 @@ import {
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
TrainingAnswerRecord,
|
||||
TrainingContentConfig,
|
||||
TrainingExamTransitionFeedback,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingProgressRecord,
|
||||
@@ -24,6 +28,13 @@ import type {
|
||||
TrainingStats,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
matchesTrainingAgent,
|
||||
resolveTrainingContentConfig,
|
||||
resolveTrainingVideoGuide,
|
||||
resolveTrainingVideoUrl,
|
||||
type TrainingGuideLike,
|
||||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
@@ -36,44 +47,41 @@ type TrainingUserLike = {
|
||||
real_name?: string | null;
|
||||
employee_id?: string | null;
|
||||
department?: string | null;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
} | null;
|
||||
} | null | undefined;
|
||||
|
||||
export interface UseTrainingWorkspaceOptions {
|
||||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||||
currentUser: ComputedRef<TrainingUserLike>;
|
||||
currentGuides: ComputedRef<TrainingGuideLike[]>;
|
||||
pushLocalAssistantMessage?: (content: string) => Promise<void>;
|
||||
pushLocalUserMessage?: (content: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||||
* AI 触发时机:当需要把培训 UI 只挂在指定 Agent 上时使用,优先读 extra_config 显式开关,避免误伤其他聊天场景。
|
||||
*/
|
||||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
const explicitFlags = [
|
||||
extraConfig.training_workspace_enabled,
|
||||
extraConfig.training_mode,
|
||||
extraConfig.training_agent,
|
||||
];
|
||||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||||
return true;
|
||||
}
|
||||
const name = String(agent?.name || '').trim();
|
||||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||||
}
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
|
||||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
/**
|
||||
* 按百分制计算当前答题得分。
|
||||
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
|
||||
*/
|
||||
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
|
||||
if (totalQuestionCount <= 0) return 0;
|
||||
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
|
||||
};
|
||||
|
||||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { currentAgent, currentUser, currentGuides, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { t, tm } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
@@ -83,10 +91,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const selectedOptionId = ref('');
|
||||
const answerLocked = ref(false);
|
||||
const currentFeedbackCorrect = ref(false);
|
||||
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
|
||||
const latestSettledResult = ref<{
|
||||
score: number;
|
||||
correctCount: number;
|
||||
wrongCount: number;
|
||||
isPassed: boolean;
|
||||
} | null>(null);
|
||||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||||
const completionDate = ref<string | null>(null);
|
||||
const currentJoinDate = ref<string | null>(null);
|
||||
const isHydrated = ref(false);
|
||||
const hasWarnedPersistFailure = ref(false);
|
||||
const hasWarnedLoadFailure = ref(false);
|
||||
|
||||
const hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
@@ -110,12 +127,12 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
const summaryPoints = computed(() => {
|
||||
const defaultSummaryPoints = computed(() => {
|
||||
const raw = tm('chat.training.summaryPoints');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
|
||||
const summaryChecklist = computed(() => {
|
||||
const defaultSummaryChecklist = computed(() => {
|
||||
const raw = tm('chat.training.summaryChecklist');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
@@ -134,7 +151,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}));
|
||||
});
|
||||
|
||||
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
|
||||
const mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.map((item) => {
|
||||
const type = String(item.type || 'single') as TrainingQuestion['type'];
|
||||
const rawOptions = Array.isArray(item.options) ? item.options : [];
|
||||
const options = type === 'boolean'
|
||||
@@ -152,14 +169,32 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
explanation: String(item.explanation || ''),
|
||||
options,
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
|
||||
|
||||
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
|
||||
currentAgent.value,
|
||||
{
|
||||
passScore: DEFAULT_PASS_SCORE,
|
||||
summaryPoints: defaultSummaryPoints.value,
|
||||
summaryChecklist: defaultSummaryChecklist.value,
|
||||
questionBank: defaultQuestionBank.value,
|
||||
},
|
||||
booleanOptions.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 currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||||
const answeredCount = computed(() => answerRecords.value.length);
|
||||
const correctCount = computed(() => answerRecords.value.filter((item) => item.correct).length);
|
||||
const wrongCount = computed(() => answerRecords.value.filter((item) => !item.correct).length);
|
||||
const isPassed = computed(() => score.value >= 90);
|
||||
const isPassed = computed(() => score.value >= passScore.value);
|
||||
|
||||
const learnerProgressPercent = computed(() => {
|
||||
if (stage.value === 'video') return 25;
|
||||
@@ -191,10 +226,67 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
answerRecords.value = [];
|
||||
completionDate.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
|
||||
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
|
||||
*/
|
||||
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
|
||||
if (!question) return optionId;
|
||||
return question.options?.find((item) => item.id === optionId)?.label || optionId;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
|
||||
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
|
||||
*/
|
||||
const buildExamFeedback = (
|
||||
question: TrainingQuestion | null,
|
||||
answerRecord: TrainingAnswerRecord | null | undefined,
|
||||
scoreAfterAnswer: number,
|
||||
): TrainingExamTransitionFeedback | null => {
|
||||
if (!question || !answerRecord) return null;
|
||||
return {
|
||||
questionId: question.id,
|
||||
questionPrompt: question.prompt,
|
||||
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
|
||||
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
|
||||
explanation: question.explanation,
|
||||
correct: Boolean(answerRecord.correct),
|
||||
scoreAfterAnswer,
|
||||
};
|
||||
};
|
||||
|
||||
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
|
||||
question?.type === 'boolean'
|
||||
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
|
||||
: t('chat.training.chatPrompts.assistantQuestionSingleType')
|
||||
);
|
||||
|
||||
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
|
||||
if (!question) return '';
|
||||
const optionLines = (question.options || []).map((option) => option.label).join('\n');
|
||||
return [
|
||||
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
|
||||
optionLines,
|
||||
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
|
||||
].filter(Boolean).join('\n');
|
||||
};
|
||||
|
||||
const buildSummaryAssistantMessage = () => {
|
||||
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
|
||||
return [
|
||||
t('chat.training.chatPrompts.assistantSummaryIntro'),
|
||||
summaryLines,
|
||||
'',
|
||||
t('chat.training.chatPrompts.assistantSummaryReady'),
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
const syncAnswerStateForCurrentQuestion = () => {
|
||||
const questionId = currentQuestion.value?.id;
|
||||
const currentAnswer = questionId
|
||||
@@ -210,6 +302,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
currentJoinDate.value = null;
|
||||
latestSettledResult.value = null;
|
||||
return;
|
||||
}
|
||||
stage.value = record.stage;
|
||||
@@ -219,6 +312,22 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
|
||||
completionDate.value = record.completionDate;
|
||||
currentJoinDate.value = record.joinDate || null;
|
||||
latestExamFeedback.value = null;
|
||||
if (record.stage === 'result') {
|
||||
latestSettledResult.value = {
|
||||
score: Number(record.score || 0),
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
|
||||
};
|
||||
}
|
||||
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
|
||||
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
|
||||
const previousAnswer = previousQuestion
|
||||
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
|
||||
: null;
|
||||
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
|
||||
}
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
@@ -237,13 +346,23 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||||
try {
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||||
hasWarnedPersistFailure.value = false;
|
||||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||||
completionDate.value = saved.completionDate;
|
||||
if (isAdminViewer.value) {
|
||||
void loadAdminRecords();
|
||||
}
|
||||
} catch {
|
||||
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
|
||||
} catch (error) {
|
||||
if (!hasWarnedPersistFailure.value) {
|
||||
hasWarnedPersistFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.error({
|
||||
title: t('chat.training.errors.persistTitle'),
|
||||
message: `${t('chat.training.errors.persistBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
await persistQueue;
|
||||
@@ -251,10 +370,33 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
|
||||
const loadTrainingProgress = async () => {
|
||||
if (!isTrainingAgent.value) return;
|
||||
if (!hasAuthenticatedUser.value) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const record = await getMyTrainingProgress();
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(record);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
|
||||
if (error instanceof BusinessError && error.status === 401) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
return;
|
||||
}
|
||||
if (!hasWarnedLoadFailure.value) {
|
||||
hasWarnedLoadFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.warning({
|
||||
title: t('chat.training.errors.loadTitle'),
|
||||
message: `${t('chat.training.errors.loadBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
applyProgressRecord(null);
|
||||
} finally {
|
||||
isHydrated.value = true;
|
||||
@@ -290,26 +432,49 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
watch(currentAgent, (agent) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
[
|
||||
currentAgent,
|
||||
hasAuthenticatedUser,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([agent, loggedIn]) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!loggedIn) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
|
||||
[
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
hrKeyword,
|
||||
hrStatusFilter,
|
||||
hrDepartmentFilter,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([enabled, canView]) => {
|
||||
if (!enabled || !canView) return;
|
||||
void loadAdminRecords();
|
||||
@@ -320,37 +485,66 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const markVideoCompleted = () => {
|
||||
stage.value = 'summary';
|
||||
// 立即推入本地助手消息(复盘卡片)
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
if (totalQuestionCount.value <= 0) {
|
||||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||||
return;
|
||||
}
|
||||
stage.value = 'exam';
|
||||
attemptCount.value += 1;
|
||||
resetExamState();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.startExamCommand'));
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const selectAnswer = (optionId: string) => {
|
||||
if (answerLocked.value || !currentQuestion.value) return;
|
||||
const answeredQuestion = currentQuestion.value;
|
||||
selectedOptionId.value = optionId;
|
||||
const isCorrect = optionId === currentQuestion.value.answer;
|
||||
const isCorrect = optionId === answeredQuestion.answer;
|
||||
currentFeedbackCorrect.value = isCorrect;
|
||||
if (isCorrect) {
|
||||
score.value += 5;
|
||||
}
|
||||
answerRecords.value.push({
|
||||
questionId: currentQuestion.value.id,
|
||||
const nextCorrectAnswerCount = correctCount.value + (isCorrect ? 1 : 0);
|
||||
const nextScore = calculateTrainingScore(nextCorrectAnswerCount, totalQuestionCount.value);
|
||||
score.value = nextScore;
|
||||
const answerRecord: TrainingAnswerRecord = {
|
||||
questionId: answeredQuestion.id,
|
||||
selectedOptionId: optionId,
|
||||
correct: isCorrect,
|
||||
});
|
||||
answerLocked.value = true;
|
||||
};
|
||||
answerRecords.value.push(answerRecord);
|
||||
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
|
||||
|
||||
// 推入用户选择的答案到聊天流
|
||||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||||
const label = getQuestionOptionLabel(answeredQuestion, optionId);
|
||||
void pushLocalUserMessage?.(label);
|
||||
|
||||
// [STEP 1] 最后一题直接进入结算,对齐文档里的“答完即公布最终成绩”。
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
latestSettledResult.value = {
|
||||
score: nextScore,
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: nextScore >= passScore.value,
|
||||
};
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
|
||||
// [STEP 2] 非最后一题则在聊天流里自动反馈上一题,并紧接着展示下一题。
|
||||
currentQuestionIndex.value += 1;
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
@@ -364,7 +558,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
@@ -372,17 +566,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
stage.value = 'summary';
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.restartExamCommand'));
|
||||
// 重新推回视频导学,强制补考再次完整经过“视频 -> 复盘 -> 开考”链路。
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||||
};
|
||||
|
||||
const exportRecords = async () => {
|
||||
@@ -405,21 +601,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
const learnerChatPrompt = computed(() => {
|
||||
// 阶段 1:破冰与视频导学
|
||||
if (stage.value === 'video') {
|
||||
return `👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。\n\n▶️ 请先点击观看 [入职培训视频]。观看完毕后,请回复【已看完】。`;
|
||||
}
|
||||
// 阶段 2:知识点串讲
|
||||
if (stage.value === 'summary') {
|
||||
return `${t('chat.training.chatPrompts.afterVideo')}\n\n参考知识点:\n${summaryPoints.value.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
|
||||
}
|
||||
// 阶段 4:结算
|
||||
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
|
||||
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
|
||||
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.afterPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.afterFail', { score: score.value });
|
||||
}
|
||||
// 阶段 3:互动测试
|
||||
return t('chat.training.chatPrompts.examInProgress', {
|
||||
index: currentQuestionIndex.value + 1,
|
||||
total: totalQuestionCount.value,
|
||||
@@ -427,11 +616,36 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 新建培训聊天会话时使用的统一提醒文案。
|
||||
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
|
||||
*/
|
||||
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
|
||||
passScore: passScore.value,
|
||||
}));
|
||||
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
|
||||
|
||||
const learnerAssistantMessage = computed(() => {
|
||||
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
|
||||
if (stage.value === 'video') {
|
||||
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
|
||||
}
|
||||
if (stage.value === 'summary') {
|
||||
return buildSummaryAssistantMessage();
|
||||
}
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
|
||||
}
|
||||
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
|
||||
});
|
||||
|
||||
const showVideoModal = ref(false);
|
||||
const videoUrl = computed(() => {
|
||||
const extraConfig = currentAgent.value?.extra_config || {};
|
||||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||||
return customUrl || DEFAULT_TRAINING_VIDEO_URL;
|
||||
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
|
||||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||||
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -443,12 +657,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentQuestionIndex,
|
||||
currentQuestion,
|
||||
totalQuestionCount,
|
||||
passScore,
|
||||
answeredCount,
|
||||
score,
|
||||
attemptCount,
|
||||
selectedOptionId,
|
||||
answerLocked,
|
||||
currentFeedbackCorrect,
|
||||
latestExamFeedback,
|
||||
latestSettledResult,
|
||||
answerRecords,
|
||||
completionDate,
|
||||
summaryPoints,
|
||||
@@ -467,6 +684,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
filteredRecords,
|
||||
stats,
|
||||
learnerChatPrompt,
|
||||
newSessionReminderMessage,
|
||||
shouldShowNewSessionReminder,
|
||||
learnerAssistantMessage,
|
||||
managementChatPrompt,
|
||||
markVideoCompleted,
|
||||
startExam,
|
||||
|
||||
Reference in new issue
Block a user