feat(training): 完成员工培训闭环与管理配置
This commit is contained in:
1 parent
91758ef2b4
commit
95f3906779
37 files changed
+1766
-249
No files matched your search
@@ -87,6 +87,7 @@ def list_agent_guides(agent_id):
|
||||
'id': g.id,
|
||||
'file_name': g.file_name,
|
||||
'file_type': g.file_type,
|
||||
'guide_usage': g.guide_usage,
|
||||
'file_url': minio_service.get_public_url(g.file_path),
|
||||
'file_size': g.file_size,
|
||||
'remark': g.remark,
|
||||
|
||||
@@ -36,9 +36,14 @@ def _require_user():
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""确保当前用户具备培训管理权限。"""
|
||||
"""
|
||||
确保当前用户具备培训管理权限。
|
||||
|
||||
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||
"""
|
||||
user = _require_user()
|
||||
if user.role not in {"admin", "hr"}:
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
+14
-5
@@ -436,7 +436,16 @@ def _get_wecom_access_token():
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'}
|
||||
payload = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
return payload
|
||||
@@ -760,7 +769,7 @@ def casdoor_password_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -890,7 +899,7 @@ def casdoor_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
@@ -1352,7 +1361,7 @@ def home():
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -1436,7 +1445,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
|
||||
@@ -233,14 +233,26 @@ def _legacy_header_user() -> Optional[User]:
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _current_user_cache_key() -> tuple[str, str, str, str]:
|
||||
"""构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。"""
|
||||
return (
|
||||
str(request.headers.get('Authorization') or '').strip(),
|
||||
str(request.headers.get('X-User-Id') or '').strip(),
|
||||
str(request.headers.get('X-Username') or '').strip(),
|
||||
f'{request.method}:{request.path}',
|
||||
)
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
"""
|
||||
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||
Returns:
|
||||
User 实例;未认证时返回 None。
|
||||
"""
|
||||
cache_key = _current_user_cache_key()
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
cached_key = getattr(g, 'current_user_cache_key', None)
|
||||
if cached is not None and cached_key == cache_key:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
@@ -271,12 +283,14 @@ def get_current_user() -> Optional[User]:
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
@@ -61,6 +61,7 @@ class User(Base):
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||
@@ -84,6 +85,57 @@ class User(Base):
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
"""返回当前角色自带的功能权限默认值。"""
|
||||
return {
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
"""
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
|
||||
result: dict[str, bool] = {}
|
||||
for key, default_value in defaults.items():
|
||||
if key in raw:
|
||||
result[key] = bool(raw.get(key))
|
||||
else:
|
||||
result[key] = bool(default_value)
|
||||
return result
|
||||
|
||||
def set_feature_permissions(self, permissions: dict | None) -> None:
|
||||
"""
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = permissions if isinstance(permissions, dict) else {}
|
||||
overrides: dict[str, bool] = {}
|
||||
for key, default_value in defaults.items():
|
||||
if key not in raw:
|
||||
continue
|
||||
normalized = bool(raw.get(key))
|
||||
if normalized != bool(default_value):
|
||||
overrides[key] = normalized
|
||||
self.feature_permissions = overrides
|
||||
|
||||
def has_feature_permission(self, permission_key: str) -> bool:
|
||||
"""判断当前用户是否具备指定功能权限。"""
|
||||
return bool(self.get_feature_permissions().get(permission_key))
|
||||
|
||||
def can_manage_training(self) -> bool:
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -79,6 +79,7 @@ def serialize_admin_user(user: User) -> dict:
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'agent_ids': [agent.id for agent in user.agents],
|
||||
}
|
||||
|
||||
@@ -174,6 +175,7 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
@@ -224,6 +226,9 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""add agent guide usage
|
||||
|
||||
Revision ID: a1b2c3d4e610
|
||||
Revises: fe5f6a7b8c9d
|
||||
Create Date: 2026-07-05 23:40:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a1b2c3d4e610'
|
||||
down_revision = 'fe5f6a7b8c9d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
'agent_guides',
|
||||
sa.Column('guide_usage', sa.String(length=50), nullable=False, server_default='general'),
|
||||
)
|
||||
op.alter_column('agent_guides', 'guide_usage', server_default=None)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('agent_guides', 'guide_usage')
|
||||
@@ -0,0 +1,39 @@
|
||||
"""add user feature permissions
|
||||
|
||||
Revision ID: fe5f6a7b8c9d
|
||||
Revises: fd4e5f6a7b8c
|
||||
Create Date: 2026-07-05 23:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'fe5f6a7b8c9d'
|
||||
down_revision = 'fd4e5f6a7b8c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
'users',
|
||||
sa.Column(
|
||||
'feature_permissions',
|
||||
sa.JSON(),
|
||||
nullable=False,
|
||||
server_default=sa.text("'{}'::json"),
|
||||
),
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET feature_permissions = '{"training_hr_manage": true}'::json
|
||||
WHERE role = 'hr'
|
||||
"""
|
||||
)
|
||||
op.alter_column('users', 'feature_permissions', server_default=None)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('users', 'feature_permissions')
|
||||
@@ -0,0 +1,318 @@
|
||||
"""
|
||||
backend/tests/test_training_api.py
|
||||
|
||||
用途:覆盖新人培训主链的后端接口闭环,包括个人进度读写、管理端权限、统计筛选与导出。
|
||||
依赖:pytest、Flask test client、TrainingRecord/User 模型、openpyxl。
|
||||
逻辑:验证“员工个人培训记录”与“HR 管理统计导出”共用同一事实源,确保培训主链在后端可落库、可筛选、可导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import TrainingRecord, User
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = "user",
|
||||
department: str = "生产一部",
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
"""创建训练测试用户,供 legacy header 认证读取。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
real_name=f"{username}-实名",
|
||||
employee_id=f"{username.upper()}-EMP",
|
||||
department=department,
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password("password123")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""提取统一错误 envelope,便于断言错误码与详情。"""
|
||||
body = response.get_json()
|
||||
assert isinstance(body, dict)
|
||||
assert body.get("success") is False
|
||||
assert isinstance(body.get("error"), dict)
|
||||
return body["error"]
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成训练接口测试鉴权头,优先显式携带 user_id 以稳定命中 legacy 用户解析。"""
|
||||
return {
|
||||
"X-User-Id": str(user.id),
|
||||
"X-Username": user.username,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
"""员工侧培训进度应支持空记录读取、过程保存、结果结算与再次读取回显。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="trainee_roundtrip")
|
||||
|
||||
headers = _auth_headers(user)
|
||||
|
||||
empty_res = client.get("/api/user/training-record", headers=headers)
|
||||
assert empty_res.status_code == 200
|
||||
assert empty_res.get_json() is None
|
||||
|
||||
process_payload = {
|
||||
"stage": "exam",
|
||||
"current_question_index": 3,
|
||||
"score": 15,
|
||||
"passed": False,
|
||||
"attempt_count": 1,
|
||||
"join_date": "2026-07-04",
|
||||
"answer_details": [
|
||||
{"question_id": "q1", "selected_option_id": "A", "correct": True},
|
||||
{"question_id": "q2", "selected_option_id": "B", "correct": False},
|
||||
{"question_id": "q3", "selected_option_id": "C", "correct": True},
|
||||
],
|
||||
}
|
||||
save_process_res = client.put("/api/user/training-record/progress", headers=headers, json=process_payload)
|
||||
assert save_process_res.status_code == 200
|
||||
process_body = save_process_res.get_json()
|
||||
assert process_body["stage"] == "exam"
|
||||
assert process_body["current_question_index"] == 3
|
||||
assert process_body["score"] == 15
|
||||
assert process_body["passed"] is False
|
||||
assert process_body["status"] == "in_progress"
|
||||
assert process_body["employee_id"] == user.employee_id
|
||||
assert process_body["name"] == user.real_name
|
||||
assert len(process_body["answer_details"]) == 3
|
||||
|
||||
read_back_res = client.get("/api/user/training-record", headers=headers)
|
||||
assert read_back_res.status_code == 200
|
||||
assert read_back_res.get_json()["current_question_index"] == 3
|
||||
|
||||
result_payload = {
|
||||
"stage": "result",
|
||||
"current_question_index": 20,
|
||||
"score": 95,
|
||||
"passed": False,
|
||||
"attempt_count": 2,
|
||||
"join_date": "2026-07-04",
|
||||
"answer_details": process_payload["answer_details"],
|
||||
}
|
||||
save_result_res = client.put("/api/user/training-record/progress", headers=headers, json=result_payload)
|
||||
assert save_result_res.status_code == 200
|
||||
result_body = save_result_res.get_json()
|
||||
assert result_body["stage"] == "result"
|
||||
assert result_body["score"] == 95
|
||||
assert result_body["passed"] is True
|
||||
assert result_body["status"] == "passed"
|
||||
assert isinstance(result_body["completion_time"], str) and result_body["completion_time"]
|
||||
|
||||
with app.app_context():
|
||||
record = db.session.query(TrainingRecord).filter_by(user_id=user.id).one()
|
||||
assert record.stage == "result"
|
||||
assert record.score == 95
|
||||
assert record.passed is True
|
||||
assert record.attempt_count == 2
|
||||
assert record.join_date == date(2026, 7, 4)
|
||||
assert record.completion_time is not None
|
||||
|
||||
|
||||
def test_training_user_progress_requires_auth_and_valid_payload(client, app):
|
||||
"""培训个人接口必须拒绝未登录请求,并对非法参数返回统一校验错误。"""
|
||||
unauth_res = client.get("/api/user/training-record")
|
||||
assert unauth_res.status_code == 401
|
||||
assert _json_error(unauth_res)["code"] == "AUTH.UNAUTHORIZED"
|
||||
|
||||
with app.app_context():
|
||||
user = _create_user(username="trainee_validation")
|
||||
|
||||
headers = _auth_headers(user)
|
||||
invalid_stage_res = client.put(
|
||||
"/api/user/training-record/progress",
|
||||
headers=headers,
|
||||
json={
|
||||
"stage": "invalid-stage",
|
||||
"current_question_index": 0,
|
||||
"score": 0,
|
||||
"attempt_count": 0,
|
||||
"answer_details": [],
|
||||
},
|
||||
)
|
||||
assert invalid_stage_res.status_code == 400
|
||||
invalid_stage_error = _json_error(invalid_stage_res)
|
||||
assert invalid_stage_error["code"] == "VALIDATION.INVALID_PARAM"
|
||||
assert invalid_stage_error["details"]["field"] == "stage"
|
||||
|
||||
invalid_answer_res = client.put(
|
||||
"/api/user/training-record/progress",
|
||||
headers=headers,
|
||||
json={
|
||||
"stage": "exam",
|
||||
"current_question_index": 1,
|
||||
"score": 5,
|
||||
"attempt_count": 1,
|
||||
"answer_details": ["not-object"],
|
||||
},
|
||||
)
|
||||
assert invalid_answer_res.status_code == 400
|
||||
invalid_answer_error = _json_error(invalid_answer_res)
|
||||
assert invalid_answer_error["code"] == "VALIDATION.INVALID_PARAM"
|
||||
assert invalid_answer_error["details"]["field"] == "answer_details"
|
||||
assert invalid_answer_error["details"]["index"] == 0
|
||||
|
||||
|
||||
def test_training_admin_list_stats_and_export_share_one_fact_source(client, app):
|
||||
"""HR 管理列表、统计与导出应共用同一批 TrainingRecord,并支持部门/状态筛选。"""
|
||||
with app.app_context():
|
||||
hr_user = _create_user(username="training_hr", role="hr", department="人事部")
|
||||
ordinary_user = _create_user(username="training_user_denied", role="user", department="生产一部")
|
||||
passed_user = _create_user(username="passed_learner", department="生产一部")
|
||||
failed_user = _create_user(username="failed_learner", department="生产一部")
|
||||
progress_user = _create_user(username="progress_learner", department="品质部")
|
||||
|
||||
db.session.add_all(
|
||||
[
|
||||
TrainingRecord(
|
||||
user_id=passed_user.id,
|
||||
employee_id=passed_user.employee_id,
|
||||
name=passed_user.real_name,
|
||||
department=passed_user.department,
|
||||
join_date=date(2026, 7, 1),
|
||||
stage="result",
|
||||
current_question_index=20,
|
||||
score=95,
|
||||
passed=True,
|
||||
attempt_count=1,
|
||||
answer_details=[],
|
||||
started_at=datetime(2026, 7, 1, 9, 0, 0),
|
||||
completion_time=datetime(2026, 7, 1, 10, 0, 0),
|
||||
),
|
||||
TrainingRecord(
|
||||
user_id=failed_user.id,
|
||||
employee_id=failed_user.employee_id,
|
||||
name=failed_user.real_name,
|
||||
department=failed_user.department,
|
||||
join_date=date(2026, 7, 2),
|
||||
stage="result",
|
||||
current_question_index=20,
|
||||
score=60,
|
||||
passed=False,
|
||||
attempt_count=2,
|
||||
answer_details=[],
|
||||
started_at=datetime(2026, 7, 2, 9, 0, 0),
|
||||
completion_time=datetime(2026, 7, 2, 10, 0, 0),
|
||||
),
|
||||
TrainingRecord(
|
||||
user_id=progress_user.id,
|
||||
employee_id=progress_user.employee_id,
|
||||
name=progress_user.real_name,
|
||||
department=progress_user.department,
|
||||
join_date=date(2026, 7, 3),
|
||||
stage="exam",
|
||||
current_question_index=6,
|
||||
score=25,
|
||||
passed=False,
|
||||
attempt_count=1,
|
||||
answer_details=[],
|
||||
started_at=datetime(2026, 7, 3, 9, 0, 0),
|
||||
completion_time=None,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
denied_headers = _auth_headers(ordinary_user)
|
||||
denied_res = client.get("/api/admin/training-records", headers=denied_headers)
|
||||
assert denied_res.status_code == 403
|
||||
assert _json_error(denied_res)["code"] == "AUTH.FORBIDDEN"
|
||||
|
||||
hr_headers = _auth_headers(hr_user)
|
||||
list_res = client.get(
|
||||
"/api/admin/training-records?department=生产一部&status=passed&page=1&page_size=10",
|
||||
headers=hr_headers,
|
||||
)
|
||||
assert list_res.status_code == 200
|
||||
list_body = list_res.get_json()
|
||||
assert list_body["total"] == 1
|
||||
assert list_body["page"] == 1
|
||||
assert list_body["page_size"] == 10
|
||||
assert list_body["pages"] == 1
|
||||
assert set(list_body["department_options"]) == {"生产一部", "品质部"}
|
||||
assert len(list_body["items"]) == 1
|
||||
assert list_body["items"][0]["employee_id"] == passed_user.employee_id
|
||||
assert list_body["items"][0]["status"] == "passed"
|
||||
|
||||
stats_res = client.get("/api/admin/training-records/stats", headers=hr_headers)
|
||||
assert stats_res.status_code == 200
|
||||
stats_body = stats_res.get_json()
|
||||
assert stats_body == {
|
||||
"total": 3,
|
||||
"passed": 1,
|
||||
"failed": 1,
|
||||
"in_progress": 1,
|
||||
"pass_rate": 33,
|
||||
"average_score": 60,
|
||||
}
|
||||
|
||||
export_res = client.get("/api/admin/training-records/export?department=生产一部", headers=hr_headers)
|
||||
assert export_res.status_code == 200
|
||||
assert export_res.headers["Content-Type"].startswith(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
)
|
||||
assert "training_records_" in export_res.headers["Content-Disposition"]
|
||||
|
||||
workbook = load_workbook(BytesIO(export_res.data))
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态")
|
||||
assert len(rows) == 3
|
||||
assert rows[1][2] == "生产一部"
|
||||
assert rows[2][2] == "生产一部"
|
||||
assert {rows[1][7], rows[2][7]} == {"passed", "failed"}
|
||||
|
||||
|
||||
def test_training_admin_permission_can_be_granted_by_feature_permission(client, app):
|
||||
"""培训 HR 管理能力应支持通过功能权限显式授予普通用户。"""
|
||||
with app.app_context():
|
||||
granted_user = _create_user(
|
||||
username="training_perm_user",
|
||||
role="user",
|
||||
department="生产一部",
|
||||
feature_permissions={"training_hr_manage": True},
|
||||
)
|
||||
db.session.add(
|
||||
TrainingRecord(
|
||||
user_id=granted_user.id,
|
||||
employee_id=granted_user.employee_id,
|
||||
name=granted_user.real_name,
|
||||
department=granted_user.department,
|
||||
join_date=date(2026, 7, 5),
|
||||
stage="result",
|
||||
current_question_index=20,
|
||||
score=90,
|
||||
passed=True,
|
||||
attempt_count=1,
|
||||
answer_details=[],
|
||||
started_at=datetime(2026, 7, 5, 9, 0, 0),
|
||||
completion_time=datetime(2026, 7, 5, 10, 0, 0),
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
res = client.get("/api/admin/training-records", headers=_auth_headers(granted_user))
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
assert body["total"] == 1
|
||||
assert body["items"][0]["employee_id"] == granted_user.employee_id
|
||||
@@ -0,0 +1,143 @@
|
||||
# 员工入职培训 Agent (对话式考核与管理) 产品设计与落地文档
|
||||
|
||||
## 一、 背景与业务目标
|
||||
|
||||
### 1.1 业务背景
|
||||
|
||||
人事部门(HR)提出新需求,需要对入职员工进行在线培训与考核。
|
||||
核心诉求包括:
|
||||
|
||||
1. **学习闭环**:要求员工先观看培训视频,然后总结知识点最后进行答题。
|
||||
2. **交互式测试**:通过逐题一问一答的方式进行测试(共20题,每题5分,满分100分)。
|
||||
3. **即时反馈机制**:答对继续;答错必须即时显示正确答案及解析,以强化记忆。
|
||||
4. **通过标准**:90分及格,未通过者必须重新考试直至通过。
|
||||
5. **数据统计与导出**:HR 需要统计考试结果,并能够导出包含“入职日期、完成日期、部门、姓名、工号、分数”的表格。
|
||||
|
||||
<br />
|
||||
|
||||
效益整理
|
||||
|
||||
### 1.2 产品定位
|
||||
|
||||
基于 HXOPS 平台(Enterprise AI Gateway)的 Agentic 理念,我们将该需求设计为 **“对话式交互 (Chat UI) + Dify Agent + HXOPS 后端 Tool API”** 的整体解决方案。
|
||||
该方案摒弃了传统的“前端答题表单 + 后台管理看板”模式,将员工的“在线培训考核”与 HR 的“数据查询及导出”功能,全部融合在自然语言对话页面(Chat)中,实现极简的用户体验。
|
||||
|
||||
***
|
||||
|
||||
## 二、 对话交互流程设计 (User Journey)
|
||||
|
||||
### 2.1 员工端:沉浸式导学与考核
|
||||
|
||||
整个流程在 HXOPS 的 Chat 界面中闭环,分为四个状态阶段:
|
||||
|
||||
#### 阶段 1:破冰与视频导学 (Onboarding)
|
||||
|
||||
- **Agent**: "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。"
|
||||
- **Agent**: "▶️ 请先点击观看 \[入职培训视频链接]。观看完毕后,请回复【已看完】。"
|
||||
- **User**: "已看完"
|
||||
|
||||
#### 阶段 2:知识点串讲 (Knowledge Summary)
|
||||
|
||||
- **Agent**: "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦):
|
||||
> 1. **薪酬考勤**:每月15号发工资;打卡、请假必须走 OA 系统。
|
||||
> 2. **日常行政**:中米新订餐系统订餐;灭火器需站在上风口。
|
||||
> 3. **体系与安全**:QC080000 是有害物质管理标准;5S 是整理、整顿、清扫、清洁、素养。
|
||||
> 准备好接受挑战了吗?请回复【开始考试】。"
|
||||
|
||||
#### 阶段 3:互动测试 (Interactive QA) - 循环20次
|
||||
|
||||
- **User**: "开始考试"
|
||||
- **Agent**: "📝 **第 1 题 / 共 20 题(单选题)**:工资每月几号发放?
|
||||
A. 8号 B. 9号 C. 15号 D. 27号
|
||||
请直接回复选项或内容。"
|
||||
- **User**: "C"
|
||||
- **Agent**: "✅ **回答正确!** 当前得分:5分。
|
||||
📝 **第 2 题 / 共 20 题(判断题)**:发生火灾、爆炸事故时,应立即拨打“119”。(请回复对或错)"
|
||||
- **User**: "错"
|
||||
- **Agent**: "❌ **回答错误。** 正确答案是:【对】。
|
||||
*解析:生命安全第一,发生火灾必须立即拨打119。*
|
||||
当前得分:5分。
|
||||
📝 **第 3 题 / 共 20 题...**"
|
||||
|
||||
#### 阶段 4:结算与归档 (Settlement)
|
||||
|
||||
- *(如果 < 90 分)*
|
||||
**Agent**: "📊 **考试结束!** 您的最终得分是 **85 分**。及格线为 90 分。请回复【重新考试】再次挑战!"
|
||||
- *(如果 >= 90 分)*
|
||||
**Agent**: "🎉 **恭喜!** 您的最终得分是 **95 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。"
|
||||
|
||||
### 2.2 HR 管理端:对话式数据管家 (ChatBI)
|
||||
|
||||
无需额外开发后台管理页面,HR 直接通过自然语言与 Agent 对话,完成数据统计与报表导出。
|
||||
|
||||
#### 场景 1:日常数据速查 (ChatBI)
|
||||
|
||||
- **HR**: "帮我查一下这个月有多少人完成了新人培训?通过率怎么样?"
|
||||
- **Agent (思考中...)**: *(调用工具* *`query_training_stats`)*
|
||||
- **Agent**: "📊 **本月新人培训速报**:参训 15 人,通过 12 人,未通过 3 人,整体通过率 80%。"
|
||||
|
||||
#### 场景 2:报表一键导出 (Chat 导出 Excel)
|
||||
|
||||
- **HR**: "把本月通过的员工名单导出成 Excel。"
|
||||
- **Agent (思考中...)**: *(调用工具* *`export_training_records`)*
|
||||
- **Agent**: "✅ 已为您生成本月的培训成绩报表,包含入职日期、部门、姓名、工号和最终分数。
|
||||
📁 **点击下载文件**:\[本月新人培训合格名单.xlsx]"
|
||||
|
||||
***
|
||||
|
||||
## 三、 系统架构与技术实现方案
|
||||
|
||||
架构核心:**将复杂的 UI 交互转化为 Dify Agent 的大模型逻辑与 HXOPS 的 OpenAPI 工具调用。** 前端几乎零开发,主要工作在 Dify 画布编排与后端数据层。
|
||||
|
||||
### 3.1 Dify Chatflow 编排设计 (大脑)
|
||||
|
||||
在 Dify 侧创建一个 Chatflow 应用,作为整个交互的中枢控制:
|
||||
|
||||
- **全局对话变量 (Variables)**:
|
||||
- `question_index` (Integer) 默认 0:记录当前题号。
|
||||
- `score` (Integer) 默认 0:记录当前总分。
|
||||
- `questions_json` (String):系统预置变量,存放试卷的标准化 JSON 数据。
|
||||
- **核心节点逻辑**:
|
||||
1. **意图识别与权限校验**:判断用户是员工在答题,还是 HR 在查数据(结合环境变量 `{{is_hr}}` 进行权限隔离)。
|
||||
2. **LLM 判卷节点**:提取 `questions_json[question_index]` 的标准答案,与用户的自然语言输入(如选 C、回复“对”等)交给 LLM 进行语义比对与判定。
|
||||
3. **条件分支流转**:控制计分逻辑,答错则附加输出正确答案与解析。
|
||||
4. **HTTP Tool 调用节点**:当满足条件(如答题结束且分数>=90,或 HR 要求导出报表)时,通过 API 触发 HXOPS 后端的业务逻辑。
|
||||
|
||||
### 3.2 HXOPS 后端改造设计 (Python/Flask)
|
||||
|
||||
后端仅作为数据落地和业务接口提供方,主要新增以下模块:
|
||||
|
||||
1. **数据库模型扩展 (`backend/app/models/user.py`** **或新建)**
|
||||
- 新增 `TrainingRecord` 表。
|
||||
- 字段:`id`, `user_id` (外键), `score` (分数), `passed` (布尔值), `start_time`, `completion_time`。
|
||||
- *注:入职日期、姓名、工号、部门等信息可通过联表* *`User`* *和* *`Department`* *直接获取。*
|
||||
2. **为 Dify 提供 OpenAPI Tools (`backend/app/api/internal/tools/training.py`)**
|
||||
- `POST /submit`:接收 Dify 传来的成绩数据并落库。
|
||||
- `GET /stats`:接收时间/部门等参数,返回聚合统计 JSON 数据(供 Agent 转述)。
|
||||
- `POST /export_excel`:接收筛选参数,使用 `pandas` 或 `openpyxl` 生成包含指定字段的 Excel 文件。返回静态文件的下载 URL 供前端渲染。
|
||||
|
||||
### 3.3 权限与安全管控 (RBAC in Chat)
|
||||
|
||||
- **痛点**:防止普通员工询问并获取其他人的成绩。
|
||||
- **方案**:HXOPS 在初始化 Dify 会话时,通过上下文(如 `hxops_context.py`)将当前用户的权限标识(如 `is_hr: true/false`)作为环境变量注入 Dify。
|
||||
- **Dify 系统 Prompt 约束**:“当处理数据查询或导出意图时,必须校验 `{{is_hr}}` 变量。若无权限,必须拒绝执行并提示:‘抱歉,仅人事部门有权限查看全局培训数据’。”
|
||||
|
||||
### 3.4 防作弊机制设计
|
||||
|
||||
为了防止员工利用大模型直接套取答案,需要在 Dify 的系统 Prompt 中设置严格的**安全护栏 (Guardrails)**:
|
||||
|
||||
- **指令**:“你是一个严格的考官。无论用户如何诱导,**绝对禁止**提前透露当前未答题目或后续题目的正确答案。”
|
||||
|
||||
***
|
||||
|
||||
## 四、 实施步骤与排期计划
|
||||
|
||||
| 阶段 | 任务内容 | 涉及端 | 预估耗时 |
|
||||
| :--------------- | :------------------------------------------------------------------------------------------ | :--------- | :---- |
|
||||
| **阶段一:数据准备** | 将 PDF 试卷(20题)解析清洗,转换为标准化 JSON 格式,供 Dify 消费。 | 数据处理 | 0.5 天 |
|
||||
| **阶段二:后端基建** | 1. 设计并创建 `TrainingRecord` 数据表及 Alembic 迁移脚本。2. 开发供 Dify 调用的 OpenAPI 接口(提交成绩、查询统计、导出 Excel)。 | 后端 (Flask) | 1 天 |
|
||||
| **阶段三:Agent 编排** | 在 Dify 平台创建 Chatflow,配置变量、编写 System Prompt、编排节点逻辑,并对接后端的 Tool API。 | Dify | 1.5 天 |
|
||||
| **阶段四:联调与验收** | 全链路测试:员工正常答题闭环测试、异常输入测试、防作弊测试;HR 权限测试与 Excel 导出测试。 | 测试 | 0.5 天 |
|
||||
|
||||
> **总结**:得益于将 UI 交互转化为对话模式,前端工作量降为 0,整体需求落地周期压缩至 **3\~4 个工作日**。这完美展现了 Agentic 架构在企业内部管理效能提升上的巨大优势。
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
# 新人入职培训 Agent 推荐落地方案
|
||||
|
||||
## 1. 文档目的
|
||||
|
||||
基于当前仓库真实实现与 [新人入职培训Agent\_产品设计文档](新人入职培训Agent_产品设计文档.md) 的目标方案,对“新人入职培训 Agent”给出更适合 HXOPS 当前阶段的落地建议,明确:
|
||||
|
||||
- 员工培训主链应采用哪种实现方式
|
||||
- Dify 在培训场景中的合理职责边界
|
||||
- 现有实现与目标方案的差异
|
||||
- 推荐的 P0 / P1 演进顺序
|
||||
|
||||
## 2. 结论
|
||||
|
||||
结论先行:
|
||||
|
||||
- **员工培训主流程**:推荐采用“Chat 页面内嵌受控工作区 + 后端真实记录”的方案作为主线。
|
||||
- **Dify**:推荐承担培训知识问答、知识点解释、HR 自然语言统计问答等辅助能力,不建议承担考试状态推进和最终判卷主逻辑。
|
||||
- **最终推荐架构**:采用“**受控考试主链 + Dify 辅助问答/ChatBI**”的混合方案,而不是纯前端工作区或纯 Dify 编排二选一。
|
||||
|
||||
## 3. 为什么不建议纯 Dify 驱动考试主链
|
||||
|
||||
产品设计文档中的理想形态是:
|
||||
|
||||
`Chat UI + Dify Agent + HXOPS 后端 Tool API`
|
||||
|
||||
该方案适合自然语言问答,但不适合承担“培训考试主链”的核心控制,主要原因如下:
|
||||
|
||||
### 3.1 流程刚性不足
|
||||
|
||||
培训考试的核心约束是:
|
||||
|
||||
- 必须先看视频,再看总结,再考试
|
||||
- 必须一题一答,不能跳题
|
||||
- 答错必须即时给出正确答案与解析
|
||||
- 未通过必须重考
|
||||
|
||||
这类规则更适合由前端状态机和后端记录共同保证,不适合交给 LLM 根据上下文和 Prompt 自由推进。
|
||||
|
||||
### 3.2 可测试性和可审计性不足
|
||||
|
||||
考试场景需要稳定复现:
|
||||
|
||||
- 第几题
|
||||
- 选了什么
|
||||
- 当前分数
|
||||
- 是否通过
|
||||
- 补考次数
|
||||
- 完成时间
|
||||
|
||||
如果主逻辑依赖 Dify 会话变量和模型语义判断,测试成本和审计成本都会显著提高。
|
||||
|
||||
### 3.3 防作弊成本高
|
||||
|
||||
纯 Dify 方案需要依赖 Prompt Guardrails 防止:
|
||||
|
||||
- 提前索要答案
|
||||
- 诱导泄露题库
|
||||
- 绕过考试步骤
|
||||
|
||||
Prompt 约束可以作为辅助,但不应作为培训考试的唯一硬约束。
|
||||
|
||||
## 4. 为什么当前“受控工作区 + 后端落库”更适合主流程
|
||||
|
||||
当前仓库已经具备一条可运行的受控培训主链:
|
||||
|
||||
- Chat 页面顶部挂载培训工作区
|
||||
- 学员端按 `video -> summary -> exam -> result` 推进
|
||||
- 题目一题一答并即时反馈
|
||||
- 培训进度、答题明细、分数、补考次数写入后端
|
||||
- HR 可读取真实记录、统计并导出 Excel
|
||||
|
||||
这套方案更适合培训主链,原因如下:
|
||||
|
||||
### 4.1 状态推进可控
|
||||
|
||||
前端工作区明确掌控阶段推进、选项点击、下一题、补考入口,行为确定性强,便于验收和回归。
|
||||
|
||||
### 4.2 数据真实落库
|
||||
|
||||
后端 `TrainingRecord` 可作为培训事实源,承担:
|
||||
|
||||
- 当前培训阶段
|
||||
- 当前题号
|
||||
- 分数
|
||||
- 是否通过
|
||||
- 补考次数
|
||||
- 答题明细
|
||||
- 开始时间 / 完成时间
|
||||
|
||||
### 4.3 HR 视角天然闭环
|
||||
|
||||
员工培训过程与 HR 统计、导出直接共用同一张事实表,避免“前端考试一套、HR 统计另一套”的双轨状态漂移。
|
||||
|
||||
## 5. 推荐目标架构
|
||||
|
||||
```text
|
||||
员工
|
||||
-> Chat 页
|
||||
-> 培训工作区(受控状态机)
|
||||
-> 视频学习
|
||||
-> 知识点复盘
|
||||
-> 一题一答
|
||||
-> 结果结算 / 补考
|
||||
-> 本地聊天消息区(展示视频卡片/总结卡片/题目卡片/结果卡片)
|
||||
|
||||
前端培训工作区
|
||||
-> 调用 HXOPS Training API
|
||||
-> 读取个人进度
|
||||
-> 保存阶段推进
|
||||
-> 保存答题明细
|
||||
-> 保存结算结果
|
||||
|
||||
后端 Training API / Service
|
||||
-> PostgreSQL TrainingRecord
|
||||
-> HR 列表 / 统计 / Excel 导出
|
||||
|
||||
Dify(辅助能力)
|
||||
-> 培训 FAQ / 知识点解释
|
||||
-> HR 自然语言查数(ChatBI)
|
||||
-> 培训流程说明 / 制度问答
|
||||
```
|
||||
|
||||
## 6. Dify 的推荐职责边界
|
||||
|
||||
### 6.1 建议由 Dify 承担
|
||||
|
||||
- 培训规则、制度、知识点的自然语言解释
|
||||
- 视频观看后的补充问答
|
||||
- 员工关于培训内容的 FAQ
|
||||
- HR 自然语言统计问答,例如:
|
||||
- “这个月多少人完成培训?”
|
||||
- “通过率是多少?”
|
||||
- “帮我导出生产部未通过名单”
|
||||
|
||||
### 6.2 不建议由 Dify 承担
|
||||
|
||||
- 当前题号推进
|
||||
- 当前总分计算
|
||||
- 最终是否通过的唯一判定
|
||||
- 答题记录的事实落库
|
||||
- 补考次数的唯一来源
|
||||
|
||||
这些能力应仍由 HXOPS 前后端控制,Dify 只读或只做辅助解释。
|
||||
|
||||
## 7. 对当前实现的判断
|
||||
|
||||
### 7.1 已经具备的能力
|
||||
|
||||
- 培训 Agent 的 Chat 入口识别
|
||||
- Chat 顶部培训工作区
|
||||
- 视频 -> 总结 -> 答题 -> 结果 的前端交互链
|
||||
- 后端培训记录落库
|
||||
- HR 列表 / 统计 / Excel 导出
|
||||
- 页面刷新后恢复培训进度
|
||||
|
||||
### 7.2 当前不足
|
||||
|
||||
- 题库、知识点、欢迎语、通过线仍主要固化在前端
|
||||
- 视频仍可配置但未形成正式素材管理闭环
|
||||
- Dify 尚未作为培训 FAQ / HR ChatBI 的正式辅助层接入
|
||||
- 自动化测试不足
|
||||
- 培训配置后台化不足
|
||||
|
||||
## 8. 推荐实施顺序
|
||||
|
||||
### P0:先把“受控考试主链”做扎实
|
||||
|
||||
1. 保留当前培训工作区主链,不回退为纯 Dify 考试流
|
||||
2. 完善后端培训记录接口测试
|
||||
3. 补齐前端回归测试:
|
||||
- 视频完成
|
||||
- 开始考试
|
||||
- 连续答题
|
||||
- 结算
|
||||
- 补考
|
||||
- 刷新恢复
|
||||
4. 补齐 HR 权限和导出验收
|
||||
|
||||
### P1:把培训内容改成可配置
|
||||
|
||||
1. 题库从前端资源迁到后端配置或 Agent 配置
|
||||
2. 知识点、欢迎语、通过线可配置
|
||||
3. 培训视频改成正式素材配置
|
||||
4. 增加题库版本号与配置快照
|
||||
|
||||
### P2:引入 Dify 做辅助能力
|
||||
|
||||
1. 培训 FAQ 与知识点解释走 Dify
|
||||
2. HR 自然语言统计与导出走 Dify + Tool API
|
||||
3. 对外形成“看起来像 Chat,底层仍受控”的最终体验
|
||||
|
||||
<br />
|
||||
|
||||
## 9、 对话交互流程设计 (User Journey)
|
||||
|
||||
### 2.1 员工端:沉浸式导学与考核
|
||||
|
||||
整个流程在 HXOPS 的 Chat 界面中闭环,分为四个状态阶段:
|
||||
|
||||
#### 阶段 1:破冰与视频导学 (Onboarding):(展示条件:考试未通过员工每次进入该agent页面都自动展示该阶段信息,考试通过后不再展示)
|
||||
|
||||
- **Agent**: "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。"
|
||||
- **Agent**: "▶️ 请先点击观看 \[入职培训视频链接]。观看完毕后,开始**知识点复盘**。"
|
||||
|
||||
#### 阶段 2:**知识点复盘** (Knowledge Summary)
|
||||
|
||||
- **Agent**: "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦):
|
||||
> 1. **薪酬考勤**:每月15号发工资;打卡、请假必须走 OA 系统。
|
||||
> 2. **日常行政**:中米新订餐系统订餐;灭火器需站在上风口。
|
||||
> 3. **体系与安全**:QC080000 是有害物质管理标准;5S 是整理、整顿、清扫、清洁、素养。
|
||||
> 准备好接受挑战了吗?直接点击**【开始考试】**或Chat中请回复**【开始考试】**。"
|
||||
|
||||
#### 阶段 3:互动测试 (Interactive QA) - 循环20次
|
||||
|
||||
- **User**: "开始考试"
|
||||
- **Agent**: "📝 **第 1 题 / 共 20 题(单选题)**:工资每月几号发放?
|
||||
A. 8号 B. 9号 C. 15号 D. 27号
|
||||
请直接回复选项或内容。"
|
||||
- **User**: "C"
|
||||
- **Agent**: "✅ **回答正确!** 当前得分:5分。
|
||||
📝 **第 2 题 / 共 20 题(判断题)**:发生火灾、爆炸事故时,应立即拨打“119”。(请回复对或错)"
|
||||
- **User**: "错"
|
||||
- **Agent**: "❌ **回答错误。** 正确答案是:【对】。
|
||||
*解析:生命安全第一,发生火灾必须立即拨打119。*
|
||||
当前得分:5分。
|
||||
📝 **第 3 题 / 共 20 题...**"
|
||||
|
||||
#### 阶段 4:结算与归档 (Settlement)
|
||||
|
||||
- *(如果 < 90 分)*
|
||||
**Agent**: "📊 **考试结束!** 您的最终得分是 **85 分**。及格线为 90 分。请回复【重新考试】再次挑战!"
|
||||
- *(如果 >= 90 分)*
|
||||
**Agent**: "🎉 **恭喜!** 您的最终得分是 **95 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。"
|
||||
|
||||
### 2.2 HR 管理端:对话式数据管家 (ChatBI)
|
||||
|
||||
无需额外开发后台管理页面,HR 直接通过自然语言与 Agent 对话,完成数据统计与报表导出。
|
||||
|
||||
#### 场景 1:日常数据速查 (ChatBI)
|
||||
|
||||
- **HR**: "帮我查一下这个月有多少人完成了新人培训?通过率怎么样?"
|
||||
- **Agent (思考中...)**: *(调用工具* *`query_training_stats`)*
|
||||
- **Agent**: "📊 **本月新人培训速报**:参训 15 人,通过 12 人,未通过 3 人,整体通过率 80%。"
|
||||
|
||||
#### 场景 2:报表一键导出 (Chat 导出 Excel)
|
||||
|
||||
- **HR**: "把本月通过的员工名单导出成 Excel。"
|
||||
- **Agent (思考中...)**: *(调用工具* *`export_training_records`)*
|
||||
- **Agent**: "✅ 已为您生成本月的培训成绩报表,包含入职日期、部门、姓名、工号和最终分数。
|
||||
📁 **点击下载文件**:\[本月新人培训合格名单.xlsx]"
|
||||
|
||||
## 10. 最终建议
|
||||
|
||||
对于“员工培训 Agent”,当前阶段最合适的技术路线是:
|
||||
|
||||
- **主链**:继续采用当前 `Chat 化展示 + 受控工作区 + 后端真实落库`
|
||||
- **增强层**:再逐步接入 Dify 做 FAQ、解释和 HR ChatBI
|
||||
|
||||
不建议将考试主链整体改造成纯 Dify 编排,否则会显著增加:
|
||||
|
||||
- 流程漂移风险
|
||||
- 防作弊成本
|
||||
- 测试成本
|
||||
- 审计成本
|
||||
|
||||
## 11. 一句话结论
|
||||
|
||||
**员工培训考试主链要“稳、准、可审计”,就让 HXOPS 前后端控制;Dify 更适合做问答增强和 HR 自然语言数据助手。**
|
||||
@@ -97,6 +97,7 @@ onMounted(() => {
|
||||
<select v-model="permissionFilters.role" class="admin-table-filter-input w-32">
|
||||
<option value="">{{ t('admin.perm.allRoles') }}</option>
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/users/UsersPage.vue
|
||||
* 用途:用户管理独立页面(服务端筛选分页、批量操作)。
|
||||
* 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。
|
||||
@@ -189,10 +189,19 @@ onMounted(() => {
|
||||
<td class="px-6 py-4">
|
||||
<span
|
||||
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
|
||||
:class="user.role === 'admin' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-blue-50 text-blue-700 border-blue-100'"
|
||||
:class="user.role === 'admin'
|
||||
? 'bg-purple-50 text-purple-700 border-purple-100'
|
||||
: user.role === 'hr'
|
||||
? 'bg-emerald-50 text-emerald-700 border-emerald-100'
|
||||
: 'bg-blue-50 text-blue-700 border-blue-100'"
|
||||
>
|
||||
{{ t('admin.role.' + user.role) }}
|
||||
</span>
|
||||
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2">
|
||||
<span class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
|
||||
{{ t('admin.user.fields.trainingHrManage') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-right">
|
||||
<button
|
||||
|
||||
@@ -39,6 +39,7 @@ const { t } = useI18n();
|
||||
<select v-model="form.role" class="input-field text-sm">
|
||||
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -87,9 +87,24 @@ const { t } = useI18n();
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
|
||||
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
|
||||
<option value="user">{{ t('admin.role.user') }}</option>
|
||||
<option value="hr">{{ t('admin.role.hr') }}</option>
|
||||
<option value="admin">{{ t('admin.role.admin') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-2 rounded-2xl border border-default bg-surface px-4 py-4">
|
||||
<div class="text-xs font-semibold uppercase tracking-wider text-muted">{{ t('admin.user.fields.featurePermissions') }}</div>
|
||||
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
|
||||
<input
|
||||
v-model="form.feature_permissions.training_hr_manage"
|
||||
type="checkbox"
|
||||
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
|
||||
/>
|
||||
<span class="space-y-1">
|
||||
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.trainingHrManage') }}</span>
|
||||
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
|
||||
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
|
||||
* features/admin/modules/users/composables/useUsersAdmin.ts
|
||||
|
||||
@@ -386,6 +386,10 @@ export function useUsersAdmin() {
|
||||
|
||||
phone_number: user.phone_number || '',
|
||||
|
||||
feature_permissions: {
|
||||
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
|
||||
},
|
||||
|
||||
agent_ids: user.agent_ids || [],
|
||||
|
||||
};
|
||||
@@ -508,6 +512,8 @@ export function useUsersAdmin() {
|
||||
|
||||
phone_number: editingUser.value.phone_number,
|
||||
|
||||
feature_permissions: editingUser.value.feature_permissions,
|
||||
|
||||
agent_ids: editingUser.value.agent_ids,
|
||||
|
||||
});
|
||||
@@ -532,6 +538,8 @@ export function useUsersAdmin() {
|
||||
|
||||
phone_number: editingUser.value.phone_number,
|
||||
|
||||
feature_permissions: editingUser.value.feature_permissions,
|
||||
|
||||
agent_ids: editingUser.value.agent_ids,
|
||||
|
||||
});
|
||||
|
||||
@@ -37,6 +37,9 @@ export interface AdminUserRow {
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
phone_number?: string;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
};
|
||||
agent_ids: number[];
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ export interface UserFormState {
|
||||
real_name: string;
|
||||
employee_id: string;
|
||||
phone_number: string;
|
||||
feature_permissions: {
|
||||
training_hr_manage: boolean;
|
||||
};
|
||||
agent_ids: number[];
|
||||
}
|
||||
|
||||
@@ -48,6 +51,9 @@ export const createEmptyUserForm = (): UserFormState => ({
|
||||
real_name: '',
|
||||
employee_id: '',
|
||||
phone_number: '',
|
||||
feature_permissions: {
|
||||
training_hr_manage: false,
|
||||
},
|
||||
agent_ids: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/auth/stores/auth.store.ts
|
||||
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
|
||||
*/
|
||||
@@ -19,6 +19,10 @@ export interface AuthUser {
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
role?: string;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
[key: string]: boolean | undefined;
|
||||
};
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
|
||||
@@ -70,6 +70,20 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| (typeof msg.chat_log_id === 'number' ? `chat-log:${msg.chat_log_id}` : '')
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/**
|
||||
* 标记“当前消息后面是否还存在新的 assistant 消息”。
|
||||
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
|
||||
* 用户作答后虽然会追加一条 user 消息,但这不应让上一张题卡立刻失活。
|
||||
*/
|
||||
const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
const current = items[index];
|
||||
if (!current || current.role !== 'assistant') return false;
|
||||
for (let i = items.length - 1; i > index; i -= 1) {
|
||||
if (items[i]?.role === 'assistant') return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -98,6 +112,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
:show-chat-rating="showChatRating"
|
||||
:copied-index="copiedIndex"
|
||||
:is-shipping-notice-agent="isShippingNoticeAgent"
|
||||
:is-latest-assistant-message="isLatestAssistantMessage(messages, index)"
|
||||
:handlers="handlers"
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
|
||||
@@ -19,7 +19,7 @@ import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspace
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { matchesTrainingAgent } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
const page = useChatPageContext();
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
@@ -146,8 +146,11 @@ watch(() => page.currentAgentId, () => {
|
||||
<TrainingWorkspacePanel
|
||||
:current-agent="page.currentAgent"
|
||||
:current-user="page.currentUser"
|
||||
:agent-guides="page.agentGuides"
|
||||
:has-messages="page.messages.length > 0"
|
||||
:new-session-tick="page.viewId"
|
||||
:training="page.training"
|
||||
@open-guide="page.openGuideModal"
|
||||
@send-chat-prompt="page.handleSend($event)"
|
||||
@push-local-assistant-message="page.pushLocalAssistantMessage($event)"
|
||||
@update:expanded="isTrainingWorkspaceExpanded = $event"
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
BarChart3,
|
||||
BookOpen,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
@@ -17,24 +16,26 @@ import {
|
||||
Download,
|
||||
PlayCircle,
|
||||
RefreshCcw,
|
||||
Send,
|
||||
ShieldCheck,
|
||||
Target,
|
||||
Users,
|
||||
XCircle,
|
||||
} from 'lucide-vue-next';
|
||||
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
currentAgent: Record<string, unknown> | null;
|
||||
currentUser: Record<string, unknown> | null;
|
||||
agentGuides: TrainingGuideLike[];
|
||||
hasMessages: boolean;
|
||||
newSessionTick: number;
|
||||
training: ShallowUnwrapRef<ReturnType<typeof useTrainingWorkspace>>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'send-chat-prompt': [prompt: string];
|
||||
'push-local-assistant-message': [content: string];
|
||||
'open-guide': [guideId?: number];
|
||||
'update:expanded': [expanded: boolean];
|
||||
}>();
|
||||
|
||||
@@ -94,23 +95,25 @@ const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
|
||||
}
|
||||
};
|
||||
|
||||
const sendPrompt = (prompt: string) => {
|
||||
setWorkspaceExpanded(false);
|
||||
emit('send-chat-prompt', prompt);
|
||||
};
|
||||
|
||||
const currentAnswerLabel = computed(() => {
|
||||
const question = workspace.currentQuestion;
|
||||
if (!question) return '';
|
||||
return question.options?.find((item) => item.id === workspace.selectedOptionId)?.label || '';
|
||||
});
|
||||
|
||||
const trainingExamPdfGuide = computed(() => resolveTrainingExamPdfGuide(props.agentGuides));
|
||||
|
||||
// 默认进入 Chat 聊天页面(即收起工作区状态)
|
||||
const workspaceExpanded = ref(false);
|
||||
|
||||
const autoSyncInitialPrompt = () => {
|
||||
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
|
||||
emit('push-local-assistant-message', workspace.learnerChatPrompt);
|
||||
if (
|
||||
workspace.isTrainingAgent
|
||||
&& workspace.isHydrated
|
||||
&& !props.hasMessages
|
||||
&& workspace.shouldShowNewSessionReminder
|
||||
) {
|
||||
emit('push-local-assistant-message', workspace.newSessionReminderMessage);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -142,6 +145,14 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.newSessionTick,
|
||||
(tick, prevTick) => {
|
||||
if (!tick || tick === prevTick) return;
|
||||
autoSyncInitialPrompt();
|
||||
},
|
||||
);
|
||||
|
||||
const isCompactMode = computed(() => !workspaceExpanded.value);
|
||||
|
||||
const compactSummary = computed(() => {
|
||||
@@ -158,6 +169,14 @@ const compactSummary = computed(() => {
|
||||
}
|
||||
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
|
||||
});
|
||||
|
||||
const trainingTitle = computed(() => String(t('chat.training.title') || '').trim());
|
||||
const ruleItems = computed(() => ([
|
||||
t('chat.training.rules.rule1', { total: workspace.totalQuestionCount }),
|
||||
t('chat.training.rules.rule2'),
|
||||
t('chat.training.rules.rule3', { passScore: workspace.passScore }),
|
||||
t('chat.training.rules.rule4'),
|
||||
]));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -177,8 +196,8 @@ const compactSummary = computed(() => {
|
||||
<BookOpen class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.training.badge') }}
|
||||
</div>
|
||||
<div class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ $t('chat.training.title') }}
|
||||
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ trainingTitle }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1.5 flex flex-wrap gap-2">
|
||||
@@ -203,6 +222,15 @@ const compactSummary = computed(() => {
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4 shrink-0" />
|
||||
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.stage === 'video'"
|
||||
type="button"
|
||||
@@ -212,23 +240,6 @@ const compactSummary = computed(() => {
|
||||
<PlayCircle class="h-4 w-4" />
|
||||
{{ $t('chat.training.steps.video') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncLearnerToChat') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||
@click="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<BarChart3 class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncHrToChat') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@@ -276,8 +287,8 @@ const compactSummary = computed(() => {
|
||||
<BookOpen class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.training.badge') }}
|
||||
</div>
|
||||
<div class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ $t('chat.training.title') }}
|
||||
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ trainingTitle }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -304,21 +315,13 @@ const compactSummary = computed(() => {
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncLearnerToChat') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||
@click="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<BarChart3 class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncHrToChat') }}
|
||||
<BookOpen class="h-4 w-4 shrink-0" />
|
||||
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -409,6 +412,15 @@ const compactSummary = computed(() => {
|
||||
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.video.title') }}</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.viewExamPdf') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
|
||||
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
|
||||
@@ -427,14 +439,25 @@ const compactSummary = computed(() => {
|
||||
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.summary.title') }}</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.summary.description') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.startExam"
|
||||
>
|
||||
<Target class="h-4 w-4" />
|
||||
{{ $t('chat.training.summary.startExam') }}
|
||||
</button>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.viewExamPdf') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.startExam"
|
||||
>
|
||||
<Target class="h-4 w-4" />
|
||||
{{ $t('chat.training.summary.startExam') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-3 md:grid-cols-2">
|
||||
@@ -475,7 +498,7 @@ const compactSummary = computed(() => {
|
||||
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
|
||||
{{ $t('chat.training.exam.passLine') }}
|
||||
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -565,7 +588,7 @@ const compactSummary = computed(() => {
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passTitle') : $t('chat.training.result.failTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-secondary">
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore: workspace.passScore }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -606,14 +629,6 @@ const compactSummary = computed(() => {
|
||||
<RefreshCcw class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.retryExam') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.sendToChat') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -643,21 +658,9 @@ const compactSummary = computed(() => {
|
||||
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
|
||||
<ul class="mt-2 grid gap-1 text-xs leading-5 text-secondary">
|
||||
<li class="flex gap-2">
|
||||
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule1') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule2') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule3') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule4') }}</span>
|
||||
<span>{{ rule }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -667,32 +670,41 @@ const compactSummary = computed(() => {
|
||||
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
|
||||
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.total }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.total }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
|
||||
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
|
||||
<div class="text-2xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
|
||||
<div class="text-2xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="grid gap-3 xl:grid-cols-3">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.keywordLabel') }}</span>
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
|
||||
<label>
|
||||
<input
|
||||
v-model="workspace.hrKeyword"
|
||||
type="text"
|
||||
@@ -700,8 +712,7 @@ const compactSummary = computed(() => {
|
||||
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.statusLabel') }}</span>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrStatusFilter"
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
|
||||
@@ -712,8 +723,7 @@ const compactSummary = computed(() => {
|
||||
<option value="in_progress">{{ $t('chat.training.hr.status.in_progress') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.departmentLabel') }}</span>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrDepartmentFilter"
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
|
||||
@@ -724,17 +734,7 @@ const compactSummary = computed(() => {
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-10 items-center gap-2 rounded-xl border border-default bg-white px-4 text-xs font-medium text-secondary transition hover:bg-surface-soft sm:text-sm"
|
||||
@click="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.hr.actions.askAgent') }}
|
||||
</button>
|
||||
<div class="flex justify-center xl:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-10 items-center gap-2 rounded-xl bg-brand-600 px-4 text-xs font-medium text-white transition hover:bg-brand-700 sm:text-sm"
|
||||
@@ -743,6 +743,7 @@ const compactSummary = computed(() => {
|
||||
<Download class="h-4 w-4" />
|
||||
{{ $t('chat.training.hr.actions.export') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ const {
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
isLatestAssistantMessage,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
shippingHandlers,
|
||||
@@ -60,6 +61,7 @@ const {
|
||||
showChatRating: boolean;
|
||||
copiedIndex: number | null;
|
||||
isShippingNoticeAgent: boolean;
|
||||
isLatestAssistantMessage: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
@@ -93,20 +95,35 @@ const isTrainingVideoMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
// 只要包含特定引导文案,就显示视频占位符,不限于最后一条消息
|
||||
const content = message.content || '';
|
||||
return content.includes('专属入职培训助手') || (content.includes('看视频') && content.includes('已看完'));
|
||||
return content.includes('专属入职培训助手')
|
||||
|| content.includes('onboarding training assistant')
|
||||
|| content.includes('ผู้ช่วยอบรมพนักงานใหม่')
|
||||
|| content.includes('入职培训视频')
|
||||
|| content.includes('training video');
|
||||
});
|
||||
|
||||
const isTrainingSummaryMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
const content = message.content || '';
|
||||
return content.includes('完成视频学习') || content.includes('复盘重点知识') || content.includes('复盘知识点') || content.includes('总结重点知识');
|
||||
return content.includes('完成视频学习')
|
||||
|| content.includes('复盘重点知识')
|
||||
|| content.includes('复盘知识点')
|
||||
|| content.includes('总结重点知识')
|
||||
|| content.includes('核心知识点')
|
||||
|| content.includes('key knowledge points')
|
||||
|| content.includes('ประเด็นสำคัญ');
|
||||
});
|
||||
|
||||
const isTrainingResultMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
// 只要是结果文案,就显示结算卡片,不限于最后一条消息
|
||||
const content = message.content || '';
|
||||
return content.includes('考试结束') || content.includes('顺利通过新人考核');
|
||||
return content.includes('考试结束')
|
||||
|| content.includes('顺利通过新人考核')
|
||||
|| content.includes('Exam finished')
|
||||
|| content.includes('passed the onboarding assessment')
|
||||
|| content.includes('สอบเสร็จแล้ว')
|
||||
|| content.includes('ผ่านการประเมินพนักงานใหม่');
|
||||
});
|
||||
|
||||
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
|
||||
@@ -125,7 +142,7 @@ const showShippingActionsPanel = computed(() =>
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const isLastMessage = computed(() => index === messageCount - 1);
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
|
||||
@@ -614,19 +631,22 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:current-question-index="trainingHandlers.getCurrentQuestionIndex()"
|
||||
:answered-count="trainingHandlers.getAnsweredCount()"
|
||||
:total-count="trainingHandlers.getTotalCount()"
|
||||
:pass-score="trainingHandlers.getPassScore()"
|
||||
:score="trainingHandlers.getScore()"
|
||||
:selected-option-id="trainingHandlers.getSelectedOptionId()"
|
||||
:answer-locked="trainingHandlers.getAnswerLocked()"
|
||||
:feedback-correct="trainingHandlers.getFeedbackCorrect()"
|
||||
:answer-label="trainingHandlers.getAnswerLabel()"
|
||||
:latest-exam-feedback="trainingHandlers.getLatestExamFeedback()"
|
||||
:is-thinking="isThinking"
|
||||
@select="trainingHandlers.onSelect"
|
||||
@next="trainingHandlers.onNext"
|
||||
/>
|
||||
<TrainingResultCard
|
||||
v-else-if="isTrainingResultMessage"
|
||||
:score="trainingHandlers.getScore()"
|
||||
:is-passed="trainingHandlers.getScore() >= 90"
|
||||
:score="trainingHandlers.getResultScore()"
|
||||
:is-passed="trainingHandlers.getResultPassed()"
|
||||
:pass-score="trainingHandlers.getPassScore()"
|
||||
:correct-count="trainingHandlers.getCorrectCount()"
|
||||
:wrong-count="trainingHandlers.getWrongCount()"
|
||||
:is-thinking="isThinking"
|
||||
|
||||
@@ -5,23 +5,27 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { CheckCircle2, XCircle, ClipboardCheck } from 'lucide-vue-next';
|
||||
import type { TrainingQuestion } from '@/features/chat/training/training.types';
|
||||
import type { TrainingExamTransitionFeedback, TrainingQuestion } from '@/features/chat/training/training.types';
|
||||
|
||||
export interface TrainingHandlers {
|
||||
getQuestion: () => TrainingQuestion | null;
|
||||
getCurrentQuestionIndex: () => number;
|
||||
getAnsweredCount: () => number;
|
||||
getTotalCount: () => number;
|
||||
getPassScore: () => number;
|
||||
getScore: () => number;
|
||||
getSelectedOptionId: () => string;
|
||||
getAnswerLocked: () => boolean;
|
||||
getFeedbackCorrect: () => boolean;
|
||||
getAnswerLabel: () => string;
|
||||
getLatestExamFeedback: () => TrainingExamTransitionFeedback | null;
|
||||
onSelect: (optionId: string) => void;
|
||||
onNext: () => void;
|
||||
onPlayVideo: () => void;
|
||||
onStartExam: () => void;
|
||||
onRestartExam: () => void;
|
||||
getResultScore: () => number;
|
||||
getResultPassed: () => boolean;
|
||||
getCorrectCount: () => number;
|
||||
getWrongCount: () => number;
|
||||
getSummaryPoints: () => string[];
|
||||
@@ -33,11 +37,13 @@ const props = defineProps<{
|
||||
currentQuestionIndex: number;
|
||||
answeredCount: number;
|
||||
totalCount: number;
|
||||
passScore: number;
|
||||
score: number;
|
||||
selectedOptionId: string;
|
||||
answerLocked: boolean;
|
||||
feedbackCorrect: boolean;
|
||||
answerLabel: string;
|
||||
latestExamFeedback: TrainingExamTransitionFeedback | null;
|
||||
isThinking: boolean;
|
||||
}>();
|
||||
|
||||
@@ -46,7 +52,6 @@ const emit = defineEmits<{
|
||||
next: [];
|
||||
}>();
|
||||
|
||||
const passLine = 90;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -68,7 +73,42 @@ const passLine = 90;
|
||||
</div>
|
||||
<div class="rounded-lg bg-slate-50 px-3 py-1.5 font-medium text-slate-600 border border-slate-100 flex items-center gap-2">
|
||||
<span>及格线:</span>
|
||||
<span class="text-slate-800 font-bold">{{ passLine }} 分</span>
|
||||
<span class="text-slate-800 font-bold">{{ passScore }} 分</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 上一题反馈摘要:自动推进到下一题后,仍需把对错、解析和分数留在同一张题卡顶部 -->
|
||||
<div
|
||||
v-if="latestExamFeedback"
|
||||
class="rounded-2xl border p-4"
|
||||
:class="latestExamFeedback.correct ? 'border-emerald-100 bg-emerald-50/60' : 'border-red-100 bg-red-50/60'"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-sm font-bold" :class="latestExamFeedback.correct ? 'text-emerald-700' : 'text-red-700'">
|
||||
<CheckCircle2 v-if="latestExamFeedback.correct" class="h-4 w-4" />
|
||||
<XCircle v-else class="h-4 w-4" />
|
||||
{{ latestExamFeedback.correct ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/70 px-3 py-1 text-xs font-semibold text-slate-600">
|
||||
{{ $t('chat.training.exam.currentScore', { score: latestExamFeedback.scoreAfterAnswer }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 space-y-2 text-[13px] leading-6 text-slate-600">
|
||||
<div class="text-slate-500">{{ latestExamFeedback.questionPrompt }}</div>
|
||||
<div class="flex gap-2">
|
||||
<span class="font-medium" :class="latestExamFeedback.correct ? 'text-emerald-600' : 'text-red-600'">
|
||||
{{ $t('chat.training.exam.selectedAnswer', { answer: latestExamFeedback.selectedAnswerLabel || '--' }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="!latestExamFeedback.correct" class="flex gap-2">
|
||||
<span class="text-emerald-600 font-medium">
|
||||
{{ $t('chat.training.exam.correctAnswer', { answer: latestExamFeedback.correctAnswerLabel || '--' }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="pl-2 border-l-2 border-slate-200/60 text-slate-500/90">
|
||||
{{ latestExamFeedback.explanation }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ShieldCheck, XCircle, RotateCcw, CheckCircle2 } from 'lucide-vue-next';
|
||||
defineProps<{
|
||||
score: number;
|
||||
isPassed: boolean;
|
||||
passScore: number;
|
||||
correctCount: number;
|
||||
wrongCount: number;
|
||||
isThinking: boolean;
|
||||
@@ -65,7 +66,7 @@ const emit = defineEmits<{
|
||||
|
||||
<!-- 描述语 -->
|
||||
<div class="text-sm leading-relaxed text-slate-600">
|
||||
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
|
||||
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore }) }}
|
||||
</div>
|
||||
|
||||
<!-- 操作 -->
|
||||
|
||||
@@ -650,6 +650,7 @@ export function useChat() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface AgentGuide {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
guide_usage?: string;
|
||||
file_url?: string;
|
||||
file_path?: string;
|
||||
remark?: string;
|
||||
@@ -42,8 +43,9 @@ export function useChatGuides(options: UseChatGuidesOptions) {
|
||||
guides.value = [];
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
const first = guides.value[0];
|
||||
const openModal = (guideId?: number | null) => {
|
||||
const preferred = guideId ? guides.value.find((g) => g.id === guideId) : null;
|
||||
const first = preferred || guides.value[0];
|
||||
if (!first) return;
|
||||
activeGuideId.value = first.id;
|
||||
showModal.value = true;
|
||||
|
||||
@@ -27,7 +27,8 @@ import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
createChatPageLocalMessageApi,
|
||||
@@ -106,6 +107,7 @@ export function useChatPage() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
@@ -339,6 +341,7 @@ export function useChatPage() {
|
||||
const training = useTrainingWorkspace({
|
||||
currentAgent: computed(() => agent.currentAgent.value),
|
||||
currentUser: computed(() => currentUser.value),
|
||||
currentGuides: computed(() => chatGuides.guides.value),
|
||||
pushLocalAssistantMessage,
|
||||
pushLocalUserMessage,
|
||||
});
|
||||
@@ -476,6 +479,7 @@ export function useChatPage() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
input,
|
||||
browser,
|
||||
queryPreview,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 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 { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingProgress,
|
||||
@@ -15,6 +17,8 @@ import {
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
TrainingAnswerRecord,
|
||||
TrainingContentConfig,
|
||||
TrainingExamTransitionFeedback,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingProgressRecord,
|
||||
@@ -24,6 +28,13 @@ import type {
|
||||
TrainingStats,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
matchesTrainingAgent,
|
||||
resolveTrainingContentConfig,
|
||||
resolveTrainingVideoGuide,
|
||||
resolveTrainingVideoUrl,
|
||||
type TrainingGuideLike,
|
||||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
@@ -36,44 +47,41 @@ type TrainingUserLike = {
|
||||
real_name?: string | null;
|
||||
employee_id?: string | null;
|
||||
department?: string | null;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
} | null;
|
||||
} | null | undefined;
|
||||
|
||||
export interface UseTrainingWorkspaceOptions {
|
||||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||||
currentUser: ComputedRef<TrainingUserLike>;
|
||||
currentGuides: ComputedRef<TrainingGuideLike[]>;
|
||||
pushLocalAssistantMessage?: (content: string) => Promise<void>;
|
||||
pushLocalUserMessage?: (content: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||||
* AI 触发时机:当需要把培训 UI 只挂在指定 Agent 上时使用,优先读 extra_config 显式开关,避免误伤其他聊天场景。
|
||||
*/
|
||||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
const explicitFlags = [
|
||||
extraConfig.training_workspace_enabled,
|
||||
extraConfig.training_mode,
|
||||
extraConfig.training_agent,
|
||||
];
|
||||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||||
return true;
|
||||
}
|
||||
const name = String(agent?.name || '').trim();
|
||||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||||
}
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
|
||||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
/**
|
||||
* 按百分制计算当前答题得分。
|
||||
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
|
||||
*/
|
||||
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
|
||||
if (totalQuestionCount <= 0) return 0;
|
||||
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
|
||||
};
|
||||
|
||||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { currentAgent, currentUser, currentGuides, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { t, tm } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
@@ -83,10 +91,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const selectedOptionId = ref('');
|
||||
const answerLocked = ref(false);
|
||||
const currentFeedbackCorrect = ref(false);
|
||||
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
|
||||
const latestSettledResult = ref<{
|
||||
score: number;
|
||||
correctCount: number;
|
||||
wrongCount: number;
|
||||
isPassed: boolean;
|
||||
} | null>(null);
|
||||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||||
const completionDate = ref<string | null>(null);
|
||||
const currentJoinDate = ref<string | null>(null);
|
||||
const isHydrated = ref(false);
|
||||
const hasWarnedPersistFailure = ref(false);
|
||||
const hasWarnedLoadFailure = ref(false);
|
||||
|
||||
const hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
@@ -110,12 +127,12 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
const summaryPoints = computed(() => {
|
||||
const defaultSummaryPoints = computed(() => {
|
||||
const raw = tm('chat.training.summaryPoints');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
|
||||
const summaryChecklist = computed(() => {
|
||||
const defaultSummaryChecklist = computed(() => {
|
||||
const raw = tm('chat.training.summaryChecklist');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
@@ -134,7 +151,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}));
|
||||
});
|
||||
|
||||
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
|
||||
const mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.map((item) => {
|
||||
const type = String(item.type || 'single') as TrainingQuestion['type'];
|
||||
const rawOptions = Array.isArray(item.options) ? item.options : [];
|
||||
const options = type === 'boolean'
|
||||
@@ -152,14 +169,32 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
explanation: String(item.explanation || ''),
|
||||
options,
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
|
||||
|
||||
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
|
||||
currentAgent.value,
|
||||
{
|
||||
passScore: DEFAULT_PASS_SCORE,
|
||||
summaryPoints: defaultSummaryPoints.value,
|
||||
summaryChecklist: defaultSummaryChecklist.value,
|
||||
questionBank: defaultQuestionBank.value,
|
||||
},
|
||||
booleanOptions.value,
|
||||
));
|
||||
|
||||
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
|
||||
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
|
||||
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
|
||||
const passScore = computed(() => trainingContent.value.passScore);
|
||||
|
||||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||||
const answeredCount = computed(() => answerRecords.value.length);
|
||||
const correctCount = computed(() => answerRecords.value.filter((item) => item.correct).length);
|
||||
const wrongCount = computed(() => answerRecords.value.filter((item) => !item.correct).length);
|
||||
const isPassed = computed(() => score.value >= 90);
|
||||
const isPassed = computed(() => score.value >= passScore.value);
|
||||
|
||||
const learnerProgressPercent = computed(() => {
|
||||
if (stage.value === 'video') return 25;
|
||||
@@ -191,10 +226,67 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
answerRecords.value = [];
|
||||
completionDate.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
|
||||
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
|
||||
*/
|
||||
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
|
||||
if (!question) return optionId;
|
||||
return question.options?.find((item) => item.id === optionId)?.label || optionId;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
|
||||
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
|
||||
*/
|
||||
const buildExamFeedback = (
|
||||
question: TrainingQuestion | null,
|
||||
answerRecord: TrainingAnswerRecord | null | undefined,
|
||||
scoreAfterAnswer: number,
|
||||
): TrainingExamTransitionFeedback | null => {
|
||||
if (!question || !answerRecord) return null;
|
||||
return {
|
||||
questionId: question.id,
|
||||
questionPrompt: question.prompt,
|
||||
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
|
||||
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
|
||||
explanation: question.explanation,
|
||||
correct: Boolean(answerRecord.correct),
|
||||
scoreAfterAnswer,
|
||||
};
|
||||
};
|
||||
|
||||
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
|
||||
question?.type === 'boolean'
|
||||
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
|
||||
: t('chat.training.chatPrompts.assistantQuestionSingleType')
|
||||
);
|
||||
|
||||
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
|
||||
if (!question) return '';
|
||||
const optionLines = (question.options || []).map((option) => option.label).join('\n');
|
||||
return [
|
||||
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
|
||||
optionLines,
|
||||
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
|
||||
].filter(Boolean).join('\n');
|
||||
};
|
||||
|
||||
const buildSummaryAssistantMessage = () => {
|
||||
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
|
||||
return [
|
||||
t('chat.training.chatPrompts.assistantSummaryIntro'),
|
||||
summaryLines,
|
||||
'',
|
||||
t('chat.training.chatPrompts.assistantSummaryReady'),
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
const syncAnswerStateForCurrentQuestion = () => {
|
||||
const questionId = currentQuestion.value?.id;
|
||||
const currentAnswer = questionId
|
||||
@@ -210,6 +302,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
currentJoinDate.value = null;
|
||||
latestSettledResult.value = null;
|
||||
return;
|
||||
}
|
||||
stage.value = record.stage;
|
||||
@@ -219,6 +312,22 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
|
||||
completionDate.value = record.completionDate;
|
||||
currentJoinDate.value = record.joinDate || null;
|
||||
latestExamFeedback.value = null;
|
||||
if (record.stage === 'result') {
|
||||
latestSettledResult.value = {
|
||||
score: Number(record.score || 0),
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
|
||||
};
|
||||
}
|
||||
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
|
||||
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
|
||||
const previousAnswer = previousQuestion
|
||||
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
|
||||
: null;
|
||||
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
|
||||
}
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
@@ -237,13 +346,23 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||||
try {
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||||
hasWarnedPersistFailure.value = false;
|
||||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||||
completionDate.value = saved.completionDate;
|
||||
if (isAdminViewer.value) {
|
||||
void loadAdminRecords();
|
||||
}
|
||||
} catch {
|
||||
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
|
||||
} catch (error) {
|
||||
if (!hasWarnedPersistFailure.value) {
|
||||
hasWarnedPersistFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.error({
|
||||
title: t('chat.training.errors.persistTitle'),
|
||||
message: `${t('chat.training.errors.persistBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
await persistQueue;
|
||||
@@ -251,10 +370,33 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
|
||||
const loadTrainingProgress = async () => {
|
||||
if (!isTrainingAgent.value) return;
|
||||
if (!hasAuthenticatedUser.value) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const record = await getMyTrainingProgress();
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(record);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
|
||||
if (error instanceof BusinessError && error.status === 401) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
return;
|
||||
}
|
||||
if (!hasWarnedLoadFailure.value) {
|
||||
hasWarnedLoadFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.warning({
|
||||
title: t('chat.training.errors.loadTitle'),
|
||||
message: `${t('chat.training.errors.loadBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
applyProgressRecord(null);
|
||||
} finally {
|
||||
isHydrated.value = true;
|
||||
@@ -290,26 +432,49 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
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(
|
||||
[
|
||||
currentAgent,
|
||||
hasAuthenticatedUser,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([agent, loggedIn]) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!loggedIn) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
|
||||
[
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
hrKeyword,
|
||||
hrStatusFilter,
|
||||
hrDepartmentFilter,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([enabled, canView]) => {
|
||||
if (!enabled || !canView) return;
|
||||
void loadAdminRecords();
|
||||
@@ -320,37 +485,66 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const markVideoCompleted = () => {
|
||||
stage.value = 'summary';
|
||||
// 立即推入本地助手消息(复盘卡片)
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
if (totalQuestionCount.value <= 0) {
|
||||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||||
return;
|
||||
}
|
||||
stage.value = 'exam';
|
||||
attemptCount.value += 1;
|
||||
resetExamState();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.startExamCommand'));
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const selectAnswer = (optionId: string) => {
|
||||
if (answerLocked.value || !currentQuestion.value) return;
|
||||
const answeredQuestion = currentQuestion.value;
|
||||
selectedOptionId.value = optionId;
|
||||
const isCorrect = optionId === currentQuestion.value.answer;
|
||||
const isCorrect = optionId === answeredQuestion.answer;
|
||||
currentFeedbackCorrect.value = isCorrect;
|
||||
if (isCorrect) {
|
||||
score.value += 5;
|
||||
}
|
||||
answerRecords.value.push({
|
||||
questionId: currentQuestion.value.id,
|
||||
const nextCorrectAnswerCount = correctCount.value + (isCorrect ? 1 : 0);
|
||||
const nextScore = calculateTrainingScore(nextCorrectAnswerCount, totalQuestionCount.value);
|
||||
score.value = nextScore;
|
||||
const answerRecord: TrainingAnswerRecord = {
|
||||
questionId: answeredQuestion.id,
|
||||
selectedOptionId: optionId,
|
||||
correct: isCorrect,
|
||||
});
|
||||
answerLocked.value = true;
|
||||
};
|
||||
answerRecords.value.push(answerRecord);
|
||||
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
|
||||
|
||||
// 推入用户选择的答案到聊天流
|
||||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||||
const label = getQuestionOptionLabel(answeredQuestion, optionId);
|
||||
void pushLocalUserMessage?.(label);
|
||||
|
||||
// [STEP 1] 最后一题直接进入结算,对齐文档里的“答完即公布最终成绩”。
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
latestSettledResult.value = {
|
||||
score: nextScore,
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: nextScore >= passScore.value,
|
||||
};
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
|
||||
// [STEP 2] 非最后一题则在聊天流里自动反馈上一题,并紧接着展示下一题。
|
||||
currentQuestionIndex.value += 1;
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
@@ -364,7 +558,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
@@ -372,17 +566,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
stage.value = 'summary';
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.restartExamCommand'));
|
||||
// 重新推回视频导学,强制补考再次完整经过“视频 -> 复盘 -> 开考”链路。
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||||
};
|
||||
|
||||
const exportRecords = async () => {
|
||||
@@ -405,21 +601,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
const learnerChatPrompt = computed(() => {
|
||||
// 阶段 1:破冰与视频导学
|
||||
if (stage.value === 'video') {
|
||||
return `👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。\n\n▶️ 请先点击观看 [入职培训视频]。观看完毕后,请回复【已看完】。`;
|
||||
}
|
||||
// 阶段 2:知识点串讲
|
||||
if (stage.value === 'summary') {
|
||||
return `${t('chat.training.chatPrompts.afterVideo')}\n\n参考知识点:\n${summaryPoints.value.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
|
||||
}
|
||||
// 阶段 4:结算
|
||||
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
|
||||
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
|
||||
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.afterPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.afterFail', { score: score.value });
|
||||
}
|
||||
// 阶段 3:互动测试
|
||||
return t('chat.training.chatPrompts.examInProgress', {
|
||||
index: currentQuestionIndex.value + 1,
|
||||
total: totalQuestionCount.value,
|
||||
@@ -427,11 +616,36 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 新建培训聊天会话时使用的统一提醒文案。
|
||||
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
|
||||
*/
|
||||
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
|
||||
passScore: passScore.value,
|
||||
}));
|
||||
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
|
||||
|
||||
const learnerAssistantMessage = computed(() => {
|
||||
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
|
||||
if (stage.value === 'video') {
|
||||
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
|
||||
}
|
||||
if (stage.value === 'summary') {
|
||||
return buildSummaryAssistantMessage();
|
||||
}
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
|
||||
}
|
||||
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
|
||||
});
|
||||
|
||||
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;
|
||||
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
|
||||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||||
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -443,12 +657,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentQuestionIndex,
|
||||
currentQuestion,
|
||||
totalQuestionCount,
|
||||
passScore,
|
||||
answeredCount,
|
||||
score,
|
||||
attemptCount,
|
||||
selectedOptionId,
|
||||
answerLocked,
|
||||
currentFeedbackCorrect,
|
||||
latestExamFeedback,
|
||||
latestSettledResult,
|
||||
answerRecords,
|
||||
completionDate,
|
||||
summaryPoints,
|
||||
@@ -467,6 +684,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
filteredRecords,
|
||||
stats,
|
||||
learnerChatPrompt,
|
||||
newSessionReminderMessage,
|
||||
shouldShowNewSessionReminder,
|
||||
learnerAssistantMessage,
|
||||
managementChatPrompt,
|
||||
markVideoCompleted,
|
||||
startExam,
|
||||
|
||||
@@ -92,6 +92,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
getCurrentQuestionIndex: () => workspace.currentQuestionIndex.value,
|
||||
getAnsweredCount: () => workspace.answeredCount.value,
|
||||
getTotalCount: () => workspace.totalQuestionCount.value,
|
||||
getPassScore: () => workspace.passScore.value,
|
||||
getScore: () => workspace.score.value,
|
||||
getSelectedOptionId: () => workspace.selectedOptionId.value,
|
||||
getAnswerLocked: () => workspace.answerLocked.value,
|
||||
@@ -101,6 +102,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
if (!q) return '';
|
||||
return q.options?.find((o) => o.id === workspace.selectedOptionId.value)?.label || '';
|
||||
},
|
||||
getLatestExamFeedback: () => workspace.latestExamFeedback.value,
|
||||
onSelect: workspace.selectAnswer,
|
||||
onNext: workspace.moveToNextQuestion,
|
||||
onPlayVideo: () => {
|
||||
@@ -110,8 +112,10 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
},
|
||||
onStartExam: workspace.startExam,
|
||||
onRestartExam: workspace.restartExam,
|
||||
getCorrectCount: () => workspace.correctCount.value,
|
||||
getWrongCount: () => workspace.wrongCount.value,
|
||||
getCorrectCount: () => workspace.latestSettledResult.value?.correctCount ?? workspace.correctCount.value,
|
||||
getWrongCount: () => workspace.latestSettledResult.value?.wrongCount ?? workspace.wrongCount.value,
|
||||
getResultScore: () => workspace.latestSettledResult.value?.score ?? workspace.score.value,
|
||||
getResultPassed: () => workspace.latestSettledResult.value?.isPassed ?? workspace.isPassed.value,
|
||||
getSummaryPoints: () => workspace.summaryPoints.value,
|
||||
getSummaryChecklist: () => workspace.summaryChecklist.value,
|
||||
};
|
||||
|
||||
@@ -25,12 +25,29 @@ export interface TrainingQuestion {
|
||||
options?: TrainingQuestionOption[];
|
||||
}
|
||||
|
||||
export interface TrainingContentConfig {
|
||||
passScore: number;
|
||||
summaryPoints: string[];
|
||||
summaryChecklist: string[];
|
||||
questionBank: TrainingQuestion[];
|
||||
}
|
||||
|
||||
export interface TrainingAnswerRecord {
|
||||
questionId: string;
|
||||
selectedOptionId: string;
|
||||
correct: boolean;
|
||||
}
|
||||
|
||||
export interface TrainingExamTransitionFeedback {
|
||||
questionId: string;
|
||||
questionPrompt: string;
|
||||
selectedAnswerLabel: string;
|
||||
correctAnswerLabel: string;
|
||||
explanation: string;
|
||||
correct: boolean;
|
||||
scoreAfterAnswer: number;
|
||||
}
|
||||
|
||||
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
|
||||
|
||||
export interface TrainingRecord {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* features/chat/training/trainingWorkspace.utils.ts
|
||||
* 用途:沉淀新人培训工作区的纯函数规则,便于前端复用与单测。
|
||||
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
|
||||
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
|
||||
*/
|
||||
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
extra_config?: Record<string, unknown> | null;
|
||||
} | null | undefined;
|
||||
|
||||
export type TrainingGuideLike = {
|
||||
id?: number | null;
|
||||
file_type?: string | null;
|
||||
guide_usage?: string | null;
|
||||
file_url?: string | null;
|
||||
file_path?: string | null;
|
||||
} | null | undefined;
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> => (
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: {}
|
||||
);
|
||||
|
||||
const normalizeStringList = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
const normalizePassScore = (value: unknown, fallback: number): number => {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) return fallback;
|
||||
return Math.max(0, Math.min(100, Math.round(parsed)));
|
||||
};
|
||||
|
||||
const normalizeQuestionOptionList = (value: unknown): TrainingQuestionOption[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item, index) => {
|
||||
if (typeof item === 'string') {
|
||||
const label = item.trim();
|
||||
if (!label) return null;
|
||||
return {
|
||||
id: String.fromCharCode(97 + index),
|
||||
label,
|
||||
};
|
||||
}
|
||||
const raw = asRecord(item);
|
||||
const id = String(raw.id || '').trim() || String.fromCharCode(97 + index);
|
||||
const label = String(raw.label || '').trim();
|
||||
if (!label) return null;
|
||||
return { id, label };
|
||||
})
|
||||
.filter((item): item is TrainingQuestionOption => Boolean(item));
|
||||
};
|
||||
|
||||
const normalizeQuestionBank = (
|
||||
value: unknown,
|
||||
booleanOptions: TrainingQuestionOption[],
|
||||
): TrainingQuestion[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item, index): TrainingQuestion | null => {
|
||||
const raw = asRecord(item);
|
||||
const type: TrainingQuestion['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
|
||||
const prompt = String(raw.prompt || '').trim();
|
||||
if (!prompt) return null;
|
||||
const options = type === 'boolean'
|
||||
? booleanOptions
|
||||
: normalizeQuestionOptionList(raw.options);
|
||||
if (type === 'single' && options.length < 2) return null;
|
||||
const fallbackAnswer = type === 'boolean'
|
||||
? 'true'
|
||||
: String(options[0]?.id || '').trim();
|
||||
const answer = String(raw.answer || '').trim();
|
||||
const optionIds = options.map((option) => option.id);
|
||||
return {
|
||||
id: String(raw.id || '').trim() || `q${index + 1}`,
|
||||
type,
|
||||
prompt,
|
||||
answer: optionIds.includes(answer) ? answer : fallbackAnswer,
|
||||
explanation: String(raw.explanation || '').trim(),
|
||||
options,
|
||||
};
|
||||
})
|
||||
.filter((item): item is TrainingQuestion => Boolean(item));
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用培训工作区。
|
||||
* AI 触发时机:当聊天页需要决定是否渲染“视频 -> 总结 -> 答题”培训主链时使用,优先读取显式配置,避免误伤普通 Agent。
|
||||
*/
|
||||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
|
||||
return false;
|
||||
}
|
||||
const explicitFlags = [
|
||||
extraConfig.training_workspace_enabled,
|
||||
extraConfig.training_mode,
|
||||
extraConfig.training_agent,
|
||||
];
|
||||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||||
return true;
|
||||
}
|
||||
const name = String(agent?.name || '').trim();
|
||||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析培训视频地址。
|
||||
* AI 触发时机:当培训工作区需要决定播放哪个培训视频时使用,若 Agent 未配置专属视频,则回退到默认地址。
|
||||
*/
|
||||
export function resolveTrainingVideoUrl(agent: TrainingAgentLike, fallbackUrl: string): string {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||||
return customUrl || fallbackUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找培训工作区优先使用的视频指南。
|
||||
* AI 触发时机:当培训工作区需要从后台上传资料中挑选正式培训视频时使用,优先选显式标记为 training_video 的文件。
|
||||
*/
|
||||
export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
||||
const normalized = Array.isArray(guides) ? guides : [];
|
||||
return (
|
||||
normalized.find((guide) => guide?.guide_usage === 'training_video' && guide?.file_type === 'video')
|
||||
|| normalized.find((guide) => guide?.file_type === 'video')
|
||||
|| null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找培训工作区优先使用的试题 PDF。
|
||||
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
|
||||
*/
|
||||
export function resolveTrainingExamPdfGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
||||
const normalized = Array.isArray(guides) ? guides : [];
|
||||
return (
|
||||
normalized.find((guide) => guide?.guide_usage === 'training_exam_pdf' && guide?.file_type === 'pdf')
|
||||
|| null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析培训工作区的后台配置。
|
||||
* AI 触发时机:当培训工作区需要优先消费 Agent extra_config 中的题库、复盘要点和及格线时使用;若后台未配置,则逐项回退到前端默认值。
|
||||
*/
|
||||
export function resolveTrainingContentConfig(
|
||||
agent: TrainingAgentLike,
|
||||
fallback: TrainingContentConfig,
|
||||
booleanOptions: TrainingQuestionOption[],
|
||||
): TrainingContentConfig {
|
||||
const extraConfig = asRecord(agent?.extra_config);
|
||||
const trainingConfig = asRecord(extraConfig.training_config);
|
||||
const mergedConfig = {
|
||||
...extraConfig,
|
||||
...trainingConfig,
|
||||
};
|
||||
|
||||
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
|
||||
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
|
||||
const questionBank = normalizeQuestionBank(
|
||||
mergedConfig.question_bank ?? mergedConfig.questionBank,
|
||||
booleanOptions,
|
||||
);
|
||||
|
||||
return {
|
||||
passScore: normalizePassScore(
|
||||
mergedConfig.pass_score ?? mergedConfig.passScore,
|
||||
fallback.passScore || DEFAULT_PASS_SCORE,
|
||||
),
|
||||
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,
|
||||
summaryChecklist: summaryChecklist.length ? summaryChecklist : fallback.summaryChecklist,
|
||||
questionBank: questionBank.length ? questionBank : fallback.questionBank,
|
||||
};
|
||||
}
|
||||
@@ -470,8 +470,8 @@
|
||||
}
|
||||
},
|
||||
"training": {
|
||||
"badge": "Onboarding Training Workspace",
|
||||
"title": "Onboarding Training Agent",
|
||||
"badge": "Employee Training Workspace",
|
||||
"title": "",
|
||||
"subtitle": "Complete video learning, knowledge review, one-question-at-a-time testing, and HR reporting in the same chat page.",
|
||||
"tabs": {
|
||||
"learner": "Learner",
|
||||
@@ -481,7 +481,8 @@
|
||||
"syncLearnerToChat": "Sync learner context to chat",
|
||||
"syncHrToChat": "Sync HR filters to chat",
|
||||
"expandWorkspace": "Expand workspace",
|
||||
"collapseWorkspace": "Collapse workspace"
|
||||
"collapseWorkspace": "Collapse Workspace",
|
||||
"viewExamPdf": "View Exam PDF"
|
||||
},
|
||||
"steps": {
|
||||
"video": "Watch Video",
|
||||
@@ -513,7 +514,7 @@
|
||||
"title": "Step 3: One-question-at-a-time exam",
|
||||
"questionCounter": "Question {current} / {total}",
|
||||
"currentScore": "Current score: {score}",
|
||||
"passLine": "Pass line: 90 points",
|
||||
"passLine": "Pass line: {passScore} points",
|
||||
"correctFeedback": "Correct. Move on to the next question.",
|
||||
"wrongFeedback": "Incorrect. The correct answer is now shown.",
|
||||
"selectedAnswer": "Your answer: {answer}",
|
||||
@@ -526,8 +527,8 @@
|
||||
"failedTag": "Retake required",
|
||||
"passTitle": "Congratulations, you passed the onboarding exam",
|
||||
"failTitle": "This attempt did not meet the requirement",
|
||||
"passDescription": "The frontend pass-state interaction is complete. Once the backend is connected, it can write training records and the completion date.",
|
||||
"failDescription": "According to HR rules, any score below 90 requires a full retake until the learner passes.",
|
||||
"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.",
|
||||
"scoreLabel": "Final score",
|
||||
"attemptsLabel": "Attempts",
|
||||
"correctCount": "Correct answers",
|
||||
@@ -544,9 +545,9 @@
|
||||
},
|
||||
"rules": {
|
||||
"title": "Exam rules",
|
||||
"rule1": "There are 20 questions, 5 points each, with a full score of 100.",
|
||||
"rule1": "There are {total} questions, and the system calculates the result on a 100-point scale.",
|
||||
"rule2": "The system enforces one question, one answer, one feedback. Wrong answers show the correct answer immediately.",
|
||||
"rule3": "Any score below 90 is treated as failed and requires a retake.",
|
||||
"rule3": "Any score below {passScore} is treated as failed and requires a retake.",
|
||||
"rule4": "HR can view statistics and export Excel from the same chat page."
|
||||
},
|
||||
"hr": {
|
||||
@@ -593,7 +594,24 @@
|
||||
"afterSummary": "I finished reviewing the knowledge points. Please switch to exam mode and ask the first question.",
|
||||
"afterPass": "I passed the onboarding training exam with a score of {score}. Please help me generate a short completion summary.",
|
||||
"afterFail": "I scored {score} in the onboarding training exam and did not pass. Please summarize the weak points and prepare a retake reminder.",
|
||||
"examInProgress": "I am taking the onboarding training exam and am currently on question {index}/{total}. Please stay in proctor mode and continue."
|
||||
"examInProgress": "I am taking the onboarding training exam and am currently on question {index}/{total}. Please stay in proctor mode and continue.",
|
||||
"assistantVideoIntro": "👋 Welcome aboard! I am your onboarding training assistant. Today's training has three steps: watch the video ➡️ review the key knowledge points ➡️ take the quiz ({passScore} points to pass).\n\n▶️ Please start with the onboarding training video. After watching it, move on to the knowledge review.",
|
||||
"assistantSummaryIntro": "Great. Based on the video, I pulled together the key knowledge points you are most likely to be tested on:",
|
||||
"assistantSummaryReady": "Ready for the challenge? Click Start Exam directly or reply \"Start Exam\" in the chat.",
|
||||
"assistantQuestionSingleType": "Single choice",
|
||||
"assistantQuestionBooleanType": "True or false",
|
||||
"assistantQuestionReplyHint": "Reply with the option or the answer text directly.",
|
||||
"assistantResultPass": "🎉 **Congratulations!** Your final score is **{score}**. You passed the onboarding assessment, and your score has been synced to HR automatically.",
|
||||
"assistantResultFail": "📊 **Exam finished!** Your final score is **{score}**. The passing line is {passScore}. Reply \"Retake Exam\" to try again.",
|
||||
"startExamCommand": "Start Exam",
|
||||
"restartExamCommand": "Retake Exam"
|
||||
},
|
||||
"errors": {
|
||||
"persistTitle": "Training record save failed",
|
||||
"persistBody": "The current exam result has not been written to the database, so the HR console and statistics will not update",
|
||||
"loadTitle": "Training record load failed",
|
||||
"loadBody": "The training record cannot be loaded from the database right now, so the page may not reflect the latest result",
|
||||
"questionBankEmpty": "The training question bank is empty. Please maintain it first in the Agent configuration."
|
||||
},
|
||||
"summaryPoints": [
|
||||
"Salary is paid on the 15th of each month, and attendance or leave requests must go through OA.",
|
||||
|
||||
@@ -470,8 +470,8 @@
|
||||
}
|
||||
},
|
||||
"training": {
|
||||
"badge": "พื้นที่อบรมพนักงานใหม่",
|
||||
"title": "Onboarding Training Agent",
|
||||
"badge": "พื้นที่อบรมพนักงาน",
|
||||
"title": "",
|
||||
"subtitle": "ทำวิดีโอเรียนรู้ ทบทวนความรู้ สอบทีละข้อ และดูสถิติ HR ได้ในหน้าแชตเดียวกัน",
|
||||
"tabs": {
|
||||
"learner": "ผู้เรียน",
|
||||
@@ -481,7 +481,8 @@
|
||||
"syncLearnerToChat": "ส่งบริบทผู้เรียนเข้าแชต",
|
||||
"syncHrToChat": "ส่งตัวกรอง HR เข้าแชต",
|
||||
"expandWorkspace": "ขยายพื้นที่ทำงาน",
|
||||
"collapseWorkspace": "ย่อพื้นที่ทำงาน"
|
||||
"collapseWorkspace": "ย่อพื้นที่ทำงาน",
|
||||
"viewExamPdf": "ดู PDF ข้อสอบ"
|
||||
},
|
||||
"steps": {
|
||||
"video": "ดูวิดีโอ",
|
||||
@@ -513,7 +514,7 @@
|
||||
"title": "ขั้นตอน 3: สอบทีละข้อ",
|
||||
"questionCounter": "ข้อ {current} / {total}",
|
||||
"currentScore": "คะแนนปัจจุบัน: {score}",
|
||||
"passLine": "ผ่านเมื่อได้ 90 คะแนน",
|
||||
"passLine": "เกณฑ์ผ่าน: {passScore} คะแนน",
|
||||
"correctFeedback": "ตอบถูก ไปข้อถัดไปได้",
|
||||
"wrongFeedback": "ตอบผิด ระบบแสดงคำตอบที่ถูกต้องแล้ว",
|
||||
"selectedAnswer": "คำตอบของคุณ: {answer}",
|
||||
@@ -526,8 +527,8 @@
|
||||
"failedTag": "ต้องสอบใหม่",
|
||||
"passTitle": "ยินดีด้วย คุณผ่านการสอบอบรมพนักงานใหม่แล้ว",
|
||||
"failTitle": "การสอบครั้งนี้ยังไม่ผ่านเกณฑ์",
|
||||
"passDescription": "ฝั่งหน้าเว็บรองรับสถานะผ่านแล้ว และสามารถเชื่อมต่อหลังบ้านเพื่อบันทึกผลได้ในขั้นถัดไป",
|
||||
"failDescription": "ตามกฎของ HR หากได้ต่ำกว่า 90 คะแนน ต้องสอบใหม่จนกว่าจะผ่าน",
|
||||
"passDescription": "คุณผ่านการสอบครั้งนี้แล้ว ระบบจะซิงก์คะแนนไปยังหน้าจอ HR และบันทึกลงประวัติการอบรมโดยอัตโนมัติ",
|
||||
"failDescription": "ตามกฎของ HR หากได้ต่ำกว่า {passScore} คะแนน ต้องสอบใหม่จนกว่าจะผ่าน",
|
||||
"scoreLabel": "คะแนนสุดท้าย",
|
||||
"attemptsLabel": "จำนวนครั้งที่สอบ",
|
||||
"correctCount": "จำนวนข้อที่ถูก",
|
||||
@@ -544,9 +545,9 @@
|
||||
},
|
||||
"rules": {
|
||||
"title": "กติกาการสอบ",
|
||||
"rule1": "มีทั้งหมด 20 ข้อ ข้อละ 5 คะแนน เต็ม 100 คะแนน",
|
||||
"rule1": "มีทั้งหมด {total} ข้อ และระบบจะคำนวณผลสอบบนสเกล 100 คะแนน",
|
||||
"rule2": "ระบบทำงานแบบหนึ่งข้อหนึ่งคำตอบหนึ่งฟีดแบ็ก และจะแสดงคำตอบที่ถูกเมื่อผู้ใช้ตอบผิด",
|
||||
"rule3": "หากได้ต่ำกว่า 90 คะแนน ถือว่าไม่ผ่านและต้องสอบใหม่",
|
||||
"rule3": "หากได้ต่ำกว่า {passScore} คะแนน ถือว่าไม่ผ่านและต้องสอบใหม่",
|
||||
"rule4": "HR สามารถดูสถิติและส่งออก Excel ได้จากหน้าแชตเดียวกัน"
|
||||
},
|
||||
"hr": {
|
||||
@@ -593,7 +594,24 @@
|
||||
"afterSummary": "ฉันทบทวนความรู้เสร็จแล้ว โปรดเริ่มโหมดสอบและถามข้อแรก",
|
||||
"afterPass": "ฉันผ่านการสอบอบรมพนักงานใหม่ด้วยคะแนน {score} โปรดช่วยสรุปการอบรมให้สั้น ๆ",
|
||||
"afterFail": "ฉันได้คะแนน {score} ในการสอบอบรมพนักงานใหม่และยังไม่ผ่าน โปรดสรุปจุดอ่อนและเตือนให้สอบใหม่",
|
||||
"examInProgress": "ฉันกำลังสอบอบรมพนักงานใหม่ ตอนนี้อยู่ที่ข้อ {index}/{total} โปรดทำหน้าที่เป็นผู้คุมสอบและถามต่อ"
|
||||
"examInProgress": "ฉันกำลังสอบอบรมพนักงานใหม่ ตอนนี้อยู่ที่ข้อ {index}/{total} โปรดทำหน้าที่เป็นผู้คุมสอบและถามต่อ",
|
||||
"assistantVideoIntro": "👋 ยินดีต้อนรับสู่บริษัท! ฉันคือผู้ช่วยอบรมพนักงานใหม่ของคุณ วันนี้มี 3 ขั้นตอนคือ ดูวิดีโอ ➡️ ทบทวนความรู้ ➡️ ทำแบบทดสอบ (ผ่านที่ {passScore} คะแนน)\n\n▶️ โปรดเริ่มจากการดูวิดีโออบรมพนักงานใหม่ แล้วจึงเข้าสู่ช่วงทบทวนความรู้",
|
||||
"assistantSummaryIntro": "ยอดเยี่ยม จากวิดีโอเมื่อครู่นี้ ฉันสรุปประเด็นสำคัญที่มีโอกาสออกสอบไว้ให้แล้ว:",
|
||||
"assistantSummaryReady": "พร้อมรับความท้าทายหรือยัง? กดเริ่มสอบได้เลย หรือพิมพ์ \"เริ่มสอบ\" ในแชตก็ได้",
|
||||
"assistantQuestionSingleType": "ปรนัย",
|
||||
"assistantQuestionBooleanType": "ถูกหรือผิด",
|
||||
"assistantQuestionReplyHint": "ตอบด้วยตัวเลือกหรือข้อความคำตอบได้โดยตรง",
|
||||
"assistantResultPass": "🎉 **ยินดีด้วย!** คุณได้คะแนนสุดท้าย **{score}** และผ่านการประเมินพนักงานใหม่แล้ว ระบบได้ซิงก์คะแนนไปยัง HR โดยอัตโนมัติ",
|
||||
"assistantResultFail": "📊 **สอบเสร็จแล้ว!** คะแนนสุดท้ายของคุณคือ **{score}** เกณฑ์ผ่านคือ {passScore} คะแนน พิมพ์ \"สอบใหม่\" เพื่อเริ่มอีกครั้ง",
|
||||
"startExamCommand": "เริ่มสอบ",
|
||||
"restartExamCommand": "สอบใหม่"
|
||||
},
|
||||
"errors": {
|
||||
"persistTitle": "บันทึกประวัติการอบรมไม่สำเร็จ",
|
||||
"persistBody": "ผลสอบปัจจุบันยังไม่ได้เขียนลงฐานข้อมูล ดังนั้นหน้าจอ HR และสถิติจะไม่อัปเดต",
|
||||
"loadTitle": "โหลดประวัติการอบรมไม่สำเร็จ",
|
||||
"loadBody": "ไม่สามารถอ่านประวัติการอบรมจากฐานข้อมูลได้ในขณะนี้ ดังนั้นหน้าปัจจุบันอาจไม่ใช่ผลล่าสุด",
|
||||
"questionBankEmpty": "คลังข้อสอบการอบรมว่างอยู่ โปรดตั้งค่าใน Agent configuration ก่อน"
|
||||
},
|
||||
"summaryPoints": [
|
||||
"เงินเดือนจ่ายทุกวันที่ 15 ของเดือน และการลาหรือการลงเวลาต้องทำผ่าน OA",
|
||||
|
||||
@@ -470,8 +470,8 @@
|
||||
}
|
||||
},
|
||||
"training": {
|
||||
"badge": "新人培训工作区",
|
||||
"title": "新人入职培训 Agent",
|
||||
"badge": "员工培训工作区",
|
||||
"title": "",
|
||||
"subtitle": "在同一个 Chat 页面内完成视频学习、知识点复盘、逐题考试以及 HR 管理统计。",
|
||||
"tabs": {
|
||||
"learner": "学员端",
|
||||
@@ -481,7 +481,8 @@
|
||||
"syncLearnerToChat": "同步学员上下文到聊天",
|
||||
"syncHrToChat": "同步 HR 筛选到聊天",
|
||||
"expandWorkspace": "展开工作区",
|
||||
"collapseWorkspace": "收起工作区"
|
||||
"collapseWorkspace": "收起工作区",
|
||||
"viewExamPdf": "查看试题 PDF"
|
||||
},
|
||||
"steps": {
|
||||
"video": "观看视频",
|
||||
@@ -513,7 +514,7 @@
|
||||
"title": "第三步:逐题考试",
|
||||
"questionCounter": "第 {current} / {total} 题",
|
||||
"currentScore": "当前分数:{score} 分",
|
||||
"passLine": "及格线:90 分",
|
||||
"passLine": "及格线:{passScore} 分",
|
||||
"correctFeedback": "回答正确,继续下一题",
|
||||
"wrongFeedback": "回答错误,已显示正确答案",
|
||||
"selectedAnswer": "你的答案:{answer}",
|
||||
@@ -526,8 +527,8 @@
|
||||
"failedTag": "需补考",
|
||||
"passTitle": "恭喜,你已通过新人培训考试",
|
||||
"failTitle": "本次考试未达标,需要重新考试",
|
||||
"passDescription": "前端已完成通过态交互,后续接入后端后可直接回写培训记录与完成日期。",
|
||||
"failDescription": "按照 HR 规则,未达到 90 分必须重新考试,直到最终通过为止。",
|
||||
"passDescription": "您已顺利通过本次考试,成绩会自动同步到 HR 管理端并计入培训记录。",
|
||||
"failDescription": "按照 HR 规则,未达到 {passScore} 分必须重新考试,直到最终通过为止。",
|
||||
"scoreLabel": "最终得分",
|
||||
"attemptsLabel": "考试次数",
|
||||
"correctCount": "答对题数",
|
||||
@@ -544,9 +545,9 @@
|
||||
},
|
||||
"rules": {
|
||||
"title": "考试规则",
|
||||
"rule1": "共 20 题,每题 5 分,满分 100 分。",
|
||||
"rule1": "共 {total} 题,系统按百分制自动计算成绩。",
|
||||
"rule2": "系统按“一题一答一反馈”执行,答错立即展示正确答案。",
|
||||
"rule3": "低于 90 分判定为未通过,必须重新考试。",
|
||||
"rule3": "低于 {passScore} 分判定为未通过,必须重新考试。",
|
||||
"rule4": "HR 管理端可在同一聊天页查看统计并导出 Excel。"
|
||||
},
|
||||
"hr": {
|
||||
@@ -593,7 +594,24 @@
|
||||
"afterSummary": "我已完成知识点复盘,请切换到考试模式并开始第一题。",
|
||||
"afterPass": "我已经通过新人培训考试,得分 {score} 分,请帮我生成一段培训完成总结。",
|
||||
"afterFail": "我本次新人培训考试得分 {score} 分,未达到及格线,请帮我总结错题重点并安排重考提醒。",
|
||||
"examInProgress": "我正在进行新人培训考试,目前做到第 {index}/{total} 题。题目是:{question}。请保持考官模式,评价我的表现并引导我继续。"
|
||||
"examInProgress": "我正在进行新人培训考试,目前做到第 {index}/{total} 题。题目是:{question}。请保持考官模式,评价我的表现并引导我继续。",
|
||||
"assistantVideoIntro": "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复盘 ➡️ 随堂测试({passScore} 分及格)。\n\n▶️ 请先点击观看【入职培训视频】。观看完毕后,点击进入【知识点复盘】。",
|
||||
"assistantSummaryIntro": "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦):",
|
||||
"assistantSummaryReady": "准备好接受挑战了吗?直接点击【开始考试】或在 Chat 中回复【开始考试】。",
|
||||
"assistantQuestionSingleType": "单选题",
|
||||
"assistantQuestionBooleanType": "判断题",
|
||||
"assistantQuestionReplyHint": "请直接回复选项或内容。",
|
||||
"assistantResultPass": "🎉 **恭喜!** 您的最终得分是 **{score} 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。",
|
||||
"assistantResultFail": "📊 **考试结束!** 您的最终得分是 **{score} 分**。及格线为 {passScore} 分。请回复【重新考试】再次挑战!",
|
||||
"startExamCommand": "开始考试",
|
||||
"restartExamCommand": "重新考试"
|
||||
},
|
||||
"errors": {
|
||||
"persistTitle": "培训记录保存失败",
|
||||
"persistBody": "当前考试结果尚未写入数据库,HR 管理与统计不会更新",
|
||||
"loadTitle": "培训记录读取失败",
|
||||
"loadBody": "当前无法从数据库读取培训记录,页面展示可能不是最新结果",
|
||||
"questionBankEmpty": "当前培训题库为空,请先在后台 Agent 配置中维护题库"
|
||||
},
|
||||
"summaryPoints": [
|
||||
"工资每月 15 号发放,考勤与请假均需要走 OA 流程。",
|
||||
@@ -617,8 +635,8 @@
|
||||
"id": "q1",
|
||||
"type": "single",
|
||||
"prompt": "工资每月几号发放?",
|
||||
"answer": "a",
|
||||
"explanation": "根据新人培训试卷答案,工资固定在每月 8 号发放。",
|
||||
"answer": "c",
|
||||
"explanation": "根据新人培训试卷答案,工资固定在每月 15 号发放。",
|
||||
"options": [
|
||||
{ "id": "a", "label": "A. 8号" },
|
||||
{ "id": "b", "label": "B. 9号" },
|
||||
|
||||
@@ -470,8 +470,8 @@
|
||||
}
|
||||
},
|
||||
"training": {
|
||||
"badge": "新人培訓工作區",
|
||||
"title": "新人入職培訓 Agent",
|
||||
"badge": "員工培訓工作區",
|
||||
"title": "",
|
||||
"subtitle": "在同一個 Chat 頁面內完成影片學習、知識點複盤、逐題考試與 HR 管理統計。",
|
||||
"tabs": {
|
||||
"learner": "學員端",
|
||||
@@ -481,7 +481,8 @@
|
||||
"syncLearnerToChat": "同步學員上下文到聊天",
|
||||
"syncHrToChat": "同步 HR 篩選到聊天",
|
||||
"expandWorkspace": "展開工作區",
|
||||
"collapseWorkspace": "收起工作區"
|
||||
"collapseWorkspace": "收起工作區",
|
||||
"viewExamPdf": "查看試題 PDF"
|
||||
},
|
||||
"steps": {
|
||||
"video": "觀看影片",
|
||||
@@ -513,7 +514,7 @@
|
||||
"title": "第三步:逐題考試",
|
||||
"questionCounter": "第 {current} / {total} 題",
|
||||
"currentScore": "當前分數:{score} 分",
|
||||
"passLine": "及格線:90 分",
|
||||
"passLine": "及格線:{passScore} 分",
|
||||
"correctFeedback": "回答正確,繼續下一題",
|
||||
"wrongFeedback": "回答錯誤,已顯示正確答案",
|
||||
"selectedAnswer": "你的答案:{answer}",
|
||||
@@ -526,8 +527,8 @@
|
||||
"failedTag": "需補考",
|
||||
"passTitle": "恭喜,你已通過新人培訓考試",
|
||||
"failTitle": "本次考試未達標,需要重新考試",
|
||||
"passDescription": "前端已完成通過態互動,後續接入後端後可直接回寫培訓記錄與完成日期。",
|
||||
"failDescription": "依照 HR 規則,低於 90 分必須重新考試,直到最終通過。",
|
||||
"passDescription": "你已順利通過本次考試,成績會自動同步到 HR 管理端並記入培訓紀錄。",
|
||||
"failDescription": "依照 HR 規則,低於 {passScore} 分必須重新考試,直到最終通過。",
|
||||
"scoreLabel": "最終得分",
|
||||
"attemptsLabel": "考試次數",
|
||||
"correctCount": "答對題數",
|
||||
@@ -544,9 +545,9 @@
|
||||
},
|
||||
"rules": {
|
||||
"title": "考試規則",
|
||||
"rule1": "共 20 題,每題 5 分,滿分 100 分。",
|
||||
"rule1": "共 {total} 題,系統按百分制自動計算成績。",
|
||||
"rule2": "系統依「一題一答一回饋」執行,答錯立即顯示正確答案。",
|
||||
"rule3": "低於 90 分視為未通過,必須重新考試。",
|
||||
"rule3": "低於 {passScore} 分視為未通過,必須重新考試。",
|
||||
"rule4": "HR 管理端可在同一聊天頁查看統計並匯出 Excel。"
|
||||
},
|
||||
"hr": {
|
||||
@@ -593,7 +594,24 @@
|
||||
"afterSummary": "我已完成知識點複盤,請切換到考試模式並開始第一題。",
|
||||
"afterPass": "我已通過新人培訓考試,得分 {score} 分,請幫我生成一段培訓完成總結。",
|
||||
"afterFail": "我本次新人培訓考試得分 {score} 分,未達及格線,請幫我總結錯題重點並安排重考提醒。",
|
||||
"examInProgress": "我正在進行新人培訓考試,目前做到第 {index}/{total} 題,請保持考官模式繼續出題。"
|
||||
"examInProgress": "我正在進行新人培訓考試,目前做到第 {index}/{total} 題,請保持考官模式繼續出題。",
|
||||
"assistantVideoIntro": "👋 歡迎加入公司!我是你的專屬入職培訓助手。今天的培訓分為三個步驟:看影片 ➡️ 知識點複盤 ➡️ 隨堂測試({passScore} 分及格)。\n\n▶️ 請先點擊觀看【入職培訓影片】。觀看完畢後,點擊進入【知識點複盤】。",
|
||||
"assistantSummaryIntro": "太棒了!結合剛才的影片,我為你提煉了以下核心知識點(必考哦):",
|
||||
"assistantSummaryReady": "準備好接受挑戰了嗎?直接點擊【開始考試】或在 Chat 中回覆【開始考試】。",
|
||||
"assistantQuestionSingleType": "單選題",
|
||||
"assistantQuestionBooleanType": "判斷題",
|
||||
"assistantQuestionReplyHint": "請直接回覆選項或內容。",
|
||||
"assistantResultPass": "🎉 **恭喜!** 你的最終得分是 **{score} 分**,已順利通過新人考核!成績已自動同步至人事部門。",
|
||||
"assistantResultFail": "📊 **考試結束!** 你的最終得分是 **{score} 分**。及格線為 {passScore} 分。請回覆【重新考試】再次挑戰!",
|
||||
"startExamCommand": "開始考試",
|
||||
"restartExamCommand": "重新考試"
|
||||
},
|
||||
"errors": {
|
||||
"persistTitle": "培訓記錄保存失敗",
|
||||
"persistBody": "當前考試結果尚未寫入資料庫,HR 管理與統計不會更新",
|
||||
"loadTitle": "培訓記錄讀取失敗",
|
||||
"loadBody": "目前無法從資料庫讀取培訓記錄,頁面顯示可能不是最新結果",
|
||||
"questionBankEmpty": "當前培訓題庫為空,請先在後台 Agent 配置中維護題庫"
|
||||
},
|
||||
"summaryPoints": [
|
||||
"工資每月 15 號發放,考勤與請假均需走 OA 流程。",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* shared/utils/auth.ts
|
||||
* 认证 token / 用户读写、logout、跨标签同步。
|
||||
*/
|
||||
@@ -8,6 +8,10 @@ export interface AuthUser {
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
role?: string;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
[key: string]: boolean | undefined;
|
||||
};
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
|
||||
Reference in new issue
Block a user