feat(training): 打通新人培训真实数据闭环
This commit is contained in:
1 parent
3f13bb5b46
commit
19f43e8018
13 files changed
+1144
-162
No files matched your search
@@ -25,6 +25,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
@@ -40,6 +41,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
@@ -50,3 +52,4 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
list_training_records,
|
||||
serialize_training_record,
|
||||
summarize_training_records,
|
||||
upsert_user_training_record,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""确保当前用户具备培训管理权限。"""
|
||||
user = _require_user()
|
||||
if user.role not in {"admin", "hr"}:
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
user = _require_user()
|
||||
payload = request.get_json() or {}
|
||||
record = upsert_user_training_record(user, payload)
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
_require_training_admin()
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
items = result.records[start:end]
|
||||
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"items": [serialize_training_record(item) for item in items],
|
||||
"total": result.total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"department_options": department_options,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||
def get_admin_training_stats():
|
||||
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||
def export_admin_training_records():
|
||||
"""导出培训记录为 Excel。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -23,6 +23,7 @@ from app.models.shipping import (
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
@@ -64,4 +65,5 @@ __all__ = [
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'AgentGuide',
|
||||
'TrainingRecord',
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/app/models/training.py
|
||||
|
||||
用途:定义新人入职培训记录模型,承载学员当前培训进度、成绩结算与 HR 统计来源。
|
||||
依赖:models.base.Base、SQLAlchemy 映射、users 主表外键。
|
||||
逻辑:每个用户维护一条当前培训记录;前端学习流与管理端统计都基于该表读写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class TrainingRecord(Base):
|
||||
"""新人入职培训当前记录。"""
|
||||
|
||||
__tablename__ = "training_records"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), unique=True, index=True, nullable=False)
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, index=True)
|
||||
name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
join_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True, index=True)
|
||||
stage: Mapped[str] = mapped_column(String(20), nullable=False, default="video", index=True)
|
||||
current_question_index: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
score: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
passed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
answer_details: Mapped[list[dict] | None] = mapped_column(JSON, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
completion_time: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
index=True,
|
||||
)
|
||||
|
||||
user = relationship("User", back_populates="training_record")
|
||||
@@ -78,6 +78,11 @@ class User(Base):
|
||||
|
||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
training_record: Mapped[Optional['TrainingRecord']] = relationship(
|
||||
'TrainingRecord',
|
||||
back_populates='user',
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""
|
||||
backend/app/services/training_service.py
|
||||
|
||||
用途:封装新人培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||||
依赖:app.models.TrainingRecord/User、app.extensions.db、openpyxl。
|
||||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录并提供 HR 侧聚合结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from openpyxl import Workbook
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import TrainingRecord, User
|
||||
|
||||
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
||||
|
||||
|
||||
def _parse_iso_date(value: Any) -> Optional[date]:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(text)
|
||||
except ValueError as exc:
|
||||
raise ValidationError("join_date must be YYYY-MM-DD", details={"field": "join_date"}) from exc
|
||||
|
||||
|
||||
def _normalize_answer_details(value: Any) -> list[dict]:
|
||||
if value in (None, ""):
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError("answer_details must be an array", details={"field": "answer_details"})
|
||||
normalized: list[dict] = []
|
||||
for index, item in enumerate(value):
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError(
|
||||
"answer_details item must be an object",
|
||||
details={"field": "answer_details", "index": index},
|
||||
)
|
||||
normalized.append(
|
||||
{
|
||||
"question_id": str(item.get("question_id") or item.get("questionId") or ""),
|
||||
"selected_option_id": str(item.get("selected_option_id") or item.get("selectedOptionId") or ""),
|
||||
"correct": bool(item.get("correct", False)),
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _derive_status(record: TrainingRecord) -> str:
|
||||
if bool(record.passed):
|
||||
return "passed"
|
||||
if record.stage == "result":
|
||||
return "failed"
|
||||
return "in_progress"
|
||||
|
||||
|
||||
def serialize_training_record(record: TrainingRecord) -> dict[str, Any]:
|
||||
"""将培训记录序列化为前端可直接消费的结构。"""
|
||||
return {
|
||||
"id": record.id,
|
||||
"user_id": record.user_id,
|
||||
"employee_id": record.employee_id,
|
||||
"name": record.name,
|
||||
"department": record.department,
|
||||
"join_date": record.join_date.isoformat() if record.join_date else None,
|
||||
"stage": record.stage,
|
||||
"current_question_index": int(record.current_question_index or 0),
|
||||
"score": int(record.score or 0),
|
||||
"passed": bool(record.passed),
|
||||
"attempt_count": int(record.attempt_count or 0),
|
||||
"answer_details": list(record.answer_details or []),
|
||||
"started_at": record.started_at.isoformat() if record.started_at else None,
|
||||
"completion_time": record.completion_time.isoformat() if record.completion_time else None,
|
||||
"created_at": record.created_at.isoformat() if record.created_at else None,
|
||||
"updated_at": record.updated_at.isoformat() if record.updated_at else None,
|
||||
"status": _derive_status(record),
|
||||
}
|
||||
|
||||
|
||||
def _apply_user_snapshot(record: TrainingRecord, user: User) -> None:
|
||||
record.employee_id = (user.employee_id or "").strip() or None
|
||||
record.name = (user.real_name or "").strip() or (user.username or "").strip() or None
|
||||
record.department = (user.department or "").strip() or None
|
||||
|
||||
|
||||
def get_user_training_record(user_id: int) -> Optional[TrainingRecord]:
|
||||
"""查询指定用户当前培训记录。"""
|
||||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id)
|
||||
return db.session.execute(stmt).scalar_one_or_none()
|
||||
|
||||
|
||||
def upsert_user_training_record(user: User, payload: dict[str, Any]) -> TrainingRecord:
|
||||
"""
|
||||
保存当前用户培训进度。
|
||||
|
||||
Args:
|
||||
user: 当前登录用户。
|
||||
payload: 前端上传的培训进度快照。
|
||||
Returns:
|
||||
已保存的 TrainingRecord。
|
||||
"""
|
||||
stage = str(payload.get("stage") or "video").strip() or "video"
|
||||
if stage not in TRAINING_STAGES:
|
||||
raise ValidationError("stage is invalid", details={"field": "stage", "allowed": sorted(TRAINING_STAGES)})
|
||||
|
||||
current_question_index = int(payload.get("current_question_index") or payload.get("currentQuestionIndex") or 0)
|
||||
score = int(payload.get("score") or 0)
|
||||
attempt_count = int(payload.get("attempt_count") or payload.get("attemptCount") or 0)
|
||||
if current_question_index < 0:
|
||||
raise ValidationError("current_question_index must be >= 0", details={"field": "current_question_index"})
|
||||
if score < 0:
|
||||
raise ValidationError("score must be >= 0", details={"field": "score"})
|
||||
if attempt_count < 0:
|
||||
raise ValidationError("attempt_count must be >= 0", details={"field": "attempt_count"})
|
||||
|
||||
answer_details = _normalize_answer_details(payload.get("answer_details") or payload.get("answerDetails"))
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= 90)
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
|
||||
record = get_user_training_record(user.id)
|
||||
if not record:
|
||||
record = TrainingRecord(
|
||||
user_id=user.id,
|
||||
join_date=join_date or date.today(),
|
||||
started_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(record)
|
||||
elif join_date:
|
||||
record.join_date = join_date
|
||||
|
||||
_apply_user_snapshot(record, user)
|
||||
record.stage = stage
|
||||
record.current_question_index = current_question_index
|
||||
record.score = score
|
||||
record.passed = passed
|
||||
record.attempt_count = attempt_count
|
||||
record.answer_details = answer_details
|
||||
|
||||
if stage == "result":
|
||||
record.completion_time = datetime.utcnow()
|
||||
if not record.started_at:
|
||||
record.started_at = datetime.utcnow()
|
||||
else:
|
||||
record.completion_time = None
|
||||
if stage in {"summary", "exam"} and not record.started_at:
|
||||
record.started_at = datetime.utcnow()
|
||||
|
||||
db.session.commit()
|
||||
return record
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainingListResult:
|
||||
records: list[TrainingRecord]
|
||||
total: int
|
||||
|
||||
|
||||
def list_training_records(*, keyword: str | None = None, department: str | None = None, status: str | None = None) -> TrainingListResult:
|
||||
"""按筛选条件列出培训记录。"""
|
||||
query = db.session.query(TrainingRecord).order_by(TrainingRecord.updated_at.desc(), TrainingRecord.id.desc())
|
||||
records = query.all()
|
||||
|
||||
keyword_text = str(keyword or "").strip().lower()
|
||||
department_text = str(department or "").strip()
|
||||
status_text = str(status or "").strip()
|
||||
|
||||
filtered: list[TrainingRecord] = []
|
||||
for record in records:
|
||||
record_status = _derive_status(record)
|
||||
if keyword_text:
|
||||
searchable = " ".join(
|
||||
[
|
||||
str(record.name or ""),
|
||||
str(record.employee_id or ""),
|
||||
]
|
||||
).lower()
|
||||
if keyword_text not in searchable:
|
||||
continue
|
||||
if department_text and department_text != "all" and (record.department or "") != department_text:
|
||||
continue
|
||||
if status_text and status_text != "all" and record_status != status_text:
|
||||
continue
|
||||
filtered.append(record)
|
||||
|
||||
return TrainingListResult(records=filtered, total=len(filtered))
|
||||
|
||||
|
||||
def summarize_training_records(records: Iterable[TrainingRecord]) -> dict[str, int]:
|
||||
"""统计培训记录聚合指标。"""
|
||||
data = list(records)
|
||||
total = len(data)
|
||||
passed = sum(1 for item in data if _derive_status(item) == "passed")
|
||||
failed = sum(1 for item in data if _derive_status(item) == "failed")
|
||||
in_progress = sum(1 for item in data if _derive_status(item) == "in_progress")
|
||||
scored_items = [int(item.score or 0) for item in data if item.score is not None]
|
||||
average_score = round(sum(scored_items) / len(scored_items)) if scored_items else 0
|
||||
return {
|
||||
"total": total,
|
||||
"passed": passed,
|
||||
"failed": failed,
|
||||
"in_progress": in_progress,
|
||||
"pass_rate": round((passed / total) * 100) if total else 0,
|
||||
"average_score": average_score,
|
||||
}
|
||||
|
||||
|
||||
def export_training_records_excel(records: Iterable[TrainingRecord]) -> tuple[bytes, str]:
|
||||
"""将培训记录导出为 Excel 文件。"""
|
||||
workbook = Workbook()
|
||||
worksheet = workbook.active
|
||||
worksheet.title = "training"
|
||||
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.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),
|
||||
]
|
||||
)
|
||||
|
||||
buffer = BytesIO()
|
||||
workbook.save(buffer)
|
||||
filename = f"training_records_{datetime.utcnow().date().isoformat()}.xlsx"
|
||||
return buffer.getvalue(), filename
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Add training records table.
|
||||
|
||||
Purpose:
|
||||
Persist onboarding training progress, final score and HR export source data.
|
||||
Dependencies:
|
||||
Alembic revision fb2c3d4e5f6a.
|
||||
Flow:
|
||||
Frontend learner flow updates one current record per user; admin endpoints
|
||||
read the same table for stats and Excel export.
|
||||
|
||||
Revision ID: fc3d4e5f6a7b
|
||||
Revises: fb2c3d4e5f6a
|
||||
Create Date: 2026-06-30 22:30:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "fc3d4e5f6a7b"
|
||||
down_revision = "fb2c3d4e5f6a"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Create training_records table."""
|
||||
op.create_table(
|
||||
"training_records",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("employee_id", sa.String(length=50), nullable=True),
|
||||
sa.Column("name", sa.String(length=100), nullable=True),
|
||||
sa.Column("department", sa.String(length=100), nullable=True),
|
||||
sa.Column("join_date", sa.Date(), nullable=True),
|
||||
sa.Column("stage", sa.String(length=20), nullable=False),
|
||||
sa.Column("current_question_index", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("score", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("passed", sa.Boolean(), nullable=False, server_default=sa.text("false")),
|
||||
sa.Column("attempt_count", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("answer_details", sa.JSON(), nullable=True),
|
||||
sa.Column("started_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("completion_time", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("user_id", name="uq_training_records_user_id"),
|
||||
)
|
||||
op.create_index("ix_training_records_user_id", "training_records", ["user_id"], unique=True)
|
||||
op.create_index("ix_training_records_employee_id", "training_records", ["employee_id"], unique=False)
|
||||
op.create_index("ix_training_records_name", "training_records", ["name"], unique=False)
|
||||
op.create_index("ix_training_records_department", "training_records", ["department"], unique=False)
|
||||
op.create_index("ix_training_records_join_date", "training_records", ["join_date"], unique=False)
|
||||
op.create_index("ix_training_records_stage", "training_records", ["stage"], unique=False)
|
||||
op.create_index("ix_training_records_passed", "training_records", ["passed"], unique=False)
|
||||
op.create_index("ix_training_records_completion_time", "training_records", ["completion_time"], unique=False)
|
||||
op.create_index("ix_training_records_created_at", "training_records", ["created_at"], unique=False)
|
||||
op.create_index("ix_training_records_updated_at", "training_records", ["updated_at"], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""Drop training_records table."""
|
||||
op.drop_index("ix_training_records_updated_at", table_name="training_records")
|
||||
op.drop_index("ix_training_records_created_at", table_name="training_records")
|
||||
op.drop_index("ix_training_records_completion_time", table_name="training_records")
|
||||
op.drop_index("ix_training_records_passed", table_name="training_records")
|
||||
op.drop_index("ix_training_records_stage", table_name="training_records")
|
||||
op.drop_index("ix_training_records_join_date", table_name="training_records")
|
||||
op.drop_index("ix_training_records_department", table_name="training_records")
|
||||
op.drop_index("ix_training_records_name", table_name="training_records")
|
||||
op.drop_index("ix_training_records_employee_id", table_name="training_records")
|
||||
op.drop_index("ix_training_records_user_id", table_name="training_records")
|
||||
op.drop_table("training_records")
|
||||
@@ -7,6 +7,18 @@
|
||||
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
||||
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
||||
|
||||
## 新人培训 Agent
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 管理角色可在同一聊天页查看真实培训统计、筛选记录并导出 Excel |
|
||||
| 培训题库前端内置 | 前端已实现 | 内置 20 道新人试卷题目,支持一题一答、即时反馈、未通过重考 |
|
||||
| 管理端培训模式配置 | 前端已实现 | Agent 管理表单支持显式开启培训工作区,并可一键套用培训默认配置 |
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
## 1. 功能总览
|
||||
|
||||
| 模块 | 功能项 | 状态 | 优先级 |
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
# 新人入职培训 Agent 闭环整改清单
|
||||
|
||||
## 1. 文档目的
|
||||
|
||||
本文档用于整理“新员工入职培训”Agent 当前实现状态、与产品方案之间的闭环差距,以及后续的整改任务拆分,供产品、前端、后端、联调和测试统一对齐。
|
||||
|
||||
权威方案来源见 [新人入职培训Agent_产品设计文档](新人入职培训Agent_产品设计文档.md)。
|
||||
|
||||
## 2. 当前状态总结
|
||||
|
||||
### 2.1 已完成的前端闭环
|
||||
|
||||
- 已支持培训 Agent 专属入口和聊天页识别。
|
||||
- 已支持 Chat 内的欢迎语、视频占位符、知识点复盘、逐题考试、结果结算和补考入口。
|
||||
- 已支持前端内置 20 题题库、一题一答、即时反馈和分数累计。
|
||||
- 已支持聊天流与工作区联动,用户可在 Chat 内完成主要培训交互。
|
||||
- 已支持管理端开启培训模式,并提供首页培训推荐入口。
|
||||
- 已支持 HR 管理面板的前端展示、筛选和导出入口。
|
||||
|
||||
### 2.2 本轮已完成的真实数据闭环
|
||||
|
||||
- 已新增培训记录模型 `TrainingRecord`,用于保存学员当前培训阶段、当前题号、分数、补考次数和答题明细。
|
||||
- 已新增 Alembic 迁移,培训记录表结构可随版本发布落地。
|
||||
- 已新增员工侧接口:
|
||||
- 获取我的培训进度
|
||||
- 保存我的培训进度
|
||||
- 已新增管理侧接口:
|
||||
- 培训记录列表
|
||||
- 培训统计
|
||||
- Excel 导出
|
||||
- 已将前端培训工作区切换为真实后端数据源,支持:
|
||||
- 视频完成后保存阶段
|
||||
- 开始考试后保存当前轮次
|
||||
- 答题过程中保存答题明细和当前题号
|
||||
- 结算后保存最终成绩
|
||||
- 刷新页面后恢复培训进度
|
||||
- HR 面板读取真实后端记录和统计
|
||||
- HR Excel 导出读取真实后端记录
|
||||
- 已支持从 Agent `extra_config.training_video_url` 读取培训视频地址,未配置时回退到默认演示视频。
|
||||
|
||||
### 2.3 当前仍属于演示态的部分
|
||||
|
||||
- 视频资源仍是演示占位或预留容器,未接入正式培训素材。
|
||||
- 题库、知识点、及格线等规则主要固化在前端资源中,未配置化。
|
||||
- HR 权限当前更接近前端展示开关,未形成完整后端权限隔离。
|
||||
|
||||
## 3. 对照产品方案的闭环差距
|
||||
|
||||
### 3.1 数据闭环差距
|
||||
|
||||
- 培训记录表、迁移、提交接口、统计接口和导出接口已落地。
|
||||
- 当前仍缺少“多次考试历史明细”与“题库版本快照”这类更细粒度审计数据。
|
||||
|
||||
### 3.2 权限闭环差距
|
||||
|
||||
- 产品方案要求 HR 可查全局培训数据,普通员工不可查。
|
||||
- 当前实现主要按前端角色显示 HR 面板,缺少后端强校验。
|
||||
- 缺少 `is_hr` 或同等级权限标识注入,Agent 与接口层没有统一权限判断依据。
|
||||
|
||||
### 3.3 流程闭环差距
|
||||
|
||||
- 当前已支持刷新页面后恢复培训进度,且结果页与 HR 管理视图可共享同一份后端记录。
|
||||
- 仍缺少“跨设备继续考试”“考试历史回放”“多次考试明细查询”等增强流程能力。
|
||||
|
||||
### 3.4 配置闭环差距
|
||||
|
||||
- 视频地址、题库、知识点、及格线、欢迎语仍主要依赖前端静态内容。
|
||||
- HR 无法通过后台配置灵活维护培训内容。
|
||||
- 培训规则变更需要改代码并重新发版。
|
||||
|
||||
### 3.5 质量闭环差距
|
||||
|
||||
- 缺少培训主流程自动化测试。
|
||||
- 缺少培训相关后端接口测试。
|
||||
- 缺少异常流测试,例如刷新恢复、补考、权限拒绝、防作弊等。
|
||||
|
||||
## 4. P0 / P1 / P2 整改清单
|
||||
|
||||
### 4.1 P0:必须优先完成
|
||||
|
||||
#### 数据闭环
|
||||
|
||||
- 新增培训结果数据模型,至少包含:
|
||||
- `user_id`
|
||||
- `employee_id`
|
||||
- `department`
|
||||
- `score`
|
||||
- `passed`
|
||||
- `attempt_count`
|
||||
- `start_time`
|
||||
- `completion_time`
|
||||
- `answer_details`
|
||||
- 补齐 Alembic 迁移脚本。
|
||||
- 新增成绩提交接口,考试结束后由前端或 Agent 调用提交。
|
||||
- 新增 HR 统计接口,支持总人数、通过率、未完成人数、平均分等聚合统计。
|
||||
- 新增 Excel 导出接口,字段需覆盖:
|
||||
- 入职日期
|
||||
- 完成日期
|
||||
- 部门
|
||||
- 姓名
|
||||
- 工号
|
||||
- 分数
|
||||
|
||||
#### 权限闭环
|
||||
|
||||
- 明确 HR 权限来源,不再只依赖前端 `admin` 视图判断。
|
||||
- 后端统一注入 `is_hr` 或培训数据查看权限字段。
|
||||
- 普通员工访问统计/导出时,后端直接拒绝并返回统一错误码。
|
||||
- 前端 HR 管理面板按真实权限显示。
|
||||
|
||||
#### 流程闭环
|
||||
|
||||
- 考试结束后真实落库,不再只保留前端本地记录。
|
||||
- 未通过时记录补考次数与最近一次成绩。
|
||||
- 通过后更新真实完成状态,供员工视图与 HR 视图共用。
|
||||
- 页面刷新、重新进入后可恢复培训进度和考试状态。
|
||||
|
||||
### 4.2 P1:建议在 P0 后尽快完成
|
||||
|
||||
#### 配置闭环
|
||||
|
||||
- 视频地址改为后台可配置。
|
||||
- 题库、知识点、及格线从前端资源迁移为后台配置或 Agent 配置。
|
||||
- 支持管理端维护培训内容,而不是每次改题都发版。
|
||||
- Agent 培训模式配置扩展为:
|
||||
- 视频链接
|
||||
- 题库版本
|
||||
- 通过线
|
||||
- 欢迎语模板
|
||||
|
||||
#### 质量闭环
|
||||
|
||||
- 补前端回归测试:
|
||||
- 进入培训
|
||||
- 看完视频
|
||||
- 开始考试
|
||||
- 连续答题
|
||||
- 结算
|
||||
- 补考
|
||||
- 补后端接口测试:
|
||||
- 提交成绩
|
||||
- 查询统计
|
||||
- 导出 Excel
|
||||
- 权限拦截
|
||||
- 补异常流测试:
|
||||
- 刷新页面恢复
|
||||
- 切换 Agent
|
||||
- 未答完退出后再次进入
|
||||
- 补防作弊测试:
|
||||
- 提前索要答案
|
||||
- 跳题
|
||||
- 请求完整题库
|
||||
|
||||
### 4.3 P2:体验和运营优化
|
||||
|
||||
- 通过后生成培训完成凭证或完成总结卡片。
|
||||
- 增加 HR 维度筛选,例如部门、时间范围、通过状态。
|
||||
- 增加考试历史记录与最近一次成绩查看。
|
||||
- 增加题库版本管理与培训记录审计。
|
||||
|
||||
## 5. 任务拆分建议
|
||||
|
||||
### 5.1 前端任务
|
||||
|
||||
- 对接真实提交接口,替换本地模拟落库。
|
||||
- 对接真实统计接口和导出接口,替换前端样例 HR 数据。
|
||||
- 增加培训进度恢复逻辑。
|
||||
- 增加权限分流,员工与 HR 看到不同数据能力。
|
||||
- 保持现有聊天卡片体验不变,逐步将数据源切换到后端。
|
||||
|
||||
### 5.2 后端任务
|
||||
|
||||
- 新增培训记录模型与迁移。
|
||||
- 新增培训服务与 API:
|
||||
- 提交成绩
|
||||
- 查询统计
|
||||
- 导出 Excel
|
||||
- 获取个人培训进度
|
||||
- 增加培训权限校验。
|
||||
- 增加培训配置读取能力,支持视频、题库、通过线动态化。
|
||||
- 为培训 API 接入统一错误处理契约。
|
||||
|
||||
### 5.3 联调任务
|
||||
|
||||
- 明确前后端字段契约:
|
||||
- 当前题号
|
||||
- 总题数
|
||||
- 分数
|
||||
- 是否通过
|
||||
- 补考次数
|
||||
- 完成时间
|
||||
- 明确提交时机:
|
||||
- 每题即时提交
|
||||
- 或考试结束统一提交
|
||||
- 明确页面刷新后的恢复策略。
|
||||
- 明确 HR 权限字段和上下文注入方式。
|
||||
|
||||
### 5.4 测试任务
|
||||
|
||||
- 员工正常流:欢迎语 -> 视频 -> 复盘 -> 考试 -> 通过。
|
||||
- 员工失败流:未通过 -> 重考 -> 通过。
|
||||
- 恢复流:中途退出后再次进入恢复进度。
|
||||
- 权限流:普通员工禁止查看全局统计和导出。
|
||||
- HR 流:统计查询正确、Excel 字段正确。
|
||||
- 防作弊流:不能提前拿到未答题目的正确答案。
|
||||
|
||||
## 6. 建议实施顺序
|
||||
|
||||
### 第一阶段
|
||||
|
||||
- 培训记录模型
|
||||
- 数据迁移
|
||||
- 提交接口
|
||||
- 统计接口
|
||||
- 导出接口
|
||||
- HR 权限打通
|
||||
|
||||
### 第二阶段
|
||||
|
||||
- 前端对接真实数据
|
||||
- 培训进度恢复
|
||||
- 补考历史与完成状态一致性
|
||||
- 视频和题库配置化
|
||||
|
||||
### 第三阶段
|
||||
|
||||
- 自动化测试
|
||||
- 防作弊加强
|
||||
- 审计与体验优化
|
||||
|
||||
## 7. 一句话结论
|
||||
|
||||
当前“新员工培训”已经完成前端交互闭环,但距离产品文档要求的真实业务闭环,仍需优先补齐以下四块:
|
||||
|
||||
- 后端落库
|
||||
- 真实统计导出
|
||||
- HR 权限隔离
|
||||
- 正式培训素材与配置化
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* features/chat/api/training.api.ts
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
|
||||
* 依赖:shared/api/client、auth headers、training.types。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
|
||||
|
||||
type TrainingRecordApi = {
|
||||
id: number;
|
||||
user_id?: number;
|
||||
employee_id?: string | null;
|
||||
name?: string | null;
|
||||
department?: string | null;
|
||||
join_date?: string | null;
|
||||
stage?: TrainingStage;
|
||||
current_question_index?: number;
|
||||
score?: number;
|
||||
passed?: boolean;
|
||||
attempt_count?: number;
|
||||
answer_details?: Array<{
|
||||
question_id?: string;
|
||||
selected_option_id?: string;
|
||||
correct?: boolean;
|
||||
}>;
|
||||
completion_time?: string | null;
|
||||
updated_at?: string | null;
|
||||
started_at?: string | null;
|
||||
status?: TrainingRecord['status'];
|
||||
};
|
||||
|
||||
type TrainingListApi = {
|
||||
items: TrainingRecordApi[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
pages: number;
|
||||
department_options: string[];
|
||||
};
|
||||
|
||||
type TrainingStatsApi = {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
in_progress: number;
|
||||
pass_rate: number;
|
||||
average_score: number;
|
||||
};
|
||||
|
||||
export interface TrainingRecordQuery {
|
||||
keyword?: string;
|
||||
department?: string;
|
||||
status?: 'all' | 'passed' | 'failed' | 'in_progress';
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface SaveTrainingProgressPayload {
|
||||
stage: TrainingStage;
|
||||
currentQuestionIndex: number;
|
||||
score: number;
|
||||
passed: boolean;
|
||||
attemptCount: number;
|
||||
answerDetails: TrainingAnswerRecord[];
|
||||
joinDate?: string | null;
|
||||
}
|
||||
|
||||
const authHeaders = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuthHeaders = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): TrainingAnswerRecord[] {
|
||||
return Array.isArray(items)
|
||||
? items.map((item) => ({
|
||||
questionId: String(item.question_id || ''),
|
||||
selectedOptionId: String(item.selected_option_id || ''),
|
||||
correct: Boolean(item.correct),
|
||||
}))
|
||||
: [];
|
||||
}
|
||||
|
||||
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
|
||||
return {
|
||||
id: data.id,
|
||||
name: String(data.name || ''),
|
||||
employeeId: String(data.employee_id || ''),
|
||||
department: String(data.department || ''),
|
||||
joinDate: String(data.join_date || ''),
|
||||
completionDate: data.completion_time ? String(data.completion_time).slice(0, 10) : null,
|
||||
score: typeof data.score === 'number' ? data.score : null,
|
||||
attempts: Number(data.attempt_count || 0),
|
||||
status: data.status || 'in_progress',
|
||||
stage: (data.stage || 'video') as TrainingStage,
|
||||
currentQuestionIndex: Number(data.current_question_index || 0),
|
||||
passed: Boolean(data.passed),
|
||||
answerDetails: mapAnswerDetails(data.answer_details),
|
||||
startedAt: data.started_at || null,
|
||||
completionTime: data.completion_time || null,
|
||||
updatedAt: data.updated_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
||||
const progress = mapTrainingProgressRecord(data);
|
||||
return {
|
||||
id: progress.id,
|
||||
name: progress.name,
|
||||
employeeId: progress.employeeId,
|
||||
department: progress.department,
|
||||
joinDate: progress.joinDate,
|
||||
completionDate: progress.completionDate,
|
||||
score: progress.score,
|
||||
attempts: progress.attempts,
|
||||
status: progress.status,
|
||||
};
|
||||
}
|
||||
|
||||
function buildQueryString(query: TrainingRecordQuery = {}) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.keyword) params.set('keyword', query.keyword);
|
||||
if (query.department) params.set('department', query.department);
|
||||
if (query.status) params.set('status', query.status);
|
||||
if (query.page) params.set('page', String(query.page));
|
||||
if (query.page_size) params.set('page_size', String(query.page_size));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
|
||||
return data ? mapTrainingProgressRecord(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
|
||||
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
|
||||
method: 'PUT',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
stage: payload.stage,
|
||||
current_question_index: payload.currentQuestionIndex,
|
||||
score: payload.score,
|
||||
passed: payload.passed,
|
||||
attempt_count: payload.attemptCount,
|
||||
answer_details: payload.answerDetails.map((item) => ({
|
||||
question_id: item.questionId,
|
||||
selected_option_id: item.selectedOptionId,
|
||||
correct: item.correct,
|
||||
})),
|
||||
join_date: payload.joinDate || undefined,
|
||||
}),
|
||||
});
|
||||
return mapTrainingProgressRecord(data);
|
||||
}
|
||||
|
||||
export async function listTrainingRecords(query: TrainingRecordQuery = {}) {
|
||||
const qs = buildQueryString(query);
|
||||
const data = await requestJson<TrainingListApi>(`/api/admin/training-records${qs ? `?${qs}` : ''}`, authHeaders());
|
||||
return {
|
||||
items: data.items.map(mapTrainingRecord),
|
||||
total: data.total,
|
||||
page: data.page,
|
||||
pageSize: data.page_size,
|
||||
pages: data.pages,
|
||||
departmentOptions: data.department_options || [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTrainingStats(query: TrainingRecordQuery = {}): Promise<TrainingStats> {
|
||||
const qs = buildQueryString(query);
|
||||
const data = await requestJson<TrainingStatsApi>(`/api/admin/training-records/stats${qs ? `?${qs}` : ''}`, authHeaders());
|
||||
return {
|
||||
total: Number(data.total || 0),
|
||||
passed: Number(data.passed || 0),
|
||||
failed: Number(data.failed || 0),
|
||||
inProgress: Number(data.in_progress || 0),
|
||||
passRate: Number(data.pass_rate || 0),
|
||||
averageScore: Number(data.average_score || 0),
|
||||
};
|
||||
}
|
||||
|
||||
export async function exportTrainingRecords(query: TrainingRecordQuery = {}): Promise<void> {
|
||||
const qs = buildQueryString(query);
|
||||
const response = await fetch(`/api/admin/training-records/export${qs ? `?${qs}` : ''}`, {
|
||||
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 = `training_records_${new Date().toISOString().slice(0, 10)}.xlsx`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -109,7 +109,7 @@ const currentAnswerLabel = computed(() => {
|
||||
const workspaceExpanded = ref(false);
|
||||
|
||||
const autoSyncInitialPrompt = () => {
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
|
||||
emit('push-local-assistant-message', workspace.learnerChatPrompt);
|
||||
}
|
||||
};
|
||||
@@ -121,16 +121,6 @@ watch(
|
||||
userExpandedOverride.value = false;
|
||||
workspaceExpanded.value = false;
|
||||
emit('update:expanded', false);
|
||||
|
||||
// 切换 Agent 后,如果是培训 Agent 且没有消息,立即触发引导
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
// 给予极短延迟确保其它状态同步完成
|
||||
setTimeout(() => {
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
autoSyncInitialPrompt();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
@@ -143,6 +133,15 @@ watch(() => props.hasMessages, () => {
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => workspace.isHydrated,
|
||||
(ready) => {
|
||||
if (ready && workspace.isTrainingAgent && !props.hasMessages) {
|
||||
autoSyncInitialPrompt();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const isCompactMode = computed(() => !workspaceExpanded.value);
|
||||
|
||||
const compactSummary = computed(() => {
|
||||
@@ -803,7 +802,6 @@ const compactSummary = computed(() => {
|
||||
</button>
|
||||
<div class="aspect-video bg-black">
|
||||
<video
|
||||
ref="videoPlayer"
|
||||
controls
|
||||
autoplay
|
||||
class="h-full w-full"
|
||||
@@ -811,7 +809,7 @@ const compactSummary = computed(() => {
|
||||
@seeking="handleVideoSeeking"
|
||||
@ended="handleVideoEnded"
|
||||
>
|
||||
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
|
||||
<source :src="workspace.videoUrl" type="video/mp4">
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
</div>
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 Agent 的前端工作区状态,包括学员考试流、HR 统计筛选与 Excel 导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、xlsx,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,HR 端复用同页查看统计与导出。
|
||||
* 用途:封装新人培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingProgress,
|
||||
getTrainingStats,
|
||||
listTrainingRecords,
|
||||
saveMyTrainingProgress,
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
TrainingAnswerRecord,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingProgressRecord,
|
||||
TrainingRecord,
|
||||
TrainingRecordStatus,
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
|
||||
@@ -38,6 +46,7 @@ export interface UseTrainingWorkspaceOptions {
|
||||
}
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||||
@@ -59,81 +68,12 @@ export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
|
||||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
const buildInitialRecords = (): TrainingRecord[] => [
|
||||
{
|
||||
id: 'r-001',
|
||||
name: '蔡晓晴',
|
||||
employeeId: 'HX10031',
|
||||
department: '人事部',
|
||||
joinDate: '2026-06-03',
|
||||
completionDate: '2026-06-05',
|
||||
score: 95,
|
||||
attempts: 1,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-002',
|
||||
name: '刘成',
|
||||
employeeId: 'HX10052',
|
||||
department: '制造部',
|
||||
joinDate: '2026-06-08',
|
||||
completionDate: '2026-06-10',
|
||||
score: 90,
|
||||
attempts: 2,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-003',
|
||||
name: '张艳',
|
||||
employeeId: 'HX10061',
|
||||
department: '品质部',
|
||||
joinDate: '2026-06-09',
|
||||
completionDate: null,
|
||||
score: 80,
|
||||
attempts: 1,
|
||||
status: 'failed',
|
||||
},
|
||||
{
|
||||
id: 'r-004',
|
||||
name: '陈立',
|
||||
employeeId: 'HX10077',
|
||||
department: '仓储部',
|
||||
joinDate: '2026-06-12',
|
||||
completionDate: '2026-06-14',
|
||||
score: 100,
|
||||
attempts: 1,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-005',
|
||||
name: '吴佳',
|
||||
employeeId: 'HX10082',
|
||||
department: '业务部',
|
||||
joinDate: '2026-06-13',
|
||||
completionDate: null,
|
||||
score: null,
|
||||
attempts: 0,
|
||||
status: 'in_progress',
|
||||
},
|
||||
{
|
||||
id: 'r-006',
|
||||
name: '王腾',
|
||||
employeeId: 'HX10088',
|
||||
department: '工程部',
|
||||
joinDate: '2026-06-15',
|
||||
completionDate: '2026-06-18',
|
||||
score: 95,
|
||||
attempts: 3,
|
||||
status: 'passed',
|
||||
},
|
||||
];
|
||||
|
||||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { t, tm } = useI18n();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const isAdminViewer = computed(() => currentUser.value?.role === 'admin');
|
||||
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
@@ -145,15 +85,28 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const currentFeedbackCorrect = ref(false);
|
||||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||||
const completionDate = ref<string | null>(null);
|
||||
const currentJoinDate = ref<string | null>(null);
|
||||
const isHydrated = ref(false);
|
||||
|
||||
const hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
const hrDepartmentFilter = ref('all');
|
||||
const records = ref<TrainingRecord[]>(buildInitialRecords());
|
||||
const records = ref<TrainingRecord[]>([]);
|
||||
const departmentOptions = ref<string[]>([]);
|
||||
const stats = ref<TrainingStats>({
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
});
|
||||
let persistQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
watch(isTrainingAgent, (enabled) => {
|
||||
if (!enabled) {
|
||||
activeView.value = 'learner';
|
||||
isHydrated.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -226,42 +179,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
));
|
||||
const currentUserEmployeeId = computed(() => String(currentUser.value?.employee_id || '').trim() || '--');
|
||||
const currentUserDepartment = computed(() => String(currentUser.value?.department || '').trim() || t('chat.training.unknownDepartment'));
|
||||
|
||||
const departmentOptions = computed(() => {
|
||||
const values = Array.from(new Set(records.value.map((item) => item.department))).sort((a, b) => a.localeCompare(b));
|
||||
return values;
|
||||
});
|
||||
|
||||
const filteredRecords = computed(() => {
|
||||
const keyword = hrKeyword.value.trim().toLowerCase();
|
||||
return records.value.filter((item) => {
|
||||
const matchesKeyword = !keyword
|
||||
|| item.name.toLowerCase().includes(keyword)
|
||||
|| item.employeeId.toLowerCase().includes(keyword);
|
||||
const matchesStatus = hrStatusFilter.value === 'all' || item.status === hrStatusFilter.value;
|
||||
const matchesDepartment = hrDepartmentFilter.value === 'all' || item.department === hrDepartmentFilter.value;
|
||||
return matchesKeyword && matchesStatus && matchesDepartment;
|
||||
});
|
||||
});
|
||||
|
||||
const stats = computed(() => {
|
||||
const total = records.value.length;
|
||||
const passed = records.value.filter((item) => item.status === 'passed').length;
|
||||
const failed = records.value.filter((item) => item.status === 'failed').length;
|
||||
const inProgress = records.value.filter((item) => item.status === 'in_progress').length;
|
||||
const averageScoreSource = records.value.filter((item) => typeof item.score === 'number');
|
||||
const averageScore = averageScoreSource.length > 0
|
||||
? Math.round(averageScoreSource.reduce((sum, item) => sum + Number(item.score || 0), 0) / averageScoreSource.length)
|
||||
: 0;
|
||||
return {
|
||||
total,
|
||||
passed,
|
||||
failed,
|
||||
inProgress,
|
||||
passRate: total > 0 ? Math.round((passed / total) * 100) : 0,
|
||||
averageScore,
|
||||
};
|
||||
});
|
||||
const filteredRecords = computed(() => records.value);
|
||||
|
||||
/**
|
||||
* 重置考试状态,为首次开考或再次补考共用。
|
||||
@@ -277,10 +195,133 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
completionDate.value = null;
|
||||
};
|
||||
|
||||
const syncAnswerStateForCurrentQuestion = () => {
|
||||
const questionId = currentQuestion.value?.id;
|
||||
const currentAnswer = questionId
|
||||
? answerRecords.value.find((item) => item.questionId === questionId)
|
||||
: null;
|
||||
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
|
||||
answerLocked.value = Boolean(currentAnswer);
|
||||
currentFeedbackCorrect.value = Boolean(currentAnswer?.correct);
|
||||
};
|
||||
|
||||
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
|
||||
if (!record) {
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
currentJoinDate.value = null;
|
||||
return;
|
||||
}
|
||||
stage.value = record.stage;
|
||||
currentQuestionIndex.value = record.currentQuestionIndex;
|
||||
score.value = Number(record.score || 0);
|
||||
attemptCount.value = Number(record.attempts || 0);
|
||||
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
|
||||
completionDate.value = record.completionDate;
|
||||
currentJoinDate.value = record.joinDate || null;
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
const buildProgressPayload = () => ({
|
||||
stage: stage.value,
|
||||
currentQuestionIndex: currentQuestionIndex.value,
|
||||
score: score.value,
|
||||
passed: isPassed.value,
|
||||
attemptCount: attemptCount.value,
|
||||
answerDetails: answerRecords.value,
|
||||
joinDate: currentJoinDate.value || formatDate(new Date()),
|
||||
});
|
||||
|
||||
const persistProgress = async () => {
|
||||
if (!isTrainingAgent.value) return;
|
||||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||||
try {
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||||
completionDate.value = saved.completionDate;
|
||||
if (isAdminViewer.value) {
|
||||
void loadAdminRecords();
|
||||
}
|
||||
} catch {
|
||||
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
|
||||
}
|
||||
});
|
||||
await persistQueue;
|
||||
};
|
||||
|
||||
const loadTrainingProgress = async () => {
|
||||
if (!isTrainingAgent.value) return;
|
||||
try {
|
||||
const record = await getMyTrainingProgress();
|
||||
applyProgressRecord(record);
|
||||
} catch {
|
||||
applyProgressRecord(null);
|
||||
} finally {
|
||||
isHydrated.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const loadAdminRecords = async () => {
|
||||
if (!isTrainingAgent.value || !isAdminViewer.value) return;
|
||||
try {
|
||||
const query = {
|
||||
keyword: hrKeyword.value || undefined,
|
||||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||||
status: hrStatusFilter.value,
|
||||
};
|
||||
const [recordData, statsData] = await Promise.all([
|
||||
listTrainingRecords(query),
|
||||
getTrainingStats(query),
|
||||
]);
|
||||
records.value = recordData.items;
|
||||
departmentOptions.value = recordData.departmentOptions;
|
||||
stats.value = statsData;
|
||||
} catch {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
watch(currentAgent, (agent) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
}, { immediate: true });
|
||||
|
||||
watch(
|
||||
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
|
||||
([enabled, canView]) => {
|
||||
if (!enabled || !canView) return;
|
||||
void loadAdminRecords();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const markVideoCompleted = () => {
|
||||
stage.value = 'summary';
|
||||
// 立即推入本地助手消息(复盘卡片)
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
@@ -289,6 +330,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
resetExamState();
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const selectAnswer = (optionId: string) => {
|
||||
@@ -309,6 +351,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
// 推入用户选择的答案到聊天流
|
||||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||||
void pushLocalUserMessage?.(label);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -320,9 +363,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
upsertCurrentUserRecord();
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
currentQuestionIndex.value += 1;
|
||||
@@ -331,6 +374,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentFeedbackCorrect.value = false;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
@@ -338,44 +382,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const upsertCurrentUserRecord = () => {
|
||||
const recordIndex = records.value.findIndex((item) => item.employeeId === currentUserEmployeeId.value);
|
||||
const existingRecord = recordIndex >= 0 ? records.value[recordIndex] : null;
|
||||
const nextRecord: TrainingRecord = {
|
||||
id: existingRecord?.id || `r-${Date.now()}`,
|
||||
name: currentUserName.value,
|
||||
employeeId: currentUserEmployeeId.value,
|
||||
department: currentUserDepartment.value,
|
||||
joinDate: existingRecord?.joinDate || formatDate(new Date()),
|
||||
completionDate: isPassed.value ? completionDate.value : null,
|
||||
score: score.value,
|
||||
attempts: attemptCount.value,
|
||||
status: isPassed.value ? 'passed' : 'failed',
|
||||
};
|
||||
if (recordIndex >= 0) {
|
||||
records.value.splice(recordIndex, 1, nextRecord);
|
||||
} else {
|
||||
records.value.unshift(nextRecord);
|
||||
}
|
||||
};
|
||||
|
||||
const exportRecords = () => {
|
||||
const rows = filteredRecords.value.map((item) => ({
|
||||
[t('chat.training.hr.columns.joinDate')]: item.joinDate,
|
||||
[t('chat.training.hr.columns.completionDate')]: item.completionDate || '--',
|
||||
[t('chat.training.hr.columns.department')]: item.department,
|
||||
[t('chat.training.hr.columns.name')]: item.name,
|
||||
[t('chat.training.hr.columns.employeeId')]: item.employeeId,
|
||||
[t('chat.training.hr.columns.score')]: item.score ?? '--',
|
||||
[t('chat.training.hr.columns.attempts')]: item.attempts,
|
||||
[t('chat.training.hr.columns.status')]: t(`chat.training.hr.status.${item.status}`),
|
||||
}));
|
||||
const worksheet = XLSX.utils.json_to_sheet(rows);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'training');
|
||||
XLSX.writeFile(workbook, `training_records_${new Date().toISOString().slice(0, 10)}.xlsx`);
|
||||
const exportRecords = async () => {
|
||||
await exportTrainingRecords({
|
||||
keyword: hrKeyword.value || undefined,
|
||||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||||
status: hrStatusFilter.value,
|
||||
});
|
||||
};
|
||||
|
||||
const managementChatPrompt = computed(() => {
|
||||
@@ -413,10 +428,16 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
const showVideoModal = ref(false);
|
||||
const videoUrl = computed(() => {
|
||||
const extraConfig = currentAgent.value?.extra_config || {};
|
||||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||||
return customUrl || DEFAULT_TRAINING_VIDEO_URL;
|
||||
});
|
||||
|
||||
return {
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
isHydrated,
|
||||
activeView,
|
||||
stage,
|
||||
currentQuestionIndex,
|
||||
@@ -454,5 +475,6 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
restartExam,
|
||||
exportRecords,
|
||||
showVideoModal,
|
||||
videoUrl,
|
||||
};
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export interface TrainingAnswerRecord {
|
||||
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
|
||||
|
||||
export interface TrainingRecord {
|
||||
id: string;
|
||||
id: string | number;
|
||||
name: string;
|
||||
employeeId: string;
|
||||
department: string;
|
||||
@@ -44,3 +44,22 @@ export interface TrainingRecord {
|
||||
attempts: number;
|
||||
status: TrainingRecordStatus;
|
||||
}
|
||||
|
||||
export interface TrainingProgressRecord extends TrainingRecord {
|
||||
stage: TrainingStage;
|
||||
currentQuestionIndex: number;
|
||||
passed: boolean;
|
||||
answerDetails: TrainingAnswerRecord[];
|
||||
startedAt: string | null;
|
||||
completionTime: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface TrainingStats {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
inProgress: number;
|
||||
passRate: number;
|
||||
averageScore: number;
|
||||
}
|
||||
Reference in new issue
Block a user