fix(training): 修复出国培训规则培训bug

This commit is contained in:
runny committed 2026-09-15 09:55:47 +08:00
1 parent 683f602475
commit 258098ea7b
13 files changed
+280 -26

No files matched your search

+14
View File
@@ -27,6 +27,7 @@ from app.services.training_config_service import get_published_config, list_trai
from app.services.lean_training_service import (
LEAN_TRAINING_TYPE,
create_or_update_weekly_task,
export_dashboard_excel,
get_current_weekly_task,
get_weekly_task_for_admin,
list_dashboard,
@@ -275,3 +276,16 @@ def get_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
return ok(list_dashboard(raw_task_id))
@training_admin_bp.route("/lean-training/dashboard/export", methods=["GET"])
def export_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
file_data, file_name = export_dashboard_excel(raw_task_id)
return send_file(
BytesIO(file_data),
as_attachment=True,
download_name=file_name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@@ -10,8 +10,10 @@ backend/app/services/lean_training_service.py
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import func, or_, select
from app.core.errors import NotFoundError, ValidationError
@@ -30,6 +32,21 @@ LEAN_TRAINING_TYPE = "lean_management"
MIN_SUMMARY_LENGTH = 50
def _format_dashboard_datetime(value: str | None) -> str:
"""将看板 ISO 时间统一为页面展示的年月日时分格式。"""
text = str(value or "").strip()
return text[:16].replace("T", " ") if text else ""
def _dashboard_status_label(status: str | None) -> str:
"""将看板状态转换为页面一致的中文文案。"""
return {
"completed": "已完成",
"overdue": "已延期",
"in_progress": "进行中",
}.get(str(status or ""), str(status or ""))
def _get_lean_config() -> TrainingConfig:
"""读取已发布精益培训配置,未配置时阻止创建周任务。"""
config = db.session.execute(
@@ -441,3 +458,43 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
(completed if row["status"] == "completed" else incomplete).append(row)
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
def export_dashboard_excel(task_id: int | None) -> tuple[bytes, str]:
"""导出指定精益培训期次的完整看板数据。
Args:
task_id: 指定周任务 ID;为空时按看板规则导出最新一期。
Returns:
Excel 二进制内容与下载文件名;无可导出任务时抛出 NotFoundError。
"""
dashboard = list_dashboard(task_id)
task = dashboard["task"]
if not task:
raise NotFoundError("Lean training weekly task not found")
workbook = Workbook()
worksheet = workbook.active
worksheet.title = "lean_training"
worksheet.append(["期号", "培训周次", "截止时间", "工号", "姓名", "部门", "视频名称", "观看时间", "状态", "学习感悟", "完成时间"])
rows = [*dashboard["completed"], *dashboard["incomplete"]]
for row in rows:
videos = row.get("videos") or []
worksheet.append([
task.get("week_index") or "",
task.get("week_key") or "",
_format_dashboard_datetime(task.get("due_at")),
row.get("employee_id") or "",
row.get("name") or "",
row.get("department") or "",
"\n".join(str(video.get("name") or "") for video in videos),
"\n".join(_format_dashboard_datetime(video.get("watched_at")) for video in videos),
_dashboard_status_label(row.get("status")),
row.get("summary_text") or "",
_format_dashboard_datetime(row.get("completed_at")),
])
buffer = BytesIO()
workbook.save(buffer)
filename = f"lean_training_dashboard_{task['week_key']}.xlsx"
return buffer.getvalue(), filename
+24 -3
View File
@@ -24,6 +24,11 @@ from app.services.training_config_service import get_published_config
TRAINING_STAGES = {"video", "summary", "exam", "result"}
TRAINING_TYPES = {"onboarding", "safety"}
VIDEO_ONLY_TRAINING_TYPES = {
"overseas_regulations",
"overseas_regulations_training",
"overseas_training",
}
TRAINING_EXAM_MODES = {"unified", "per_level"}
SAFETY_STAGES = {"company", "department", "team", "exam", "result"}
SAFETY_LEVEL_KEYS = ("company", "department", "team")
@@ -69,6 +74,21 @@ def _normalize_training_type(value: Any) -> str:
return text
def _is_overseas_regulations_training(training_type: str) -> bool:
"""
判断培训类型是否为出国规章视频培训。
Args:
training_type: 已标准化的培训类型编码。
Returns:
是否应以完整观看视频作为一次培训完成。
"""
if training_type in VIDEO_ONLY_TRAINING_TYPES:
return True
published = get_published_config(training_type)
return "出国规章培训" in str((published or {}).get("name") or "")
def _normalize_training_version(value: Any, training_type: str) -> str:
"""
规范培训版本号,未传时按培训类型补默认值。
@@ -538,7 +558,7 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
else:
passed = bool(payload.get("passed")) or (stage == "result" and score >= pass_score)
if stage == "result" and question_bank and not answer_details:
if stage == "result" and question_bank and not answer_details and not _is_overseas_regulations_training(training_type):
raise ValidationError("answer_details is required when submitting result", details={"field": "answer_details"})
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
safety_stage = None
@@ -661,19 +681,20 @@ def export_training_records_excel(records: Iterable[TrainingRecord]) -> tuple[by
workbook = Workbook()
worksheet = workbook.active
worksheet.title = "training"
worksheet.append(["入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态"])
worksheet.append(["入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态"])
for record in records:
worksheet.append(
[
record.join_date.isoformat() if record.join_date else "",
record.completion_time.date().isoformat() if record.completion_time else "",
record.training_type or "",
record.department or "",
record.name or "",
record.employee_id or "",
record.score if record.score is not None else "",
record.attempt_count or 0,
_derive_status(record),
{"passed": "已通过", "failed": "未通过", "in_progress": "进行中"}.get(_derive_status(record), _derive_status(record)),
]
)
+60 -5
View File
@@ -18,7 +18,7 @@ import pytest
from app import db
from app.core.errors import ValidationError
from app.models import Agent, AgentGuide, TrainingConfig, TrainingConfigResource, TrainingRecord, User
from app.services import training_config_service, training_service
from app.services import lean_training_service, training_config_service, training_service
from app.services.training_service import _grade_answer_details, _normalize_question_bank
from app.api.chat import preview_support
@@ -236,6 +236,38 @@ def test_training_user_progress_round_trip_and_completion(client, app):
assert record.completion_time is not None
def test_overseas_regulations_video_completion_creates_passed_result(client, app):
"""关键断言:自定义编码的出国规章培训完整观看视频后无需题库作答,也必须落库为一次完成。"""
with app.app_context():
user = _create_user(username="overseas_video_completion")
agent = _create_training_agent(name="overseas_video_agent")
db.session.add(TrainingConfig(
training_type="overseas_policy_v2",
name="出国规章培训",
version="v1",
status="published",
))
db.session.commit()
response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={
"agent_id": agent.id,
"type": "overseas_policy_v2",
"stage": "result",
"score": 100,
"passed": True,
"attempt_count": 0,
"answer_details": [],
})
assert response.status_code == 200
body = response.get_json()
assert body["training_type"] == "overseas_policy_v2"
assert body["stage"] == "result"
assert body["passed"] is True
assert body["status"] == "passed"
assert isinstance(body["completion_time"], str) and body["completion_time"]
def test_safety_training_progress_round_trip(client, app):
"""安全培训应持久化培训版本、考试模式、三级状态和级别进度。"""
with app.app_context():
@@ -583,11 +615,34 @@ def test_training_admin_list_stats_and_export_share_one_fact_source(client, app)
workbook = load_workbook(BytesIO(export_res.data))
sheet = workbook.active
rows = list(sheet.iter_rows(values_only=True))
assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态")
assert rows[0] == ("入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态")
assert len(rows) == 3
assert rows[1][2] == "生产一部"
assert rows[2][2] == "生产一部"
assert {rows[1][7], rows[2][7]} == {"passed", "failed"}
assert rows[1][3] == "生产一部"
assert rows[2][3] == "生产一部"
assert {rows[1][8], rows[2][8]} == {"已通过", "未通过"}
def test_lean_dashboard_export_uses_page_time_and_status_labels(monkeypatch):
"""精益看板 Excel 必须复用页面的分钟级时间格式与中文状态文案。"""
monkeypatch.setattr(
lean_training_service,
"list_dashboard",
lambda task_id: {
"task": {"week_index": 2, "week_key": "2026-09-14", "due_at": "2026-09-20T23:59:59"},
"completed": [{"employee_id": "EMP-001", "name": "张三", "department": "生产部", "videos": [{"name": "精益视频", "watched_at": "2026-09-15T08:30:45"}], "status": "completed", "summary_text": "已完成学习", "completed_at": "2026-09-15T09:00:12"}],
"incomplete": [{"employee_id": "EMP-002", "name": "李四", "department": "品质部", "videos": [], "status": "overdue", "summary_text": None, "completed_at": None}],
"periods": [],
},
)
file_data, _ = lean_training_service.export_dashboard_excel(1)
rows = list(load_workbook(BytesIO(file_data)).active.iter_rows(values_only=True))
assert rows[1][2] == "2026-09-20 23:59"
assert rows[1][7] == "2026-09-15 08:30"
assert rows[1][8] == "已完成"
assert rows[1][10] == "2026-09-15 09:00"
assert rows[2][8] == "已延期"
def test_training_preview_proxy_reads_kb_storage_without_http_callback(monkeypatch, tmp_path, app):
@@ -105,7 +105,7 @@
- **【立即新增任务补推】**(原"立即推送下一批"):按现有游标逻辑对**所选周**任务增推一批(数量 = 每周任务数量),无需等待每周一排程;可用于发布失败后的补发。若当前无待推视频则返回"全部视频已推送完毕"。发布/补推后按任务 ID 刷新所选周上下文(不跳回最新周)。
- **推送记录**:展示每轮推送的触发来源(发布推送/每周排程/手动推送)、批次数量、企微发送/失败统计与失败明细。
管理端接口:`POST /api/admin/lean-training/weekly-tasks`(创建/更新并发布所选周任务)、`GET /api/admin/lean-training/weekly-tasks/<id>`(按 ID 读取指定周任务)、`POST /api/admin/lean-training/weekly-tasks/<id>/push`(补推)、`GET /api/admin/lean-training/weekly-tasks/<id>/push-logs`、`POST /api/admin/lean-training/weekly-tasks/<id>/reminders`、`GET /api/admin/lean-training/dashboard`([backend/app/api/training.py](../../../backend/app/api/training.py))。
管理端接口:`POST /api/admin/lean-training/weekly-tasks`(创建/更新并发布所选周任务)、`GET /api/admin/lean-training/weekly-tasks/<id>`(按 ID 读取指定周任务)、`POST /api/admin/lean-training/weekly-tasks/<id>/push`(补推)、`GET /api/admin/lean-training/weekly-tasks/<id>/push-logs`、`POST /api/admin/lean-training/weekly-tasks/<id>/reminders`、`GET /api/admin/lean-training/dashboard`、`GET /api/admin/lean-training/dashboard/export?task_id=<id>`(导出当前期全部看板数据)([backend/app/api/training.py](../../../backend/app/api/training.py))。
---
+2 -2
View File
@@ -55,8 +55,8 @@
| 功能项 | 状态 | 说明 |
| -------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;管理端顶部提供【全部培训】/【精益管理】页签,统计卡片随页签按各自实际数据切换(全部培训=考试通过统计;精益管理=按看板三态计数的完成率统计);精益页签展示单表格明细(已完成+未完成合并为一张表,仅靠状态列区分已完成/已延期/进行中),并提供期次下拉可区分/切换第几期任务(期号按周次升序,最早为第 1 期),切换后重拉对应期看板与精益统计;状态列统一中文显示;权限支持角色默认值与前端用户配置共同控制 |
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区;“出国规章培训”每次进入均从视频开始,完整播放一次后记录为一次学习完成 |
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;【导出 Excel】复用当前关键字、培训类型、状态和部门筛选条件,导出全部匹配记录,字段与列表一致(入职日期、完成日期、培训类型、部门、姓名、工号、分数、考试次数、状态);管理端顶部提供【全部培训】/【精益管理】页签,统计卡片随页签按各自实际数据切换(全部培训=考试通过统计;精益管理=按看板三态计数的完成率统计);精益页签展示单表格明细(已完成+未完成合并为一张表,仅靠状态列区分已完成/已延期/进行中),并提供期次下拉可区分/切换第几期任务(期号按周次升序,最早为第 1 期),切换后重拉对应期看板与精益统计;状态列统一中文显示;权限支持角色默认值与前端用户配置共同控制 |
| Chat 附件发送前预览 | 已实现 | 附件列表显示在输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;支持右上角删除,上传中保护删除,发货通知保留解析重试与重复处理入口 |
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
@@ -311,6 +311,25 @@ export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTra
};
}
export async function exportLeanTrainingDashboard(taskId: number): Promise<void> {
const response = await fetch(`/api/admin/lean-training/dashboard/export?task_id=${taskId}`, {
method: 'GET',
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Export failed: HTTP ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `lean_training_dashboard_${new Date().toISOString().slice(0, 10)}.xlsx`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
@@ -500,6 +500,17 @@ const stopNonSafetyVideoTimer = () => {
workspace.stopMaterialTimer();
};
/**
* 处理普通培训主视频播放结束事件。
* AI 触发时机:学员完整播放当前主视频到结尾时调用;仅出国规章培训将视频播放结束作为一次学习完成,其他培训类型保持现有阶段推进入口。
*/
const handleNonSafetyVideoEnded = () => {
stopNonSafetyVideoTimer();
if (workspace.isOverseasRegulationsTraining) {
workspace.markVideoCompleted();
}
};
watch([() => workspace.learnerTab, nonSafetyVideoMaterials], () => {
if (!nonSafetyVideoMaterials.value.some((material) => material.id === activeNonSafetyVideoId.value)) {
activeNonSafetyVideoId.value = nonSafetyVideoMaterials.value[0]?.id ?? null;
@@ -589,8 +600,8 @@ const leanStatusMeta: Record<LeanTrainingTaskStatus, { badgeClass: string; label
/** 看板总结弹框上下文:员工姓名 + 完整总结文案;为 null 时弹框关闭。 */
const summaryModal = ref<{ name: string; text: string } | null>(null);
/** 总结列预览截断:最多显示 15 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
const truncateSummary = (text: string) => (text.length > 15 ? `${text.slice(0, 15)}…` : text);
/** 总结列预览截断:最多显示 4 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
const truncateSummary = (text: string) => (text.length > 4 ? `${text.slice(0, 4)}…` : text);
/** 打开总结详情弹框:仅当该行有总结文案时可点击(无总结的行显示 "--" 不可点)。 */
const openSummaryModal = (name: string, text: string) => {
@@ -992,7 +1003,7 @@ const currentSafetyStageText = computed(() => {
:src="activeNonSafetyVideo.resource?.fileUrl"
@play="startNonSafetyVideoTimer"
@pause="stopNonSafetyVideoTimer"
@ended="stopNonSafetyVideoTimer"
@ended="handleNonSafetyVideoEnded"
/>
</div>
<div v-else class="mt-3 rounded-2xl border border-dashed border-default bg-surface-soft px-4 py-10 text-center text-sm text-muted">
@@ -1831,6 +1842,10 @@ const currentSafetyStageText = computed(() => {
>
<option v-for="period in workspace.leanDashboard.periods" :key="period.id" :value="period.id">{{ $t('chat.training.lean.dashboard.periodLabel', { index: period.index }) }}({{ period.weekKey }})</option>
</select>
<button type="button" class="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-2.5 py-1.5 text-xs font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60" :disabled="workspace.leanExportLoading" @click="workspace.exportLeanDashboard">
<Download class="h-3.5 w-3.5" />
{{ workspace.leanExportLoading ? $t('chat.training.lean.dashboard.exporting') : $t('chat.training.lean.dashboard.export') }}
</button>
</div>
</div>
<div class="rounded-full bg-white px-3 py-1 text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.dueAt', { time: workspace.leanDashboard.task.dueAt.slice(0, 16).replace('T', ' ') }) }}</div>
@@ -1862,7 +1877,7 @@ const currentSafetyStageText = computed(() => {
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="`${video.name}-${video.watchedAt}`" class="whitespace-nowrap">{{ video.watchedAt ? video.watchedAt.slice(0, 16).replace('T', ' ') : '--' }}</div><span v-if="!row.videos.length">--</span></td>
<!-- 状态徽章三态:已完成(绿)/已延期(红)/进行中(蓝),文案统一中文(含其余三语言),禁止回显原始键。 -->
<td class="border-b border-default px-3 py-2.5"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold" :class="row.status === 'completed' ? 'bg-emerald-50 text-emerald-700' : row.status === 'overdue' ? 'bg-red-50 text-red-700' : 'bg-blue-50 text-blue-700'">{{ $t(`chat.training.lean.status.${row.status}`) }}</span></td>
<!-- [RULE] 总结列最多显示 15 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
<!-- [RULE] 总结列最多显示 4 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
常显虚线下划线提示可点击(用户复测反馈点击无效,实为部署版本差异,此处强化可点性视觉)。 -->
<td class="border-b border-default px-3 py-2.5 text-secondary">
<button v-if="row.summaryText" type="button" class="max-w-56 cursor-pointer text-left whitespace-pre-wrap break-words underline decoration-dotted decoration-secondary/60 underline-offset-2 transition hover:decoration-solid hover:text-primary" :title="$t('chat.training.lean.summaryModal.viewHint')" @click="openSummaryModal(row.name, row.summaryText)">{{ truncateSummary(row.summaryText) }}</button>
@@ -11,6 +11,7 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
exportLeanTrainingDashboard,
getMyTrainingConfig,
getMyTrainingProgress,
getMyTrainingTypes,
@@ -82,6 +83,11 @@ export interface UseTrainingWorkspaceOptions {
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION = 'v1.0';
const OVERSEAS_REGULATIONS_TRAINING_TYPES = new Set([
'overseas_regulations',
'overseas_regulations_training',
'overseas_training',
]);
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -125,6 +131,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
const leanDashboardTaskId = ref<number | null>(null);
const leanReminderLoading = ref<Record<number, boolean>>({});
const leanExportLoading = ref(false);
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
const leanSummaryByTask = ref<Record<number, string>>({});
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
@@ -136,6 +143,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
{ code: 'onboarding', name: t('chat.training.safety.tabs.onboarding') },
{ code: 'safety', name: t('chat.training.safety.tabs.safety') },
]);
const isOverseasRegulationsTraining = computed(() => (
OVERSEAS_REGULATIONS_TRAINING_TYPES.has(learnerTab.value)
|| trainingTypes.value.some((item) => item.code === learnerTab.value && item.name.includes('出国规章'))
));
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION);
const examMode = ref<TrainingExamMode>('unified');
const safetyStage = ref<SafetyStage>('company');
@@ -147,6 +158,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const stage = ref<TrainingStage>('video');
watch(isOverseasRegulationsTraining, (isOverseas) => {
if (isOverseas) {
stage.value = 'video';
}
});
const currentQuestionIndex = ref(0);
const score = ref(0);
const attemptCount = ref(0);
@@ -665,7 +681,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
safetyViewStage.value = record.safetyStage || 'company';
}
}
stage.value = record.stage;
stage.value = isOverseasRegulationsTraining.value ? 'video' : record.stage;
syncExamQuestionIndex(record.currentQuestionIndex);
score.value = Number(record.score || 0);
attemptCount.value = Number(record.attempts || 0);
@@ -706,7 +722,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
passed: isOverseasRegulationsTraining.value && stage.value === 'result' ? true : isPassed.value,
attemptCount: attemptCount.value,
answerDetails: answerRecords.value,
joinDate: currentJoinDate.value || formatDate(new Date()),
@@ -749,11 +765,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
isHydrated.value = true;
return;
}
const requestedTrainingType = learnerTab.value;
try {
const record = await getMyTrainingProgress(learnerTab.value);
const record = await getMyTrainingProgress(requestedTrainingType);
if (learnerTab.value !== requestedTrainingType) return;
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
if (learnerTab.value !== requestedTrainingType) return;
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
if (error instanceof BusinessError && error.status === 401) {
hasWarnedLoadFailure.value = false;
@@ -782,15 +801,21 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
trainingConfigLoading.value = false;
return;
}
const requestedTrainingType = learnerTab.value;
trainingConfigLoading.value = true;
try {
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
const config = await getMyTrainingConfig(requestedTrainingType);
if (learnerTab.value === requestedTrainingType) {
publishedConfig.value = config;
}
} catch (error) {
if (!(error instanceof BusinessError && error.status === 401)) {
if (learnerTab.value === requestedTrainingType && !(error instanceof BusinessError && error.status === 401)) {
publishedConfig.value = null;
}
} finally {
trainingConfigLoading.value = false;
if (learnerTab.value === requestedTrainingType) {
trainingConfigLoading.value = false;
}
}
};
@@ -841,6 +866,20 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
await loadLeanDashboard();
};
const exportLeanDashboard = async () => {
const taskId = leanDashboardTaskId.value ?? leanDashboard.value.task?.id;
if (!taskId || leanExportLoading.value) return;
leanExportLoading.value = true;
try {
await exportLeanTrainingDashboard(taskId);
msg.success(t('chat.training.lean.dashboard.exportSuccess'));
} catch {
msg.error(t('chat.training.lean.dashboard.exportFailed'));
} finally {
leanExportLoading.value = false;
}
};
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
const loadLeanTraining = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
@@ -966,11 +1005,25 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (!hasPublishedTrainingConfig.value) return;
if (!isOverseasRegulationsTraining.value && !videoUrl.value) return;
if (learnerTab.value === 'safety') {
checkAndAdvanceStage();
return;
}
if (isOverseasRegulationsTraining.value) {
stage.value = 'result';
score.value = 100;
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: 100,
correctCount: 0,
wrongCount: 0,
isPassed: true,
};
void persistProgress();
return;
}
stage.value = 'summary';
void persistProgress();
};
@@ -1252,6 +1305,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
void persistProgress();
} else {
if (isOverseasRegulationsTraining.value) return;
const activeStageMaterials = publishedTrainingMaterials.value;
if (!activeStageMaterials.length) return;
const allCompleted = activeStageMaterials.every(m => {
@@ -1357,6 +1411,8 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
leanStats,
leanRows,
leanDashboardTaskId,
leanExportLoading,
exportLeanDashboard,
selectLeanDashboardPeriod,
learnerChatPrompt,
newSessionReminderMessage,
@@ -1364,6 +1420,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
learnerAssistantMessage,
managementChatPrompt,
markVideoCompleted,
isOverseasRegulationsTraining,
startExam,
selectAnswer,
submitTextAnswer,
+5 -1
View File
@@ -1060,7 +1060,11 @@
"count": "{count} people",
"empty": "No personnel data",
"passRate": "Completion Rate",
"periodLabel": "Period {index}"
"periodLabel": "Session {index}",
"export": "Export Excel",
"exporting": "Exporting...",
"exportSuccess": "Excel exported successfully",
"exportFailed": "Excel export failed. Please try again later."
},
"columns": {
"employeeId": "Employee ID",
+5 -1
View File
@@ -1060,7 +1060,11 @@
"count": "{count} คน",
"empty": "ไม่มีข้อมูลบุคลากร",
"passRate": "อัตราความสำเร็จ",
"periodLabel": "รอบที่ {index}"
"periodLabel": "รอบที่ {index}",
"export": "ส่งออก Excel",
"exporting": "กำลังส่งออก...",
"exportSuccess": "ส่งออก Excel สำเร็จ",
"exportFailed": "ส่งออก Excel ไม่สำเร็จ โปรดลองอีกครั้งภายหลัง"
},
"columns": {
"employeeId": "รหัสพนักงาน",
+5 -1
View File
@@ -1094,7 +1094,11 @@
"count": "共 {count} 人",
"empty": "暂无人员数据",
"passRate": "完成率",
"periodLabel": "第 {index} 期"
"periodLabel": "第 {index} 期",
"export": "导出 Excel",
"exporting": "正在导出...",
"exportSuccess": "Excel 导出成功",
"exportFailed": "Excel 导出失败,请稍后重试"
},
"columns": {
"employeeId": "工号",
+5 -1
View File
@@ -1060,7 +1060,11 @@
"count": "共 {count} 人",
"empty": "暫無人員資料",
"passRate": "完成率",
"periodLabel": "第 {index} 期"
"periodLabel": "第 {index} 期",
"export": "匯出 Excel",
"exporting": "正在匯出...",
"exportSuccess": "Excel 匯出成功",
"exportFailed": "Excel 匯出失敗,請稍後再試"
},
"columns": {
"employeeId": "工號",