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

@@ -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)),
]
)