fix(培训): 完善培训相关细节!

This commit is contained in:
runny committed 2026-09-22 19:42:15 +08:00
1 parent 453d910364
commit ae882d5d04
8 files changed
+96 -16

No files matched your search

@@ -28,6 +28,7 @@ from app.services.lean_training_service import (
_already_pushed_resource_ids,
_config_video_resource_ids,
_current_week_bounds,
format_beijing_iso,
target_user_ids_for_task,
)
from app.services.schedule.timezone_util import utc_now_naive
@@ -132,7 +133,8 @@ def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
"status": log.status,
"error_message": log.error_message,
"created_by_id": log.created_by_id,
"created_at": log.created_at.isoformat() if log.created_at else None,
# 展示层转北京时间:管理端"推送记录"直接渲染该字段,UTC 直出会比实际早 8 小时
"created_at": format_beijing_iso(log.created_at),
}
+60 -7
View File
@@ -69,6 +69,55 @@ def _format_dashboard_datetime(value: str | None) -> str:
return text[:16].replace("T", " ") if text else ""
def format_beijing_iso(value: datetime | str | None) -> str | None:
"""
将存储的 UTC 时间转换为北京时间 ISO 字符串,供页面/Excel 展示。
用途:培训模块数据库统一存 UTC naive(观看/完成/截止时间),而业务要求所有对外展示为北京时间;
此前序列化直接输出 UTC 导致页面显示比实际早 8 小时(如 18:47 显示 10:47)。
Args:
value: UTC naive datetime 或 ISO 字符串;naive 按 UTC 处理,带时区则先归一到绝对时间;
字符串无法解析时原样返回,避免历史脏数据导致展示层报错。
Returns:
带 +08:00 偏移的 ISO 字符串(如 2026-09-22T18:47:00+08:00,前端 slice(0,16) 即得北京时间);入参为空返回 None。
业务约束:仅用于序列化输出层,禁止将转换结果写回数据库——存储与服务端比较(超期判定等)仍一律 UTC。
"""
if value is None or (isinstance(value, str) and not value.strip()):
return None
if isinstance(value, str):
try:
parsed = datetime.fromisoformat(value.strip())
except ValueError:
return value.strip()
else:
parsed = value
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(resolve_schedule_tzinfo("Asia/Shanghai")).isoformat()
def parse_client_iso_to_utc_text(text: str) -> str:
"""
将客户端回显的观看时间 ISO 字符串归一为 UTC naive ISO 文本,供存储。
用途:save_completion 会合并客户端提交的 watched_at 兜底值(服务端记录缺失时入库);
客户端时间格式随版本演进(UTC 带 Z / 北京时间带 +08:00),必须归一为 UTC,
否则 watched_at_json 混入非 UTC 值会破坏"存储一律 UTC"的约定,后续服务端比较将出错。
Args:
text: 客户端提交的 ISO 时间字符串。
Returns:
UTC naive ISO 文本;无法解析时原样返回(与历史行为一致,不因脏数据阻塞提交)。
"""
try:
parsed = datetime.fromisoformat(str(text))
except ValueError:
return str(text)
if parsed.tzinfo is None:
# naive 视为北京时间墙钟(新版客户端口径),入库前转 UTC
parsed = parsed.replace(tzinfo=resolve_schedule_tzinfo("Asia/Shanghai"))
return to_utc_naive(parsed).isoformat()
def _dashboard_status_label(status: str | None) -> str:
"""将看板状态转换为页面一致的中文文案。"""
return {
@@ -244,7 +293,8 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
"week_key": task.week_key,
"week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None,
"week_index": week_index_for_task(task),
"due_at": task.due_at.isoformat(),
# 展示层转北京时间:管理端编辑器/看板头与学员端均直接渲染该字段,UTC 直出会比实际早 8 小时
"due_at": format_beijing_iso(task.due_at),
"video_resource_ids": visible_ids,
"target_roles": list(task.target_roles or []),
"target_user_ids": list(task.target_user_ids or []),
@@ -414,8 +464,9 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
item["completion"] = {
"summary_text": completion.summary_text,
"watched_at": dict(completion.watched_at_json or {}),
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
# 展示层转北京时间:学员端"已观看"直接渲染该字典值,存储仍为 UTC
"watched_at": {key: format_beijing_iso(value) for key, value in (completion.watched_at_json or {}).items()},
"completed_at": format_beijing_iso(completion.completed_at),
} if completion else None
items.append(item)
return items
@@ -451,7 +502,8 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
# 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成
db.session.add(completion)
db.session.commit()
return {"watched_at": watched}
# 返回值供学员端即时回显"已观看时间",展示层转北京时间;数据库中保持 UTC
return {"watched_at": {key: format_beijing_iso(value) for key, value in watched.items()}}
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
@@ -465,7 +517,8 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()}
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
completion = db.session.execute(
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
@@ -501,7 +554,7 @@ def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompl
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
visible_ids = task.video_resource_ids[: task.pushed_video_count]
return [
{"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))}
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
for resource_id in visible_ids
]
@@ -522,7 +575,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
"videos": _task_video_rows(task, completion),
"summary_text": completion.summary_text,
"status": status,
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
"completed_at": format_beijing_iso(completion.completed_at),
}
@@ -431,7 +431,13 @@ const compactSummary = computed(() => {
total: workspace.totalQuestionCount,
});
}
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
// 通过标题按培训类型区分:出国规章培训为纯视频学习,通过文案不使用"新人培训考试"表述
if (workspace.isPassed) {
return workspace.isOverseasRegulationsTraining
? t('chat.training.result.overseasPassTitle')
: t('chat.training.result.passTitle');
}
return t('chat.training.result.failTitle');
});
const ruleItems = computed(() => ([
@@ -1189,14 +1195,15 @@ const currentSafetyStageText = computed(() => {
{{ 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') }}
{{ workspace.isPassed ? (workspace.isOverseasRegulationsTraining ? $t('chat.training.result.overseasPassTitle') : $t('chat.training.result.passTitle')) : $t('chat.training.result.failTitle') }}
</h3>
<p class="mt-2 text-sm leading-6 text-secondary">
<!-- [RULE] 出国规章培训为纯视频学习(无考试),描述文案与考试语义不匹配,仅其他培训类型展示 -->
<p v-if="!workspace.isOverseasRegulationsTraining" 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 v-if="!workspace.isOverseasRegulationsTraining" 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>
@@ -1208,12 +1215,13 @@ const currentSafetyStageText = computed(() => {
</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">
<!-- [RULE] 出国规章培训完成页仅保留与视频学习相关的完成日期,对错题数等考试统计一律隐藏 -->
<div class="mt-3 grid gap-2.5" :class="workspace.isOverseasRegulationsTraining ? '' : 'md:grid-cols-3'">
<div v-if="!workspace.isOverseasRegulationsTraining" 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 v-if="!workspace.isOverseasRegulationsTraining" 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>
@@ -91,6 +91,18 @@ const OVERSEAS_REGULATIONS_TRAINING_TYPES = new Set([
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
/**
* 将当前时刻格式化为北京时间(UTC+8)ISO 字符串,如 2026-09-22T18:47:33+08:00。
* 用途:精益培训"已观看"的本地即时回显必须与服务端展示口径(北京时间)一致;
* 此前用 toISOString()(UTC)回显,观看后立刻显示的时间比实际早 8 小时。
* 业务约束:带 +08:00 偏移,后端 save_completion 兜底入库前会归一为 UTC 存储。
*/
const formatBeijingIso = (value: Date) => {
const beijing = new Date(value.getTime() + (8 * 60 + value.getTimezoneOffset()) * 60000);
const pad = (num: number) => String(num).padStart(2, '0');
return `${beijing.getFullYear()}-${pad(beijing.getMonth() + 1)}-${pad(beijing.getDate())}T${pad(beijing.getHours())}:${pad(beijing.getMinutes())}:${pad(beijing.getSeconds())}+08:00`;
};
/**
* 按百分制计算当前答题得分。
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
@@ -908,7 +920,8 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const markLeanVideoWatched = (taskId: number, resourceId: number) => {
const taskWatched = leanWatchedByTask.value[taskId] || {};
if (taskWatched[String(resourceId)]) return;
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: new Date().toISOString() } };
// 本地即时回显用北京时间,与服务端序列化口径一致;持久化失败时该值会经 save_completion 兜底入库(后端归一为 UTC)
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: formatBeijingIso(new Date()) } };
// 持久化失败不阻塞本地状态;下次刷新列表会以服务端记录为准,未持久化的视频需重新完整观看
void markMyLeanVideoWatched(taskId, resourceId).catch(() => {});
};
+1
View File
@@ -1140,6 +1140,7 @@
"passedTag": "Passed",
"failedTag": "Retake required",
"passTitle": "Congratulations, you passed the onboarding exam",
"overseasPassTitle": "Congratulations, you passed the overseas regulations training",
"failTitle": "This attempt did not meet the requirement",
"passDescription": "You passed this exam successfully. The score is automatically synced to the HR console and saved into the training record.",
"failDescription": "According to HR rules, any score below {passScore} requires a full retake until the learner passes.",
+1
View File
@@ -1140,6 +1140,7 @@
"passedTag": "ผ่านแล้ว",
"failedTag": "ต้องสอบใหม่",
"passTitle": "ยินดีด้วย คุณผ่านการสอบอบรมพนักงานใหม่แล้ว",
"overseasPassTitle": "ยินดีด้วย คุณผ่านการอบรมระเบียบการไปต่างประเทศแล้ว",
"failTitle": "การสอบครั้งนี้ยังไม่ผ่านเกณฑ์",
"passDescription": "คุณผ่านการสอบครั้งนี้แล้ว ระบบจะซิงก์คะแนนไปยังหน้าจอ HR และบันทึกลงประวัติการอบรมโดยอัตโนมัติ",
"failDescription": "ตามกฎของ HR หากได้ต่ำกว่า {passScore} คะแนน ต้องสอบใหม่จนกว่าจะผ่าน",
+1
View File
@@ -1174,6 +1174,7 @@
"passedTag": "已通过",
"failedTag": "需补考",
"passTitle": "恭喜,你已通过新人培训考试",
"overseasPassTitle": "恭喜,你已通过出国规章培训",
"failTitle": "本次考试未达标,需要重新考试",
"passDescription": "您已顺利通过本次考试,成绩会自动同步到 HR 管理端并计入培训记录。",
"failDescription": "按照 HR 规则,未达到 {passScore} 分必须重新考试,直到最终通过为止。",
+1
View File
@@ -1140,6 +1140,7 @@
"passedTag": "已通過",
"failedTag": "需補考",
"passTitle": "恭喜,你已通過新人培訓考試",
"overseasPassTitle": "恭喜,你已通過出國規章培訓",
"failTitle": "本次考試未達標,需要重新考試",
"passDescription": "你已順利通過本次考試,成績會自動同步到 HR 管理端並記入培訓紀錄。",
"failDescription": "依照 HR 規則,低於 {passScore} 分必須重新考試,直到最終通過。",