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):