feat(training): 完善安全培训题库与考试交互

修复 PDF 导入判断和填空题解析,支持文本题判分、回顾改答及安全培训三级流程校验。
This commit is contained in:
runny committed 2026-08-18 01:12:04 +08:00
1 parent ec4ed9b67d
commit e62e4961d4
19 files changed
+721 -48

No files matched your search

+14
View File
@@ -30,6 +30,20 @@ def get_document_version_source_file(version_id: int):
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
@knowledge_base_bp.route('/document-versions/<int:version_id>/training-preview-file', methods=['GET'])
def get_training_preview_file(version_id: int):
"""
返回员工培训资料的可预览文件。
用途:培训配置文件预览使用与聊天源文件相同的受保护同源访问方式;原始文件缺失时由服务层回退清洗预览文件。
参数约束:仅允许已登录用户访问,不改变原始文件下载接口语义。
"""
require_user()
preview_path, filename = document_service.resolve_training_preview_file_path(version_id)
as_attachment = str(request.args.get('download') or '').strip() == '1'
return send_file(preview_path, as_attachment=as_attachment, download_name=filename)
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
def list_document_sync_records(document_id: int):
require_user()
@@ -27,11 +27,16 @@ from edkb_system.skills import loader_pdf, ocr
_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$')
_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*')
_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
_PARENTHESIZED_ANSWER_PATTERN = re.compile(r'[\((]\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)\s*[\))]', re.IGNORECASE)
_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE)
_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题')
_FILL_SECTION_PATTERN = re.compile(r'填空(?:题)?|填\s*空')
_ESSAY_SECTION_PATTERN = re.compile(r'问答题|简答题')
_BOOLEAN_SECTION_PATTERN = re.compile(r'判\s*断\s*题?')
_BOOLEAN_SECTION_ANSWER_PATTERN = re.compile(r'判\s*断\s*题\s*[::]?\s*(.*)$')
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s*[、,,.::]?\s*(.+)$')
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
@@ -145,7 +150,7 @@ def _is_answer_sheet_line(line: str) -> bool:
if range_match:
token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3))
expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1
if len(token_matches) >= max(expected_count - 1, 2):
if token_matches:
return True
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
return len(matches) >= 2
@@ -176,6 +181,20 @@ def _extract_answer_sequence(lines: list[str]) -> list[str]:
return answers
def _extract_section_answer_sequence(lines: list[str], section_pattern: re.Pattern[str]) -> list[str]:
"""提取带题型标题的答案行,支持“判断题:1-10、√ ×”这类分节答案表。"""
answers: list[str] = []
for line in lines:
if not section_pattern.search(line) or not _is_answer_sheet_line(line):
continue
range_match = re.search(r'\d{1,3}\s*[-~-—至到]\s*\d{1,3}\s*[、,,.::]?\s*(.*)$', line)
token_text = range_match.group(1) if range_match else line
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(token_text):
answer = _normalize_answer_token(raw_token)
if answer:
answers.append(answer)
return answers
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
"""
从“参考答案”区域提取题号与答案映射。
@@ -196,24 +215,119 @@ def _extract_answer_map(lines: list[str]) -> dict[int, str]:
return answer_map
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
blocks: list[tuple[int, str]] = []
def _section_type_for_line(line: str) -> str | None:
if _FILL_SECTION_PATTERN.search(line):
return 'fill'
if _ESSAY_SECTION_PATTERN.search(line):
return 'essay'
if _BOOLEAN_SECTION_PATTERN.search(line):
return 'boolean'
if re.search(r'选择题|单选题', line):
return 'single'
return None
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
occurrences: dict[str, int] = {}
active_type: str | None = None
answers: dict[str, list[str]] = {'fill': []}
in_answer_sheet = False
for line in lines:
if _is_answer_section_heading(line):
in_answer_sheet = True
active_type = None
continue
section_type = _section_type_for_line(line)
if section_type:
occurrences[section_type] = occurrences.get(section_type, 0) + 1
if occurrences[section_type] > 1:
in_answer_sheet = True
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
continue
if not in_answer_sheet or active_type != 'fill':
continue
match = _QUESTION_START_PATTERN.match(line)
if match:
value = _normalize_spaces(match.group(2))
if value:
answers['fill'].append(value)
return answers
def _format_fill_prompt(prompt: str, standard_answer: str) -> str:
"""把 PDF 中表示填空位置的空白转换为稳定可见的下划线。"""
text = _normalize_spaces(prompt)
if not standard_answer:
return text
answer_parts = [part for part in re.split(r'[、,,;;]+', standard_answer) if part.strip()]
expected = max(1, len(answer_parts))
candidates = list(re.finditer(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff、,,;;。])', text))
if not candidates:
return f"{text} {' '.join('______' for _ in range(expected))}"
positions = {match.start() for match in candidates[:expected]}
result: list[str] = []
last = 0
for match in candidates:
result.append(text[last:match.start()])
result.append(' ______ ' if match.start() in positions else ' ')
last = match.end()
result.append(text[last:])
formatted = _normalize_spaces(''.join(result))
missing_count = expected - formatted.count('______')
if missing_count > 0:
# PDF 文本抽取会丢失部分空白字符;补足占位符,确保学员能看到与标准答案数量一致的填空位置。
formatted = f"{formatted} {' '.join('______' for _ in range(missing_count))}"
return formatted
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]]:
"""
按题号及所属小节切分题目块。
用途:保留“填空题”“判断题”“问答题”小节语义,避免无选项题被当作解析失败而丢弃。
参数约束:仅识别明确的题目小节;未命中时返回 None,后续继续按单选/判断规则判别。
"""
blocks: list[tuple[int, str, str | None]] = []
current_no: int | None = None
current_lines: list[str] = []
current_section_type: str | None = None
section_occurrences: dict[str, int] = {}
for line in lines:
if _SECTION_HEADING_PATTERN.match(line):
if _is_answer_section_heading(line):
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
current_section_type = 'answer_sheet'
continue
section_type = _section_type_for_line(line)
if section_type:
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
section_occurrences[section_type] = section_occurrences.get(section_type, 0) + 1
current_section_type = section_type if section_occurrences[section_type] == 1 else f'answer_{section_type}'
continue
if _is_answer_section_heading(line):
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
current_section_type = 'answer_sheet'
continue
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
continue
if _is_answer_sheet_line(line):
continue
question_match = _QUESTION_START_PATTERN.match(line)
if question_match:
if _is_answer_sheet_line(line) and '答案' not in line:
continue
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = int(question_match.group(1))
current_lines = [question_match.group(2)]
continue
@@ -223,12 +337,22 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
current_lines.append(line)
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
return blocks
def _is_answer_section_heading(line: str) -> bool:
return bool(re.match(r'^(?:参考)?答案(?:解析|及解析)?\s*[::]?$', line))
def _extract_inline_answer(block_text: str) -> str:
match = _INLINE_ANSWER_PATTERN.search(block_text)
"""
从单题文本中提取内联标准答案。
用途:兼容“答案:B”与“(B)”两种常见试卷标注;后者需排除空括号,避免把答题留白误判为答案。
参数约束:仅返回可标准化为单选或判断值的答案,否则返回空字符串。
"""
match = _INLINE_ANSWER_PATTERN.search(block_text) or _PARENTHESIZED_ANSWER_PATTERN.search(block_text)
if not match:
return ''
return _normalize_answer_token(match.group(1))
@@ -257,6 +381,25 @@ def _build_boolean_question(question_no: int, prompt: str, answer: str, explanat
}
def _build_text_question(question_no: int, prompt: str, question_type: str, explanation: str, answer: str = '') -> dict[str, Any] | None:
"""
构造无选项的填空或问答题。
用途:填空题会携带 PDF 答案区提取到的标准答案用于自动判分;问答题没有固定答案时仍按文本长度规则评分。
参数约束:question_type 只能为 fill 或 essay;answer 仅允许来自同一 PDF 的对应填空答案。
"""
prompt_text = _normalize_spaces(prompt)
if not prompt_text or question_type not in {'fill', 'essay'}:
return None
return {
'id': f'q{question_no}',
'type': question_type,
'prompt': prompt_text,
'answer': _normalize_spaces(answer) if question_type == 'fill' else '',
'explanation': explanation,
}
def _build_answer_candidates(
*,
inline_answer: str,
@@ -332,21 +475,59 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
lines = _collect_candidate_lines(text)
answer_map = _extract_answer_map(lines)
answer_sequence = _extract_answer_sequence(lines)
repeated_section_answers = _extract_repeated_section_answers(lines)
question_blocks = _split_question_blocks(lines)
question_bank: list[dict[str, Any]] = []
skipped_questions: list[int] = []
fill_answer_index = 0
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
for index, (question_no, raw_block) in enumerate(question_blocks):
answer_sequence_index = 0
for question_no, raw_block, section_type in question_blocks:
inline_answer = _extract_inline_answer(raw_block)
explanation = _extract_inline_explanation(raw_block)
block_text = _strip_inline_meta(raw_block)
option_matches = list(_OPTION_PATTERN.finditer(block_text))
consumes_answer = section_type not in {'fill', 'essay'}
ordered_answer = answer_sequence[answer_sequence_index] if answer_sequence_index < len(answer_sequence) else ''
if consumes_answer:
answer_sequence_index += 1
answer_candidates = _build_answer_candidates(
inline_answer=inline_answer,
mapped_answer=answer_map.get(question_no, ''),
ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '',
ordered_answer=ordered_answer,
)
if section_type == 'boolean':
for answer in answer_candidates:
question_payload = _build_boolean_question(
question_no=question_no,
prompt=block_text,
answer=answer,
explanation=explanation,
)
if question_payload:
question_payload['id'] = f'q{len(question_bank) + 1}'
question_bank.append(question_payload)
break
else:
question_payload = None
if question_payload:
continue
if section_type in {'fill', 'essay'}:
fill_answer = (
repeated_section_answers['fill'][fill_answer_index]
if section_type == 'fill' and fill_answer_index < len(repeated_section_answers['fill'])
else ''
)
if section_type == 'fill':
fill_answer_index += 1
block_text = _format_fill_prompt(block_text, fill_answer)
question_payload = _build_text_question(question_no, block_text, section_type, explanation, fill_answer)
if question_payload:
question_payload['id'] = f'q{len(question_bank) + 1}'
question_bank.append(question_payload)
continue
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
for answer in answer_candidates:
@@ -103,6 +103,23 @@ def list_document_versions(document_id: int) -> list[KbDocumentVersion]:
return list(document.versions)
def resolve_training_preview_file_path(version_id: int) -> tuple[Path, str]:
"""
解析培训资料的可预览文件路径。
用途:培训配置的资料预览优先返回上传原件;部署环境未保留原件时,回退到清洗后预览文件,避免学习流程因历史文件缺失中断。
参数与输出约束:仅接受有效且未删除的知识库版本;返回存在的绝对路径及下载展示名,不存在任何可用文件时抛出 NotFoundError。
"""
version = load_document_version(version_id)
candidate_paths = (version.source_file_path, version.cleaned_preview_path, version.cleaned_file_path)
for candidate in candidate_paths:
preview_path = resolve_storage_path(candidate)
if preview_path and preview_path.exists() and preview_path.is_file():
filename = version.source_file_name or preview_path.name
return preview_path, filename
raise NotFoundError('培训资料文件不存在或已被移除')
def resolve_source_file_path(version_id: int) -> tuple[Path, str]:
"""
解析版本原始文件路径。
@@ -57,7 +57,7 @@ def _resource_payload(resource: TrainingConfigResource) -> dict[str, Any]:
"version_no": resource.kb_document_version.version_no,
"source_file_name": resource.kb_document_version.source_file_name,
"file_name": resource.kb_document_version.source_file_name,
"file_url": f"/api/kb/document-versions/{resource.kb_document_version.id}/source-file",
"file_url": f"/api/kb/document-versions/{resource.kb_document_version.id}/training-preview-file",
"file_type": resource.kb_document_version.source_file_ext,
"group_name": resource.kb_document_version.document.group.name if resource.kb_document_version.document and resource.kb_document_version.document.group else None,
} if resource.kb_document_version else None
+104 -7
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from io import BytesIO
import re
from typing import Any, Iterable, Optional
from openpyxl import Workbook
@@ -158,6 +159,40 @@ def _normalize_safety_progress(value: Any, safety_stage: str) -> dict[str, Any]:
return normalized
def _is_safety_learning_complete(safety_progress: dict[str, Any], training_type: str) -> bool:
"""
按已发布安全培训配置校验三级资料是否均已完成。
用途:安全培训请求进入考试或结算阶段时,服务端不能信任前端阶段字段,必须以每项配置资料的完成记录为准。
参数约束:仅安全培训生效;未配置资料的级别视为无须学习,所有已配置资料必须在 resource_progress 中标记 completed=True。
"""
if training_type != "safety":
return True
published = get_published_config("safety")
learning_resources = [
resource for resource in (published or {}).get("resources") or []
if resource.get("resource_type") != "inline_questions"
and resource.get("training_level") in SAFETY_LEVEL_KEYS
]
resource_progress = safety_progress.get("resource_progress") or {}
return all(
isinstance(resource_progress.get(str(resource.get("id"))), dict)
and bool(resource_progress[str(resource["id"])].get("completed"))
for resource in learning_resources
)
def _assert_safety_exam_prerequisites(stage: str, safety_progress: dict[str, Any], training_type: str) -> None:
"""
拦截未完成三级学习的安全培训考试与结算请求。
用途:当客户端尝试保存 exam/result 阶段时阻止绕过学习流程,确保考试状态只能在三级资料完成后产生。
参数约束:仅 stage 为 exam 或 result 且 training_type 为 safety 时校验失败并抛出统一 ValidationError。
"""
if training_type == "safety" and stage in {"exam", "result"} and not _is_safety_learning_complete(safety_progress, training_type):
raise ValidationError("Complete all company, department, and team safety training materials before starting or submitting the exam")
def _parse_iso_date(value: Any) -> Optional[date]:
text = str(value or "").strip()
if not text:
@@ -184,7 +219,9 @@ def _normalize_answer_details(value: Any) -> list[dict]:
{
"question_id": str(item.get("question_id") or item.get("questionId") or ""),
"selected_option_id": str(item.get("selected_option_id") or item.get("selectedOptionId") or ""),
"answer_text": str(item.get("answer_text") or item.get("answerText") or ""),
"correct": bool(item.get("correct", False)),
"score_ratio": float(item.get("score_ratio") or item.get("scoreRatio") or 0),
}
)
return normalized
@@ -217,8 +254,36 @@ def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
prompt = str(raw.get("prompt") or "").strip()
answer = str(raw.get("answer") or "").strip()
question_id = str(raw.get("id") or "").strip() or f"q{index + 1}"
if not prompt or not answer:
question_type = str(raw.get("type") or "single").strip().lower()
question_type = {
"choice": "single",
"select": "single",
"bool": "boolean",
"judgment": "boolean",
"judge": "boolean",
"判断": "boolean",
"判断题": "boolean",
"3": "boolean",
"blank": "fill",
"fill_blank": "fill",
"qa": "essay",
"question_answer": "essay",
"short_answer": "essay",
"问答": "essay",
"问答题": "essay",
"简答": "essay",
"简答题": "essay",
"4": "essay",
}.get(question_type, question_type)
if question_type not in {"single", "boolean", "fill", "essay"} or not prompt:
continue
if question_type in {"single", "boolean"} and not answer:
continue
try:
score_ratio = float(raw.get("score_ratio") or raw.get("scoreRatio") or 1)
except (TypeError, ValueError):
score_ratio = 1.0
score_ratio = max(0.0, score_ratio)
options: list[dict[str, str]] = []
raw_options = raw.get("options")
@@ -244,9 +309,10 @@ def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
normalized.append(
{
"id": question_id,
"type": "boolean" if str(raw.get("type") or "").strip() == "boolean" else "single",
"type": question_type,
"prompt": prompt,
"answer": answer,
"score_ratio": score_ratio,
"options": options,
"explanation": str(raw.get("explanation") or "").strip(),
}
@@ -302,6 +368,19 @@ def _resolve_training_runtime_config(agent_id: Any, training_type: str) -> tuple
return pass_score, question_bank
def _normalize_text_answer(value: Any) -> str:
"""
规范文本题答案以进行无格式差异的自动判定。
用途:填空和问答题有标准答案时忽略空白与大小写,避免录入格式造成误判。
Args:
value: 学员作答或题库标准答案。
Returns:
删除全部空白并转换为小写后的文本。
"""
return re.sub(r"[\s\u3000、,,;;。..!!??::()()【】\[\]{}\"'“”‘’\-—_]+", "", str(value or "")).casefold()
def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[str, Any]], pass_score: int) -> tuple[list[dict], int, bool]:
"""
基于后端题库对答题记录重新判卷。
@@ -318,27 +397,44 @@ def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[s
question_lookup = {str(item["id"]): item for item in question_bank}
normalized: list[dict] = []
correct_count = 0
total_score_ratio = sum(float(question.get("score_ratio") or 0) for question in question_bank)
earned_score_ratio = 0.0
for index, item in enumerate(answer_details):
question_id = str(item.get("question_id") or item.get("questionId") or "").strip()
selected_option_id = str(item.get("selected_option_id") or item.get("selectedOptionId") or "").strip()
answer_text = str(item.get("answer_text") or item.get("answerText") or "")
if not question_id:
raise ValidationError("answer_details item must include question_id", details={"field": "answer_details", "index": index})
question = question_lookup.get(question_id)
if not question:
raise ValidationError("answer_details question_id is invalid", details={"field": "answer_details", "index": index, "question_id": question_id})
is_correct = selected_option_id == str(question["answer"])
if is_correct:
correct_count += 1
question_type = str(question["type"])
if question_type in {"fill", "essay"}:
normalized_answer = _normalize_text_answer(answer_text)
normalized_standard_answer = _normalize_text_answer(question["answer"])
if normalized_standard_answer:
earned_ratio = 1.0 if normalized_answer == normalized_standard_answer else 0.0
elif not normalized_answer:
earned_ratio = 0.0
else:
earned_ratio = 1.0 if len(answer_text.strip()) > 20 else 0.8
is_correct = earned_ratio == 1.0
else:
earned_ratio = 1.0 if selected_option_id == str(question["answer"]) else 0.0
is_correct = bool(earned_ratio)
question_score_ratio = float(question.get("score_ratio") or 0)
earned_score_ratio += question_score_ratio * earned_ratio
normalized.append(
{
"question_id": question_id,
"selected_option_id": selected_option_id,
"answer_text": answer_text,
"correct": is_correct,
"score_ratio": earned_ratio,
}
)
score = round((correct_count / len(question_bank)) * 100) if question_bank else 0
score = round((earned_score_ratio / total_score_ratio) * 100) if total_score_ratio > 0 else 0
return normalized, score, score >= pass_score
@@ -441,6 +537,7 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
payload.get("safety_progress") or payload.get("safetyProgress"),
safety_stage,
)
_assert_safety_exam_prerequisites(stage, safety_progress, training_type)
record = get_user_training_record(user.id, training_type)
if not record:
@@ -32,6 +32,21 @@ def test_parse_training_question_bank_text_supports_inline_answers():
assert payload['question_bank'][0]['explanation'] == '工资固定在每月15号发放。'
def test_parse_training_question_bank_text_supports_parenthesized_inline_answers():
"""断言题干末尾的括号答案可被识别,避免格式差异导致整卷题库为空。"""
text = """
一、选择题
1、发生火灾时应第一时间拨打哪个号码? A、110 B、119 C、120 D、122 (B)
2、个人防护用品由谁提供? A、员工自费 B、公司免费提供 C、客户提供 (B)
"""
payload = parse_training_question_bank_text(text)
# 关键断言:括号中的标准答案应与对应选项匹配并完整生成两道单选题。
assert payload['parsed_count'] == 2
assert [item['answer'] for item in payload['question_bank']] == ['b', 'b']
def test_parse_training_question_bank_text_supports_answer_sheet_mapping():
text = """
1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122
@@ -124,6 +139,73 @@ def test_parse_training_question_bank_text_supports_boolean_range_answer_sheet()
assert [item['answer'] for item in payload['question_bank']] == ['c', 'b', 'true', 'true', 'false']
def test_parse_training_question_bank_text_supports_fill_and_essay_sections_without_answers():
"""关键断言:填空题和问答题即使没有标准答案也必须保留,供服务端按文本作答规则判卷。"""
text = """
三、填空题(1-10)
1. 公司安全生产方针是:______。
2. 发生火灾时应拨打______。
四、问答题
1. 请说明发现安全隐患后的处理流程。
"""
payload = parse_training_question_bank_text(text)
assert payload['parsed_count'] == 3
assert [item['type'] for item in payload['question_bank']] == ['fill', 'fill', 'essay']
assert [item['answer'] for item in payload['question_bank']] == ['', '', '']
def test_parse_training_question_bank_text_supports_boolean_section_and_answer_range_with_delimiter():
"""关键断言:带“判断题”小节和“1-10、√”答案表时,判断题不得被填空区吞掉或跳过。"""
text = """
一、填空:(每题3分)
1、公司安全生产方针是:______。
二、判断题:(每题2分)
1、“预防为主”就是把安全工作的重点从事后处理转变为事前预防。()
2、安全生产管理是企业管理人员的事,跟普通工人无关。()
三、问答题
1、简要叙述下你所在岗位的安全风险?
参考答案:
一、填空:1、厂级(公司级)、车间级、班组级
二、判断题:1-2、√ ×
"""
payload = parse_training_question_bank_text(text)
assert [item['type'] for item in payload['question_bank']] == ['fill', 'boolean', 'boolean', 'essay']
assert [item['answer'] for item in payload['question_bank'][1:3]] == ['true', 'false']
def test_parse_training_question_bank_text_preserves_fill_answers_and_ignores_repeated_answer_section():
"""关键断言:填空答案区不能变成新题,且标准答案必须回填到题库用于前后端判分。"""
text = """
一、填空题
1、三级教育是指 、 、 。
2、操作牌是设备操作的 。
二、判断题
1、安全生产人人有责。()
三、问答题
1、说明岗位安全风险。
参考答案:
一、填空题
1、公司级、车间级、班组级
2、唯一凭证
二、判断题
1、√
"""
payload = parse_training_question_bank_text(text)
assert [item['type'] for item in payload['question_bank']] == ['fill', 'fill', 'boolean', 'essay']
assert [item['answer'] for item in payload['question_bank'][:2]] == ['公司级、车间级、班组级', '唯一凭证']
assert [item['prompt'].count('______') for item in payload['question_bank'][:2]] == [3, 1]
def test_parse_training_question_bank_text_raises_when_no_usable_questions():
with pytest.raises(ValidationError, match='未能从试题 PDF 中识别出可用题目'):
parse_training_question_bank_text('这是一份扫描件占位文本,没有题号也没有答案。')
+72
View File
@@ -12,9 +12,13 @@ from datetime import date, datetime
from io import BytesIO
from openpyxl import load_workbook
import pytest
from app import db
from app.core.errors import ValidationError
from app.models import Agent, TrainingRecord, User
from app.services import training_service
from app.services.training_service import _grade_answer_details, _normalize_question_bank
def _create_user(
@@ -120,6 +124,35 @@ def _auth_headers(user: User) -> dict[str, str]:
}
def test_normalize_question_bank_accepts_judgment_and_qa_aliases():
"""关键断言:题库历史类型别名必须映射为员工端可渲染、服务端可判卷的标准题型。"""
question_bank = _normalize_question_bank([
{"id": "q1", "type": "judgment", "prompt": "安全帽必须正确佩戴。", "answer": "true"},
{"id": "q2", "type": "问答题", "prompt": "请说明发现隐患后的处理流程。", "answer": ""},
])
assert [item["type"] for item in question_bank] == ["boolean", "essay"]
def test_training_text_questions_apply_standard_answer_and_unanswered_scoring_rules():
"""关键断言:文本题标准答案忽略空白与大小写;无答案题按非空 80%、超过 20 字 100% 判分。"""
question_bank = _normalize_question_bank([
{"id": "q1", "type": "fill", "prompt": "填写系统名称", "answer": "OA 系统"},
{"id": "q2", "type": "essay", "prompt": "说明安全要求", "answer": "", "score_ratio": 2},
{"id": "q3", "type": "fill", "prompt": "填写电话", "answer": "", "score_ratio": 1},
])
details, score, passed = _grade_answer_details([
{"question_id": "q1", "answer_text": " oa系统 "},
{"question_id": "q2", "answer_text": "发现安全隐患后应立即停止作业并报告负责人,确认整改完成后再恢复作业。"},
{"question_id": "q3", "answer_text": "119"},
], question_bank, 90)
assert [item["score_ratio"] for item in details] == [1.0, 1.0, 0.8]
assert score == 95
assert passed is True
def test_training_user_progress_round_trip_and_completion(client, app):
"""员工侧培训进度应支持空记录读取、过程保存、结果结算与再次读取回显。"""
with app.app_context():
@@ -260,6 +293,45 @@ def test_safety_training_progress_round_trip(client, app):
}
def test_safety_exam_requires_all_configured_learning_resources(monkeypatch):
"""断言安全培训缺少任一级资料完成记录时,后端拒绝直接进入考试或结算。"""
monkeypatch.setattr(
training_service,
"get_published_config",
lambda _training_type: {
"resources": [
{"id": 11, "resource_type": "agent_guide", "training_level": "company"},
{"id": 12, "resource_type": "kb_document_version", "training_level": "department"},
{"id": 13, "resource_type": "kb_document_version", "training_level": "team"},
],
},
)
progress = {"resource_progress": {"11": {"completed": True}, "12": {"completed": False}}}
# 关键断言:客户端伪造 exam 阶段不能跳过班组级学习资料。
with pytest.raises(ValidationError):
training_service._assert_safety_exam_prerequisites("exam", progress, "safety")
def test_safety_exam_accepts_all_configured_learning_resources(monkeypatch):
"""断言三级配置资料均完成时,后端允许安全培训进入考试阶段。"""
monkeypatch.setattr(
training_service,
"get_published_config",
lambda _training_type: {
"resources": [
{"id": 11, "resource_type": "agent_guide", "training_level": "company"},
{"id": 12, "resource_type": "kb_document_version", "training_level": "department"},
{"id": 13, "resource_type": "kb_document_version", "training_level": "team"},
],
},
)
progress = {"resource_progress": {str(resource_id): {"completed": True} for resource_id in (11, 12, 13)}}
# 关键断言:所有已配置资料完成后,不阻断正常开考。
training_service._assert_safety_exam_prerequisites("exam", progress, "safety")
def test_training_result_is_graded_by_server_question_bank(client, app):
"""服务端应基于 Agent 题库重算分数与通过状态,不能信任前端伪造结果。"""
with app.app_context():
+1 -1
View File
@@ -409,7 +409,7 @@ export const listAdminTrainingResourceCandidates = () =>
requestJson<TrainingResourceCandidates>('/api/admin/training-configs/resource-candidates', auth());
export interface TrainingQuestionBankParseResult {
question_bank: unknown[];
question_bank: Array<{ type?: string; [key: string]: unknown }>;
parsed_count: number;
skipped_question_numbers: number[];
kb_document_version_id: number;
@@ -141,11 +141,33 @@ const parseQuestionBank = async () => {
}
isParsingQuestions.value = true;
try {
// #region debug-point A:training-question-parse-click
fetch('http://127.0.0.1:7788/event', { method: 'POST', body: JSON.stringify({ sessionId: 'training-pdf-question-import', runId: 'pre-fix', hypothesisId: 'A', location: 'TrainingConfigPage.vue:144', msg: '[DEBUG] Training PDF parse requested', data: { versionId: questionSourceVersionId.value }, ts: Date.now() }) }).catch(() => {});
// #endregion
const result = await parseAdminTrainingQuestionBank(questionSourceVersionId.value);
// #region debug-point B:training-question-parse-result
fetch('http://127.0.0.1:7788/event', { method: 'POST', body: JSON.stringify({ sessionId: 'training-pdf-question-import', runId: 'pre-fix', hypothesisId: 'B', location: 'TrainingConfigPage.vue:149', msg: '[DEBUG] Training PDF parse succeeded', data: { versionId: questionSourceVersionId.value, parsedCount: result.parsed_count, mode: result.extraction_mode, skipped: result.skipped_question_numbers }, ts: Date.now() }) }).catch(() => {});
// #endregion
// #region debug-point type-import-result
fetch('http://127.0.0.1:7789/event', { method: 'POST', body: JSON.stringify({ sessionId: 'training-question-type-import', runId: 'pre-fix', hypothesisId: 'A', location: 'TrainingConfigPage.vue:151', msg: '[DEBUG] Training question types parsed', data: { versionId: questionSourceVersionId.value, parsedCount: result.parsed_count, skipped: result.skipped_question_numbers, types: result.question_bank.map((question) => question.type) }, ts: Date.now() }) }).catch(() => {});
// #endregion
const activeDocumentVersionIds = new Set(candidates.value.documents.map((document) => document.id));
questionJsonText.value = JSON.stringify(result.question_bank, null, 2);
// 题库由当前清洗后 PDF 解析;将配置中已失效的旧文档引用替换为该有效版本,避免保存时被后端 current/active 校验拒绝。
questionSourceVersionId.value = result.kb_document_version_id;
form.value.resources = form.value.resources.map((resource) => (
resource.resource_type === 'kb_document_version'
&& resource.kb_document_version_id
&& !activeDocumentVersionIds.has(resource.kb_document_version_id)
? { ...resource, kb_document_version_id: result.kb_document_version_id }
: resource
));
questionParseMeta.value = { mode: result.extraction_mode, fileName: result.source_file_name, skipped: result.skipped_question_numbers };
msg.success(t('admin.trainingConfig.messages.parseSuccess', { count: result.parsed_count }));
} catch (error) {
// #region debug-point C:training-question-parse-error
fetch('http://127.0.0.1:7788/event', { method: 'POST', body: JSON.stringify({ sessionId: 'training-pdf-question-import', runId: 'pre-fix', hypothesisId: 'C', location: 'TrainingConfigPage.vue:156', msg: '[DEBUG] Training PDF parse failed', data: { versionId: questionSourceVersionId.value, error: error instanceof Error ? error.message : String(error) }, ts: Date.now() }) }).catch(() => {});
// #endregion
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.parseFailed'));
} finally {
isParsingQuestions.value = false;
@@ -262,6 +284,9 @@ const saveConfig = async () => {
}
isSaving.value = true;
try {
// #region debug-point training-config-save-payload
fetch('http://127.0.0.1:7790/event', { method: 'POST', body: JSON.stringify({ sessionId: 'training-config-save-validation', runId: 'pre-fix', hypothesisId: 'A', location: 'TrainingConfigPage.vue:277', msg: '[DEBUG] Training config save requested', data: { configId: selected.value.id, resources: form.value.resources.map((resource) => ({ type: resource.resource_type, guideId: resource.agent_guide_id || null, versionId: resource.kb_document_version_id || null, level: resource.training_level || null })) }, ts: Date.now() }) }).catch(() => {});
// #endregion
const saved = await updateAdminTrainingConfig(selected.value.id, form.value);
await load();
selectConfig(saved);
@@ -38,7 +38,9 @@ type TrainingRecordApi = {
answer_details?: Array<{
question_id?: string;
selected_option_id?: string;
answer_text?: string;
correct?: boolean;
score_ratio?: number;
}>;
completion_time?: string | null;
updated_at?: string | null;
@@ -122,7 +124,9 @@ function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): Training
? items.map((item) => ({
questionId: String(item.question_id || ''),
selectedOptionId: String(item.selected_option_id || ''),
answerText: String(item.answer_text || ''),
correct: Boolean(item.correct),
scoreRatio: Number(item.score_ratio || 0),
}))
: [];
}
@@ -249,7 +253,9 @@ export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayloa
answer_details: payload.answerDetails.map((item) => ({
question_id: item.questionId,
selected_option_id: item.selectedOptionId,
answer_text: item.answerText || '',
correct: item.correct,
score_ratio: item.scoreRatio || 0,
})),
join_date: payload.joinDate || undefined,
}),
@@ -216,9 +216,16 @@ const expandCurrentWorkspace = () => {
const currentAnswerLabel = computed(() => {
const question = workspace.currentQuestion;
if (!question) return '';
if (question.type === 'fill' || question.type === 'essay') return workspace.answerText;
return question.options?.find((item) => item.id === workspace.selectedOptionId)?.label || '';
});
const isTextQuestion = computed(() => ['fill', 'essay'].includes(workspace.currentQuestion?.type || ''));
const isTextFeedbackPending = computed(() => (
workspace.currentQuestion?.type === 'essay'
|| (workspace.currentQuestion?.type === 'fill' && !workspace.currentQuestion.answer)
));
const trainingExamPdfGuide = computed(() => resolveTrainingExamPdfGuide(props.agentGuides));
const workspaceExpanded = ref(false);
@@ -747,7 +754,25 @@ const currentSafetyStageText = computed(() => {
</div>
</div>
<div class="mt-2.5 grid gap-2">
<div v-if="isTextQuestion" class="mt-2.5 grid gap-2">
<textarea
v-model="workspace.answerText"
:disabled="workspace.currentQuestion.type === 'essay' && workspace.answerLocked"
:rows="workspace.currentQuestion.type === 'essay' ? 5 : 3"
class="w-full rounded-2xl border border-default bg-white px-3.5 py-2 text-sm leading-6 text-primary outline-none transition focus:border-brand-400 focus:ring-2 focus:ring-brand-100 disabled:bg-surface-soft"
:placeholder="$t(workspace.currentQuestion.type === 'essay' ? 'chat.training.exam.essayPlaceholder' : 'chat.training.exam.fillPlaceholder')"
/>
<button
v-if="!workspace.answerLocked"
type="button"
:disabled="!workspace.answerText.trim()"
class="justify-self-start rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-50"
@click="workspace.submitTextAnswer()"
>
{{ $t('chat.training.exam.submitTextAnswer') }}
</button>
</div>
<div v-else class="mt-2.5 grid gap-2">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
@@ -776,20 +801,25 @@ const currentSafetyStageText = computed(() => {
</button>
</div>
<div
v-if="workspace.answerLocked"
class="mt-3 rounded-2xl border p-3"
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="workspace.currentFeedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div
v-if="workspace.answerLocked"
class="mt-3 rounded-2xl border p-3"
:class="isTextFeedbackPending || workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="isTextFeedbackPending || workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'"">
<CheckCircle2 v-if="isTextFeedbackPending || workspace.currentFeedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ isTextFeedbackPending ? $t('chat.training.exam.textAnswerRecorded') : workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.selectedAnswer', { answer: currentAnswerLabel || '--' }) }}
</div>
<div class="mt-1 text-sm leading-6 text-secondary">
<div v-if="isTextQuestion" class="mt-1 text-sm leading-6 text-secondary">
{{ workspace.currentQuestion.type === 'fill' && workspace.currentQuestion.answer
? $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.answer })
: $t('chat.training.exam.textAnswerRecorded') }}
</div>
<div v-else class="mt-1 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.options?.find((item) => item.id === workspace.currentQuestion?.answer)?.label || '--' }) }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
@@ -1056,7 +1086,25 @@ const currentSafetyStageText = computed(() => {
</div>
</div>
<div class="mt-2.5 grid gap-2">
<div v-if="isTextQuestion" class="mt-2.5 grid gap-2">
<textarea
v-model="workspace.answerText"
:disabled="workspace.currentQuestion.type === 'essay' && workspace.answerLocked"
:rows="workspace.currentQuestion.type === 'essay' ? 5 : 3"
class="w-full rounded-2xl border border-default bg-white px-3.5 py-2 text-sm leading-6 text-primary outline-none transition focus:border-brand-400 focus:ring-2 focus:ring-brand-100 disabled:bg-surface-soft"
:placeholder="$t(workspace.currentQuestion.type === 'essay' ? 'chat.training.exam.essayPlaceholder' : 'chat.training.exam.fillPlaceholder')"
/>
<button
v-if="workspace.currentQuestion.type === 'fill' || !workspace.answerLocked"
type="button"
:disabled="!workspace.answerText.trim()"
class="justify-self-start rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-50"
@click="workspace.submitTextAnswer()"
>
{{ $t('chat.training.exam.submitTextAnswer') }}
</button>
</div>
<div v-else class="mt-2.5 grid gap-2">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
@@ -1088,17 +1136,22 @@ const currentSafetyStageText = computed(() => {
<div
v-if="workspace.answerLocked"
class="mt-3 rounded-2xl border p-3"
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
:class="isTextFeedbackPending || workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="workspace.currentFeedbackCorrect" class="h-4 w-4" />
<div class="flex items-center gap-2 text-sm font-semibold" :class="isTextFeedbackPending || workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'"">
<CheckCircle2 v-if="isTextFeedbackPending || workspace.currentFeedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
{{ isTextFeedbackPending ? $t('chat.training.exam.textAnswerRecorded') : workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.selectedAnswer', { answer: currentAnswerLabel || '--' }) }}
</div>
<div class="mt-1 text-sm leading-6 text-secondary">
<div v-if="isTextQuestion" class="mt-1 text-sm leading-6 text-secondary">
{{ workspace.currentQuestion.type === 'fill' && workspace.currentQuestion.answer
? $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.answer })
: $t('chat.training.exam.textAnswerRecorded') }}
</div>
<div v-else class="mt-1 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.options?.find((item) => item.id === workspace.currentQuestion?.answer)?.label || '--' }) }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
@@ -84,6 +84,15 @@ const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount:
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
};
/**
* 规范填空题文本以便与题库标准答案进行即时比对。
* 用途:忽略作答中的空格和大小写,避免 PDF 文本换行或录入格式导致本应正确的填空题被误判。
*/
const normalizeTextAnswer = (value: string) => value
.normalize('NFKC')
.replace(/[\s\u3000、,,;;。..!!??::()()【】\[\]{}"'“”‘’\-—_]+/g, '')
.toLocaleLowerCase();
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const { currentAgent, currentUser, currentGuides } = options;
const { t, tm } = useI18n();
@@ -114,6 +123,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const score = ref(0);
const attemptCount = ref(0);
const selectedOptionId = ref('');
const answerText = ref('');
const answerLocked = ref(false);
const currentFeedbackCorrect = ref(false);
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
@@ -203,6 +213,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
type,
prompt: String(item.prompt || ''),
answer: String(item.answer || ''),
scoreRatio: Number(item.score_ratio || item.scoreRatio || 1),
explanation: String(item.explanation || ''),
options,
};
@@ -293,6 +304,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
};
/**
* 校验三级安全培训资料是否已全部完成。
* 用途:在员工端进入或提交安全考试前提供即时拦截;服务端仍会使用同一资源完成事实做最终校验。
*/
const isSafetyLearningComplete = () => (
isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team')
);
const safetyStepItems = computed(() => {
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
@@ -358,6 +377,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentQuestionIndex.value = 0;
score.value = 0;
selectedOptionId.value = '';
answerText.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
latestExamFeedback.value = null;
@@ -450,8 +470,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
? answerRecords.value.find((item) => item.questionId === questionId)
: null;
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
answerText.value = currentAnswer?.answerText || '';
answerLocked.value = Boolean(currentAnswer);
currentFeedbackCorrect.value = Boolean(currentAnswer?.correct);
currentFeedbackCorrect.value = currentQuestion.value?.type === 'fill' && currentQuestion.value.answer && currentAnswer?.answerText
? normalizeTextAnswer(currentAnswer.answerText) === normalizeTextAnswer(currentQuestion.value.answer)
: Boolean(currentAnswer?.correct);
};
/**
@@ -499,6 +522,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
*/
const enterSafetyExam = () => {
if (!isSafetyLearningComplete()) {
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
return;
}
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
@@ -609,6 +636,8 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
score.value = Number(saved.score || 0);
answerRecords.value = saved.answerDetails;
if (isAdminViewer.value) {
void loadAdminRecords();
}
@@ -796,7 +825,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
* AI 触发时机:当员工在逐题考试阶段点击右侧题号返回某题时,需要允许直接改答且不破坏“提交答卷后才结算”的流程。
*/
const selectAnswer = (optionId: string) => {
if (!currentQuestion.value) return;
if (!currentQuestion.value || currentQuestion.value.type === 'fill' || currentQuestion.value.type === 'essay') return;
const answeredQuestion = currentQuestion.value;
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
selectedOptionId.value = optionId;
@@ -830,6 +859,40 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
void persistProgress();
};
/**
* 提交填空或问答题的文本作答。
* 核心逻辑:文本题由服务端以题库标准答案或无标准答案的字数规则最终判卷;前端仅保存非空文本并推进。
* @returns 无有效文本时不记录,否则更新当前题作答并保持既有逐题推进行为。
*/
const submitTextAnswer = () => {
if (!currentQuestion.value || !['fill', 'essay'].includes(currentQuestion.value.type)) return;
const answeredQuestion = currentQuestion.value;
const text = answerText.value.trim();
if (!text) return;
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
const answerRecord: TrainingAnswerRecord = {
questionId: answeredQuestion.id,
selectedOptionId: '',
answerText: text,
correct: answeredQuestion.type === 'fill' && answeredQuestion.answer
? normalizeTextAnswer(text) === normalizeTextAnswer(answeredQuestion.answer)
: false,
scoreRatio: 0,
};
answerLocked.value = true;
upsertAnswerRecord(answerRecord);
const nextScore = recalculateScoreFromAnswers(answerRecords.value);
score.value = nextScore;
currentFeedbackCorrect.value = answerRecord.correct;
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
if (hadExistingAnswer || currentQuestionIndex.value >= totalQuestionCount.value - 1) {
void persistProgress();
return;
}
syncExamQuestionIndex(currentQuestionIndex.value + 1);
void persistProgress();
};
/**
* 进入下一题或结束考试。
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
@@ -850,6 +913,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
*/
const submitExam = () => {
if (!examReadyToSubmit.value) return;
if (learnerTab.value === 'safety' && !isSafetyLearningComplete()) {
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
return;
}
stage.value = 'result';
if (learnerTab.value === 'safety') {
safetyStage.value = 'result';
@@ -1077,6 +1144,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
score,
attemptCount,
selectedOptionId,
answerText,
answerLocked,
currentFeedbackCorrect,
examReadyToSubmit,
@@ -1109,6 +1177,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
markVideoCompleted,
startExam,
selectAnswer,
submitTextAnswer,
syncExamQuestionIndex,
moveToNextQuestion,
submitExam,
@@ -15,7 +15,7 @@ export type SafetyStage = 'company' | 'department' | 'team' | 'exam' | 'result';
export type TrainingWorkspaceView = 'learner' | 'admin';
export type TrainingQuestionType = 'single' | 'boolean';
export type TrainingQuestionType = 'single' | 'boolean' | 'fill' | 'essay';
export interface TrainingQuestionOption {
id: string;
@@ -27,6 +27,7 @@ export interface TrainingQuestion {
type: TrainingQuestionType;
prompt: string;
answer: string;
scoreRatio?: number;
explanation: string;
options?: TrainingQuestionOption[];
}
@@ -68,7 +69,9 @@ export interface TrainingPublishedConfig {
export interface TrainingAnswerRecord {
questionId: string;
selectedOptionId: string;
answerText?: string;
correct: boolean;
scoreRatio?: number;
}
export interface TrainingExamTransitionFeedback {
@@ -99,12 +99,39 @@ const normalizeQuestionBank = (
return value
.map((item, index): TrainingQuestion | null => {
const raw = asRecord(item);
const type: TrainingQuestion['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
const rawType = String(raw.type || 'single').trim().toLowerCase();
const typeAliases: Record<string, TrainingQuestion['type']> = {
single: 'single',
choice: 'single',
select: 'single',
boolean: 'boolean',
bool: 'boolean',
judgment: 'boolean',
judge: 'boolean',
'判断': 'boolean',
'判断题': 'boolean',
'3': 'boolean',
true_false: 'boolean',
truefalse: 'boolean',
fill: 'fill',
blank: 'fill',
fill_blank: 'fill',
essay: 'essay',
qa: 'essay',
'问答': 'essay',
'问答题': 'essay',
'简答': 'essay',
'简答题': 'essay',
'4': 'essay',
question_answer: 'essay',
short_answer: 'essay',
};
const type = typeAliases[rawType] || 'single';
const prompt = String(raw.prompt || '').trim();
if (!prompt) return null;
const options = type === 'boolean'
? booleanOptions
: normalizeQuestionOptionList(raw.options);
: type === 'single' ? normalizeQuestionOptionList(raw.options) : [];
if (type === 'single' && options.length < 2) return null;
const fallbackAnswer = type === 'boolean'
? 'true'
@@ -115,7 +142,8 @@ const normalizeQuestionBank = (
id: String(raw.id || '').trim() || `q${index + 1}`,
type,
prompt,
answer: optionIds.includes(answer) ? answer : fallbackAnswer,
answer: type === 'fill' || type === 'essay' ? answer : optionIds.includes(answer) ? answer : fallbackAnswer,
scoreRatio: Number(raw.score_ratio || raw.scoreRatio || 1),
explanation: String(raw.explanation || '').trim(),
options,
};
@@ -369,8 +369,14 @@ export function useKbWorkspaceDocuments(
};
const handleSyncDocument = async (documentId: number) => {
// #region debug-point A:sync-click
fetch('http://127.0.0.1:7787/event', { method: 'POST', body: JSON.stringify({ sessionId: 'knowledge-base-dify-sync', runId: 'pre-fix', hypothesisId: 'A', location: 'useKbWorkspaceDocuments.ts:371', msg: '[DEBUG] Dify sync click received', data: { documentId }, ts: Date.now() }) }).catch(() => {});
// #endregion
syncingDocumentId.value = documentId;
const result = await syncKbDocumentToDify(documentId);
// #region debug-point B:sync-response
fetch('http://127.0.0.1:7787/event', { method: 'POST', body: JSON.stringify({ sessionId: 'knowledge-base-dify-sync', runId: 'pre-fix', hypothesisId: 'B', location: 'useKbWorkspaceDocuments.ts:376', msg: '[DEBUG] Dify sync API response received', data: { documentId, ok: result.ok, error: result.error || null, jobId: result.job?.id || null, message: result.job?.message || null }, ts: Date.now() }) }).catch(() => {});
// #endregion
syncingDocumentId.value = null;
if (!result.ok) {
+6 -1
View File
@@ -1074,6 +1074,10 @@
"correctAnswer": "Correct answer: {answer}",
"nextQuestion": "Next Question",
"submitPaper": "Submit Paper",
"fillPlaceholder": "Enter your fill-in answer",
"essayPlaceholder": "Enter your response",
"submitTextAnswer": "Submit Answer",
"textAnswerRecorded": "Answer recorded; it will be graded when you submit the paper",
"finishExam": "Finish Exam"
},
"result": {
@@ -1179,7 +1183,8 @@
"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."
"questionBankEmpty": "The training question bank is empty. Please maintain it first in the Agent configuration.",
"safetyLearningIncomplete": "Please complete all company-level, department-level, and team-level training materials before taking the exam."
},
"summaryPoints": [
"Salary is paid on the 15th of each month, and attendance or leave requests must go through OA.",
+6 -1
View File
@@ -1074,6 +1074,10 @@
"correctAnswer": "คำตอบที่ถูกต้อง: {answer}",
"nextQuestion": "ข้อถัดไป",
"submitPaper": "ส่งข้อสอบ",
"fillPlaceholder": "กรอกคำตอบเติมคำ",
"essayPlaceholder": "กรอกคำตอบของคุณ",
"submitTextAnswer": "ส่งคำตอบ",
"textAnswerRecorded": "บันทึกคำตอบแล้ว ระบบจะตรวจเมื่อส่งข้อสอบ",
"finishExam": "จบการสอบ"
},
"result": {
@@ -1179,7 +1183,8 @@
"persistBody": "ผลสอบปัจจุบันยังไม่ได้เขียนลงฐานข้อมูล ดังนั้นหน้าจอ HR และสถิติจะไม่อัปเดต",
"loadTitle": "โหลดประวัติการอบรมไม่สำเร็จ",
"loadBody": "ไม่สามารถอ่านประวัติการอบรมจากฐานข้อมูลได้ในขณะนี้ ดังนั้นหน้าปัจจุบันอาจไม่ใช่ผลล่าสุด",
"questionBankEmpty": "คลังข้อสอบการอบรมว่างอยู่ โปรดตั้งค่าใน Agent configuration ก่อน"
"questionBankEmpty": "คลังข้อสอบการอบรมว่างอยู่ โปรดตั้งค่าใน Agent configuration ก่อน",
"safetyLearningIncomplete": "โปรดเรียนเนื้อหาการฝึกอบรมระดับบริษัท ระดับแผนก และระดับทีมให้ครบถ้วนก่อนเข้าสอบ"
},
"summaryPoints": [
"เงินเดือนจ่ายทุกวันที่ 15 ของเดือน และการลาหรือการลงเวลาต้องทำผ่าน OA",
+6 -1
View File
@@ -1108,6 +1108,10 @@
"correctAnswer": "正确答案:{answer}",
"nextQuestion": "下一题",
"submitPaper": "提交答卷",
"fillPlaceholder": "请输入填空答案",
"essayPlaceholder": "请输入您的回答",
"submitTextAnswer": "提交作答",
"textAnswerRecorded": "作答已记录,提交答卷后自动评分",
"finishExam": "完成考试"
},
"result": {
@@ -1286,7 +1290,8 @@
"persistBody": "当前考试结果尚未写入数据库,HR 管理与统计不会更新",
"loadTitle": "培训记录读取失败",
"loadBody": "当前无法从数据库读取培训记录,页面展示可能不是最新结果",
"questionBankEmpty": "当前培训题库为空,请先在后台 Agent 配置中维护题库"
"questionBankEmpty": "当前培训题库为空,请先在后台 Agent 配置中维护题库",
"safetyLearningIncomplete": "请先完成公司级、部门级和班组级全部培训资料,再进入考试"
},
"summaryPoints": [
"工资每月 15 号发放,考勤与请假均需要走 OA 流程。",
+6 -1
View File
@@ -1074,6 +1074,10 @@
"correctAnswer": "正確答案:{answer}",
"nextQuestion": "下一題",
"submitPaper": "提交答卷",
"fillPlaceholder": "請輸入填空答案",
"essayPlaceholder": "請輸入您的回答",
"submitTextAnswer": "提交作答",
"textAnswerRecorded": "作答已記錄,提交答卷後自動評分",
"finishExam": "完成考試"
},
"result": {
@@ -1179,7 +1183,8 @@
"persistBody": "當前考試結果尚未寫入資料庫,HR 管理與統計不會更新",
"loadTitle": "培訓記錄讀取失敗",
"loadBody": "目前無法從資料庫讀取培訓記錄,頁面顯示可能不是最新結果",
"questionBankEmpty": "當前培訓題庫為空,請先在後台 Agent 配置中維護題庫"
"questionBankEmpty": "當前培訓題庫為空,請先在後台 Agent 配置中維護題庫",
"safetyLearningIncomplete": "請先完成公司級、部門級和班組級的全部培訓資料,再進入考試"
},
"summaryPoints": [
"工資每月 15 號發放,考勤與請假均需走 OA 流程。",