feat: improve student training tasks and PDF export

bugfix/ai-assessment-evidence-rescore
chenyuan 3 months ago
parent 6bba6e9359
commit 43b48f6d6c

@ -548,7 +548,7 @@
margin-bottom: 10px;
}
.teacher-sidebar-toggle {
.course-sidebar-toggle {
position: absolute;
top: 14px;
right: 14px;
@ -603,7 +603,122 @@
display: none;
}
.teacher-sidebar-toggle {
.course-sidebar-toggle {
right: 16px;
transform: none;
}
}
.main-container {
margin-left: 64px;
}
}
}
/* 仅学生实训任务页提供课程导航的图标轨道,离开任务页不改变原有学生布局。 */
.studentLayout:has(.student-training-shell) {
.sidebar-container {
border-right: 1px solid rgba(0, 180, 255, 0.24);
.student-course-nav {
margin: 20px;
}
.course-sidebar-toggle {
position: absolute;
top: 28px;
right: 28px;
z-index: 8;
display: grid;
width: 32px;
height: 32px;
place-items: center;
border: 1px solid rgba(89, 218, 255, 0.5);
border-radius: 9px;
color: #dff8ff;
background: rgba(5, 54, 83, 0.84);
box-shadow: 0 0 14px rgba(0, 170, 255, 0.15);
font-size: 24px;
line-height: 1;
cursor: pointer;
transition: background .2s ease, border-color .2s ease, transform .2s ease;
&:hover,
&:focus-visible {
border-color: #70e4ff;
outline: none;
background: rgba(11, 116, 160, 0.8);
transform: translateX(1px);
}
}
}
&.hideSidebar {
.sidebar-container {
width: 64px !important;
.student-course-nav {
box-sizing: border-box;
width: 100%;
min-height: 100%;
margin: 0;
padding: 58px 11px 24px;
border: 0;
border-radius: 0;
background:
linear-gradient(180deg, rgba(8, 31, 47, .92), rgba(3, 16, 28, .98));
box-shadow: inset -1px 0 0 rgba(132, 228, 255, .1);
}
.student-course-heading,
.student-course-link {
box-sizing: border-box;
width: 42px;
justify-content: center;
padding-right: 0;
padding-left: 0;
}
/* 分类名收起后没有辨识价值,保留具有页面入口的标题按钮。 */
div.student-course-heading {
display: none;
}
.student-course-heading {
min-height: 42px;
margin: 0 0 10px;
}
.student-course-link {
min-height: 42px;
margin: 0 0 8px;
border-radius: 13px;
background: rgba(255, 255, 255, .025);
}
.student-course-list {
margin: 0 0 10px;
}
.student-course-text {
display: none;
}
.student-course-icon {
width: 27px;
height: 27px;
}
.student-course-link.active {
border: 1px solid rgba(0, 190, 255, .85);
background: linear-gradient(135deg, rgba(0, 174, 255, .28), rgba(18, 95, 190, .14));
box-shadow: 0 0 14px rgba(0, 178, 255, .25);
transform: none;
}
.course-sidebar-toggle {
top: 12px;
right: 16px;
transform: none;
}

@ -39,6 +39,16 @@
background: #06111d !important;
}
/* 学生实训工作台:右侧 AI 栏默认折叠,展开后使用更舒展的阅读宽度。 */
#app .studentLayout .app-main:has(.student-training-shell) .student-training-shell {
grid-template-columns: minmax(660px, 1fr) minmax(360px, 390px) !important;
transition: grid-template-columns .24s ease;
}
#app .studentLayout .app-main:has(.student-training-shell) .student-training-shell:has(.training-ai-sidebar.is-collapsed) {
grid-template-columns: minmax(0, 1fr) 56px !important;
}
/*
* Student pages use different local names for their main and workbench cards.
* Keep the layout density here so a page-specific card cannot reclaim the
@ -605,6 +615,15 @@
background: #06111d !important;
}
#app .studentLayout .legacy-training-page {
grid-template-columns: minmax(0, 1fr) minmax(360px, 390px) !important;
transition: grid-template-columns .24s ease;
}
#app .studentLayout .legacy-training-page:has(.training-ai-sidebar.is-collapsed) {
grid-template-columns: minmax(0, 1fr) 56px !important;
}
.legacy-training-page > :not(.training-ai-sidebar) {
grid-column: 1 !important;
min-width: 0 !important;

@ -11,12 +11,12 @@
<!-- <logo v-if="showLogo" :collapse="isCollapse" /> -->
<template v-if="isCourseStyleSidebar">
<button
v-if="isTeacherRole"
class="teacher-sidebar-toggle"
v-if="isTeacherRole || isStudentTrainingWorkspace"
class="course-sidebar-toggle"
type="button"
:aria-label="isCollapse ? '展开导航' : '收起导航'"
:title="isCollapse ? '展开导航' : '收起导航'"
@click="toggleTeacherSidebar"
@click="toggleCourseSidebar"
>{{ isCollapse ? '›' : '‹' }}</button>
<el-scrollbar class="theme-dark student-sidebar-scroll" wrap-class="scrollbar-wrapper">
<nav class="student-course-nav">
@ -281,7 +281,10 @@ const isCollapse = computed(() => !appStore.sidebar.opened);
const isTeacherRole = computed(() => Number(userStore.userInfo.roleId) === 3);
const isStudentRole = computed(() => ![1, 2, 3].includes(Number(userStore.userInfo.roleId)));
const isCourseStyleSidebar = computed(() => isStudentRole.value || isTeacherRole.value);
function toggleTeacherSidebar() {
const isStudentTrainingWorkspace = computed(() => isStudentRole.value && [
"/foundation/", "/demand/", "/product/", "/channel/", "/assessment/", "/test/", "/comprehensive/",
].some((prefix) => route.path.startsWith(prefix)));
function toggleCourseSidebar() {
appStore.toggleSideBar(false);
}
const sidebarStyle = computed(() => {

@ -0,0 +1,51 @@
export const STEP_ONE_CHOICE_TASK_KEYS = new Set([
"new-product-survey",
"industry-demand-analysis",
"competitive-environment-analysis",
]);
export const QUESTION_OPTION_KEYS = ["A", "B", "C", "D", "E", "F"];
function text(value) {
return String(value ?? "").trim();
}
export function supportsStepOneChoiceQuestions(taskKey) {
return STEP_ONE_CHOICE_TASK_KEYS.has(text(taskKey));
}
export function createStepOneChoiceQuestion(index = 0) {
return {
id: `step-one-question-${Date.now()}-${index + 1}`,
title: "",
options: QUESTION_OPTION_KEYS.slice(0, 2).map((key) => ({ key, content: "" })),
answer: "A",
};
}
export function parseStepOneChoiceQuestions(value) {
let source = value;
if (typeof value === "string") {
try {
source = JSON.parse(value);
} catch {
source = [];
}
}
if (!Array.isArray(source)) return [];
return source.map((question, questionIndex) => {
const options = Array.isArray(question?.options) ? question.options : [];
const normalizedOptions = options
.map((option, optionIndex) => ({
key: QUESTION_OPTION_KEYS[optionIndex],
content: text(typeof option === "string" ? option : option?.content),
}))
.filter((option) => option.content);
return {
id: text(question?.id) || `step-one-question-${questionIndex + 1}`,
title: text(question?.title),
options: normalizedOptions,
answer: text(question?.answer).toUpperCase(),
};
}).filter((question) => question.title && question.options.length >= 2);
}

@ -0,0 +1,334 @@
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import { saveAs } from "file-saver";
const PAGE = { width: 210, height: 297, marginX: 12, marginY: 14 };
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function normalizeText(value) {
return String(value ?? "").trim();
}
function normalizeList(value) {
if (Array.isArray(value)) return value.map(normalizeText).filter(Boolean);
const text = normalizeText(value);
if (!text) return [];
try {
const parsed = JSON.parse(text);
if (Array.isArray(parsed)) return parsed.map((item) => normalizeText(item?.name ?? item?.title ?? item)).filter(Boolean);
} catch {
// 兼容历史任务中使用换行保存的步骤或目标。
}
return text.split(/\r?\n/).map((item) => item.replace(/^\s*(?:\d+[、..]|[-•])\s*/, "").trim()).filter(Boolean);
}
function safeFileName(value) {
return normalizeText(value || "实训成果").replace(/[\\/:*?\"<>|]/g, "_").slice(0, 80);
}
function sectionMarkup(title, body) {
return `<section class="training-outcome-pdf__section"><h2>${escapeHtml(title)}</h2>${body}</section>`;
}
function paragraphMarkup(value) {
const content = escapeHtml(normalizeText(value) || "未配置").replace(/\r?\n/g, "<br>");
return `<p>${content}</p>`;
}
function listMarkup(items, itemClass) {
if (!items.length) return "<p>未配置</p>";
return `<ol class="${itemClass}">${items.map((item) => `<li>${escapeHtml(item)}</li>`).join("")}</ol>`;
}
function compactText(value) {
return normalizeText(value).replace(/\s+/g, " ");
}
function topLevelNodes(nodes) {
return nodes.filter((node) => !nodes.some((candidate) => candidate !== node && candidate.contains(node)));
}
function findStepNodes(scope) {
for (const selector of [".step-content", "[data-training-step]", ".training-step", ".step-panel"]) {
const nodes = topLevelNodes(Array.from(scope.querySelectorAll(selector)));
if (nodes.length) return nodes;
}
return [];
}
function printableCopy(node) {
if (!node) return null;
const copy = node.cloneNode(true);
copy.querySelectorAll("input, textarea, select, button, .training-task-toolbar, .training-ai-sidebar, .step-actions, .step-navigation, .el-input__suffix, script, style")
.forEach((element) => element.remove());
return copy;
}
function tableData(table) {
const rows = Array.from(table.querySelectorAll("tr"))
.map((row) => ({
header: Boolean(row.querySelector("th")),
cells: Array.from(row.querySelectorAll(":scope > th, :scope > td")).map((cell) => compactText(cell.textContent)),
}))
.filter((row) => row.cells.some(Boolean));
if (!rows.length) return null;
const headerIndex = rows.findIndex((row) => row.header);
const firstRowIndex = headerIndex >= 0 ? headerIndex : 0;
return {
headers: rows[firstRowIndex].cells,
rows: rows.filter((_, index) => index !== firstRowIndex).map((row) => row.cells),
};
}
function readableContent(node) {
const copy = printableCopy(node);
if (!copy) return { text: "", tables: [] };
const tables = Array.from(copy.querySelectorAll("table")).map(tableData).filter(Boolean);
copy.querySelectorAll("table").forEach((table) => table.remove());
return { text: compactText(copy.textContent), tables };
}
function tableHeaderLabel(control) {
const cell = control.closest("td, th");
const table = control.closest("table");
if (!cell || !table) return "";
const index = Array.from(cell.parentElement?.children || []).indexOf(cell);
const headerRows = Array.from(table.querySelectorAll("thead tr"));
const headers = headerRows.length ? Array.from(headerRows[headerRows.length - 1].children) : [];
return compactText(headers[index]?.textContent || "");
}
function controlLabel(control, index) {
const formItem = control.closest(".el-form-item");
const formLabel = formItem?.querySelector("label, .el-form-item__label");
const tableLabel = tableHeaderLabel(control);
return compactText(control.getAttribute("aria-label") || formLabel?.textContent || tableLabel || control.getAttribute("placeholder") || `填写项 ${index + 1}`);
}
function controlValue(control) {
const type = String(control.type || "").toLowerCase();
if ((type === "checkbox" || type === "radio") && !control.checked) return "";
if (control.tagName === "SELECT") return Array.from(control.selectedOptions || []).map((option) => compactText(option.textContent)).filter(Boolean).join("、");
return normalizeText(control.value);
}
function collectDomAnswers(stepNodes) {
return stepNodes.map((node) => {
const seen = new Set();
return Array.from(node.querySelectorAll("input, textarea, select"))
.filter((control) => !control.closest(".training-task-toolbar, .training-ai-sidebar") && control.type !== "file" && !control.closest(".el-select__input"))
.map((control, index) => ({ label: controlLabel(control, index), value: controlValue(control) }))
.filter(({ value }) => value)
.filter(({ label, value }) => {
const key = `${label}:${value}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
});
}
function parseAnswer(value) {
if (typeof value !== "string") return value;
try { return JSON.parse(value); } catch { return value; }
}
const ANSWER_LABELS = {
summary: "总结", conclusion: "结论", recommendation: "建议", currentStep: "当前步骤", rows: "填写数据",
selected: "选择结果", analysis: "分析", strategy: "策略", imageName: "上传图片", imageUrl: "上传图片地址",
};
function answerLabel(key) {
return ANSWER_LABELS[key] || String(key || "填写内容").replace(/([a-z])([A-Z])/g, "$1 $2");
}
function flattenAnswer(value, prefix = "") {
const parsed = parseAnswer(value);
if (parsed == null || parsed === "") return [];
if (typeof parsed !== "object") return [{ label: prefix || "填写内容", value: normalizeText(parsed) }].filter((item) => item.value);
if (Array.isArray(parsed)) {
if (parsed.every((item) => typeof item !== "object" || item == null)) {
return [{ label: prefix || "填写内容", value: parsed.map((item) => normalizeText(item)).filter(Boolean).join("、") }].filter((item) => item.value);
}
return parsed.flatMap((item, index) => flattenAnswer(item, `${prefix || "填写内容"} ${index + 1}`));
}
return Object.entries(parsed)
.filter(([key]) => !["saveAction", "submitted", "taskKey", "taskId", "currentStep"].includes(key))
.flatMap(([key, item]) => flattenAnswer(item, prefix ? `${prefix} · ${answerLabel(key)}` : answerLabel(key)));
}
function savedStepAnswers(answer, count) {
const source = answer || {};
const dynamic = parseAnswer(source.dynamicStepAnswers) || {};
return Array.from({ length: count }, (_, index) => {
const step = index + 1;
const value = source[`step${step}Answer`] ?? dynamic[`step${step}`] ?? dynamic[`step${step}Answer`];
return flattenAnswer(value);
});
}
/** Collect task-page instructions and student values before rendering the PDF. */
export function collectTrainingOutcomeDetails(task, studentAnswer) {
const steps = normalizeList(task?.steps);
const scope = document.querySelector(".student-training-shell") || document.querySelector(".training-step-area") || document.body;
const nodes = findStepNodes(scope);
const savedAnswers = savedStepAnswers(studentAnswer, steps.length);
const domAnswers = collectDomAnswers(nodes);
return steps.map((name, index) => {
const content = readableContent(nodes[index]);
return {
name,
content: content.text || (content.tables.length ? "" : "当前步骤内容以页面实训说明为准。"),
tables: content.tables,
answers: domAnswers[index]?.length ? domAnswers[index] : savedAnswers[index],
};
});
}
function stepTablesMarkup(tables) {
if (!tables?.length) return "";
return tables.map((table, index) => `
<div class="training-outcome-pdf__table-wrap">
<p class="training-outcome-pdf__table-caption">表 ${index + 1}</p>
<table class="training-outcome-pdf__table">
<thead><tr>${table.headers.map((header) => `<th>${escapeHtml(header || "-")}</th>`).join("")}</tr></thead>
<tbody>${table.rows.map((row) => `<tr>${table.headers.map((_, cellIndex) => `<td>${escapeHtml(row[cellIndex] || "-")}</td>`).join("")}</tr>`).join("")}</tbody>
</table>
</div>`).join("");
}
function stepDetailsMarkup(items) {
if (!items.length) return "<p>未配置</p>";
return `<div class="training-outcome-pdf__step-details">${items.map((step, index) => `
<article class="training-outcome-pdf__step-detail">
<h3><span>${String(index + 1).padStart(2, "0")}</span>${escapeHtml(step.name)}</h3>
<h4>步骤内容</h4>
${step.content ? paragraphMarkup(step.content) : ""}
${stepTablesMarkup(step.tables)}
<h4>学生作答</h4>
${step.answers?.length
? `<ul class="training-outcome-pdf__answers">${step.answers.map((answer) => `<li><b>${escapeHtml(answer.label)}:</b>${escapeHtml(answer.value)}</li>`).join("")}</ul>`
: "<p class=\"training-outcome-pdf__empty-answer\">该步骤暂未填写作答。</p>"}
</article>`).join("")}</div>`;
}
function createPrintDocument(task) {
const title = normalizeText(task?.taskName || task?.title || "实训成果");
const objectives = normalizeList(task?.objectives);
const steps = normalizeList(task?.steps);
const stepDetails = Array.isArray(task?.stepDetails) && task.stepDetails.length
? task.stepDetails
: steps.map((name) => ({ name, content: "当前步骤内容以页面实训说明为准。", tables: [], answers: [] }));
const generatedAt = new Intl.DateTimeFormat("zh-CN", {
year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit",
hour12: false,
}).format(new Date());
const element = document.createElement("article");
element.className = "training-outcome-pdf";
element.setAttribute("aria-hidden", "true");
element.innerHTML = `
<style>
.training-outcome-pdf__header { padding: 0 0 24px; border-bottom: 3px solid #149dcc; }
.training-outcome-pdf__header p { margin: 0 0 8px; color: #1185b4; font-size: 15px; font-weight: 800; letter-spacing: 1px; }
.training-outcome-pdf__header h1 { margin: 0; color: #082641; font-size: 30px; line-height: 1.35; }
.training-outcome-pdf__header span { display: block; margin-top: 10px; color: #617083; font-size: 13px; }
.training-outcome-pdf__section { margin-top: 26px; break-inside: avoid; }
.training-outcome-pdf__section h2 { margin: 0 0 10px; padding-left: 12px; border-left: 5px solid #149dcc; color: #0c4e73; font-size: 20px; line-height: 1.45; }
.training-outcome-pdf__section p { margin: 0; padding: 15px 17px; border-radius: 8px; color: #263c4f; background: #f3f8fb; font-size: 15px; }
.training-outcome-pdf__section ol { margin: 0; padding: 5px 0 5px 30px; }
.training-outcome-pdf__section li { margin: 8px 0; padding: 5px 10px; color: #263c4f; font-size: 15px; }
.training-outcome-pdf__goals li { background: #f3f8fb; }
.training-outcome-pdf__steps { counter-reset: step; list-style: none; padding-left: 0 !important; }
.training-outcome-pdf__steps li { display: flex; gap: 11px; align-items: flex-start; padding: 12px 14px; border: 1px solid #d3e6ef; border-radius: 8px; background: #fbfdfe; }
.training-outcome-pdf__steps li::before { content: counter(step, decimal-leading-zero); counter-increment: step; flex: 0 0 auto; color: #0f91bd; font-weight: 800; }
.training-outcome-pdf__step-detail { margin: 18px 0 26px; padding: 17px; border: 1px solid #d3e6ef; border-radius: 10px; background: #fbfdfe; break-inside: avoid; }
.training-outcome-pdf__step-detail h3 { display: flex; gap: 10px; align-items: center; margin: 0 0 14px; color: #0c4e73; font-size: 18px; }
.training-outcome-pdf__step-detail h3 span { display: inline-grid; width: 29px; height: 29px; place-items: center; border-radius: 50%; color: #fff; background: #149dcc; font-size: 13px; }
.training-outcome-pdf__step-detail h4 { margin: 15px 0 7px; color: #31718f; font-size: 14px; }
.training-outcome-pdf__step-detail p { padding: 11px 13px; font-size: 14px; }
.training-outcome-pdf__table-wrap { margin: 11px 0 15px; overflow: hidden; border: 1px solid #c7e1ec; border-radius: 7px; }
.training-outcome-pdf__table-caption { margin: 0 !important; padding: 7px 10px !important; color: #0d638b; background: #eaf6fb !important; font-size: 12px !important; font-weight: 800; }
.training-outcome-pdf__table { width: 100% !important; min-width: 0 !important; table-layout: fixed; border-collapse: collapse; font-size: 11px; }
.training-outcome-pdf__table th, .training-outcome-pdf__table td { box-sizing: border-box; padding: 7px 6px; color: #263c4f; word-break: break-word; border: 1px solid #c7e1ec; vertical-align: top; }
.training-outcome-pdf__table th { color: #0c4e73; background: #edf8fc; font-weight: 800; }
.training-outcome-pdf__answers { margin: 0; padding: 10px 14px; border-radius: 7px; background: #eef8fc; list-style: none; }
.training-outcome-pdf__answers li { margin: 6px 0; padding: 0; color: #234255; font-size: 13px; word-break: break-word; }
.training-outcome-pdf__answers b { color: #0d638b; }
.training-outcome-pdf__empty-answer { color: #778899; font-style: italic; }
.training-outcome-pdf footer { margin-top: 34px; padding-top: 12px; border-top: 1px solid #d9e8ef; color: #7c8b99; font-size: 12px; text-align: center; }
</style>
<header class="training-outcome-pdf__header">
<p>电商互联网产品开发实训系统</p>
<h1>${escapeHtml(title)}</h1>
<span>实训任务说明 · 导出时间:${escapeHtml(generatedAt)}</span>
</header>
${sectionMarkup("实训背景", paragraphMarkup(task?.background))}
${sectionMarkup("实训目标", listMarkup(objectives, "training-outcome-pdf__goals"))}
${sectionMarkup("实训要求", paragraphMarkup(task?.requirements))}
${sectionMarkup("实训步骤与学生作答", stepDetailsMarkup(stepDetails))}
<footer>电商互联网产品开发实训系统 · ${escapeHtml(title)}</footer>
`;
Object.assign(element.style, {
position: "fixed", left: "-10000px", top: "0", width: "794px", padding: "54px 58px 48px",
boxSizing: "border-box", color: "#11243b", background: "#ffffff", fontFamily: "Microsoft YaHei, PingFang SC, Arial, sans-serif",
lineHeight: "1.75", zIndex: "-1",
});
return element;
}
function appendPdfPages(pdf, canvas) {
const contentWidthMm = PAGE.width - PAGE.marginX * 2;
const contentHeightMm = PAGE.height - PAGE.marginY * 2;
const sourceHeight = Math.floor(canvas.width * contentHeightMm / contentWidthMm);
let sourceY = 0;
let page = 0;
while (sourceY < canvas.height) {
const currentHeight = Math.min(sourceHeight, canvas.height - sourceY);
const slice = document.createElement("canvas");
slice.width = canvas.width;
slice.height = currentHeight;
slice.getContext("2d").drawImage(canvas, 0, sourceY, canvas.width, currentHeight, 0, 0, canvas.width, currentHeight);
if (page > 0) pdf.addPage();
pdf.addImage(slice.toDataURL("image/jpeg", 0.96), "JPEG", PAGE.marginX, PAGE.marginY, contentWidthMm, currentHeight * contentWidthMm / canvas.width, undefined, "FAST");
sourceY += currentHeight;
page += 1;
}
}
/**
* Export the configured training brief as a Chinese PDF. Browser rendering keeps
* Chinese characters reliable without requiring a separately embedded font file.
*/
export async function exportTrainingOutcomePdf(task) {
if (!normalizeText(task?.taskName || task?.title)) throw new Error("当前实训任务未加载完成,无法导出 PDF。");
const documentNode = createPrintDocument(task);
document.body.appendChild(documentNode);
try {
const canvas = await html2canvas(documentNode, {
backgroundColor: "#ffffff",
scale: 2,
useCORS: true,
logging: false,
});
const pdf = new jsPDF({ orientation: "p", unit: "mm", format: "a4", compress: true });
appendPdfPages(pdf, canvas);
// jsPDF 的 save 在异步渲染结束后可能被浏览器当作非用户触发下载而拦截。
// 先生成 Blob,再通过项目已使用的 file-saver 发起下载,兼容性更稳定。
const pdfBlob = pdf.output("blob");
if (!(pdfBlob instanceof Blob) || pdfBlob.size === 0) {
throw new Error("PDF 文件生成失败,请重新尝试导出。");
}
saveAs(pdfBlob, `${safeFileName(task.taskName || task.title)}-实训成果.pdf`);
} finally {
documentNode.remove();
}
}

@ -0,0 +1,127 @@
<template>
<el-dialog
:model-value="visible"
:title="`${taskName || '实训任务'} · 第一步选择题`"
width="min(900px, 94vw)"
append-to-body
class="step-one-question-editor"
@update:model-value="close"
>
<div class="choice-editor-intro">
<div>
<span>STEP 01 · KNOWLEDGE CHECK</span>
<p>每次新增一题;填写题干、至少两个选项,并标记正确答案。</p>
</div>
<el-button type="primary" @click="addQuestion">新增题目</el-button>
</div>
<el-empty v-if="!draft.length" description="暂未设置选择题,可点击“新增题目”开始配置。" />
<div v-else class="choice-question-list">
<article v-for="(question, questionIndex) in draft" :key="question.id" class="choice-question-card">
<header>
<span class="choice-question-number">{{ String(questionIndex + 1).padStart(2, '0') }}</span>
<strong>单选题</strong>
<button type="button" class="choice-question-remove" @click="removeQuestion(questionIndex)">删除本题</button>
</header>
<el-input v-model="question.title" maxlength="300" show-word-limit placeholder="请输入题目内容" aria-label="题目内容" />
<div class="choice-options">
<div v-for="(option, optionIndex) in question.options" :key="option.key" class="choice-option-row">
<el-radio v-model="question.answer" :label="option.key" :aria-label="`设置 ${option.key} 为正确答案`">
正确答案
</el-radio>
<span class="choice-option-key">{{ option.key }}</span>
<el-input v-model="option.content" maxlength="200" show-word-limit :placeholder="`请输入 ${option.key} 选项`" />
<el-button text type="danger" :disabled="question.options.length <= 2" @click="removeOption(question, optionIndex)">删除</el-button>
</div>
</div>
<el-button v-if="question.options.length < optionKeys.length" text type="primary" @click="addOption(question)">+ 添加选项</el-button>
</article>
</div>
<template #footer>
<el-button @click="close(false)">取消</el-button>
<el-button type="primary" @click="save">保存选择题</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { QUESTION_OPTION_KEYS, createStepOneChoiceQuestion, parseStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
const props = defineProps({
visible: { type: Boolean, default: false },
modelValue: { type: Array, default: () => [] },
taskName: { type: String, default: "" },
});
const emit = defineEmits(["update:visible", "update:modelValue"]);
const draft = ref([]);
const optionKeys = QUESTION_OPTION_KEYS;
watch(() => props.visible, (opened) => {
if (opened) draft.value = structuredClone(parseStepOneChoiceQuestions(props.modelValue));
}, { immediate: true });
function addQuestion() {
draft.value.push(createStepOneChoiceQuestion(draft.value.length));
}
function addOption(question) {
const key = optionKeys[question.options.length];
if (key) question.options.push({ key, content: "" });
}
function removeOption(question, index) {
if (question.options.length <= 2) return;
const removed = question.options.splice(index, 1)[0];
question.options.forEach((option, optionIndex) => { option.key = optionKeys[optionIndex]; });
if (question.answer === removed.key) question.answer = question.options[0].key;
}
function removeQuestion(index) {
draft.value.splice(index, 1);
}
function normalizeAndValidate() {
return draft.value.map((question, questionIndex) => {
const title = String(question.title || "").trim();
const options = question.options
.map((option, optionIndex) => ({ key: optionKeys[optionIndex], content: String(option.content || "").trim() }))
.filter((option) => option.content);
if (!title) throw new Error(`请填写第 ${questionIndex + 1} 题题干`);
if (options.length < 2) throw new Error(`第 ${questionIndex + 1} 题至少需要两个选项`);
const answer = String(question.answer || "").trim().toUpperCase();
if (!options.some((option) => option.key === answer)) throw new Error(`请设置第 ${questionIndex + 1} 题的正确答案`);
return { id: question.id || `step-one-question-${questionIndex + 1}`, title, options, answer };
});
}
function save() {
try {
emit("update:modelValue", normalizeAndValidate());
emit("update:visible", false);
ElMessage.success("选择题已保存到当前任务配置,点击“保存配置”后对学生生效");
} catch (error) {
ElMessage.warning(error?.message || "请选择正确答案");
}
}
function close(value = false) {
emit("update:visible", value);
}
</script>
<style lang="scss">
.step-one-question-editor {
.el-dialog { overflow: hidden; border: 1px solid rgba(64, 211, 255, .6); background: #061a2a; box-shadow: 0 24px 80px rgba(0, 0, 0, .46), inset 0 1px rgba(200, 247, 255, .14); }
.el-dialog__header { margin: 0; padding: 20px 24px; border-bottom: 1px solid rgba(72, 201, 255, .25); }
.el-dialog__title { color: #e9fbff; font-size: 18px; font-weight: 800; }
.el-dialog__body { max-height: min(66vh, 720px); overflow-y: auto; padding: 20px 24px; }
.el-dialog__footer { padding: 16px 24px; border-top: 1px solid rgba(72, 201, 255, .25); }
}
.choice-editor-intro { display:flex; align-items:center; justify-content:space-between; gap:20px; margin-bottom:18px; padding:15px 17px; border-left:3px solid #3be2ff; background:linear-gradient(90deg,rgba(18,151,211,.2),transparent); }
.choice-editor-intro span { color:#59dcff; font-size:12px; font-weight:800; letter-spacing:.12em; }.choice-editor-intro p { margin:5px 0 0; color:#b6d9e7; line-height:1.6; }
.choice-question-list { display:grid; gap:16px; }.choice-question-card { padding:16px; border:1px solid rgba(82,204,250,.32); border-radius:10px; background:rgba(4,37,57,.7); }.choice-question-card header { display:flex; align-items:center; gap:9px; margin-bottom:13px; color:#dff8ff; }.choice-question-number { display:grid; place-items:center; width:28px; height:28px; border-radius:50%; color:#032335; background:#60e6e1; font-size:12px; font-weight:900; }.choice-question-remove { margin-left:auto; color:#ff92a5; cursor:pointer; border:0; background:transparent; }.choice-options { display:grid; gap:9px; margin:13px 0 7px; }.choice-option-row { display:grid; grid-template-columns:94px 28px minmax(0,1fr) 52px; align-items:center; gap:8px; }.choice-option-row .el-radio { margin-right:0; color:#bde9f8; }.choice-option-key { display:grid; place-items:center; width:25px; height:25px; color:#64e7ff; font-weight:900; border:1px solid rgba(91,222,255,.5); border-radius:5px; }
@media (max-width:640px) { .choice-editor-intro { align-items:flex-start; flex-direction:column; }.choice-option-row { grid-template-columns:78px 25px minmax(0,1fr); }.choice-option-row > .el-button { grid-column:3; justify-self:end; } }
</style>

@ -1,6 +1,18 @@
<template>
<aside class="training-ai-sidebar">
<section class="ai-panel ai-panel--study">
<aside :class="['training-ai-sidebar', { 'is-collapsed': sidebarCollapsed }]">
<button
class="ai-sidebar-toggle"
type="button"
:aria-expanded="String(!sidebarCollapsed)"
:aria-label="sidebarCollapsed ? '展开 AI 助学与助评' : '收起 AI 助学与助评'"
:title="sidebarCollapsed ? '展开 AI 助学与助评' : '收起 AI 助学与助评'"
@click="sidebarCollapsed = !sidebarCollapsed"
>
<span class="ai-sidebar-toggle__icon">{{ sidebarCollapsed ? '‹' : '›' }}</span>
<span class="ai-sidebar-toggle__label">AI</span>
</button>
<section v-show="!sidebarCollapsed" class="ai-panel ai-panel--study">
<h3>
<el-icon><Reading /></el-icon>
AI助学
@ -30,7 +42,7 @@
</div>
</section>
<section class="ai-panel ai-panel--review">
<section v-show="!sidebarCollapsed" class="ai-panel ai-panel--review">
<h3>
<el-icon><Star /></el-icon>
AI助评
@ -125,6 +137,7 @@ const internalScoreVisible = ref(false);
const assessmentLoading = ref(false);
const evaluation = ref({});
const assistMessages = ref([]);
const sidebarCollapsed = ref(true);
const route = useRoute();
const currentTaskKey = computed(() => resolveTrainingTaskKey(route, props.taskKey));
const reports = computed(() => normalizeEvaluationReports(evaluation.value));
@ -232,7 +245,48 @@ function plainText(value) {
box-shadow:
inset 0 1px 0 rgba(169, 229, 255, 0.12),
0 24px 56px rgba(0, 0, 0, 0.22);
transition: min-height .24s ease, padding .24s ease, border-color .24s ease, background .24s ease;
}
.training-ai-sidebar.is-collapsed {
min-height: 56px;
padding: 6px;
border-color: rgba(92, 224, 255, .48);
background: linear-gradient(180deg, rgba(10, 44, 64, .94), rgba(4, 18, 31, .98));
box-shadow: inset 0 1px 0 rgba(169, 229, 255, .18), 0 12px 28px rgba(0, 0, 0, .2);
}
.ai-sidebar-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 42px;
padding: 0 11px;
border: 1px solid rgba(102, 229, 255, .58);
border-radius: 14px;
color: #e9faff;
background: rgba(8, 78, 111, .72);
box-shadow: inset 0 1px 0 rgba(220, 253, 255, .14);
font: inherit;
font-size: 12px;
font-weight: 900;
letter-spacing: .08em;
cursor: pointer;
transition: transform .2s ease, border-color .2s ease, background .2s ease;
}
.ai-sidebar-toggle:hover,
.ai-sidebar-toggle:focus-visible {
border-color: #80efff;
outline: none;
background: rgba(12, 124, 165, .86);
transform: translateX(-1px);
}
.ai-sidebar-toggle__icon { font-size: 22px; line-height: 1; }
.training-ai-sidebar.is-collapsed .ai-sidebar-toggle {
width: 100%;
min-height: 42px;
padding: 0;
}
.training-ai-sidebar.is-collapsed .ai-sidebar-toggle__label { display: none; }
.ai-panel {
position: relative;

@ -0,0 +1,37 @@
<template>
<section v-if="questions.length" class="training-step-one-questions" aria-label="第一步选择题">
<header>
<span>知识自测</span>
<p>请根据实训资料选择最符合的答案。</p>
</header>
<article v-for="(question, index) in questions" :key="question.id" class="training-step-one-question">
<h4><b>{{ String(index + 1).padStart(2, '0') }}</b>{{ question.title }}</h4>
<el-radio-group :model-value="answers[question.id] || ''" @update:model-value="setAnswer(question.id, $event)">
<el-radio v-for="option in question.options" :key="option.key" :label="option.key" border>
<strong>{{ option.key }}.</strong> {{ option.content }}
</el-radio>
</el-radio-group>
</article>
</section>
</template>
<script setup>
import { computed } from "vue";
import { parseStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
const props = defineProps({
questions: { type: [Array, String], default: () => [] },
modelValue: { type: Object, default: () => ({}) },
});
const emit = defineEmits(["update:modelValue"]);
const questions = computed(() => parseStepOneChoiceQuestions(props.questions));
const answers = computed(() => props.modelValue || {});
function setAnswer(questionId, answer) {
emit("update:modelValue", { ...answers.value, [questionId]: answer });
}
</script>
<style lang="scss" scoped>
.training-step-one-questions { margin:20px 0; padding:18px; border:1px solid rgba(70,218,255,.38); border-radius:14px; background:linear-gradient(135deg,rgba(8,76,111,.26),rgba(3,28,45,.38)); }.training-step-one-questions header { display:flex; align-items:baseline; gap:12px; padding-bottom:12px; border-bottom:1px solid rgba(90,211,255,.22); }.training-step-one-questions header span { color:#60e6e1; font-size:15px; font-weight:900; letter-spacing:.08em; }.training-step-one-questions header p { margin:0; color:#b9ddea; font-size:13px; }.training-step-one-question { padding:17px 0 4px; }.training-step-one-question + .training-step-one-question { border-top:1px dashed rgba(93,214,255,.2); }.training-step-one-question h4 { display:flex; gap:9px; margin:0 0 12px; color:#edfaff; font-size:16px; line-height:1.65; }.training-step-one-question h4 b { flex:0 0 auto; color:#59dcff; }.training-step-one-question :deep(.el-radio-group) { display:grid; gap:9px; }.training-step-one-question :deep(.el-radio.is-bordered) { width:100%; height:auto; min-height:38px; margin:0; padding:9px 12px; color:#d9f5ff; line-height:1.55; border-color:rgba(100,219,255,.36); background:rgba(3,23,38,.55); }.training-step-one-question :deep(.el-radio.is-bordered.is-checked) { border-color:#59dcff; background:rgba(17,149,207,.2); }.training-step-one-question :deep(.el-radio__label) { white-space:normal; }.training-step-one-question strong { color:#61e7ff; }
</style>

@ -7,7 +7,7 @@
<el-button class="task-toolbar-button" @click="triggerExistingAction('reset')">
<el-icon><RefreshLeft /></el-icon>重新实训
</el-button>
<el-button class="task-toolbar-button" @click="triggerExistingAction('export')">
<el-button class="task-toolbar-button" :loading="exporting" @click="exportCurrentTrainingOutcome">
<el-icon><Download /></el-icon>导出实训成果
</el-button>
</div>
@ -18,9 +18,10 @@ import { computed, onMounted, ref, watch } from "vue";
import { CircleCheck, Download, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getTrainingTaskByKey } from "@/api/trainingTask";
import { deleteStudentTrainingAnswer, saveStudentTrainingAnswer } from "@/api/studentTrainingAnswer";
import { deleteStudentTrainingAnswer, getStudentTrainingAnswer, saveStudentTrainingAnswer } from "@/api/studentTrainingAnswer";
import { resolveTrainingTaskKey } from "@/views/training/taskKeyMap";
import TrainingMaterialButton from "@/views/components/TrainingMaterialButton.vue";
import { collectTrainingOutcomeDetails, exportTrainingOutcomePdf } from "@/utils/trainingOutcomePdf";
const props = defineProps({
materialName: { type: String, default: "" },
@ -33,26 +34,60 @@ const props = defineProps({
const route = useRoute();
const loadedMaterial = ref({ name: "", url: "" });
const loadedTask = ref(null);
const exporting = ref(false);
const resolvedTaskKey = computed(() => resolveTrainingTaskKey(route, props.taskKey));
const resolvedMaterial = computed(() => ({
name: String(props.materialName || loadedMaterial.value.name || ""),
url: String(props.materialUrl || loadedMaterial.value.url || ""),
}));
onMounted(loadMaterial);
watch(resolvedTaskKey, loadMaterial);
onMounted(loadTaskConfig);
watch(resolvedTaskKey, loadTaskConfig);
async function loadMaterial() {
if (props.materialName || props.materialUrl || !resolvedTaskKey.value) return;
async function loadTaskConfig() {
if (!resolvedTaskKey.value) return;
try {
const response = await getTrainingTaskByKey(resolvedTaskKey.value);
const task = response?.data || response || {};
loadedTask.value = task;
loadedMaterial.value = {
name: String(task.materialName || ""),
url: String(task.materialUrl || ""),
name: String(props.materialName || task.materialName || ""),
url: String(props.materialUrl || task.materialUrl || ""),
};
} catch {
// The material button keeps its unavailable state when a task has no configured case file.
loadedTask.value = null;
}
}
async function exportCurrentTrainingOutcome() {
if (exporting.value) return;
exporting.value = true;
try {
let task = loadedTask.value;
if (!task?.taskName) {
const response = await getTrainingTaskByKey(resolvedTaskKey.value);
task = response?.data || response || null;
loadedTask.value = task;
}
let studentAnswer = null;
try {
const answerResponse = await getStudentTrainingAnswer(resolvedTaskKey.value);
studentAnswer = answerResponse?.data || null;
} catch {
// 当前页面的填写值仍可导出;已保存记录不可用时不阻塞学生下载任务说明。
}
await exportTrainingOutcomePdf({
...task,
stepDetails: collectTrainingOutcomeDetails(task, studentAnswer),
});
ElMessage.success("PDF 实训成果已开始下载");
} catch (error) {
console.error("导出实训成果 PDF 失败", error);
ElMessage.error(error?.message || "PDF 导出失败,请稍后重试。");
} finally {
exporting.value = false;
}
}
@ -60,7 +95,6 @@ function triggerExistingAction(action) {
const directActions = {
submit: props.onSubmit,
reset: props.onReset,
export: props.onExport,
};
if (directActions[action]) {

@ -59,6 +59,11 @@
</div>
<p class="task-desc">请对上述信息进行SWOT分析归类。</p>
<TrainingStepOneChoiceQuestions
v-if="currentStep === 1"
:questions="taskConfig?.stepOneQuestions"
v-model="form.choiceAnswers"
/>
<div class="swot-grid">
<article v-for="item in swotItems" :key="item.key" class="swot-card">
@ -127,6 +132,7 @@
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue";
import TrainingMaterialButton from "@/views/components/TrainingMaterialButton.vue";
import TrainingTaskBrief from "@/views/components/TrainingTaskBrief.vue";
import TrainingStepOneChoiceQuestions from "@/views/components/TrainingStepOneChoiceQuestions.vue";
import { getTrainingTaskByKey } from "@/api/trainingTask";
import { parseTrainingArray } from "@/views/training/taskKeyMap";
import { getStudentTrainingAnswer, saveStudentTrainingAnswer } from "@/api/studentTrainingAnswer";
@ -214,6 +220,7 @@ function createForm() {
},
entryStrategy: "",
competitionConclusion: "",
choiceAnswers: {},
};
}
@ -297,6 +304,7 @@ function applySavedAnswer(value) {
},
entryStrategy: parsed.entryStrategy || "",
competitionConclusion: parsed.competitionConclusion || "",
choiceAnswers: parsed.choiceAnswers && typeof parsed.choiceAnswers === "object" ? parsed.choiceAnswers : {},
};
} catch (error) {
// Ignore malformed historical answers.
@ -310,6 +318,7 @@ function buildOutcome() {
entryStrategy: form.value.entryStrategy,
competitors: competitorRows,
competitionConclusion: form.value.competitionConclusion,
choiceAnswers: form.value.choiceAnswers,
};
}

@ -29,6 +29,7 @@
<template v-if="currentStep === 1">
<div class="step-title-row"><div><p class="section-eyebrow">Step 01</p><h3>{{ trainingSteps[0] }}</h3></div><span class="step-chip">PEST 分类练习</span></div>
<p class="step-desc">请根据案例文档中的案例信息进行 PEST 分析,进行上述各项内容归类,把文档中相应内容填写到以下四类中。</p>
<TrainingStepOneChoiceQuestions :questions="taskConfig?.stepOneQuestions" v-model="stepOneChoiceAnswers" />
<div class="pest-table-wrap">
<table class="pest-table"><thead><tr><th>序号</th><th>PEST类型</th><th>信息资讯</th></tr></thead>
<tbody><tr v-for="(row, index) in pestRows" :key="row.key"><td>{{ index + 1 }}</td><td class="type-cell">{{ row.label }}</td><td><textarea v-model.trim="form[row.key]" :placeholder="row.placeholder" /></td></tr></tbody>
@ -99,6 +100,7 @@ import useUserStore from "@/store/modules/user";
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue";
import TrainingTaskBrief from "@/views/components/TrainingTaskBrief.vue";
import TrainingTaskToolbar from "@/views/components/TrainingTaskToolbar.vue";
import TrainingStepOneChoiceQuestions from "@/views/components/TrainingStepOneChoiceQuestions.vue";
const TASK_KEY = "industry-demand-analysis";
const { proxy } = getCurrentInstance();
@ -132,6 +134,7 @@ const stepOnePassed = ref(false);
const stepTwoPassed = ref(false);
const stepThreePassed = ref(false);
const form = ref(createForm());
const stepOneChoiceAnswers = ref({});
const supplementForm = ref(createForm());
const analysisForm = ref(createAnalysisForm());
const conclusionForm = ref(createConclusionForm());
@ -161,10 +164,10 @@ async function loadSavedAnswer() {
if (Number(answer?.currentStep) > 0) currentStep.value = Number(answer.currentStep);
} catch (error) { /* Keep the local draft when the answer endpoint is unavailable. */ }
}
function restoreOutcome(value, target, field = "pest") { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; target.value = { ...createForm(), ...(parsed?.[field] || parsed || {}) }; } catch (error) { target.value = createForm(); } }
function restoreOutcome(value, target, field = "pest") { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; target.value = { ...createForm(), ...(parsed?.[field] || parsed || {}) }; if (field === "pest" && parsed?.choiceAnswers && typeof parsed.choiceAnswers === "object") stepOneChoiceAnswers.value = parsed.choiceAnswers; } catch (error) { target.value = createForm(); } }
function restoreAnalysisOutcome(value) { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; const source = parsed?.analysis || parsed || {}; analysisForm.value = Object.fromEntries(pestAnalysisRows.map((row) => [row.key, { ...createAnalysisRow(), ...(source[row.key] || {}) }])); } catch (error) { analysisForm.value = createAnalysisForm(); } }
function restoreConclusionOutcome(value) { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; conclusionForm.value = { ...createConclusionForm(), ...(parsed?.conclusion || parsed || {}) }; } catch (error) { conclusionForm.value = createConclusionForm(); } }
function buildStepOneOutcome() { return { title: taskTitle.value, pest: { ...form.value } }; }
function buildStepOneOutcome() { return { title: taskTitle.value, pest: { ...form.value }, choiceAnswers: { ...stepOneChoiceAnswers.value } }; }
function buildStepTwoOutcome() { return { title: taskTitle.value, supplements: { ...supplementForm.value } }; }
function buildStepThreeOutcome() { return { title: taskTitle.value, analysis: JSON.parse(JSON.stringify(analysisForm.value)) }; }
function buildStepFourOutcome() { return { title: taskTitle.value, conclusion: { ...conclusionForm.value } }; }
@ -202,8 +205,8 @@ async function saveCurrentProgress(showMessage = true) {
}
function previousStep() { if (currentStep.value > 1) currentStep.value -= 1; }
async function nextStep() { if (currentStep.value < trainingSteps.value.length && await saveCurrentProgress(false)) currentStep.value += 1; }
async function resetTraining() { form.value = createForm(); supplementForm.value = createForm(); analysisForm.value = createAnalysisForm(); conclusionForm.value = createConclusionForm(); stepOnePassed.value = false; stepTwoPassed.value = false; stepThreePassed.value = false; currentStep.value = 1; clearDraft(); try { saving.value = true; await deleteStudentTrainingAnswer(TASK_KEY); } catch (error) { /* Local clearing still succeeds. */ } finally { saving.value = false; } proxy?.$modal?.msgSuccess("已重新开始本次实训"); }
function resetStepOne() { form.value = createForm(); stepOnePassed.value = false; proxy?.$modal?.msgSuccess("已清空第 1 步填写内容"); }
async function resetTraining() { form.value = createForm(); stepOneChoiceAnswers.value = {}; supplementForm.value = createForm(); analysisForm.value = createAnalysisForm(); conclusionForm.value = createConclusionForm(); stepOnePassed.value = false; stepTwoPassed.value = false; stepThreePassed.value = false; currentStep.value = 1; clearDraft(); try { saving.value = true; await deleteStudentTrainingAnswer(TASK_KEY); } catch (error) { /* Local clearing still succeeds. */ } finally { saving.value = false; } proxy?.$modal?.msgSuccess("已重新开始本次实训"); }
function resetStepOne() { form.value = createForm(); stepOneChoiceAnswers.value = {}; stepOnePassed.value = false; proxy?.$modal?.msgSuccess("已清空第 1 步填写内容"); }
function resetStepTwo() { supplementForm.value = createForm(); proxy?.$modal?.msgSuccess("已清空第 2 步填写内容"); }
function resetStepThree() { analysisForm.value = createAnalysisForm(); proxy?.$modal?.msgSuccess("已清空第 3 步填写内容"); }
function resetStepFour() { conclusionForm.value = createConclusionForm(); proxy?.$modal?.msgSuccess("已清空第 4 步填写内容"); }

@ -51,6 +51,10 @@
<span class="step-chip">卖点分类练习</span>
</div>
<p class="step-desc">查看案例产品详情,仔细阅读主图及详情页信息,对下列产品卖点进行三层次分类。</p>
<TrainingStepOneChoiceQuestions
:questions="taskConfig?.stepOneQuestions"
v-model="stepOneChoiceAnswers"
/>
<div class="training-table-wrap classification-table-wrap">
<table class="training-data-table classification-table">
@ -264,6 +268,7 @@ import { extractTrainingStepNames } from "@/views/training/taskKeyMap";
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue";
import TrainingTaskBrief from "@/views/components/TrainingTaskBrief.vue";
import TrainingTaskToolbar from "@/views/components/TrainingTaskToolbar.vue";
import TrainingStepOneChoiceQuestions from "@/views/components/TrainingStepOneChoiceQuestions.vue";
const TASK_KEY = "new-product-survey";
const { proxy } = getCurrentInstance();
@ -361,6 +366,7 @@ const createStep4Form = () => ({
});
const classifications = ref({});
const stepOneChoiceAnswers = ref({});
const checkResult = ref(null);
const step2Form = ref(createStep2Form());
const step3Rows = ref(createStep3Rows());
@ -495,6 +501,7 @@ function applyStep1Answer(value) {
return result;
}, {});
classifications.value = restored;
stepOneChoiceAnswers.value = parsed.choiceAnswers && typeof parsed.choiceAnswers === "object" ? parsed.choiceAnswers : {};
checkResult.value = normalizeCheckResult(parsed.checkResult);
return Object.keys(restored).length > 0;
}
@ -690,7 +697,7 @@ function buildAnswerPayload(status) {
return {
saveAction,
currentStep: currentStep.value,
step1Answer: JSON.stringify({ classifications: classifications.value, checkResult: checkResult.value }),
step1Answer: JSON.stringify({ classifications: classifications.value, checkResult: checkResult.value, choiceAnswers: stepOneChoiceAnswers.value }),
step2Answer: JSON.stringify(step2Form.value),
step3Answer: JSON.stringify(buildStepThreeValidationPayload()),
step4Answer: JSON.stringify(step4Form.value),
@ -794,6 +801,7 @@ function prevStep() {
function resetExample() {
classifications.value = {};
stepOneChoiceAnswers.value = {};
checkResult.value = null;
step2Form.value = createStep2Form();
imagePreviewUrl.value = "";
@ -813,6 +821,7 @@ function buildOutcome() {
steps: steps.value.map((item) => item.name),
classifications: classifications.value,
checkResult: checkResult.value,
choiceAnswers: stepOneChoiceAnswers.value,
step2Form: step2Form.value,
step3Rows: step3Rows.value,
step4Form: step4Form.value,

@ -171,6 +171,15 @@
<template v-for="(step, index) in taskForm.steps" :key="step.id">
<div class="step-item">
<el-input v-model="step.name" placeholder="步骤名称" />
<el-button
v-if="index === 0 && supportsStepOneChoiceQuestions(taskForm.taskKey) && !isReadonly"
class="step-question-editor"
text
type="primary"
@click.stop="stepQuestionEditorVisible = true"
>
编辑选择题
</el-button>
</div>
<span v-if="index < taskForm.steps.length - 1" class="step-arrow">&gt;&gt;&gt;</span>
</template>
@ -179,6 +188,12 @@
</section>
</el-form>
<StepOneChoiceQuestionEditor
v-model:visible="stepQuestionEditorVisible"
v-model="taskForm.stepOneQuestions"
:task-name="taskForm.title"
/>
<footer class="drawer-footer">
<el-button @click="dialogVisible = false">{{ isReadonly ? "关闭" : "取消" }}</el-button>
<el-button v-if="!isReadonly" type="primary" :loading="saving" @click="submitTask">保存配置</el-button>
@ -197,6 +212,8 @@ import {
uploadTrainingTaskMaterial,
} from "@/api/trainingTask";
import { getStudentTrainingStepCount } from "@/views/training/taskKeyMap";
import StepOneChoiceQuestionEditor from "@/views/components/StepOneChoiceQuestionEditor.vue";
import { parseStepOneChoiceQuestions, supportsStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
const { proxy } = getCurrentInstance();
@ -208,6 +225,7 @@ const materialUploading = ref(false);
const tasks = ref([]);
const dialogVisible = ref(false);
const dialogMode = ref("view");
const stepQuestionEditorVisible = ref(false);
const currentTaskId = ref("");
const taskForm = reactive(createEmptyTask());
const isReadonly = computed(() => dialogMode.value === "view");
@ -297,6 +315,7 @@ function createEmptyTask() {
materialName: "",
materialUrl: "",
steps: createBuiltinSteps(),
stepOneQuestions: [],
sort: 0,
enabled: true,
};
@ -315,6 +334,7 @@ function normalizeTask(task) {
materialName: material.name,
materialUrl: material.url,
steps: normalizeTaskSteps(task.taskKey, parseArray(task.steps, [])),
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
sort: task.sort || 0,
enabled: task.enabled !== false,
};
@ -389,6 +409,7 @@ function cloneTask(task) {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
steps: normalizeTaskSteps(task.taskKey, task.steps),
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
};
}
@ -464,6 +485,7 @@ function buildPayload() {
objectives: JSON.stringify(taskForm.objectives.map((item) => item.trim()).filter(Boolean)),
requirements: taskForm.requirements,
steps: JSON.stringify(fixedSteps),
stepOneQuestions: JSON.stringify(taskForm.stepOneQuestions),
materialName: taskForm.materialName,
materialUrl: taskForm.materialUrl,
sort: taskForm.sort,

@ -193,6 +193,15 @@
<template v-for="(step, index) in taskForm.steps" :key="step.id">
<div class="step-item">
<el-input v-model="step.name" placeholder="步骤名称" />
<el-button
v-if="index === 0 && supportsStepOneChoiceQuestions(taskForm.taskKey) && !isReadonly"
class="step-question-editor"
text
type="primary"
@click.stop="stepQuestionEditorVisible = true"
>
编辑选择题
</el-button>
</div>
<span v-if="index < taskForm.steps.length - 1" class="step-arrow">&gt;&gt;&gt;</span>
</template>
@ -201,6 +210,12 @@
</section>
</el-form>
<StepOneChoiceQuestionEditor
v-model:visible="stepQuestionEditorVisible"
v-model="taskForm.stepOneQuestions"
:task-name="taskForm.title"
/>
<footer class="drawer-footer">
<el-button @click="dialogVisible = false">{{ isReadonly ? "关闭" : "取消" }}</el-button>
<el-button
@ -234,6 +249,8 @@ import { createStudentDemoSession } from "@/api/studentDemo";
import * as indexApi from "@/api/teacher";
import useUserStore from "@/store/modules/user";
import { getStudentTrainingStepCount } from "@/views/training/taskKeyMap";
import StepOneChoiceQuestionEditor from "@/views/components/StepOneChoiceQuestionEditor.vue";
import { parseStepOneChoiceQuestions, supportsStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
@ -250,6 +267,7 @@ const classList = ref([]);
const selectedTeachingClassId = ref("");
const dialogVisible = ref(false);
const dialogMode = ref("view");
const stepQuestionEditorVisible = ref(false);
const taskForm = reactive(createEmptyTask());
const currentUserId = computed(() => userStore.userInfo.userId);
const isReadonly = computed(() => dialogMode.value === "view");
@ -392,6 +410,7 @@ function createEmptyTask() {
materialName: "",
materialUrl: "",
steps: createBuiltinSteps(),
stepOneQuestions: [],
sort: 0,
enabled: true,
};
@ -410,6 +429,7 @@ function normalizeTask(task) {
materialName: material.name,
materialUrl: material.url,
steps: normalizeTaskSteps(task.taskKey, parseArray(task.steps, [])),
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
sort: task.sort || 0,
enabled: task.enabled !== false,
};
@ -501,6 +521,7 @@ function cloneTask(task) {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
steps: normalizeTaskSteps(task.taskKey, task.steps),
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
};
}
@ -630,6 +651,7 @@ function buildPayload() {
objectives: JSON.stringify(taskForm.objectives.map((item) => item.trim()).filter(Boolean)),
requirements: taskForm.requirements,
steps: JSON.stringify(fixedSteps),
stepOneQuestions: JSON.stringify(taskForm.stepOneQuestions),
materialName: taskForm.materialName,
materialUrl: taskForm.materialUrl,
sort: taskForm.sort,

@ -6,7 +6,7 @@
<el-table :data="report.modules || []" border><el-table-column prop="moduleName" label="实训模块"/><el-table-column label="权重"><template #default="{row}">{{ percent(row.weight) }}</template></el-table-column><el-table-column prop="score" label="模块成绩"/><el-table-column label="任务完成"><template #default="{row}">{{ row.completedTaskCount }} / {{ row.totalTaskCount }}</template></el-table-column></el-table>
</el-card>
<el-card class="tasks"><template #header>实训任务明细</template>
<el-table :data="report.tasks || []" border><el-table-column prop="taskName" label="任务名称"/><el-table-column prop="moduleName" label="所属模块"/><el-table-column prop="progressStatus" label="完成状态"/><el-table-column prop="aiAssessmentScore" label="AI 评分"><template #default="{row}">{{ row.aiAssessmentScore ?? '-' }}</template></el-table-column></el-table>
<el-table :data="report.tasks || []" border><el-table-column prop="taskName" label="任务名称"/><el-table-column prop="moduleName" label="所属模块"/><el-table-column label="完成状态"><template #default="{row}">{{ progressStatusLabel(row.progressStatus) }}</template></el-table-column><el-table-column prop="aiAssessmentScore" label="AI 评分"><template #default="{row}">{{ row.aiAssessmentScore ?? '-' }}</template></el-table-column></el-table>
</el-card>
</div>
</template>
@ -15,6 +15,7 @@ import { getCurrentExperimentReport } from '@/api/index';
import useUserStore from '@/store/modules/user';
const userInfo=useUserStore().userInfo; const report=ref({modules:[],tasks:[]});
const percent=(weight)=>weight==null?'-':`${Number(weight)*100}%`;
const progressStatusLabel=(status)=>({ NOT_STARTED:'未开始', IN_PROGRESS:'进行中', COMPLETED:'已完成' })[status]||'未开始';
onMounted(async()=>{const res=await getCurrentExperimentReport(); report.value=res?.data||{modules:[],tasks:[]};});
</script>
<style lang="scss" scoped>

@ -0,0 +1,30 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const page = fs.readFileSync(
path.resolve(__dirname, "../src/views/product/requirements-doc.vue"),
"utf8"
);
assert.match(page, /const PRD_DETAIL_MODULES = \[/);
assert.match(page, /项目背景与痛点/);
assert.match(page, /用户需求与场景/);
assert.match(page, /核心功能需求/);
assert.match(page, /非功能需求/);
assert.match(page, /硬件规格与设计需求/);
assert.match(page, /测试需求/);
assert.match(page, /项目规划/);
assert.match(page, /step2Answer: JSON\.stringify\(buildStepTwoAnswer\(\)\)/);
assert.match(page, /saveAction: "SAVE"/);
assert.match(page, /示例参考:/);
assert.match(page, /学生填写:/);
assert.match(page, /XLSX\.writeFile\(workbook, "PRD详细信息表\.xlsx"\)/);
assert.match(page, /previewRequirementsDocumentFile/);
assert.match(page, /step3Answer: JSON\.stringify\(buildStepThreeAnswer\(\)\)/);
assert.match(page, /accept="\.docx,\.pdf/);
assert.match(page, /handleDocumentUpload/);
assert.match(page, /在线预览/);
console.log("requirements-document step two and three static checks passed");

@ -0,0 +1,32 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const read = (relativePath) => fs.readFileSync(path.join(root, relativePath), "utf8");
const util = read("src/utils/stepOneChoiceQuestions.js");
const editor = read("src/views/components/StepOneChoiceQuestionEditor.vue");
const studentQuestions = read("src/views/components/TrainingStepOneChoiceQuestions.vue");
for (const key of ["new-product-survey", "industry-demand-analysis", "competitive-environment-analysis"]) {
assert.match(util, new RegExp(key));
}
assert.match(editor, /新增题目/);
assert.match(editor, /正确答案/);
assert.match(studentQuestions, /el-radio-group/);
for (const page of [
"src/views/schoolAdmin/trainingTask/index.vue",
"src/views/teacherEnd/trainingTask/index.vue",
]) {
const source = read(page);
assert.match(source, /编辑选择题/);
assert.match(source, /stepOneQuestions/);
}
for (const page of [
"src/views/foundation/new-product-survey.vue",
"src/views/demand/industry-demand-analysis.vue",
"src/views/demand/environment.vue",
]) {
assert.match(read(page), /TrainingStepOneChoiceQuestions/);
}
console.log("step-one choice questions static checks passed");

@ -0,0 +1,25 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const pdfExporter = fs.readFileSync(path.join(root, "src/utils/trainingOutcomePdf.js"), "utf8");
const toolbar = fs.readFileSync(path.join(root, "src/views/components/TrainingTaskToolbar.vue"), "utf8");
assert.match(pdfExporter, /export async function exportTrainingOutcomePdf/);
assert.match(pdfExporter, /export function collectTrainingOutcomeDetails/);
assert.match(pdfExporter, /function tableData/);
assert.match(pdfExporter, /training-outcome-pdf__table/);
assert.match(pdfExporter, /html2canvas/);
assert.match(pdfExporter, /new jsPDF/);
assert.match(pdfExporter, /import \{ saveAs \} from "file-saver"/);
assert.match(pdfExporter, /pdf\.output\("blob"\)/);
assert.match(pdfExporter, /saveAs\(pdfBlob/);
for (const section of ["实训背景", "实训目标", "实训要求", "实训步骤与学生作答", "步骤内容", "学生作答"]) {
assert.match(pdfExporter, new RegExp(section));
}
assert.match(toolbar, /@click="exportCurrentTrainingOutcome"/);
assert.match(toolbar, /exportTrainingOutcomePdf/);
assert.match(toolbar, /getStudentTrainingAnswer/);
assert.match(toolbar, /collectTrainingOutcomeDetails/);
console.log("training outcome PDF static checks passed");
Loading…
Cancel
Save