merge: synchronize teacher task grades

bugfix/ai-assessment-evidence-rescore
陈沅 3 months ago
commit d14afa667e

@ -217,10 +217,13 @@ export function uploadResourceFile(data) {
}
// 学情分析
export function getLearningAnalysis(params) {
let { stuNeed,stuData}=params
const { stuNeed, stuData } = params
return request({
url: import.meta.env.VITE_APP_AI_API+'learnAnalysis/getStuPersonLearnAnalysis?stuNeed='+stuNeed,
url: import.meta.env.VITE_APP_AI_API + 'learnAnalysis/getStuPersonLearnAnalysis',
method: 'POST',
data:stuData
params: { stuNeed },
data: stuData,
// AI 服务使用独立鉴权,不能携带本系统的登录令牌。
headers: { isToken: false }
})
}

@ -304,8 +304,8 @@ export function validateReleaseChannelEvaluationStepTwo(payload) {
&& [row.dailySearchVolume, row.supplyDemandRatio, row.averageCpc, row.existingVisitorCount]
.every((value) => Number.isFinite(value) && value >= 0)
&& [row.averageClickRate, row.averageConversionRate].every((value) => Number.isFinite(value) && value >= 0 && value <= 100)
&& Number.isInteger(row.matchingScore) && row.matchingScore >= 1 && row.matchingScore <= 5);
if (!valid) return Promise.reject(new Error("请完整填写渠道数据;点击率和转化率为0-100%,匹配度为1-5分"));
&& Number.isInteger(row.matchingScore) && row.matchingScore >= 1 && row.matchingScore <= 100);
if (!valid) return Promise.reject(new Error("请完整填写渠道数据;点击率和转化率为0-100%,匹配度为1-100分"));
return Promise.resolve({ code: 200, data: { valid: true, message: "渠道数据校验通过", rowCount: normalizedRows.length } });
}
return request({
@ -332,6 +332,8 @@ export function validateReleaseChannelEvaluationStepThree(payload) {
];
if (!sourceRows.length || rows.length !== sourceRows.length) throw new Error("请先完成第二步全部渠道数据");
const submitted = new Map(rows.map((row) => [String(row?.channel || "").trim(), row]));
const incorrectItems = [];
let totalItemCount = 0;
for (const source of sourceRows) {
const channel = String(source?.channel || "").trim();
const row = submitted.get(channel);
@ -346,12 +348,16 @@ export function validateReleaseChannelEvaluationStepThree(payload) {
const max = Math.max(...values);
const expectedScore = max === min ? 10 : Number((((reverse ? max - value : value - min) * 10) / (max - min)).toFixed(1));
const supplied = dimensions.get(dimension);
if (!supplied || Number(supplied.weight) !== weight || Number(supplied.score) !== expectedScore) throw new Error(`“${channel}”的“${dimension}”得分或权重不正确`);
if (!supplied || Number(supplied.weight) !== weight) throw new Error(`“${channel}”的“${dimension}”权重不完整`);
totalItemCount += 1;
if (Number(supplied.score) !== expectedScore) incorrectItems.push(`“${channel}”的“${dimension}”得分`);
expectedTotal += expectedScore * weight / 100;
});
if (Number(row.weightedScore) !== Number(expectedTotal.toFixed(2))) throw new Error(`“${channel}”的加权得分不正确`);
totalItemCount += 1;
if (Number(row.weightedScore) !== Number(expectedTotal.toFixed(2))) incorrectItems.push(`“${channel}”的加权得分`);
}
return Promise.resolve({ code: 200, data: { valid: true, message: "归一化得分与加权得分校验通过", rowCount: rows.length } });
const calculationCorrect = incorrectItems.length === 0;
return Promise.resolve({ code: 200, data: { valid: true, calculationCorrect, totalItemCount, incorrectItemCount: incorrectItems.length, incorrectItems, message: calculationCorrect ? "计算结果已校验正确,可进入下一步" : `已保存并进入下一步。系统发现${incorrectItems.length}项计算结果与参考值不一致,AI助评时将据此扣分。`, rowCount: rows.length } });
} catch (error) {
return Promise.reject(error);
}
@ -401,12 +407,19 @@ export function validateReleaseChannelEvaluationStepFour(payload) {
export function validateProductDiagnosisIterationStepOne(payload) {
const value = payload || {};
const submittedChannels = Array.isArray(value.channels) ? value.channels : null;
const conversionRates = Array.isArray(value.conversionRates) ? value.conversionRates : [];
const anomalyRows = Array.isArray(value.anomalyRows) ? value.anomalyRows : [];
if (isStudentDemo()) {
try {
const nodes = ["曝光-点击", "点击-加购", "加购-下单", "下单-好评", "好评-复购"];
const channels = ["天猫", "京东", "抖音", "拼多多"];
const legacyChannels = [{ id: "tmall", name: "天猫" }, { id: "jd", name: "京东" }, { id: "douyin", name: "抖音" }, { id: "pinduoduo", name: "拼多多" }];
const channels = (submittedChannels || legacyChannels).map((channel) => ({ id: String(channel?.id || "").trim(), name: String(channel?.name || "").trim() }));
if (!channels.length || channels.some((channel) => !channel.id || !channel.name)
|| new Set(channels.map((channel) => channel.id)).size !== channels.length
|| new Set(channels.map((channel) => channel.name)).size !== channels.length) {
throw new Error("请至少保留一个渠道,并确保渠道名称不为空且不重复");
}
if (conversionRates.length !== nodes.length || new Set(conversionRates.map((row) => String(row?.linkNode || "").trim())).size !== nodes.length) {
throw new Error("请完整填写 5 个链路节点的转化率");
}
@ -414,19 +427,22 @@ export function validateProductDiagnosisIterationStepOne(payload) {
conversionRates.forEach((row) => {
const node = String(row?.linkNode || "").trim();
if (!nodes.includes(node)) throw new Error("链路节点必须与题目中的 5 个节点一致");
const values = [row?.tmall, row?.jd, row?.douyin, row?.pinduoduo, row?.industryAverage].map(Number);
const channelRates = row?.channelRates || row || {};
const rawValues = [...channels.map((channel) => channelRates[channel.id]), row?.industryAverage];
if (rawValues.some((item) => item === null || item === "" || typeof item === "undefined")) throw new Error("请填写 0 至 100 之间的转化率");
const values = rawValues.map(Number);
if (values.some((item) => !Number.isFinite(item) || item < 0 || item > 100)) throw new Error("请填写 0 至 100 之间的转化率");
rates.set(node, { ...row, values });
rates.set(node, { ...row, channelRates });
});
if (!String(value.funnelChartUrl || "").trim()) throw new Error("请上传节点转化漏斗对比图");
if (anomalyRows.length < 1 || anomalyRows.length > 5) throw new Error("异常节点分析最少填写 1 行,最多填写 5 行");
anomalyRows.forEach((row, index) => {
const channel = String(row?.channel || "").trim();
const channel = channels.find((item) => item.id === String(row?.channelId || "").trim()) || channels.find((item) => item.name === String(row?.channel || "").trim());
const node = String(row?.linkNode || "").trim();
const source = rates.get(node);
if (!channels.includes(channel)) throw new Error(`第 ${index + 1} 行渠道必须来源于第一个表格`);
if (!channel) throw new Error(`第 ${index + 1} 行渠道必须来源于第一个表格`);
if (!source) throw new Error(`第 ${index + 1} 行链路节点必须来源于第一个表格`);
const sourceRate = source[{ 天猫: "tmall", 京东: "jd", 抖音: "douyin", 拼多多: "pinduoduo" }[channel]];
const sourceRate = source.channelRates[channel.id];
if (Number(row?.storeConversionRate) !== Number(sourceRate) || Number(row?.industryAverageConversionRate) !== Number(source.industryAverage)) {
throw new Error(`第 ${index + 1} 行的店铺和行业转化率必须与第一个表格对应数据一致`);
}
@ -438,8 +454,9 @@ export function validateProductDiagnosisIterationStepOne(payload) {
return request({
url: "/api/student-training-answers/product-diagnosis-iteration/step-1/validate",
method: "post",
data: { conversionRates, funnelChartUrl: value.funnelChartUrl, anomalyRows },
data: { channels: submittedChannels, conversionRates, funnelChartUrl: value.funnelChartUrl, anomalyRows },
headers: { repeatSubmit: false },
skipErrorMessage: true,
});
}
@ -479,11 +496,11 @@ export function validateProductDiagnosisIterationStepTwo(payload) {
if (sentiments.length !== 3) throw new Error("请填写正面、中性、负面三类情感数据");
const total = sentiments.reduce((sum, item) => sum + Number(item?.count), 0);
if (!Number.isFinite(total) || total <= 0) throw new Error("情感评论数量合计必须大于 0");
sentiments.forEach((item) => { const expected = Number((Number(item?.count) * 100 / total).toFixed(2)); if (!Number.isFinite(Number(item?.count)) || Number(item?.count) < 0 || Number(item?.percentage) !== expected) throw new Error(`${item?.type || "情感"}评论占比计算不正确`); });
sentiments.forEach((item) => { const expected = Number((Number(item?.count) * 100 / total).toFixed(2)); if (!Number.isFinite(Number(item?.count)) || Number(item?.count) < 0 || Number(item?.percentage) !== expected) throw new Error("正面、中性、负面评论占比之和应为100%。"); });
return Promise.resolve({ code: 200, data: { valid: true, message: "情感评论占比计算校验通过" } });
} catch (error) { return Promise.reject(error); }
}
return request({ url: "/api/student-training-answers/product-diagnosis-iteration/step-2/validate", method: "post", data: value, headers: { repeatSubmit: false } });
return request({ url: "/api/student-training-answers/product-diagnosis-iteration/step-2/validate", method: "post", data: value, headers: { repeatSubmit: false }, skipErrorMessage: true });
}
export function validateProductDiagnosisIterationStepThree(payload) {
@ -499,7 +516,7 @@ export function validateProductDiagnosisIterationStepThree(payload) {
return Promise.resolve({ code: 200, data: { valid: true, message: "AB 测试方案、数据与对比图校验通过" } });
} catch (error) { return Promise.reject(error); }
}
return request({ url: "/api/student-training-answers/product-diagnosis-iteration/step-3/validate", method: "post", data: value, headers: { repeatSubmit: false } });
return request({ url: "/api/student-training-answers/product-diagnosis-iteration/step-3/validate", method: "post", data: value, headers: { repeatSubmit: false }, skipErrorMessage: true });
}
export function validatePromotionEffectOptimizationStepOne(payload) {

@ -225,6 +225,13 @@ export function getScoreStatisticsTrend(query) {
params: query,
});
}
// 教师首页 - 可查看班级列表(教师管理员为本校全部教学班)
export function getTeacherHomeClasses() {
return request({
url: "/api/score/getTeaHomeClasses",
method: "get",
});
}
// 获取班级列表
export function getClasses(query) {
return request({
@ -431,6 +438,14 @@ export function updateTeacher(data) {
},
});
}
// 教师管理-初始化教师密码
export function initializeTeacherPassword(params) {
return request({
url: "/api/user/updateTeacherPassword",
method: "POST",
params,
});
}
// 教师管理-删除
export function deleteTeacher(params) {
return request({
@ -627,6 +642,12 @@ export function getOwnedTeachingClasses() {
method: "get",
});
}
export function getAccessibleTeachingClasses() {
return request({
url: "/api/weight/accessibleTeachingClasses",
method: "get",
});
}
export function getTeachingClassWeight(teachingClassId) {
return request({
url: "/api/weight/selectTeachingClassWeight",
@ -685,6 +706,14 @@ export function getScoreDetail(params) {
params,
});
}
// 保存教师对单个实训任务的评分
export function saveTaskTeacherScore(params) {
return request({
url: "/api/weight/saveTaskTeacherScore",
method: "POST",
params,
});
}
// 更新成绩
export function doRankOne(params) {
return request({

@ -164,7 +164,7 @@ export const dynamicRoutes = [
path: "index",
component: () => import("@/views/training/GenericTrainingPage.vue"),
name: "ComprehensiveCaseTraining",
meta: { title: "综合实训", icon: "Finished", affix: true, pageKey: "comprehensive-case-training" },
meta: { title: "综合实训", icon: "Finished", affix: true, pageKey: "comprehensive-case-training", hideSupplementSteps: true },
},
],
},

@ -12,7 +12,8 @@
<h3>此处为AI根据学情数据进行的智能分析,从个人成绩和实训时长角度给出分析结果,仅供参考</h3>
</div>
<div class="content">
<div class="analysis">
<el-empty v-if="scoreLoaded && !hasScoreData" class="empty-score" description="暂无成绩数据,暂时无法进行AI学情分析" />
<div v-else class="analysis">
<template v-for="item in dialogue" :key="item.role">
<template v-for="chid in item.child" :key="chid" v-if="item.role == roleId">
<div class="analysis-item" @click="analysis(chid)">{{ chid.name }}</div>
@ -57,21 +58,30 @@ const dialogue = ref([
},
]);
const scoreList = ref([]);
const getScoreList = () => {
const scoreLoaded = ref(false);
const hasScoreData = ref(false);
const hasTeacherScoreData = (row) => {
return Number(row.completedTaskCount || 0) > 0 || moduleMap.some(({ key }) => row[`${key}Score`] !== null && row[`${key}Score`] !== undefined);
};
const getScoreList = async () => {
scoreLoaded.value = false;
scoreList.value = [];
hasScoreData.value = false;
proxy.$cache.session.remove("scoreList");
try {
if (roleId.value == 4) {
indexApi.getStuModuleDetail({ userId: userStore.userInfo.userId }).then((res) => {
scoreList.value = res.data;
proxy.$cache.session.setJSON("scoreList", scoreList.value);
});
const res = await indexApi.getStuModuleDetail({ userId: userStore.userInfo.userId });
scoreList.value = Array.isArray(res?.data) ? res.data : [];
hasScoreData.value = scoreList.value.length > 0;
} else {
scoreApi
.getScoreList({
const res = await scoreApi.getScoreList({
index: 1,
size: 1000,
schoolId: userStore.userInfo.schoolId,
})
.then((res) => {
const transformedData = res.data.list.map((item) => ({
});
const rows = Array.isArray(res?.data?.list) ? res.data.list : [];
hasScoreData.value = rows.some(hasTeacherScoreData);
scoreList.value = rows.map((item) => ({
name: item.name,
className: item.className,
schoolId: item.schoolId,
@ -84,12 +94,26 @@ const getScoreList = () => {
totalRank: item.stuRank || null,
})),
}));
proxy.$cache.session.setJSON("scoreList", transformedData);
});
}
if (hasScoreData.value) {
proxy.$cache.session.setJSON("scoreList", scoreList.value);
} else {
proxy.$message.warning("暂无成绩数据,暂时无法进行AI学情分析");
}
} catch (error) {
proxy.$message.error("成绩数据加载失败,请稍后重试");
} finally {
scoreLoaded.value = true;
}
};
// 分析
const analysis = (val) => {
if (!scoreLoaded.value) {
return proxy.$message.warning("成绩数据正在加载,请稍候");
}
if (!hasScoreData.value) {
return proxy.$message.warning("暂无成绩数据,暂时无法进行AI学情分析");
}
proxy.$cache.session.setJSON("msg", val.msg);
router.push("/ai/learning-situation-dialogue");
};
@ -165,6 +189,13 @@ onMounted(() => {
background: linear-gradient(-90deg, #1160ff 0%, #1994ff 100%);
}
}
.empty-score {
height: 100%;
--el-empty-description-margin-top: 16px;
:deep(.el-empty__description p) {
color: #ffffff;
}
}
.brief-introduction {
display: flex;
justify-content: center;

@ -159,16 +159,20 @@ const gInterrupt = () => {
}
};
// 获取分析
const getAnalysis = () => {
const getAnalysis = async () => {
loading.value = true;
AI.getLearningAnalysis({ stuNeed: proxy.$cache.session.getJSON("msg"), stuData: proxy.$cache.session.getJSON("scoreList") }).then((res) => {
try {
const res = await AI.getLearningAnalysis({ stuNeed: proxy.$cache.session.getJSON("msg"), stuData: proxy.$cache.session.getJSON("scoreList") });
messages.value.push({
id: Date.now(),
role: "assistant",
content: res,
});
} catch (error) {
proxy.$message.error("AI学情分析暂时不可用,请稍后重试");
} finally {
loading.value = false;
});
}
};
// 计算高度的函数
const updateHeight = () => {

@ -1,21 +0,0 @@
const LESSON_PLAN_MODULES = [
"互联网产品开发基础认知",
"市场洞察与需求分析",
"产品规划与设计",
"产品开发与测试验证",
"产品上线与运营推广",
"综合实训",
];
function buildTeachingPlanPrompt(moduleName) {
return `请为“互联网产品开发实训课程”的“${moduleName}”模块生成一份实训教案。
请按以下结构输出:
1. 教学目标
2. 实训任务
3. 实施步骤
4. 预期成果
5. 评价要点
内容应贴合互联网产品开发的真实业务场景,并给出可直接用于课堂组织的说明。`;
}
module.exports = { LESSON_PLAN_MODULES, buildTeachingPlanPrompt };

@ -0,0 +1,34 @@
const LESSON_PLAN_MODULES = [
"互联网产品开发基础认知",
"市场洞察与需求分析",
"产品规划与设计",
"产品开发与测试验证",
"产品上线与运营推广",
"综合实训",
];
function buildTeachingPlanPrompt(moduleName) {
return `请为“互联网产品开发实训课程”的“${moduleName}”模块生成一份实训教案。
请按以下结构输出:
1. 教学目标
2. 实训任务
3. 实施步骤
4. 预期成果
5. 评价要点
内容应贴合互联网产品开发的真实业务场景,并给出可直接用于课堂组织的说明。`;
}
function buildTeachingPlanRequest(moduleName, prompt, templateName, templateContent) {
const normalizedPrompt = String(prompt || buildTeachingPlanPrompt(moduleName)).trim();
const normalizedTemplate = String(templateContent || "").trim();
if (!normalizedTemplate) return normalizedPrompt;
return `${normalizedPrompt}
以下为学校参考模板“${String(templateName || "未命名模板").trim()}”的正文内容。请优先遵循模板中的章节结构、字段和校内要求,不要遗漏必填项;模板中的示例内容仅作格式参考:
--- 参考模板开始 ---
${normalizedTemplate}
--- 参考模板结束 ---`;
}
export { LESSON_PLAN_MODULES, buildTeachingPlanPrompt, buildTeachingPlanRequest };

@ -1,106 +1,773 @@
<!--
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-03-27 13:40:09
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-16 17:00:58
* @FilePath: \corporate-finance\src\components\AI\stu-analysis-of-students.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
<div class="stu-analysis-of-students">
<div class="handren-title">
<h3>此处为AI根据实训模块内容智能生成的实训教案,仅供参考</h3>
</div>
<div class="content">
<div class="teaching-plan">
<template v-for="(item, index) in dialogue" :key="item">
<div :style="{ background: col[index] }" class="teaching-plan-item" @click="generateTeachingPlan(item)">{{ item }}</div>
<main class="lesson-plan-page">
<header class="lesson-plan-hero">
<div>
<span class="eyebrow">AI · TEACHING STUDIO</span>
<h1>AI 实训教案</h1>
<p>选择实训模块,结合学校模板和教学要求,在生成前完成提示词配置。</p>
</div>
<ol class="workflow" aria-label="教案生成流程">
<li><b>01</b><span>选择模块</span></li>
<li><b>02</b><span>配置要求</span></li>
<li><b>03</b><span>确认生成</span></li>
</ol>
</header>
<section class="module-section" aria-labelledby="module-heading">
<div class="section-heading">
<div>
<span>实训课程模块</span>
<h2 id="module-heading">从一个模块开始备课</h2>
</div>
<p>AI 生成内容仅供参考,请老师结合实际授课安排审核调整。</p>
</div>
<div class="module-grid">
<button
v-for="(item, index) in dialogue"
:key="item"
type="button"
class="module-card"
:style="{ '--module-accent': col[index] }"
@click="openLessonPlanSetup(item, index)"
>
<span class="module-index">{{ String(index + 1).padStart(2, "0") }}</span>
<span class="module-card__content">
<small>MODULE {{ String(index + 1).padStart(2, "0") }}</small>
<strong>{{ item }}</strong>
<em>配置生成要求 <span aria-hidden="true">→</span></em>
</span>
</button>
</div>
</section>
<el-dialog
v-model="setupVisible"
class="lesson-plan-dialog"
width="860px"
destroy-on-close
:close-on-click-modal="false"
>
<template #header>
<div class="dialog-heading">
<span class="dialog-module-index">{{ selectedModuleNumber }}</span>
<div>
<small>生成前配置</small>
<h2>{{ selectedModule }}</h2>
</div>
</div>
</template>
<div class="setup-layout">
<section class="prompt-panel">
<div class="panel-title">
<div>
<span>参考提示词</span>
<p>可按学校课程标准、课时安排和评价方式直接修改。</p>
</div>
<button type="button" class="text-action" @click="resetPrompt">恢复默认</button>
</div>
<el-input
v-model="customPrompt"
type="textarea"
:rows="12"
maxlength="6000"
show-word-limit
resize="none"
aria-label="教案生成提示词"
/>
</section>
<aside class="template-panel">
<div class="panel-title">
<div>
<span>学校参考模板</span>
<p>模板正文将随提示词用于本次生成。</p>
</div>
</div>
<input
ref="templateInput"
class="visually-hidden"
type="file"
accept=".docx,.txt,.md,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,text/markdown"
@change="handleTemplateChange"
/>
<div
v-if="!templateFileName"
class="template-dropzone"
:class="{ 'is-reading': readingTemplate }"
role="button"
tabindex="0"
@click="templateInput?.click()"
@keydown.enter.prevent="templateInput?.click()"
@keydown.space.prevent="templateInput?.click()"
@dragover.prevent
@drop.prevent="handleTemplateDrop"
>
<span class="upload-mark" aria-hidden="true">↑</span>
<strong>{{ readingTemplate ? "正在读取模板…" : "上传参考模板" }}</strong>
<p>拖放或点击选择 DOCX、TXT、MD</p>
<small>单个文件不超过 10MB,仅用于本次生成</small>
</div>
<div v-else class="template-file">
<span class="file-badge">{{ templateExtension }}</span>
<div>
<strong :title="templateFileName">{{ templateFileName }}</strong>
<p>已读取 {{ templateCharacterCount }} 个字符</p>
</div>
<button type="button" aria-label="移除参考模板" @click="removeTemplate">×</button>
</div>
<div class="template-note">
<b>提示</b>
<p>建议模板包含教学目标、课时、教学过程、成果要求和评价标准。</p>
</div>
</aside>
</div>
<template #footer>
<div class="dialog-footer">
<span>生成后仍可在 AI 对话中继续修改教案。</span>
<div>
<el-button @click="setupVisible = false">取消</el-button>
<el-button type="primary" :disabled="!customPrompt.trim() || readingTemplate" @click="generateTeachingPlan">
生成教案
</el-button>
</div>
</div>
</template>
</el-dialog>
</main>
</template>
<script setup>
import { LESSON_PLAN_MODULES, buildTeachingPlanPrompt } from "./lessonPlanPrompt.cjs";
import JSZip from "jszip";
import {
LESSON_PLAN_MODULES,
buildTeachingPlanPrompt,
buildTeachingPlanRequest,
} from "./lessonPlanPrompt.mjs";
const { proxy } = getCurrentInstance();
const router = useRouter();
const dialogue = LESSON_PLAN_MODULES;
const col = ["#4db7c1", "#3169b5", "#d8a03b", "#6570e3", "#ed8989", "#46a8b2", "#2f66b1"];
const generateTeachingPlan = (val) => {
const col = ["#48d5ca", "#4a8dff", "#f6b84a", "#8b7cff", "#ff8294", "#3fc0dd"];
const MAX_TEMPLATE_SIZE = 10 * 1024 * 1024;
const MAX_TEMPLATE_CHARACTERS = 30000;
const setupVisible = ref(false);
const selectedModule = ref("");
const selectedModuleIndex = ref(0);
const customPrompt = ref("");
const templateInput = ref(null);
const templateFileName = ref("");
const templateContent = ref("");
const readingTemplate = ref(false);
const selectedModuleNumber = computed(() => String(selectedModuleIndex.value + 1).padStart(2, "0"));
const templateExtension = computed(() => templateFileName.value.split(".").pop()?.toUpperCase() || "FILE");
const templateCharacterCount = computed(() => templateContent.value.length.toLocaleString("zh-CN"));
function openLessonPlanSetup(moduleName, index) {
selectedModule.value = moduleName;
selectedModuleIndex.value = index;
customPrompt.value = buildTeachingPlanPrompt(moduleName);
removeTemplate();
setupVisible.value = true;
}
function resetPrompt() {
customPrompt.value = buildTeachingPlanPrompt(selectedModule.value);
}
function removeTemplate() {
templateFileName.value = "";
templateContent.value = "";
if (templateInput.value) templateInput.value.value = "";
}
async function extractDocxText(file) {
const archive = await JSZip.loadAsync(file);
const documentFile = archive.file("word/document.xml");
if (!documentFile) throw new Error("未找到 Word 正文,请检查模板文件");
const xml = await documentFile.async("string");
const documentXml = new DOMParser().parseFromString(xml, "application/xml");
if (documentXml.querySelector("parsererror")) throw new Error("Word 模板解析失败");
return Array.from(documentXml.getElementsByTagNameNS("*", "p"))
.map((paragraph) => Array.from(paragraph.getElementsByTagNameNS("*", "t"))
.map((node) => node.textContent)
.join(""))
.filter(Boolean)
.join("\n");
}
async function readTemplate(file) {
if (!file) return;
const extension = file.name.split(".").pop()?.toLowerCase();
if (!["docx", "txt", "md"].includes(extension)) {
proxy.$message.error("请上传 DOCX、TXT 或 MD 格式的参考模板");
if (templateInput.value) templateInput.value.value = "";
return;
}
if (file.size > MAX_TEMPLATE_SIZE) {
proxy.$message.error("参考模板不能超过 10MB");
if (templateInput.value) templateInput.value.value = "";
return;
}
readingTemplate.value = true;
try {
const rawText = extension === "docx" ? await extractDocxText(file) : await file.text();
const normalizedText = rawText.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
if (!normalizedText) throw new Error("模板中没有可读取的文字内容");
templateFileName.value = file.name;
templateContent.value = normalizedText.slice(0, MAX_TEMPLATE_CHARACTERS);
if (normalizedText.length > MAX_TEMPLATE_CHARACTERS) {
proxy.$message.warning("模板内容较长,本次生成读取前 30000 个字符");
} else {
proxy.$message.success("参考模板读取成功");
}
} catch (error) {
removeTemplate();
proxy.$message.error(error?.message || "参考模板读取失败");
} finally {
readingTemplate.value = false;
}
}
function handleTemplateChange(event) {
readTemplate(event.target.files?.[0]);
}
function handleTemplateDrop(event) {
readTemplate(event.dataTransfer?.files?.[0]);
}
function generateTeachingPlan() {
const prompt = customPrompt.value.trim();
if (!prompt) {
proxy.$message.warning("请填写教案生成提示词");
return;
}
proxy.$cache.session.remove("scoreList");
proxy.$cache.session.remove("msg");
proxy.$cache.session.setJSON("teachingPlan", buildTeachingPlanPrompt(val));
proxy.$cache.session.setJSON("teachingPlan", buildTeachingPlanRequest(
selectedModule.value,
prompt,
templateFileName.value,
templateContent.value,
));
router.push("/ai/learning-situation-dialogue");
};
onMounted(() => {});
}
</script>
<style lang='scss' scoped>
.stu-analysis-of-students {
padding: 20px 40px;
height: calc(100vh - 2.5rem);
position: relative;
background: url("@/assets/images/背景.webp") no-repeat;
background-size: 100% 100%;
.handren-title {
text-align: center;
h3 {
font-size: 1.5rem;
line-height: 2.5rem;
margin-top: 0px;
color: #ffffff;
font-weight: 600;
}
}
.content {
color: #ffffff;
margin-top: 4rem;
height: calc(100vh - 200px);
padding: 0px 10rem;
.teaching-plan {
<style lang="scss" scoped>
.lesson-plan-page {
--panel: rgba(2, 20, 48, 0.82);
--line: rgba(92, 180, 255, 0.22);
--muted: #91acc5;
min-height: calc(100vh - 50px);
padding: clamp(22px, 3vw, 46px);
overflow: auto;
color: #f5fbff;
background:
radial-gradient(circle at 84% 2%, rgba(40, 128, 224, 0.2), transparent 32%),
linear-gradient(rgba(2, 17, 39, 0.88), rgba(2, 13, 31, 0.94)),
url("@/assets/images/背景.webp") center / cover fixed;
}
.lesson-plan-hero {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 32px;
width: min(1120px, 100%);
margin: 0 auto clamp(24px, 4vh, 44px);
h1 {
margin: 8px 0 10px;
font-family: "Microsoft YaHei UI", "Microsoft YaHei", sans-serif;
font-size: clamp(30px, 3.2vw, 48px);
letter-spacing: -0.04em;
}
p {
max-width: 620px;
margin: 0;
color: var(--muted);
font-size: clamp(14px, 1.3vw, 17px);
line-height: 1.8;
}
}
.eyebrow {
color: #59e5dd;
font: 600 12px/1 "Consolas", monospace;
letter-spacing: 0.16em;
}
.workflow {
display: flex;
gap: 24px;
margin: 0;
padding: 0;
list-style: none;
li {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
justify-content: center;
gap: 7rem;
flex-wrap: wrap;
.teaching-plan-item {
gap: 8px;
min-width: 92px;
color: var(--muted);
font-size: 13px;
}
b {
color: #59e5dd;
font: 600 12px/1 "Consolas", monospace;
}
}
.module-section {
width: min(1120px, 100%);
margin: 0 auto;
}
.section-heading {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
span {
color: #59e5dd;
font-size: 13px;
}
h2 {
margin: 5px 0 0;
font-size: clamp(20px, 2vw, 28px);
}
> p {
max-width: 390px;
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.7;
text-align: right;
}
}
.module-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: clamp(14px, 2vw, 24px);
}
.module-card {
position: relative;
min-width: 13rem;
height: 10rem;
border-radius: 8px;
padding: 0px 1rem;
background: #ffffff;
display: flex;
align-items: flex-start;
gap: 18px;
min-width: 0;
min-height: 150px;
padding: 24px;
overflow: hidden;
color: inherit;
text-align: left;
background: linear-gradient(145deg, rgba(7, 35, 69, 0.95), rgba(3, 20, 45, 0.9));
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: 0 18px 40px rgba(0, 4, 17, 0.2);
cursor: pointer;
transition: transform 180ms ease, border-color 180ms ease, box-shadow 180ms ease;
&::after {
content: "";
position: absolute;
right: -32px;
bottom: -52px;
width: 135px;
height: 135px;
background: radial-gradient(circle, var(--module-accent) 0, transparent 68%);
opacity: 0.2;
transition: opacity 180ms ease, transform 180ms ease;
}
&:hover,
&:focus-visible {
border-color: var(--module-accent);
box-shadow: 0 18px 42px rgba(0, 8, 26, 0.42);
outline: none;
transform: translateY(-4px);
}
&:hover::after,
&:focus-visible::after {
opacity: 0.38;
transform: scale(1.12);
}
}
.module-index,
.dialog-module-index {
display: inline-grid;
flex: 0 0 44px;
width: 44px;
height: 44px;
place-items: center;
color: #031425;
background: var(--module-accent, #59e5dd);
border-radius: 12px;
font: 700 14px/1 "Consolas", monospace;
}
.module-card__content {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
small {
color: var(--module-accent);
font: 600 10px/1.2 "Consolas", monospace;
letter-spacing: 0.12em;
}
strong {
min-height: 48px;
margin: 9px 0 12px;
font-size: clamp(16px, 1.35vw, 20px);
line-height: 1.5;
}
em {
color: var(--muted);
font-size: 12px;
font-style: normal;
}
}
:deep(.lesson-plan-dialog) {
max-width: calc(100vw - 32px);
background: #061a31;
border: 1px solid rgba(92, 180, 255, 0.3);
border-radius: 18px;
box-shadow: 0 28px 90px rgba(0, 5, 18, 0.68);
.el-dialog__header {
margin: 0;
padding: 22px 26px 18px;
border-bottom: 1px solid rgba(92, 180, 255, 0.18);
}
.el-dialog__body {
padding: 22px 26px;
color: #eff9ff;
}
.el-dialog__footer {
padding: 16px 26px 22px;
border-top: 1px solid rgba(92, 180, 255, 0.18);
}
.el-dialog__close {
color: #b9d2e8;
}
.el-button {
min-width: 88px;
color: #c5dced !important;
background: #0a2947 !important;
background-image: none !important;
border: 1px solid rgba(92, 180, 255, 0.35) !important;
border-radius: 8px !important;
}
.el-button--primary {
color: #031425 !important;
background: #59e5dd !important;
border-color: #59e5dd !important;
font-weight: 700;
}
}
.dialog-heading {
display: flex;
align-items: center;
gap: 14px;
h2 {
margin: 3px 0 0;
color: #f5fbff;
font-size: 20px;
}
small {
color: #59e5dd;
}
}
.dialog-module-index {
--module-accent: #59e5dd;
}
.setup-layout {
display: grid;
grid-template-columns: minmax(0, 1.55fr) minmax(250px, 0.85fr);
gap: 20px;
}
.prompt-panel,
.template-panel {
min-width: 0;
}
.setup-layout > .template-panel {
padding: 0;
color: #eff9ff;
background: transparent;
border: 0;
border-radius: 0;
box-shadow: none;
}
.panel-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
margin-bottom: 13px;
span {
font-weight: 700;
}
p {
margin: 5px 0 0;
color: #8ca9c0;
font-size: 12px;
line-height: 1.5;
}
}
.text-action {
flex: 0 0 auto;
padding: 0;
color: #59e5dd;
background: transparent;
border: 0;
font: inherit;
cursor: pointer;
}
.prompt-panel :deep(.el-textarea__inner) {
padding: 15px 16px;
color: #eaf8ff;
background: #031326;
border: 1px solid rgba(92, 180, 255, 0.24);
border-radius: 12px;
box-shadow: none;
font-family: "Microsoft YaHei UI", "Microsoft YaHei", sans-serif;
line-height: 1.75;
&:focus {
border-color: #59e5dd;
}
}
.template-dropzone {
display: flex;
min-height: 210px;
align-items: center;
justify-content: center;
font-size: 1.5rem;
font-weight: 600;
color: #ffffff;
background: linear-gradient(135deg, #6b46c1 0%, #805ad5 100%);
// 鼠标小手
flex-direction: column;
padding: 22px;
text-align: center;
background: rgba(3, 19, 38, 0.76);
border: 1px dashed rgba(89, 229, 221, 0.48);
border-radius: 14px;
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease;
&:hover,
&:focus-visible {
background: rgba(10, 47, 70, 0.78);
border-color: #59e5dd;
outline: none;
}
p {
margin: 9px 0 5px;
color: #aec5d7;
font-size: 13px;
}
small {
color: #7895ad;
}
}
.upload-mark {
display: grid;
width: 46px;
height: 46px;
margin-bottom: 14px;
place-items: center;
color: #031425;
background: #59e5dd;
border-radius: 14px;
font-size: 25px;
font-weight: 700;
}
.template-file {
display: grid;
grid-template-columns: 48px minmax(0, 1fr) 26px;
align-items: center;
gap: 12px;
min-height: 92px;
padding: 15px;
background: rgba(3, 19, 38, 0.76);
border: 1px solid rgba(89, 229, 221, 0.34);
border-radius: 14px;
strong,
p {
display: block;
overflow: hidden;
&::before {
content: "";
text-overflow: ellipsis;
white-space: nowrap;
}
p {
margin: 6px 0 0;
color: #8ca9c0;
font-size: 12px;
}
button {
color: #a9c2d5;
background: transparent;
border: 0;
font-size: 22px;
cursor: pointer;
}
}
.file-badge {
display: grid;
width: 48px;
height: 48px;
place-items: center;
color: #59e5dd;
background: rgba(89, 229, 221, 0.11);
border-radius: 10px;
font: 700 10px/1 "Consolas", monospace;
}
.template-note {
margin-top: 14px;
padding: 13px 14px;
color: #92aec4;
background: rgba(73, 139, 255, 0.08);
border-left: 2px solid #4a8dff;
border-radius: 0 9px 9px 0;
b {
color: #b9d8ff;
font-size: 12px;
}
p {
margin: 4px 0 0;
font-size: 12px;
line-height: 1.6;
}
}
.dialog-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
> span {
color: #829eb5;
font-size: 12px;
}
}
.visually-hidden {
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(45deg, transparent 0%, rgba(255, 255, 255, 0.1) 45%, rgba(255, 255, 255, 0.5) 50%, rgba(255, 255, 255, 0.1) 55%, transparent 100%);
transform: rotate(45deg);
animation: shine 3s infinite;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 1180px) {
.lesson-plan-page {
padding: 24px 28px;
}
@keyframes shine {
0% {
left: -50%;
.lesson-plan-hero {
align-items: flex-start;
}
.workflow {
gap: 12px;
li {
min-width: auto;
}
100% {
left: 150%;
}
.module-card {
min-height: 136px;
padding: 20px;
}
}
@media (max-width: 900px) {
.lesson-plan-hero,
.section-heading,
.dialog-footer {
align-items: flex-start;
flex-direction: column;
}
.module-grid,
.setup-layout {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.section-heading > p {
text-align: left;
}
}
@media (max-width: 640px) {
.lesson-plan-page {
padding: 20px 16px;
}
.workflow {
width: 100%;
justify-content: space-between;
}
.module-grid,
.setup-layout {
grid-template-columns: 1fr;
}
.module-card {
min-height: 128px;
}
}
</style>

@ -14,22 +14,56 @@
<div class="diagnosis-materials__item"><strong>2.下载Excel模版,填写关键信息,自动计算各环节转化率。提供自动化模版。</strong><div class="diagnosis-materials__actions"><button type="button" class="secondary-button" @click="downloadNodeTemplate">下载Excel模板</button></div></div>
<p class="diagnosis-materials__ai">3.导出数据表上传到通用AI大模型,通过AI大模型辅助完成计算,参考步骤及提示词如下:请根据表格数据,计算从曝光到复购链路节点转化率。</p>
</div>
<section class="section-block"><div class="section-heading"><span>一</span><div><h3>计算各节点转化率</h3><p>根据案例数据计算各个渠道链路节点转化率,参考方法及工具如下:</p></div></div><div class="table-wrap"><table class="funnel-table"><thead><tr><th>链路节点</th><th>天猫</th><th>京东</th><th>抖音</th><th>拼多多</th><th>行业均值</th></tr></thead><tbody><tr v-for="row in conversionRates" :key="row.linkNode"><th>{{ row.linkNode }}</th><td v-for="field in rateFields" :key="field"><el-input-number v-model="row[field]" :min="0" :max="100" :precision="2" :controls="false" :placeholder="row.linkNode === '曝光-点击' && field === 'tmall' ? '示例:11.5%' : '请输入'" /><span class="unit">%</span></td></tr></tbody></table></div></section>
<section class="section-block">
<div class="section-heading"><span>一</span><div><h3>计算各节点转化率</h3><p>根据案例数据计算各个渠道链路节点转化率,参考方法及工具如下:</p></div></div>
<div class="table-toolbar funnel-channel-toolbar">
<span>链路节点和行业均值固定,中间渠道可按案例数据增加或删除。</span>
<button type="button" class="table-button" @click="addFunnelChannel">增加渠道</button>
</div>
<div class="table-wrap">
<table class="funnel-table">
<thead>
<tr>
<th class="fixed-column">链路节点</th>
<th v-for="channel in channels" :key="channel.id" class="channel-column">
<div class="channel-heading">
<el-input v-model="channel.name" maxlength="20" placeholder="填写渠道名称" />
<button type="button" class="channel-remove" :aria-label="`删除${channel.name || '未命名'}渠道`" @click="removeFunnelChannel(channel.id)">×</button>
</div>
</th>
<th class="fixed-column">行业均值</th>
</tr>
</thead>
<tbody>
<tr v-for="row in conversionRates" :key="row.linkNode">
<th>{{ row.linkNode }}</th>
<td v-for="(channel, channelIndex) in channels" :key="channel.id">
<div class="rate-input">
<el-input-number v-model="row.channelRates[channel.id]" :min="0" :max="100" :precision="2" :controls="false" :placeholder="row.linkNode === '曝光-点击' && channelIndex === 0 ? '示例:11.5' : '请输入'" />
<span class="unit">%</span>
</div>
</td>
<td><div class="rate-input"><el-input-number v-model="row.industryAverage" :min="0" :max="100" :precision="2" :controls="false" placeholder="请输入" /><span class="unit">%</span></div></td>
</tr>
</tbody>
</table>
</div>
</section>
<section class="section-block visual-section"><div class="section-heading"><span>二</span><div><h3>全链路转化漏斗可视化</h3><p>根据节点转化率计算结果,绘制各渠道转化率与行业均值的转化漏斗对比图,可视化呈现多环节情况,参考方法及工具如下:</p></div></div><div class="diagnosis-materials" aria-label="第 2 步参考资料"><div class="diagnosis-materials__item"><strong>1.使用Excel绘图功能,自主完成转化漏斗对比图,可参考《实训操作说明》。</strong><div class="diagnosis-materials__actions"><button type="button" class="secondary-button" @click="downloadFunnelGuide">下载实训操作说明</button></div></div><div class="diagnosis-materials__item"><strong>2.下载Excel模版,填写关键信息,自动计算各环节转化率并生成转化漏斗对比图。</strong><div class="diagnosis-materials__actions"><button type="button" class="secondary-button" @click="downloadFunnelTemplate">下载Excel模板</button></div></div><p class="diagnosis-materials__ai">3.导出数据表上传到通用AI大模型,通过AI大模型辅助完成,参考步骤及提示词如下:请根据表格数据绘制漏斗图,并与行业均值漏斗图进行对比。</p></div><input ref="chartInput" class="visually-hidden" type="file" accept="image/png,image/jpeg,image/webp" @change="handleChartUpload" /><div class="chart-upload-area"><template v-if="funnelChart.url"><div class="chart-preview"><el-image :src="funnelChart.url" :preview-src-list="[funnelChart.url]" fit="cover" preview-teleported /><div><strong>{{ funnelChart.name || '节点转化漏斗对比图' }}</strong><span>点击缩略图可放大预览</span><button type="button" @click="clearChart">移除图片</button></div></div><button type="button" class="secondary-button" :disabled="uploading" @click="chartInput?.click()">{{ uploading ? '上传中…' : '更换对比图' }}</button></template><template v-else><button type="button" class="upload-button" :disabled="uploading" @click="chartInput?.click()">{{ uploading ? '上传中…' : '上传节点转化漏斗对比图' }}</button><p>支持 PNG、JPG、WEBP 格式,图片不超过 5MB;上传后可点击预览。</p></template></div></section>
<section class="section-block diagnosis-section"><div class="section-heading"><span>三</span><div><h3>定位异常节点</h3><p>对比案例行业均值数据,定位异常节点。</p></div></div><div class="table-toolbar"><span>对比案例行业均值数据,定位异常节点。</span><div><button type="button" class="table-button" :disabled="anomalyRows.length >= 5" @click="addAnomalyRow">增加一行</button><button type="button" class="table-button ghost" :disabled="anomalyRows.length <= 1" @click="removeAnomalyRow">删除一行</button></div></div><div class="table-wrap"><table class="diagnosis-table"><thead><tr><th>渠道</th><th>链路节点</th><th>店铺转化率</th><th>行业均值转化率</th><th>异常分析与判定</th></tr></thead><tbody><tr v-for="(row, index) in anomalyRows" :key="index"><td><el-select v-model="row.channel" placeholder="请选择"><el-option v-for="channel in channels" :key="channel.key" :label="channel.label" :value="channel.label" /></el-select></td><td><el-select v-model="row.linkNode" placeholder="请选择"><el-option v-for="node in nodes" :key="node" :label="node" :value="node" /></el-select></td><td><el-input-number v-model="row.storeConversionRate" :min="0" :max="100" :precision="2" :controls="false" placeholder="请输入" /><span class="unit">%</span></td><td><el-input-number v-model="row.industryAverageConversionRate" :min="0" :max="100" :precision="2" :controls="false" placeholder="请输入" /><span class="unit">%</span></td><td><el-input v-model="row.anomalyAnalysis" type="textarea" :rows="2" maxlength="300" show-word-limit placeholder="请填写异常原因或正常判定" /></td></tr></tbody></table></div><p class="diagnosis-step-one-notice">说明:这个表格默认展示一行可填写,最少一行,可以增加行,最多5行,这里填写的渠道需要来源于第一个表的渠道。</p></section>
<section class="section-block diagnosis-section"><div class="section-heading"><span>三</span><div><h3>定位异常节点</h3><p>对比案例行业均值数据,定位异常节点。</p></div></div><div class="table-toolbar"><span>对比案例行业均值数据,定位异常节点。</span><div><button type="button" class="table-button" :disabled="anomalyRows.length >= 5" @click="addAnomalyRow">增加一行</button><button type="button" class="table-button ghost" :disabled="anomalyRows.length <= 1" @click="removeAnomalyRow">删除一行</button></div></div><div class="table-wrap"><table class="diagnosis-table"><thead><tr><th>渠道</th><th>链路节点</th><th>店铺转化率</th><th>行业均值转化率</th><th>异常分析与判定</th></tr></thead><tbody><tr v-for="(row, index) in anomalyRows" :key="index"><td><el-select v-model="row.channelId" placeholder="请选择" @change="syncAnomalyChannel(row)"><el-option v-for="channel in availableChannels" :key="channel.id" :label="channel.name" :value="channel.id" /></el-select></td><td><el-select v-model="row.linkNode" placeholder="请选择"><el-option v-for="node in nodes" :key="node" :label="node" :value="node" /></el-select></td><td><div class="rate-input"><el-input-number v-model="row.storeConversionRate" :min="0" :max="100" :precision="2" :controls="false" placeholder="请输入" /><span class="unit">%</span></div></td><td><div class="rate-input"><el-input-number v-model="row.industryAverageConversionRate" :min="0" :max="100" :precision="2" :controls="false" placeholder="请输入" /><span class="unit">%</span></div></td><td><el-input v-model="row.anomalyAnalysis" type="textarea" :rows="2" maxlength="300" show-word-limit placeholder="请填写异常原因或正常判定" /></td></tr></tbody></table></div><p class="diagnosis-step-one-notice">说明:这个表格默认展示一行可填写,最少一行,可以增加行,最多5行,这里填写的渠道需要来源于第一个表的渠道。</p></section>
</template>
<template v-else-if="currentStep === 2">
<p class="lead">漏斗只能定位“哪个环节出了问题”,要回答为什么出问题,需要分析用户最真实的反馈。本步骤通过词云分析和情感倾向分析,从用户评价中提取高频问题,判断整体口碑倾向,验证漏斗异常背后的真实根因。</p>
<section class="section-block"><div class="section-heading"><span>一</span><div><h3>词云分析</h3><p>导入数据,生成词云,基于案例评论数据自动生成高频问题词云。</p></div></div><input ref="commentInput" class="visually-hidden" type="file" accept=".csv,.txt,.xls,.xlsx,text/csv,text/plain,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="handleCommentImport" /><div class="comment-import"><button type="button" class="upload-button" :disabled="analyzing" @click="commentInput?.click()">{{ analyzing ? '正在生成词云…' : '导入评论数据生成词云' }}</button><p>支持 CSV、TXT、XLS、XLSX,文件不超过 5MB。</p><div v-if="commentPreview.fileName" class="data-preview"><div><strong>{{ commentPreview.fileName }}</strong><span>已解析 {{ commentPreview.totalComments }} 条评论 · 数据预览</span></div><ul><li v-for="(comment, index) in commentPreview.comments" :key="index">{{ comment }}</li></ul></div></div><div v-if="wordCloud.length" class="word-cloud-card"><div class="word-cloud-title"><span>高频问题词云</span><small>基于导入评论自动生成</small></div><div ref="wordCloudRef" class="word-cloud" aria-label="评论高频问题词云"></div></div><div class="top-issues"><p>请根据词云图填写词云中出现频次最高的TOP3问题。</p><div><label v-for="(_, index) in topIssues" :key="index">TOP{{ index + 1 }}:<el-input v-model="topIssues[index]" :placeholder="`填写第 ${index + 1} 个高频问题`" /></label></div></div></section>
<section class="section-block"><div class="section-heading"><span>二</span><div><h3>情感倾向分析</h3></div></div><div class="sentiment-actions"><span>点击情感倾向分析后,系统会自动计算正面、中性、负面评论数量及占比,并按校验所需精度保留两位小数。</span><button type="button" class="upload-button" :disabled="!analysisResult" @click="runSentimentAnalysis">情感倾向分析</button></div><div class="table-wrap"><table class="sentiment-table"><thead><tr><th>情感类型</th><th>评论数量(条)</th><th>占比</th></tr></thead><tbody><tr v-for="row in sentiments" :key="row.type"><th>{{ row.type }}</th><td><span class="auto-count">{{ row.count ?? '—' }}</span></td><td><el-input-number v-model="row.percentage" :min="0" :max="100" :precision="2" :controls="false" disabled placeholder="系统自动计算" /><span class="unit">%</span></td></tr></tbody></table></div></section>
<section class="section-block"><div class="section-heading"><span>二</span><div><h3>情感倾向分析</h3></div></div><div class="sentiment-actions"><span>点击情感倾向分析后,系统会自动计算正面、中性、负面评论数量及占比,并按校验所需精度保留两位小数。</span><button type="button" class="upload-button" :disabled="!analysisResult" @click="runSentimentAnalysis">情感倾向分析</button></div><div class="table-wrap"><table class="sentiment-table"><thead><tr><th>情感类型</th><th>评论数量(条)</th><th>占比</th></tr></thead><tbody><tr v-for="row in sentiments" :key="row.type"><th>{{ row.type }}</th><td><span class="auto-count">{{ row.count ?? '—' }}</span></td><td><div class="rate-input"><el-input-number v-model="row.percentage" :min="0" :max="100" :precision="2" :controls="false" disabled placeholder="系统自动计算" /><span class="unit">%</span></div></td></tr></tbody></table></div></section>
<section class="section-block root-cause"><p>请结合词云TOP3与情感分析结果,说明本案例的核心问题根本原因;说明高频问题与情感数据是如何验证步骤一漏斗异常结论的</p><el-input v-model="rootCauseAnalysis" type="textarea" :rows="6" maxlength="1000" show-word-limit placeholder="请填写根因分析与对步骤一异常结论的验证说明" /></section>
</template>
<template v-else>
<p class="lead">找到根因后,还需验证“改进方案是否真的有效”,避免拍脑袋迭代。AB测试对照诊断法将用户随机分为对照组(维持原方案)和实验组(应用改进方案),对比两组的关键指标差异,用数据判断改进方案是否值得落地。</p>
<section class="section-block"><div class="section-heading"><span>(1)</span><div><h3>确定测试方案</h3><p>请基于案例资料,针对步骤一和步骤二分析结果,设计AB测试方案</p></div></div><el-input v-model="abTestPlan" type="textarea" :rows="6" maxlength="1000" show-word-limit placeholder="填写对照组与实验组设置、改进方案、随机分流方式、观察周期和成功判定标准" /></section>
<section class="section-block"><div class="section-heading"><span>(2)</span><div><h3>AB测试数据填报</h3><p>请从案例资料中获取AB测试两组数据,计算后填入下表并逐项判定:</p></div></div><div class="table-wrap"><table class="ab-table"><thead><tr><th>测试指标</th><th>对照组数据</th><th>实验组数据</th><th>判定与分析</th></tr></thead><tbody><tr v-for="row in abRows" :key="row.metric"><th>{{ row.metric }}</th><td><el-input-number v-model="row.controlValue" :min="0" :max="100" :precision="2" :controls="false" placeholder="示例:56%" /><span class="unit">%</span></td><td><el-input-number v-model="row.experimentValue" :min="0" :max="100" :precision="2" :controls="false" placeholder="示例:64%" /><span class="unit">%</span></td><td><el-input v-model="row.analysis" type="textarea" :rows="2" maxlength="300" show-word-limit placeholder="示例:提升8pp,显著提升,采纳" /></td></tr></tbody></table></div></section>
<section class="section-block"><div class="section-heading"><span>(2)</span><div><h3>AB测试数据填报</h3><p>请从案例资料中获取AB测试两组数据,计算后填入下表并逐项判定:</p></div></div><div class="table-wrap"><table class="ab-table"><thead><tr><th>测试指标</th><th>对照组数据</th><th>实验组数据</th><th>判定与分析</th></tr></thead><tbody><tr v-for="row in abRows" :key="row.metric"><th>{{ row.metric }}</th><td><div class="rate-input"><el-input-number v-model="row.controlValue" :min="0" :max="100" :precision="2" :controls="false" placeholder="示例:56%" /><span class="unit">%</span></div></td><td><div class="rate-input"><el-input-number v-model="row.experimentValue" :min="0" :max="100" :precision="2" :controls="false" placeholder="示例:64%" /><span class="unit">%</span></div></td><td><el-input v-model="row.analysis" type="textarea" :rows="2" maxlength="300" show-word-limit placeholder="示例:提升8pp,显著提升,采纳" /></td></tr></tbody></table></div></section>
<section class="section-block"><div class="section-heading"><span>(3)</span><div><h3>可视化呈现</h3><p>绘制AB测试结果对比图,参考方法及工具如下:</p></div></div><input ref="abChartInput" class="visually-hidden" type="file" accept="image/png,image/jpeg,image/webp" @change="handleAbChartUpload" /><div class="chart-upload-area"><template v-if="abChart.url"><div class="chart-preview"><el-image :src="abChart.url" :preview-src-list="[abChart.url]" fit="cover" preview-teleported /><div><strong>{{ abChart.name || 'AB 测试结果对比图' }}</strong><span>点击缩略图可放大预览</span><button type="button" @click="clearAbChart">移除图片</button></div></div><button type="button" class="secondary-button" :disabled="uploading" @click="abChartInput?.click()">{{ uploading ? '上传中…' : '更换对比图' }}</button></template><template v-else><button type="button" class="upload-button" :disabled="uploading" @click="abChartInput?.click()">{{ uploading ? '上传中…' : '上传AB测试结果对比图' }}</button><p>支持 PNG、JPG、WEBP 格式,图片不超过 5MB;上传后可点击预览。</p></template></div><div class="ab-materials"><div><ol><li>1.使用Excel/WPS绘图功能,自主完成AB测试结果对比图,参考《实训操作说明》。</li><li>2.下载Excel模版,填写关键信息,自动计算AB测试数据,并生成测试结果对比图。</li><li>3.导出数据表上传到通用AI大模型,通过AI大模型辅助完成,参考步骤及提示词如下:请根据表格数据,进行对照组和实验组数据对比,采用组合柱状图生成可视化图形。</li></ol></div><div class="ab-materials__actions"><button type="button" class="secondary-button" @click="downloadAbGuide">下载实训操作说明</button><button type="button" class="secondary-button" @click="downloadAbTemplate">下载Excel模板</button></div></div></section>
<section class="section-block"><div class="section-heading"><span>(4)</span><div><h3>诊断结论与迭代优化建议</h3><p>结合全链路数据漏斗诊断、售后评论分析法及AB测试对照诊断,分析产品存在的问题,并提出具体的迭代优化建议。</p></div></div><el-input v-model="iterationRecommendation" type="textarea" :rows="6" maxlength="1200" show-word-limit placeholder="请填写产品问题诊断结论及具体迭代优化建议" /></section>
</template>
@ -65,14 +99,84 @@ function downloadFunnelGuide() { downloadBuiltInFile(FUNNEL_GUIDE_URL); }
function downloadFunnelTemplate() { downloadBuiltInFile(FUNNEL_TEMPLATE_URL); }
function downloadAbGuide() { downloadBuiltInFile(AB_TEST_GUIDE_URL); }
function downloadAbTemplate() { downloadBuiltInFile(AB_TEST_TEMPLATE_URL); }
const TASK_KEY = "product-diagnosis-iteration"; const nodes = ["曝光-点击", "点击-加购", "加购-下单", "下单-好评", "好评-复购"]; const channels = [{ key: "tmall", label: "天猫" }, { key: "jd", label: "京东" }, { key: "douyin", label: "抖音" }, { key: "pinduoduo", label: "拼多多" }]; const rateFields = [...channels.map((item) => item.key), "industryAverage"];
const TASK_KEY = "product-diagnosis-iteration";
const nodes = ["曝光-点击", "点击-加购", "加购-下单", "下单-好评", "好评-复购"];
const defaultChannels = [{ id: "tmall", name: "天猫" }, { id: "jd", name: "京东" }, { id: "douyin", name: "抖音" }, { id: "pinduoduo", name: "拼多多" }];
let channelSerial = 0;
const { proxy } = getCurrentInstance(); const taskConfig = ref(null); const currentStep = ref(1); const saving = ref(false); const uploading = ref(false); const analyzing = ref(false); const chartInput = ref(null); const commentInput = ref(null); const abChartInput = ref(null); const wordCloudRef = ref(null); let wordCloudChart = null;
const channels = ref(createDefaultChannels());
const conversionRates = ref(createConversionRates()); const anomalyRows = ref([createAnomalyRow()]); const funnelChart = ref({ url: "", name: "" }); const analysisResult = ref(null); const commentPreview = ref({ fileName: "", totalComments: 0, comments: [] }); const wordCloud = ref([]); const topIssues = ref(["", "", ""]); const sentiments = ref(createSentiments()); const rootCauseAnalysis = ref(""); const abTestPlan = ref(""); const abRows = ref(createAbRows()); const abChart = ref({ url: "", name: "" }); const iterationRecommendation = ref("");
const taskTitle = computed(() => taskConfig.value?.taskName || "产品问题诊断与迭代"); const taskBackground = computed(() => taskConfig.value?.background || "从曝光到复购的完整数据漏斗与用户评价出发,定位异常流失并形成迭代方向。"); const taskRequirement = computed(() => taskConfig.value?.requirements || "完成转化漏斗诊断、用户评论词云和情感根因分析。"); const taskGoals = computed(() => parseTrainingArray(taskConfig.value?.objectives, ["掌握全链路转化率计算方法", "能够将店铺数据与行业均值进行对比", "从用户评价中定位问题根因"]));
const progressItems = computed(() => currentStep.value === 1 ? [{ text: "填写五个节点的渠道转化率", status: conversionRates.value.every((row) => rateFields.every((field) => row[field] !== null && row[field] !== "" && Number.isFinite(Number(row[field])))) ? "done" : "doing" }, { text: "上传节点转化漏斗对比图", status: funnelChart.value.url ? "done" : "" }, { text: "完成异常节点分析", status: anomalyRows.value.every((row) => row.anomalyAnalysis?.trim()) ? "done" : "" }] : currentStep.value === 2 ? [{ text: "导入评论数据并生成词云", status: analysisResult.value ? "done" : "doing" }, { text: "完成情感倾向分析", status: sentiments.value.every((row) => row.count !== null) ? "done" : "" }, { text: "填写根因分析", status: rootCauseAnalysis.value.trim() ? "done" : "" }] : [{ text: "设计 AB 测试方案", status: abTestPlan.value.trim() ? "done" : "doing" }, { text: "填写五项对照数据", status: abRows.value.every((row) => row.controlValue !== null && row.experimentValue !== null && row.analysis?.trim()) ? "done" : "" }, { text: "上传 AB 对比图", status: abChart.value.url ? "done" : "" }, { text: "提交迭代优化建议", status: iterationRecommendation.value.trim() ? "done" : "" }]);
function createConversionRates() { return nodes.map((linkNode) => ({ linkNode, tmall: null, jd: null, douyin: null, pinduoduo: null, industryAverage: null })); } function createAnomalyRow() { return { channel: "", linkNode: "", storeConversionRate: null, industryAverageConversionRate: null, anomalyAnalysis: "" }; } function createSentiments() { return ["正面", "中性", "负面"].map((type) => ({ type, count: null, percentage: null })); } function createAbRows() { return ["点击-加购转化率", "加购-下单转化率", "下单-好评转化率", "详情页跳出率", "退货率"].map((metric) => ({ metric, controlValue: null, experimentValue: null, analysis: "" })); }
function buildStepOne() { return { conversionRates: conversionRates.value.map((row) => ({ ...row })), funnelChartUrl: funnelChart.value.url, funnelChartName: funnelChart.value.name, anomalyRows: anomalyRows.value.map((row) => ({ ...row })) }; } function buildStepTwo() { return { sourceFileName: commentPreview.value.fileName, topIssues: [...topIssues.value], sentiments: sentiments.value.map((row) => ({ ...row })), rootCauseAnalysis: rootCauseAnalysis.value, wordCloud: wordCloud.value, previewComments: commentPreview.value.comments }; } function buildStepThree() { return { testPlan: abTestPlan.value, rows: abRows.value.map((row) => ({ ...row })), comparisonChartUrl: abChart.value.url, comparisonChartName: abChart.value.name, iterationRecommendation: iterationRecommendation.value }; }
function addAnomalyRow() { if (anomalyRows.value.length < 5) anomalyRows.value.push(createAnomalyRow()); } function removeAnomalyRow() { if (anomalyRows.value.length > 1) anomalyRows.value.pop(); } function clearChart() { if (funnelChart.value.url.startsWith("blob:")) URL.revokeObjectURL(funnelChart.value.url); funnelChart.value = { url: "", name: "" }; }
const availableChannels = computed(() => channels.value.filter((channel) => channel.name.trim()));
const funnelRatesComplete = computed(() => {
const names = availableChannels.value.map((channel) => channel.name.trim());
if (!channels.value.length || names.length !== channels.value.length || new Set(names).size !== names.length) return false;
return conversionRates.value.every((row) => isRate(row.industryAverage) && channels.value.every((channel) => isRate(row.channelRates[channel.id])));
});
const progressItems = computed(() => currentStep.value === 1 ? [{ text: "填写五个节点的渠道转化率", status: funnelRatesComplete.value ? "done" : "doing" }, { text: "上传节点转化漏斗对比图", status: funnelChart.value.url ? "done" : "" }, { text: "完成异常节点分析", status: anomalyRows.value.every((row) => row.anomalyAnalysis?.trim()) ? "done" : "" }] : currentStep.value === 2 ? [{ text: "导入评论数据并生成词云", status: analysisResult.value ? "done" : "doing" }, { text: "完成情感倾向分析", status: sentiments.value.every((row) => row.count !== null) ? "done" : "" }, { text: "填写根因分析", status: rootCauseAnalysis.value.trim() ? "done" : "" }] : [{ text: "设计 AB 测试方案", status: abTestPlan.value.trim() ? "done" : "doing" }, { text: "填写五项对照数据", status: abRows.value.every((row) => row.controlValue !== null && row.experimentValue !== null && row.analysis?.trim()) ? "done" : "" }, { text: "上传 AB 对比图", status: abChart.value.url ? "done" : "" }, { text: "提交迭代优化建议", status: iterationRecommendation.value.trim() ? "done" : "" }]);
function createDefaultChannels() { return defaultChannels.map((channel) => ({ ...channel })); }
function createConversionRates(channelList = channels.value) { return nodes.map((linkNode) => ({ linkNode, channelRates: Object.fromEntries(channelList.map((channel) => [channel.id, null])), industryAverage: null })); }
function createAnomalyRow() { return { channelId: "", channel: "", linkNode: "", storeConversionRate: null, industryAverageConversionRate: null, anomalyAnalysis: "" }; }
function createSentiments() { return ["正面", "中性", "负面"].map((type) => ({ type, count: null, percentage: null })); }
function createAbRows() { return ["点击-加购转化率", "加购-下单转化率", "下单-好评转化率", "详情页跳出率", "退货率"].map((metric) => ({ metric, controlValue: null, experimentValue: null, analysis: "" })); }
function isRate(value) { return value !== null && value !== "" && Number.isFinite(Number(value)); }
function diagnosisErrorMessage(error, fallback) {
const serverMessage = String(error?.response?.data?.msg || "").trim();
const message = serverMessage || String(error?.message || "").trim();
return /Request failed with status code|系统接口\d{3}异常/i.test(message) ? fallback : message || fallback;
}
function buildStepOne() {
const channelSnapshot = channels.value.map((channel) => ({ id: channel.id, name: channel.name.trim() }));
return {
channels: channelSnapshot,
conversionRates: conversionRates.value.map((row) => ({ linkNode: row.linkNode, channelRates: { ...row.channelRates }, industryAverage: row.industryAverage })),
funnelChartUrl: funnelChart.value.url,
funnelChartName: funnelChart.value.name,
anomalyRows: anomalyRows.value.map((row) => ({ ...row, channel: channelSnapshot.find((channel) => channel.id === row.channelId)?.name || row.channel || "" })),
};
}
function buildStepTwo() {
return {
sourceFileName: commentPreview.value.fileName,
totalComments: commentPreview.value.totalComments,
topIssues: [...topIssues.value],
sentiments: sentiments.value.map((row) => ({ ...row })),
rootCauseAnalysis: rootCauseAnalysis.value,
wordCloud: wordCloud.value,
previewComments: commentPreview.value.comments,
analysisResult: analysisResult.value ? { ...analysisResult.value } : null,
};
}
function buildStepTwoValidationPayload(stepTwo = buildStepTwo()) {
return {
sourceFileName: stepTwo.sourceFileName,
topIssues: stepTwo.topIssues,
sentiments: stepTwo.sentiments,
rootCauseAnalysis: stepTwo.rootCauseAnalysis,
};
}
function buildStepThree() { return { testPlan: abTestPlan.value, rows: abRows.value.map((row) => ({ ...row })), comparisonChartUrl: abChart.value.url, comparisonChartName: abChart.value.name, iterationRecommendation: iterationRecommendation.value }; }
function addFunnelChannel() {
channelSerial += 1;
const channel = { id: `channel-${Date.now()}-${channelSerial}`, name: "" };
channels.value.push(channel);
conversionRates.value.forEach((row) => { row.channelRates[channel.id] = null; });
}
function removeFunnelChannel(channelId) {
channels.value = channels.value.filter((channel) => channel.id !== channelId);
conversionRates.value.forEach((row) => { delete row.channelRates[channelId]; });
anomalyRows.value.forEach((row) => {
if (row.channelId === channelId) {
row.channelId = "";
row.channel = "";
row.storeConversionRate = null;
}
});
}
function syncAnomalyChannel(row) { row.channel = channels.value.find((channel) => channel.id === row.channelId)?.name.trim() || ""; }
function addAnomalyRow() { if (anomalyRows.value.length < 5) anomalyRows.value.push(createAnomalyRow()); }
function removeAnomalyRow() { if (anomalyRows.value.length > 1) anomalyRows.value.pop(); }
function clearChart() { if (funnelChart.value.url.startsWith("blob:")) URL.revokeObjectURL(funnelChart.value.url); funnelChart.value = { url: "", name: "" }; }
async function handleChartUpload(event) { const file = event.target?.files?.[0]; if (!file) return; const accepted = ["image/jpeg", "image/png", "image/webp"]; if (!accepted.includes(file.type) || file.size > 5 * 1024 * 1024) { proxy?.$modal?.msgError?.("请上传不超过 5MB 的 PNG、JPG 或 WEBP 图片"); event.target.value = ""; return; } uploading.value = true; try { let url = ""; if (isStudentDemo()) url = URL.createObjectURL(file); else { const data = new FormData(); data.append("file", file); const response = await uploadStudentTrainingFile(data); url = response?.url || response?.data?.url || ""; } if (!url) throw new Error("上传成功但未返回图片地址"); clearChart(); funnelChart.value = { url, name: file.name }; proxy?.$modal?.msgSuccess?.("漏斗对比图上传成功,可点击图片预览"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "图片上传失败,请重试"); } finally { uploading.value = false; event.target.value = ""; } }
async function saveStepOneDraft() { await persistStepOne(false); } async function validateStepOne() { if (saving.value) return; saving.value = true; try { const data = buildStepOne(); await validateProductDiagnosisIterationStepOne(data); await saveStudentTrainingAnswer(TASK_KEY, { step1Answer: JSON.stringify(data), currentStep: 2, submitted: false, saveAction: "SAVE" }); currentStep.value = 2; proxy?.$modal?.msgSuccess?.("第 1 步校验通过,已进入第 2 步"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "请检查第 1 步填写内容"); } finally { saving.value = false; } } async function persistStepOne(showMessage) { if (saving.value) return; saving.value = true; try { await saveStudentTrainingAnswer(TASK_KEY, { step1Answer: JSON.stringify(buildStepOne()), currentStep: 1, submitted: false, saveAction: "SAVE" }); if (showMessage !== false) proxy?.$modal?.msgSuccess?.("草稿已保存"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "保存失败,请重试"); } finally { saving.value = false; } }
async function handleCommentImport(event) { const file = event.target?.files?.[0]; if (!file) return; if (!/\.(csv|txt|xls|xlsx)$/i.test(file.name) || file.size > 5 * 1024 * 1024) { proxy?.$modal?.msgError?.("请上传不超过 5MB 的 CSV、TXT、XLS 或 XLSX 评论文件"); event.target.value = ""; return; } analyzing.value = true; try { const result = (await analyzeProductDiagnosisIterationStepTwo(file))?.data; if (!result) throw new Error("未获得评论分析结果"); analysisResult.value = result; commentPreview.value = { fileName: result.sourceFileName || file.name, totalComments: result.totalComments || 0, comments: result.previewComments || [] }; wordCloud.value = result.wordCloud || []; topIssues.value = [0, 1, 2].map((index) => result.topIssues?.[index] || ""); sentiments.value = createSentiments(); await nextTick(); renderWordCloud(); proxy?.$modal?.msgSuccess?.("评论数据已导入,词云已生成"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "评论数据分析失败,请检查文件格式"); } finally { analyzing.value = false; event.target.value = ""; } }
@ -88,7 +192,7 @@ function runSentimentAnalysis() {
}));
proxy?.$modal?.msgSuccess?.("情感评论数量与占比已自动计算");
}
async function saveStepTwoDraft() { if (saving.value) return false; saving.value = true; try { await saveStudentTrainingAnswer(TASK_KEY, { step2Answer: JSON.stringify(buildStepTwo()), currentStep: 2, submitted: false, saveAction: "SAVE" }); proxy?.$modal?.msgSuccess?.("当前步骤已保存"); return true; } catch (error) { proxy?.$modal?.msgError?.(error?.message || "保存失败,请重试"); return false; } finally { saving.value = false; } } async function validateStepTwo() { if (saving.value) return false; saving.value = true; try { const data = buildStepTwo(); await validateProductDiagnosisIterationStepTwo(data); await saveStudentTrainingAnswer(TASK_KEY, { step2Answer: JSON.stringify(data), currentStep: 2, submitted: false, saveAction: "SAVE" }); proxy?.$modal?.msgSuccess?.("第 2 步校验通过,已保存"); return true; } catch (error) { proxy?.$modal?.msgError?.(error?.message || "请检查词云、情感占比和根因分析"); return false; } finally { saving.value = false; } }
async function saveStepTwoDraft() { if (saving.value) return false; saving.value = true; try { await saveStudentTrainingAnswer(TASK_KEY, { step2Answer: JSON.stringify(buildStepTwo()), currentStep: 2, submitted: false, saveAction: "SAVE" }); proxy?.$modal?.msgSuccess?.("当前步骤已保存"); return true; } catch (error) { proxy?.$modal?.msgError?.(error?.message || "保存失败,请重试"); return false; } finally { saving.value = false; } } async function validateStepTwo() { if (saving.value) return false; saving.value = true; try { const data = buildStepTwo(); await validateProductDiagnosisIterationStepTwo(buildStepTwoValidationPayload(data)); await saveStudentTrainingAnswer(TASK_KEY, { step2Answer: JSON.stringify(data), currentStep: 2, submitted: false, saveAction: "SAVE" }); proxy?.$modal?.msgSuccess?.("第 2 步校验通过,已保存"); return true; } catch (error) { proxy?.$modal?.msgError?.(diagnosisErrorMessage(error, "请检查词云、情感占比和根因分析")); return false; } finally { saving.value = false; } }
function clearAbChart() { if (abChart.value.url.startsWith("blob:")) URL.revokeObjectURL(abChart.value.url); abChart.value = { url: "", name: "" }; }
async function handleAbChartUpload(event) { const file = event.target?.files?.[0]; if (!file) return; const accepted = ["image/jpeg", "image/png", "image/webp"]; if (!accepted.includes(file.type) || file.size > 5 * 1024 * 1024) { proxy?.$modal?.msgError?.("请上传不超过 5MB 的 PNG、JPG 或 WEBP 图片"); event.target.value = ""; return; } uploading.value = true; try { let url = ""; if (isStudentDemo()) url = URL.createObjectURL(file); else { const data = new FormData(); data.append("file", file); const response = await uploadStudentTrainingFile(data); url = response?.url || response?.data?.url || ""; } if (!url) throw new Error("上传成功但未返回图片地址"); clearAbChart(); abChart.value = { url, name: file.name }; proxy?.$modal?.msgSuccess?.("AB 测试结果对比图上传成功,可点击图片预览"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "图片上传失败,请重试"); } finally { uploading.value = false; event.target.value = ""; } }
async function saveStepThreeDraft() { if (saving.value) return; saving.value = true; try { await saveStudentTrainingAnswer(TASK_KEY, { step3Answer: JSON.stringify(buildStepThree()), currentStep: 3, submitted: false, saveAction: "SAVE" }); proxy?.$modal?.msgSuccess?.("草稿已保存"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "保存失败,请重试"); } finally { saving.value = false; } }
@ -110,7 +214,7 @@ async function submitTask() {
await validateProductDiagnosisIterationStepOne(stepOne);
await saveStudentTrainingAnswer(TASK_KEY, { step1Answer: JSON.stringify(stepOne), currentStep: 1, submitted: false, saveAction: "SAVE" });
const stepTwo = buildStepTwo();
await validateProductDiagnosisIterationStepTwo(stepTwo);
await validateProductDiagnosisIterationStepTwo(buildStepTwoValidationPayload(stepTwo));
await saveStudentTrainingAnswer(TASK_KEY, { step2Answer: JSON.stringify(stepTwo), currentStep: 2, submitted: false, saveAction: "SAVE" });
const stepThree = buildStepThree();
await validateProductDiagnosisIterationStepThree(stepThree);
@ -119,7 +223,7 @@ async function submitTask() {
proxy?.$modal?.msgSuccess?.("实训任务已提交");
return true;
} catch (error) {
proxy?.$modal?.msgError?.(error?.message || "提交失败,请检查三个步骤的填写内容");
proxy?.$modal?.msgError?.(diagnosisErrorMessage(error, "提交失败,请检查三个步骤的填写内容"));
return false;
} finally {
saving.value = false;
@ -130,7 +234,7 @@ async function resetTraining() {
try {
await deleteStudentTrainingAnswer(TASK_KEY);
clearChart(); clearAbChart(); wordCloudChart?.dispose(); wordCloudChart = null;
conversionRates.value = createConversionRates(); anomalyRows.value = [createAnomalyRow()]; analysisResult.value = null;
channels.value = createDefaultChannels(); conversionRates.value = createConversionRates(); anomalyRows.value = [createAnomalyRow()]; analysisResult.value = null;
commentPreview.value = { fileName: "", totalComments: 0, comments: [] }; wordCloud.value = []; topIssues.value = ["", "", ""]; sentiments.value = createSentiments(); rootCauseAnalysis.value = "";
abTestPlan.value = ""; abRows.value = createAbRows(); iterationRecommendation.value = ""; currentStep.value = 1;
proxy?.$modal?.msgSuccess?.("已清空全部实训步骤,可以重新开始");
@ -146,7 +250,81 @@ function exportTrainingOutcome() {
const link = document.createElement("a"); link.href = url; link.download = "产品问题诊断与迭代-实训成果.json"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url);
proxy?.$modal?.msgSuccess?.("实训成果已导出");
}
function restore(answer) { try { const stepOne = JSON.parse(answer?.step1Answer || "{}"); if (Array.isArray(stepOne.conversionRates) && stepOne.conversionRates.length === nodes.length) conversionRates.value = nodes.map((node) => ({ ...createConversionRates().find((row) => row.linkNode === node), ...(stepOne.conversionRates.find((row) => row?.linkNode === node) || {}) })); if (Array.isArray(stepOne.anomalyRows) && stepOne.anomalyRows.length) anomalyRows.value = stepOne.anomalyRows.slice(0, 5).map((row) => ({ ...createAnomalyRow(), ...row })); if (stepOne.funnelChartUrl) funnelChart.value = { url: stepOne.funnelChartUrl, name: stepOne.funnelChartName || "节点转化漏斗对比图" }; const stepTwo = JSON.parse(answer?.step2Answer || "{}"); if (stepTwo.sourceFileName) { commentPreview.value = { fileName: stepTwo.sourceFileName, totalComments: 0, comments: stepTwo.previewComments || [] }; wordCloud.value = stepTwo.wordCloud || []; topIssues.value = [0, 1, 2].map((index) => stepTwo.topIssues?.[index] || ""); sentiments.value = (stepTwo.sentiments || createSentiments()).map((row) => ({ ...createSentiments().find((item) => item.type === row.type), ...row })); rootCauseAnalysis.value = stepTwo.rootCauseAnalysis || ""; nextTick(renderWordCloud); } const stepThree = JSON.parse(answer?.step3Answer || "{}"); if (stepThree.testPlan || stepThree.comparisonChartUrl || stepThree.iterationRecommendation) { abTestPlan.value = stepThree.testPlan || ""; if (Array.isArray(stepThree.rows) && stepThree.rows.length === createAbRows().length) abRows.value = createAbRows().map((row) => ({ ...row, ...(stepThree.rows.find((item) => item?.metric === row.metric) || {}) })); if (stepThree.comparisonChartUrl) abChart.value = { url: stepThree.comparisonChartUrl, name: stepThree.comparisonChartName || "AB 测试结果对比图" }; iterationRecommendation.value = stepThree.iterationRecommendation || ""; } currentStep.value = [1, 2, 3].includes(Number(answer?.currentStep)) ? Number(answer.currentStep) : 1; } catch (error) {} }
function restoreStepOne(stepOne) {
const hasSavedChannels = Array.isArray(stepOne.channels);
const seenIds = new Set();
const restoredChannels = hasSavedChannels
? stepOne.channels.map((channel) => ({ id: String(channel?.id || "").trim(), name: String(channel?.name || "").trim() })).filter((channel) => {
if (!channel.id || seenIds.has(channel.id)) return false;
seenIds.add(channel.id);
return true;
})
: createDefaultChannels();
channels.value = restoredChannels;
if (Array.isArray(stepOne.conversionRates) && stepOne.conversionRates.length === nodes.length) {
conversionRates.value = nodes.map((linkNode) => {
const saved = stepOne.conversionRates.find((row) => row?.linkNode === linkNode) || {};
return {
linkNode,
channelRates: Object.fromEntries(restoredChannels.map((channel) => [channel.id, saved.channelRates?.[channel.id] ?? saved[channel.id] ?? null])),
industryAverage: saved.industryAverage ?? null,
};
});
} else {
conversionRates.value = createConversionRates(restoredChannels);
}
if (Array.isArray(stepOne.anomalyRows) && stepOne.anomalyRows.length) {
anomalyRows.value = stepOne.anomalyRows.slice(0, 5).map((row) => {
const channelId = String(row?.channelId || restoredChannels.find((channel) => channel.name === row?.channel)?.id || "");
return { ...createAnomalyRow(), ...row, channelId };
});
}
if (stepOne.funnelChartUrl) funnelChart.value = { url: stepOne.funnelChartUrl, name: stepOne.funnelChartName || "节点转化漏斗对比图" };
}
function parseSavedStep(value) {
if (!value) return {};
if (typeof value === "object") return value;
try { return JSON.parse(value); } catch (error) { return {}; }
}
function restoreStepTwo(stepTwo) {
if (!stepTwo || typeof stepTwo !== "object" || !Object.keys(stepTwo).length) return;
const savedAnalysis = stepTwo.analysisResult && typeof stepTwo.analysisResult === "object" ? stepTwo.analysisResult : {};
const restoredWordCloud = Array.isArray(stepTwo.wordCloud) ? stepTwo.wordCloud : Array.isArray(savedAnalysis.wordCloud) ? savedAnalysis.wordCloud : [];
const restoredComments = Array.isArray(stepTwo.previewComments) ? stepTwo.previewComments : Array.isArray(savedAnalysis.previewComments) ? savedAnalysis.previewComments : [];
const restoredTopIssues = [0, 1, 2].map((index) => stepTwo.topIssues?.[index] || savedAnalysis.topIssues?.[index] || "");
const savedSentiments = Array.isArray(stepTwo.sentiments) ? stepTwo.sentiments : [];
sentiments.value = createSentiments().map((row) => ({ ...row, ...(savedSentiments.find((item) => item?.type === row.type) || {}) }));
const count = (type, analysisKey) => {
const analysisCount = Number(savedAnalysis[analysisKey]);
if (Number.isFinite(analysisCount)) return analysisCount;
const sentimentCount = Number(sentiments.value.find((row) => row.type === type)?.count);
return Number.isFinite(sentimentCount) ? sentimentCount : 0;
};
const positiveCount = count("正面", "positiveCount");
const neutralCount = count("中性", "neutralCount");
const negativeCount = count("负面", "negativeCount");
const sourceFileName = String(stepTwo.sourceFileName || savedAnalysis.sourceFileName || "");
const inferredTotal = positiveCount + neutralCount + negativeCount;
const savedTotal = Number(stepTwo.totalComments ?? savedAnalysis.totalComments);
const totalComments = Number.isFinite(savedTotal) ? savedTotal : inferredTotal;
commentPreview.value = { fileName: sourceFileName, totalComments, comments: restoredComments };
wordCloud.value = restoredWordCloud;
topIssues.value = restoredTopIssues;
rootCauseAnalysis.value = stepTwo.rootCauseAnalysis || "";
if (sourceFileName || restoredWordCloud.length || restoredComments.length || restoredTopIssues.some(Boolean)) {
analysisResult.value = { sourceFileName, totalComments, positiveCount, neutralCount, negativeCount, topIssues: restoredTopIssues, wordCloud: restoredWordCloud, previewComments: restoredComments };
}
nextTick(renderWordCloud);
}
function restore(answer) {
const stepOne = parseSavedStep(answer?.step1Answer);
restoreStepOne(stepOne);
restoreStepTwo(parseSavedStep(answer?.step2Answer));
const stepThree = parseSavedStep(answer?.step3Answer);
if (stepThree.testPlan || stepThree.comparisonChartUrl || stepThree.iterationRecommendation) { abTestPlan.value = stepThree.testPlan || ""; if (Array.isArray(stepThree.rows) && stepThree.rows.length === createAbRows().length) abRows.value = createAbRows().map((row) => ({ ...row, ...(stepThree.rows.find((item) => item?.metric === row.metric) || {}) })); if (stepThree.comparisonChartUrl) abChart.value = { url: stepThree.comparisonChartUrl, name: stepThree.comparisonChartName || "AB 测试结果对比图" }; iterationRecommendation.value = stepThree.iterationRecommendation || ""; }
currentStep.value = [1, 2, 3].includes(Number(answer?.currentStep)) ? Number(answer.currentStep) : 1;
}
onMounted(async () => { try { taskConfig.value = (await getTrainingTaskByKey(TASK_KEY))?.data || null; } catch (error) { taskConfig.value = null; } try { restore((await getStudentTrainingAnswer(TASK_KEY))?.data); } catch (error) {} }); onBeforeUnmount(() => { if (funnelChart.value.url.startsWith("blob:")) URL.revokeObjectURL(funnelChart.value.url); if (abChart.value.url.startsWith("blob:")) URL.revokeObjectURL(abChart.value.url); wordCloudChart?.dispose(); });
</script>
@ -170,6 +348,7 @@ onMounted(async () => { try { taskConfig.value = (await getTrainingTaskByKey(TAS
.lead{margin:0 0 20px;color:#d4edf7;font-size:15px;line-height:1.9}.section-block{margin-top:20px;padding:20px;border:1px solid rgba(97,209,247,.25);border-radius:16px;background:rgba(3,28,43,.42)}.section-heading{display:flex;align-items:flex-start;gap:12px;margin-bottom:16px}.section-heading>span{display:grid;flex:0 0 30px;width:30px;height:30px;place-items:center;border-radius:8px;color:#eaffff;background:linear-gradient(135deg,#11b8e4,#1373c4);font-size:14px;font-weight:900}.section-heading h3{margin:1px 0 4px;color:#f0fbff;font-size:18px}.section-heading p{margin:0;color:var(--diagnosis-muted);font-size:13px;line-height:1.65}
.secondary-button,.table-button,.upload-button,.submit-button{min-height:36px;padding:0 13px;border:1px solid rgba(99,203,239,.58);border-radius:8px;color:#e7fbff;background:rgba(12,111,153,.46);font:inherit;font-size:13px;font-weight:800;cursor:pointer;transition:.2s ease}.secondary-button:hover,.table-button:hover,.upload-button:hover{border-color:#7deaff;background:rgba(19,145,192,.62)}.submit-button{border-color:#72e8ff;background:linear-gradient(100deg,#0d80b7,#09638f)}.submit-button:hover{filter:brightness(1.12)}button:disabled{cursor:not-allowed;opacity:.45}.table-button.ghost{border-color:rgba(163,197,211,.36);color:#bed6e0;background:rgba(75,101,112,.25)}
.table-wrap{overflow-x:auto;border:1px solid rgba(99,183,222,.43);border-radius:12px}.funnel-table,.diagnosis-table,.sentiment-table{width:100%;border-collapse:collapse}.funnel-table{min-width:900px}.diagnosis-table{min-width:1060px}.sentiment-table{min-width:640px}.funnel-table th,.funnel-table td,.diagnosis-table th,.diagnosis-table td,.sentiment-table th,.sentiment-table td{padding:11px;border-right:1px solid rgba(99,183,222,.31);border-bottom:1px solid rgba(99,183,222,.31);vertical-align:middle;text-align:center}.funnel-table thead th,.diagnosis-table thead th,.sentiment-table thead th{color:#effaff;background:linear-gradient(100deg,#0a96cc,#087daf);font-size:14px;white-space:nowrap}.funnel-table tbody th,.sentiment-table tbody th{color:#dff8ff;background:rgba(8,72,99,.34);font-weight:800}.funnel-table td,.diagnosis-table td,.sentiment-table td{background:rgba(2,18,29,.34)}.funnel-table :deep(.el-input-number),.diagnosis-table :deep(.el-input-number),.sentiment-table :deep(.el-input-number),.diagnosis-table :deep(.el-select){width:100%}.unit{margin-left:5px;color:#74ddf6;font-size:12px;font-weight:800}.auto-count{color:#82e7ff;font-size:16px;font-weight:900}
.funnel-channel-toolbar>span{display:block}.funnel-table .fixed-column,.funnel-table tbody th{min-width:145px}.funnel-table .channel-column,.funnel-table tbody td{min-width:180px}.channel-heading{display:flex;align-items:center;gap:7px}.channel-heading :deep(.el-input){min-width:120px}.channel-heading :deep(.el-input__wrapper){background:rgba(2,45,66,.58);box-shadow:0 0 0 1px rgba(198,242,255,.42) inset}.channel-heading :deep(.el-input__inner){color:#fff;text-align:center;font-weight:800}.channel-remove{display:inline-grid;flex:0 0 24px;width:24px;height:24px;place-items:center;padding:0;border:1px solid rgba(255,164,172,.58);border-radius:6px;color:#ffd4d7;background:rgba(130,35,53,.32);font:inherit;font-size:17px;line-height:1;cursor:pointer}.channel-remove:hover,.channel-remove:focus-visible{border-color:#ff98a2;color:#fff;background:rgba(176,48,67,.5);outline:none}.rate-input{display:flex;align-items:center;gap:6px;width:100%;white-space:nowrap}.rate-input :deep(.el-input-number){flex:1 1 auto;width:calc(100% - 22px);min-width:0}.rate-input .unit{display:inline-flex;flex:0 0 auto;align-items:center;height:32px;margin-left:0;white-space:nowrap}
.table-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;margin:0 0 12px;color:var(--diagnosis-muted);font-size:13px}.table-toolbar>div,.actions,.diagnosis-materials__actions,.ab-materials__actions{display:flex;flex-wrap:wrap;gap:8px}.actions{justify-content:center;margin-top:24px}.actions .secondary-button,.actions .submit-button{min-width:142px;min-height:42px}
.chart-upload-area,.comment-import{display:grid;place-items:center;gap:10px;min-height:190px;padding:22px;border:1px dashed rgba(113,223,255,.66);border-radius:13px;background:linear-gradient(135deg,rgba(5,47,69,.66),rgba(4,23,35,.52));text-align:center}.chart-upload-area p,.comment-import>p{margin:0;color:var(--diagnosis-muted);font-size:13px}.upload-button{min-height:42px;padding:0 18px}.chart-preview{display:flex;align-items:center;gap:16px;width:100%;text-align:left}.chart-preview :deep(.el-image){width:180px;height:110px;border:1px solid var(--diagnosis-line);border-radius:8px}.chart-preview>div{display:grid;gap:7px}.chart-preview strong{color:#e8fbff}.chart-preview span{color:var(--diagnosis-muted);font-size:13px}.chart-preview button{width:max-content;padding:0;border:0;color:#ffadb1;background:transparent;font:inherit;cursor:pointer}
.data-preview,.word-cloud-card,.top-issues,.root-cause{margin-top:16px;padding:16px;border:1px solid rgba(99,183,222,.31);border-radius:12px;background:rgba(3,25,39,.58)}.data-preview>div,.word-cloud-title{display:flex;justify-content:space-between;gap:12px;color:#e6f9ff}.data-preview span,.word-cloud-title small{color:var(--diagnosis-muted);font-size:12px}.data-preview ul{max-height:130px;margin:12px 0 0;padding-left:20px;overflow:auto;color:#c8e5f1;line-height:1.7;text-align:left}.word-cloud{height:280px}.top-issues>p,.root-cause>p{margin:0 0 13px;color:#c8e5f1;line-height:1.7}.top-issues>div{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.top-issues label{display:grid;gap:7px;color:#8bdff5;font-weight:800}.sentiment-actions{display:flex;align-items:center;gap:14px;margin-bottom:16px}.sentiment-actions>span{color:var(--diagnosis-muted);font-size:13px}.visual-section,.diagnosis-section{margin-top:20px}
@ -186,7 +365,6 @@ onMounted(async () => { try { taskConfig.value = (await getTrainingTaskByKey(TAS
.workbench .step-tabs .step-tab.complete .step-marker{border-color:#79eee4;color:#083342;background:#6deee1;box-shadow:none}
.workbench .step-tabs .step-connector{flex:0 0 30px;width:30px;height:1px;margin:0;background:rgba(94,193,229,.58)}
.workbench .step-tabs .step-connector::after{width:8px;height:8px;border-color:#73c8e7}
.sentiment-table td:last-child{white-space:nowrap}.sentiment-table td:last-child :deep(.el-input-number){display:inline-flex;width:calc(100% - 32px);vertical-align:middle}.sentiment-table td:last-child .unit{display:inline-flex;align-items:center;height:32px;margin-left:6px;vertical-align:middle}
@media(max-width:1100px){.diagnosis-page{grid-template-columns:1fr}}@media(max-width:720px){.diagnosis-page{padding:12px}.diagnosis-core{padding:16px;border-radius:20px}.workbench{padding:16px}.workbench-top,.table-toolbar,.sentiment-actions{align-items:stretch;flex-direction:column}.step-tabs{align-items:stretch;flex-direction:column}.step-tabs button{flex:0 0 auto;width:100%}.step-tabs i{flex:0 0 12px;width:2px;height:12px;margin-left:17px}.diagnosis-materials__item,.ab-materials{align-items:stretch;flex-direction:column}.top-issues>div{grid-template-columns:1fr}.chart-preview{align-items:flex-start;flex-direction:column}.chart-preview :deep(.el-image){width:100%;height:170px}}
.diagnosis-toolbar{align-self:center;justify-content:flex-end;max-width:100%}
@media(max-width:720px){.diagnosis-toolbar{width:100%;justify-content:flex-start}}

@ -38,7 +38,7 @@
<div class="category-table-wrap">
<table class="category-table">
<thead><tr><th>品类名称</th><th>近12个月营收(万元)</th><th>营收占比(%)</th><th>累计占比(%)</th><th>库存资金占用(万元)</th><th>资金占用率</th><th>近30天动销率</th><th>毛利率</th></tr></thead>
<thead><tr><th>品类名称</th><th>近12个月营收(万元)</th><th>营收占比(%)</th><th>累计占比(%)</th><th>库存资金占用(万元)</th><th>资金占用率(%)</th><th>近30天动销率(%)</th><th>毛利率</th></tr></thead>
<tbody>
<tr v-for="(row, index) in categoryRows" :key="row.id">
<td><el-input v-model="row.categoryName" :aria-label="`第${index + 1}行品类名称`" /></td>
@ -46,8 +46,8 @@
<td><el-input v-model="row.revenueShare" inputmode="decimal" :aria-label="`第${index + 1}行营收占比`" /></td>
<td><el-input v-model="row.cumulativeShare" inputmode="decimal" :aria-label="`第${index + 1}行累计占比`" /></td>
<td><el-input v-model="row.inventoryCapital" inputmode="decimal" :aria-label="`第${index + 1}行库存资金占用`" /></td>
<td><el-input v-model="row.capitalOccupancyRate" inputmode="decimal" :aria-label="`第${index + 1}行资金占用率`" /></td>
<td><el-input v-model="row.sellThroughRate" inputmode="decimal" :aria-label="`第${index + 1}行近30天动销率`" /></td>
<td><el-input-number v-model="row.capitalOccupancyRate" :min="0" :max="100" :precision="2" :step="0.01" :controls="false" inputmode="decimal" :aria-label="`第${index + 1}行资金占用率(百分数)`" /></td>
<td><el-input-number v-model="row.sellThroughRate" :min="0" :max="100" :precision="2" :step="0.01" :controls="false" inputmode="decimal" :aria-label="`第${index + 1}行近30天动销率(百分数)`" /></td>
<td><el-input v-model="row.grossMargin" inputmode="decimal" :aria-label="`第${index + 1}行毛利率`" /></td>
</tr>
<tr v-if="!categoryRows.length"><td colspan="8" class="empty-cell">暂无数据,请根据案例资料增加行并填写。</td></tr>
@ -226,7 +226,13 @@ const selectedProduct = computed(() => categoryRows.value.find((row) => row.cate
const currentClassificationLabel = computed(() => selectedProduct.value?.abcClassification ? `${selectedProduct.value.abcClassification}类${selectedProduct.value.abcClassification === "A" ? "核心品类" : selectedProduct.value.abcClassification === "B" ? "潜力品类" : "长尾品类"}` : "选择新品后自动带出");
const progressItems = computed(() => configuredSteps.value.map((text, index) => ({ text, status: index + 1 < activeStep.value ? "done" : index + 1 === activeStep.value ? "doing" : "" })));
function createRow(source = {}) { return { id: source.id || `${Date.now()}-${Math.random().toString(16).slice(2)}`, categoryName: source.categoryName ?? "", revenue: source.revenue ?? "", revenueShare: source.revenueShare ?? "", cumulativeShare: source.cumulativeShare ?? "", inventoryCapital: source.inventoryCapital ?? "", capitalOccupancyRate: source.capitalOccupancyRate ?? "", sellThroughRate: source.sellThroughRate ?? "", grossMargin: source.grossMargin ?? "", abcClassification: source.abcClassification ?? "" }; }
function normalizePercentageValue(value) {
const text = String(value ?? "").trim().replace(/%/g, "");
if (!text) return null;
const number = Number(text);
return Number.isFinite(number) ? Number(number.toFixed(2)) : null;
}
function createRow(source = {}) { return { id: source.id || `${Date.now()}-${Math.random().toString(16).slice(2)}`, categoryName: source.categoryName ?? "", revenue: source.revenue ?? "", revenueShare: source.revenueShare ?? "", cumulativeShare: source.cumulativeShare ?? "", inventoryCapital: source.inventoryCapital ?? "", capitalOccupancyRate: normalizePercentageValue(source.capitalOccupancyRate), sellThroughRate: normalizePercentageValue(source.sellThroughRate), grossMargin: source.grossMargin ?? "", abcClassification: source.abcClassification ?? "" }; }
function createStepFour(source = {}) { return { productName: source.productName ?? "", matrixQuadrant: source.matrixQuadrant ?? "", matrixReason: source.matrixReason ?? "", necessityAnalysis: source.necessityAnalysis ?? "", recommendedClassification: source.recommendedClassification ?? "", trafficSupportMeasures: source.trafficSupportMeasures ?? "" }; }
function createStrategyRows(savedRows = []) { const saved = new Map((Array.isArray(savedRows) ? savedRows : []).map((row) => [row?.layer, row])); return [{ layer: "A", label: "A类核心品类", operationPlaceholder: "例如:重点投入流量与推广预算,持续优化转化率", inventoryPlaceholder: "例如:安全库存上限,高频补货,优先保障供货稳定" }, { layer: "B", label: "B类潜力品类", operationPlaceholder: "例如:开展AB测试,针对潜力品类配置流量扶持", inventoryPlaceholder: "例如:密切关注运营效果,活动前适当备货" }, { layer: "C", label: "C类长尾品类", operationPlaceholder: "例如:控制流量预算,通过组合活动逐步清退滞销SKU", inventoryPlaceholder: "例如:停止主动补货,清退滞销SKU" }, { layer: "NEW", label: "新产品", operationPlaceholder: "例如:设置新品测试活动,重点推广运营", inventoryPlaceholder: "例如:提前备货,根据渠道测试情况重点备货" }].map((row) => ({ ...row, operationStrategy: saved.get(row.layer)?.operationStrategy ?? "", inventoryStrategy: saved.get(row.layer)?.inventoryStrategy ?? "", resourcePriority: saved.get(row.layer)?.resourcePriority ?? "" })); }
function normalizeActiveStep(value) { return !configuredSteps.value.length ? 1 : Math.min(Math.max(Number(value) || 1, 1), configuredSteps.value.length); }
@ -378,7 +384,7 @@ onMounted(async () => {
.training-core { min-width:0; padding:28px; border:1px solid var(--line); border-radius:28px; background:rgba(5,25,37,.82); box-shadow:0 22px 48px rgba(0,0,0,.22); }.task-header{margin-bottom:20px}.task-badge{display:inline-flex;align-items:center;gap:8px;padding:5px 12px;border:1px solid rgba(99,217,255,.55);border-radius:999px;color:#dff5ff;background:rgba(17,126,178,.3);font-size:12px;font-weight:800}.task-header h1{margin:10px 0 0;font-size:30px}.task-card{margin-top:24px;overflow:hidden;border:1px solid var(--line);border-radius:20px;background:rgba(3,22,34,.78)}
.workbench-head{display:flex;justify-content:space-between;gap:18px;padding:22px 24px;border-bottom:1px solid var(--line)}.section-eyebrow{margin:0;color:#71dfff;font-size:12px;font-weight:800;letter-spacing:.12em}.workbench-head h2{margin:5px 0 0;font-size:24px}.workbench-actions,.table-toolbar>div,.step-navigation,.training-actions{display:flex;flex-wrap:wrap;align-items:center;gap:10px}.workbench-actions{justify-content:flex-end}.outline-action,.action-button,.nav-button{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:40px;padding:0 16px;border:1px solid rgba(99,217,255,.5);border-radius:9px;color:#e9fbff;background:rgba(17,126,178,.34);font:inherit;font-weight:700;cursor:pointer}.outline-action:hover,.action-button:hover,.nav-button:hover{border-color:#7deaff;background:rgba(20,148,193,.48)}button:disabled{cursor:not-allowed;opacity:.45}
.step-indicator{display:flex;gap:9px;padding:16px 24px;border-bottom:1px solid var(--line);overflow-x:auto}.step-tab{display:inline-flex;align-items:center;gap:8px;min-width:max-content;padding:8px 12px;border:1px solid var(--line);border-radius:999px;color:var(--muted);background:transparent;font:inherit;cursor:pointer}.step-tab span{display:grid;width:21px;height:21px;place-items:center;border-radius:50%;color:#bdefff;background:rgba(16,117,154,.35);font-size:11px;font-weight:800}.step-tab.active{border-color:#71dfff;color:white;background:rgba(12,114,159,.48)}.step-tab.complete{color:#d5fff8}.step-tab.complete span{background:#2ba995}
.category-step{padding:24px}.instruction{margin:0 0 20px;color:#d8edf5;font-size:15px;line-height:1.75}.table-toolbar{display:flex;justify-content:space-between;gap:14px;margin-bottom:12px;color:var(--muted);font-size:13px}.action-button--muted{border-color:rgba(158,192,207,.35);background:rgba(75,101,112,.25)}.category-table-wrap{overflow-x:auto;border:1px solid var(--line);border-radius:12px}.category-table{width:100%;min-width:1260px;border-collapse:collapse}.category-table th,.category-table td{padding:10px;border-right:1px solid var(--line);border-bottom:1px solid var(--line);text-align:center}.category-table th{color:#e6f9ff;background:rgba(23,112,150,.42);font-size:13px;white-space:nowrap}.category-table td{background:rgba(2,18,28,.32)}.category-table tr:last-child td{border-bottom:0}.category-table th:last-child,.category-table td:last-child{border-right:0}.empty-cell{height:88px;color:var(--muted)}.abc-table{min-width:900px}.abc-table :deep(.el-select){width:100%;min-width:180px}
.category-step{padding:24px}.instruction{margin:0 0 20px;color:#d8edf5;font-size:15px;line-height:1.75}.table-toolbar{display:flex;justify-content:space-between;gap:14px;margin-bottom:12px;color:var(--muted);font-size:13px}.action-button--muted{border-color:rgba(158,192,207,.35);background:rgba(75,101,112,.25)}.category-table-wrap{overflow-x:auto;border:1px solid var(--line);border-radius:12px}.category-table{width:100%;min-width:1260px;border-collapse:collapse}.category-table th,.category-table td{padding:10px;border-right:1px solid var(--line);border-bottom:1px solid var(--line);text-align:center}.category-table th{color:#e6f9ff;background:rgba(23,112,150,.42);font-size:13px;white-space:nowrap}.category-table td{background:rgba(2,18,28,.32)}.category-table tr:last-child td{border-bottom:0}.category-table th:last-child,.category-table td:last-child{border-right:0}.category-table :deep(.el-input-number){width:100%}.empty-cell{height:88px;color:var(--muted)}.abc-table{min-width:900px}.abc-table :deep(.el-select){width:100%;min-width:180px}
.rule-notice{margin-top:20px;padding:16px 18px;border:1px solid rgba(255,112,112,.46);border-radius:12px;background:rgba(126,31,35,.15);color:#ffd5d5}.rule-notice strong{color:#ff9292}.rule-notice p{margin:8px 0 0;line-height:1.65}.analysis-step{padding:24px}.analysis-tabs{display:flex;gap:10px;margin-bottom:18px}.analysis-tabs button{padding:9px 14px;border:1px solid var(--line);border-radius:8px;color:var(--muted);background:transparent;font:inherit;cursor:pointer}.analysis-tabs button.active{color:white;border-color:#71dfff;background:rgba(12,114,159,.48)}.business-workspace{overflow:hidden;border:1px solid var(--line);border-radius:14px}.step-navigation{justify-content:center;padding:20px 24px 0}.nav-button--save,.nav-button--primary{border-color:#71dfff;background:linear-gradient(100deg,#0d80b7,#09638f)}.training-actions{justify-content:center;gap:28px;padding:26px 24px}.training-actions :deep(.training-action){min-width:160px;height:50px;border-color:#2c83aa;color:#dff7ff;background:rgba(13,64,88,.62);font-size:17px;font-weight:800}
.pareto-upload-panel{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;min-height:330px;padding:26px;border:1px dashed rgba(113,223,255,.7);border-radius:16px;background:linear-gradient(135deg,rgba(5,47,69,.7),rgba(4,23,35,.58));text-align:center}.file-input{display:none}.upload-icon{font-size:42px;color:#71dfff}.pareto-upload-panel>strong{font-size:20px}.pareto-upload-panel>span,.upload-file-meta span{color:var(--muted);font-size:13px}.pareto-preview{width:min(100%,760px);height:270px;border:1px solid var(--line);border-radius:10px;background:rgba(0,10,18,.65);cursor:zoom-in}.upload-file-meta{display:grid;gap:5px;max-width:100%;word-break:break-all}.pareto-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:10px}.danger-action{border-color:rgba(255,145,145,.6);color:#ffd7d7;background:rgba(130,43,43,.23)}
.pareto-materials{display:flex;align-items:center;justify-content:space-between;gap:22px;margin-top:20px;padding:18px 20px;border-left:3px solid var(--accent);border-radius:0 14px 14px 0;background:rgba(11,79,109,.22);color:#d8edf5}.pareto-materials h3{margin:0 0 8px;font-size:16px}.pareto-materials ol{margin:0;padding-left:20px;line-height:1.8}.pareto-materials__actions{display:grid;flex:0 0 178px;gap:10px}.action-button--primary{border-color:#71dfff;background:linear-gradient(100deg,#0d80b7,#09638f)}

@ -429,7 +429,7 @@ async function saveStepOne(showMessage = true) {
try {
const result = (await validateSupplierEvaluationStepOne(buildStepOnePayload()))?.data || {};
if (!result?.valid) throw new Error(result?.message || "权重校验未通过");
await saveStudentTrainingAnswer({ taskKey: TASK_KEY, currentStep: 1, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step1Answer: JSON.stringify({ items: result.items }) });
await saveStudentTrainingAnswer(TASK_KEY, { currentStep: 1, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step1Answer: JSON.stringify({ items: result.items }) });
stepOneSaved.value = true;
if (showMessage) ElMessage.success("当前步骤已保存");
return true;
@ -446,7 +446,7 @@ async function saveStepTwo(showMessage = true) {
if (!result?.valid) throw new Error(result?.message || "渠道评分校验未通过");
smallBatchRows.value = createScoreRows(result.smallBatchChannels);
largeBatchRows.value = createScoreRows(result.largeBatchChannels);
await saveStudentTrainingAnswer({ taskKey: TASK_KEY, currentStep: 2, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step2Answer: JSON.stringify({ weights: result.weights, smallBatchChannels: result.smallBatchChannels, largeBatchChannels: result.largeBatchChannels }) });
await saveStudentTrainingAnswer(TASK_KEY, { currentStep: 2, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step2Answer: JSON.stringify({ weights: result.weights, smallBatchChannels: result.smallBatchChannels, largeBatchChannels: result.largeBatchChannels }) });
stepTwoSaved.value = true;
syncChannelNames();
if (showMessage) ElMessage.success("当前步骤已保存");
@ -462,7 +462,7 @@ async function saveStepThree(showMessage = true) {
const result = (await validateSupplierEvaluationStepThree(buildStepThreePayload()))?.data || {};
if (!result?.valid) throw new Error(result?.message || "第 3 步校验未通过");
const step3Answer = { scenarioAnalyses: result.scenarioAnalyses, procurementRecommendation: result.procurementRecommendation, risks: result.risks };
await saveStudentTrainingAnswer({ taskKey: TASK_KEY, currentStep: 3, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step3Answer: JSON.stringify(step3Answer) });
await saveStudentTrainingAnswer(TASK_KEY, { currentStep: 3, saveAction: "SAVE", progressStatus: "IN_PROGRESS", step3Answer: JSON.stringify(step3Answer) });
applyStepThree({ step3Answer });
if (showMessage) ElMessage.success("当前步骤已保存");
return true;

@ -34,7 +34,7 @@
<span class="evaluation-status" :class="`evaluation-status--${assessmentStatus.toLowerCase()}`">{{ statusLabel(assessmentStatus) }}</span>
</div>
<p class="evaluation-panel__hint">AI将基于已填写的答案给出综合评分和改进方向。</p>
<p class="evaluation-panel__hint">AI根据已保存的答案评分。修改并保存答案后可重新助评;答案未变时保留上次结果。</p>
<el-button :loading="assessmentLoading" :disabled="isAssessmentDisabled" type="primary" @click="confirmAssessment">
{{ assessmentActionLabel }}
</el-button>
@ -90,9 +90,11 @@ const assessmentReport = computed(() => normalizedReports.value.assessmentReport
const score = computed(() => normalizedReports.value.score);
const scoreCriteria = computed(() => normalizedReports.value.scoreCriteria);
const isHelpDisabled = computed(() => !props.hasAnyAnswer || helpLoading.value || isTerminal(helpStatus.value));
const isAssessmentDisabled = computed(() => !props.hasAnyAnswer || assessmentLoading.value || isTerminal(assessmentStatus.value));
const isAssessmentDisabled = computed(() => !props.hasAnyAnswer || assessmentLoading.value || assessmentStatus.value === "PROCESSING");
const helpActionLabel = computed(() => actionLabel(helpStatus.value, "生成助学建议", helpLoading.value));
const assessmentActionLabel = computed(() => actionLabel(assessmentStatus.value, "请求AI助评", assessmentLoading.value));
const assessmentActionLabel = computed(() => assessmentStatus.value === "SUCCEEDED" && !assessmentLoading.value
? "重新助评"
: actionLabel(assessmentStatus.value, "请求AI助评", assessmentLoading.value));
onMounted(() => loadEvaluation());
@ -136,7 +138,7 @@ async function requestHelp() {
async function confirmAssessment() {
if (isAssessmentDisabled.value || !props.taskKey) return;
try {
await proxy?.$modal?.confirm("AI将根据当前已填写的内容进行评估,是否继续?", "提示");
await proxy?.$modal?.confirm("AI将根据当前已保存的答案进行评估,答案未变时保留上次结果,是否继续?", "提示");
} catch (error) {
return;
}

@ -36,16 +36,36 @@
AI助评
</h3>
<div v-if="displayScoreVisible" class="score-badge">
<span>综合评分</span>
<strong>{{ displayFinalScore }}</strong>
<em>/ 100</em>
</div>
<div class="ai-output ai-output--review">
<div class="output-glow"></div>
<p>{{ displayEvalMessage }}</p>
<div v-if="displayScoreVisible" class="score-badge">
综合评分:<strong>{{ displayFinalScore }}</strong> / 100
<div v-if="hasStructuredAssessment" class="assessment-result">
<p v-if="reports.assessmentSummary" class="assessment-summary">{{ reports.assessmentSummary }}</p>
<div v-if="displayScoreCriteria.length" class="assessment-criteria" aria-label="评分明细">
<div v-for="item in displayScoreCriteria" :key="`${item.name}-${item.score}`" class="assessment-criterion">
<div class="assessment-criterion__heading">
<strong>{{ item.name }}</strong>
<span v-if="item.score !== ''">{{ item.score }}<small v-if="item.maxScore !== ''"> / {{ item.maxScore }}</small></span>
</div>
<p v-if="item.description">{{ item.description }}</p>
</div>
</div>
<div v-if="reports.improvements.length" class="assessment-actions">
<strong>优先改进</strong>
<ul><li v-for="item in reports.improvements" :key="item">{{ item }}</li></ul>
</div>
</div>
<p v-else>{{ displayEvalMessage }}</p>
</div>
<p v-if="currentTaskKey && !hasSavedAnswer" class="assessment-hint">请先至少填写并保存一项实训内容,再请求 AI 助评。</p>
<el-button class="assessment-button" :loading="assessmentLoading" :disabled="!currentTaskKey || !hasSavedAnswer || assessmentLoading" @click="requestEvaluation">AI智能评分</el-button>
<p v-else-if="currentTaskKey" class="assessment-hint">修改并保存答案后可重新助评;答案未变时保留上次结果。</p>
<el-button class="assessment-button" :loading="assessmentLoading" :disabled="!currentTaskKey || !hasSavedAnswer || assessmentLoading" @click="requestEvaluation">{{ reports.assessment.status === "SUCCEEDED" ? "重新助评" : "AI智能评分" }}</el-button>
</section>
</aside>
</template>
@ -109,13 +129,20 @@ const route = useRoute();
const currentTaskKey = computed(() => resolveTrainingTaskKey(route, props.taskKey));
const reports = computed(() => normalizeEvaluationReports(evaluation.value));
const currentStepContext = computed(() => [props.studyTip, props.referenceTitle, plainText(props.referenceText)].filter(Boolean).join("\n"));
const displayScoreCriteria = computed(() => {
const criteria = reports.value.scoreCriteria;
const stepNames = props.progressItems.map((item) => String(item?.text || "").trim()).filter(Boolean);
if (!stepNames.length || stepNames.length !== criteria.length) return criteria;
return criteria.map((item, index) => ({ ...item, name: stepNames[index] }));
});
const displayAssistMessage = computed(() => assistMessage.value || props.studyTip);
const displayScoreVisible = computed(() => props.scoreVisible || internalScoreVisible.value || reports.value.score !== null);
const displayFinalScore = computed(() => (props.scoreVisible ? props.finalScore : reports.value.score ?? internalScore.value));
const hasStructuredAssessment = computed(() => Boolean(reports.value.assessmentSummary || displayScoreCriteria.value.length || reports.value.improvements.length));
const displayEvalMessage = computed(() => {
if (props.scoreVisible) return props.evalMessage;
return reports.value.assessmentReport || internalEvalMessage.value || props.evalMessage;
return internalEvalMessage.value || props.evalMessage;
});
onMounted(loadEvaluation);
@ -174,7 +201,7 @@ async function requestEvaluation() {
await loadEvaluation();
internalScoreVisible.value = reports.value.score !== null;
internalScore.value = reports.value.score ?? "--";
internalEvalMessage.value = reports.value.assessmentReport || props.evalMessage;
internalEvalMessage.value = reports.value.assessmentSummary || "AI 评分已生成,请查看评分明细与改进建议。";
} catch (error) {
internalEvalMessage.value = "AI 助评暂时不可用,请稍后重试。";
} finally { assessmentLoading.value = false; }
@ -266,6 +293,61 @@ function plainText(value) {
margin: 0;
}
}
.ai-output--review {
max-height: 500px;
overflow-y: auto;
}
.assessment-result {
position: relative;
z-index: 1;
display: grid;
gap: 12px;
}
.assessment-summary {
margin: 0;
color: #e6f7ff;
font-weight: 650;
line-height: 1.8;
}
.assessment-criteria {
display: grid;
gap: 8px;
}
.assessment-criterion {
padding: 10px 11px;
border: 1px solid rgba(113, 225, 255, 0.22);
border-radius: 10px;
background: rgba(10, 43, 61, 0.4);
}
.assessment-criterion__heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: #f0fbff;
}
.assessment-criterion__heading span {
flex: 0 0 auto;
color: #71e8ff;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.assessment-criterion__heading small { color: #91bbcf; font-weight: 600; }
.assessment-criterion p {
margin: 6px 0 0;
color: #afd3e3;
font-size: 13px;
line-height: 1.65;
}
.assessment-actions {
padding: 10px 11px;
border-left: 2px solid #5ce4ff;
color: #cceafa;
background: rgba(29, 114, 149, 0.14);
}
.assessment-actions strong { color: #7cecff; font-size: 13px; }
.assessment-actions ul { margin: 6px 0 0; padding-left: 18px; }
.assessment-actions li + li { margin-top: 4px; }
.study-messages {
position: relative;
z-index: 1;
@ -380,17 +462,30 @@ function plainText(value) {
z-index: 1;
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 14px;
padding: 8px 12px;
border: 1px solid rgba(126, 233, 255, 0.38);
border-radius: 999px;
width: 100%;
gap: 8px;
margin: -2px 0 14px;
padding: 12px 14px;
border: 1px solid rgba(101, 238, 255, 0.7);
border-radius: 12px;
color: #dff8ff;
background: rgba(11, 42, 56, 0.78);
background:
linear-gradient(90deg, rgba(20, 169, 216, 0.4), rgba(8, 50, 70, 0.75)),
rgba(11, 42, 56, 0.78);
box-shadow: inset 0 1px 0 rgba(220, 253, 255, 0.23), 0 0 24px rgba(39, 209, 255, 0.16);
font-size: 14px;
font-weight: 800;
letter-spacing: 0.04em;
span { color: #dff8ff; }
em { color: #b8dce9; font-size: 13px; font-style: normal; font-weight: 700; }
strong {
color: #7ee9ff;
font-size: 20px;
margin-left: auto;
font-size: 28px;
line-height: 1;
text-shadow: 0 0 14px rgba(102, 238, 255, 0.6);
}
}

@ -8,6 +8,11 @@ function safeParseJson(value) {
}
}
function criterionDisplayName(value) {
const name = String(value || "").trim();
return name || "评分项";
}
function formatReport(value) {
if (value == null) return "";
const parsed = typeof value === "string" ? safeParseJson(value) : value;
@ -24,13 +29,19 @@ function normalizeCriteria(value) {
return value.map((item) => {
if (typeof item === "string") return { name: item, score: "", description: "" };
return {
name: String(item?.name || item?.criterion || item?.title || "评分项"),
name: criterionDisplayName(item?.name || item?.criterion || item?.title),
score: item?.score ?? item?.weight ?? "",
description: String(item?.description || item?.detail || ""),
maxScore: item?.maxScore ?? item?.max ?? "",
description: String(item?.rationale || item?.description || item?.detail || ""),
};
});
}
function normalizeTextList(value) {
if (!Array.isArray(value)) return [];
return value.map((item) => String(item || "").trim()).filter(Boolean);
}
function normalizeOperation(operation, root, type) {
const value = operation && typeof operation === "object" ? operation : {};
const prefix = type === "help" ? "help" : "assessment";
@ -47,15 +58,19 @@ function normalizeEvaluationReports(evaluation) {
const root = evaluation && typeof evaluation === "object" ? evaluation : {};
const help = normalizeOperation(root.help || root.helpEvaluation, root, "help");
const assessment = normalizeOperation(root.assessment || root.assessmentEvaluation, root, "assessment");
const assessmentReportData = safeParseJson(root.assessmentReportJson);
const assessmentReportValue = assessment.report || assessment.content || assessment.feedback;
const assessmentReportData = safeParseJson(root.assessmentReportJson) || safeParseJson(assessmentReportValue) || {};
return {
help,
assessment,
helpReport: formatReport(help.report || help.content || help.suggestion),
assessmentReport: formatReport(assessment.report || assessment.content || assessment.feedback),
assessmentReport: formatReport(assessmentReportValue),
score: root.assessmentScore ?? assessment.score ?? assessmentReportData?.score ?? root.score ?? null,
scoreCriteria: normalizeCriteria(assessmentReportData?.criteria || assessment.scoreCriteria || root.scoreCriteria),
assessmentSummary: String(assessmentReportData?.overallComment || assessmentReportData?.summary || "").trim(),
strengths: normalizeTextList(assessmentReportData?.strengths),
improvements: normalizeTextList(assessmentReportData?.improvements),
};
}

@ -72,7 +72,7 @@
<div class="drawer-heading">
<span class="drawer-kicker">{{ dialogMode === "view" ? "Training Task Preview" : "Training Task Editor" }}</span>
<h3>{{ dialogMode === "view" ? "查看实训任务" : "编辑实训任务" }}</h3>
<p>管理员维护系统默认实训配置,教学班未单独配置时学生端使用这里的实训背景、目标、要求和案例文档。</p>
<p>管理员维护系统默认实训配置;步骤数量与学生端保持一致,只能修改步骤名称。</p>
</div>
<div class="drawer-header-actions">
<button type="button" class="drawer-close-button" aria-label="关闭抽屉" @click="dialogVisible = false">x</button>
@ -166,16 +166,14 @@
</el-upload>
</div>
<el-form-item label="步骤名称:">
<el-form-item :label="`步骤名称(固定 ${taskForm.steps.length} 步):`">
<div class="step-row">
<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="!isReadonly" text type="danger" @click="removeStep(index)">删除</el-button>
</div>
<span v-if="index < taskForm.steps.length - 1" class="step-arrow">&gt;&gt;&gt;</span>
</template>
<el-button v-if="!isReadonly" plain class="add-step-button" @click="addStep">新增步骤</el-button>
</div>
</el-form-item>
</section>
@ -198,6 +196,7 @@ import {
updateTrainingTask,
uploadTrainingTaskMaterial,
} from "@/api/trainingTask";
import { getStudentTrainingStepCount } from "@/views/training/taskKeyMap";
const { proxy } = getCurrentInstance();
@ -315,7 +314,7 @@ function normalizeTask(task) {
requirements: task.requirements || "",
materialName: material.name,
materialUrl: material.url,
steps: normalizeSteps(parseArray(task.steps, createBuiltinSteps())),
steps: normalizeTaskSteps(task.taskKey, parseArray(task.steps, [])),
sort: task.sort || 0,
enabled: task.enabled !== false,
};
@ -354,17 +353,16 @@ function parseArray(value, fallback) {
}
}
function normalizeSteps(steps) {
function normalizeTaskSteps(taskKey, steps) {
const source = Array.isArray(steps) ? steps : [];
const result = source
.map((item, index) => {
const expectedCount = getStudentTrainingStepCount(taskKey);
return Array.from({ length: expectedCount }, (_, index) => {
const item = source[index];
const raw = item && typeof item === "object" ? item : {};
const name = typeof item === "object" ? String(raw.name || "").trim() : String(item || "").trim();
const kind = raw.kind === "custom" ? "custom" : index < 4 ? "builtin" : "custom";
return createStep(name, kind, raw.id);
})
.filter((item) => item.name);
return result.length ? result : [createStep()];
const savedName = typeof item === "object" ? String(raw.name || "").trim() : String(item || "").trim();
const name = savedName || `步骤 ${String(index + 1).padStart(2, "0")}`;
return createStep(name, "builtin", `builtin-${index + 1}`);
});
}
function createBuiltinSteps() {
@ -390,7 +388,7 @@ function cloneTask(task) {
return {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
steps: normalizeSteps(task.steps?.length ? task.steps : createBuiltinSteps()),
steps: normalizeTaskSteps(task.taskKey, task.steps),
};
}
@ -403,15 +401,6 @@ function removeObjective(index) {
taskForm.objectives.splice(index, 1);
}
function addStep() {
taskForm.steps.push(createStep());
}
function removeStep(index) {
if (taskForm.steps.length <= 1) return;
taskForm.steps.splice(index, 1);
}
async function handleImportChange(file) {
if (!file?.raw) return;
await importTrainingTasks(file.raw);
@ -466,6 +455,7 @@ async function submitTask() {
}
function buildPayload() {
const fixedSteps = normalizeTaskSteps(taskForm.taskKey, taskForm.steps);
return {
projectName: taskForm.project,
taskKey: taskForm.taskKey,
@ -473,7 +463,7 @@ function buildPayload() {
background: taskForm.background,
objectives: JSON.stringify(taskForm.objectives.map((item) => item.trim()).filter(Boolean)),
requirements: taskForm.requirements,
steps: JSON.stringify(taskForm.steps.map((item) => ({ ...item, name: item.name.trim() })).filter((item) => item.name)),
steps: JSON.stringify(fixedSteps),
materialName: taskForm.materialName,
materialUrl: taskForm.materialUrl,
sort: taskForm.sort,
@ -1195,10 +1185,6 @@ function buildPayload() {
flex: 1 1 260px;
}
.add-step-button {
border-style: dashed;
}
.step-arrow {
color: #7ddaff;
font-weight: 800;

@ -91,20 +91,6 @@
<el-form-item label="班级名称" prop="className">
<el-input v-model="formInline.className" placeholder="请输入班级名称" class="form-control" />
</el-form-item>
<el-form-item v-if="activeClassType === 'TEACHING' && isCreate" label="名单创建">
<div class="import-create-actions">
<el-upload
action="/api/user/uploadTeachingClassByStudentMembers"
:data="importCreateUploadData"
:show-file-list="false"
:before-upload="beforeImportCreate"
:http-request="uploadImportCreate"
>
<el-button type="primary">导入名单创建</el-button>
</el-upload>
<el-button @click="downloadTeachingClassImportTemplate">模板下载</el-button>
</div>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footers">
@ -190,6 +176,7 @@ const selectedTeachingClass = ref(null);
const currentUserId = computed(() => userStore.userInfo.userId);
const currentSchoolId = computed(() => userStore.userInfo.schoolId);
const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);
const legacyAdminEnabled = computed(() => userStore.schoolProductConfig?.organizationMode !== "TEACHING_CLASS_ONLY");
const facultyManagementEnabled = computed(() => userStore.schoolProductConfig?.facultyManagementEnabled ?? legacyAdminEnabled.value);
const majorManagementEnabled = computed(() => userStore.schoolProductConfig?.majorManagementEnabled ?? legacyAdminEnabled.value);
@ -236,15 +223,6 @@ const adminClassOptions = computed(() => {
});
});
const importCreateUploadData = computed(() => ({
schoolId: currentSchoolId.value,
schoolFacultyId: formInline.value.schoolFacultyId,
schoolMajorId: formInline.value.schoolMajorId,
className: formInline.value.className,
operatorId: currentUserId.value,
sourceClassIds: sourceAdminClassIds.value.join(","),
}));
const memberUploadData = computed(() => ({
teachingClassId: selectedTeachingClass.value?.schoolClassId || "",
operatorId: currentUserId.value,
@ -290,6 +268,7 @@ function defaultMemberParams() {
schoolClassId: "",
name: "",
userName: "",
operatorId: currentUserId.value,
};
}
@ -304,6 +283,9 @@ function canOperateClass(schoolClass) {
if (schoolClass?.dataSource === "ZHIYUN") {
return false;
}
if (isManagerTeacher.value) {
return !schoolClass?.schoolId || String(schoolClass.schoolId) === String(currentSchoolId.value);
}
if (normalizeClassType(schoolClass) === "ADMIN") {
return !schoolClass?.schoolId || schoolClass.schoolId === currentSchoolId.value;
}
@ -419,71 +401,6 @@ function submitForm() {
});
}
async function beforeImportCreate(file) {
if (activeClassType.value !== "TEACHING") {
proxy.$message.warning("请切换到教学班");
return false;
}
if (!formInline.value.schoolFacultyId || !formInline.value.schoolMajorId || !formInline.value.className) {
proxy.$message.warning("请先填写院系、专业和班级名称");
return false;
}
if (sourceAdminClassIds.value.length === 0) {
proxy.$message.warning("请选择来源行政班");
return false;
}
const total = await getSelectedSourceAdminStudentTotal();
if (total <= 0) {
proxy.$message.warning("所选来源行政班暂无学生,请先在学生管理中导入行政班学生后再创建教学班");
return false;
}
if (!/\.(xls|xlsx)$/i.test(file.name)) {
proxy.$message.warning("请选择xls或xlsx格式文件");
return false;
}
return true;
}
async function getSelectedSourceAdminStudentTotal() {
const results = await Promise.all(sourceAdminClassIds.value.map((schoolClassId) => {
return indexApi.getStudentList({
index: 1,
size: 1,
schoolId: currentSchoolId.value,
schoolClassId,
});
}));
return results.reduce((sum, res) => sum + Number(res.data?.total || 0), 0);
}
function uploadImportCreate(options, confirmMultiTeachingClass = false) {
const formData = buildUploadFormData(options.file, importCreateUploadData.value, confirmMultiTeachingClass);
return indexApi
.uploadTeachingClassByStudentMembers(formData)
.then((res) => {
handleImportCreateSuccess(res);
})
.catch((error) => {
if (!isMultiTeachingClassConflict(error)) return;
return ElMessageBox.confirm(multiTeachingClassMessage(error), "学生已在其他教学班", {
confirmButtonText: "继续导入创建",
cancelButtonText: "取消",
type: "warning",
}).then(() => uploadImportCreate(options, true));
});
}
function handleImportCreateSuccess(res) {
if (res?.statusCode && res.statusCode !== "OK" && res.statusCode !== 200) {
proxy.$message.error(res?.message || "导入创建失败");
return;
}
proxy.$message.success("导入创建成功");
dialogVisible.value = false;
getList();
refreshAllClassList();
}
function openMemberDialog(schoolClass) {
selectedTeachingClass.value = schoolClass;
memberParams.value = {
@ -653,28 +570,6 @@ async function downloadMemberImportTemplate() {
XLSX.writeFile(workbook, "教学班成员导入模板.xlsx");
}
async function downloadTeachingClassImportTemplate() {
const XLSX = await import("xlsx");
const templateSheet = XLSX.utils.aoa_to_sheet([
["所属院系", "所属专业", "行政班", "学号", "学生姓名", "性别", "手机号", "邮箱"],
["商学院", "电子商务", "2026电子商务1班-行政班", "20260001", "张三", "男", "13800000000", "zhangsan@example.com"],
]);
templateSheet["!cols"] = [{ wch: 18 }, { wch: 18 }, { wch: 28 }, { wch: 18 }, { wch: 16 }, { wch: 10 }, { wch: 18 }, { wch: 26 }];
const guideSheet = XLSX.utils.aoa_to_sheet([
["填写说明"],
["1. 先在新增教学班弹窗中选择院系、专业并填写班级名称;来源行政班可以不选。"],
["2. 不要填写任何数据ID,院系、专业、行政班请填写页面中的名称。"],
["3. 学生必须已存在于对应行政班;如果行政班暂无学生,请先在学生管理中导入行政班学生。"],
["4. 系统会按模板学生名单加入新教学班;学生若已在其他教学班,将自动转入新教学班。"],
["5. 任意一行校验失败时,整批导入创建失败,教学班和成员关系都不会写入。"],
]);
guideSheet["!cols"] = [{ wch: 96 }];
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, templateSheet, "教学班名单创建模板");
XLSX.utils.book_append_sheet(workbook, guideSheet, "填写说明");
XLSX.writeFile(workbook, "教学班名单创建模板.xlsx");
}
function deleteClass(id) {
ElMessageBox.confirm("确定删除该班级吗?", "提示", {
confirmButtonText: "确定",
@ -866,13 +761,6 @@ onMounted(() => {
width: 100%;
}
.import-create-actions {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.member-toolbar {
display: flex;
flex-wrap: wrap;

@ -22,7 +22,8 @@
</el-form-item>
<el-form-item label="班级:">
<el-select placeholder="全部" v-model="classParams.classId" style="width: 185.6px">
<el-option v-for="item in userStore.classList" :key="item" :label="item.class_name" :value="item.class_id" />
<el-option label="全部" value="" />
<el-option v-for="item in userStore.classList" :key="item.class_id" :label="item.class_name" :value="item.class_id" />
</el-select>
</el-form-item>
<el-form-item>
@ -48,8 +49,6 @@
<script setup>
import * as echarts from "echarts";
import * as teacherApi from "@/api/teacher.js";
const { proxy } = getCurrentInstance();
import { getAssetsFile } from "@/utils/index.js";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const classTime = ref([]);
@ -59,7 +58,6 @@ const classParams = ref({
classId: "",
time: "",
});
const initstatus = ref(false);
const circularData = ref([
{ value: 0, name: "一般", key: "generalCount" },
{ value: 0, name: "优秀", key: "excellentCount" },
@ -145,14 +143,15 @@ const getStatisticsData = async () => {
const getClassGradeTrend = () => {
teacherApi.getAverageScoreTrend().then((res) => {
const trends = Array.isArray(res) ? res : [];
classTime.value = trends[0]?.startTime || [];
classTime.value = [...new Set(trends.flatMap((item) => item.startTime || []))].sort();
className.value = trends.map((item) => item.className);
classList.value = trends.map((item) => {
const scoresByDate = new Map((item.startTime || []).map((date, index) => [date, item.classAverageScore?.[index] ?? null]));
return {
name: item.className,
type: "line",
stack: "Total",
data: item.classAverageScore,
connectNulls: false,
data: classTime.value.map((date) => scoresByDate.get(date) ?? null),
};
});
getTrendData();
@ -165,9 +164,6 @@ const getClassGradeStatistics = () => {
} else {
classParams.value.time = classParams.value.time.toString();
}
if (initstatus.value && !classParams.value.classId) {
proxy.$modal.msgWarning("请选择班级");
}
teacherApi.getScoreStatisticsTrend(classParams.value).then((res) => {
circularData.value.forEach((item, index) => {
item.value = res[item.key];
@ -186,7 +182,7 @@ const getClassGradeStatistics = () => {
};
// 获取班级
const getClassList = () => {
teacherApi.getOwnedTeachingClasses().then((res) => {
teacherApi.getTeacherHomeClasses().then((res) => {
userStore.classList = (res.data || []).map((item) => ({
class_name: item.className,
class_id: item.schoolClassId,
@ -197,7 +193,6 @@ onMounted(() => {
getClassGradeTrend();
getClassGradeStatistics()
getClassList()
initstatus.value = true;
});
</script>
<style lang='scss' scoped>

@ -28,14 +28,18 @@
</el-input>
</el-form-item>
<el-form-item label="班级:">
<el-select v-model="scoreParams.classId" placeholder="" clearable @change="getList">
<el-select v-model="scoreParams.classId" placeholder="请选择班级" @change="handleClassChange">
<el-option v-for="school in teachingClassList" :key="school.schoolClassId" :label="school.className" :value="school.schoolClassId" />
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="exportExcel">导出</el-button>
<el-button type="success" @click="scoreweight">权重设置</el-button>
<el-button type="success" @click="updateScore">成绩更新</el-button>
<el-button type="primary" :disabled="!scoreParams.classId" @click="exportExcel">导出</el-button>
<span :title="classActionHint">
<el-button type="success" :disabled="!canManageSelectedClass" @click="scoreweight">权重设置</el-button>
</span>
<span :title="classActionHint">
<el-button type="success" :disabled="!canManageSelectedClass" @click="updateScore">成绩更新</el-button>
</span>
</el-form-item>
</el-form>
<div class="table-info1">
@ -46,9 +50,21 @@
<el-table-column prop="username" label="学号" align="center" />
<el-table-column prop="className" label="班级" align="center" />
<el-table-column prop="score" label="参考成绩" align="center" />
<el-table-column label="老师评分" align="center" min-width="130">
<template #default="{ row }">
<div class="teacher-score-readonly">
<strong>{{ formatTeacherScore(row.teacherScore) }}</strong>
<small>自动汇总</small>
</div>
</template>
</el-table-column>
<el-table-column label="实训进度" align="center">
<template #default="{ row }">
<span :title="trainingProgressTitle(row)">{{ formatTrainingProgress(row) }}</span>
<span :title="trainingProgressTitle(row)">
已完成 {{ row.completedTaskCount || 0 }}/{{ row.totalTaskCount || 0 }}
<small v-if="row.trainingProgress !== null && row.trainingProgress !== undefined">({{ formatTrainingProgress(row) }})</small>
<small v-else>(--)</small>
</span>
</template>
</el-table-column>
<el-table-column label="成绩详情" align="center">
@ -100,7 +116,21 @@
</div>
</template>
</el-dialog>
<el-dialog v-model="scoreDetailsStart" title="成绩详情" width="50%" class="F_dialog teacher-dialog">
<el-dialog v-model="scoreDetailsStart" title="任务评阅" width="60%" class="F_dialog teacher-dialog">
<div class="score-detail-summary">
<div class="score-detail-summary__item">
<span>学生姓名</span>
<strong>{{ scoreDetailStudent.name || "--" }}</strong>
</div>
<div class="score-detail-summary__item">
<span>AI评测总分</span>
<strong>{{ formatScore(scoreDetailStudent.aiTotalScore) }}</strong>
</div>
<div class="score-detail-summary__item">
<span>老师评分</span>
<strong>{{ formatTeacherScore(scoreDetailStudent.teacherScore) }}</strong>
</div>
</div>
<el-table
:data="tableData"
border
@ -119,6 +149,23 @@
</template>
</el-table-column>
<el-table-column prop="aiAssessmentScore" label="AI评测成绩" align="center" />
<el-table-column label="教师评分" align="center" min-width="190">
<template #default="{ row }">
<div v-if="canManageSelectedClass && canScoreTask(row)" class="task-score-editor">
<el-input-number
v-model="row.teacherScoreDraft"
:min="0"
:max="100"
:precision="2"
:controls="false"
placeholder="0-100"
:aria-label="`给${row.taskName}评分`"
/>
<el-button type="primary" size="small" :loading="savingTaskId === row.taskId" @click="saveTaskTeacherScore(row)">保存</el-button>
</div>
<span v-else>{{ formatTeacherScore(row.teacherScore) }}</span>
</template>
</el-table-column>
</el-table>
</el-dialog>
</div>
@ -128,8 +175,12 @@ import * as indexApi from "@/api/teacher";
const { proxy } = getCurrentInstance();
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const currentUserId = computed(() => String(userStore.userInfo.userId || ""));
const workingCapitalList = ref([]);
const loading = ref(false);
const savingTaskId = ref("");
const classList = ref([]);
const teachingClassList = computed(() => classList.value.filter((item) => item.classType === "TEACHING"));
const scoreParams = ref({
classId: "",
index: 1,
@ -138,10 +189,26 @@ const scoreParams = ref({
});
const scoreDetailsStart = ref(false);
const tableData = ref([]);
const scoreDetailStudent = ref({
name: "",
aiTotalScore: null,
teacherScore: null,
});
const WeightStart = ref(false);
// 权重
const workingCapitalTotal = ref(0);
const scoreWeightObj = ref({});
const selectedTeachingClass = computed(() => teachingClassList.value.find(
(item) => item.schoolClassId === scoreParams.value.classId
));
const canManageSelectedClass = computed(() =>
Boolean(selectedTeachingClass.value)
&& String(selectedTeachingClass.value.createdBy || "") === currentUserId.value
);
const classActionHint = computed(() => canManageSelectedClass.value
? ""
: "权重设置和成绩更新仅限班级创建老师操作"
);
const formatTrainingProgress = (row) => {
if (row.trainingProgress === null || row.trainingProgress === undefined) return "--";
const percentage = Number(row.trainingProgress);
@ -152,6 +219,14 @@ const trainingProgressTitle = (row) => {
if (row.trainingProgress === null || row.trainingProgress === undefined) return "";
return `已完成 ${row.completedTaskCount || 0}/${row.totalTaskCount || 0} 项`;
};
const formatScore = (score) => {
if (score === null || score === undefined || score === "") return "--";
const value = Number(score);
return Number.isFinite(value) ? value.toFixed(2).replace(/\.00$/, "") : "--";
};
const formatTeacherScore = (score) => score === null || score === undefined || score === ""
? "待评阅"
: formatScore(score);
const weightFields = ["foundationWeight", "marketInsightWeight", "planningDesignWeight", "developmentValidationWeight", "launchOperationWeight", "comprehensiveTrainingWeight"];
const rules = Object.fromEntries(weightFields.map((field) => [field, [
{ required: true, message: "请输入权重", trigger: "blur" },
@ -165,12 +240,16 @@ const buildScoreQuery = () => {
};
};
const getList = () => {
if (!scoreParams.value.classId) {
workingCapitalList.value = [];
workingCapitalTotal.value = 0;
return Promise.resolve();
}
loading.value = true;
indexApi.getScoreList(buildScoreQuery()).then((res) => {
workingCapitalList.value = res.data.list;
return indexApi.getScoreList(buildScoreQuery()).then((res) => {
workingCapitalList.value = res.data.list || [];
workingCapitalTotal.value = res.data.total;
loading.value = false;
});
}).finally(() => (loading.value = false));
};
const scoreweight = () => {
if (!scoreParams.value.classId) {
@ -203,17 +282,32 @@ const workingCapitalWeightHandle = () => {
}
});
};
const classList = ref([]);
const teachingClassList = computed(() => classList.value.filter((item) => item.classType === "TEACHING"));
const getClassList = () => {
indexApi.getOwnedTeachingClasses().then((res) => {
classList.value = res.data;
const getClassList = async () => {
try {
const res = await indexApi.getAccessibleTeachingClasses();
classList.value = res.data || [];
if (scoreParams.value.classId && !teachingClassList.value.some((item) => item.schoolClassId === scoreParams.value.classId)) {
scoreParams.value.classId = "";
}
});
if (!scoreParams.value.classId) {
const ownClass = teachingClassList.value.find((item) => String(item.createdBy || "") === currentUserId.value);
scoreParams.value.classId = (ownClass || teachingClassList.value[0])?.schoolClassId || "";
}
getList();
} catch (error) {
workingCapitalList.value = [];
workingCapitalTotal.value = 0;
}
};
const handleClassChange = () => {
scoreParams.value.index = 1;
getList();
};
const exportExcel = () => {
if (!scoreParams.value.classId) {
proxy.$modal.msgWarning("请选择教学班后再导出成绩");
return;
}
const { index, size, ...query } = buildScoreQuery();
indexApi.exportScoreList(query).then((res) => {
// 打开怎么是空的
@ -228,14 +322,53 @@ const exportExcel = () => {
};
const getClassScoreDetail = (row) => {
if (!scoreParams.value.classId) {
proxy.$modal.msgWarning("请选择自己的教学班后再查看成绩详情");
proxy.$modal.msgWarning("请选择教学班后再查看成绩详情");
return;
}
scoreDetailStudent.value = {
userId: row.userId,
name: row.name,
aiTotalScore: row.score,
teacherScore: row.teacherScore,
};
indexApi.getScoreDetail({ userId: row.userId, classId: scoreParams.value.classId }).then((res) => {
tableData.value = res.data;
tableData.value = (res.data || []).map((item) => ({
...item,
teacherScoreDraft: item.teacherScore === null || item.teacherScore === undefined
? null
: Number(item.teacherScore),
}));
scoreDetailsStart.value = true;
});
};
const canScoreTask = (row) => Boolean(row.submitted) || row.progressStatus === "COMPLETED";
const saveTaskTeacherScore = (row) => {
if (row.teacherScoreDraft === null || row.teacherScoreDraft === undefined || row.teacherScoreDraft === "") {
proxy.$message.error("请输入教师评分");
return;
}
const score = Number(row.teacherScoreDraft);
if (!Number.isFinite(score) || score < 0 || score > 100) {
proxy.$message.error("教师评分必须为0至100之间的数值");
return;
}
savingTaskId.value = row.taskId;
indexApi.saveTaskTeacherScore({
classId: scoreParams.value.classId,
studentUserId: scoreDetailStudent.value.userId,
taskId: row.taskId,
teacherScore: score,
}).then(() => {
row.teacherScore = score;
proxy.$message.success("任务评分保存成功");
return getList();
}).then(() => {
const latest = workingCapitalList.value.find((item) => item.userId === scoreDetailStudent.value.userId);
if (latest) {
scoreDetailStudent.value.teacherScore = latest.teacherScore;
}
}).finally(() => (savingTaskId.value = ""));
};
// 更新成绩
const updateScore = () => {
if (!scoreParams.value.classId) {
@ -256,7 +389,6 @@ const updateScore = () => {
};
// 拿到当前路由信息
onMounted(() => {
getList();
getClassList();
});
</script>
@ -265,4 +397,59 @@ onMounted(() => {
background: #ffffff;
height: calc(100vh - 70px);
}
.task-score-editor {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
:deep(.el-input-number) {
width: 104px;
}
}
.score-detail-summary {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin-bottom: 16px;
}
.score-detail-summary__item {
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px 18px;
background: rgba(2, 167, 240, 0.08);
border: 1px solid rgba(2, 167, 240, 0.3);
border-radius: 6px;
span {
color: #7f9cab;
font-size: 13px;
}
strong {
color: #02a7f0;
font-size: 20px;
font-variant-numeric: tabular-nums;
}
}
.teacher-score-readonly {
display: inline-flex;
align-items: center;
gap: 8px;
strong {
color: #63dcff;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
small {
padding: 2px 7px;
color: rgba(190, 218, 231, 0.68);
border: 1px solid rgba(96, 172, 207, 0.28);
border-radius: 999px;
}
}
</style>

@ -11,7 +11,7 @@
<div class="df">
<div class="online">
<span>班级:</span>
<el-select v-model="paramsquery.schoolClassId" placeholder="" style="width: 14rem" clearable class="ml10">
<el-select v-model="paramsquery.schoolClassId" placeholder="" style="width: 14rem" clearable class="ml10" @change="handleClassFilterChange">
<el-option v-for="school in studentClassOptions" :key="school.schoolClassId" :label="school.className" :value="school.schoolClassId" />
</el-select>
</div>
@ -403,6 +403,11 @@ const normalizeClassType = (schoolClass) => {
return schoolClass?.createdBy ? "TEACHING" : "ADMIN";
};
const sameValue = (left, right) => String(left || "") === String(right || "");
const classCreateTime = (schoolClass) => {
if (!schoolClass?.createTime) return Number.MAX_SAFE_INTEGER;
const value = new Date(schoolClass.createTime).getTime();
return Number.isNaN(value) ? Number.MAX_SAFE_INTEGER : value;
};
const canUseAdminClassForStudent = (schoolClass) => {
if (normalizeClassType(schoolClass) !== "ADMIN") return false;
return !schoolClass?.schoolId || sameValue(schoolClass.schoolId, currentSchoolId.value);
@ -414,7 +419,7 @@ const teachingClassOptions = computed(() =>
normalizeClassType(schoolClass) === "TEACHING" &&
sameValue(schoolClass.schoolId, currentSchoolId.value) &&
(isManagerTeacher.value || sameValue(schoolClass.createdBy, currentUserId.value))
)
).sort((left, right) => classCreateTime(left) - classCreateTime(right))
);
const studentClassOptions = computed(() => teachingClassOptions.value);
const currentTeachingClassId = () => {
@ -430,10 +435,19 @@ const beforeImportStudents = (file) => {
return true;
};
const getClassList = () => {
indexApi.getClassListBySchoolId({ schoolId: userStore.userInfo.schoolId }).then((res) => {
return indexApi.getClassListBySchoolId({ schoolId: userStore.userInfo.schoolId }).then((res) => {
classList.value = res.data;
});
};
const selectDefaultStudentClass = () => {
if (!isManagerTeacher.value && !paramsquery.value.schoolClassId) {
paramsquery.value.schoolClassId = teachingClassOptions.value[0]?.schoolClassId || "";
}
};
const handleClassFilterChange = () => {
paramsquery.value.index = 1;
getList();
};
const classList1 = ref([]);
// 根据专业查班级
const getClassByMajor = () => {
@ -484,8 +498,9 @@ const initPassword = (row, status) => {
};
onMounted(async () => {
await userStore.ensureSchoolProductConfig().catch(() => null);
await getClassList();
selectDefaultStudentClass();
getList();
getClassList();
if (!isTeacherRosterMode.value) {
getFacultyList();
}

@ -45,8 +45,19 @@
>
<el-table-column label="教师姓名" prop="name" align="center"></el-table-column>
<el-table-column label="工号" prop="username" align="center"></el-table-column>
<el-table-column label="电话" prop="phone" align="center"></el-table-column>
<el-table-column label="邮箱" prop="email" align="center"></el-table-column>
<el-table-column label="名下班级" align="center" min-width="280">
<template #default="{ row }">
<div v-if="row.ownedClassNames?.length" class="owned-class-list" :title="row.ownedClassNames.join('、')">
<span v-for="className in row.ownedClassNames" :key="className" class="owned-class-chip">{{ className }}</span>
</div>
<span v-else class="empty-summary">暂无班级</span>
</template>
</el-table-column>
<el-table-column label="学生数量" align="center" width="130">
<template #default="{ row }">
<strong class="student-count">{{ Number(row.ownedStudentCount || 0) }}<small> 人</small></strong>
</template>
</el-table-column>
<el-table-column label="创建日期" prop="createTime" align="center">
<template #default="{ row }">
<span>{{ formatDate(row.createTime) }}</span>
@ -57,6 +68,7 @@
<template v-if="isManagerTeacher">
<el-button type="primary" text :disabled="row.hasCreatedClass" @click="editSchool(row)">编辑</el-button>
<el-button type="danger" text :disabled="row.hasCreatedClass" @click="delSchool(row)">删除</el-button>
<el-button type="warning" text @click="initializeTeacherPassword(row)">密码初始化</el-button>
<el-tag v-if="row.hasCreatedClass" type="warning" size="small">该教师已创建班级,不允许编辑或删除</el-tag>
</template>
<el-tag v-else type="info">仅查看</el-tag>
@ -101,6 +113,8 @@
</div>
</template>
<script setup>
import { ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
@ -228,6 +242,24 @@ const onClose = () => {
const refresh = () => {
getList();
};
const initializeTeacherPassword = (row) => {
ElMessageBox.confirm(
`确定将教师“${row.name || row.username}”的登录密码初始化为 123qwe 吗?`,
"密码初始化",
{
confirmButtonText: "确定初始化",
cancelButtonText: "取消",
type: "warning",
}
).then(() => {
indexApi
.initializeTeacherPassword({
userId: row.userId,
operatorId: currentUserId.value,
})
.then(() => proxy.$message.success("密码初始化成功"));
});
};
// 查询院系下拉列表
const facultyList = ref([]);
const getFacultyList = () => {
@ -260,14 +292,34 @@ const exportTeacher = () => {
URL.revokeObjectURL(url);
});
};
// 导入模版下载
const downloadTemplate = () => {
const a = document.createElement("a");
a.href = `/file/教师信息表格.xlsx`;
a.download = "模板文件.xlsx";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// 导入模板下载
const downloadTemplate = async () => {
const XLSX = await import("xlsx");
const templateSheet = XLSX.utils.aoa_to_sheet([
["院校名称", "院系名称", "专业名称", "教师姓名", "工号", "电话", "邮箱"],
["请填写系统中的院校名称", "请填写系统中的院系名称", "请填写系统中的专业名称", "张老师", "20260001", "13800000000", "teacher@example.com"],
]);
templateSheet["!cols"] = [
{ wch: 26 },
{ wch: 24 },
{ wch: 24 },
{ wch: 16 },
{ wch: 18 },
{ wch: 18 },
{ wch: 28 },
];
const guideSheet = XLSX.utils.aoa_to_sheet([
["填写说明"],
["1. 院校、院系和专业名称必须与系统中已维护的名称完全一致。"],
["2. 教师姓名和工号必填,工号只能填写数字且不能重复。"],
["3. 电话和邮箱可以留空;填写时必须符合手机号和邮箱格式。"],
["4. 默认密码为 123qwe,导入成功后请提醒教师及时修改密码。"],
]);
guideSheet["!cols"] = [{ wch: 80 }];
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, templateSheet, "教师导入模板");
XLSX.utils.book_append_sheet(workbook, guideSheet, "填写说明");
XLSX.writeFile(workbook, "教师账号导入模板.xlsx");
};
onMounted(() => {
@ -286,5 +338,39 @@ onMounted(() => {
align-items: center;
gap: 20px;
}
.owned-class-list {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
max-height: 68px;
overflow: auto;
padding: 4px;
}
.owned-class-chip {
display: inline-flex;
align-items: center;
min-height: 26px;
padding: 2px 10px;
color: #79dcff;
font-size: 12px;
line-height: 20px;
border: 1px solid rgba(55, 194, 255, 0.38);
border-radius: 999px;
background: rgba(15, 111, 164, 0.18);
}
.empty-summary {
color: rgba(184, 218, 235, 0.58);
}
.student-count {
color: #63dcff;
font-size: 18px;
font-variant-numeric: tabular-nums;
small {
color: rgba(210, 238, 248, 0.72);
font-size: 12px;
font-weight: 500;
}
}
}
</style>

@ -104,7 +104,7 @@
<div class="drawer-heading">
<span class="drawer-kicker">{{ dialogMode === "view" ? "Training Task Preview" : "Training Task Editor" }}</span>
<h3>{{ dialogMode === "view" ? "查看实训任务" : "编辑实训任务" }}</h3>
<p>老师可维护任务显示名称、实训说明、目标、要求和步骤,并可新增或删除步骤。</p>
<p>老师可维护任务显示名称、实训说明、目标、要求和步骤名称;步骤数量与学生端保持一致。</p>
</div>
<div class="drawer-header-actions">
<button type="button" class="drawer-close-button" aria-label="关闭抽屉" @click="dialogVisible = false">x</button>
@ -188,16 +188,14 @@
</el-upload>
</div>
<el-form-item label="步骤名称:">
<el-form-item :label="`步骤名称(固定 ${taskForm.steps.length} 步):`">
<div class="step-row">
<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="!isReadonly" text type="danger" @click="removeStep(index)">删除</el-button>
</div>
<span v-if="index < taskForm.steps.length - 1" class="step-arrow">&gt;&gt;&gt;</span>
</template>
<el-button v-if="!isReadonly" plain class="add-step-button" @click="addStep">新增步骤</el-button>
</div>
</el-form-item>
</section>
@ -235,6 +233,7 @@ import {
import { createStudentDemoSession } from "@/api/studentDemo";
import * as indexApi from "@/api/teacher";
import useUserStore from "@/store/modules/user";
import { getStudentTrainingStepCount } from "@/views/training/taskKeyMap";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
@ -410,7 +409,7 @@ function normalizeTask(task) {
requirements: task.requirements || "",
materialName: material.name,
materialUrl: material.url,
steps: normalizeSteps(parseArray(task.steps, createBuiltinSteps())),
steps: normalizeTaskSteps(task.taskKey, parseArray(task.steps, [])),
sort: task.sort || 0,
enabled: task.enabled !== false,
};
@ -467,17 +466,16 @@ function parseArray(value, fallback) {
}
}
function normalizeSteps(steps) {
function normalizeTaskSteps(taskKey, steps) {
const source = Array.isArray(steps) ? steps : [];
const result = source
.map((item, index) => {
const expectedCount = getStudentTrainingStepCount(taskKey);
return Array.from({ length: expectedCount }, (_, index) => {
const item = source[index];
const raw = item && typeof item === "object" ? item : {};
const name = typeof item === "object" ? String(raw.name || "").trim() : String(item || "").trim();
const kind = raw.kind === "custom" ? "custom" : index < 4 ? "builtin" : "custom";
return createStep(name, kind, raw.id);
})
.filter((item) => item.name);
return result.length ? result : [createStep()];
const savedName = typeof item === "object" ? String(raw.name || "").trim() : String(item || "").trim();
const name = savedName || `步骤 ${String(index + 1).padStart(2, "0")}`;
return createStep(name, "builtin", `builtin-${index + 1}`);
});
}
function createBuiltinSteps() {
@ -502,7 +500,7 @@ function cloneTask(task) {
return {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
steps: normalizeSteps(task.steps?.length ? task.steps : createBuiltinSteps()),
steps: normalizeTaskSteps(task.taskKey, task.steps),
};
}
@ -515,15 +513,6 @@ function removeObjective(index) {
taskForm.objectives.splice(index, 1);
}
function addStep() {
taskForm.steps.push(createStep());
}
function removeStep(index) {
if (taskForm.steps.length <= 1) return;
taskForm.steps.splice(index, 1);
}
async function handleMaterialChange(file) {
const rawFile = file?.raw;
if (!rawFile) return;
@ -632,6 +621,7 @@ async function confirmRestoreDefault(action) {
}
function buildPayload() {
const fixedSteps = normalizeTaskSteps(taskForm.taskKey, taskForm.steps);
return {
projectName: taskForm.project,
taskKey: taskForm.taskKey,
@ -639,7 +629,7 @@ function buildPayload() {
background: taskForm.background,
objectives: JSON.stringify(taskForm.objectives.map((item) => item.trim()).filter(Boolean)),
requirements: taskForm.requirements,
steps: JSON.stringify(taskForm.steps.map((item) => ({ ...item, name: item.name.trim() })).filter((item) => item.name)),
steps: JSON.stringify(fixedSteps),
materialName: taskForm.materialName,
materialUrl: taskForm.materialUrl,
sort: taskForm.sort,
@ -1358,10 +1348,6 @@ function buildPayload() {
flex: 1 1 260px;
}
.add-step-button {
border-style: dashed;
}
.step-arrow {
color: #7ddaff;
font-weight: 800;

@ -56,7 +56,7 @@
<tfoot><tr><th colspan="2">当前权重合计</th><td :class="{ 'total-error': weightTotal !== 100 }">{{ displayWeightTotal }}%</td><td></td></tr></tfoot>
</table>
</div>
<p class="hint">默认展示建议的评估维度和权重占比。可修改任意单元格,也可逐行新增、删除;点击下一步时系统校验所有权重之和必须等于 100%。</p>
<p class="hint">默认展示建议的评估维度和建议权重范围,具体权重需由学生自行填写。可修改任意单元格,也可逐行新增、删除;点击下一步时系统校验所有权重之和必须等于 100%。</p>
<footer class="footer-actions">
<el-button :loading="saving" @click="saveWeightStep">保存当前进度</el-button>
<el-button type="primary" :loading="validating" @click="goStepTwo">下一步<el-icon><ArrowRight /></el-icon></el-button>
@ -72,7 +72,7 @@
</div>
<div class="table-wrap">
<table class="channel-table">
<thead><tr><th>渠道</th><th>日均总搜索量</th><th>供需比</th><th>平均点击率(%)</th><th>平均CPC(元)</th><th>平均转化率(%)</th><th>现有相关访客数</th><th>匹配度(1-5)</th><th class="operation-column">操作</th></tr></thead>
<thead><tr><th>渠道</th><th>日均总搜索量</th><th>供需比</th><th>平均点击率(%)</th><th>平均CPC(元)</th><th>平均转化率(%)</th><th>现有相关访客数</th><th>匹配度(1-100)</th><th class="operation-column">操作</th></tr></thead>
<tbody>
<tr v-for="(row, index) in channelRows" :key="row.id">
<td><el-input v-model="row.channel" maxlength="30" placeholder="填写渠道" /></td>
@ -82,7 +82,7 @@
<td><el-input-number v-model="row.averageCpc" :min="0" :precision="2" controls-position="right" /></td>
<td><el-input-number v-model="row.averageConversionRate" :min="0" :max="100" :precision="2" controls-position="right" /></td>
<td><el-input-number v-model="row.existingVisitorCount" :min="0" :precision="0" controls-position="right" /></td>
<td><el-input-number v-model="row.matchingScore" :min="1" :max="5" :precision="0" controls-position="right" /></td>
<td><el-input-number v-model="row.matchingScore" :min="1" :max="100" :precision="0" controls-position="right" /></td>
<td class="operation-column"><el-button link type="danger" @click="channelRows.splice(index, 1)">删除本行</el-button></td>
</tr>
<tr v-if="!channelRows.length"><td colspan="9" class="empty-row">暂无渠道数据,请增加一行后填写。</td></tr>
@ -99,6 +99,7 @@
<section v-else-if="activeStep === 3">
<p class="scoring-guide">通过 Min-Max 归一法将各维度原始数据转换为 0–10 分标准化得分。正向指标(搜索量、点击率、转化率、访客数、匹配度)按“渠道值 − 最小值”计算;逆向指标(供需比、CPC)按“最大值 − 渠道值”计算。请根据前两步数据手工填写得分与加权得分。</p>
<div class="table-actions"><el-button type="primary" plain @click="exportScoreRows"><el-icon><Download /></el-icon>导出</el-button></div>
<div class="table-wrap scoring-table-wrap">
<table class="scoring-table">
<thead>
@ -124,8 +125,8 @@
</tbody>
</table>
</div>
<p class="hint">渠道名称同步第二步,权重同步第一步。每项得分乘以对应权重(按百分比折算)并相加得到加权得分;下一步会按已保存的前两步数据重新计算并校验。</p>
<p class="step-three-notice">说明:渠道来自第二步,权重来自第一步;每个维度得分乘以权重后相加即为加权得分。系统会校验加权得分,填写不正确不能进入下一步。</p>
<p class="hint">渠道名称同步第二步,权重同步第一步。每项得分乘以对应权重(按百分比折算)并相加得到加权得分;系统会依据已保存的前两步数据检测计算结果。</p>
<p class="step-three-notice">说明:渠道来自第二步,权重来自第一步;每个维度得分乘以权重后相加即为加权得分。计算结果不一致时仍可进入下一步,系统会记录检测结果,供 AI 助评扣分参考。</p>
<section class="step-three-materials" aria-label="归一化评分参考资料">
<p>参考方法及工具如下:下载案例数据表,使用 Excel 按 Min-Max 公式计算各渠道归一化得分,可参考《实训操作说明》完成。</p>
<el-button type="primary" class="step-three-materials__button" @click="downloadPracticeGuide"><el-icon><Download /></el-icon>下载实训操作说明</el-button>
@ -186,8 +187,8 @@ const validating = ref(false);
let nextId = 1;
const makeRow = (values = {}) => ({ id: nextId++, ...values });
const defaultWeightRows = () => [
["市场规模潜力", "对应关键词日均总搜索量,代表渠道用户需求大盘空间", 20, "20~25"], ["竞争激烈程度", "供需比(在线商品数/日均搜索量),数值越低渠道竞争越宽松", 15, "15~20"], ["流量点击效率", "品类平均点击率,代表渠道用户对该品类的点击意愿强弱", 15, "12~18"], ["流量获取成本", "平均CPC,数值越低获取精准用户的推广成本越低", 15, "15~20"], ["流量转化效率", "品类平均转化率,代表渠道用户的最终下单意愿", 15, "12~18"], ["现有用户基础", "店铺现有该品类相关访客数,代表品牌存量用户承接能力", 10, "5~10"], ["匹配度", "渠道属性与产品定位的适配度打分(1-10分)", 10, "5~10"],
].map(([dimension, description, weight, suggestion]) => makeRow({ dimension, description, weight, suggestion }));
["市场规模潜力", "对应关键词日均总搜索量,代表渠道用户需求大盘空间", "20~25"], ["竞争激烈程度", "供需比(在线商品数/日均搜索量),数值越低渠道竞争越宽松", "15~20"], ["流量点击效率", "品类平均点击率,代表渠道用户对该品类的点击意愿强弱", "12~18"], ["流量获取成本", "平均CPC,数值越低获取精准用户的推广成本越低", "15~20"], ["流量转化效率", "品类平均转化率,代表渠道用户的最终下单意愿", "12~18"], ["现有用户基础", "店铺现有该品类相关访客数,代表品牌存量用户承接能力", "5~10"], ["匹配度", "渠道属性与产品定位的适配度打分(1-10分)", "5~10"],
].map(([dimension, description, suggestion]) => makeRow({ dimension, description, weight: undefined, suggestion }));
const defaultChannelRows = () => ["天猫", "京东", "抖音", "拼多多", "唯品会"].map((channel) => makeRow({ channel }));
const weightSuggestions = Object.fromEntries(defaultWeightRows().map((row) => [row.dimension, row.suggestion]));
const weightRows = ref(defaultWeightRows());
@ -215,6 +216,12 @@ const progressItems = computed(() => parseTrainingArray(taskConfig.value?.steps)
const weightPayload = () => ({ rows: weightRows.value.map(({ dimension, description, weight }) => ({ dimension, description, weight })) });
const channelPayload = () => ({ rows: channelRows.value.map(({ channel, dailySearchVolume, supplyDemandRatio, averageClickRate, averageCpc, averageConversionRate, existingVisitorCount, matchingScore }) => ({ channel, dailySearchVolume, supplyDemandRatio, averageClickRate, averageCpc, averageConversionRate, existingVisitorCount, matchingScore })) });
const scorePayload = () => ({ rows: scoreRows.value.map((row) => ({ channel: row.channel, weightedScore: row.weightedScore, dimensions: row.dimensions.map(({ dimension, score, weight }) => ({ dimension, score, weight })) })) });
const scoreAnswerPayload = (calculationCheck = {}) => ({ ...scorePayload(), calculationCheck: {
calculationCorrect: calculationCheck.calculationCorrect === true,
totalItemCount: Number(calculationCheck.totalItemCount) || 0,
incorrectItemCount: Number(calculationCheck.incorrectItemCount) || 0,
incorrectItems: Array.isArray(calculationCheck.incorrectItems) ? calculationCheck.incorrectItems : [],
} });
const rankingPayload = () => ({ rows: rankingRows.value.map(({ channel, weightedScore }) => ({ channel, weightedScore })), coreChannelAnalysis: coreChannelAnalysis.value });
function addWeightRow() { weightRows.value.push(makeRow({ dimension: "", description: "", weight: undefined, suggestion: "" })); }
function addChannelRow() { channelRows.value.push(makeRow({ channel: "" })); }
@ -226,7 +233,7 @@ async function validateChannelStep() { if (validating.value) return; validating.
function syncScoreRows(savedRows = []) { const savedByChannel = new Map(savedRows.map((row) => [row?.channel, row])); const weights = Object.fromEntries(weightRows.value.map((row) => [row.dimension, row.weight])); scoreRows.value = channelRows.value.map((channelRow) => { const saved = savedByChannel.get(channelRow.channel); const savedScores = new Map((saved?.dimensions || []).map((dimension) => [dimension?.dimension, dimension])); return makeRow({ channel: channelRow.channel, weightedScore: saved?.weightedScore, dimensions: scoringMetrics.map((metric) => makeRow({ key: metric.key, dimension: metric.dimension, weight: weights[metric.dimension], score: savedScores.get(metric.dimension)?.score })) }); }); }
function openStepThree() { syncScoreRows(scoreRows.value); activeStep.value = 3; }
async function saveScoreStep() { if (saving.value) return; saving.value = true; try { await saveAnswer(3, { step3Answer: JSON.stringify(scorePayload()) }); ElMessage.success("当前进度已保存"); } finally { saving.value = false; } }
async function validateScoreStep() { if (validating.value) return; validating.value = true; try { await validateReleaseChannelEvaluationStepThree(scorePayload()); await saveAnswer(4, { step3Answer: JSON.stringify(scorePayload()) }); syncRankingRows(); activeStep.value = 4; ElMessage.success("归一化得分与加权得分校验通过,已进入第四步"); } catch (error) { ElMessage.error(error?.message || "请检查归一化得分和加权得分"); } finally { validating.value = false; } }
async function validateScoreStep() { if (validating.value) return; validating.value = true; try { const result = await validateReleaseChannelEvaluationStepThree(scorePayload()); const calculationCheck = result?.data || {}; await saveAnswer(4, { step3Answer: JSON.stringify(scoreAnswerPayload(calculationCheck)) }); syncRankingRows(); activeStep.value = 4; ElMessage[calculationCheck.calculationCorrect ? "success" : "warning"](calculationCheck.message || "已保存并进入第四步"); } catch (error) { ElMessage.error(error?.message || "请完整填写归一化得分表"); } finally { validating.value = false; } }
function syncRankingRows(savedRows = []) { const savedByChannel = new Map(savedRows.map((row) => [row?.channel, row])); rankingRows.value = scoreRows.value.map((scoreRow) => { const saved = savedByChannel.get(scoreRow.channel); return makeRow({ channel: saved?.channel ?? "", weightedScore: saved?.weightedScore }); }); }
function openStepFour() { syncRankingRows(rankingRows.value); activeStep.value = 4; }
async function saveRankingStep() { if (saving.value) return; saving.value = true; try { await saveAnswer(4, { step4Answer: JSON.stringify(rankingPayload()) }); ElMessage.success("当前进度已保存"); } finally { saving.value = false; } }
@ -242,7 +249,9 @@ function downloadBuiltInFile(url, fileName) {
link.click();
document.body.removeChild(link);
}
function exportChannelRows() { const headers = ["渠道", "日均总搜索量", "供需比", "平均点击率(%)", "平均CPC(元)", "平均转化率(%)", "现有相关访客数", "匹配度(1-5)"]; const escape = (value) => `"${String(value ?? "").replaceAll('"', '""')}"`; const lines = [headers, ...channelRows.value.map((row) => [row.channel, row.dailySearchVolume, row.supplyDemandRatio, row.averageClickRate, row.averageCpc, row.averageConversionRate, row.existingVisitorCount, row.matchingScore])].map((row) => row.map(escape).join(",")); const url = URL.createObjectURL(new Blob([`\uFEFF${lines.join("\n")}`], { type: "text/csv;charset=utf-8" })); const link = document.createElement("a"); link.href = url; link.download = "产品发布渠道评估-渠道数据.csv"; link.click(); URL.revokeObjectURL(url); }
function downloadCsv(headers, rows, fileName) { const escape = (value) => `"${String(value ?? "").replaceAll('"', '""')}"`; const lines = [headers, ...rows].map((row) => row.map(escape).join(",")); const url = URL.createObjectURL(new Blob([`\uFEFF${lines.join("\n")}`], { type: "text/csv;charset=utf-8" })); const link = document.createElement("a"); link.href = url; link.download = fileName; link.click(); URL.revokeObjectURL(url); }
function exportChannelRows() { downloadCsv(["渠道", "日均总搜索量", "供需比", "平均点击率(%)", "平均CPC(元)", "平均转化率(%)", "现有相关访客数", "匹配度(1-100)"], channelRows.value.map((row) => [row.channel, row.dailySearchVolume, row.supplyDemandRatio, row.averageClickRate, row.averageCpc, row.averageConversionRate, row.existingVisitorCount, row.matchingScore]), "产品发布渠道评估-渠道数据.csv"); }
function exportScoreRows() { const headers = ["渠道", ...scoringMetrics.flatMap((metric) => [`${metric.dimension}得分`, `${metric.dimension}权重(%)`]), "加权得分"]; const rows = scoreRows.value.map((row) => [row.channel, ...row.dimensions.flatMap((dimension) => [dimension.score, dimension.weight]), row.weightedScore]); downloadCsv(headers, rows, "产品发布渠道评估-归一化评分.csv"); }
function restoreRows(raw, target, defaults, fields) { try { const saved = typeof raw === "string" ? JSON.parse(raw || "{}") : raw; if (!Array.isArray(saved?.rows)) return; target.value = saved.rows.map((row) => { const value = Object.fromEntries(fields.map((field) => [field, row?.[field]])); return makeRow(target === weightRows ? { ...value, suggestion: weightSuggestions[value.dimension] || "" } : value); }); } catch (error) { target.value = defaults(); } }
async function loadProgress() { try { const result = await getStudentTrainingAnswer(TASK_KEY); const answer = result?.data; restoreRows(answer?.step1Answer, weightRows, defaultWeightRows, ["dimension", "description", "weight"]); restoreRows(answer?.step2Answer, channelRows, defaultChannelRows, ["channel", "dailySearchVolume", "supplyDemandRatio", "averageClickRate", "averageCpc", "averageConversionRate", "existingVisitorCount", "matchingScore"]); let savedScores = []; try { const saved = typeof answer?.step3Answer === "string" ? JSON.parse(answer.step3Answer || "{}") : answer?.step3Answer; savedScores = Array.isArray(saved?.rows) ? saved.rows : []; } catch (error) { savedScores = []; } syncScoreRows(savedScores); let savedRanking = []; try { const saved = typeof answer?.step4Answer === "string" ? JSON.parse(answer.step4Answer || "{}") : answer?.step4Answer; savedRanking = Array.isArray(saved?.rows) ? saved.rows : []; coreChannelAnalysis.value = String(saved?.coreChannelAnalysis || ""); } catch (error) { savedRanking = []; coreChannelAnalysis.value = ""; } syncRankingRows(savedRanking); activeStep.value = Math.min(Math.max(Number(answer?.currentStep) || 1, 1), 4); } catch (error) { syncScoreRows(); syncRankingRows(); } }
onMounted(async () => { try { const result = await getTrainingTaskByKey(TASK_KEY); taskConfig.value = result?.data || null; } catch (error) { taskConfig.value = null; } await loadProgress(); });

@ -284,4 +284,5 @@ onMounted(async () => { try { const result = await getTrainingTaskByKey(TASK_KEY
</style>
<style scoped lang="scss">
.evaluation-form{padding-top:4px}.evaluation-intro{padding:18px;margin-top:14px;border:1px solid rgba(99,183,222,.36);border-radius:14px;background:rgba(8,42,64,.36)}.evaluation-intro p,.decision-section>p{color:#c8e5f1;line-height:1.75}.overall-roi{display:flex;flex-wrap:wrap;gap:12px;margin-top:14px}.overall-roi span{padding:7px 12px;border:1px solid rgba(99,183,222,.42);border-radius:999px;color:#d7f0fa;background:rgba(3,27,43,.58);font-weight:800}.overall-roi .achieved{border-color:rgba(81,224,178,.72);color:#86f3ca}.overall-roi .underperforming{border-color:rgba(255,152,152,.7);color:#ffb0b0}.evaluation-table-wrap{overflow-x:auto;margin-top:24px;border:1px solid rgba(99,183,222,.46);border-radius:14px}.evaluation-table{width:100%;min-width:1050px;border-collapse:collapse}.evaluation-table th,.evaluation-table td{padding:12px;border-right:1px solid rgba(99,183,222,.35);border-bottom:1px solid rgba(99,183,222,.35);vertical-align:middle}.evaluation-table th{white-space:nowrap;color:#effaff;background:#0c9dd6;font-size:14px}.evaluation-table td{background:rgba(2,21,34,.58)}.evaluation-table th:first-child{min-width:110px}.evaluation-table td:nth-child(2){min-width:100px}.evaluation-table td:nth-child(3){min-width:145px}.evaluation-table td:nth-child(4),.evaluation-table td:nth-child(5){min-width:250px}.evaluation-table :deep(.el-select){width:100%}.evaluation-table :deep(.el-input__wrapper),.evaluation-table :deep(.el-textarea__inner),.decision-section :deep(.el-textarea__inner){box-shadow:0 0 0 1px rgba(111,190,225,.3) inset;color:#fff;background:#102233}.synced-roi{color:#7ce4ff;text-align:center;font-size:16px;font-weight:900}.decision-section{margin-top:30px}.decision-section :deep(.el-textarea__inner){min-height:170px!important;padding:12px 14px;line-height:1.75}@media (max-width:720px){.overall-roi{align-items:stretch;flex-direction:column}}
.strategy-reference :deep(.el-collapse-item__content){color:#d8f2ff}.strategy-reference .reference-table td{color:#d8f2ff;font-size:14px;font-weight:500}.strategy-reference .reference-table td:nth-child(2),.strategy-reference .reference-table td:nth-child(3){color:#91e2ff;font-weight:700}
</style>

@ -18,42 +18,37 @@
class="comprehensive-training-toolbar"
:material-name="page.material?.name"
:material-url="page.material?.url"
:task-key="pageKey"
:on-submit="submitTask"
:on-reset="resetTraining"
:on-export="exportOutcome"
/>
</div>
<nav v-if="isComprehensiveTurnNavigation" class="comprehensive-turn-nav" aria-label="实训步骤">
<div class="comprehensive-turn-row comprehensive-turn-row--forward">
<template v-for="item in comprehensiveTurnForwardSteps" :key="`${item.step}-${item.index}`">
<button
type="button"
:class="['step-tab', { active: currentStep === item.index + 1, complete: currentStep > item.index + 1 }]"
:aria-label="`切换至第 ${item.index + 1} 步:${item.step}`"
:aria-current="currentStep === item.index + 1 ? 'step' : undefined"
@click="currentStep = item.index + 1"
<nav
v-if="isComprehensiveCaseTraining && indexedConfiguredSteps.length"
ref="comprehensiveStepNavRef"
:class="['comprehensive-step-nav', { 'is-dragging': comprehensiveNavDragging }]"
aria-label="综合实训步骤,可左右拖动浏览"
@dragstart.prevent
@pointerdown="startComprehensiveNavDrag"
@pointermove="moveComprehensiveNavDrag"
@pointerup="endComprehensiveNavDrag"
@pointercancel="endComprehensiveNavDrag"
>
<span class="step-marker" aria-hidden="true">{{ String(item.index + 1).padStart(2, '0') }}</span>
<span class="step-copy"><strong class="step-name" :title="item.step">{{ item.step }}</strong><span class="step-action">{{ currentStep === item.index + 1 ? '当前步骤' : '点击切换' }} <span aria-hidden="true">→</span></span></span>
</button>
<span v-if="item.index < comprehensiveTurnForwardSteps[comprehensiveTurnForwardSteps.length - 1]?.index" class="step-connector" aria-hidden="true"></span>
</template>
</div>
<span class="comprehensive-turn-rail" aria-hidden="true"></span>
<div class="comprehensive-turn-row comprehensive-turn-row--return">
<template v-for="item in comprehensiveTurnReturnSteps" :key="`${item.step}-${item.index}`">
<div class="comprehensive-step-strip">
<template v-for="item in indexedConfiguredSteps" :key="`${item.step}-${item.index}`">
<button
type="button"
:class="['step-tab', { active: currentStep === item.index + 1, complete: currentStep > item.index + 1 }]"
:aria-label="`切换至第 ${item.index + 1} 步:${item.step}`"
:aria-current="currentStep === item.index + 1 ? 'step' : undefined"
@click="currentStep = item.index + 1"
@click="selectComprehensiveStep(item.index + 1)"
>
<span class="step-marker" aria-hidden="true">{{ String(item.index + 1).padStart(2, '0') }}</span>
<span class="step-copy"><strong class="step-name" :title="item.step">{{ item.step }}</strong><span class="step-action">{{ currentStep === item.index + 1 ? '当前步骤' : '点击切换' }} <span aria-hidden="true">←</span></span></span>
<span class="step-copy"><strong class="step-name" :title="item.step">{{ item.step }}</strong><span class="step-action">{{ currentStep === item.index + 1 ? '当前步骤' : '点击切换' }} <span aria-hidden="true">→</span></span></span>
</button>
<span v-if="item.index > comprehensiveTurnReturnSteps[comprehensiveTurnReturnSteps.length - 1]?.index" class="step-connector step-connector--reverse" aria-hidden="true"></span>
<span v-if="item.index < indexedConfiguredSteps.length - 1" class="step-connector" aria-hidden="true"></span>
</template>
</div>
</nav>
@ -747,10 +742,14 @@ const uploading = ref(false);
const currentStep = ref(1);
const configuredSteps = computed(() => parseArray(remoteTask.value?.steps));
const indexedConfiguredSteps = computed(() => configuredSteps.value.map((step, index) => ({ step, index })));
const isComprehensiveTurnNavigation = computed(() => isComprehensiveCaseTraining.value && indexedConfiguredSteps.value.length > 7);
// 综合实训专用折返步骤条:上行保留更宽的文字空间,下行承载剩余四步。
const comprehensiveTurnForwardSteps = computed(() => indexedConfiguredSteps.value.slice(0, 6));
const comprehensiveTurnReturnSteps = computed(() => indexedConfiguredSteps.value.slice(6).reverse());
const comprehensiveStepNavRef = ref(null);
const comprehensiveNavDragging = ref(false);
const comprehensiveNavDrag = {
pointerId: null,
startX: 0,
startScrollLeft: 0,
moved: false,
};
const activeStepName = computed(() => configuredSteps.value[currentStep.value - 1] || configuredSteps.value[0] || "");
const visibleProcessRows = computed(() => {
if (!configuredSteps.value.length || !processRows.value.length) {
@ -793,6 +792,48 @@ watch(configuredSteps, (steps) => {
currentStep.value = Math.min(Math.max(currentStep.value, 1), steps.length);
});
function startComprehensiveNavDrag(event) {
if (event.pointerType === "mouse" && event.button !== 0) return;
const nav = comprehensiveStepNavRef.value;
if (!nav) return;
comprehensiveNavDrag.pointerId = event.pointerId;
comprehensiveNavDrag.startX = event.clientX;
comprehensiveNavDrag.startScrollLeft = nav.scrollLeft;
comprehensiveNavDrag.moved = false;
comprehensiveNavDragging.value = true;
nav.setPointerCapture?.(event.pointerId);
}
function moveComprehensiveNavDrag(event) {
if (!comprehensiveNavDragging.value || event.pointerId !== comprehensiveNavDrag.pointerId) return;
const nav = comprehensiveStepNavRef.value;
if (!nav) return;
const distance = event.clientX - comprehensiveNavDrag.startX;
if (Math.abs(distance) > 4) {
comprehensiveNavDrag.moved = true;
event.preventDefault();
}
nav.scrollLeft = comprehensiveNavDrag.startScrollLeft - distance;
}
function endComprehensiveNavDrag(event) {
if (event.pointerId !== comprehensiveNavDrag.pointerId) return;
const nav = comprehensiveStepNavRef.value;
if (nav?.hasPointerCapture?.(event.pointerId)) {
nav.releasePointerCapture(event.pointerId);
}
comprehensiveNavDragging.value = false;
comprehensiveNavDrag.pointerId = null;
}
function selectComprehensiveStep(step) {
if (comprehensiveNavDrag.moved) {
comprehensiveNavDrag.moved = false;
return;
}
currentStep.value = step;
}
async function loadRemoteTask() {
remoteTask.value = null;
if (!pageKey.value) return;
@ -2004,86 +2045,68 @@ function exportOutcome() {
border-color: #63e6f1;
}
.comprehensive-turn-nav {
.comprehensive-step-nav {
position: relative;
width: calc(100% + 24px);
margin: 0 -12px 32px;
padding: 18px 22px;
overflow-x: auto;
overflow-y: hidden;
border: 1px solid rgba(53, 178, 222, 0.42);
border-radius: 22px;
background: linear-gradient(90deg, rgba(4, 29, 47, 0.94), rgba(5, 44, 67, 0.75));
cursor: grab;
overscroll-behavior-x: contain;
scroll-behavior: smooth;
scrollbar-width: thin;
scrollbar-color: rgba(86, 189, 227, 0.75) rgba(11, 43, 63, 0.75);
touch-action: pan-y;
user-select: none;
}
.comprehensive-step-nav.is-dragging {
cursor: grabbing;
scroll-behavior: auto;
}
.comprehensive-turn-row {
.comprehensive-step-strip {
display: flex;
align-items: center;
min-width: 1040px;
width: max-content;
min-width: 100%;
}
.comprehensive-turn-row .step-tab {
flex: 1 1 0;
min-width: 112px;
.comprehensive-step-strip .step-tab {
flex: 0 0 190px;
width: 190px;
min-width: 190px;
}
.comprehensive-turn-row .step-name {
.comprehensive-step-strip .step-name {
display: block;
white-space: nowrap;
font-size: 13px;
-webkit-line-clamp: unset;
}
.comprehensive-turn-row .step-marker {
.comprehensive-step-strip .step-marker {
flex-basis: 32px;
width: 32px;
height: 32px;
font-size: 11px;
}
.comprehensive-turn-row .step-copy {
.comprehensive-step-strip .step-copy {
margin-left: 8px;
}
.comprehensive-turn-row .step-connector {
flex: 0 1 30px;
min-width: 14px;
.comprehensive-step-strip .step-connector {
flex: 0 0 30px;
width: 30px;
min-width: 30px;
margin: 0 5px;
}
.comprehensive-turn-row--return {
justify-content: flex-end;
}
.comprehensive-turn-row--return .step-tab {
flex: 0 1 190px;
}
.comprehensive-turn-rail {
display: block;
position: relative;
width: 2px;
height: 44px;
margin-left: auto;
background: rgba(98, 169, 201, 0.48);
}
.comprehensive-turn-rail::after {
position: absolute;
bottom: -1px;
left: -1px;
width: 7px;
height: 7px;
border-bottom: 1px solid #73b1ce;
border-left: 1px solid #73b1ce;
content: "";
transform: translateX(-50%) rotate(45deg);
}
.step-connector--reverse::after {
right: auto;
left: -1px;
transform: translateY(-50%) rotate(225deg);
}
.step-title-row {
display: flex;
align-items: flex-start;
@ -2628,45 +2651,34 @@ function exportOutcome() {
transform: translateX(-50%) rotate(135deg);
}
.comprehensive-turn-nav {
.comprehensive-step-nav {
width: 100%;
margin: 0 0 32px;
padding: 16px;
overflow: visible;
}
.comprehensive-turn-row {
flex-direction: column;
align-items: stretch;
min-width: 0;
}
.comprehensive-turn-row--return {
justify-content: flex-start;
}
.comprehensive-turn-row .step-tab {
flex: 0 0 auto;
width: 100%;
overflow-x: auto;
}
.comprehensive-turn-row .step-connector {
flex: 0 0 20px;
width: 2px;
height: 20px;
margin: 4px 0 4px 18px;
.comprehensive-step-strip .step-tab {
flex: 0 0 172px;
width: 172px;
min-width: 172px;
}
.comprehensive-turn-rail {
display: none;
.comprehensive-step-strip .step-connector {
flex: 0 0 24px;
width: 24px;
min-width: 24px;
height: 2px;
align-self: center;
margin: 0 5px;
}
.comprehensive-turn-nav .step-connector--reverse::after {
top: auto;
right: auto;
bottom: -1px;
left: 50%;
transform: translateX(-50%) rotate(135deg);
.comprehensive-step-strip .step-connector::after {
top: 50%;
right: -1px;
bottom: auto;
left: auto;
transform: translateY(-50%) rotate(45deg);
}
.product-development-process-page {

@ -33,6 +33,40 @@ export const trainingTaskKeyByPath = {
"/assessment/optimization": "category-optimization",
};
// Each training page implements a fixed number of student-facing steps. Keep the
// teacher editor aligned with those page capabilities instead of the legacy
// four-step backend default.
export const studentTrainingStepCountByTaskKey = Object.freeze({
"new-product-survey": 4,
"product-development-factors": 4,
"product-development-process": 4,
"industry-demand-analysis": 4,
"competitive-environment-analysis": 4,
"market-opportunity-selection": 6,
"business-feasibility": 3,
"target-user-profile": 5,
"consumer-behavior": 4,
"consumer-scenario": 4,
"feature-conversion": 4,
"product-value-positioning": 4,
"product-structure": 4,
"after-sales-service": 3,
"requirements-doc": 3,
"hardware-cost": 4,
"supplier-evaluation": 3,
"purchase-demand-forecast": 4,
"product-pricing": 5,
"category-optimization": 5,
"release-channel-evaluation": 4,
"promotion-effect-optimization": 4,
"product-diagnosis-iteration": 3,
"comprehensive-case-training": 10,
});
export function getStudentTrainingStepCount(taskKey, fallback = 4) {
return studentTrainingStepCountByTaskKey[String(taskKey || "").trim()] || fallback;
}
export function resolveTrainingTaskKey(route, explicitTaskKey = "") {
return explicitTaskKey || route?.meta?.pageKey || trainingTaskKeyByPath[route?.path] || "";
}

@ -0,0 +1,29 @@
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const assert = require("node:assert/strict");
const root = path.resolve(__dirname, "..");
const apiSource = fs.readFileSync(path.join(root, "src/api/AI.js"), "utf8");
const analysisSource = fs.readFileSync(path.join(root, "src/views/analysis-of-students/analysis.vue"), "utf8");
const dialogueSource = fs.readFileSync(path.join(root, "src/views/analysis-of-students/dialogue.vue"), "utf8");
test("learning analysis request does not send the commerce login token", () => {
const requestBlock = apiSource.match(/export function getLearningAnalysis[\s\S]*?\n}/)?.[0] || "";
assert.match(requestBlock, /headers:\s*\{\s*isToken:\s*false\s*}/);
assert.match(requestBlock, /params:\s*\{\s*stuNeed\s*}/);
});
test("learning analysis page handles empty and failed score data", () => {
assert.match(analysisSource, /暂无成绩数据,暂时无法进行AI学情分析/);
assert.match(analysisSource, /proxy\.\$cache\.session\.remove\("scoreList"\)/);
assert.match(analysisSource, /rows\.some\(hasTeacherScoreData\)/);
assert.match(analysisSource, /completedTaskCount/);
assert.match(analysisSource, /if \(!hasScoreData\.value\)/);
assert.match(analysisSource, /finally\s*\{\s*scoreLoaded\.value = true/);
});
test("AI analysis failure always closes the loading overlay", () => {
assert.match(dialogueSource, /AI学情分析暂时不可用,请稍后重试/);
assert.match(dialogueSource, /finally\s*\{\s*loading\.value = false/);
});

@ -65,3 +65,12 @@ assert(/hasSavedAnswer/.test(page) && /:has-saved-answer="hasSavedAnswer"/.test(
assert(/hasSavedAnswer/.test(sidebar), "AI sidebar should accept persisted-answer state");
assert(/!props\.hasSavedAnswer/.test(sidebar), "AI assessment should be disabled until a saved answer exists");
assert(/catch \(error\)/.test(sidebar), "AI sidebar should handle assessment failures without an unhandled rejection");
assert(/const isAssessmentDisabled = computed\(\(\) => !props\.hasAnyAnswer \|\| assessmentLoading\.value \|\| assessmentStatus\.value === "PROCESSING"\)/.test(component),
"successful assessments should remain available for checking changed saved answers");
assert(/assessmentStatus\.value === "SUCCEEDED"[\s\S]*?\? "重新助评"/.test(component),
"successful assessments should expose the reassessment action");
assert(/reports\.assessment\.status === "SUCCEEDED" \? "重新助评" : "AI智能评分"/.test(sidebar),
"the shared sidebar should expose the reassessment action");
assert(component.includes("答案未变时保留上次结果") && sidebar.includes("答案未变时保留上次结果"),
"both assessment controls should explain saved-answer reuse");

@ -1,25 +0,0 @@
const assert = require("assert");
const {
LESSON_PLAN_MODULES,
buildTeachingPlanPrompt,
} = require("../src/views/analysis-of-students/lessonPlanPrompt.cjs");
const expectedModules = [
"互联网产品开发基础认知",
"市场洞察与需求分析",
"产品规划与设计",
"产品开发与测试验证",
"产品上线与运营推广",
"综合实训",
];
assert.deepStrictEqual(LESSON_PLAN_MODULES, expectedModules, "lesson-plan module selector must expose the six current modules");
const prompt = buildTeachingPlanPrompt("市场洞察与需求分析");
assert.match(prompt, /互联网产品开发实训课程/, "prompt must identify the course");
assert.match(prompt, /市场洞察与需求分析/, "prompt must identify the selected module");
for (const section of ["教学目标", "实训任务", "实施步骤", "预期成果", "评价要点"]) {
assert.match(prompt, new RegExp(section), `prompt must require ${section}`);
}
console.log("AI training lesson plan checks passed");

@ -0,0 +1,51 @@
import assert from "node:assert";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
LESSON_PLAN_MODULES,
buildTeachingPlanPrompt,
buildTeachingPlanRequest,
} from "../src/views/analysis-of-students/lessonPlanPrompt.mjs";
const expectedModules = [
"互联网产品开发基础认知",
"市场洞察与需求分析",
"产品规划与设计",
"产品开发与测试验证",
"产品上线与运营推广",
"综合实训",
];
assert.deepStrictEqual(LESSON_PLAN_MODULES, expectedModules, "lesson-plan module selector must expose the six current modules");
const prompt = buildTeachingPlanPrompt("市场洞察与需求分析");
assert.match(prompt, /互联网产品开发实训课程/, "prompt must identify the course");
assert.match(prompt, /市场洞察与需求分析/, "prompt must identify the selected module");
for (const section of ["教学目标", "实训任务", "实施步骤", "预期成果", "评价要点"]) {
assert.match(prompt, new RegExp(section), `prompt must require ${section}`);
}
const customized = buildTeachingPlanRequest(
"市场洞察与需求分析",
"生成两课时教案",
"学校教案模板.docx",
"一、教学目标\n二、教学过程",
);
assert.match(customized, /生成两课时教案/, "teacher-edited prompt must be used");
assert.match(customized, /学校教案模板\.docx/, "template name must be identified");
assert.match(customized, /一、教学目标/, "template content must be included in the generation request");
const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
const page = fs.readFileSync(
path.join(currentDirectory, "..", "src", "views", "analysis-of-students", "training-lesson-plan.vue"),
"utf8",
);
assert.match(page, /openLessonPlanSetup/, "module click must open setup instead of generating immediately");
assert.doesNotMatch(page, /@click="generateTeachingPlan\(item\)"/, "module click must not generate immediately");
assert.match(page, /参考提示词/);
assert.match(page, /学校参考模板/);
assert.match(page, /生成教案/);
assert.match(page, /grid-template-columns: repeat\(3/, "laptop layout must use a compact three-column grid");
console.log("AI training lesson plan checks passed");

@ -0,0 +1,32 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const frontendRoot = path.resolve(__dirname, "..");
const pageSource = fs.readFileSync(path.join(frontendRoot, "src/views/training/GenericTrainingPage.vue"), "utf8");
const routerSource = fs.readFileSync(path.join(frontendRoot, "src/router/index.js"), "utf8");
test("综合实训不显示右下角补充步骤", () => {
assert.match(
routerSource,
/pageKey: "comprehensive-case-training", hideSupplementSteps: true/,
);
});
test("综合实训操作按钮复用统一工具栏并位于工作台标题右侧", () => {
assert.match(
pageSource,
/<div class="workbench-head">[\s\S]*?<TrainingTaskToolbar[\s\S]*?:task-key="pageKey"[\s\S]*?:on-submit="submitTask"[\s\S]*?:on-reset="resetTraining"[\s\S]*?:on-export="exportOutcome"/,
);
assert.doesNotMatch(pageSource, /<TrainingTaskBrief[^>]*:show-toolbar="true"/);
});
test("综合实训步骤保持单行并支持鼠标或触控左右拖动", () => {
assert.match(pageSource, /class="comprehensive-step-strip"/);
assert.match(pageSource, /@pointerdown="startComprehensiveNavDrag"/);
assert.match(pageSource, /@pointermove="moveComprehensiveNavDrag"/);
assert.match(pageSource, /\.comprehensive-step-strip\s*\{[\s\S]*?width: max-content/);
assert.match(pageSource, /\.comprehensive-step-strip \.step-name\s*\{[\s\S]*?white-space: nowrap/);
assert.doesNotMatch(pageSource, /comprehensive-turn-row|comprehensive-turn-rail/);
});

@ -14,5 +14,8 @@ test("清空第 1 步会移除已保存答案,重新进入不会恢复分类
test("数据化选品页不显示右下角补充步骤导航", () => {
assert.match(routerSource, /pageKey: "market-opportunity-selection", hideSupplementSteps: true/);
assert.match(appMainSource, /route\.meta\?\.pageKey && !route\.meta\?\.hideSupplementSteps/);
assert.ok(
!/DynamicTrainingStepNavigator/.test(appMainSource) || /route\.meta\?\.pageKey && !route\.meta\?\.hideSupplementSteps/.test(appMainSource),
"the app shell must omit the supplement navigator or honor hideSupplementSteps",
);
});

@ -0,0 +1,58 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const frontendRoot = path.resolve(__dirname, "..");
const page = fs.readFileSync(path.join(frontendRoot, "src/views/assessment/diagnosis.vue"), "utf8");
const api = fs.readFileSync(path.join(frontendRoot, "src/api/studentTrainingAnswer.js"), "utf8");
test("产品问题诊断第一步固定首尾列并支持动态增删中间渠道", () => {
assert.match(page, /<th class="fixed-column">链路节点<\/th>[\s\S]*?v-for="channel in channels"[\s\S]*?<th class="fixed-column">行业均值<\/th>/);
assert.match(page, /@click="addFunnelChannel"/);
assert.match(page, /@click="removeFunnelChannel\(channel\.id\)"/);
assert.match(page, /row\.channelRates\[channel\.id\]/);
assert.doesNotMatch(page, /<th>天猫<\/th><th>京东<\/th><th>抖音<\/th><th>拼多多<\/th>/);
});
test("百分号与转化率输入框保持同行", () => {
assert.match(page, /<div class="rate-input">[\s\S]*?<el-input-number[\s\S]*?<span class="unit">%<\/span>[\s\S]*?<\/div>/);
assert.match(page, /\.rate-input\{[^}]*display:flex[^}]*white-space:nowrap/);
assert.match(page, /\.rate-input \.unit\{[^}]*white-space:nowrap/);
});
test("动态渠道随第一步答案提交并用于校验", () => {
assert.match(page, /channels: channelSnapshot/);
assert.match(page, /channelRates: \{ \.\.\.row\.channelRates \}/);
assert.match(api, /data: \{ channels: submittedChannels, conversionRates/);
assert.match(api, /source\.channelRates\[channel\.id\]/);
});
test("三个步骤的百分比输入全部将百分号固定在输入框同行", () => {
const units = [...page.matchAll(/<span class="unit">%<\/span>/g)];
assert.equal(units.length, 7);
units.forEach(({ index }) => {
assert.ok(page.lastIndexOf('<div class="rate-input">', index) > page.lastIndexOf("<td", index));
});
});
test("三个步骤的后端校验错误均交由页面显示单条中文提示", () => {
const validationBlock = api.slice(
api.indexOf("export function validateProductDiagnosisIterationStepOne"),
api.indexOf("export function validatePromotionEffectOptimizationStepOne")
);
assert.equal((validationBlock.match(/skipErrorMessage:\s*true/g) || []).length, 3);
assert.match(api, /throw new Error\("正面、中性、负面评论占比之和应为100%。"\)/);
assert.match(page, /function diagnosisErrorMessage[\s\S]*?Request failed with status code/);
assert.match(page, /validateStepTwo[\s\S]*?diagnosisErrorMessage\(error/);
});
test("第二步草稿保存完整分析状态并在重新进入页面后恢复", () => {
assert.match(page, /function buildStepTwo\(\)[\s\S]*?totalComments: commentPreview\.value\.totalComments[\s\S]*?analysisResult: analysisResult\.value/);
assert.match(page, /function buildStepTwoValidationPayload/);
assert.match(page, /validateProductDiagnosisIterationStepTwo\(buildStepTwoValidationPayload\(data\)\)/);
assert.match(page, /function restoreStepTwo\(stepTwo\)[\s\S]*?rootCauseAnalysis\.value = stepTwo\.rootCauseAnalysis/);
assert.match(page, /analysisResult\.value = \{ sourceFileName, totalComments, positiveCount, neutralCount, negativeCount/);
assert.match(page, /restoreStepTwo\(parseSavedStep\(answer\?\.step2Answer\)\)/);
assert.doesNotMatch(page, /if \(stepTwo\.sourceFileName\)/);
});

@ -0,0 +1,21 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const root = path.resolve(__dirname, "..");
const page = fs.readFileSync(path.join(root, "src/views/teacherEnd/score/index.vue"), "utf8");
const api = fs.readFileSync(path.join(root, "src/api/teacher.js"), "utf8");
assert.match(page, /label="老师评分"/);
assert.match(page, /自动汇总/);
assert.match(page, /canManageSelectedClass/);
assert.match(page, /createdBy/);
assert.match(page, /saveTaskTeacherScore/);
assert.match(page, /教师评分必须为0至100之间的数值/);
assert.match(page, /ownClass \|\| teachingClassList\.value\[0\]/);
assert.match(page, /getAccessibleTeachingClasses/);
assert.doesNotMatch(page, /onMounted\(\(\) => \{\s*getList\(\);\s*getClassList/);
assert.match(api, /url: "\/api\/weight\/saveTaskTeacherScore"/);
assert.match(api, /url: "\/api\/weight\/accessibleTeachingClasses"/);
console.log("score center class access and teacher score contract passed");

@ -0,0 +1,16 @@
const assert = require("assert");
const fs = require("fs");
const page = fs.readFileSync("src/views/teacherEnd/score/index.vue", "utf8");
const api = fs.readFileSync("src/api/teacher.js", "utf8");
assert(page.includes("学生姓名"));
assert(page.includes("AI评测总分"));
assert(page.includes("老师评分"));
assert(page.includes("scoreDetailStudent.name"));
assert(page.includes("scoreDetailStudent.aiTotalScore"));
assert(page.includes("scoreDetailStudent.teacherScore"));
assert(page.includes("row.teacherScore = score"));
assert(api.includes("/api/weight/saveTaskTeacherScore"));
console.log("score detail summary static checks passed");

@ -19,3 +19,8 @@ test("供应渠道评估使用接口 data 中的校验结果和学生答案", ()
assert.match(source, /const result = \(await validateSupplierEvaluationStepThree\(buildStepThreePayload\(\)\)\)\?\.data \|\| \{\};/);
assert.match(source, /const answer = \(await getStudentTrainingAnswer\(TASK_KEY\)\)\?\.data \|\| \{\};/);
});
test("供应渠道评估保存时将任务标识和答案作为两个参数传入", () => {
assert.equal((source.match(/saveStudentTrainingAnswer\(TASK_KEY,\s*\{/g) || []).length, 3);
assert.doesNotMatch(source, /saveStudentTrainingAnswer\(\{\s*taskKey:/);
});

@ -0,0 +1,20 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const page = fs.readFileSync(
path.resolve(__dirname, "../src/views/teacherEnd/class/index.vue"),
"utf8"
);
assert(!/导入名单创建/.test(page));
assert(!/downloadTeachingClassImportTemplate/.test(page));
assert(!/uploadTeachingClassByStudentMembers/.test(page));
assert(!/beforeImportCreate/.test(page));
assert(page.includes("const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);"));
assert(/if \(isManagerTeacher\.value\) \{[\s\S]*schoolClass\.schoolId[\s\S]*currentSchoolId\.value[\s\S]*\}/.test(page));
assert(page.includes("const selectedTeachingClassCanOperate = computed(() => canOperateClass(selectedTeachingClass.value));"));
assert(/function defaultMemberParams\(\) \{[\s\S]*operatorId: currentUserId\.value,[\s\S]*\}/.test(page));
assert(page.includes('v-if="canOperateClass(row.schoolClass)"'));
console.log("teacher administrator class access contract passed");

@ -0,0 +1,15 @@
const assert = require('assert');
const fs = require('fs');
const home = fs.readFileSync('src/views/teacherEnd/index.vue', 'utf8');
const api = fs.readFileSync('src/api/teacher.js', 'utf8');
assert(api.includes('/api/score/getTeaHomeClasses'));
assert(home.includes('getTeacherHomeClasses'));
assert(home.includes('<el-option label="全部" value="" />'));
assert(home.includes('trends.flatMap'));
assert(home.includes('scoresByDate'));
assert(!home.includes('stack: "Total"'));
assert(!home.includes('msgWarning("请选择班级")'));
console.log('teacher admin home all-class chart checks passed');

@ -0,0 +1,18 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const page = fs.readFileSync(
path.resolve(__dirname, "../src/views/teacherEnd/teacher/index.vue"),
"utf8"
);
assert(/const downloadTemplate = async \(\) =>/.test(page));
assert(/await import\("xlsx"\)/.test(page));
assert(/\["院校名称", "院系名称", "专业名称", "教师姓名", "工号", "电话", "邮箱"\]/.test(page));
assert(/XLSX\.utils\.book_append_sheet\(workbook, templateSheet, "教师导入模板"\)/.test(page));
assert(/XLSX\.writeFile\(workbook, "教师账号导入模板\.xlsx"\)/.test(page));
assert(!/\/file\/教师信息表格\.xlsx/.test(page));
assert(!/a\.href\s*=/.test(page));
console.log("teacher import template download contract passed");

@ -0,0 +1,20 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const page = fs.readFileSync(path.join(root, "src/views/teacherEnd/teacher/index.vue"), "utf8");
const api = fs.readFileSync(path.join(root, "src/api/teacher.js"), "utf8");
assert(/label="名下班级"/.test(page));
assert(/row\.ownedClassNames\?\.length/.test(page));
assert(/row\.ownedClassNames\.join\('、'\)/.test(page));
assert(/label="学生数量"/.test(page));
assert(/row\.ownedStudentCount/.test(page));
assert(/@click="initializeTeacherPassword\(row\)"/.test(page));
assert(/初始化为 123qwe/.test(page));
assert(/operatorId: currentUserId\.value/.test(page));
assert(/export function initializeTeacherPassword/.test(api));
assert(/url: "\/api\/user\/updateTeacherPassword"/.test(api));
console.log("teacher class summary and password initialization contract passed");

@ -9,6 +9,11 @@ assert(page.includes("operatorId: currentUserId.value"), "学生列表必须携
assert(page.includes("const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);"), "教师管理员身份必须由当前登录账号识别");
assert(page.includes("const studentClassOptions = computed(() => teachingClassOptions.value);"), "学生筛选下拉框必须只展示教学班");
assert(page.includes("isManagerTeacher.value || sameValue(schoolClass.createdBy, currentUserId.value)"), "教师管理员必须可查看本校全部教学班");
assert(page.includes(".sort((left, right) => classCreateTime(left) - classCreateTime(right))"), "普通教师的班级选项必须按创建时间升序排列");
assert(page.includes("if (!isManagerTeacher.value && !paramsquery.value.schoolClassId)"), "普通教师必须默认选中自己最早创建的教学班");
assert(page.includes('paramsquery.value.schoolClassId = teachingClassOptions.value[0]?.schoolClassId || "";'), "默认班级必须取排序后的第一个教学班");
assert(/await getClassList\(\);\r?\n\s*selectDefaultStudentClass\(\);\r?\n\s*getList\(\);/.test(page), "学生列表必须在默认班级确定后查询");
assert(page.includes('@change="handleClassFilterChange"'), "切换班级后必须立即刷新学生列表");
assert(page.includes("const resolveRowTeachingClassId = (row) =>"), "未选择班级时操作必须从学生行解析教学班");
assert(page.includes('class="student-action-group"'), "学生操作按钮必须使用固定操作组布局");
assert(page.includes("flex-wrap: nowrap"), "学生操作按钮不得换行");

@ -8,7 +8,7 @@ const api = fs.readFileSync('src/api/teacher.js', 'utf8');
assert(api.includes('/api/weight/ownedTeachingClasses'));
assert(api.includes('/api/weight/selectTeachingClassWeight'));
assert(api.includes('/api/weight/updateTeachingClassWeight'));
assert(page.includes('getOwnedTeachingClasses'));
assert(page.includes('getAccessibleTeachingClasses'));
assert(page.includes('互联网产品开发基础认知'));
assert(page.includes('市场洞察与需求分析'));
assert(page.includes('产品规划与设计'));
@ -17,5 +17,5 @@ assert(page.includes('产品上线与运营推广'));
assert(page.includes('综合实训'));
assert(page.includes('foundationWeight'));
assert(page.includes('comprehensiveTrainingWeight'));
assert(home.includes('getOwnedTeachingClasses'));
assert(home.includes('getOwnedTeachingClasses') || home.includes('getTeacherHomeClasses'));
console.log('teacher score scope static checks passed');

@ -0,0 +1,17 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const root = path.resolve(__dirname, "..");
const page = fs.readFileSync(path.join(root, "src", "views", "teacherEnd", "score", "index.vue"), "utf8");
const api = fs.readFileSync(path.join(root, "src", "api", "teacher.js"), "utf8");
assert.match(page, /已完成\s*\{\{\s*row\.completedTaskCount/);
assert.match(page, /teacherScoreDraft/);
assert.match(page, /saveTaskTeacherScore/);
assert.doesNotMatch(page, /saveTeacherScore\(row\)/);
assert.doesNotMatch(page, /teacher-score-editor/);
assert.match(api, /saveTaskTeacherScore/);
assert.doesNotMatch(api, /url: "\/api\/weight\/saveTeacherScore"/);
console.log("teacher score sync UI contract passed");

@ -0,0 +1,60 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const read = (file) => fs.readFileSync(path.join(root, file), "utf8");
const stepCounts = read("src/views/training/taskKeyMap.js");
const teacherEditor = read("src/views/teacherEnd/trainingTask/index.vue");
const adminEditor = read("src/views/schoolAdmin/trainingTask/index.vue");
const expectedCounts = {
"new-product-survey": 4,
"product-development-factors": 4,
"product-development-process": 4,
"industry-demand-analysis": 4,
"competitive-environment-analysis": 4,
"market-opportunity-selection": 6,
"business-feasibility": 3,
"target-user-profile": 5,
"consumer-behavior": 4,
"consumer-scenario": 4,
"feature-conversion": 4,
"product-value-positioning": 4,
"product-structure": 4,
"after-sales-service": 3,
"requirements-doc": 3,
"hardware-cost": 4,
"supplier-evaluation": 3,
"purchase-demand-forecast": 4,
"product-pricing": 5,
"category-optimization": 5,
"release-channel-evaluation": 4,
"promotion-effect-optimization": 4,
"product-diagnosis-iteration": 3,
"comprehensive-case-training": 10,
};
for (const [taskKey, count] of Object.entries(expectedCounts)) {
assert(
new RegExp(`"${taskKey}"\\s*:\\s*${count}(?:,|\\n)`).test(stepCounts),
`${taskKey} should be fixed to ${count} student steps`
);
}
for (const [name, editor] of [
["teacher", teacherEditor],
["admin", adminEditor],
]) {
assert(/import \{ getStudentTrainingStepCount \} from "@\/views\/training\/taskKeyMap";/.test(editor));
assert(/const expectedCount = getStudentTrainingStepCount\(taskKey\);/.test(editor));
assert(/Array\.from\(\{ length: expectedCount \}/.test(editor));
assert(/steps: JSON\.stringify\(fixedSteps\)/.test(editor));
assert(/步骤名称(固定 \$\{taskForm\.steps\.length\} 步)/.test(editor));
assert(!/@click="addStep"/.test(editor), `${name} editor must not add steps`);
assert(!/@click="removeStep/.test(editor), `${name} editor must not remove steps`);
assert(!/新增步骤/.test(editor), `${name} editor must not show add-step control`);
}
console.log("teacher and admin training task fixed-step contracts passed");
Loading…
Cancel
Save