293 lines
11 KiB
TypeScript
293 lines
11 KiB
TypeScript
/**
|
|
* features/chat/training/trainingWorkspace.utils.ts
|
|
* 用途:沉淀新人培训工作区的纯函数规则,便于前端复用与单测。
|
|
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
|
|
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库、复盘配置与动态进度文案。
|
|
*/
|
|
import type { TrainingContentConfig, TrainingProgressItem, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
|
|
|
|
type TrainingAgentLike = {
|
|
name?: string | null;
|
|
handler_config?: {
|
|
content_profile?: string | null;
|
|
[key: string]: unknown;
|
|
} | null;
|
|
extra_config?: Record<string, unknown> | null;
|
|
} | null | undefined;
|
|
|
|
export type TrainingGuideLike = {
|
|
id?: number | null;
|
|
file_type?: string | null;
|
|
guide_usage?: string | null;
|
|
file_url?: string | null;
|
|
file_path?: string | null;
|
|
} | 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 是否应启用培训工作区。
|
|
* AI 触发时机:聊天页决定是否渲染培训主链时调用;优先 content_profile / extra_config,禁止名称启发式。
|
|
*/
|
|
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
|
const extraConfig = agent?.extra_config || {};
|
|
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
|
|
return false;
|
|
}
|
|
const contentProfile = String(agent?.handler_config?.content_profile || '').trim();
|
|
if (contentProfile === TRAINING_CONTENT_PROFILE) {
|
|
return true;
|
|
}
|
|
const explicitFlags = [
|
|
extraConfig.training_workspace_enabled,
|
|
extraConfig.training_mode,
|
|
extraConfig.training_agent,
|
|
];
|
|
return explicitFlags.some((value) => value === true || value === 'true');
|
|
}
|
|
|
|
const asRecord = (value: unknown): Record<string, unknown> => (
|
|
value && typeof value === 'object' && !Array.isArray(value)
|
|
? value as Record<string, unknown>
|
|
: {}
|
|
);
|
|
|
|
const normalizeStringList = (value: unknown): string[] => {
|
|
if (!Array.isArray(value)) return [];
|
|
return value
|
|
.map((item) => String(item || '').trim())
|
|
.filter(Boolean);
|
|
};
|
|
|
|
const normalizePassScore = (value: unknown, fallback: number): number => {
|
|
const parsed = Number(value);
|
|
if (!Number.isFinite(parsed)) return fallback;
|
|
return Math.max(0, Math.min(100, Math.round(parsed)));
|
|
};
|
|
|
|
const normalizeQuestionOptionList = (value: unknown): TrainingQuestionOption[] => {
|
|
if (!Array.isArray(value)) return [];
|
|
return value
|
|
.map((item, index) => {
|
|
if (typeof item === 'string') {
|
|
const label = item.trim();
|
|
if (!label) return null;
|
|
return {
|
|
id: String.fromCharCode(97 + index),
|
|
label,
|
|
};
|
|
}
|
|
const raw = asRecord(item);
|
|
const id = String(raw.id || '').trim() || String.fromCharCode(97 + index);
|
|
const label = String(raw.label || '').trim();
|
|
if (!label) return null;
|
|
return { id, label };
|
|
})
|
|
.filter((item): item is TrainingQuestionOption => Boolean(item));
|
|
};
|
|
|
|
const normalizeQuestionBank = (
|
|
value: unknown,
|
|
booleanOptions: TrainingQuestionOption[],
|
|
): TrainingQuestion[] => {
|
|
if (!Array.isArray(value)) return [];
|
|
return value
|
|
.map((item, index): TrainingQuestion | null => {
|
|
const raw = asRecord(item);
|
|
const rawType = String(raw.type || 'single').trim().toLowerCase();
|
|
const typeAliases: Record<string, TrainingQuestion['type']> = {
|
|
single: 'single',
|
|
choice: 'single',
|
|
select: 'single',
|
|
boolean: 'boolean',
|
|
bool: 'boolean',
|
|
judgment: 'boolean',
|
|
judge: 'boolean',
|
|
'判断': 'boolean',
|
|
'判断题': 'boolean',
|
|
'3': 'boolean',
|
|
true_false: 'boolean',
|
|
truefalse: 'boolean',
|
|
fill: 'fill',
|
|
blank: 'fill',
|
|
fill_blank: 'fill',
|
|
essay: 'essay',
|
|
qa: 'essay',
|
|
'问答': 'essay',
|
|
'问答题': 'essay',
|
|
'简答': 'essay',
|
|
'简答题': 'essay',
|
|
'4': 'essay',
|
|
question_answer: 'essay',
|
|
short_answer: 'essay',
|
|
};
|
|
const type = typeAliases[rawType] || 'single';
|
|
const prompt = String(raw.prompt || '').trim();
|
|
if (!prompt) return null;
|
|
const options = type === 'boolean'
|
|
? booleanOptions
|
|
: type === 'single' ? normalizeQuestionOptionList(raw.options) : [];
|
|
if (type === 'single' && options.length < 2) return null;
|
|
const fallbackAnswer = type === 'boolean'
|
|
? 'true'
|
|
: String(options[0]?.id || '').trim();
|
|
const answer = String(raw.answer || '').trim();
|
|
const optionIds = options.map((option) => option.id);
|
|
return {
|
|
id: String(raw.id || '').trim() || `q${index + 1}`,
|
|
type,
|
|
prompt,
|
|
answer: type === 'fill' || type === 'essay' ? answer : optionIds.includes(answer) ? answer : fallbackAnswer,
|
|
scoreRatio: Number(raw.score_ratio || raw.scoreRatio || 1),
|
|
explanation: String(raw.explanation || '').trim(),
|
|
options,
|
|
};
|
|
})
|
|
.filter((item): item is TrainingQuestion => Boolean(item));
|
|
};
|
|
|
|
const DEFAULT_PASS_SCORE = 90;
|
|
|
|
/**
|
|
* 解析学员侧培训进度项。
|
|
* AI 触发时机:当工作区需要按后台配置渲染流程卡片时调用;若后台未配置任何有效项,则返回空数组供页面整体隐藏该模块。
|
|
*/
|
|
export function resolveLearnerProgressItems(publishedConfig?: TrainingPublishedConfig | null): TrainingProgressItem[] {
|
|
const settings = asRecord(publishedConfig?.settings);
|
|
const rawItems = settings.progress_items;
|
|
if (!Array.isArray(rawItems)) return [];
|
|
|
|
const seenStages = new Set<string>();
|
|
return rawItems
|
|
.map((item) => {
|
|
const raw = asRecord(item);
|
|
const stage = String(raw.stage || raw.key || '').trim();
|
|
const label = String(raw.label || raw.title || '').trim();
|
|
if (!stage || !label || seenStages.has(stage)) return null;
|
|
seenStages.add(stage);
|
|
return { stage, label };
|
|
})
|
|
.filter((item): item is TrainingProgressItem => Boolean(item));
|
|
}
|
|
|
|
/**
|
|
* 读取学员侧长文本配置。
|
|
* AI 触发时机:培训进度说明和步骤引导只在后台返回非空文本时渲染,避免页面出现空占位。
|
|
*/
|
|
export function resolveLearnerCopyText(
|
|
publishedConfig: TrainingPublishedConfig | null | undefined,
|
|
key: 'progress_hint_text' | 'step_intro_text',
|
|
): string {
|
|
const settings = asRecord(publishedConfig?.settings);
|
|
return String(settings[key] || '').trim();
|
|
}
|
|
|
|
/**
|
|
* 解析培训视频地址。
|
|
* AI 触发时机:当培训工作区需要决定播放哪个培训视频时使用,若 Agent 未配置专属视频,则回退到默认地址。
|
|
*/
|
|
export function resolveTrainingVideoUrl(agent: TrainingAgentLike, fallbackUrl: string): string {
|
|
const extraConfig = agent?.extra_config || {};
|
|
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
|
return customUrl || fallbackUrl;
|
|
}
|
|
|
|
/**
|
|
* 查找培训工作区优先使用的视频指南。
|
|
* AI 触发时机:当培训工作区需要从后台上传资料中挑选正式培训视频时使用,优先选显式标记为 training_video 的文件。
|
|
*/
|
|
export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
|
const normalized = Array.isArray(guides) ? guides : [];
|
|
return (
|
|
normalized.find((guide) => guide?.guide_usage === 'training_video' && guide?.file_type === 'video')
|
|
|| normalized.find((guide) => guide?.file_type === 'video')
|
|
|| null
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 按安全培训当前级别查找对应视频指南。
|
|
* 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 错当成考试资料。
|
|
*/
|
|
export function resolveTrainingExamPdfGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
|
const normalized = Array.isArray(guides) ? guides : [];
|
|
return (
|
|
normalized.find((guide) => guide?.guide_usage === 'training_exam_pdf' && guide?.file_type === 'pdf')
|
|
|| null
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 解析培训工作区的后台配置。
|
|
* AI 触发时机:当培训工作区需要优先消费 Agent extra_config 中的题库、复盘要点和及格线时使用;若后台未配置,则逐项回退到前端默认值。
|
|
*/
|
|
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(
|
|
publishedQuestions.length
|
|
? publishedQuestions
|
|
: mergedConfig.questions ?? mergedConfig.question_bank ?? mergedConfig.questionBank,
|
|
booleanOptions,
|
|
);
|
|
|
|
return {
|
|
passScore: normalizePassScore(
|
|
publishedConfig?.passScore ?? mergedConfig.pass_score ?? mergedConfig.passScore,
|
|
fallback.passScore || DEFAULT_PASS_SCORE,
|
|
),
|
|
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,
|
|
summaryChecklist: summaryChecklist.length ? summaryChecklist : fallback.summaryChecklist,
|
|
questionBank: questionBank.length ? questionBank : fallback.questionBank,
|
|
};
|
|
}
|