Compare commits

..

No commits in common. 'f9f85a512c9afad03897391cba0c1a69a6b2004e' and 'a5b5c05424c1528894d80d2a8b7e8522237270d6' have entirely different histories.

@ -1191,7 +1191,7 @@ const taskConfig = ref(null); // 后端任务配置
const saving = ref(false); // 保存中锁
const checking = ref(false); // 判题中锁
const uploadingImages = ref(false); // 上传中锁
const currentStep = ref(1); // (1-based)
const currentStep = ref(1); // 当前步骤(1-based)
const briefOpen = ref(false); // 简介展开
const classifications = ref({}); // step1 三层次分类答案
const checkResult = ref(null); // step1 判题结果

@ -1191,7 +1191,7 @@ const taskConfig = ref(null); // 后端任务配置
const saving = ref(false); // 保存中锁
const checking = ref(false); // 判题中锁
const uploadingImages = ref(false); // 上传中锁
const currentStep = ref(1); // (1-based)
const currentStep = ref(1); // 当前步骤(1-based)
const briefOpen = ref(false); // 简介展开
const classifications = ref({}); // step1 三层次分类答案
const checkResult = ref(null); // step1 判题结果

@ -40,7 +40,7 @@ iframe 高度:子页 ResizeObserver + MutationObserver 测量 → postMessage(`t
### 已修复:评阅预览"看起来还在用废弃页面"的根因(两个叠加原因)
用户反馈截图里步骤导航是一条满宽蓝色大条,误判为废弃页面。实测根因 **不是页面文件错了**,而是样式失配:
1. **学生页"新版皮肤"全部由布局门控选择器承载**:`#app .studentLayout section.app-main:has(.xxx-page) …`(非 scoped 全局块,写在每个实训页底部)。
而 `/task-review-preview` 路由**脱离 Layout**(`component` 直接指向组件,无 Layout 包裹)→ 没有 `.studentLayout`、没有 `section.app-main` → 这些新样式全部失配,页面静默退化到全局旧版样式(步骤说明 `small`「」重新出现、胶囊样式丢失、按钮配色不一致)。
而 `/task-review-preview` 路由**脱离 Layout**(`component` 直接指向组件,无 Layout 包裹)→ 没有 `.studentLayout`、没有 `section.app-main` → 这些新样式全部失配,页面静默退化到全局旧版样式(步骤说明 `small`「当前步骤」重新出现、胶囊样式丢失、按钮配色不一致)。
`studentLayout` 类由 `layout/index.vue` 的 `classObj` 计算(仅 role 4 挂载);`.app-main` 由 `layout/components/AppMain.vue` 渲染且样式是 scoped。
2. **预览 iframe 宽度约 1000px**(`TaskReviewPanel.vue` 左栏 `minmax(440px,520px)` + 右栏自适应),命中 `student-training.scss` 的 `@media (max-width: 1100px)`:
`.student-training-shell .step-indicator { flex-direction: column }` + `#app .student-training-shell .step-tab { width: 100% !important }`。

@ -28,7 +28,7 @@
| 弱提示 | `#9ab3d0` / `#8299aa` | 未选中步骤、占位符 |
| 青蓝强调 | `#71dfff` / `#5ce0ff` | 标签、焦点、交互边框 |
| 主按钮渐变 | `#0b84bd → #096491` | 下一步、保存、提交等主要操作 |
| 激活标签渐变 | `#0a6b9e → #0a5c86` | 步骤、选中的单选项 |
| 激活标签渐变 | `#0a6b9e → #0a5c86` | 当前步骤、选中的单选项 |
| 输入底色 | `#0f1a24` | 原生输入框、文本域 |
| 深卡片底色 | `rgba(0, 25, 42, .64)` | 实训卡、步骤卡 |
| 表格底色 | `rgba(1, 14, 26, .72)` | 表格外层 |
@ -105,7 +105,7 @@
2. **实训说明区**:背景、目标、要求等由配置驱动的说明内容。
3. **任务工作台头部**:`Training Task` 眉题、实训标题和辅助操作按钮。
4. **步骤导航区**:仅承载配置驱动的步骤,具体样式见第 5 节。
5. **本步骤内容区**:步骤的说明、表单、表格、提示卡与操作区。
5. **当前步骤内容区**:当前步骤的说明、表单、表格、提示卡与操作区。
- 区域之间的标准纵向间距:任务识别区到说明区 `24px`;说明区到任务工作台 `28px`;工作台头部到步骤栏 `22px`;步骤栏到内容区 `32px`。
- 不得将步骤内容直接贴在实训说明区之后;必须先经过任务工作台头部和步骤导航形成层级过渡。
@ -151,7 +151,7 @@
- 头部右侧的“案例文档 / 导出实训成果 / 下载数据”等均为同一组**小型轮廓按钮**:最小高度 `40px`、左右内边距 `18px`、圆角 `999px`、字号 `14px`、字重 `800`、边框 `rgba(99,217,255,.55)`、背景 `rgba(17,126,178,.36)`。同一操作组内不得混入亮蓝色实心主按钮、图片按钮或不同高度的按钮。
- 主工作台外层、任务工作台、步骤内容卡各自只承担一层边框与阴影;禁止再叠加第二个无语义的大型容器、重复圆角或竞争性的重阴影。页面视觉必须保持“外层工作台 → 任务工作台 → 步骤内容卡”的三级结构。
#### 本步骤内容区
#### 当前步骤内容区
- 步骤标题行采用左右布局:左侧为眉题与步骤标题,右侧可放一个业务状态芯片;间距 `18px`,底部间距 `14px`。
- 步骤标题:`22px / 900 / #ffffff`;眉题:`12px / 800 / #71dfff`;状态芯片按第 9 节执行。
@ -173,8 +173,8 @@
- 本节**只定义样式**,不定义、不修改、不校验步骤名称、步骤数量和步骤顺序。
- 步骤文字、图标和可用状态必须继续由任务配置或现有业务逻辑提供;样式实现不得写死任何步骤文案。
- 标准页中的功能步骤栏与旧页面的阶段步骤栏均使用本节的视觉规则。
- **无有效步骤数据时不显示步骤条**:当任务配置中 `steps` 缺失、为空、解析后为空数组或无可展示步骤时,必须完全不渲染步骤导航容器及其占位间距;不得用默认步骤、固定文案、空胶囊或禁用占位项补齐。本步骤内容仍按原有业务结构展示。
- **有效步骤必须可操作**:当任务配置返回一个或多个可用步骤时,每个步骤项必须使用语义化 `button`(或等价可访问控件),具备键盘可达和点击事件;点击后必须切换步骤及对应内容区,并同步当前激活态。禁止将可用步骤渲染为静态 `span`、`div` 或仅有视觉选中态的伪按钮。
- **无有效步骤数据时不显示步骤条**:当任务配置中 `steps` 缺失、为空、解析后为空数组或无可展示步骤时,必须完全不渲染步骤导航容器及其占位间距;不得用默认步骤、固定文案、空胶囊或禁用占位项补齐。当前步骤内容仍按原有业务结构展示。
- **有效步骤必须可操作**:当任务配置返回一个或多个可用步骤时,每个步骤项必须使用语义化 `button`(或等价可访问控件),具备键盘可达和点击事件;点击后必须切换当前步骤及对应内容区,并同步当前激活态。禁止将可用步骤渲染为静态 `span`、`div` 或仅有视觉选中态的伪按钮。
- 如某步骤因业务前置条件暂不可进入,必须由业务逻辑显式标记为禁用并说明原因;不得静默吞掉点击事件或展示“可点击外观”的不可用项。
### 5.2 桌面端尺寸与布局
@ -183,21 +183,21 @@
#### 截图视觉基准(标准步骤条)
标准步骤条必须呈现为一条完整的深色胶囊流程轨道。每一步从左到右依次为两位编号圆点、步骤名称和状态提示,步骤之间保留青蓝色连线与右向箭头。默认和已完成步骤直接置于整条轨道上,**不得**再绘制独立的深色矩形卡片、边框或背景块;只有步骤使用完整的蓝色渐变胶囊、带光晕的蓝色编号圆点和“步骤”提示。已完成步骤仅将编号圆点和前置连线改为青绿色,编号不得被勾选图标替代。
标准步骤条必须呈现为一条完整的深色胶囊流程轨道。每一步从左到右依次为两位编号圆点、步骤名称和状态提示,步骤之间保留青蓝色连线与右向箭头。默认和已完成步骤直接置于整条轨道上,**不得**再绘制独立的深色矩形卡片、边框或背景块;只有当前步骤使用完整的蓝色渐变胶囊、带光晕的蓝色编号圆点和“当前步骤”提示。已完成步骤仅将编号圆点和前置连线改为青绿色,编号不得被勾选图标替代。
```text
(01) 步骤名称 / 切换 → → [ (02) 步骤名称 / 步骤 ] → (03) 步骤名称 / 切换 →
(01) 步骤名称 / 点击切换 → → [ (02) 步骤名称 / 当前步骤 ] → (03) 步骤名称 / 点击切换 →
```
实现必须保留 `.step-marker`、`.step-copy`(含 `.step-name` 和 `.step-action`)以及 `.step-connector` 四类元素;不得通过隐藏编号、状态文案或连接箭头把流程步骤条简化为纯文字胶囊导航。
- 为避免与工作台内容区过于局促,桌面端步骤栏可相对内容区向左右各扩展 `12px`:`width: calc(100% + 24px)`、`margin-left/right: -12px`。扩展范围只能位于主工作台内,不得突破主工作台边框。
- 容器内边距 `10px 18px`,圆角 `999px`,边框 `1px solid rgba(0,180,255,.3)`;使用深青蓝背景与轻微内高光,作为所有步骤共用的一条轨道。
- 每个步骤项使用 `flex: 1 1 0` 分配宽度,最小宽度 `150px`、最小高度 `72px`、内边距 `8px 12px`、圆角 `999px`。默认背景和描边均透明;仅步骤使用蓝色渐变背景与青色描边。步骤名称不同不得改变统一的最小可用宽度。
- 每个步骤项使用 `flex: 1 1 0` 分配宽度,最小宽度 `150px`、最小高度 `72px`、内边距 `8px 12px`、圆角 `999px`。默认背景和描边均透明;仅当前步骤使用蓝色渐变背景与青色描边。步骤名称不同不得改变统一的最小可用宽度。
- 步骤项左侧为 `56px` 圆形编号节点;节点始终显示两位步骤编号(如 `01`),**已完成步骤不得替换为勾选符号**。已完成态只能通过节点和连线颜色表达。
- 步骤项依次显示“步骤名称”和操作提示;不得显示 `STAGE` 或其他英文阶段眉题。未激活项常驻显示“切换 →”,当前项显示“步骤”。
- 步骤项依次显示“步骤名称”和操作提示;不得显示 `STAGE` 或其他英文阶段眉题。未激活项常驻显示“点击切换 →”,当前项显示“当前步骤”。
- 步骤项之间使用低饱和青蓝 `2px` 连线与右箭头表达先后关系;已完成区段可提高亮度,连线不承担点击区域。
- **桌面端步骤间距(硬性值):** 单段连接线使用 `flex: 0 1 72px`、`min-width: 40px`、`height: 2px`、`margin: 0 12px`;箭头使用 `8px × 8px` 的右向描边。连线位于整条轨道内,用于区分透明的默认步骤与步骤。
- **桌面端步骤间距(硬性值):** 单段连接线使用 `flex: 0 1 72px`、`min-width: 40px`、`height: 2px`、`margin: 0 12px`;箭头使用 `8px × 8px` 的右向描边。连线位于整条轨道内,用于区分透明的默认步骤与当前步骤。
- 步骤名称由配置提供,最多显示两行,超出后使用省略号截断;必须保留完整名称的悬停提示(如 `title`)和可访问名称。不得因长名称压缩编号节点、操作提示或相邻步骤卡。
- 当全部步骤的最小宽度无法容纳时,步骤栏允许横向滚动;禁止把步骤卡、文字或连线压缩变形。
@ -205,11 +205,11 @@
| 状态 | 文字 | 背景 | 描边与效果 |
| --- | --- | --- | --- |
| 默认/待完成 | `#9ab3d0` | 透明 | 无独立描边;显示“切换 →” |
| Hover(可点击) | `#ffffff` | 透明或轻微青蓝半透明 | 仅以胶囊圆角高亮反馈;上移 `2px`、强化“切换”颜色 |
| 当前/激活 | `#ffffff` | `#0eaae4 → #0572ac` 蓝色渐变胶囊 | `#36d9ff` 描边;节点使用蓝色渐变与青色光晕,提示为“步骤” |
| 默认/待完成 | `#9ab3d0` | 透明 | 无独立描边;显示“点击切换 →” |
| Hover(可点击) | `#ffffff` | 透明或轻微青蓝半透明 | 仅以胶囊圆角高亮反馈;上移 `2px`、强化“点击切换”颜色 |
| 当前/激活 | `#ffffff` | `#0eaae4 → #0572ac` 蓝色渐变胶囊 | `#36d9ff` 描边;节点使用蓝色渐变与青色光晕,提示为“当前步骤” |
| 已完成(如业务提供) | `#dffbff` | 透明 | 编号节点和已完成连线使用青绿色;编号仍可见,不显示勾选 |
| 禁用(如业务提供) | `#8299aa` | 透明 | `opacity: .45`;无指针手势,且不显示“切换” |
| 禁用(如业务提供) | `#8299aa` | 透明 | `opacity: .45`;无指针手势,且不显示“点击切换” |
- 过渡仅用于 `transform`、颜色、背景、描边和阴影,时长 `0.2s`;不得做闪烁、跳动或自动轮播动画。
- 激活状态只表现当前业务状态,不根据名称、索引或固定第一个项目推断。
@ -282,7 +282,7 @@
- **渲染条件与固定位置**:只要任务配置中存在有效 `steps`,就必须渲染完整的“上一步 / 保存当前进度 / 下一步”三个按钮;位于当前可见步骤内容卡之后、底部大操作区之前,与步骤内容卡间距 `22px`,与底部大操作区间距 `36px`。没有有效步骤数据时,步骤栏和步骤操作区都不渲染且不保留占位。
- **固定排版**:桌面端三个按钮水平居中,组内间距 `14px`,顺序固定为“上一步 → 保存当前进度 → 下一步”;不得一左一右贴在内容卡两端,不得放入任务工作台头部、表格行内或 AI 侧栏。小于等于 `900px` 时改为纵向全宽排列,间距 `14px`。
- **按钮尺寸与默认态**:三个按钮均为 `min-height: 40px`、内边距 `0 18px`、圆角 `999px`、`14px / 800`。上一步为轮廓态:`rgba(17,126,178,.36)` 背景和 `rgba(99,217,255,.55)` 描边;保存当前进度和下一步为主按钮态:`#0b84bd → #096491` 渐变、白字和 `rgba(92,224,255,.7)` 描边。图标与文字间距 `8px`,上一步/下一步可分别使用左/右箭头,保存使用确认图标。
- **状态与交互**:首步禁用上一步,末步禁用下一步;禁用态 `opacity: .45` 且不可点击。保存当前进度始终可用(保存请求进行中除外),并调用该任务既有保存逻辑。上一步/下一步每次点击必须切换本步骤内容、顶部步骤栏激活态及持久化的步骤值;不允许只改变颜色或只滚动页面。
- **状态与交互**:首步禁用上一步,末步禁用下一步;禁用态 `opacity: .45` 且不可点击。保存当前进度始终可用(保存请求进行中除外),并调用该任务既有保存逻辑。上一步/下一步每次点击必须切换当前步骤内容、顶部步骤栏激活态及持久化的当前步骤值;不允许只改变颜色或只滚动页面。
> 底部大操作区仅承载“提交任务”和“清空填写/重置”等成果操作,继续使用第 6.3 节 `64px` 大按钮;其桌面端固定居中、组内间距 `52px`,位置始终在步骤操作区之后(无有效步骤时紧随最后一个内容卡)。案例文档和导出成果仍只位于工作台头部右侧,禁止在步骤操作区或底部重复出现。
@ -314,7 +314,7 @@
### 7.4 文件上传组件
用于上传甘特图、数据附件、截图或任务佐证;上传组件只能位于本步骤内容卡内,并由业务规则决定允许的文件类型与文件数量。
用于上传甘特图、数据附件、截图或任务佐证;上传组件只能位于当前步骤内容卡内,并由业务规则决定允许的文件类型与文件数量。
- 原生文件输入框保持隐藏;对外只展示一个可点击的上传按钮和已选文件名,不额外暴露浏览器默认文件控件。
- 上传按钮使用常规主按钮:最小高度 `40px`、左右内边距 `18px`、圆角 `999px`、字重 `800`、文字白色、背景 `linear-gradient(95deg, #0b84bd, #096491)`、边框 `rgba(92,224,255,.7)`。
@ -340,7 +340,7 @@
### 9.1 步骤内资料信息块与分析维度卡
适用于行业背景、题干资料、案例事实等需要在步骤内逐条阅读的内容,以及 PEST、SWOT 等并列分析维度;它们只能作为“步骤内容卡”中的第三级组件,不能脱离步骤卡另起大面板。
适用于行业背景、题干资料、案例事实等需要在当前步骤内逐条阅读的内容,以及 PEST、SWOT 等并列分析维度;它们只能作为“步骤内容卡”中的第三级组件,不能脱离步骤卡另起大面板。
| 组件 | 结构与间距 | 文字 | 背景与边界 | 窄屏规则 |
| --- | --- | --- | --- | --- |
@ -349,7 +349,7 @@
### 9.2 访谈记录切换与详情弹层
适用于用户访谈、案例角色或多份资料的查看与填写;仅能位于本步骤内容卡中,不能作为工作台头部或页面级导航。
适用于用户访谈、案例角色或多份资料的查看与填写;仅能位于当前步骤内容卡中,不能作为工作台头部或页面级导航。
| 组件 | 结构与间距 | 文字 | 背景与边界 | 交互与窄屏规则 |
| --- | --- | --- | --- | --- |
@ -362,7 +362,7 @@
### 9.3 用户旅程地图、阶段匹配与参考图
适用于消费场景、服务蓝图等需要把用户行为串成旅程的任务;只能位于本步骤内容卡内,不能脱离工作台单独成为第二个页面级面板。
适用于消费场景、服务蓝图等需要把用户行为串成旅程的任务;只能位于当前步骤内容卡内,不能脱离工作台单独成为第二个页面级面板。
| 组件 | 结构与间距 | 文字 | 背景与边框 | 响应式与交互 |
| --- | --- | --- | --- | --- |
@ -376,7 +376,7 @@
### 9.4 需求转化与优先级评估工作区
适用于将用户反馈转写为功能定义、验收标准并开展优先级评估的实训任务。它仅位于本步骤内容卡内;原始反馈、示例说明、转化表、打分表和优先级决策均不得脱离步骤卡形成第二个页面级面板。
适用于将用户反馈转写为功能定义、验收标准并开展优先级评估的实训任务。它仅位于当前步骤内容卡内;原始反馈、示例说明、转化表、打分表和优先级决策均不得脱离步骤卡形成第二个页面级面板。
| 组件 | 结构与间距 | 文字 | 背景、边框与交互 |
| --- | --- | --- | --- |
@ -385,18 +385,18 @@
| 优先级决策字段组 | 每个优先级字段为“标签 + 文本域”的纵向块,字段间距 `16px`;文本域最小高度 `110px` | 标签 `14px / 800 / #dff5ff`;说明 `15px / 1.8 / #d7ecff` | 文本域沿用第 7.2 节;不以 P0/P1/P2/P3 等具体业务名称绑定视觉样式 |
- 反馈内容、示例、表头、优先级名称及数量均由任务业务数据提供;规范只约束承载结构与视觉,不得将其写死为页面样式的一部分。
- 若存在配置步骤,步骤栏必须是可键盘操作的语义按钮,点击后切换本步骤内容和激活态;若不存在有效配置步骤,隐藏步骤栏且上述业务区按连续内容显示。
- 若存在配置步骤,步骤栏必须是可键盘操作的语义按钮,点击后切换当前步骤内容和激活态;若不存在有效配置步骤,隐藏步骤栏且上述业务区按连续内容显示。
### 9.5 同一步骤内的业务分析工具切换
适用于 ABC/帕累托分析、购物篮分析等同一实训内存在多套业务工具的场景。它不是任务配置步骤栏的替代品,只能位于本步骤内容卡内,用于切换并列的业务工作区。
适用于 ABC/帕累托分析、购物篮分析等同一实训内存在多套业务工具的场景。它不是任务配置步骤栏的替代品,只能位于当前步骤内容卡内,用于切换并列的业务工作区。
| 项目 | 规范 |
| --- | --- |
| 层级与位置 | 位于步骤标题与业务工作区之间,距标题区下方 `14px`,距业务工作区 `18px`;不得移至工作台头部、AI 侧栏或底部操作区。 |
| 容器 | `display:flex`,允许换行,间距 `10px`;不另起白底、灰底或无边界的大卡片。 |
| 工具切换按钮 | 必须使用语义化 `button`;最小高度 `40px`、左右内边距 `18px`、圆角 `999px`、`14px / 800`。默认态为小型轮廓按钮,激活态使用 `#0a6b9e → #0a5c86` 渐变、白字与 `rgba(92,224,255,.7)` 描边。 |
| 交互 | 点击、键盘焦点和激活态必须同步切换对应业务工作区;不得只改变按钮颜色。当前工具选择应沿用任务现有保存逻辑或与步骤一起持久化。 |
| 交互 | 点击、键盘焦点和激活态必须同步切换对应业务工作区;不得只改变按钮颜色。当前工具选择应沿用任务现有保存逻辑或与当前步骤一起持久化。 |
| 业务内操作 | “下载数据 / 提交 / 添加组合”等保留既有业务动作,但必须按第 6.1、6.2、6.4 节收敛为深色轮廓/主按钮,禁止图片按钮。最终的“提交任务 / 清空填写”只保留在工作台底部标准操作区,业务组件内部不得重复渲染任务页脚。 |
| 窄屏 | 按钮可换行;空间不足时每项占满可用宽度,点击面积不低于 `40px`。 |

@ -1,67 +0,0 @@
# Compact Training Step Navigation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Reduce the desktop spacing and arrow length between training-step buttons without changing button content or the mobile vertical layout.
**Architecture:** Keep the existing `GenericTrainingPage.vue` markup and state unchanged. Adjust only the shared desktop `.step-connector` flex basis, minimum width, and horizontal margins; preserve the media-query connector rules.
**Tech Stack:** Vue 3 single-file components, scoped SCSS, Node static test.
## Global Constraints
- Do not change the step count, step button width, copy truncation, or click behavior.
- Keep the existing vertical connector styles for screens at or below 900px.
- The desktop connector must remain visible and retain its arrowhead.
---
### Task 1: Compact the desktop connector
**Files:**
- Modify: `src/views/training/GenericTrainingPage.vue:789-808`
- Create: `tests/step-indicator-layout.static.test.cjs`
**Interfaces:**
- Consumes: `.step-connector` and `.step-connector::after` emitted between each `.step-tab`.
- Produces: A shorter desktop connector with the same arrowhead and unchanged mobile override.
- [ ] **Step 1: Write the failing test**
```js
const source = fs.readFileSync(path.join(root, "src/views/training/GenericTrainingPage.vue"), "utf8");
const connector = source.match(/\.step-connector \{([\s\S]*?)\n\}/)?.[1] || "";
assert.match(connector, /flex:\s*0 1 40px;/);
assert.match(connector, /min-width:\s*18px;/);
assert.match(connector, /margin:\s*0 8px;/);
```
- [ ] **Step 2: Run the test to verify it fails**
Run: `node tests/step-indicator-layout.static.test.cjs`
Expected: FAIL because the connector currently uses `64px`, `22px`, and `0 14px`.
- [ ] **Step 3: Implement the minimal style change**
```scss
.step-connector {
flex: 0 1 40px;
min-width: 18px;
margin: 0 8px;
}
```
Leave the pseudo-element arrowhead and the `@media (max-width: 900px)` connector block unchanged.
- [ ] **Step 4: Run the test to verify it passes**
Run: `node tests/step-indicator-layout.static.test.cjs`
Expected: PASS.
- [ ] **Step 5: Build the frontend**
Run: `npm run build:prod`
Expected: Vite build completes successfully.

@ -1,172 +0,0 @@
# Student Task Header Removal Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Remove the task-workbench title and requirement description from every student training route while retaining download/export controls and all task behavior.
**Architecture:** Use two shared templates for routes that already inherit a common workbench, then update the remaining direct student training views in place. Each changed workbench keeps its existing `TrainingMaterialButton` and export button inside an actions-only header; only presentation markup and local header spacing change.
**Tech Stack:** Vue 3, `<script setup>`, SCSS, Node.js static assertions, Vite 3.
## Global Constraints
- Modify student training views only; do not alter teacher, administrator, or API code.
- Preserve `TrainingMaterialButton` or `material-download`, export controls, task data, step navigation, save, submit, reset, and draft persistence.
- Remove only the workbench-level `Training Task / 任务实训` eyebrow, heading, and requirement-description markup.
- Use `apply_patch` for source and test edits.
---
### Task 1: Expand the student-workbench regression coverage
**Files:**
- Modify: `tests/demand-index-step-standard.static.test.cjs`
**Interfaces:**
- Consumes: UTF-8 Vue source files under `src/views`.
- Produces: static assertions verifying the removed header is absent and `TrainingMaterialButton` remains in every direct/shared student training implementation.
- [ ] **Step 1: Write the failing test**
```js
const workbenchPages = [
"training/GenericTrainingPage.vue",
"product/components/ProductStandardTrainingPage.vue",
"foundation/product-development-factors.vue",
"demand/index.vue",
"demand/environment.vue",
"demand/people.vue",
"demand/consumer-behavior.vue",
"demand/consumer-scenario.vue",
"demand/feature-conversion.vue",
"product/index.vue",
"product/price.vue",
"product/differentiation.vue",
"product/structure.vue",
"product/after-sales-service.vue",
"channel/index.vue",
"channel/supplier.vue",
"assessment/optimization.vue"
];
for (const pageName of workbenchPages) {
const page = fs.readFileSync(path.resolve(__dirname, `../src/views/${pageName}`), "utf8");
assert.doesNotMatch(page, /class="workbench-head">\s*<div>[\s\S]*?workbench-description/, `${pageName} should not render the task-workbench heading or description`);
assert.match(page, /TrainingMaterialButton|class="material-download"/, `${pageName} should retain the file download control`);
}
```
- [ ] **Step 2: Run test to verify it fails**
Run: `node tests/demand-index-step-standard.static.test.cjs`
Expected: failure naming a remaining student page that still contains the workbench title/description.
- [ ] **Step 3: Implement the minimal test coverage**
Append the direct/shared page list and assertions to the existing static test without weakening the prior step-navigation checks.
- [ ] **Step 4: Run test to verify the expected red state**
Run: `node tests/demand-index-step-standard.static.test.cjs`
Expected: failure until Tasks 2 and 3 remove all remaining headers.
### Task 2: Remove headers in shared student templates
**Files:**
- Modify: `src/views/training/GenericTrainingPage.vue`
- Modify: `src/views/product/components/ProductStandardTrainingPage.vue`
**Interfaces:**
- Consumes: current task header plus its `TrainingMaterialButton` or `material-download` markup.
- Produces: actions-only headers inherited by foundation/product-development-process, demand/business-feasibility, product/requirements-doc, product/hardware-cost, test/index, and test/promotion.
- [ ] **Step 1: Replace the header markup**
```vue
<div class="workbench-head workbench-head--actions-only">
<div class="workbench-actions">
<TrainingMaterialButton :material-name="taskConfig?.materialName" :material-url="taskConfig?.materialUrl" />
<button type="button" class="outline-action" @click="exportOutcome">导出实训成果</button>
</div>
</div>
```
- [ ] **Step 2: Add the actions-only visual rule**
```scss
.workbench-head--actions-only {
justify-content: flex-end;
margin-bottom: 18px;
padding-bottom: 0;
border-bottom: 0;
}
```
- [ ] **Step 3: Run the static test**
Run: `node tests/demand-index-step-standard.static.test.cjs`
Expected: remaining failures are direct student views only.
### Task 3: Remove headers in direct student training views
**Files:**
- Modify: `src/views/foundation/product-development-factors.vue`
- Modify: `src/views/demand/index.vue`
- Modify: `src/views/demand/environment.vue`
- Modify: `src/views/demand/people.vue`
- Modify: `src/views/demand/consumer-behavior.vue`
- Modify: `src/views/demand/consumer-scenario.vue`
- Modify: `src/views/demand/feature-conversion.vue`
- Modify: `src/views/product/index.vue`
- Modify: `src/views/product/price.vue`
- Modify: `src/views/product/differentiation.vue`
- Modify: `src/views/product/structure.vue`
- Modify: `src/views/product/after-sales-service.vue`
- Modify: `src/views/channel/index.vue`
- Modify: `src/views/channel/supplier.vue`
- Modify: `src/views/assessment/optimization.vue`
**Interfaces:**
- Consumes: per-page workbench header templates and existing download/export handlers.
- Produces: direct student pages with download/export controls only above their standard step navigation.
- [ ] **Step 1: Replace each direct page header**
Use the actions-only workbench markup while preserving each page's existing `TrainingMaterialButton` or `material-download` binding and export binding exactly.
- [ ] **Step 2: Add or extend local actions-only header CSS**
Add the same four properties from Task 2 in the final effective style block of each page so minified legacy rules do not override it.
- [ ] **Step 3: Run the static test**
Run: `node tests/demand-index-step-standard.static.test.cjs`
Expected: all assertions pass.
### Task 4: Verify all changed student pages compile
**Files:**
- Verify: `tests/demand-index-step-standard.static.test.cjs`
- Verify: all files in Tasks 2 and 3 plus previously changed `foundation/new-product-survey.vue` and `assessment/diagnosis.vue`.
- [ ] **Step 1: Check whitespace errors**
Run: `git diff --check`
Expected: exit code 0.
- [ ] **Step 2: Run regression checks**
Run: `node tests/demand-index-step-standard.static.test.cjs`
Expected: exit code 0.
- [ ] **Step 3: Run production compilation**
Run: `npm run build:prod`
Expected: Vite exits 0; any existing `::v-deep`, unresolved image, or chunk-size warnings are reported separately from build failure.

@ -1,94 +0,0 @@
# AI 实训教案模块更新 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 将 AI 实训教案切换到新的六个课程模块,并向 AI 发送包含教案结构要求的提示词。
**Architecture:** 教案选择页维护唯一的六模块数组和提示词生成函数。点击模块后,将完整提示词写入既有 `teachingPlan` session 缓存;通用对话页继续读取该缓存并将文本作为既有 Kimi 请求的 POST body 发送,不调整接口协议。
**Tech Stack:** Vue 3 Composition API、Vite、Node.js `assert` 静态检查。
## Global Constraints
- 仅修改 AI 实训教案选择页及其静态检查,不变更聊天接口、成绩中心或 AI 助学/助评接口。
- 页面必须只提供以下六个模块:互联网产品开发基础认知、市场洞察与需求分析、产品规划与设计、产品开发与测试验证、产品上线与运营推广、综合实训。
- 每次预置请求必须同时包含课程名称、所选模块、教学目标、实训任务、实施步骤、预期成果、评价要点。
---
### Task 1: 覆盖新模块与提示词的静态检查
**Files:**
- Create: `tests/ai-training-lesson-plan.static.test.cjs`
- Modify: `src/views/analysis-of-students/training-lesson-plan.vue`
**Interfaces:**
- Consumes: `training-lesson-plan.vue` 的 `dialogue` 常量和 `generateTeachingPlan(val)`。
- Produces: 对六个模块和结构化提示词的回归保护;测试通过时输出 `AI training lesson plan static checks passed`。
- [ ] **Step 1: 写出失败的静态检查**
```js
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/analysis-of-students/training-lesson-plan.vue"), "utf8");
const modules = [
"互联网产品开发基础认知",
"市场洞察与需求分析",
"产品规划与设计",
"产品开发与测试验证",
"产品上线与运营推广",
"综合实训",
];
for (const name of modules) assert(page.includes(name), `missing module: ${name}`);
assert(!page.includes("市场需求挖掘"), "old module names must be removed");
assert(page.includes("互联网产品开发实训课程"), "prompt should name the course");
for (const section of ["教学目标", "实训任务", "实施步骤", "预期成果", "评价要点"]) {
assert(page.includes(section), `prompt should require ${section}`);
}
console.log("AI training lesson plan static checks passed");
```
- [ ] **Step 2: 运行测试并确认失败**
Run: `node tests/ai-training-lesson-plan.static.test.cjs`
Expected: FAIL,因为页面尚未出现全部六个模块及结构化提示词字段。
- [ ] **Step 3: 以最小改动更新选择页和提示词**
在 `training-lesson-plan.vue` 中将旧的五项 `dialogue` 常量替换为六项数组;保留模板的 `v-for` 渲染。将 `generateTeachingPlan(val)` 的缓存值改为下列模板字符串,其中 `${val}` 保持为当前点击的模块:
```js
`请为“互联网产品开发实训课程”的“${val}”模块生成一份实训教案。
请按以下结构输出:
1. 教学目标
2. 实训任务
3. 实施步骤
4. 预期成果
5. 评价要点
内容应贴合互联网产品开发的真实业务场景,并给出可直接用于课堂组织的说明。`
```
- [ ] **Step 4: 运行新增检查并确认通过**
Run: `node tests/ai-training-lesson-plan.static.test.cjs`
Expected: PASS,并输出 `AI training lesson plan static checks passed`。
- [ ] **Step 5: 运行所有前端静态检查**
Run: `Get-ChildItem -Path tests -Filter '*.cjs' | Sort-Object Name | ForEach-Object { node $_.FullName; if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } }`
Expected: 所有检查通过,包含新增的 AI 实训教案检查。
- [ ] **Step 6: 提交实现**
```bash
git add src/views/analysis-of-students/training-lesson-plan.vue tests/ai-training-lesson-plan.static.test.cjs
git commit -m "feat: update AI lesson plan modules"
```

@ -195,7 +195,7 @@ return request({
将现有 `factorRows` 重命名为 `stepOneRows`,新增 `STEP_TWO_FACTOR_ROWS` 与 `stepTwoRows`,并为两步分别提供 `create...Rows`、`build...Outcome`、`build...ValidationPayload`。模板保留第 1 步 `v-if="currentStep === 0"`,新增 `v-else-if="currentStep === 1"` 的原型表格和“保存并进入第 3 步”按钮,最后 `v-else` 才保留第 3 步待配置占位。
`loadSavedAnswer()` 分别读取 `answer.step1Answer` 与 `answer.step2Answer` 并按维度恢复;本地草稿保存两个步骤的内容和步骤,读取时兼容旧第 1 步草稿。第 2 步保存函数先校验,再调用 `saveStudentTrainingAnswer(TASK_KEY, buildStepTwoAnswerPayload("SAVE", 3))`,步骤配置不少于三步时设置 `currentStep.value = 2`,否则显示已保存但未配置第 3 步。重置时清空两步行数据、将步骤设为 0,并保持既有 `RESET` 行为。
`loadSavedAnswer()` 分别读取 `answer.step1Answer` 与 `answer.step2Answer` 并按维度恢复;本地草稿保存两个步骤的内容和当前步骤,读取时兼容旧第 1 步草稿。第 2 步保存函数先校验,再调用 `saveStudentTrainingAnswer(TASK_KEY, buildStepTwoAnswerPayload("SAVE", 3))`,步骤配置不少于三步时设置 `currentStep.value = 2`,否则显示已保存但未配置第 3 步。重置时清空两步行数据、将当前步骤设为 0,并保持既有 `RESET` 行为。
- [ ] **Step 5: 运行前端契约测试**

@ -1,19 +0,0 @@
# 新产品定价第 4 步实施计划
## 已确认范围
- 实现“新产品定价”第 4 步 PSM 价格敏感度测试页面。
- 固定保留 6 个默认价格区间;学生可新增、删除自定义区间。
- 学生手动填写 4 组累计占比和 3 个价格点,保存到现有通用实训答案。
- 支持导出 PSM 表格,以及上传并预览 PSM 价格折线图。
## 实现方式
- 仅修改 `src/views/product/price.vue`,复用 `step4Answer` 和通用附件上传接口,不增加数据库、后端接口或迁移。
- 对占比字段校验为 0–100 的数值;价格点校验为非空正数,价格范围校验为非空。
- 上传仅接受常见图片格式且限制 5 MB;保存上传后的地址与文件名,并用现有图片组件提供预览。
## 验证
- 检查默认行不可删除、自定义行可删、表格导出和保存负载的字段完整性。
- 运行生产构建,确认 Vue 模板与静态资源可编译。

@ -1,37 +0,0 @@
# Student Task Header Removal Design
## Goal
Remove the workbench-level `Training Task / 任务实训` heading and its requirement description from every student training page, while retaining file download, outcome export, step navigation, step content, persistence, and submit/reset behavior.
## Scope
Only Vue views reachable through student routes are included. Teacher, school-admin, and platform-admin pages are excluded.
## Design
Each affected page will use an actions-only workbench header:
- Delete the heading eyebrow, `任务实训` heading, and requirement description markup.
- Keep `TrainingMaterialButton` and the existing export button unchanged.
- Add an actions-only header class that right-aligns the retained actions, removes the now-empty divider, and reduces the bottom gap.
- Do not change task configuration, API calls, step state, module selection, draft persistence, export payloads, save, submit, or reset behavior.
## Implementation Boundaries
Shared templates are changed once so their student-route consumers inherit the behavior:
- `src/views/training/GenericTrainingPage.vue` for generic foundation and demand tasks.
- `src/views/product/components/ProductStandardTrainingPage.vue` for requirements, hardware cost, release-channel evaluation, and promotion tasks.
Direct student training views are updated in place:
- Foundation: `new-product-survey.vue`, `product-development-factors.vue`.
- Demand: `index.vue`, `environment.vue`, `people.vue`, `consumer-behavior.vue`, `consumer-scenario.vue`, `feature-conversion.vue`.
- Product: `index.vue`, `price.vue`, `differentiation.vue`, `structure.vue`, `after-sales-service.vue`.
- Channel: `index.vue`, `supplier.vue`.
- Assessment: `diagnosis.vue`, `optimization.vue`.
## Verification
The static regression test will enumerate every direct/shared student training implementation and assert that the heading/description markup is absent while `TrainingMaterialButton` remains. The production build (`npm run build:prod`) must complete successfully.

@ -6,7 +6,7 @@
## 页面
第一步展示四步进度条,步骤为“产品卖点的三层次分类”。页面提供案例资料下载入口、说明文字和包含 11 条卖点的表格。每行显示序号、卖点内容和必选下拉框;下拉项固定为“核心层”“有形层”“延伸层”。不向学生展示标准答案。
第一步展示四步进度条,当前步骤为“产品卖点的三层次分类”。页面提供案例资料下载入口、说明文字和包含 11 条卖点的表格。每行显示序号、卖点内容和必选下拉框;下拉项固定为“核心层”“有形层”“延伸层”。不向学生展示标准答案。
点击“下一步”时,页面先校验 11 项均已选择。校验通过后请求判题接口:正确行显示成功状态,错误行显示错误提示但保留学生选择;全部正确时进入第二步。页面将学生选择和本步的判题结果保存进既有学生实训答案记录,以便刷新后恢复。
@ -16,7 +16,7 @@
新增仅学生可调用的第一步判题接口。接口接收 11 条 `{ id, category }` 选择,服务端从标准答案表读取答案后逐条比对,返回每项的正确状态、错误信息、正确数量、总数量和是否全部正确。响应不包含正确层级,避免泄露标准答案。
学生页面在收到判题响应后,再调用既有学生实训答案保存接口,持久化选择、判题结果和步骤。本步未全部正确时不推进步骤;保存当前进度仍可保存草稿,不触发判题。
学生页面在收到判题响应后,再调用既有学生实训答案保存接口,持久化选择、判题结果和当前步骤。本步未全部正确时不推进步骤;保存当前进度仍可保存草稿,不触发判题。
## 数据与兼容性

@ -16,7 +16,7 @@
| 产品体验闭环 | 操作是否无需说明书,“零学习成本”?是否操作简单、反馈明确、稳定性高 |
| 生态与兼容 | 是否能接入主流平台?是否支持 iOS/Android、HomeKit、米家、Alexa 等生态?是否支持第三方开发者扩展,提供 API 或 SDK,鼓励生态共建? |
每一行的“成功产品”和“失败产品”各有一个多行输入框,学生填写对应分析。保存草稿不校验;“保存并进入第 2 步”会先校验六个输入框均为非空(去除首尾空白后判断),校验通过后以 `SAVE` 保存答案并将步骤推进至第 2 步,不触发任务总提交或成绩结算。
每一行的“成功产品”和“失败产品”各有一个多行输入框,学生填写对应分析。保存草稿不校验;“保存并进入第 2 步”会先校验六个输入框均为非空(去除首尾空白后判断),校验通过后以 `SAVE` 保存答案并将当前步骤推进至第 2 步,不触发任务总提交或成绩结算。
步骤切换后,第 1 步内容不应继续显示在第 2 步页签下。第 2 步尚未纳入本次开发时,显示轻量的待配置占位内容;若任务未配置第 2 步,则保存成功但提示当前任务尚未配置下一步并保持在第 1 步。

@ -1,32 +0,0 @@
# 新产品定价:第 3 步价值感知定价设计
## 范围
仅调整学生端“新产品定价”(`product-pricing`)的第 3 步“价值感知定价”。复用现有 `StudentTrainingAnswer.step3Answer` 和通用学生答题读写接口;不新增接口、数据表、附件上传或附件预览。
## 页面与交互
1. 步骤导航新增第 3 步“价值感知定价”,保留现有前两步功能和数据。
2. 页面提供“可替代产品/功能/额外价值感知”和“价值感知(元)”两列表格。初始仅有一行,展示“示例:闹钟”和“示例:20”作为输入提示,学生可直接填写或替换。
3. 学生可增加或删除普通数据行,至少保留一行。底部“感知价值合计”自动汇总所有有效的价值金额。
4. 学生填写“利润让渡折扣率”(0 到 100,表示百分比);“价值定价法价格”自动按 `感知价值合计 × 折扣率 ÷ 100` 计算并保留两位小数。
5. 保存时要求至少有一条完整条目、每条价值金额大于 0,折扣率必须在 0 到 100 范围内。保存成功后停留在第 3 步,不虚构后续步骤。
## 数据与兼容性
第 3 步写入 `step3Answer`,格式如下:
```json
{
"rows": [
{ "item": "闹钟", "value": 20 }
],
"profitDiscountRate": 80
}
```
读取时恢复条目与折扣率;总计和价格由页面重新计算,不单独持久化,避免保存冗余计算结果。
## 验证
执行现有前端构建 `npm run build:prod`,确认 Vue 模板、脚本与样式可编译;并人工检查新增步骤可保存、刷新后恢复、总计与价格计算正确、无上传控件出现。

@ -1,6 +1,6 @@
import request from "@/utils/request";
import { getDemoAnswerKey, getStudentDemoSession, isStudentDemo } from "@/utils/studentDemo";
import { getTrainingReviewPreviewContext, isReviewPreviewHost } from "@/utils/trainingReviewPreview";
import { getTrainingReviewPreviewContext } from "@/utils/trainingReviewPreview";
const newProductSurveyStepOneAnswers = {
"selling-point-1": "核心层",
@ -16,28 +16,6 @@ const newProductSurveyStepOneAnswers = {
"selling-point-11": "有形层",
};
const productDevelopmentProcessStepOneAnswers = {
"1.1": "关键任务",
"1.2": "关键任务",
"2.1": "关键任务",
"2.2": "关键任务",
"2.3": "关键任务",
"3.1": "关键任务",
"3.2": "非关键任务",
"3.3": "关键任务",
"3.4": "关键任务",
"3.5": "非关键任务",
"3.6": "关键任务",
"4.1": "非关键任务",
"4.2": "关键任务",
"4.3": "关键任务",
"4.4": "非关键任务",
"5.1": "关键任务",
"5.2": "非关键任务",
"5.3": "关键任务",
"5.4": "关键任务",
};
function demoResult(taskKey) {
try { return JSON.parse(sessionStorage.getItem(getDemoAnswerKey(taskKey)) || "null"); } catch (error) { return null; }
}
@ -48,12 +26,6 @@ export function getStudentTrainingAnswer(taskKey, params) {
return Promise.resolve({ code: 200, data: preview.taskKey === taskKey ? preview.answer || null : null });
}
if (isStudentDemo()) return Promise.resolve({ code: 200, data: demoResult(taskKey) });
/*
* 评阅预览兜底:正常情况下预览上下文应能命中(preview 分支);
* 万一 key 同步失效,也不允许在教师端预览里拿教师 token 真发学生作答接口,
* 直接返回空作答,页面按"该生暂无作答"展示。
*/
if (isReviewPreviewHost()) return Promise.resolve({ code: 200, data: null });
return request({
url: `/api/student-training-answers/${taskKey}`,
method: "get",

@ -579,7 +579,7 @@ export function getTaskList(query) {
params: query,
});
}
// 查询教学班实训任务发布状态;未保存过配置时 configured=false,学生端默认开放首个项目的前三项。
// 查询教学班实训任务发布状态;未保存过配置时 configured=false,学生端默认全部可见。
export function getTaskPublication(query) {
return request({
url: "/api/taskAllocation/selectTaskPublicationByClassId",
@ -615,15 +615,6 @@ export function addTask(data) {
},
});
}
// 更新教学班任务的参考答案开放状态。
export function updateTaskReferenceAnswerVisibility({ teachingClassId, taskKey, enabled }) {
return request({
url: `/api/training-tasks/classes/${encodeURIComponent(teachingClassId)}/${encodeURIComponent(taskKey)}/reference-answer`,
method: "put",
params: { enabled: enabled === true },
});
}
// 学校默认实训任务(仅管理员教师)
export function getSchoolDefaultTasks() {
return request({
@ -737,21 +728,6 @@ export function batchSaveTaskTeacherScore(data) {
data,
});
}
export function startTaskAiAssessment(params) {
return request({ url: "/api/weight/taskReview/ai-assessment", method: "post", params, headers: { repeatSubmit: false }, skipErrorMessage: true });
}
export function getTaskAiAssessment(params) {
return request({ url: "/api/weight/taskReview/ai-assessment", method: "get", params, skipErrorMessage: true });
}
export function startBatchTaskAiAssessment(data) {
return request({ url: "/api/weight/taskReview/ai-assessment/batch", method: "post", data, headers: { repeatSubmit: false }, skipErrorMessage: true });
}
export function generateTaskAiComment(params) {
return request({ url: "/api/weight/taskReview/ai-comment", method: "post", params, headers: { repeatSubmit: false }, skipErrorMessage: true });
}
export function previewTaskReferenceAnswer(params) {
return request({ url: "/api/weight/taskReview/reference-answer/preview", method: "get", params, responseType: "blob", skipErrorMessage: true });
}
// 更新成绩
export function doRankOne(params) {
return request({

@ -66,14 +66,6 @@ export function loadStudentTrainingTasks() {
return requestPromise;
}
export function previewStudentReferenceAnswer(taskKey) {
return request({
url: `/api/training-tasks/key/${encodeURIComponent(String(taskKey || "").trim())}/reference-answer/preview`,
method: "get",
responseType: "blob",
skipErrorMessage: true,
});
}
export function getTrainingTaskByKey(taskKey) {
const normalizedTaskKey = String(taskKey || "").trim();
const preview = getTrainingReviewPreviewContext();

@ -724,7 +724,7 @@ function filterTeacherManageNavigation(sections) {
.filter((section) => (section.children ? section.children.length > 0 : isSchoolNavigationVisible(section)));
}
watch(
() => JSON.stringify(userStore.schoolProductConfig),
() => userStore.schoolProductConfig?.organizationMode,
(organizationMode, previousOrganizationMode) => {
if (organizationMode === previousOrganizationMode) return;
if ([2, 3].includes(Number(userStore.userInfo.roleId))) {
@ -734,12 +734,5 @@ watch(
);
onMounted(() => {
getTaskList();
window.addEventListener("focus", refreshSchoolConfiguration);
});
onBeforeUnmount(() => window.removeEventListener("focus", refreshSchoolConfiguration));
function refreshSchoolConfiguration() {
if ([2, 3].includes(Number(userStore.userInfo.roleId))) {
userStore.ensureSchoolProductConfig().catch(() => null);
}
}
</script>

@ -1,30 +1,28 @@
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2024-08-16 17:56:32
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-16 17:02:23
* @FilePath: \vue3\src\permission.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import router from "./router";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, getUserInfo } from "@/utils/auth";
import { isHttp } from "@/utils/validate";
import { isRelogin } from "@/utils/request";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";
import { loadStudentTrainingTasks } from "@/api/trainingTask";
import { resolveTrainingTaskKey } from "@/views/training/taskKeyMap";
NProgress.configure({ showSpinner: false });
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2024-08-16 17:56:32
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-16 17:02:23
* @FilePath: \vue3\src\permission.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import router from "./router";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, getUserInfo } from "@/utils/auth";
import { isHttp } from "@/utils/validate";
import { isRelogin } from "@/utils/request";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";
NProgress.configure({ showSpinner: false });
const whiteList = ["/login", "/register", "/student-demo"];
router.beforeEach((to, from, next) => {
NProgress.start();
if (getToken()) {
router.beforeEach((to, from, next) => {
NProgress.start();
if (getToken()) {
if (to.path === "/login") {
if (JSON.parse(getUserInfo()).roleId == 1) {
next({ path: "/index" });
@ -36,16 +34,15 @@ router.beforeEach((to, from, next) => {
next({ path: "/index" });
NProgress.done();
} else if (JSON.parse(getUserInfo()).roleId == 4) {
next({ path: "/index" });
NProgress.done();
}
next({ path: "/index" });
NProgress.done();
}
} else {
const userStore = useUserStore();
const requiresSchoolProductConfig = [2, 3].includes(Number(userStore.userInfo?.roleId)) || to.matched.some((record) =>
const requiresSchoolProductConfig = to.matched.some((record) =>
record.meta?.requiresFacultyManagement
|| record.meta?.requiresMajorManagement
|| record.meta?.requiresAdminClass
|| record.meta?.awaitSchoolProductConfig
);
const continueNavigation = () => {
usePermissionStore()
@ -53,31 +50,7 @@ router.beforeEach((to, from, next) => {
.then(() => next()); // hack方法 确保addRoutes已完成
};
// 学生实训页面不能只依赖侧边栏隐藏:直接输入地址时也必须按当前教学班的发布配置拦截。
const userInfo = JSON.parse(getUserInfo() || "{}");
const taskKey = Number(userInfo.roleId) === 4
? resolveTrainingTaskKey(to, to.params?.pageKey)
: "";
if (taskKey) {
loadStudentTrainingTasks()
.then((response) => {
const tasks = Array.isArray(response?.data) ? response.data : [];
if (tasks.some((task) => task?.taskKey === taskKey)) {
continueNavigation();
return;
}
ElMessage.warning("该实训任务暂未对当前教学班开放");
next({ path: "/index" });
NProgress.done();
})
.catch(() => {
// 后端任务详情接口仍会做最终校验,网络异常时保留原有路由错误处理。
continueNavigation();
});
return;
}
// 学校管理员和教师导航时刷新配置,管理页额外校验对应能力。
// 普通页面无需等待学校配置接口;仅管理页需要用该配置做访问校验。
if (!requiresSchoolProductConfig) {
continueNavigation();
return;
@ -86,10 +59,10 @@ router.beforeEach((to, from, next) => {
userStore
.ensureSchoolProductConfig()
.then((config) => {
if (!config) throw new Error("学校配置尚未就绪");
const facultyEnabled = config.facultyManagementEnabled === true;
const majorEnabled = config.majorManagementEnabled === true;
const adminClassEnabled = config.adminClassManagementEnabled === true;
const legacyAdminEnabled = config?.organizationMode !== "TEACHING_CLASS_ONLY";
const facultyEnabled = config?.facultyManagementEnabled ?? legacyAdminEnabled;
const majorEnabled = config?.majorManagementEnabled ?? legacyAdminEnabled;
const adminClassEnabled = config?.adminClassManagementEnabled ?? legacyAdminEnabled;
const unavailableManagementRoute = to.matched.some((record) =>
(record.meta?.requiresFacultyManagement && !facultyEnabled)
|| (record.meta?.requiresMajorManagement && !majorEnabled)
@ -111,19 +84,19 @@ router.beforeEach((to, from, next) => {
next(false);
NProgress.done();
});
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next();
} else {
next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
NProgress.done();
}
}
});
router.afterEach(() => {
NProgress.done();
});
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next();
} else {
next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
NProgress.done();
}
}
});
router.afterEach(() => {
NProgress.done();
});

@ -1,92 +1,92 @@
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-04-22 14:05:45
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-20 17:53:58
* @FilePath: \e-commerce-internet\src\router\index.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-04-22 14:05:45
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-04-28 14:48:41
* @FilePath: \e-commerce-internet\src\router\index.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-04-22 14:05:45
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-05-20 17:53:58
* @FilePath: \e-commerce-internet\src\router\index.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
/*
* @Author: qinzhenpen qzp1807@126.com
* @Date: 2025-04-22 14:05:45
* @LastEditors: qinzhenpen qzp1807@126.com
* @LastEditTime: 2025-04-28 14:48:41
* @FilePath: \e-commerce-internet\src\router\index.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { createWebHashHistory, createRouter } from "vue-router";
/* Layout */
import Layout from "@/layout";
/**
* Note: 路由配置项
*
* hidden: true // 当设置 true 的时候该路由不会再侧边栏出现 如401,login等页面,或者如一些编辑页面/edit/1
* alwaysShow: true // 当你一个路由下面的 children 声明的路由大于1个时,自动会变成嵌套的模式--如组件页面
* // 只有一个时,会将那个子路由当做根路由显示在侧边栏--如引导页面
* // 若你想不管路由下面的 children 声明的个数都显示你的根路由
* // 你可以设置 alwaysShow: true,这样它就会忽略之前定义的规则,一直显示根路由
* redirect: noRedirect // 当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
* name:'router-name' // 设定路由的名字,一定要填写不然使用<keep-alive>时会出现各种问题
* query: '{"id": 1, "name": "ry"}' // 访问路由的默认传递参数
* roles: ['admin', 'common'] // 访问路由的角色权限
* permissions: ['a:a:a', 'b:b:b'] // 访问路由的菜单权限
* meta : {
noCache: true // 如果设置为true,则不会被 <keep-alive> 缓存(默认 false)
title: 'title' // 设置该路由在侧边栏和面包屑中展示的名字
icon: 'svg-name' // 设置该路由的图标,对应路径src/asse ts/icons/svg
breadcrumb: false // 如果设置为false,则不会在breadcrumb面包屑中显示
activeMenu: '/system/user' // 当路由设置了该属性,则会高亮相对应的侧边栏。
}
*/
// 公共路由
export const constantRoutes = [
{
path: "/redirect",
component: Layout,
hidden: true,
children: [
{
path: "/redirect/:path(.*)",
component: () => import("@/views/redirect/index.vue"),
},
],
},
{
path: "/login",
component: () => import("@/views/login"),
hidden: true,
},
/* Layout */
import Layout from "@/layout";
/**
* Note: 路由配置项
*
* hidden: true // 当设置 true 的时候该路由不会再侧边栏出现 如401,login等页面,或者如一些编辑页面/edit/1
* alwaysShow: true // 当你一个路由下面的 children 声明的路由大于1个时,自动会变成嵌套的模式--如组件页面
* // 只有一个时,会将那个子路由当做根路由显示在侧边栏--如引导页面
* // 若你想不管路由下面的 children 声明的个数都显示你的根路由
* // 你可以设置 alwaysShow: true,这样它就会忽略之前定义的规则,一直显示根路由
* redirect: noRedirect // 当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
* name:'router-name' // 设定路由的名字,一定要填写不然使用<keep-alive>时会出现各种问题
* query: '{"id": 1, "name": "ry"}' // 访问路由的默认传递参数
* roles: ['admin', 'common'] // 访问路由的角色权限
* permissions: ['a:a:a', 'b:b:b'] // 访问路由的菜单权限
* meta : {
noCache: true // 如果设置为true,则不会被 <keep-alive> 缓存(默认 false)
title: 'title' // 设置该路由在侧边栏和面包屑中展示的名字
icon: 'svg-name' // 设置该路由的图标,对应路径src/asse ts/icons/svg
breadcrumb: false // 如果设置为false,则不会在breadcrumb面包屑中显示
activeMenu: '/system/user' // 当路由设置了该属性,则会高亮相对应的侧边栏。
}
*/
// 公共路由
export const constantRoutes = [
{
path: "/redirect",
component: Layout,
hidden: true,
children: [
{
path: "/redirect/:path(.*)",
component: () => import("@/views/redirect/index.vue"),
},
],
},
{
path: "/login",
component: () => import("@/views/login"),
hidden: true,
},
{
path: "/register",
component: () => import("@/views/register"),
hidden: true,
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/error/404"),
hidden: true,
},
{
path: "/401",
component: () => import("@/views/error/401"),
hidden: true,
},
{
path: "",
component: Layout,
redirect: "/index",
meta: { title: "首页", icon: "首页", affix: true },
children: [
{
path: "/index",
component: () => import("@/views/index"),
name: "Index",
},
],
},
];
// 动态路由,基于用户权限动态去加载
component: () => import("@/views/register"),
hidden: true,
},
{
path: "/:pathMatch(.*)*",
component: () => import("@/views/error/404"),
hidden: true,
},
{
path: "/401",
component: () => import("@/views/error/401"),
hidden: true,
},
{
path: "",
component: Layout,
redirect: "/index",
meta: { title: "首页", icon: "首页", affix: true },
children: [
{
path: "/index",
component: () => import("@/views/index"),
name: "Index",
},
],
},
];
// 动态路由,基于用户权限动态去加载
export const dynamicRoutes = [
{
path: "/training-step",
@ -103,48 +103,48 @@ export const dynamicRoutes = [
],
},
{
path: "/ai",
component: Layout,
redirect: "/ai/assistant",
roles: ["student"],
children: [
{
path: "learning-situation-analysis",
hidden: true,
component: () => import("@/views/analysis-of-students/analysis.vue"),
name: "learning-situation-analysis",
meta: { title: "AI学情分析", icon: "ai", affix: true },
},
{
path: "learning-situation-dialogue",
hidden: true,
component: () => import("@/views/analysis-of-students/dialogue.vue"),
name: "learning-situation-dialogue",
meta: { title: "对话", icon: "ai", affix: true },
},
// 实训教案
{
path: "teaching-plan",
hidden: true,
component: () => import("@/views/analysis-of-students/training-lesson-plan"),
name: "teaching-plan",
meta: { title: "AI助手", icon: "ai", affix: true },
},
],
},
// 智能助手
path: "/ai",
component: Layout,
redirect: "/ai/assistant",
roles: ["student"],
children: [
{
path: "learning-situation-analysis",
hidden: true,
component: () => import("@/views/analysis-of-students/analysis.vue"),
name: "learning-situation-analysis",
meta: { title: "AI学情分析", icon: "ai", affix: true },
},
{
path: "learning-situation-dialogue",
hidden: true,
component: () => import("@/views/analysis-of-students/dialogue.vue"),
name: "learning-situation-dialogue",
meta: { title: "对话", icon: "ai", affix: true },
},
// 实训教案
{
path: "teaching-plan",
hidden: true,
component: () => import("@/views/analysis-of-students/training-lesson-plan"),
name: "teaching-plan",
meta: { title: "AI助手", icon: "ai", affix: true },
},
],
},
// 智能助手
{
path: "/assistant",
component: Layout,
redirect: "/assistant/index",
roles: ["student"],
meta: { title: "AI智能助手", icon: "智能助手", affix: true },
children: [
{
path: "index",
component: () => import("@/views/AI/index.vue"),
name: "assistant",
meta: { title: "AI智能助手", icon: "智能助手", affix: true },
meta: { title: "AI智能助手", icon: "智能助手", affix: true },
children: [
{
path: "index",
component: () => import("@/views/AI/index.vue"),
name: "assistant",
meta: { title: "AI智能助手", icon: "智能助手", affix: true },
},
],
},
@ -214,21 +214,21 @@ export const dynamicRoutes = [
//市场需求挖掘
{
path: "/demand",
component: Layout,
redirect: "/demand/index",
roles: ["student"],
meta: { title: "市场需求挖掘", icon: "需求挖掘", affix: true },
alwaysShow: true,
children: [
//行业需求分析
component: Layout,
redirect: "/demand/index",
roles: ["student"],
meta: { title: "市场需求挖掘", icon: "需求挖掘", affix: true },
alwaysShow: true,
children: [
//行业需求分析
{
path: "index",
component: () => import("@/views/demand/industry-demand-analysis.vue"),
name: "demand",
meta: { title: "行业需求分析", icon: "需求挖掘", affix: true, pageKey: "industry-demand-analysis" },
},
// 竞争环境分析
{
// 竞争环境分析
{
path: "environment",
component: () => import("@/views/demand/competitive-environment-analysis.vue"),
name: "environment",
@ -241,7 +241,7 @@ export const dynamicRoutes = [
name: "people",
meta: { title: "目标用户画像", icon: "需求挖掘", affix: true, pageKey: "target-user-profile" },
},
// 用户数据分析
// 用户数据分析
{
path: "user",
component: () => import("@/views/demand/user.vue"),
@ -274,24 +274,24 @@ export const dynamicRoutes = [
},
],
},
// 产品规划
{
path: "/product",
component: Layout,
redirect: "/product/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品规划", icon: "产品规划", affix: true },
children: [
// 产品定位
{
// 产品规划
{
path: "/product",
component: Layout,
redirect: "/product/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品规划", icon: "产品规划", affix: true },
children: [
// 产品定位
{
path: "index",
component: () => import("@/views/product/market-opportunity-selection.vue"),
name: "product",
meta: { title: "市场机会识别与选品", icon: "产品规划", affix: true, pageKey: "market-opportunity-selection", hideSupplementSteps: true },
},
// 产品定价
{
// 产品定价
{
path: "price",
component: () => import("@/views/product/price.vue"),
name: "price",
@ -304,7 +304,7 @@ export const dynamicRoutes = [
name: "differentiation",
meta: { title: "产品价值主张及定位", icon: "产品规划", affix: true, pageKey: "product-value-positioning" },
},
// 产品结构规划
// 产品结构规划
{
path: "structure",
component: () => import("@/views/product/structure.vue"),
@ -331,125 +331,125 @@ export const dynamicRoutes = [
},
],
},
// 产品投放测试
{
path: "/test",
component: Layout,
redirect: "/test/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品投放测试", icon: "产品投放测试", affix: true },
children: [
// 产品投放测试
{
// 产品投放测试
{
path: "/test",
component: Layout,
redirect: "/test/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品投放测试", icon: "产品投放测试", affix: true },
children: [
// 产品投放测试
{
path: "index",
component: () => import("@/views/test/index.vue"),
name: "test",
meta: { title: "发布渠道评估", icon: "产品投放测试", affix: true, pageKey: "release-channel-evaluation" },
},
// 产品推广测试
{
// 产品推广测试
{
path: "promotion",
component: () => import("@/views/test/promotion.vue"),
name: "promotion",
meta: { title: "产品推广测试", icon: "产品投放测试", affix: true, pageKey: "promotion-effect-optimization" },
},
// 渠道表现分析
{
// 渠道表现分析
{
path: "channelas",
component: () => import("@/views/test/channel.vue"),
name: "channelas",
meta: { title: "渠道表现分析", icon: "产品投放测试", affix: true, pageKey: "release-channel-evaluation" },
},
// 产品营销定位
{
// 产品营销定位
{
path: "marketing",
component: () => import("@/views/test/marketing.vue"),
name: "marketing",
meta: { title: "产品营销定位", icon: "产品投放测试", affix: true, pageKey: "promotion-effect-optimization" },
},
],
},
// 供应渠道管理
{
path: "/channel",
component: Layout,
redirect: "/channel/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "供应渠道管理", icon: "供应渠道管理", affix: true },
children: [
// 供应渠道管理
{
},
],
},
// 供应渠道管理
{
path: "/channel",
component: Layout,
redirect: "/channel/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "供应渠道管理", icon: "供应渠道管理", affix: true },
children: [
// 供应渠道管理
{
path: "index",
component: () => import("@/views/channel/index.vue"),
name: "channel",
meta: { title: "采购需求预测", icon: "供应渠道管理", affix: true, pageKey: "purchase-demand-forecast" },
},
// 采购产品定位
{
// 采购产品定位
{
path: "purchase",
component: () => import("@/views/channel/purchase.vue"),
name: "purchase",
meta: { title: "采购产品定位", icon: "供应渠道管理", affix: true, pageKey: "purchase-demand-forecast" },
},
// 供应商评估与选择
{
// 供应商评估与选择
{
path: "supplier",
component: () => import("@/views/channel/supplier.vue"),
name: "supplier",
meta: { title: "供应商评估与选择", icon: "供应渠道管理", affix: true, pageKey: "supplier-evaluation" },
},
],
},
//产品评估与考核
{
path: "/assessment",
component: Layout,
redirect: "/assessment/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品评估与考核", icon: "产品评估与考核", affix: true },
children: [
// 产品评估与考核
{
},
],
},
//产品评估与考核
{
path: "/assessment",
component: Layout,
redirect: "/assessment/index",
roles: ["student"],
alwaysShow: true,
meta: { title: "产品评估与考核", icon: "产品评估与考核", affix: true },
children: [
// 产品评估与考核
{
path: "index",
component: () => import("@/views/assessment/index.vue"),
name: "assessment",
meta: { title: "产品表现分析", icon: "产品评估与考核", affix: true, pageKey: "product-diagnosis-iteration" },
},
// 产品问题诊断
{
// 产品问题诊断
{
path: "diagnosis",
component: () => import("@/views/assessment/diagnosis.vue"),
name: "diagnosis",
meta: { title: "产品问题诊断", icon: "产品评估与考核", affix: true, pageKey: "product-diagnosis-iteration" },
},
// 品类结构优化
{
// 品类结构优化
{
path: "optimization",
component: () => import("@/views/assessment/optimization.vue"),
name: "optimization",
meta: { title: "品类结构优化", icon: "产品评估与考核", affix: true, pageKey: "category-optimization" },
},
],
},
// 实验报告
{
path: "/report",
component: Layout,
redirect: "/report/index",
roles: ["student"],
children: [
{
path: "index",
component: () => import("@/views/test-report/index"),
name: "Report",
hidden: true,
meta: { title: "实验报告", icon: "成绩中心", affix: true },
},
],
},
},
],
},
// 实验报告
{
path: "/report",
component: Layout,
redirect: "/report/index",
roles: ["student"],
children: [
{
path: "index",
component: () => import("@/views/test-report/index"),
name: "Report",
hidden: true,
meta: { title: "实验报告", icon: "成绩中心", affix: true },
},
],
},
// 旧实验数据源入口兼容跳转,导航统一收敛到 BI 可视化
{
path: "/data",
@ -457,44 +457,44 @@ export const dynamicRoutes = [
roles: ["student"],
hidden: true,
},
// 学情分析,
{
path: "/analysis",
component: Layout,
redirect: "/analysis/index",
roles: ["student"],
children: [
{
path: "index",
component: () => import("@/views/analysis-of-students/analysis"),
name: "Analysis",
hidden: true,
meta: { title: "学情分析", icon: "成绩中心", affix: true },
},
{
path: "dialogue",
component: () => import("@/views/analysis-of-students/dialogue"),
name: "dialogue",
hidden: true,
meta: { title: "学情分析", icon: "成绩中心", affix: true },
},
],
},
// Bi可视化分析
{
path: "",
component: Layout,
roles: ["student"],
redirect: "/bi",
hidden: true,
children: [
{
path: "/bi",
component: () => import("@/views/visual-analysis/index.vue"),
name: "bi",
meta: { title: "BI可视化分析", icon: "dashboard", affix: true },
},
],
// 学情分析,
{
path: "/analysis",
component: Layout,
redirect: "/analysis/index",
roles: ["student"],
children: [
{
path: "index",
component: () => import("@/views/analysis-of-students/analysis"),
name: "Analysis",
hidden: true,
meta: { title: "学情分析", icon: "成绩中心", affix: true },
},
{
path: "dialogue",
component: () => import("@/views/analysis-of-students/dialogue"),
name: "dialogue",
hidden: true,
meta: { title: "学情分析", icon: "成绩中心", affix: true },
},
],
},
// Bi可视化分析
{
path: "",
component: Layout,
roles: ["student"],
redirect: "/bi",
hidden: true,
children: [
{
path: "/bi",
component: () => import("@/views/visual-analysis/index.vue"),
name: "bi",
meta: { title: "BI可视化分析", icon: "dashboard", affix: true },
},
],
},
{
path: "/examination",
@ -540,83 +540,81 @@ export const teacherRoutes = [
redirect: "/school/index",
roles: ["teacher"],
meta: { title: "院系管系", icon: "院系管系", affix: true, requiresFacultyManagement: true },
children: [
// 院校管理
{
path: "index",
component: () => import("@/views/teacherEnd/school/index.vue"),
name: "school",
meta: { title: "院系管系", icon: "院系管系", affix: true },
},
],
},
// 专业管理
{
children: [
// 院校管理
{
path: "index",
component: () => import("@/views/teacherEnd/school/index.vue"),
name: "school",
meta: { title: "院系管系", icon: "院系管系", affix: true },
},
],
},
// 专业管理
{
path: "/major",
component: Layout,
redirect: "/major/index",
roles: ["teacher"],
meta: { title: "专业管理", icon: "专业管理", affix: true, requiresMajorManagement: true },
children: [
// 专业管理
{
path: "index",
component: () => import("@/views/teacherEnd/major/index.vue"),
name: "major",
meta: { title: "专业管理", icon: "专业管理", affix: true },
},
],
},
// 班级管理
{
path: "/class",
component: Layout,
redirect: "/class/index",
roles: ["teacher"],
meta: { title: "班级管理", icon: "班级管理", affix: true },
children: [
// 班级管理
{
path: "index",
component: () => import("@/views/teacherEnd/class/index.vue"),
name: "class",
// 页面按超管平台组织模式配置渲染行政班/教学班,导航前先等配置接口返回,
// 避免配置晚于挂载导致页面先按行政班渲染再闪变。
meta: { title: "班级管理", icon: "班级管理", affix: true, awaitSchoolProductConfig: true },
},
],
},
// 教师管理
{
children: [
// 专业管理
{
path: "index",
component: () => import("@/views/teacherEnd/major/index.vue"),
name: "major",
meta: { title: "专业管理", icon: "专业管理", affix: true },
},
],
},
// 班级管理
{
path: "/class",
component: Layout,
redirect: "/class/index",
roles: ["teacher"],
meta: { title: "班级管理", icon: "班级管理", affix: true },
children: [
// 班级管理
{
path: "index",
component: () => import("@/views/teacherEnd/class/index.vue"),
name: "class",
meta: { title: "班级管理", icon: "班级管理", affix: true },
},
],
},
// 教师管理
{
path: "/teacher",
component: Layout,
redirect: "/teacher/index",
roles: ["teacher"],
meta: { title: "教师管理", icon: "教师管理", affix: true },
children: [
// 教师管理
{
path: "index",
component: () => import("@/views/teacherEnd/teacher/index.vue"),
name: "teacher",
meta: { title: "教师管理", icon: "教师管理", affix: true },
},
],
},
// 学生管理
children: [
// 教师管理
{
path: "index",
component: () => import("@/views/teacherEnd/teacher/index.vue"),
name: "teacher",
meta: { title: "教师管理", icon: "教师管理", affix: true },
},
],
},
// 学生管理
{
path: "/student",
component: Layout,
redirect: "/student/index",
roles: ["teacher"],
meta: { title: "学生管理", icon: "学生管理", affix: true },
children: [
// 学生管理
{
path: "index",
component: () => import("@/views/teacherEnd/student/index.vue"),
name: "student",
meta: { title: "学生管理", icon: "学生管理", affix: true },
redirect: "/student/index",
roles: ["teacher"],
meta: { title: "学生管理", icon: "学生管理", affix: true },
children: [
// 学生管理
{
path: "index",
component: () => import("@/views/teacherEnd/student/index.vue"),
name: "student",
meta: { title: "学生管理", icon: "学生管理", affix: true },
},
],
},
@ -654,21 +652,21 @@ export const teacherRoutes = [
},
{
path: "/task",
component: Layout,
redirect: "/task/index",
roles: ["teacher"],
meta: { title: "任务分配", icon: "任务分配", affix: true },
children: [
// 任务分配
{
path: "index",
component: () => import("@/views/teacherEnd/task/index.vue"),
name: "task",
meta: { title: "任务分配", icon: "任务分配", affix: true },
},
],
},
// 成绩中心
component: Layout,
redirect: "/task/index",
roles: ["teacher"],
meta: { title: "任务分配", icon: "任务分配", affix: true },
children: [
// 任务分配
{
path: "index",
component: () => import("@/views/teacherEnd/task/index.vue"),
name: "task",
meta: { title: "任务分配", icon: "任务分配", affix: true },
},
],
},
// 成绩中心
{
path: "/task-review",
component: Layout,
@ -686,19 +684,19 @@ export const teacherRoutes = [
},
{
path: "/score",
component: Layout,
redirect: "/score/index",
roles: ["teacher"],
meta: { title: "成绩中心", icon: "成绩中心", affix: true },
children: [
// 成绩中心
{
path: "index",
component: () => import("@/views/teacherEnd/score/index.vue"),
name: "score",
meta: { title: "成绩中心", icon: "成绩中心", affix: true },
},
],
component: Layout,
redirect: "/score/index",
roles: ["teacher"],
meta: { title: "成绩中心", icon: "成绩中心", affix: true },
children: [
// 成绩中心
{
path: "index",
component: () => import("@/views/teacherEnd/score/index.vue"),
name: "score",
meta: { title: "成绩中心", icon: "成绩中心", affix: true },
},
],
},
{
path: "/exam",
@ -902,11 +900,11 @@ const router = createRouter({
history: createWebHashHistory(),
routes: [...constantRoutes, ...dynamicRoutes, ...teacherRoutes, ...platformAdminRoutes, ...schoolAdminRoutes],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
},
});
export default router;
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
},
});
export default router;

@ -10,7 +10,6 @@ import { login, logout, getInfo } from "@/api/login";
import { getCurrentSchoolProductConfig } from "@/api/schoolProductConfig";
import { getToken, setToken, removeToken, setUserInfo, removeUserInfo, getUserInfo } from "@/utils/auth";
import defAva from "@/assets/images/profile.jpg";
const schoolConfigRequests = new WeakMap();
const useUserStore = defineStore("user", {
state: () => ({
token: getToken(),
@ -33,7 +32,6 @@ const useUserStore = defineStore("user", {
.then((res) => {
setToken(res.data.token);
this.token = res.data.token;
this.schoolProductConfig = null;
this.userInfo = res.data;
setUserInfo(JSON.stringify(res.data));
resolve();
@ -67,25 +65,16 @@ const useUserStore = defineStore("user", {
});
},
ensureSchoolProductConfig() {
if (this.schoolProductConfig) {
return Promise.resolve(this.schoolProductConfig);
}
if (this.userInfo?.roleId == 1) {
this.schoolProductConfig = null;
return Promise.resolve(null);
}
const requestToken = this.token;
const pending = schoolConfigRequests.get(this);
if (pending?.token === requestToken) return pending.promise;
const promise = getCurrentSchoolProductConfig().then((res) => {
if (this.token !== requestToken) return null;
return getCurrentSchoolProductConfig().then((res) => {
this.schoolProductConfig = res.data;
return this.schoolProductConfig;
}).catch((error) => {
if (this.token === requestToken) this.schoolProductConfig = null;
throw error;
}).finally(() => {
if (schoolConfigRequests.get(this)?.promise === promise) schoolConfigRequests.delete(this);
});
schoolConfigRequests.set(this, { token: requestToken, promise });
return promise;
},
// 退出系统
logOut() {

@ -1,33 +1,34 @@
import Cookies from "js-cookie";
import { clearStudentDemoSession, getStudentDemoSession, isStudentDemo } from "@/utils/studentDemo";
const TokenKey = "Admin-Token";
const user = "UserInfo";
// 历史遗留:旧版本曾把 cookie 写到共享主域 .sztzjy.com,会污染其他子域系统的登录态。
// 现已改为 host-only(只写当前子域),此常量仅用于清理浏览器中遗留的旧主域 cookie。
const LegacySharedCookieDomain = ".sztzjy.com";
const SharedCookieDomain = ".sztzjy.com";
function isSharedCookieHost() {
if (typeof window === "undefined") return false;
const hostname = window.location.hostname.toLowerCase();
return hostname === "sztzjy.com" || hostname.endsWith(LegacySharedCookieDomain);
return hostname === "sztzjy.com" || hostname.endsWith(SharedCookieDomain);
}
function removeLegacySharedCookie(name) {
if (isSharedCookieHost()) {
Cookies.remove(name, { domain: LegacySharedCookieDomain, path: "/" });
}
function getAuthCookieOptions() {
if (!isSharedCookieHost()) return { path: "/" };
return {
domain: SharedCookieDomain,
path: "/",
secure: true,
sameSite: "Lax",
};
}
function setAuthCookie(name, value) {
// 先清掉旧主域 cookie,避免同名双 cookie 导致读取到脏值
removeLegacySharedCookie(name);
return Cookies.set(name, value, { path: "/" });
if (isSharedCookieHost()) Cookies.remove(name, { path: "/" });
return Cookies.set(name, value, getAuthCookieOptions());
}
function removeAuthCookie(name) {
Cookies.remove(name, { path: "/" });
removeLegacySharedCookie(name);
if (isSharedCookieHost()) Cookies.remove(name, getAuthCookieOptions());
}
export function getToken() {

@ -1,57 +0,0 @@
export const DEFAULT_INTERVIEW_RECORDS = [
{
code: "U01",
basicAttributes: "李伟,29岁,男性,上海,互联网公司程序员,月收入约2.8万元",
content: [
{ question: "您平时的睡眠质量如何?通常因为什么失眠?", answer: "非常差。几乎每天都熬夜,不是因为想玩,是脑子停不下来,一直在想工作上的bug和方案。即使躺下,也觉得心神不宁,入睡特别困难。有时候心脏会有点不舒服,知道是压力大和缺觉搞的。" },
{ question: "您尝试过哪些方法来改善睡眠?", answer: "买过褪黑素,吃了一段时间感觉效果不明显,而且怕有依赖。也用过一些冥想App,听着白噪音确实有点用,但手机亮着屏幕放在旁边总觉得不舒服,而且容易被消息通知打断。" },
{ question: "如果有一款智能助眠灯,您最希望它有什么功能?", answer: "首先,光一定要柔和,能让我放松下来。其次,最好能无缝衔接我用的冥想App的内容,别让我再来回切换。还有就是,我挺想知道自己每晚到底睡了多久,醒了多少次,有个数据报告会让我觉得这钱花得值。如果能在我睡着后自动关灯、调低空调温度,那就太智能了。" },
{ question: "在购买这类产品时,您最看重什么?", answer: "效果和科技感。价格不是最敏感的因素,只要它真的能帮我解决问题,我愿意为专业和便捷付费。品牌最好有点调性,别显得太廉价。" },
],
},
{
code: "U02",
basicAttributes: "赵静,31岁,女性,杭州,中学教师,月收入约1.5万元",
content: [
{ question: "您目前的睡眠状况是怎样的?", answer: "碎片化,非常碎片化。宝宝现在一岁多,夜里还是会醒。从她出生后我就没睡过一个整觉。现在问题是,即使宝宝睡了,我自己也因为长期疲劳变得神经衰弱,很难深度睡眠,有点声音就醒。" },
{ question: "在您的睡前时光,通常有什么习惯或需求?", answer: "我需要一段属于自己的缓冲时间。会看会儿手机,但知道蓝光不好。也希望有一些温和的声音能盖掉家里的其他杂音,帮助我放松。另外,夜里起床照顾宝宝,需要一盏能瞬间提供柔和、不刺眼照明的小灯,现在开大灯太晃眼了。" },
{ question: "对于智能助眠灯,您有什么期待?", answer: "操作一定要简单!我可没时间研究复杂的APP。最好能语音控制,比如我说小眠,开夜灯,它就亮起最暗的光。灯光颜色最好能适合哺乳。内容上,我希望有一些针对成人的睡前放松引导,或者温和的轻音乐,最好也能播放一些给宝宝听的摇篮曲。" },
{ question: "购买决策时,哪些因素会打动您?", answer: "安全、实用、高性价比。材质必须安全无害,因为宝宝可能会碰到。功能要真正解决我的痛点,而不是花里胡哨。" },
],
},
{
code: "U03",
basicAttributes: "王悦,22岁,女性,广州,设计专业大学生,月生活费约3000元",
content: [
{ question: "您关注睡眠健康吗?", answer: "关注!我们寝室经常聊朋克养生,就是一边熬夜做设计作业,一边泡枸杞。我知道睡眠很重要,但有时候是功课多,有时候就是单纯不想睡,刷短视频停不下来。" },
{ question: "您的睡前仪式通常包括什么?", answer: "我很喜欢营造氛围感。会在宿舍点香薰蜡烛,但不太安全。也喜欢用手机放ASMR或者助眠视频,但同样需要开着屏幕。我觉得我的睡眠环境需要更有仪式感和科技感。" },
{ question: "一款什么样的助眠灯会吸引您购买?", answer: "颜值是第一位的!设计必须好看,有质感,能融入我的宿舍装饰风格。灯光效果要多,能切换不同颜色和模式,满足我学习、休息、自拍打光等不同场景。可以没有深入的睡眠监测,但一定要能语音控制,和我互动,比如问问天气、设定闹钟。最好还有一些有趣的、小众的白噪音,比如雨声、篝火声。" },
{ question: "在消费这类产品时,您是怎样的心理?", answer: "我愿意为情绪价值和社交价值买单。它不仅要好用,还要能成为我的一个社交货币,就是可以拍照分享到小红书的那种。价格不能太贵,四五百元我觉得是上限了,但如果它足够好看、好玩,我会非常心动。" },
],
},
]
export function cloneInterviewRecords(records = DEFAULT_INTERVIEW_RECORDS) {
const source = Array.isArray(records) && records.length ? records : DEFAULT_INTERVIEW_RECORDS
return JSON.parse(JSON.stringify(source)).map((record, index) => ({
title: String(record?.title || `访谈记录${index + 1}`),
code: String(record?.code || `U0${index + 1}`),
basicAttributes: String(record?.basicAttributes || ""),
content: Array.isArray(record?.content) && record.content.length
? record.content.map((item) => ({ question: String(item?.question || ""), answer: String(item?.answer || "") }))
: [{ question: "", answer: "" }],
}))
}
export function parseInterviewRecords(value) {
if (Array.isArray(value) && value.length) return cloneInterviewRecords(value)
if (typeof value === "string" && value.trim()) {
try {
const parsed = JSON.parse(value)
if (Array.isArray(parsed) && parsed.length) return cloneInterviewRecords(parsed)
} catch (error) {
// Fall back to the built-in records when older task rows have no JSON.
}
}
return cloneInterviewRecords()
}

@ -12,17 +12,6 @@ let downloadLoadingInstance;
// 是否显示重新登录
export let isRelogin = { show: false };
// 进行中的 axios 请求计数:任务评阅预览页用它判断「接口全部返回」后再放行页面
let pendingRequestCount = 0;
export function getPendingRequestCount() {
return pendingRequestCount;
}
function settleRequest() {
pendingRequestCount = Math.max(0, pendingRequestCount - 1);
}
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
@ -70,7 +59,6 @@ service.interceptors.request.use(
} else {
}
}
pendingRequestCount++;
return config;
},
(error) => {
@ -81,7 +69,6 @@ service.interceptors.request.use(
// 响应拦截器
service.interceptors.response.use(
(res) => {
settleRequest();
// 未设置状态码则默认成功状态
const code = res.data.code || 200;
// console.log(code);
@ -124,7 +111,6 @@ service.interceptors.response.use(
}
},
(error) => {
settleRequest();
console.log("err" + error);
let { message } = error;
const serverMessage = String(error?.response?.data?.msg || "").trim();

@ -850,7 +850,7 @@ export function collectTrainingOutcomeDetails(task, studentAnswer) {
const content = readableContent(nodes[index]);
return {
name,
content: content.text || (content.tables.length ? "" : "本步骤内容以页面实训说明为准。"),
content: content.text || (content.tables.length ? "" : "当前步骤内容以页面实训说明为准。"),
tables: content.tables,
answers: domAnswers[index]?.length ? domAnswers[index] : savedAnswers[index],
};
@ -894,7 +894,7 @@ function createPrintDocument(task) {
const title = normalizeText(task?.taskName || task?.title || "实训成果");
const objectives = normalizeList(task?.objectives);
const steps = normalizeList(task?.steps);
const stepDetails = Array.isArray(task?.stepDetails) && task.stepDetails.length ? task.stepDetails : steps.map((name) => ({ name, content: "本步骤内容以页面实训说明为准。", tables: [], answers: [] }));
const stepDetails = Array.isArray(task?.stepDetails) && task.stepDetails.length ? task.stepDetails : steps.map((name) => ({ name, content: "当前步骤内容以页面实训说明为准。", tables: [], answers: [] }));
const generatedAt = new Intl.DateTimeFormat("zh-CN", {
year: "numeric",
month: "2-digit",

@ -42,20 +42,10 @@ export function getTrainingReviewPreviewContext() {
return readTrainingReviewPreview(getTrainingReviewPreviewKey());
}
/*
* 兜底识别「当前页面是评阅预览 iframe」:不依赖 reviewPreviewKey 是否还能解析出
* 有效上下文。key 同步一旦失效,取作答/只读守卫仍能凭路由特征兜住,绝不真发请求。
*/
export function isReviewPreviewHost() {
if (typeof window === "undefined") return false;
return String(window.location.hash || "").includes("task-review-preview");
}
export function isTrainingReviewPreviewRequest(config = {}) {
const method = String(config.method || "get").toLowerCase();
const url = String(config.url || "").split("?")[0];
const inPreview = Boolean(getTrainingReviewPreviewKey()) || isReviewPreviewHost();
return inPreview
return Boolean(getTrainingReviewPreviewKey())
&& ["post", "put", "patch", "delete"].includes(method)
&& (url.startsWith("/api/student-training-answers/")
|| url.startsWith("/api/student/project-study-time/")

@ -758,7 +758,7 @@ const onClick = (type, idx) => {
inputMessage.value = type.com
}
}
currentNode.value = type //记录步骤节点
currentNode.value = type //记录当前步骤节点
scrollToElement(type.name)
}
const changeTab = (type) => {

@ -1,61 +0,0 @@
export const CATEGORY_EXCEL_COLUMNS = [
{ key: "categoryName", label: "品类名称" },
{ key: "revenue", label: "近12个月营收(万元)" },
{ key: "revenueShare", label: "营收占比(%)" },
{ key: "cumulativeShare", label: "累计占比(%)" },
{ key: "inventoryCapital", label: "库存资金占用(万元)" },
{ key: "capitalOccupancyRate", label: "资金占用率(%)" },
{ key: "sellThroughRate", label: "近30天动销率(%)" },
{ key: "grossMargin", label: "毛利率(%)" },
];
const boundedRates = new Set(["capitalOccupancyRate", "sellThroughRate"]);
export function sanitizeCategoryNumber(value, key) {
let text = String(value ?? "").replace(/[^0-9.]/g, "");
const dot = text.indexOf(".");
if (dot >= 0) text = text.slice(0, dot + 1) + text.slice(dot + 1).replace(/\./g, "");
if (text.startsWith(".")) text = "0" + text;
if (boundedRates.has(key) && text) {
if (Number(text) > 100) return "100";
if (dot >= 0) {
const [whole, fraction] = text.split(".");
text = whole + "." + fraction.slice(0, 2);
}
}
return text;
}
const headerName = (value) => String(value ?? "").replace(/[((][^))]*[))]/g, "").replace(/[\s%]/g, "");
const hasValue = (row) => Array.isArray(row) && row.some((value) => String(value ?? "").trim());
export function parseCategoryExcelRows(sheetRows, maxRows = 30) {
const headerIndex = sheetRows.findIndex(hasValue);
if (headerIndex < 0) throw new Error("Excel 中没有数据,请按模板填写后导入");
const headers = sheetRows[headerIndex].map(headerName);
const indexes = CATEGORY_EXCEL_COLUMNS.map((column) => headers.indexOf(headerName(column.label)));
const missing = CATEGORY_EXCEL_COLUMNS.filter((column, index) => index < 2 && indexes[index] < 0);
if (missing.length) throw new Error("Excel 缺少表头:" + missing.map((column) => column.label).join("、"));
for (const column of CATEGORY_EXCEL_COLUMNS) {
if (headers.filter((name) => name === headerName(column.label)).length > 1) {
throw new Error("Excel 表头重复:" + column.label);
}
}
const rows = sheetRows.slice(headerIndex + 1).map((values, index) => ({ values, line: headerIndex + index + 2 })).filter((row) => hasValue(row.values));
if (!rows.length) throw new Error("Excel 只有表头,没有可导入的品类数据");
if (rows.length > maxRows) throw new Error(`品类数据最多导入 ${maxRows} 行,当前文件有 ${rows.length} 行`);
return rows.map(({ values, line }) => Object.fromEntries(CATEGORY_EXCEL_COLUMNS.map((column, index) => {
let value = String(indexes[index] < 0 ? "" : values[indexes[index]] ?? "").trim();
if (column.key === "categoryName") {
if (!value) throw new Error(`Excel 第 ${line} 行:请填写品类名称`);
return [column.key, value];
}
if (!value) return [column.key, ""];
// sheet_to_json(raw:false) 保留 Excel 百分数的显示单位,例如 0.25 格式化为 25%。
if (!["revenue", "inventoryCapital"].includes(column.key)) value = value.replace(/%$/, "").trim();
if (/^\d{1,3}(,\d{3})+(\.\d+)?$/.test(value)) value = value.replace(/,/g, "");
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value)) throw new Error(`Excel 第 ${line} 行「${column.label}」只接受数字和小数点`);
if (boundedRates.has(column.key) && Number(value) > 100) throw new Error(`Excel 第 ${line} 行「${column.label}」不能超过 100`);
return [column.key, sanitizeCategoryNumber(value, column.key)];
})));
}

@ -35,7 +35,6 @@
"0") }}</span><span class="step-copy"><b class="step-name">{{ step }}</b></span></button><span
v-if="index < trainingSteps.length - 1" class="step-connector"
aria-hidden="true" /></template></nav>
<TrainingExcelTools v-if="currentStep !== 1" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<template v-if="currentStep === 1">
<header class="step-heading">
@ -55,9 +54,6 @@
<span>链路节点和行业均值固定,中间渠道可按案例数据增加或删除。</span>
<button type="button" class="table-button" @click="addFunnelChannel">增加渠道</button>
</div>
<TrainingExcelTools :tables="numericExcelTables.filter(table => table.id === 'funnel')"
:context-key="currentStep" :disabled="saving" />
<div class="table-wrap">
<table class="funnel-table">
<thead>
@ -130,9 +126,6 @@
@click="addAnomalyRow">增加一行</button><button type="button" class="table-button ghost"
:disabled="anomalyRows.length <= 1" @click="removeAnomalyRow">删除一行</button></div>
</div>
<TrainingExcelTools :tables="numericExcelTables.filter(table => table.id === 'anomaly')"
:context-key="currentStep" :disabled="saving" />
<div class="table-wrap">
<table class="diagnosis-table">
<thead>
@ -379,10 +372,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, DataAnalysis } from "@element-plus/icons-vue"
import * as echarts from "echarts"
@ -494,7 +483,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(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 } }
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 } }
@ -631,16 +620,6 @@ function restore(answer) {
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() })
const numericExcelTables = excelComputed(() => {
if (currentStep.value === 1) return [
et('funnel', '全链路转化率', conversionRates.value, [fc('linkNode', '链路节点'), ...channels.value.map((c,i) => rc(c.id, (c.name.trim() || ('渠道' + (i+1))) + '转化率(%)', {precision: 2, get: r => r.channelRates[c.id], set: (r,v) => {r.channelRates[c.id] = v;}})), rc('industryAverage', '行业平均值(%)', {precision: 2})]),
et('anomaly', '异常节点诊断', anomalyRows.value, [tc('channel', '渠道', {values: availableChannels.value.map(c => c.name.trim()), get: r => availableChannels.value.find(c => c.id === r.channelId)?.name.trim() || '', set: (r,v) => {r.channelId = availableChannels.value.find(c => c.name.trim() === v)?.id || ''; r.channel = v;}}), tc('linkNode', '链路节点', {values: nodes}), rc('storeConversionRate', '本店转化率(%)', {precision: 2}), rc('industryAverageConversionRate', '行业转化率(%)', {precision: 2}), tc('anomalyAnalysis', '异常分析', {maxLength: 300})])
];
if (currentStep.value === 3) return [et('ab', 'AB测试对照数据', abRows.value, [fc('metric', '指标'), rc('controlValue', '对照组(%)', {precision: 2}), rc('experimentValue', '实验组(%)', {precision: 2}), tc('analysis', '判定与分析', {maxLength: 300})])];
return [];
});
</script>
<style scoped lang="scss">
@ -1734,7 +1713,7 @@ button.is-disabled {
}
}
/* 步骤:教育蓝实底 */
/* 当前步骤:教育蓝实底 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -59,8 +59,6 @@
<TrainingTaskToolbar task-key="product-diagnosis-iteration" />
</div>
<div class="training-step-area">
<TrainingExcelTools :tables="numericExcelTables" />
<p>功效系数法:绩效评估的标准化工具‌,将各指标数据通过标准化处理消除量纲差异,转化为“功效值”后加权计算综合得分,适用于多维度绩效评估‌,可用于分析电商产品表现。</p>
<div class="caseBacktitle">
@ -199,10 +197,6 @@
</div>
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import TrainingLegacyActions from "@/views/components/TrainingLegacyActions.vue";
@ -434,11 +428,6 @@ const getTask = () => {
onMounted(() => {
getTask();
});
const numericExcelTables = excelComputed(() => {
return [et('efficacy', '功效值计算', efficacyResults.value, [fc('indicator', '指标'), nc('efficacyValue', '功效值', {min: null, string: true})]), et('weights', '功效系数权重与得分', data.value, [fc('indicator', '指标'), rc('currentWeight', '权重设置(%)', {string: true, get: r => parsePercentage(r.currentWeight) * 100, set: (r,v) => {r.currentWeight = v === '' ? '' : v + '%';}}), nc('efficacyScore', '功效得分', {min: null, string: true})])];
return [];
});
</script>
<style lang='scss' scoped>
.index {

@ -49,12 +49,6 @@
<div class="table-toolbar">
<span>已填写 {{ categoryRows.length }} / 30 行</span>
<div>
<input ref="categoryExcelInput" class="file-input" type="file" accept=".xlsx,.xls"
@change="importCategoryExcel" />
<button type="button" class="action-button" :disabled="importingCategories"
@click="downloadCategoryTemplate">下载导入模板</button>
<button type="button" class="action-button" :disabled="importingCategories"
@click="categoryExcelInput?.click()">{{ importingCategories ? "导入中…" : "导入 Excel" }}</button>
<button type="button" class="action-button" :disabled="categoryRows.length >= MAX_ROWS"
@click="addRow"><el-icon>
<Plus />
@ -77,27 +71,29 @@
<th>库存资金占用(万元)</th>
<th>资金占用率(%)</th>
<th>近30天动销率(%)</th>
<th>毛利率(%)</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>
<td><el-input :model-value="row.revenue" @update:model-value="row.revenue = sanitizeCategoryNumber($event, 'revenue')" inputmode="decimal"
<td><el-input v-model="row.revenue" inputmode="decimal"
:aria-label="`第${index + 1}行近12个月营收`" />
</td>
<td><el-input :model-value="row.revenueShare" @update:model-value="row.revenueShare = sanitizeCategoryNumber($event, 'revenueShare')" inputmode="decimal"
<td><el-input v-model="row.revenueShare" inputmode="decimal"
:aria-label="`第${index + 1}行营收占比`" />
</td>
<td><el-input :model-value="row.cumulativeShare" @update:model-value="row.cumulativeShare = sanitizeCategoryNumber($event, 'cumulativeShare')" inputmode="decimal"
<td><el-input v-model="row.cumulativeShare" inputmode="decimal"
:aria-label="`第${index + 1}行累计占比`" /></td>
<td><el-input :model-value="row.inventoryCapital" @update:model-value="row.inventoryCapital = sanitizeCategoryNumber($event, 'inventoryCapital')" inputmode="decimal"
<td><el-input v-model="row.inventoryCapital" inputmode="decimal"
:aria-label="`第${index + 1}行库存资金占用`" /></td>
<td><el-input :model-value="row.capitalOccupancyRate" @update:model-value="row.capitalOccupancyRate = sanitizeCategoryNumber($event, 'capitalOccupancyRate')" inputmode="decimal"
<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 :model-value="row.sellThroughRate" @update:model-value="row.sellThroughRate = sanitizeCategoryNumber($event, 'sellThroughRate')" inputmode="decimal"
<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 :model-value="row.grossMargin" @update:model-value="row.grossMargin = sanitizeCategoryNumber($event, 'grossMargin')" inputmode="decimal"
<td><el-input v-model="row.grossMargin" inputmode="decimal"
:aria-label="`第${index + 1}行毛利率`" />
</td>
</tr>
@ -110,8 +106,7 @@
<div class="rule-notice">
<strong>填写与校验说明</strong>
<p>可手动填写或导入 Excel,最多30行。导入首个工作表,按表头对应列;品类名称、近12个月营收为必需列,其余列可留空。导入后请保存进度。</p>
<p>数值框只接受数字和小数点,其他字符会自动忽略;资金占用率、近30天动销率仍限定为0–100,最多两位小数。</p>
<p>默认无数据,学生自行根据案例资料增加行填写数据,最多30行。</p>
<p>近12个月营收须从高到低排列;营收占比 = 当前行近12个月营收 ÷ 所有品类营收之和;累计占比 = 从第一行到当前行的营收占比之和。三项逻辑不符时将提示,且不能进入下一步或提交任务。
</p>
</div>
@ -373,8 +368,7 @@
<script setup>
import { computed, defineAsyncComponent, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, Delete, Minus, Plus, TrendCharts, UploadFilled } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { CATEGORY_EXCEL_COLUMNS, parseCategoryExcelRows, sanitizeCategoryNumber } from "./categoryOptimizationExcel"
import { ElMessage } from "element-plus"
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
import TrainingTaskToolbar from "@/views/components/TrainingTaskToolbar.vue"
import { getTrainingTaskByKey } from "@/api/trainingTask"
@ -392,8 +386,6 @@ const saving = ref(false)
const workspaceKey = ref(0)
const businessComponent = ref(null)
const categoryRows = ref([])
const categoryExcelInput = ref(null)
const importingCategories = ref(false)
const paretoInput = ref(null)
const uploadingPareto = ref(false)
const paretoImage = ref({ url: "", name: "" })
@ -449,42 +441,6 @@ function applyStepFourProgress(value) { stepFour.value = createStepFour(value) }
function applyStepFiveProgress(value) { strategyRows.value = createStrategyRows(value?.rows) }
async function persistProgress(saveAction = "SAVE") { dynamicStepAnswers.value = { ...dynamicStepAnswers.value, step5: buildStepFiveProgress() }; await saveStudentTrainingAnswer(TASK_KEY, { saveAction, currentStep: activeStep.value, submitted: saveAction === "SUBMIT", step1Answer: JSON.stringify(buildProgress()), step2Answer: JSON.stringify(buildStepTwoProgress()), step3Answer: JSON.stringify(buildStepThreeProgress()), step4Answer: JSON.stringify(buildStepFourProgress()), dynamicStepAnswers: JSON.stringify(dynamicStepAnswers.value) }) }
function addRow() { if (categoryRows.value.length >= MAX_ROWS) return; categoryRows.value.push(createRow()) }
async function downloadCategoryTemplate() {
const XLSX = await import("xlsx")
const workbook = XLSX.utils.book_new()
const sheet = XLSX.utils.aoa_to_sheet([CATEGORY_EXCEL_COLUMNS.map((column) => column.label)])
sheet["!cols"] = CATEGORY_EXCEL_COLUMNS.map(() => ({ wch: 24 }))
XLSX.utils.book_append_sheet(workbook, sheet, "品类营收数据")
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([
["填写说明"], ["首行为表头,最多30行数据;品类名称和近12个月营收为必需列,其余列可留空。"],
["营收占比等百分数填写25表示25%,也支持Excel百分比格式。"],
["营收须降序排列,占比、累计占比请自行计算,导入不会自动排序或计算。"],
["数值列不接受文字或负数。资金占用率和近30天动销率范围为0–100,最多两位小数。"],
["导入会覆盖当前第一步表格,已有内容时会提示确认;导入后请保存进度。"],
]), "填写说明")
XLSX.writeFile(workbook, "品类结构优化-第一步导入模板.xlsx")
}
async function importCategoryExcel(event) {
const file = event?.target?.files?.[0]
if (event?.target) event.target.value = ""
if (!file || importingCategories.value) return
if (!/\.(xlsx|xls)$/i.test(file.name)) { ElMessage.error("请选择 .xlsx 或 .xls 格式的 Excel 文件"); return }
importingCategories.value = true
try {
const XLSX = await import("xlsx")
const workbook = XLSX.read(await file.arrayBuffer(), { type: "array" })
const sheet = workbook.Sheets[workbook.SheetNames[0]]
if (!sheet) throw new Error("Excel 中没有可导入的工作表")
const rows = parseCategoryExcelRows(XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "", raw: false, blankrows: true }), MAX_ROWS)
if (categoryRows.value.length) {
const confirmed = await ElMessageBox.confirm(`导入将覆盖当前第一步的 ${categoryRows.value.length} 行数据,是否继续?`, "导入 Excel", { type: "warning", confirmButtonText: "覆盖并导入", cancelButtonText: "取消" }).then(() => true).catch(() => false)
if (!confirmed) return
}
categoryRows.value = rows.map(createRow)
ElMessage.success(`已导入 ${rows.length} 行品类数据,请保存进度`)
} catch (error) { ElMessage.error(error?.message || "Excel 导入失败,请检查文件和表头") }
finally { importingCategories.value = false }
}
function removeLastRow() { categoryRows.value.pop() }
async function validateStepOne() {
if (!categoryRows.value.length) {
@ -1632,7 +1588,7 @@ button:disabled {
}
}
/* 步骤:教育蓝实底 */
/* 当前步骤:教育蓝实底 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -36,8 +36,6 @@
v-if="index < configuredSteps.length - 1" class="step-connector"
aria-hidden="true"></span></template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="activeStep" :disabled="saving" />
<section v-show="isSectionVisible(1)" class="step-card">
<div class="step-title-row">
<div>
@ -205,10 +203,6 @@
</div>
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
@ -869,14 +863,6 @@ onMounted(async () => {
await echoData()
await loadSavedProgress()
})
const numericExcelTables = excelComputed(() => {
if (activeStep.value === 1) return [et('forecast', '线性回归需求预测', linearForecastRows.value, [fc('label', '预测月份'), nc('demand', '预测销量(台)', {precision: 0})])];
if (activeStep.value === 3) return [et('procurement', '月度采购计划', procurementPlanRows.value, [fc('label', '预测月份'), nc('safetyStock', '安全库存(台)', {precision: 0}), nc('openingStock', '期初库存(台)', {precision: 0}), nc('purchaseQuantity', '采购量(台)', {min: null, precision: 0})])];
if (activeStep.value === 4) return [et('annual', '年度采购量预测', forecastData.value, [fc('month', '月份'), nc('forecast', '预测采购量', {string: true})])];
return [];
});
</script>
<style lang="scss" scoped>

@ -36,7 +36,6 @@
</button>
</template>
</nav>
<TrainingExcelTools v-if="currentStep !== 2" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<template v-if="currentStep === 1">
<section class="supplier-step-card">
@ -96,8 +95,6 @@
<p>试产加权总分 = Σ(评分 × 试产权重) · 量产加权总分 = Σ(评分 × 量产权重)</p>
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<div class="table-scroll">
<table class="training-table score-table merged-score-table">
<thead>
@ -267,10 +264,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, DataAnalysis, Delete, Plus } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
@ -514,7 +507,7 @@ async function saveStepOne(advance = false) {
currentStep.value = 2
ElMessage.success("权重已保存,请继续完成渠道评分")
} else {
ElMessage.success("已保存")
ElMessage.success("当前步骤已保存")
}
} catch (error) {
ElMessage.error(error?.message || "保存失败,请检查权重填写")
@ -636,13 +629,6 @@ onMounted(async () => {
loading.value = false
}
})
const numericExcelTables = excelComputed(() => {
if (currentStep.value === 1) return [et('weights', '供应渠道评估权重', rows.value, [fc('name', '评估维度'), rc('smallBatchWeight', '试产权重(%)', {precision: 0}), rc('largeBatchWeight', '量产权重(%)', {precision: 0})])];
if (currentStep.value === 2) return [et('scores', '供应渠道评分', channelRows.value, [tc('channel', '渠道', {maxLength: 40}), ...rows.value.map(d => nc(d.key, d.name, {max: 10, precision: 0, get: r => r.scores[d.key], set: (r, v) => {r.scores[d.key] = v; r.smallWeightedTotal = null; r.largeWeightedTotal = null;}}))])];
return [];
});
</script>
<style lang="scss" scoped>

@ -1,89 +0,0 @@
<template>
<el-dialog v-model="visibleProxy" title="编辑访谈记录" width="min(980px, 94vw)" append-to-body destroy-on-close class="interview-records-editor">
<div class="editor-tabs" role="tablist" aria-label="访谈记录">
<button v-for="(record, index) in draftRecords" :key="record.code || index" type="button" :class="{ active: activeIndex === index }" @click="activeIndex = index">
{{ record.code || `U0${index + 1}` }}
</button>
</div>
<div v-if="activeRecord" class="editor-body">
<div class="editor-field">
<label>用户编号</label>
<el-input :model-value="activeRecord.code" disabled />
</div>
<div class="editor-field">
<label>记录标题</label>
<el-input v-model="activeRecord.title" placeholder="例如:访谈记录一" />
</div>
<div class="editor-field">
<label>基本属性</label>
<el-input v-model="activeRecord.basicAttributes" type="textarea" :rows="2" placeholder="年龄、性别、城市、职业、收入等" />
</div>
<div class="content-heading">
<strong>访谈内容</strong>
<el-button type="primary" link @click="addQuestion">新增问答</el-button>
</div>
<div v-for="(item, index) in activeRecord.content" :key="index" class="qa-editor-row">
<div class="qa-label">Q{{ index + 1 }}</div>
<el-input v-model="item.question" placeholder="请输入访谈问题" />
<div class="qa-label answer-label">A{{ index + 1 }}</div>
<el-input v-model="item.answer" type="textarea" :rows="3" placeholder="请输入访谈回答" />
<el-button type="danger" link :disabled="activeRecord.content.length <= 1" @click="removeQuestion(index)">删除</el-button>
</div>
</div>
<el-empty v-else description="暂无访谈记录" />
<template #footer>
<el-button @click="visibleProxy = false">取消</el-button>
<el-button type="primary" @click="save">保存访谈记录</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue"
import { cloneInterviewRecords, DEFAULT_INTERVIEW_RECORDS } from "@/utils/interviewRecords"
const props = defineProps({
visible: { type: Boolean, default: false },
modelValue: { type: Array, default: () => [] },
})
const emit = defineEmits(["update:visible", "update:modelValue"])
const visibleProxy = computed({ get: () => props.visible, set: (value) => emit("update:visible", value) })
const draftRecords = ref([])
const activeIndex = ref(0)
const activeRecord = computed(() => draftRecords.value[activeIndex.value] || null)
watch(() => props.visible, (visible) => {
if (!visible) return
draftRecords.value = cloneInterviewRecords(props.modelValue?.length ? props.modelValue : DEFAULT_INTERVIEW_RECORDS)
activeIndex.value = 0
}, { immediate: true })
function addQuestion() {
if (!activeRecord.value) return
activeRecord.value.content.push({ question: "", answer: "" })
}
function removeQuestion(index) {
if (!activeRecord.value || activeRecord.value.content.length <= 1) return
activeRecord.value.content.splice(index, 1)
}
function save() {
emit("update:modelValue", cloneInterviewRecords(draftRecords.value))
visibleProxy.value = false
}
</script>
<style scoped>
.editor-tabs { display: flex; gap: 10px; padding-bottom: 14px; border-bottom: 1px solid #e8edf5; }
.editor-tabs button { min-width: 66px; padding: 7px 16px; border: 1px solid #d9e1ee; border-radius: 7px; background: #fff; color: #52627a; cursor: pointer; font-weight: 600; }
.editor-tabs button.active { border-color: #2563eb; background: #2563eb; color: #fff; }
.editor-body { max-height: min(62vh, 650px); overflow: auto; padding: 20px 4px 4px; }
.editor-field { margin-bottom: 16px; }
.editor-field label { display: block; margin-bottom: 7px; color: #25344d; font-size: 13px; font-weight: 600; }
.content-heading { display: flex; align-items: center; justify-content: space-between; margin: 22px 0 10px; color: #25344d; }
.qa-editor-row { display: grid; grid-template-columns: 34px minmax(0, 1fr) 34px minmax(0, 1.3fr) auto; gap: 8px; align-items: start; margin-bottom: 12px; padding: 12px; border: 1px solid #e8edf5; border-radius: 8px; background: #f8fbff; }
.qa-label { padding-top: 8px; color: #2563eb; font-size: 12px; font-weight: 700; }
.answer-label { color: #16a36a; }
@media (max-width: 760px) { .qa-editor-row { grid-template-columns: 30px minmax(0, 1fr); } .qa-editor-row .answer-label { grid-column: 1; } .qa-editor-row .el-button { grid-column: 2; justify-self: end; } }
</style>

@ -153,10 +153,6 @@ async function requestAssessment() {
const res = await requestAiTrainingAssessment(props.taskKey);
applyOperationResult("assessment", res?.data);
await loadEvaluation();
for (let attempt = 0; attempt < 80 && assessmentStatus.value === "PROCESSING"; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 1500));
await loadEvaluation();
}
} catch (error) {
setLocalStatus("assessment", "FAILED");
assessmentError.value = friendlyAiEvaluationMessage(error, "AI助评请求失败,可重试。");

@ -389,10 +389,6 @@ async function requestEvaluation() {
try {
await requestAiTrainingAssessment(currentTaskKey.value);
await loadEvaluation();
for (let attempt = 0; attempt < 80 && evaluation.value?.assessmentStatus === "PROCESSING"; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 1500));
await loadEvaluation();
}
internalScoreVisible.value = reports.value.score !== null;
internalScore.value = reports.value.score ?? "--";
internalEvalMessage.value = reports.value.assessmentSummary || "AI 评分已生成,请查看评分明细与改进建议。";

@ -1,82 +0,0 @@
<template>
<div v-if="tables.length" class="training-excel-tools">
<el-select v-if="tables.length > 1" v-model="selectedId" :disabled="busy || disabled" aria-label="选择要导入的表格">
<el-option v-for="table in tables" :key="table.id" :label="table.title" :value="table.id" />
</el-select>
<span v-else class="excel-table-title">{{ activeTable?.title }}</span>
<el-button :disabled="busy || disabled || !activeTable" @click="downloadTemplate">下载 Excel 模板</el-button>
<el-button type="primary" :disabled="busy || disabled || !activeTable" @click="fileInput?.click()">{{ busy ? '处理中…' : '导入 Excel' }}</el-button>
<input ref="fileInput" hidden type="file" accept=".xls,.xlsx" @change="importFile" />
<small>按序号填入对应行;导入后请保存本步骤。</small>
</div>
</template>
<script setup>
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { importTableFile, templateRows } from '@/views/training/numericTableExcel.mjs';
const props = defineProps({ tables: { type: Array, default: () => [] }, contextKey: { type: [String, Number], default: '' }, disabled: Boolean });
const selectedId = ref('');
const fileInput = ref(null);
const busy = ref(false);
let mounted = true;
onBeforeUnmount(() => { mounted = false; });
const activeTable = computed(() => props.tables.find((table) => table.id === selectedId.value) || props.tables[0]);
watch(() => [props.contextKey, ...props.tables.map((table) => table.id)], () => { selectedId.value = activeTable.value?.id || ''; }, { immediate: true });
async function downloadTemplate() {
const table = activeTable.value;
if (!table || props.disabled || busy.value) return;
busy.value = true;
try {
const XLSX = await import('xlsx');
const workbook = XLSX.utils.book_new();
const sheet = XLSX.utils.aoa_to_sheet(templateRows(table));
sheet['!cols'] = [{ wch: 8 }, ...table.columns.map(() => ({ wch: 26 }))];
XLSX.utils.book_append_sheet(workbook, sheet, '填写数据');
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([
['填写说明'], ['请在首个工作表填写,保留表头和序号;支持调整列顺序和行顺序。'],
['数值留空不提供示例答案;百分比按 25 或 25% 填写(均表示 25%)。'],
['导入行的空白数值会清空输入;未导入的行不变。总计和系统计算字段不导入。'],
...table.columns.map((column) => [column.label, column.readonly ? '与当前页面保持一致' : column.type === 'number' ? `${column.min != null ? `最小 ${column.min};` : ''}${column.max != null ? `最大 ${column.max};` : ''}${column.precision != null ? `最多 ${column.precision} 位小数` : '数字或小数'}` : column.values?.join('、') || '填写文本']),
]), '填写说明');
XLSX.writeFile(workbook, `${table.title}-导入模板.xlsx`);
} catch (error) { ElMessage.error(error?.message || '模板下载失败'); }
finally { busy.value = false; }
}
async function importFile(event) {
const file = event.target?.files?.[0];
event.target.value = '';
const table = activeTable.value;
if (!file || !table || props.disabled || busy.value) return;
const context = props.contextKey;
const columns = JSON.stringify(table.columns);
busy.value = true;
try {
const count = await importTableFile(file, { ...table, apply: (next) => activeTable.value.apply(next) }, {
readWorkbook: async (source) => {
const XLSX = await import('xlsx');
const workbook = XLSX.read(await source.arrayBuffer(), { type: 'array' });
if (!workbook.SheetNames.length) throw new Error('Excel 中没有工作表');
const sheet = workbook.Sheets[workbook.SheetNames[0]];
if (XLSX.utils.decode_range(sheet['!ref'] || 'A1').e.r > 10000) throw new Error('工作表行数过多,请仅保留需要导入的数据');
return XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false, defval: '', blankrows: true, range: 0 });
},
confirm: (message) => ElMessageBox.confirm(message, '确认导入', { type: 'warning', confirmButtonText: '导入', cancelButtonText: '取消' }),
isCurrent: () => mounted && !props.disabled && props.contextKey === context && activeTable.value?.id === table.id && JSON.stringify(activeTable.value.columns) === columns && JSON.stringify(activeTable.value.rows) === JSON.stringify(table.rows),
});
ElMessage.success(`已导入 ${count} 行,请保存本步骤`);
} catch (error) {
if (error !== 'cancel' && error !== 'close') ElMessage.error(error?.message || '导入失败,请检查 Excel 文件');
} finally { busy.value = false; }
}
</script>
<style scoped>
.training-excel-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 14px 0; }
.training-excel-tools :deep(.el-select) { width: 270px; max-width: 100%; }
.training-excel-tools .el-button + .el-button { margin-left: 0; }
.excel-table-title { color: inherit; font-weight: 600; }
.training-excel-tools small { color: #718096; }
</style>

@ -10,12 +10,9 @@
:ai-manual-name="resolvedAiManual.name"
:ai-manual-url="resolvedAiManual.url"
/>
<!-- 成绩展示:无成绩不显示;有老师评分优先显示老师评分,否则显示 AI 评分;有 AI 评分时点击可查看 AI 评分详情 -->
<!-- 成绩展示:无成绩不显示;有老师评分优先显示老师评分,否则显示 AI 评分 -->
<template v-if="scoreVisible">
<button v-if="displayScore !== null && hasAiScore" type="button" class="task-toolbar-score" :title="scoreBadgeTitle" @click="openAiEvaluationDialog">
{{ displayScore }}<small>分</small>
</button>
<span v-else-if="displayScore !== null" class="task-toolbar-score" :title="scoreBadgeTitle">
<span v-if="displayScore !== null" class="task-toolbar-score" :title="scoreBadgeTitle">
{{ displayScore }}<small>分</small>
</span>
<el-button class="task-toolbar-button" @click="openScoreDialog">
@ -38,76 +35,38 @@
</el-button>
</div>
<!-- 成绩弹窗:成绩、评语和参考答案(老师推送后展示) -->
<el-dialog v-model="scoreDialogVisible" title="实训成绩"
:width="referenceAnswerPushed ? 'min(1280px, calc(100vw - 48px))' : 'min(760px, calc(100vw - 32px))'"
top="4vh" append-to-body class="task-score-dialog"
:class="{ 'task-score-dialog--with-reference': referenceAnswerPushed }" @open="onScoreDialogOpen">
<div class="task-score-body" :class="{ 'task-score-body--with-reference': referenceAnswerPushed && hasScoreData }">
<div v-if="hasScoreData" class="task-score-summary">
<section v-if="hasTeacherScore || hasAiScore" class="task-score-cards">
<div v-if="hasTeacherScore" class="task-score-card task-score-card--teacher">
<p class="task-score-card__label">老师评分</p>
<p class="task-score-card__value">{{ formatScoreValue(teacherScore) }}<small>分</small></p>
<p v-if="teacherScoredAt" class="task-score-card__time">{{ formatScoreTime(teacherScoredAt) }}</p>
</div>
<div v-if="hasAiScore" class="task-score-card task-score-card--ai">
<p class="task-score-card__label">AI 评分</p>
<p class="task-score-card__value">{{ formatScoreValue(aiScore) }}<small>分</small></p>
</div>
</section>
<section v-if="teacherComment" class="task-score-block">
<p class="task-score-block__label">老师评语</p>
<p class="task-score-block__text">{{ teacherComment }}</p>
</section>
</div>
<section v-if="referenceAnswerPushed" class="task-score-block task-score-block--reference">
<!-- 成绩弹窗:成绩 / 评语 / 参考答案,有则展示无则隐藏 -->
<el-dialog v-model="scoreDialogVisible" title="实训成绩" width="560px" append-to-body class="task-score-dialog">
<div class="task-score-body">
<section v-if="hasTeacherScore || hasAiScore" class="task-score-cards">
<div v-if="hasTeacherScore" class="task-score-card task-score-card--teacher">
<p class="task-score-card__label">老师评分</p>
<p class="task-score-card__value">{{ formatScoreValue(teacherScore) }}<small>分</small></p>
<p v-if="teacherScoredAt" class="task-score-card__time">{{ formatScoreTime(teacherScoredAt) }}</p>
</div>
<div v-if="hasAiScore" class="task-score-card task-score-card--ai">
<p class="task-score-card__label">AI 评分</p>
<p class="task-score-card__value">{{ formatScoreValue(aiScore) }}<small>分</small></p>
</div>
</section>
<section v-if="teacherComment" class="task-score-block">
<p class="task-score-block__label">老师评语</p>
<p class="task-score-block__text">{{ teacherComment }}</p>
</section>
<section v-if="referenceAnswer" class="task-score-block">
<p class="task-score-block__label">参考答案</p>
<p class="task-score-block__text task-score-reference-name">{{ loadedTask?.referenceAnswerName || "参考答案" }}</p>
<iframe v-if="referenceAnswerPdfUrl" :src="referenceAnswerPdfUrl" class="reference-answer-frame reference-answer-frame--inline" title="参考答案预览" />
<p v-else-if="referenceAnswerLoading" class="task-score-block__text">参考答案加载中...</p>
<p class="task-score-block__text">{{ referenceAnswer }}</p>
</section>
<el-empty v-if="!hasScoreData && !referenceAnswerPushed" description="老师还没有批阅这份实训任务" :image-size="90" />
<el-empty v-if="!hasScoreData" description="老师还没有批阅这份实训任务" :image-size="90" />
</div>
</el-dialog>
<!-- AI 评分结果:悬浮在页面上(非弹窗) -->
<transition name="ai-eval-pop">
<div v-if="aiEvaluationFloatVisible" class="ai-evaluation-float">
<div class="ai-evaluation-float__header">
<span class="ai-evaluation-float__title">AI评分结果</span>
<button type="button" class="ai-evaluation-float__close" @click="aiEvaluationFloatVisible = false">
<el-icon><Close /></el-icon>
</button>
</div>
<div class="ai-evaluation-float__summary">
<span class="ai-evaluation-float__label">综合评分</span>
<span class="ai-evaluation-float__score">{{ formatScoreValue(aiEvaluationScore) }}<small>/100</small></span>
</div>
<p v-if="aiEvaluationComment" class="ai-evaluation-float__comment">{{ aiEvaluationComment }}</p>
<div v-for="(criterion, index) in aiEvaluationCriteria" :key="index" class="ai-evaluation-float__criterion">
<p class="ai-evaluation-float__criterion-head">
<span>{{ criterion.name }}</span>
<b>{{ criterion.score }}<i>/{{ criterion.maxScore }}</i></b>
</p>
<p class="ai-evaluation-float__text">{{ criterion.rationale }}</p>
</div>
<template v-if="aiEvaluationImprovements.length">
<p class="ai-evaluation-float__label">优先改进</p>
<ul class="ai-evaluation-float__improvements">
<li v-for="(item, index) in aiEvaluationImprovements" :key="index">{{ item }}</li>
</ul>
</template>
<el-empty v-if="!aiEvaluationComment && !aiEvaluationCriteria.length" description="暂无AI评价内容" :image-size="90" />
</div>
</transition>
</template>
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { CircleCheck, Close, Download, RefreshLeft, View } from "@element-plus/icons-vue";
import { computed, onMounted, ref, watch } from "vue";
import { CircleCheck, Download, RefreshLeft, View } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getTrainingTaskByKey, previewStudentReferenceAnswer } from "@/api/trainingTask";
import { getAiTrainingEvaluation } from "@/api/aiTrainingEvaluation";
import { getTrainingTaskByKey } from "@/api/trainingTask";
import { deleteStudentTrainingAnswer, getStudentTrainingAnswer, saveStudentTrainingAnswer } from "@/api/studentTrainingAnswer";
import { resolveTrainingTaskKey } from "@/views/training/taskKeyMap";
import TrainingMaterialButton from "@/views/components/TrainingMaterialButton.vue";
@ -146,53 +105,24 @@ const savingProgress = ref(false);
// ========== 成绩展示状态 ==========
const scoreAnswer = ref(null);
const scoreDialogVisible = ref(false);
const referenceAnswerPdfUrl = ref("");
const referenceAnswerLoading = ref(false);
const aiEvaluationFloatVisible = ref(false);
const aiEvaluationScore = ref(null);
const aiEvaluationComment = ref("");
const aiEvaluationCriteria = ref([]);
const aiEvaluationImprovements = ref([]);
// 不同接口对同一分数的命名不一致,统一兜底取值,避免换了字段名就读不到分数
const teacherScore = computed(() => pickScore(scoreAnswer.value, ["teacherScore", "teacherTotalScore"]));
const aiScore = computed(() => pickScore(scoreAnswer.value, ["aiAssessmentScore", "aiTotalScore", "aiScore", "score", "totalScore"]));
const teacherComment = computed(() => pickText(scoreAnswer.value, ["teacherComment", "teacherComments", "comment"]));
const teacherScoredAt = computed(() => String(scoreAnswer.value?.teacherScoredAt || "").trim());
// 参考答案:约定老师“开放推送”后任务配置里才携带该字段(后端字段暂未提供,预留读取,提供后自动生效)
const referenceAnswer = computed(() => String(loadedTask.value?.referenceAnswer || "").trim());
const hasTeacherScore = computed(() => teacherScore.value !== null);
const hasAiScore = computed(() => aiScore.value !== null);
const hasScoreData = computed(() => hasTeacherScore.value || hasAiScore.value || Boolean(teacherComment.value));
const scoreVisible = computed(() => hasScoreData.value);
// 工具栏入口:分数、评语、参考答案任一存在才显示
const scoreVisible = computed(() => hasScoreData.value || Boolean(referenceAnswer.value));
const displayScore = computed(() => {
if (hasTeacherScore.value) return teacherScore.value;
if (hasAiScore.value) return aiScore.value;
return null;
});
const scoreBadgeTitle = computed(() => "AI 评分,点击查看评分详情");
// 老师在任务配置里“推送”参考答案后,学生任务信息才会携带参考答案文件
const referenceAnswerPushed = computed(() => Boolean(loadedTask.value?.referenceAnswerUrl));
let referenceAnswerObjectUrl = "";
function onScoreDialogOpen() {
// 打开时重新拉取,保证教师刚评完的分/评语能及时看到。
loadScoreState();
if (referenceAnswerObjectUrl) {
URL.revokeObjectURL(referenceAnswerObjectUrl);
referenceAnswerObjectUrl = "";
}
referenceAnswerPdfUrl.value = "";
if (!referenceAnswerPushed.value) return;
referenceAnswerLoading.value = true;
previewStudentReferenceAnswer(resolvedTaskKey.value).then((response) => {
const blob = response instanceof Blob ? response : new Blob([response], { type: "application/pdf" });
referenceAnswerObjectUrl = URL.createObjectURL(blob);
// 关闭浏览器 PDF 查看器左侧缩略图导航栏,只保留正文预览。
referenceAnswerPdfUrl.value = `${referenceAnswerObjectUrl}#pagemode=none`;
}).catch(() => {
ElMessage.error("参考答案加载失败,请稍后重试");
}).finally(() => {
referenceAnswerLoading.value = false;
});
}
const scoreBadgeTitle = computed(() => (hasTeacherScore.value ? "老师评分,点击查看成绩详情" : "AI 评分,点击查看成绩详情"));
function toScoreNumber(value) {
if (value === null || value === undefined || value === "") return null;
@ -249,31 +179,6 @@ async function loadScoreState() {
}
}
async function openAiEvaluationDialog() {
if (!resolvedTaskKey.value) return;
try {
const response = await getAiTrainingEvaluation(resolvedTaskKey.value);
const data = response?.data || {};
let report = {};
try { report = data.assessmentReportJson ? JSON.parse(data.assessmentReportJson) : {}; } catch { report = {}; }
aiEvaluationScore.value = toScoreNumber(data.assessmentScore ?? report.score);
aiEvaluationComment.value = data.assessmentComment || report.overallComment || report.overallDiagnosis || "";
aiEvaluationCriteria.value = Array.isArray(report.criteria) ? report.criteria : [];
aiEvaluationImprovements.value = Array.isArray(report.improvements) ? report.improvements : [];
aiEvaluationFloatVisible.value = true;
} catch {
ElMessage.error("AI评价加载失败,请稍后重试");
}
}
// 点击悬浮卡片与分数徽标以外区域时收起
function onDocMouseDownForAiFloat(e) {
if (!aiEvaluationFloatVisible.value) return;
const target = e.target;
if (target.closest?.(".ai-evaluation-float") || target.closest?.(".task-toolbar-score")) return;
aiEvaluationFloatVisible.value = false;
}
function openScoreDialog() {
// 打开时重新拉取,保证教师刚评完的分/评语能及时看到。
loadScoreState();
@ -297,13 +202,7 @@ const resolvedAiManual = computed(() => ({
url: String(props.aiManualUrl || loadedMaterial.value.aiManualUrl || ""),
}));
onMounted(() => {
loadTaskConfig();
document.addEventListener("mousedown", onDocMouseDownForAiFloat);
});
onBeforeUnmount(() => {
document.removeEventListener("mousedown", onDocMouseDownForAiFloat);
});
onMounted(loadTaskConfig);
watch(resolvedTaskKey, loadTaskConfig);
async function loadTaskConfig() {
@ -541,118 +440,38 @@ function exportLegacyTraining() {
</script>
<style lang="scss" scoped>
.training-task-toolbar { display:flex; flex-wrap:wrap; align-items:center; justify-content:flex-end; gap:var(--student-sp-2, 8px); }
.training-task-toolbar { display:flex; flex-wrap:wrap; align-items:center; justify-content:flex-end; gap:8px; }
.training-task-toolbar :deep(.material-actions) { margin-right:auto; }
.task-toolbar-button { min-height:var(--student-action-height, 34px); height:var(--student-action-height, 34px); padding:0 var(--student-sp-3, 14px); border-color:var(--student-panel-border); border-radius:var(--student-radius-sm, 6px); color:var(--student-accent); background:var(--student-card-bg); font-size:var(--student-fs-button); font-weight:600; }
.task-toolbar-button:hover { border-color:var(--student-accent-light); color:var(--student-accent-deep); background:var(--student-accent-soft); }
.task-toolbar-button--save { border-color:rgba(43,164,113,.45); color:var(--student-success); }
.task-toolbar-button--save:hover { border-color:var(--student-success); color:#1f8f62; background:#f0fbf6; }
.task-toolbar-button--submit { border-color:var(--student-accent); color:#fff; background:var(--student-accent); }
.task-toolbar-button--submit:hover { border-color:var(--student-accent-deep); color:#fff; background:var(--student-accent-deep); }
.task-toolbar-button { min-height:34px; height:34px; padding:0 14px; border-color:rgba(37,99,235,.35); border-radius:8px; color:#2563eb; background:#fff; font-size: var(--student-fs-body); font-weight:600; }
.task-toolbar-button:hover { border-color:#2563eb; color:#1d4ed8; background:#eff6ff; }
.task-toolbar-button--save { border-color:rgba(43,164,113,.45); color:#2ba471; }
.task-toolbar-button--save:hover { border-color:#2ba471; color:#1f8f62; background:#f0fbf6; }
.task-toolbar-button--submit { border-color:#2563eb; color:#fff; background:#2563eb; }
.task-toolbar-button--submit:hover { border-color:#1d4ed8; color:#fff; background:#1d4ed8; }
@media (max-width:768px) { .training-task-toolbar { justify-content:stretch; } .training-task-toolbar > * { flex:1 1 auto; } }
/* 成绩徽标:琥珀色,区别于蓝色系工具栏按钮 */
.task-toolbar-score {
display:inline-flex; align-items:center; gap:var(--student-sp-1, 4px); height:var(--student-action-height, 34px); padding:0 var(--student-sp-3, 14px);
border-radius:var(--student-radius-sm, 6px); background:var(--student-accent-soft);
border:1px solid var(--student-accent-light); color:var(--student-accent-deep); font-weight:700; font-size:var(--student-fs-data); line-height:1;
display:inline-flex; align-items:center; gap:2px; height:34px; padding:0 12px;
border-radius:8px; background:#fff7ed;
border:1px solid rgba(180,83,9,.35); color:#b45309; font-weight:700; font-size:16px; line-height:1;
white-space:nowrap;
}
.task-toolbar-score small { font-size: var(--student-fs-body); font-weight:600; }
/* 成绩弹窗 */
.task-score-body { display:flex; flex-direction:column; gap:var(--student-sp-4, 16px); }
.task-score-summary { display:flex; flex-direction:column; gap:var(--student-sp-4, 16px); min-width:0; min-height:0; }
.task-score-body--with-reference { display:grid; grid-template-columns:260px minmax(0, 1fr); align-items:stretch; }
.task-score-body--with-reference .task-score-summary { overflow-y:auto; }
.task-score-body--with-reference .task-score-cards { flex-direction:column; }
.task-score-cards { display:flex; gap:var(--student-sp-3, 12px); }
.task-score-card { flex:1; min-width:0; border-radius:var(--student-radius-sm, 6px); padding:var(--student-sp-3, 12px) var(--student-sp-4, 16px); border:1px solid var(--student-panel-border); background:var(--student-panel-bg); }
.task-score-card--teacher { background:var(--student-accent-soft); border-color:var(--student-accent-light); }
.task-score-card--ai { background:#f0fbf6; border-color:var(--student-success); }
.task-score-card__label { margin:0 0 var(--student-sp-1, 4px); font-size:var(--student-fs-caption); color:var(--student-text-secondary); }
.task-score-card__value { margin:0; font-size:28px; font-weight:700; line-height:1.2; font-family:var(--student-font-data); }
.task-score-card--teacher .task-score-card__value { color:var(--student-accent-deep); }
.task-score-card--ai .task-score-card__value { color:var(--student-success); }
.task-score-card__value small { font-size:var(--student-fs-caption); font-weight:500; margin-left:2px; color:var(--student-text-secondary); }
.task-score-card__time { margin:var(--student-sp-2, 8px) 0 0; font-size:var(--student-fs-caption); color:var(--student-text-secondary); }
.task-score-block { border-radius:var(--student-radius-sm, 6px); border:1px solid var(--student-panel-border); background:var(--student-panel-bg); padding:var(--student-sp-3, 12px) var(--student-sp-4, 16px); }
.task-score-block__label { margin:0 0 var(--student-sp-1, 4px); font-size:var(--student-fs-caption); font-weight:600; color:var(--student-text-secondary); }
.task-score-block__text { margin:0; font-size:var(--student-fs-body); line-height:1.7; color:var(--student-text); white-space:pre-wrap; word-break:break-word; }
.task-score-block--reference { display:flex; flex:1; flex-direction:column; min-width:0; min-height:0; }
.task-score-reference-name { margin-bottom:12px; color:var(--student-text-secondary); overflow-wrap:anywhere; }
.reference-answer-frame { display:block; flex:1; width:100%; height:100%; min-height:0; box-sizing:border-box; border:1px solid var(--student-panel-border); border-radius:var(--student-radius-sm, 6px); background:var(--student-card-bg); }
@media (max-width:960px) {
.task-score-body--with-reference { display:flex; }
.task-score-body--with-reference .task-score-summary { overflow-y:visible; }
.task-score-body--with-reference .task-score-cards { flex-direction:row; }
.task-score-block--reference { flex:none; min-height:0; }
.reference-answer-frame { flex:none; height:60vh; min-height:240px; }
}
@media (max-width:640px) { .task-score-cards, .task-score-body--with-reference .task-score-cards { flex-direction:column; } }
/* AI 评分结果悬浮卡片(悬浮在页面上,非弹窗) */
.ai-evaluation-float { position:fixed; top:132px; right:28px; z-index:1800; width:380px; max-height:calc(100vh - 200px); overflow-y:auto; padding:16px; background:var(--student-card-bg, #ffffff); border:1px solid var(--student-panel-border); border-radius:12px; box-shadow:0 12px 32px rgba(15,23,42,.18); }
.ai-evaluation-float__header { display:flex; align-items:center; justify-content:space-between; margin-bottom:10px; }
.ai-evaluation-float__title { font-size:var(--student-fs-body, 14px); font-weight:700; color:var(--student-text, #1f2937); }
.ai-evaluation-float__close { display:inline-flex; align-items:center; justify-content:center; padding:4px; color:var(--student-text-secondary); background:transparent; border:0; border-radius:6px; cursor:pointer; }
.ai-evaluation-float__close:hover { color:var(--student-text, #1f2937); background:var(--student-panel-bg, #f3f4f6); }
.ai-evaluation-float__summary { display:flex; align-items:flex-end; justify-content:space-between; padding:12px 14px; border:1px solid var(--student-accent-light, rgba(37,99,235,.15)); border-left:4px solid var(--student-accent, #2563eb); border-radius:8px; background:var(--student-accent-soft, #eff6ff); }
.ai-evaluation-float__label { margin:0 0 4px; font-size:var(--student-fs-caption, 12px); font-weight:600; color:var(--student-text-secondary); }
.ai-evaluation-float__score { font-size:26px; font-weight:700; line-height:1.1; color:var(--student-accent-deep, #2563eb); font-family:var(--student-font-data); }
.ai-evaluation-float__score small { font-size:var(--student-fs-caption, 12px); font-weight:500; margin-left:2px; color:var(--student-text-secondary); }
.ai-evaluation-float__comment { margin:10px 0 0; font-size:var(--student-fs-body, 14px); line-height:1.7; color:var(--student-text, #1f2937); }
.ai-evaluation-float__criterion { margin-top:12px; padding:10px 12px; border:1px solid var(--student-panel-border); border-radius:8px; background:var(--student-panel-bg); }
.ai-evaluation-float__criterion-head { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:0; font-size:var(--student-fs-body, 14px); font-weight:600; color:var(--student-text, #1f2937); }
.ai-evaluation-float__criterion-head b { color:var(--student-success, #16a34a); font-weight:700; }
.ai-evaluation-float__criterion-head i { font-style:normal; font-weight:500; color:var(--student-text-secondary); }
.ai-evaluation-float__text { margin:6px 0 0; font-size:var(--student-fs-body-sm, 13px); line-height:1.7; color:var(--student-text-secondary, #4b5563); }
.ai-evaluation-float__improvements { margin:6px 0 0; padding-left:18px; }
.ai-evaluation-float__improvements li { margin-bottom:4px; font-size:var(--student-fs-body-sm, 13px); line-height:1.6; color:var(--student-text, #1f2937); }
.ai-eval-pop-enter-active, .ai-eval-pop-leave-active { transition:opacity .18s ease, transform .18s ease; }
.ai-eval-pop-enter-from, .ai-eval-pop-leave-to { opacity:0; transform:translateY(-6px); }
</style>
<!-- The dialog is appended to body; limit these layout rules to this dialog. -->
<style lang="scss">
.el-dialog.task-score-dialog {
display: flex;
flex-direction: column;
max-height: calc(100vh - 64px);
margin-bottom: 0;
border-radius: var(--student-radius-lg, 12px);
.el-dialog__header {
flex-shrink: 0;
margin-right: 0;
padding: 20px 48px 16px 24px;
border-bottom: 1px solid var(--student-panel-border, #e5e7eb);
}
.el-dialog__body {
display: flex;
flex: 1;
min-height: 0;
padding: 20px 24px 24px;
overflow-y: auto;
}
.task-score-body { flex: 1; min-width: 0; min-height: 0; }
&.task-score-dialog--with-reference {
height: min(820px, calc(100vh - 64px));
}
@media (max-width: 960px) {
&.task-score-dialog--with-reference { height: auto; }
.el-dialog__body { display: block; max-height: calc(100vh - 144px); }
}
@media (max-width: 640px) {
width: calc(100vw - 24px);
max-height: calc(100vh - 32px);
.el-dialog__header { padding: 16px 44px 12px 16px; }
.el-dialog__body { padding: 16px; max-height: calc(100vh - 112px); }
}
}
.task-score-body { display:flex; flex-direction:column; gap:16px; }
.task-score-cards { display:flex; gap:12px; }
.task-score-card { flex:1; border-radius:10px; padding:14px 16px; border:1px solid; }
.task-score-card--teacher { background:#eff6ff; border-color:rgba(37,99,235,.35); }
.task-score-card--ai { background:#f0fbf6; border-color:rgba(43,164,113,.35); }
.task-score-card__label { margin:0 0 4px; font-size:12px; color:#64748b; }
.task-score-card__value { margin:0; font-size:28px; font-weight:700; line-height:1.2; }
.task-score-card--teacher .task-score-card__value { color:#1d4ed8; }
.task-score-card--ai .task-score-card__value { color:#1f8f62; }
.task-score-card__value small { font-size:13px; font-weight:500; margin-left:2px; color:#64748b; }
.task-score-card__time { margin:6px 0 0; font-size:12px; color:#94a3b8; }
.task-score-block { border-radius:10px; border:1px solid rgba(100,116,139,.25); background:#f8fafc; padding:12px 16px; }
.task-score-block__label { margin:0 0 6px; font-size:12px; font-weight:600; color:#475569; }
.task-score-block__text { margin:0; font-size:14px; line-height:1.7; color:#1e293b; white-space:pre-wrap; word-break:break-word; }
</style>

@ -38,8 +38,6 @@
<span class="step-name">{{ step }}</span>
</button>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<section v-if="currentStep === 1" class="step-card">
<div class="step-heading">
@ -393,10 +391,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { ArrowLeft, ArrowRight, Check, CircleCheck, Delete, Document, Download, RefreshLeft, UploadFilled, View } from "@element-plus/icons-vue"
import { checkBusinessFeasibilityStepOne, checkBusinessFeasibilityStepTwo, checkBusinessFeasibilityStepThree, getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer"
import { getTrainingTaskByKey } from "@/api/trainingTask"
@ -478,15 +472,6 @@ function prevStep() { if (currentStep.value > 1) currentStep.value -= 1 }
async function saveCurrentProgress() { if (saving.value) return; saving.value = true; try { const step = currentStep.value; const payload = { currentStep: step, submitted: false, saveAction: "SAVE" }; if (step === 1) payload.step1Answer = JSON.stringify({ form: form.value, calculations: { unitTotalCost: totalCost.value, unitGrossProfit: unitGrossProfit.value, grossMargin: grossMargin.value } }); else if (step === 2) payload.step2Answer = JSON.stringify({ stepTwo: stepTwo.value }); else if (step === 3) payload.step3Answer = JSON.stringify({ report: report.value }); await saveStudentTrainingAnswer(TASK_KEY, payload); proxy?.$modal?.msgSuccess("已保存") } catch (error) { proxy?.$modal?.msgError?.(error?.message || "保存失败,请稍后重试") } finally { saving.value = false } }
async function nextStep() { if (currentStep.value === 1) return validateAndContinue(); if (currentStep.value === 2) return saveStepTwo(); if (currentStep.value === 3) return saveStepThree() }
function exportOutcome() { const blob = new Blob([JSON.stringify({ task: taskTitle.value, step: 1, ...payload(), calculations: { unitTotalCost: totalCost.value, unitGrossProfit: unitGrossProfit.value, grossMargin: grossMargin.value } }, null, 2)], { type: "application/json;charset=utf-8" }); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = "商业可行性论证-第1步.json"; link.click(); URL.revokeObjectURL(link.href) }
const numericExcelTables = excelComputed(() => {
if (currentStep.value === 1) return [
et('market', '商业可行性市场数据', [form.value.marketAnalysis], marketFields.filter(f => f.type === 'number').map(f => nc(f.key, f.label + '(' + f.suffix + ')', {percent: f.suffix === '%'})), {apply: next => Object.assign(form.value.marketAnalysis, next[0])}),
et('costs', '商业可行性成本结构', form.value.costs, [fc('label', '成本项目'), nc('amount', '金额(元)')])
];
return [];
});
</script>
<style lang="scss" scoped>

@ -32,7 +32,7 @@
:class="['step-tab', { active: currentStep === index + 1, complete: currentStep > index + 1 }]"
@click="switchStep(index + 1)"><span class="step-marker">{{ String(index + 1).padStart(2,
'0') }}</span><span class="step-copy"><strong>{{ step }}</strong><small>{{ currentStep
=== index + 1 ? '' : '' }} →</small></span></button><i
=== index + 1 ? '当前步骤' : '点击切换' }} →</small></span></button><i
v-if="index < trainingSteps.length - 1" class="step-connector" /></template>
</nav>
<section class="step-card">
@ -119,7 +119,7 @@
<thead>
<tr>
<th>策略类型</th>
<th>第 2 步补充信息</th>
<th>组合逻辑(自动生成)</th>
<th>具体策略建议</th>
<th>预期效果</th>
</tr>
@ -304,7 +304,7 @@ async function loadSavedAnswer() { try { const answer = (await getStudentTrainin
function restoreOutcome(value, target, field = "swot") { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; target.value = { ...createForm(), ...(parsed?.[field] || parsed || {}) }; if (field === "swot") { const structured = parsed?.choiceAnswers && typeof parsed.choiceAnswers === "object" ? parsed.choiceAnswers : null; if (structured && Object.keys(structured).length) stepOneChoiceAnswers.value = structured; else { /* 兜底:工具栏 DOM 快照 legacy-training-snapshot-v3,教师端评阅预览返回的就是这类数据 */ const legacyAnswers = parseLegacySnapshotChoiceAnswers(parsed, stepOneQuestions.value); if (legacyAnswers) stepOneChoiceAnswers.value = legacyAnswers } } } catch (error) { target.value = createForm() } }
function restoreStrategyOutcome(value) { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; const source = parsed?.strategies || parsed || {}; strategyForm.value = Object.fromEntries(strategyDefinitions.map((row) => [row.key, { ...createStrategyRow(), ...(source[row.key] || {}) }])) } catch (error) { strategyForm.value = createStrategyForm() } }
function restoreFinalOutcome(value) { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; const source = parsed?.decision || parsed || {}; const priorities = source.priorities || {}; finalForm.value = { ...createFinalForm(), ...source, priorities: Object.fromEntries(strategyDefinitions.map((row) => [row.key, { priority: null, reason: "", ...(priorities[row.key] || {}) }])) } } catch (error) { finalForm.value = createFinalForm() } }
function getCombinedLogic(row) { return [{ label: `${row.firstLabel}· `, value: supplementForm.value[row.first] }, { label: `${row.secondLabel}· `, value: supplementForm.value[row.second] }] }
function getCombinedLogic(row) { return [{ label: `${row.firstLabel}(第1步)· `, value: form.value[row.first] }, { label: `${row.firstLabel}(第2步补充)· `, value: supplementForm.value[row.first] }, { label: `${row.secondLabel}(第1步)· `, value: form.value[row.second] }, { label: `${row.secondLabel}(第2步补充)· `, value: supplementForm.value[row.second] }] }
function buildStepOneOutcome() { return { title: taskTitle.value, swot: { ...form.value }, choiceAnswers: { ...stepOneChoiceAnswers.value } } } function buildStepTwoOutcome() { return { title: taskTitle.value, supplements: { ...supplementForm.value } } } function buildStepThreeOutcome() { return { title: taskTitle.value, strategies: JSON.parse(JSON.stringify(strategyForm.value)) } } function buildStepFourOutcome() { return { title: taskTitle.value, decision: JSON.parse(JSON.stringify(finalForm.value)) } } function buildDraft() { return { step1: buildStepOneOutcome(), step2: buildStepTwoOutcome(), step3: buildStepThreeOutcome(), step4: buildStepFourOutcome(), currentStep: currentStep.value } } function getLocalDraftKey() { const info = userStore.userInfo || {}; return `${TASK_KEY}:draft:${info.userId || info.user_id || info.username || info.userName || "anonymous"}` } function persistDraft() { if (!draftReady.value) return; try { localStorage.setItem(getLocalDraftKey(), JSON.stringify(buildDraft())) } catch (error) { /* Optional browser draft. */ } } function loadDraft() { try { const raw = localStorage.getItem(getLocalDraftKey()); if (raw) { const draft = JSON.parse(raw); restoreOutcome(draft?.step1 || draft, form); restoreOutcome(draft?.step2, supplementForm, "supplements"); restoreStrategyOutcome(draft?.step3); restoreFinalOutcome(draft?.step4); if (Number(draft?.currentStep) > 0) currentStep.value = Number(draft.currentStep) } } catch (error) { clearDraft() } } function clearDraft() { try { localStorage.removeItem(getLocalDraftKey()) } catch (error) { /* Ignore storage failures. */ } }
function switchStep(step) { if (step === 2 && !stepOnePassed.value) { proxy?.$modal?.msgWarning("请先完成并保存第 1 步"); return } if (step === 3 && !stepTwoPassed.value) { proxy?.$modal?.msgWarning("请先完成并保存第 2 步"); return } if (step === 4 && !stepThreePassed.value) { proxy?.$modal?.msgWarning("请先完成并保存第 3 步"); return } currentStep.value = step }
function prevStep() { if (currentStep.value > 1) currentStep.value -= 1 }

@ -348,7 +348,7 @@
</section>
</main>
<TrainingAiSidebar study-tip="建议:先确认问卷能覆盖用户基本信息、购买行为、决策因素和未购买顾虑,再用数据分析支撑结论。" reference-title="消费者行为分析参考"
<TrainingAiSidebar study-tip="当前步骤建议:先确认问卷能覆盖用户基本信息、购买行为、决策因素和未购买顾虑,再用数据分析支撑结论。" reference-title="消费者行为分析参考"
reference-text="· 需求类型:功能需求、价格需求、服务需求、隐私安全需求<br />· 决策因素:价格、品牌、功能、质量、便捷性、售后<br />· 分析方法:分群对比、渠道分析、购买场景分析、未购买原因归因"
assist-text="报告中尽量把数据结论写成“现象 + 人群差异 + 产品启示”的结构,避免只罗列比例。" :progress-items="progressItems" />
</div>
@ -1079,7 +1079,7 @@ function exportOutcome() {
const lines = [
`任务:${taskTitle.value}`,
"",
`步骤:${flowSteps.value[form.value.activeStep] || ""}`,
`当前步骤:${flowSteps.value[form.value.activeStep] || ""}`,
"",
"问卷调查目标人群与核心假设:",
...form.value.targetHypotheses.map((item, index) => `${index + 1}. 目标人群:${item.targetGroup || ""}\n实训8关键发现:${item.keyFinding || ""}\n核心假设:${item.coreHypothesis || ""}`),

@ -35,7 +35,7 @@
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy">
<strong class="step-name" :title="step">{{ step }}</strong>
<span class="step-action">{{ form.activeStep === index + 1 ? "" : "" }} <span
<span class="step-action">{{ form.activeStep === index + 1 ? "当前步骤" : "点击切换" }} <span
aria-hidden="true">→</span></span>
</span>
</button>
@ -251,7 +251,7 @@
</section>
</main>
<TrainingAiSidebar study-tip="建议:先把文本判断到购买旅程阶段,再填写每个阶段的用户目标、行为、触点、情绪和痛点。" reference-title="消费场景解构参考"
<TrainingAiSidebar study-tip="当前步骤建议:先把文本判断到购买旅程阶段,再填写每个阶段的用户目标、行为、触点、情绪和痛点。" reference-title="消费场景解构参考"
reference-text="· 旅程阶段:问题感知、信息搜索、评估决策、购买转化、购后行为<br />· 拆解维度:用户目标、用户行为、接触点、情绪曲线、痛点/机会点<br />· 输出重点:找到情绪低点和产品可介入的关键节点"
assist-text="可让 AI 帮你把一段用户故事拆成旅程阶段,再检查每个阶段是否有明确触点和痛点。" :progress-items="progressItems" />
</div>
@ -1908,7 +1908,7 @@ function exportOutcome() {
}
}
/* 步骤 */
/* 当前步骤 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -37,7 +37,7 @@
<span class="step-marker" aria-hidden="true">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy">
<strong class="step-name" :title="step">{{ step }}</strong>
<span class="step-action">{{ currentStep === index + 1 ? '' : '' }} <span
<span class="step-action">{{ currentStep === index + 1 ? '当前步骤' : '点击切换' }} <span
aria-hidden="true">→</span></span>
</span>
</button>

@ -35,15 +35,13 @@
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy">
<strong class="step-name" :title="step">{{ step }}</strong>
<span class="step-action">{{ form.activeStep === index + 1 ? "" : "" }} <span
<span class="step-action">{{ form.activeStep === index + 1 ? "当前步骤" : "点击切换" }} <span
aria-hidden="true">→</span></span>
</span>
</button>
<span v-if="index < flowSteps.length - 1" class="step-connector" aria-hidden="true"></span>
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="form.activeStep" :disabled="saving" />
<section v-show="isSectionVisible(1)" class="step-card conversion-content">
<div v-if="activeStepName" class="step-title-row">
@ -255,10 +253,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, getCurrentInstance, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck } from "@element-plus/icons-vue"
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
@ -718,12 +712,6 @@ function exportOutcome() {
link.click()
URL.revokeObjectURL(url)
}
const numericExcelTables = excelComputed(() => {
if (form.value.activeStep === 2) return [et('rice', '需求优先级RICE评分', form.value.scoreRows, [fc('requirementId', '需求ID'), fc('name', '功能名称'), tc('kano', 'KANO属性', {values: kanoTypes}), nc('reach', 'Reach覆盖范围', {min: 1, max: 5, precision: 0}), nc('impact', 'Impact影响程度', {min: 1, max: 5, precision: 0}), rc('confidence', 'Confidence置信度(%)', {min: 1, precision: 0}), nc('effort', 'Effort人月', {min: 0.1})])];
return [];
});
</script>
<style scoped lang="scss">

@ -37,7 +37,7 @@
<span class="step-marker" aria-hidden="true">{{ String(index + 1).padStart(2, "0") }}</span>
<span class="step-copy">
<strong class="step-name" :title="step">{{ step }}</strong>
<span class="step-action">{{ currentStep === index + 1 ? "" : "" }} <span
<span class="step-action">{{ currentStep === index + 1 ? "当前步骤" : "点击切换" }} <span
aria-hidden="true">→</span></span>
</span>
</button>

@ -34,7 +34,7 @@
@click="switchStep(index + 1)">
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy"><strong class="step-name" :title="step">{{ step }}</strong><span
class="step-action">{{ currentStep === index + 1 ? '' : '' }}
class="step-action">{{ currentStep === index + 1 ? '当前步骤' : '点击切换' }}
→</span></span>
</button>
<span v-if="index < trainingSteps.length - 1" class="step-connector" />
@ -370,9 +370,9 @@ async function saveCurrentProgress(showMessage = true) {
if (currentStep.value === 2) stepTwoPassed.value = true
if (currentStep.value === 3) stepThreePassed.value = true
clearDraft()
if (showMessage) proxy?.$modal?.msgSuccess("已保存")
if (showMessage) proxy?.$modal?.msgSuccess("当前步骤已保存")
return true
} catch (error) { proxy?.$modal?.msgError?.(error?.message || "请完整填写本步骤内容"); return false } finally { saving.value = false }
} catch (error) { proxy?.$modal?.msgError?.(error?.message || "请完整填写当前步骤内容"); return false } finally { saving.value = false }
}
function previousStep() { if (currentStep.value > 1) currentStep.value -= 1 }
async function nextStep() { if (currentStep.value < trainingSteps.value.length && await saveCurrentProgress(false)) currentStep.value += 1 }

@ -342,7 +342,7 @@
</section>
</main>
<TrainingAiSidebar study-tip="建议:先上传客户画像搜索结果,再围绕用户是谁、为什么买、在哪里用、担心什么四个问题完成画像分析。" reference-title="用户画像分析参考"
<TrainingAiSidebar study-tip="当前步骤建议:先上传客户画像搜索结果,再围绕用户是谁、为什么买、在哪里用、担心什么四个问题完成画像分析。" reference-title="用户画像分析参考"
reference-text="· 基础属性:年龄、性别、地域、职业<br />· 消费特征:价格敏感度、购买渠道、品牌偏好<br />· 场景需求:家庭照明、睡眠改善、健康管理<br />· 决策阻碍:安装成本、效果可信度、售后保障"
assist-text="如果画像分析较散,可以先列出目标人群标签,再补充证据来源,最后总结最值得切入的重点用户群。" :progress-items="progressItems" />
</div>
@ -355,7 +355,6 @@ import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
import TrainingTaskToolbar from "@/views/components/TrainingTaskToolbar.vue"
import { getTrainingTaskByKey } from "@/api/trainingTask"
import { parseTrainingArray } from "@/views/training/taskKeyMap"
import { DEFAULT_INTERVIEW_RECORDS, parseInterviewRecords } from "@/utils/interviewRecords"
import { checkTargetUserProfileStepFive, checkTargetUserProfileStepFour, checkTargetUserProfileStepOne, checkTargetUserProfileStepThree, checkTargetUserProfileStepTwo, getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer"
const TASK_KEY = "target-user-profile"
@ -398,9 +397,40 @@ const defaultGoals = [
"能够形成面向产品定位和后续选品判断的用户画像结论。",
]
const interviewTranscripts = ref(DEFAULT_INTERVIEW_RECORDS)
const interviewTranscripts = [
{
code: "U01",
basicAttributes: "李伟,29岁,男性,上海,互联网公司程序员,月收入约2.8万元",
content: [
{ question: "您平时的睡眠质量如何?通常因为什么失眠?", answer: "非常差。几乎每天都熬夜,不是因为想玩,是脑子停不下来,一直在想工作上的bug和方案。即使躺下,也觉得心神不宁,入睡特别困难。有时候心脏会有点不舒服,知道是压力大和缺觉搞的。" },
{ question: "您尝试过哪些方法来改善睡眠?", answer: "买过褪黑素,吃了一段时间感觉效果不明显,而且怕有依赖。也用过一些冥想App,听着白噪音确实有点用,但手机亮着屏幕放在旁边总觉得不舒服,而且容易被消息通知打断。" },
{ question: "如果有一款智能助眠灯,您最希望它有什么功能?", answer: "首先,光一定要柔和,能让我放松下来。其次,最好能无缝衔接我用的冥想App的内容,别让我再来回切换。还有就是,我挺想知道自己每晚到底睡了多久,醒了多少次,有个数据报告会让我觉得这钱花得值。如果能在我睡着后自动关灯、调低空调温度,那就太智能了。" },
{ question: "在购买这类产品时,您最看重什么?", answer: "效果和科技感。价格不是最敏感的因素,只要它真的能帮我解决问题,我愿意为专业和便捷付费。品牌最好有点调性,别显得太廉价。" },
],
},
{
code: "U02",
basicAttributes: "赵静,31岁,女性,杭州,中学教师,月收入约1.5万元",
content: [
{ question: "您目前的睡眠状况是怎样的?", answer: "碎片化,非常碎片化。宝宝现在一岁多,夜里还是会醒。从她出生后我就没睡过一个整觉。现在问题是,即使宝宝睡了,我自己也因为长期疲劳变得神经衰弱,很难深度睡眠,有点声音就醒。" },
{ question: "在您的睡前时光,通常有什么习惯或需求?", answer: "我需要一段属于自己的缓冲时间。会看会儿手机,但知道蓝光不好。也希望有一些温和的声音能盖掉家里的其他杂音,帮助我放松。另外,夜里起床照顾宝宝,需要一盏能瞬间提供柔和、不刺眼照明的小灯,现在开大灯太晃眼了。" },
{ question: "对于智能助眠灯,您有什么期待?", answer: "操作一定要简单!我可没时间研究复杂的APP。最好能语音控制,比如我说小眠,开夜灯,它就亮起最暗的光。灯光颜色最好能适合哺乳。内容上,我希望有一些针对成人的睡前放松引导,或者温和的轻音乐,最好也能播放一些给宝宝听的摇篮曲。" },
{ question: "购买决策时,哪些因素会打动您?", answer: "安全、实用、高性价比。材质必须安全无害,因为宝宝可能会碰到。功能要真正解决我的痛点,而不是花里胡哨。" },
],
},
{
code: "U03",
basicAttributes: "王悦,22岁,女性,广州,设计专业大学生,月生活费约3000元",
content: [
{ question: "您关注睡眠健康吗?", answer: "关注!我们寝室经常聊朋克养生,就是一边熬夜做设计作业,一边泡枸杞。我知道睡眠很重要,但有时候是功课多,有时候就是单纯不想睡,刷短视频停不下来。" },
{ question: "您的睡前仪式通常包括什么?", answer: "我很喜欢营造氛围感。会在宿舍点香薰蜡烛,但不太安全。也喜欢用手机放ASMR或者助眠视频,但同样需要开着屏幕。我觉得我的睡眠环境需要更有仪式感和科技感。" },
{ question: "一款什么样的助眠灯会吸引您购买?", answer: "颜值是第一位的!设计必须好看,有质感,能融入我的宿舍装饰风格。灯光效果要多,能切换不同颜色和模式,满足我学习、休息、自拍打光等不同场景。可以没有深入的睡眠监测,但一定要能语音控制,和我互动,比如问问天气、设定闹钟。最好还有一些有趣的、小众的白噪音,比如雨声、篝火声。" },
{ question: "在消费这类产品时,您是怎样的心理?", answer: "我愿意为情绪价值和社交价值买单。它不仅要好用,还要能成为我的一个社交货币,就是可以拍照分享到小红书的那种。价格不能太贵,四五百元我觉得是上限了,但如果它足够好看、好玩,我会非常心动。" },
],
},
]
const currentInterviewTranscript = computed(() => interviewTranscripts.value.find((item) => item.code === form.value.keyUserRecords[activeInterviewIndex.value]?.code) || interviewTranscripts.value[0])
const currentInterviewTranscript = computed(() => interviewTranscripts.find((item) => item.code === form.value.keyUserRecords[activeInterviewIndex.value]?.code) || interviewTranscripts[0])
function createKeyUserRecords() {
return [
@ -481,7 +511,6 @@ async function loadTaskConfig() {
try {
const res = await getTrainingTaskByKey(TASK_KEY)
taskConfig.value = res?.data || null
interviewTranscripts.value = parseInterviewRecords(taskConfig.value?.interviewRecords)
} catch (error) {
taskConfig.value = null
}
@ -630,7 +659,7 @@ function openChartPreview(chart) {
function handleInterviewClick(index) {
activeInterviewIndex.value = index
const record = form.value.keyUserRecords[index]
if (interviewTranscripts.value.some((item) => item.code === record?.code)) {
if (interviewTranscripts.some((item) => item.code === record?.code)) {
interviewDialogVisible.value = true
}
}

@ -101,8 +101,7 @@
</div>
<img class="xtImg" src="../../../assets/images/线条.png" alt="" />
</template>
<TrainingExcelTools :tables="numericExcelTables" context-key="descriptive-statistics" />
<div class="from-item">
<div class="from-item">
<el-form :inline="true" label-position="right" label-width="84px" :model="form" class="demo-form-inline">
<el-form-item label="平均数:">
<el-input style="width: 120px" v-model="formInline.average" clearable />
@ -237,10 +236,6 @@
</pop-model>
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import * as portraitModel from "@/api/portraitModel";
import { paginate } from "@/utils/index.js";
import * as API from "@/api/AI.js";
@ -571,11 +566,6 @@ const closeDialog = () => {
formInline.value[key] = "";
}
};
const numericExcelTables = excelComputed(() => [et('statistics', '描述性统计计算结果', [formInline.value], [
...[['average','平均值'],['mode','众数'],['median','中位数'],['standardDeviation','标准差'],['variance','方差'],['kurtosis','峰度'],['standardError','标准误差'],['skewness','偏度'],['max','最大值'],['min','最小值'],['summation','求和']].map(([key,label]) => nc(key,label,{min: null, string: true})),
nc('observations', '观测数', {precision: 0, string: true})
], {apply: next => Object.assign(formInline.value, next[0])})]);
</script>
<style lang="scss" scoped>

@ -453,10 +453,10 @@ const stepOneQuestions = computed(() => parseStepOneChoiceQuestions(taskConfig.v
const currentStudyTip = computed(() => {
const tips = {
1: "建议:先从案例或电商详情页中拆出核心层、有形层、延伸层,不要把功能和用户利益混在一起。",
2: "建议:选择一个主流电商平台与真实 AI 产品,用“核心词 + 属性词 + 场景词”搜索并保留主图、详情页截图。",
3: "建议:将上一步选定产品的卖点按核心层、有形层、延伸层拆分,每层至少记录两条可核对的分析要点。",
4: "建议:把前面三步的发现收束为产品开发启发,说明哪些价值值得继续强化。",
1: "当前步骤建议:先从案例或电商详情页中拆出核心层、有形层、延伸层,不要把功能和用户利益混在一起。",
2: "当前步骤建议:选择一个主流电商平台与真实 AI 产品,用“核心词 + 属性词 + 场景词”搜索并保留主图、详情页截图。",
3: "当前步骤建议:将上一步选定产品的卖点按核心层、有形层、延伸层拆分,每层至少记录两条可核对的分析要点。",
4: "当前步骤建议:把前面三步的发现收束为产品开发启发,说明哪些价值值得继续强化。",
}
return tips[currentStep.value]
})

@ -1,68 +0,0 @@
export const scheduleExcelHeaders = ['阶段', '任务编号', '具体工作任务', '是否关键任务', '开始时间', '完成时间', '项目依赖关系'];
export function scheduleTemplateRows(rows) {
return [scheduleExcelHeaders, ...rows.map(row => [row.stage, row.taskNo, row.task, row.classification, '', '', ''])];
}
function validDate(year, month, day, location) {
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > days[month - 1]) {
throw new Error(`${location}日期不存在`);
}
return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
export function parseScheduleDate(value, location, { date1904 = false, parseDateCode } = {}) {
if (value == null || String(value).trim() === '') return '';
if (typeof value === 'number') {
if (!Number.isInteger(value) || value < 0 || value > 2958465) throw new Error(`${location}请填写有效日期,不要包含时间`);
const date = parseDateCode?.(value, { date1904 });
if (!date) throw new Error(`${location}Excel 日期无效`);
return validDate(date.y, date.m, date.d, location);
}
const text = String(value).trim();
const match = /^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})$/.exec(text) || /^(\d{4})年(\d{1,2})月(\d{1,2})日$/.exec(text);
if (!match) throw new Error(`${location}请使用 YYYY-MM-DD 日期格式或 Excel 日期单元格`);
const [, year, separatorOrMonth, monthOrDay, day] = match;
return day === undefined
? validDate(Number(year), Number(separatorOrMonth), Number(monthOrDay), location)
: validDate(Number(year), Number(monthOrDay), Number(day), location);
}
export function parseScheduleRows(sheetRows, currentRows, options = {}) {
const blank = value => value == null || String(value).trim() === '';
const headerIndex = sheetRows.findIndex(row => row.some(value => !blank(value)));
if (headerIndex < 0) throw new Error('Excel 中没有表头');
const aliases = { 开始日期: '开始时间', 完成日期: '完成时间', 结束日期: '完成时间', 结束时间: '完成时间' };
const headers = sheetRows[headerIndex].map(value => {
const label = String(value ?? '').replace(/\s/g, '');
return aliases[label] || label;
});
const populated = headers.filter(Boolean);
if (new Set(populated).size !== populated.length) throw new Error('Excel 表头有重复列');
const required = ['任务编号', '开始时间', '完成时间', '项目依赖关系'];
const missing = required.filter(label => !headers.includes(label));
if (missing.length) throw new Error(`缺少列:${missing.join('、')},请使用 WBS 排期模板`);
if (populated.some(label => !scheduleExcelHeaders.includes(label))) throw new Error('包含不属于 WBS 排期表的列,请使用本步骤模板');
const positions = Object.fromEntries(required.map(label => [label, headers.indexOf(label)]));
const existing = new Map(currentRows.map(row => [String(row.taskNo), row]));
const updates = new Map();
for (let index = headerIndex + 1; index < sheetRows.length; index += 1) {
const cells = sheetRows[index];
if (cells.every(blank)) continue;
if (cells.some((value, column) => !blank(value) && !headers[column])) throw new Error(`第 ${index + 1} 行包含无表头的数据`);
const taskNo = String(cells[positions['任务编号']] ?? '').trim();
if (!taskNo) throw new Error(`第 ${index + 1} 行缺少任务编号`);
if (!existing.has(taskNo)) throw new Error(`第 ${index + 1} 行任务编号 ${taskNo} 不存在`);
if (updates.has(taskNo)) throw new Error(`第 ${index + 1} 行任务编号 ${taskNo} 重复`);
const startDate = parseScheduleDate(cells[positions['开始时间']], `第 ${index + 1} 行任务 ${taskNo} 的开始时间:`, options);
const endDate = parseScheduleDate(cells[positions['完成时间']], `第 ${index + 1} 行任务 ${taskNo} 的完成时间:`, options);
if (startDate && endDate && startDate > endDate) throw new Error(`第 ${index + 1} 行任务 ${taskNo} 的完成时间不能早于开始时间`);
const dependency = String(cells[positions['项目依赖关系']] ?? '').trim();
if (dependency.length > 100) throw new Error(`第 ${index + 1} 行任务 ${taskNo} 的项目依赖关系最多 100 个字符`);
updates.set(taskNo, { startDate, endDate, dependency });
}
if (!updates.size) throw new Error('没有可导入的排期数据');
return { count: updates.size, rows: currentRows.map(row => ({ ...row, ...(updates.get(String(row.taskNo)) || {}) })) };
}

@ -1258,7 +1258,7 @@ async function nextStep() {
}
}
/* 步骤:教育蓝实底白字,白色编号徽章蓝字 */
/* 当前步骤:教育蓝实底白字,白色编号徽章蓝字 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -95,12 +95,6 @@
<h3>{{ trainingSteps[1] }}</h3>
</div>
<div class="step-title-actions">
<button type="button" class="outline-action schedule-export-action" :disabled="importingSchedule"
@click="downloadScheduleTemplate">下载 Excel 模板</button>
<button type="button" class="outline-action schedule-export-action"
:disabled="!hasCompletedStepOne || checking || saving || importingSchedule"
@click="scheduleExcelInput?.click()">{{ importingSchedule ? '导入中…' : '导入 Excel' }}</button>
<input ref="scheduleExcelInput" type="file" hidden accept=".xls,.xlsx" @change="importScheduleExcel" />
<button type="button" class="outline-action schedule-export-action"
@click="exportScheduleList"><el-icon>
<Download />
@ -110,7 +104,6 @@
</div>
<p class="process-intro">将开发一款互联网产品的模糊目标,拆解为可执行的具体工作任务。根据案例信息,填写参考工期和项目依赖关系。</p>
<p v-if="!hasCompletedStepOne" class="step-warning">请先完成第 1 步并判题通过;关键任务结果会自动带入本表。</p>
<p class="schedule-import-hint">支持导入填写后的模板或导出列表,按任务编号匹配。日期可填写 YYYY-MM-DD 或使用 Excel 日期格式;导入后请保存。</p>
<div class="training-table-wrap">
<table class="process-table schedule-table">
<thead>
@ -211,7 +204,7 @@
</el-icon>
上一步
</button>
<button type="button" class="btn-nav btn-save" :disabled="saving || uploadingGantt || importingSchedule"
<button type="button" class="btn-nav btn-save" :disabled="saving || uploadingGantt"
@click="saveCurrentProgress">
<el-icon>
<CircleCheck />
@ -223,7 +216,7 @@
<span class="step-progress">Step {{ String(currentStep).padStart(2, '0') }} / {{
String(trainingSteps.length).padStart(2, '0') }}</span>
<button v-if="currentStep < trainingSteps.length" type="button" class="btn-nav btn-primary"
:disabled="checking || saving || uploadingGantt || importingSchedule" @click="nextStep">
:disabled="checking || saving || uploadingGantt" @click="nextStep">
{{ checking ? '判题中…' : '下一步' }}
<el-icon>
<ArrowRight />
@ -241,10 +234,8 @@
</template>
<script setup>
import { ArrowLeft, ArrowRight, CircleCheck, Download, Operation, RefreshLeft, Upload } from "@element-plus/icons-vue"
import { ArrowLeft, ArrowRight, CircleCheck, Operation, RefreshLeft, Upload } from "@element-plus/icons-vue"
import * as XLSX from "xlsx"
import { ElMessageBox } from "element-plus"
import { parseScheduleRows, scheduleTemplateRows } from "./processScheduleExcel.mjs"
import { checkProductDevelopmentProcessStepOne, checkProductDevelopmentProcessStepTwo, checkProductDevelopmentProcessStepThree, checkProductDevelopmentProcessStepFour, getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer"
import { getTrainingTaskByKey } from "@/api/trainingTask"
import { parseTrainingArray } from "@/views/training/taskKeyMap"
@ -278,8 +269,6 @@ const currentStep = ref(1)
const briefOpen = ref(true)
const checking = ref(false)
const saving = ref(false)
const scheduleExcelInput = ref(null)
const importingSchedule = ref(false)
const draftReady = ref(false)
const checkResult = ref(null)
const stepOnePassed = ref(false)
@ -639,52 +628,6 @@ function downloadBuiltInFile(url, filename) {
document.body.removeChild(link)
}
function downloadScheduleTemplate() {
const workbook = XLSX.utils.book_new()
const worksheet = XLSX.utils.aoa_to_sheet(scheduleTemplateRows(processRows.value))
worksheet['!cols'] = [{ wch: 12 }, { wch: 10 }, { wch: 36 }, { wch: 14 }, { wch: 16 }, { wch: 16 }, { wch: 30 }]
XLSX.utils.book_append_sheet(workbook, worksheet, 'WBS排期表')
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([
['填写说明'], ['在第一个工作表填写开始时间、完成时间和项目依赖关系。'],
['按任务编号匹配,可调整行或列的顺序;未导入的任务保持不变。'],
['阶段、具体工作任务和是否关键任务仅供参考,导入不会修改第一步分类结果。'],
['日期填写 YYYY-MM-DD(如 2026-10-20),也支持 YYYY/M/D、YYYY.M.D、YYYY年M月D日和 Excel 日期单元格。'],
['完成时间不能早于开始时间;导入行的空白日期或依赖关系会清空对应字段。'],
['导入后点击保存;下一步仍按原有规则检查全部任务的排期。'],
]), '填写说明')
XLSX.writeFile(workbook, '产品开发WBS排期-导入模板.xlsx')
}
async function importScheduleExcel(event) {
const file = event.target?.files?.[0]
if (event.target) event.target.value = ''
if (!file || currentStep.value !== 2 || !hasCompletedStepOne.value || checking.value || saving.value || importingSchedule.value) return
importingSchedule.value = true
const currentRows = processRows.value
const snapshot = JSON.stringify(currentRows)
try {
if (!/\.(xls|xlsx)$/i.test(file.name)) throw new Error('请选择 .xls 或 .xlsx 文件')
if (file.size > 5 * 1024 * 1024) throw new Error('Excel 文件不能超过 5MB')
const workbook = XLSX.read(await file.arrayBuffer(), { type: 'array', cellDates: false })
if (!workbook.SheetNames.length) throw new Error('Excel 中没有工作表')
const sheet = workbook.Sheets[workbook.SheetNames[0]]
const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1')
if (range.e.r > 10000 || range.e.c > 50) throw new Error('工作表范围过大,请仅保留 WBS 排期数据')
const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: true, defval: '', blankrows: true, range: 0 })
const result = parseScheduleRows(rows, currentRows, { date1904: !!workbook.Workbook?.WBProps?.date1904, parseDateCode: XLSX.SSF.parse_date_code })
await ElMessageBox.confirm(`将更新 ${result.count} 个任务的开始时间、完成时间和项目依赖关系。导入行的空白字段会清空对应输入,未导入的任务和第一步分类结果保持不变。是否继续?`, '确认导入排期', { type: 'warning', confirmButtonText: '导入', cancelButtonText: '取消' })
if (currentStep.value !== 2 || !hasCompletedStepOne.value || checking.value || saving.value || processRows.value !== currentRows || JSON.stringify(currentRows) !== snapshot) {
throw new Error('当前步骤或排期已变化,请重新导入')
}
processRows.value = result.rows
proxy?.$modal?.msgSuccess?.(`已导入 ${result.count} 个任务的排期,请保存本步骤`)
} catch (error) {
if (error !== 'cancel' && error !== 'close') proxy?.$modal?.msgError?.(error?.message || '导入失败,请检查 Excel 文件')
} finally {
importingSchedule.value = false
}
}
function exportScheduleList() {
const rows = processRows.value.map((row) => ({
阶段: row.stage,
@ -967,13 +910,6 @@ async function nextStep() {
gap: 8px;
}
.schedule-import-hint {
margin: 0 0 12px;
color: #6b7280;
font-size: var(--student-fs-body-sm);
line-height: 1.6;
}
/* 标题行内联导出:次按钮的紧凑小号(继承 .outline-action 描边与圆角语言) */
.schedule-export-action {
min-height: 36px;
@ -1769,7 +1705,7 @@ tr.is-incorrect .classification-feedback {
}
}
/* 步骤:教育蓝实底白字 */
/* 当前步骤:教育蓝实底白字 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -147,7 +147,7 @@
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :disabled="configLoading" :loading="saving" @click="submit">保存</el-button>
<el-button type="primary" @click="submit">保存</el-button>
</template>
</el-dialog>
</section>
@ -167,9 +167,6 @@ const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const editingId = ref("");
const configLoading = ref(false);
const saving = ref(false);
let editRequestId = 0;
const form = ref({});
const defaultProductConfig = () => ({
organizationMode: "ADMIN_CLASS_ENABLED",
@ -209,9 +206,6 @@ const handleSizeChange = () => {
};
const openCreate = () => {
if (saving.value) return;
editRequestId++;
configLoading.value = false;
editingId.value = "";
form.value = {
schoolName: "",
@ -232,20 +226,11 @@ const openDetail = (row) => {
};
const openEdit = async (row) => {
if (saving.value) return;
const requestId = ++editRequestId;
editingId.value = row.schoolId;
form.value = { ...row };
configLoading.value = true;
dialogVisible.value = false;
try {
const res = await getPlatformSchoolProductConfig(row.schoolId);
if (requestId !== editRequestId) return;
productConfig.value = normalizeProductConfig(res.data);
dialogVisible.value = true;
} finally {
if (requestId === editRequestId) configLoading.value = false;
}
const res = await getPlatformSchoolProductConfig(row.schoolId);
productConfig.value = normalizeProductConfig(res.data);
dialogVisible.value = true;
};
const handleProvinceChange = () => {
@ -321,29 +306,22 @@ const buildSchoolPayload = () => ({
});
const submit = async () => {
if (configLoading.value || saving.value) return;
const schoolId = editingId.value;
const payload = buildSchoolPayload();
saving.value = true;
try {
if (schoolId) {
await updatePlatformSchoolProductConfig(schoolId, {
organizationMode: productConfig.value.organizationMode,
studentRosterOwner: productConfig.value.studentRosterOwner,
facultyManagementEnabled: productConfig.value.facultyManagementEnabled,
majorManagementEnabled: productConfig.value.majorManagementEnabled,
adminClassManagementEnabled: productConfig.value.adminClassManagementEnabled,
});
await updatePlatformSchool(schoolId, payload);
} else {
await addPlatformSchool(payload);
}
ElMessage.success("保存成功");
dialogVisible.value = false;
load({ showLoading: false });
} finally {
saving.value = false;
if (editingId.value) {
await updatePlatformSchoolProductConfig(editingId.value, {
organizationMode: productConfig.value.organizationMode,
studentRosterOwner: productConfig.value.studentRosterOwner,
facultyManagementEnabled: productConfig.value.facultyManagementEnabled,
majorManagementEnabled: productConfig.value.majorManagementEnabled,
adminClassManagementEnabled: productConfig.value.adminClassManagementEnabled,
});
await updatePlatformSchool(editingId.value, payload);
} else {
await addPlatformSchool(payload);
}
ElMessage.success("保存成功");
dialogVisible.value = false;
load({ showLoading: false });
};
const remove = async (row) => {

@ -59,8 +59,7 @@
计算结果保留小数点后一位
<br />
</span>
<TrainingExcelTools :tables="numericExcelTables" context-key="funnel-rate" />
<div style="margin-top: 10px; display: flex">
<div style="margin-top: 10px; display: flex">
<el-table
:data="step1Data"
style="width: 900px"
@ -313,10 +312,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import popModal from "@/views/components/popModal.vue";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
@ -1229,8 +1224,6 @@ const submitTimeCount = () => {
// .then((res) => {})
// .catch((error) => {});
};
const numericExcelTables = excelComputed(() => [et('funnel', '漏斗模型转化率', step1Data.value.slice(1), [fc('data1', '指标'), ...[['params1','浏览'],['params2','购物车'],['params3','订单'],['params4','支付'],['params5','完成交易']].map(([key,label]) => rc(key, label + '(%)', {precision: 1, string: true}))], {apply: next => step1Data.value.splice(1, step1Data.value.length - 1, ...next)})]);
</script>
<style scoped lang="scss">
.content {

@ -34,7 +34,7 @@
@click="switchStep(index + 1)">
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy"><strong class="step-name" :title="step">{{ step }}</strong><span
class="step-action">{{ currentStep === index + 1 ? '' : '' }}
class="step-action">{{ currentStep === index + 1 ? '当前步骤' : '点击切换' }}
→</span></span>
</button>
<span v-if="index < trainingSteps.length - 1" class="step-connector" aria-hidden="true"></span>
@ -1557,7 +1557,7 @@ button:disabled {
}
}
/* 步骤:教育蓝实底 */
/* 当前步骤:教育蓝实底 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -44,7 +44,7 @@
:aria-label="`第${index + 1}步:${step}`" @click="setCurrentStep(index + 1)">
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy"><strong class="step-name" :title="step">{{ step }}</strong><span
class="step-action">{{ activeStep === index + 1 ? "" : "" }} <span
class="step-action">{{ activeStep === index + 1 ? "当前步骤" : "点击切换" }} <span
aria-hidden="true">→</span></span></span>
</button>
<span v-if="index < configuredSteps.length - 1" class="step-connector"

@ -36,7 +36,7 @@
<span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="step-copy">
<strong class="step-name" :title="step">{{ step }}</strong>
<span class="step-action">{{ form.activeStep === index + 1 ? "" : "" }} <span
<span class="step-action">{{ form.activeStep === index + 1 ? "当前步骤" : "点击切换" }} <span
aria-hidden="true">→</span></span>
</span>
</button>

@ -35,14 +35,12 @@
@click="goToStepFromTab(index + 1)">
<span class="step-marker" aria-hidden="true">{{ String(index + 1).padStart(2, "0") }}</span>
<span class="step-copy"><strong class="step-name" :title="step">{{ step }}</strong><span
class="step-action">{{ currentStep === index + 1 ? '' : '' }} <span
class="step-action">{{ currentStep === index + 1 ? '当前步骤' : '点击切换' }} <span
aria-hidden="true">→</span></span></span>
</button>
<span v-if="index < trainingSteps.length - 1" class="step-connector" aria-hidden="true" />
</template>
</nav>
<TrainingExcelTools v-if="currentStep > 2" :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<section v-if="currentStep === 1" class="step-card hardware-step-card">
<section class="cost-brief">
@ -68,9 +66,6 @@
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<div class="bom-table-wrap">
<table class="bom-table">
<thead>
@ -152,9 +147,6 @@
</div>
<span class="step-chip">{{ costRows.length }} 项物料同步自第一步</span>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<div class="bom-table-wrap">
<table class="bom-table batch-cost-table">
<thead>
@ -404,10 +396,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, getCurrentInstance, onMounted, reactive, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, DataAnalysis } from "@element-plus/icons-vue"
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
@ -888,14 +876,6 @@ onMounted(async () => {
try { taskConfig.value = (await getTrainingTaskByKey(TASK_KEY))?.data || {} } catch (_) { taskConfig.value = {} }
try { await loadAnswer() } catch (_) { /* A missing saved answer should not block the worksheet. */ }
})
const numericExcelTables = excelComputed(() => {
if (currentStep.value === 1) return [et('bom', '物料明细与金额核算', rows.value, [tc('materialName', '物料名称', {maxLength: 40}), tc('specification', '选型规格参数', {maxLength: 120}), nc('unitPrice', '单价(元)', {string: true}), nc('quantity', '数量', {min: 1, max: 9999, precision: 0})], {maxRows: MAX_ROWS, templateRowCount: MIN_ROWS, createRow: () => createBlankRow()})];
if (currentStep.value === 2) return [et('batch', '物料批量成本核算', costRows.value, [fc('materialName', '物料名称'), nc('smallBatchUnitCost', '小批量单台成本(元)', {string: true}), nc('largeBatchUnitCost', '大批量单台成本(元)', {string: true})])];
if (currentStep.value === 3) return [et('manufacturing', '制造费用分摊', stepThree.items, [tc('expenseName', '费用名称', {maxLength: 40}), nc('smallBatchUnitCost', '小批量制造费用(元)', {string: true}), nc('largeBatchUnitCost', '大批量制造费用(元)', {string: true})], {maxRows: MAX_MANUFACTURING_ROWS, templateRowCount: MIN_MANUFACTURING_ROWS, createRow: () => createManufacturingRow()})];
return [];
});
</script>
<style lang="scss" scoped>

@ -223,7 +223,7 @@
</section>
</main>
<TrainingAiSidebar study-tip="建议:先从政策、经济、社会、技术四类因素中提取关键现象,再判断对应的机会与风险。" reference-title="选品机会判断参考"
<TrainingAiSidebar study-tip="当前步骤建议:先从政策、经济、社会、技术四类因素中提取关键现象,再判断对应的机会与风险。" reference-title="选品机会判断参考"
reference-text="· 政治:政策补贴、标准认证、合规门槛<br />· 经济:价格带、采购成本、市场规模<br />· 社会:健康意识、家庭场景、消费偏好<br />· 技术:传感器、联网能力、数据分析能力"
assist-text="可以把每个维度先写成“现象 -> 机会/风险”的句式,最后再汇总判断是否适合作为选品方向。" :progress-items="progressItems" />
</div>

@ -29,12 +29,10 @@
:key="step"><button type="button"
:class="['step-tab', { active: currentStep === index + 1, complete: currentStep > index + 1 }]"
@click="switchStep(index + 1)"><b>{{ String(index + 1).padStart(2, '0')
}}</b><span><strong>{{ step }}</strong><small>{{ currentStep === index + 1 ? '' :
'' }} →</small></span></button><i
}}</b><span><strong>{{ step }}</strong><small>{{ currentStep === index + 1 ? '当前步骤' :
'点击切换' }} →</small></span></button><i
v-if="index < trainingSteps.length - 1" /></template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<section class="step-card">
<template v-if="currentStep === 1">
<div class="step-heading">
@ -220,14 +218,10 @@
<tbody>
<tr v-for="product in products" :key="product.id">
<td class="metric">{{ product.name }}</td>
<td>
<div class="review-rate-cell">
<el-input-number v-model="reviewInsights[product.id].favorableRate"
:disabled="!stepFourPassed" :min="0" :max="100" :step="0.01"
:aria-label="`${product.name} 的好评率`" controls-position="right"
class="review-rate-input" /><span class="percent">%</span>
</div>
</td>
<td><el-input-number v-model="reviewInsights[product.id].favorableRate"
:disabled="!stepFourPassed" :min="0" :max="100" :step="0.01"
:aria-label="`${product.name} 的好评率`" controls-position="right"
style="width:100%" /><span class="percent">%</span></td>
<td><el-input v-model.trim="reviewInsights[product.id].painPoint"
type="textarea" :autosize="{ minRows: 2 }" :disabled="!stepFourPassed"
:aria-label="`${product.name} 的用户痛点`" placeholder="请根据评论数据提炼用户痛点" />
@ -240,6 +234,14 @@
</tbody>
</table>
</div>
<div class="insight-guide">
<div>
<h3>可参考以下方法:</h3>
<p>1. 自行根据评价数据计算好评率,阅读评论后分析用户痛点及未被满足的需求。</p>
<p>2. 导出评论数据表,上传到通用 AI 大模型,通过文本分析完成计算与提炼。</p>
<p>提示词:请计算 Excel 表中产品评论数据的好评率,提炼用户痛点和未被满足的需求。</p>
</div>
</div>
</template>
<template v-else-if="currentStep === 6">
<div class="step-heading">
@ -299,10 +301,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import * as XLSX from "xlsx"
import { ArrowLeft, ArrowRight, CircleCheck, Download, RefreshLeft, UploadFilled } from "@element-plus/icons-vue"
import { checkMarketOpportunitySelectionStepOne, checkMarketOpportunitySelectionStepTwo, checkMarketOpportunitySelectionStepThree, checkMarketOpportunitySelectionStepFour, checkMarketOpportunitySelectionStepFive, checkMarketOpportunitySelectionStepSix, deleteStudentTrainingAnswer, getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer"
@ -438,17 +436,6 @@ async function saveAndGoToStepSix() { if (saving.value || !stepFourPassed.value)
async function saveAndCompleteTraining() { if (saving.value || !stepFivePassed.value) return; saving.value = true; try { await checkMarketOpportunitySelectionStepSix({ developmentConclusion: developmentConclusion.value }); dynamicStepAnswers.value = buildDynamicStepAnswers({ step5: buildStepFiveOutcome(), step6: buildStepSixOutcome() }); await saveStudentTrainingAnswer(TASK_KEY, { dynamicStepAnswers: JSON.stringify(dynamicStepAnswers.value), currentStep: 6, submitted: true, saveAction: "SUBMIT" }); proxy?.$modal?.msgSuccess("实训成果已保存,恭喜完成本次实训") } catch (error) { proxy?.$modal?.msgError?.(error?.message || "请填写建议开发的产品及具体原因") } finally { saving.value = false } }
function downloadFile(content, fileName, type) { const blob = new Blob([content], { type }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = fileName; link.click(); URL.revokeObjectURL(url) }
function exportOutcome() { const blob = new Blob([JSON.stringify({ taskName: taskTitle.value, step1: buildStepOneOutcome(), step2: buildStepTwoOutcome(), step3: buildStepThreeOutcome(), step4: buildStepFourOutcome(), step5: buildStepFiveOutcome(), step6: buildStepSixOutcome(), currentStep: currentStep.value }, null, 2)], { type: "application/json;charset=utf-8" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = `${taskTitle.value}-实训结果.json`; link.click(); URL.revokeObjectURL(url) }
const numericExcelTables = excelComputed(() => {
if (currentStep.value === 2 && stepOnePassed.value) return [
et('primary', '选品一级指标权重', categories.map(name => ({name, value: primaryWeights.value[name]})), [fc('name', '一级指标'), rc('value', '权重(%)', {min: 1, precision: 0})], {apply: next => next.forEach(r => {primaryWeights.value[r.name] = r.value;})}),
et('dimensions', '选品维度内权重', indicators.map(i => ({id: i.id, name: i.name, value: weights.value[i.id]})), [fc('name', '评估维度'), rc('value', '权重(%)', {min: 1, precision: 0})], {apply: next => next.forEach(r => {weights.value[r.id] = r.value;})})
];
if (currentStep.value === 3 && stepTwoPassed.value) return [et('scores', '选品综合得分', products.map(p => ({id: p.id, name: p.name, score: scores.value[p.id]})), [tc('name', '产品品类', {maxLength: 40}), nc('score', '综合得分', {max: 100})], {apply: next => next.forEach(r => {products.find(p => p.id === r.id).name = r.name; scores.value[r.id] = r.score;})})];
if (currentStep.value === 5 && stepFourPassed.value) return [et('reviews', '选品用户好评率', products.map(p => ({id: p.id, name: p.name, rate: reviewInsights.value[p.id].favorableRate})), [fc('name', '产品品类'), rc('rate', '好评率(%)')], {apply: next => next.forEach(r => {reviewInsights.value[r.id].favorableRate = r.rate;})})];
return [];
});
</script>
<style lang="scss" scoped>
@ -898,19 +885,6 @@ return [];
line-height: 1.55;
}
.review-rate-cell {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
white-space: nowrap;
}
.review-rate-cell .review-rate-input {
flex: 1 1 auto;
min-width: 0;
}
.calculation-guide h3,
.visual-guide h3,
.insight-guide h3 {

@ -40,7 +40,6 @@
class="step-connector" aria-hidden="true"></span>
</template>
</nav>
<TrainingExcelTools v-if="currentStep !== 4" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<section class="step-card">
<header class="step-title-row">
@ -202,8 +201,6 @@
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<div class="table-scroll">
<table class="price-table psm-table">
<thead>
@ -488,10 +485,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, getCurrentInstance, onMounted, reactive, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck } from "@element-plus/icons-vue"
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
@ -1362,7 +1355,7 @@ async function saveStepFiveDraft() {
dynamicStepAnswers: JSON.stringify(dynamicStepAnswers.value),
})
hasSavedAnswer.value = true
proxy?.$modal?.msgSuccess?.("已保存")
proxy?.$modal?.msgSuccess?.("当前步骤已保存")
} finally {
saving.value = false
}
@ -1596,16 +1589,6 @@ async function loadSavedProgress() {
onMounted(async () => {
await Promise.all([loadTaskConfig(), loadSavedProgress()])
})
const numericExcelTables = excelComputed(() => {
const money = (key, label) => nc(key, label, {string: true});
if (currentStep.value === 1) return [et('markup', '成本加成定价', pricingRows.value, [fc('channel', '销售渠道'), nc('markupRate', '成本加成比例(%)', {percent: true, string: true})])];
if (currentStep.value === 2) return [et('competitors', '竞争定价分析', competitorRows.value, [tc('productType', '竞品类型'), tc('brand', '品牌'), money('ecommercePrice', '电商售价(元)'), tc('differentiator', '差异化优势')])];
if (currentStep.value === 3) return [et('value', '用户感知价值', perceivedValueItems.value, [tc('name', '价值感知项'), money('perceivedValue', '感知价值(元)')], {maxRows: 10000, createRow: () => createPerceivedValueItem()})];
if (currentStep.value === 4) return [et('psm', 'PSM价格敏感度', psmRows.value, [fc('priceRange', '价格区间'), ...[['tooExpensive','太贵'], ['tooCheap','太便宜'], ['expensiveAcceptable','贵但可接受'], ['cheapValue','便宜划算']].map(([k,l]) => rc(k, l + '(%)', {string: true}))], {apply: next => {psmRows.value = next; clearValidation();}})];
return [];
});
</script>
<style scoped lang="scss">

@ -451,9 +451,9 @@ function normalizeStepThreeDocument(value) {
}
}
function stepStateText(index) {
if (index === 0) return stepOnePassed.value ? "已通过" : ""
if (index === 1) return stepOnePassed.value ? (currentStep.value === 2 ? "" : "可填写") : "完成第 1 步后解锁"
if (index === 2) return stepOnePassed.value ? (currentStep.value === 3 ? "" : isDocumentReady.value ? "已上传" : "可填写") : "完成第 1 步后解锁"
if (index === 0) return stepOnePassed.value ? "已通过" : "当前步骤"
if (index === 1) return stepOnePassed.value ? (currentStep.value === 2 ? "当前步骤" : "可填写") : "完成第 1 步后解锁"
if (index === 2) return stepOnePassed.value ? (currentStep.value === 3 ? "当前步骤" : isDocumentReady.value ? "已上传" : "可填写") : "完成第 1 步后解锁"
return currentStep.value > index + 1 ? "已完成" : "后续步骤"
}
function invalidateCheck() { checkResult.value = null; stepOnePassed.value = false }
@ -614,7 +614,7 @@ function switchStep(step) {
currentStep.value = 3
return
}
proxy?.$modal?.msgInfo("请先完成本步骤后再进入后续实训。")
proxy?.$modal?.msgInfo("请先完成当前步骤后再进入后续实训。")
}
function goNextStep() { switchStep(2) }
function saveCurrentProgress() {
@ -1803,7 +1803,7 @@ function exportOutcome() { if (currentStep.value === 2) { exportStepTwoTable() }
}
}
/* 步骤:教育蓝实底 */
/* 当前步骤:教育蓝实底 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -315,7 +315,7 @@
<span class="section-number">03</span>
<div class="section-info">
<h4>资料与步骤</h4>
<p>上传案例资料、案例数据、实训指导手册、AI辅助指导手册与参考答案,配置实训步骤</p>
<p>上传案例资料、案例数据、实训指导手册与AI排错指导手册,配置实训步骤</p>
</div>
</div>
<div v-for="slot in materialSlots" :key="slot.key" class="material-row">
@ -331,7 +331,7 @@
</div>
</div>
<div class="material-ops">
<el-upload v-if="!isReadonly" action="#" :auto-upload="false" :show-file-list="false" :accept="slot.accept" :on-change="(file) => handleMaterialChange(slot.key, file)">
<el-upload v-if="!isReadonly" action="#" :auto-upload="false" :show-file-list="false" :on-change="(file) => handleMaterialChange(slot.key, file)">
<el-button type="primary" :loading="uploadingField === slot.key" class="upload-btn">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />
@ -348,7 +348,6 @@
<!-- 第一步选择题:编辑入口固定在第一个步骤行旁,仅三个白名单任务显示 -->
<StepOneQuestionBankPicker v-model:visible="bankPickerVisible" :load-questions="loadBankQuestions" :existing="taskForm.stepOneQuestions" @confirm="handleBankConfirm" />
<StepOneChoiceQuestionEditor v-model:visible="choiceEditorVisible" v-model="taskForm.stepOneQuestions" :task-name="taskForm.title" :load-questions="loadBankQuestions" />
<InterviewRecordsEditor v-if="taskForm.taskKey === 'target-user-profile'" v-model:visible="interviewEditorVisible" v-model="taskForm.interviewRecords" />
<el-form-item label="步骤名称:">
<div class="step-list">
@ -365,7 +364,6 @@
<el-button v-if="!isReadonly" type="primary" class="step-question-btn" @click="choiceEditorVisible = true">编辑题目{{ stepOneQuestionCount ? `(${stepOneQuestionCount}题)` : "" }}</el-button>
<span v-else class="step-question-tag">已配置 {{ stepOneQuestionCount }} 道题</span>
</template>
<el-button v-if="!isReadonly && taskForm.taskKey === 'target-user-profile' && index === 3" type="primary" plain class="step-interview-btn" @click="interviewEditorVisible = true">编辑访谈记录</el-button>
<button v-if="!isReadonly && taskForm.steps.length > 1" type="button" class="remove-btn" @click="removeStep(index)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6" />
@ -408,8 +406,6 @@
import { downloadTrainingTaskTemplate, importTrainingTasks, listTrainingTasks, updateTrainingTask, uploadTrainingTaskMaterial } from "@/api/trainingTask";
import StepOneChoiceQuestionEditor from "@/views/components/StepOneChoiceQuestionEditor.vue";
import StepOneQuestionBankPicker from "@/views/components/StepOneQuestionBankPicker.vue";
import InterviewRecordsEditor from "@/views/components/InterviewRecordsEditor.vue";
import { parseInterviewRecords } from "@/utils/interviewRecords";
import { parseStepOneChoiceQuestions, supportsStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
import { getPlatformQuestions } from "@/api/exam";
@ -422,14 +418,12 @@ const saving = ref(false);
const uploadingField = ref("");
const choiceEditorVisible = ref(false);
const bankPickerVisible = ref(false);
const interviewEditorVisible = ref(false);
// 五类资料槽位:key 对应 taskForm 的 `${key}Name` / `${key}Url` 字段。
// 四类资料槽位:key 对应 taskForm 的 `${key}Name` / `${key}Url` 字段
const materialSlots = [
{ key: "material", label: "案例资料" },
{ key: "trainingData", label: "案例数据" },
{ key: "guideManual", label: "实训指导手册" },
{ key: "aiManual", label: "AI辅助指导手册" },
{ key: "referenceAnswer", label: "参考答案", accept: ".pdf,application/pdf" },
];
const tasks = ref([]);
const dialogVisible = ref(false);
@ -525,10 +519,7 @@ function createEmptyTask() {
guideManualUrl: "",
aiManualName: "",
aiManualUrl: "",
referenceAnswerName: "",
referenceAnswerUrl: "",
stepOneQuestions: [],
interviewRecords: parseInterviewRecords(),
steps: createBuiltinSteps(),
sort: 0,
enabled: true,
@ -563,7 +554,6 @@ function normalizeTask(task) {
const trainingData = normalizeMaterial(task.trainingDataName, task.trainingDataUrl);
const guideManual = normalizeMaterial(task.guideManualName, task.guideManualUrl);
const aiManual = normalizeMaterial(task.aiManualName, task.aiManualUrl);
const referenceAnswer = normalizeMaterial(task.referenceAnswerName, task.referenceAnswerUrl);
return {
id: task.id,
taskKey: task.taskKey,
@ -580,10 +570,7 @@ function normalizeTask(task) {
guideManualUrl: guideManual.url,
aiManualName: aiManual.name,
aiManualUrl: aiManual.url,
referenceAnswerName: referenceAnswer.name,
referenceAnswerUrl: referenceAnswer.url,
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
interviewRecords: parseInterviewRecords(task.interviewRecords),
steps: normalizeSteps(parseArray(task.steps, createBuiltinSteps())),
sort: task.sort || 0,
enabled: task.enabled !== false,
@ -659,7 +646,6 @@ function cloneTask(task) {
return {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
interviewRecords: parseInterviewRecords(task.interviewRecords),
steps: normalizeSteps(task.steps?.length ? task.steps : createBuiltinSteps()),
};
}
@ -692,13 +678,8 @@ async function handleImportChange(file) {
async function handleMaterialChange(slotKey, file) {
const rawFile = file?.raw;
if (!rawFile) return;
if (slotKey === "referenceAnswer" && !isPdfFile(rawFile)) {
proxy?.$modal?.msgError?.("参考答案仅支持 PDF 文件(.pdf)");
return;
}
const data = new FormData();
data.append("file", rawFile);
data.append("materialType", slotKey);
uploadingField.value = slotKey;
try {
const res = await uploadTrainingTaskMaterial(data);
@ -712,11 +693,6 @@ async function handleMaterialChange(slotKey, file) {
}
}
function isPdfFile(file) {
const name = String(file?.name || "").trim().toLowerCase();
return name.endsWith(".pdf");
}
function clearMaterial(slotKey) {
taskForm[`${slotKey}Name`] = "";
taskForm[`${slotKey}Url`] = "";
@ -767,10 +743,7 @@ function buildPayload() {
guideManualUrl: taskForm.guideManualUrl,
aiManualName: taskForm.aiManualName,
aiManualUrl: taskForm.aiManualUrl,
referenceAnswerName: taskForm.referenceAnswerName,
referenceAnswerUrl: taskForm.referenceAnswerUrl,
stepOneQuestions: JSON.stringify(taskForm.stepOneQuestions || []),
interviewRecords: JSON.stringify(taskForm.interviewRecords || []),
sort: taskForm.sort,
enabled: taskForm.enabled,
};
@ -1797,8 +1770,6 @@ function buildPayload() {
border-radius: 8px;
}
.step-interview-btn { margin-left: 8px; white-space: nowrap; }
.step-question-btn {
flex-shrink: 0;
height: 32px;

@ -21,9 +21,10 @@
<section class="score-visual" aria-label="模块成绩分布">
<div ref="scoreChartRef" class="score-chart"></div>
<div v-if="hasScore" class="score-summary">
<div class="score-metric">
<span class="summary-label">评分:</span>
<div class="score-metric" :class="scoreType === 'teacher' ? 'score-metric--teacher' : 'score-metric--ai'">
<span class="summary-label">{{ scoreLabel }}</span>
<strong>{{ displayScore }}</strong>
<span class="summary-unit">分</span>
</div>
</div>
</section>
@ -86,7 +87,7 @@ const userStore = useUserStore();
const scoreChartRef = ref(null);
const studyTimeChartRef = ref(null);
const progressChartRef = ref(null);
const report = ref({ totalScore: null, aiAssessmentScore: null, teacherScore: null, modules: [] });
const report = ref({ totalScore: 0, modules: [] });
const projectStudyTimes = ref([]);
const loading = ref(true);
const loadError = ref("");
@ -98,7 +99,7 @@ let studyTimeChart;
let progressChart;
const displayModules = computed(() => report.value.modules || []);
const aiScore = computed(() => report.value.aiAssessmentScore ?? report.value.aiScore ?? null);
const aiScore = computed(() => report.value.aiAssessmentScore ?? report.value.aiScore ?? report.value.totalScore);
const teacherScore = computed(() => report.value.teacherScore);
// 新的评分显示逻辑:有老师评分显示老师评分,否则显示AI评分,都没有就不显示
@ -109,9 +110,11 @@ const hasAiScore = computed(() =>
aiScore.value !== null && aiScore.value !== undefined && aiScore.value !== ""
);
const hasScore = computed(() => hasTeacherScore.value || hasAiScore.value);
const scoreType = computed(() => hasTeacherScore.value ? 'teacher' : 'ai');
const displayScore = computed(() =>
hasTeacherScore.value ? formatScore(teacherScore.value) : formatScore(aiScore.value)
);
const scoreLabel = computed(() => hasTeacherScore.value ? '老师评分' : 'AI评分');
const studySecondsByProject = computed(() => Object.fromEntries(
projectStudyTimes.value.map((item) => [item.projectName, Number(item.studySeconds) || 0])
@ -130,10 +133,7 @@ const totalStudyMinutes = computed(() => Math.round(
const studyHours = computed(() => (totalStudyMinutes.value / 60).toFixed(1));
const formatScore = (value) => {
if (value === null || value === undefined || value === "") return "—";
return Number(value).toFixed(2).replace(/\.00$/, "");
};
const formatScore = (value) => Number(value || 0).toFixed(2).replace(/\.00$/, "");
const formatWeight = (weight) => `${(Number(weight || 0) * 100).toFixed(0)}%`;
const moduleColor = (index) => MODULE_COLORS[index % MODULE_COLORS.length];
const progressPercent = (module) => {
@ -256,7 +256,7 @@ const loadDashboard = async () => {
return;
}
report.value = reportResult.value?.data || { totalScore: null, aiAssessmentScore: null, teacherScore: null, modules: [] };
report.value = reportResult.value?.data || { totalScore: 0, modules: [] };
projectStudyTimes.value = projectStudyTimeResult.status === "fulfilled" && Array.isArray(projectStudyTimeResult.value?.data)
? projectStudyTimeResult.value.data
: [];
@ -333,15 +333,19 @@ onBeforeUnmount(() => {
flex-direction: column;
align-items: center;
gap: 6px;
flex-wrap: nowrap;
white-space: nowrap;
text-align: center;
color: #72809a;
strong { font-size: 26px; line-height: 1; }
.summary-unit { font-weight: 600; }
}
.score-metric { display: inline-flex; align-items: baseline; gap: 4px; }
.score-metric--ai { color: #1d4ed8; }
.score-metric--ai strong { font-size: 26px; }
.score-metric--teacher { color: #6b7280; }
.score-metric--teacher strong { font-size: 26px; }
.summary-label { font-size: 12px; font-weight: 600; }
.score-table-wrap { display: flex; align-items: center; min-width: 0; overflow-x: auto; padding: 8px 0 8px 24px; }
.score-table { width: 100%; min-width: 760px; }

@ -299,7 +299,7 @@ import * as indexApi from "@/api/teacher"
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const activeClassType = ref(userStore.schoolProductConfig?.adminClassManagementEnabled === true ? "ADMIN" : "TEACHING")
const activeClassType = ref("ADMIN")
const dialogVisible = ref(false)
const memberDialogVisible = ref(false)
const loading = ref(false)
@ -318,10 +318,11 @@ const selectedTeachingClass = ref(null)
const currentUserId = computed(() => userStore.userInfo.userId)
const currentSchoolId = computed(() => userStore.userInfo.schoolId)
const facultyManagementEnabled = computed(() => userStore.schoolProductConfig?.facultyManagementEnabled === true)
const majorManagementEnabled = computed(() => userStore.schoolProductConfig?.majorManagementEnabled === true)
const adminClassManagementEnabled = computed(() => userStore.schoolProductConfig?.adminClassManagementEnabled === true)
const isTeacherRosterMode = computed(() => userStore.schoolProductConfig?.studentRosterOwner === "TEACHER")
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)
const adminClassManagementEnabled = computed(() => userStore.schoolProductConfig?.adminClassManagementEnabled ?? legacyAdminEnabled.value)
const isTeacherRosterMode = computed(() => !facultyManagementEnabled.value && !majorManagementEnabled.value && !adminClassManagementEnabled.value)
const canCreateCurrentClass = computed(() => activeClassType.value === "ADMIN" || activeClassType.value === "TEACHING")
const paramsquery = ref({
@ -433,16 +434,13 @@ function normalizeClassType(schoolClass) {
}
function canOperateClass(schoolClass) {
if (!schoolClass || schoolClass.schoolId !== currentSchoolId.value) {
return false
}
if (schoolClass?.dataSource === "ZHIYUN") {
return false
}
if (normalizeClassType(schoolClass) === "ADMIN") {
return adminClassManagementEnabled.value
return !schoolClass?.schoolId || schoolClass.schoolId === currentSchoolId.value
}
return userStore.userInfo.teacherAdmin === true || schoolClass.createdBy === currentUserId.value
return schoolClass?.createdBy === currentUserId.value
}
function getList(options = {}) {
@ -930,17 +928,13 @@ function refreshAllClassList() {
}
onMounted(() => {
if (!adminClassManagementEnabled.value) {
activeClassType.value = "TEACHING"
}
getList()
getAllClassList()
getFacultyList()
})
// 配置未加载或刷新失败时同样不得显示行政班;只有后端明确开启才展示行政班入口。
watch(adminClassManagementEnabled, (enabled) => {
if (!enabled) {
activeClassType.value = "TEACHING"
}
}, { immediate: true })
</script>
<style lang="scss" scoped>

@ -35,8 +35,8 @@
<el-table-column label="实训任务" prop="module" min-width="260" align="center" header-align="center">
<template #default="{ row }">
<div class="name-cell">
<span class="task-badge">{{ taskNameFor(row.module).charAt(0) }}</span>
<span class="name-text">{{ taskNameFor(row.module) }}</span>
<span class="task-badge">{{ (row.module || "?").charAt(0) }}</span>
<span class="name-text">{{ row.module }}</span>
</div>
</template>
</el-table-column>
@ -70,15 +70,11 @@
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { Check, FolderOpened, Refresh, RefreshRight } from "@element-plus/icons-vue";
import * as teacherApi from "@/api/teacher";
import { listTrainingTasks } from "@/api/trainingTask";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const tasks = ref([]);
const trainingTasks = ref([]);
const taskNames = computed(() => new Map(trainingTasks.value.map((task) => [task.taskKey, task.taskName])));
const taskNameFor = (taskKey) => taskNames.value.get(taskKey) || taskKey || "?";
const status = ref("INITIALIZING");
const lastError = ref("");
const loading = ref(false);
@ -96,14 +92,10 @@ const loadTasks = async () => {
}
loading.value = true;
try {
const [res, catalog] = await Promise.all([
teacherApi.getSchoolDefaultTasks(),
listTrainingTasks({ enabledOnly: false }),
]);
trainingTasks.value = catalog.data || [];
const res = await teacherApi.getSchoolDefaultTasks();
status.value = res.data?.status || "INITIALIZING";
lastError.value = res.data?.lastError || "";
tasks.value = (res.data?.tasks || []).filter((task) => task.module !== "__TEACHING_CLASS_TASK_PUBLICATION__");
tasks.value = res.data?.tasks || [];
} finally {
loading.value = false;
}

@ -537,10 +537,7 @@ const getClassGradeStatistics = () => {
};
// 获取班级
const getClassList = () => {
const loadClasses = userStore.userInfo.teacherAdmin === true
? teacherApi.getAccessibleTeachingClasses
: teacherApi.getOwnedTeachingClasses;
loadClasses().then((res) => {
teacherApi.getOwnedTeachingClasses().then((res) => {
userStore.classList = (res.data || []).map((item) => ({
class_name: item.className,
class_id: item.schoolClassId,

File diff suppressed because it is too large Load Diff

@ -240,15 +240,11 @@ const { proxy } = getCurrentInstance();
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const currentUserId = computed(() => String(userStore.userInfo.userId || ""));
const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);
const workingCapitalList = ref([]);
const loading = ref(false);
const savingTaskId = ref("");
const classList = ref([]);
const teachingClassList = computed(() => classList.value.filter((item) =>
item.classType === "TEACHING"
&& (isManagerTeacher.value || String(item.createdBy || "") === currentUserId.value)
));
const teachingClassList = computed(() => classList.value.filter((item) => item.classType === "TEACHING"));
const scoreParams = ref({
classId: "",
index: 1,
@ -274,7 +270,7 @@ const selectedTeachingClass = computed(() => teachingClassList.value.find(
));
const canManageSelectedClass = computed(() =>
Boolean(selectedTeachingClass.value)
&& (isManagerTeacher.value || String(selectedTeachingClass.value.createdBy || "") === currentUserId.value)
&& String(selectedTeachingClass.value.createdBy || "") === currentUserId.value
);
const classActionHint = computed(() => canManageSelectedClass.value
? ""

@ -8,9 +8,9 @@
</el-select>
</div>
<el-tag v-if="classId" :type="configured ? 'success' : 'warning'">
{{ configured ? '已保存发布配置' : '默认开放首个项目前三项(未配置)' }}
{{ configured ? '已保存发布配置' : '默认全部发布(未配置)' }}
</el-tag>
<span v-if="classId" class="task-tip">{{ configured ? '仅勾选的实训任务会出现在学生端。' : '未保存配置时仅开放第一个项目的前三个任务。' }}</span>
<span v-if="classId" class="task-tip">{{ configured ? '仅勾选的实训任务会出现在学生端。' : '现有实训任务默认勾选;“综合案例实训”默认不发布,需由教师主动勾选。' }}</span>
<el-button type="primary" :disabled="!canOperateSelectedClass || !classId" :loading="saving" @click="savePublication">
<el-icon>
<Check />
@ -39,7 +39,6 @@
<svg class="collapse-icon" :class="{ collapsed: !isProjectExpanded(group.projectName) }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="6 9 12 15 18 9" />
</svg>
<span class="project-number">{{ group.projectNumber }}</span>
<span class="project-label">{{ group.projectName }}</span>
<span class="project-count">({{ group.tasks.length }})</span>
</div>
@ -56,21 +55,9 @@
@change="toggleTaskSelection(task.taskKey)"
/>
</div>
<span class="task-number">{{ task.taskNumber }}</span>
<span class="task-badge">{{ (task.taskName || "?").charAt(0) }}</span>
<span class="task-name">{{ task.taskName }}</span>
<span class="task-hint" v-if="task.taskKey === comprehensiveTaskKey">(默认不发布)</span>
<div class="reference-answer-control" @click.stop>
<span class="reference-answer-label">参考答案</span>
<el-switch
:model-value="isReferenceAnswerEnabled(task)"
:loading="Boolean(referenceAnswerSaving[task.taskKey])"
:disabled="!canOperateSelectedClass || !task.referenceAnswerUrl || Boolean(referenceAnswerSaving[task.taskKey])"
active-text="开"
inactive-text="关"
inline-prompt
@change="toggleReferenceAnswer(task, $event)"
/>
</div>
</div>
</div>
</div>
@ -103,21 +90,12 @@ const loading = ref(false);
const saving = ref(false);
const comprehensiveTaskKey = "comprehensive-case-training";
const expandedProjects = ref(new Set()); // 追踪展开的项目
const referenceAnswerSaving = reactive({});
let activeLoadGeneration = 0;
function sameValue(left, right) {
return String(left ?? "").trim() === String(right ?? "").trim();
}
const currentUserId = computed(() => userStore.userInfo.userId);
const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);
const teachingClassList = computed(() => classList.value.filter((item) =>
(item.classType === "TEACHING" || (!item.classType && item.createdBy))
&& (isManagerTeacher.value || sameValue(item.createdBy, currentUserId.value))
));
const teachingClassList = computed(() => classList.value.filter((item) => item.classType === "TEACHING" || !item.classType && item.createdBy));
const selectedClass = computed(() => teachingClassList.value.find((item) => item.schoolClassId === classId.value));
const canOperateSelectedClass = computed(() => sameValue(selectedClass.value?.createdBy, currentUserId.value));
const canOperateSelectedClass = computed(() => selectedClass.value?.createdBy === currentUserId.value);
// 按项目分组任务
const groupedTasks = computed(() => {
@ -136,20 +114,9 @@ const groupedTasks = computed(() => {
projectMap.get(projectName).tasks.push(task);
});
return Array.from(projectMap.values()).map((group, projectIndex) => ({
...group,
projectNumber: String(projectIndex + 1),
tasks: group.tasks.map((task, taskIndex) => ({
...task,
taskNumber: `${projectIndex + 1}.${taskIndex + 1}`,
})),
}));
return Array.from(projectMap.values());
});
function defaultPublishedTaskKeys() {
return groupedTasks.value[0]?.tasks.slice(0, 3).map((task) => task.taskKey) || [];
}
// 判断项目是否展开
function isProjectExpanded(projectName) {
return expandedProjects.value.has(projectName);
@ -214,29 +181,6 @@ function toggleTaskSelection(taskKey) {
}
}
function isReferenceAnswerEnabled(task) {
return task?.referenceAnswerEnabled === true;
}
async function toggleReferenceAnswer(task, enabled) {
if (!canOperateSelectedClass.value || !classId.value || !task?.taskKey) return;
const previous = task.referenceAnswerEnabled;
task.referenceAnswerEnabled = enabled === true;
referenceAnswerSaving[task.taskKey] = true;
try {
await indexApi.updateTaskReferenceAnswerVisibility({
teachingClassId: classId.value,
taskKey: task.taskKey,
enabled: task.referenceAnswerEnabled,
});
proxy.$modal.msgSuccess(task.referenceAnswerEnabled ? "参考答案已开放" : "参考答案已关闭");
} catch (error) {
task.referenceAnswerEnabled = previous;
} finally {
delete referenceAnswerSaving[task.taskKey];
}
}
async function loadClasses() {
const res = await indexApi.getClassListBySchoolId({ schoolId: userStore.userInfo.schoolId });
classList.value = res.data || [];
@ -291,7 +235,9 @@ async function loadPublication() {
configured.value = res.data?.configured === true;
selectedTaskKeys.value = configured.value
? (res.data?.taskKeys || [])
: defaultPublishedTaskKeys();
: tasks.value
.filter((task) => task.taskKey !== comprehensiveTaskKey)
.map((task) => task.taskKey);
} finally {
if (requestGeneration === activeLoadGeneration) loading.value = false;
}
@ -433,19 +379,6 @@ onMounted(async () => {
flex: 1;
}
.project-number,
.task-number {
flex-shrink: 0;
color: var(--edu-primary);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
.project-number {
min-width: 24px;
font-size: 15px;
}
.project-count {
font-size: 13px;
color: #9ca3af;
@ -513,20 +446,6 @@ onMounted(async () => {
font-weight: 600;
}
.task-number {
min-width: 38px;
font-size: 13px;
}
.reference-answer-control {
display: inline-flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
color: var(--text-body);
font-size: 12px;
}
.task-hint {
font-size: 12px;
color: #9ca3af;

@ -13,8 +13,7 @@
<div class="studentLayout student-task-preview-root">
<section class="app-main">
<main ref="previewRoot" class="student-task-readonly-preview" @click.capture="guardPreviewInteraction" @keydown.capture="guardPreviewInteraction">
<!-- :key 用 previewKey:同任务换学生时强制重挂载,保证学生页重新按新上下文拉取作答 -->
<component v-if="previewComponent" :is="previewComponent" :key="activePreviewKey" v-bind="previewProps" />
<component v-if="previewComponent" :is="previewComponent" v-bind="previewProps" />
<el-empty v-else :description="emptyDescription" :image-size="112" />
</main>
</section>
@ -23,8 +22,7 @@
<script setup>
import { ElMessage } from "element-plus";
import { readTrainingReviewPreview } from "@/utils/trainingReviewPreview";
import { getPendingRequestCount } from "@/utils/request";
import { getTrainingReviewPreviewContext } from "@/utils/trainingReviewPreview";
import { studentTaskPreviewComponentByKey, studentTaskPreviewPropsByKey } from "./studentTaskPreviewMap";
const route = useRoute();
@ -32,211 +30,50 @@ const previewComponent = shallowRef(null);
const previewProps = ref({});
const emptyDescription = ref("正在加载学生任务页面");
const previewRoot = ref();
const activeTaskKey = ref("");
const activePreviewKey = ref("");
const previewBooting = ref(true);
const PREVIEW_HEIGHT_MESSAGE = "teacher-task-review-preview-height";
/* 与父页 TaskReviewPanel.vue 约定的热切换协议 */
const PARENT_LOAD_MESSAGE = "teacher-task-review-preview-load";
const PARENT_READY_MESSAGE = "teacher-task-review-preview-ready";
/* 闸门放行后通知父页揭幕(加载遮罩画在教师端预览容器上,不在学生页内) */
const PARENT_LOADED_MESSAGE = "teacher-task-review-preview-loaded";
/* 放行闸门参数:DOM 静默判定窗口 / 最短遮罩时长 / 最长强制放行兜底 */
const SETTLE_DELAY = 350;
const MIN_HOLD = 250;
const FORCE_REVEAL_DELAY = 8000;
let resizeObserver;
let mutationObserver;
let animationFrame;
let loadVersion = 0;
let settleTimer = 0;
let forceRevealTimer = 0;
let bootStartAt = 0;
/*
* 预览 iframe 内禁用 localStorage(中心化隔离,覆盖所有学生页)。
*
* 根因:多个学生实训页有「本地草稿」机制,草稿 key 取当前登录用户——
* 教师预览时所有学生共用教师这一个草稿键。预览学生 A 回显作答会触发
* persistDraft 把 A 的作答写进教师草稿;切换到未作答学生 B 时 loadDraft
* 先行恢复,B 的页面就出现了 A 的答题记录(跨学生数据污染)。
*
* 预览是只读的:用内存假 localStorage 顶替,旧草稿读不到、新写入不留存;
* sessionStorage 不受影响(评阅预览上下文由父页写在 sessionStorage)。
*/
function isolatePreviewStorage() {
if (typeof window === "undefined") return;
try {
const memoryStore = new Map();
const keys = () => Array.from(memoryStore.keys());
const shim = {
getItem: (key) => (memoryStore.has(String(key)) ? memoryStore.get(String(key)) : null),
setItem: (key, value) => { memoryStore.set(String(key), String(value)); },
removeItem: (key) => { memoryStore.delete(String(key)); },
clear: () => memoryStore.clear(),
key: (index) => keys()[index] ?? null,
get length() { return memoryStore.size; },
};
Object.defineProperty(window, "localStorage", { configurable: true, get: () => shim });
} catch (_) {
/* 个别隐私模式下 localStorage 本就不可用,忽略 */
}
}
isolatePreviewStorage();
/*
* 性能关键点:iframe 只冷启动一次(首次靠路由 query 加载),
* 之后父页切换学生/任务时通过 postMessage 热切换动态组件,
* 不再整页重载 SPA。loadVersion 防止两次切换的异步加载交错覆盖。
*
* 数据隔离关键点:切换学生必须让学生页组件「重新加载」(全新实例),
* 因此这里刻意分两阶段交换——
* 1) 先置空并 await nextTick():确保旧实例真正卸载、其 DOM 与副作用清空;
* 2) 再挂载新实例。
* 若把置空与赋值放在同一 tick,Vue 会把两次渲染合并成一次 keyed patch,
* 新旧实例短暂并存,旧实例里未完成的异步回填可能把上一个学生的数据带进来。
*/
async function loadPreview(taskKey, previewKey) {
const version = ++loadVersion;
clearBootTimers();
async function loadPreview() {
previewComponent.value = null;
previewProps.value = {};
emptyDescription.value = "正在加载学生任务页面";
activeTaskKey.value = taskKey;
activePreviewKey.value = previewKey;
previewBooting.value = true;
bootStartAt = Date.now();
syncPreviewLocation(taskKey, previewKey);
const preview = readTrainingReviewPreview(previewKey);
const taskKey = String(route.query.taskKey || "");
const preview = getTrainingReviewPreviewContext();
const loader = studentTaskPreviewComponentByKey[taskKey];
if (!preview || preview.taskKey !== taskKey) {
emptyDescription.value = "学生作答预览已失效,请返回任务评阅重新选择学生";
revealPreview(version);
return;
}
if (!loader) {
emptyDescription.value = "该实训任务暂不支持页面预览";
revealPreview(version);
return;
}
try {
const component = (await loader()).default;
if (version !== loadVersion) return;
/* 阶段一:等旧实例卸载完成,避免新旧实例并存导致数据串味 */
await nextTick();
if (version !== loadVersion) return;
/* 阶段二:以全新实例挂载(:key 变化 = 完整重建) */
previewComponent.value = (await loader()).default;
previewProps.value = studentTaskPreviewPropsByKey[taskKey]?.(taskKey) || {};
previewComponent.value = component;
await nextTick();
if (version !== loadVersion) return;
armReadyGate(version);
schedulePreviewHeight();
} catch (_) {
if (version !== loadVersion) return;
emptyDescription.value = "学生任务页面加载失败,请刷新后重试";
revealPreview(version);
}
}
/*
* 把 iframe 地址栏 query 同步为当前预览上下文。
* 关键:getStudentTrainingAnswer / isTrainingReviewPreviewRequest 等都是从
* window.location 解析 reviewPreviewKey 再查 sessionStorage。热切换只改内部状态
* 不动 URL 的话,iframe 地址栏还停留在首次冷启动的旧 key,旧上下文已被父页删除,
* 页面会误判「不在预览模式」→ 拿教师 token 真发 /api/student-training-answers/:taskKey,
* 既发错请求也踩只读守卫。replaceState 不触发路由 watch,不会造成重复加载。
*/
function syncPreviewLocation(taskKey, previewKey) {
if (typeof window === "undefined" || !window.history?.replaceState) return;
const query = `taskKey=${encodeURIComponent(taskKey)}&reviewPreviewKey=${encodeURIComponent(previewKey)}`;
const hash = `#${route.path}?${query}`;
window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}${hash}`);
}
/*
* 放行闸门:组件挂载后,等待「无进行中请求 + DOM 连续 SETTLE_DELAY 无变化
* + 最短遮罩时长」才放行;FORCE_REVEAL_DELAY 兜底防止个别页面长轮询导致永不放行。
*/
function armReadyGate(version) {
scheduleSettleCheck(version);
/* 冷启动时 watch 与 onMounted 会各调一次,强制放行定时器先清再设,避免提前触发 */
if (forceRevealTimer) clearTimeout(forceRevealTimer);
forceRevealTimer = setTimeout(() => revealPreview(version), FORCE_REVEAL_DELAY);
}
function scheduleSettleCheck(version) {
if (settleTimer) clearTimeout(settleTimer);
settleTimer = setTimeout(() => checkSettled(version), SETTLE_DELAY);
}
function checkSettled(version) {
settleTimer = 0;
if (version !== loadVersion) return;
if (getPendingRequestCount() > 0 || Date.now() - bootStartAt < MIN_HOLD) {
scheduleSettleCheck(version);
return;
}
revealPreview(version);
}
function revealPreview(version) {
if (version !== loadVersion) return;
clearBootTimers();
previewBooting.value = false;
/* 通知父页:页面已就绪,可以揭掉教师端预览容器上的加载遮罩 */
window.parent?.postMessage({
type: PARENT_LOADED_MESSAGE,
previewKey: activePreviewKey.value,
}, window.location.origin);
}
function clearBootTimers() {
if (settleTimer) clearTimeout(settleTimer);
if (forceRevealTimer) clearTimeout(forceRevealTimer);
settleTimer = 0;
forceRevealTimer = 0;
}
function loadPreviewFromRoute() {
loadPreview(String(route.query.taskKey || ""), String(route.query.reviewPreviewKey || ""));
}
watch(() => [route.query.taskKey, route.query.reviewPreviewKey], loadPreviewFromRoute, { immediate: true });
function onParentMessage(event) {
if (event.origin !== window.location.origin) return;
const data = event.data || {};
if (data.type !== PARENT_LOAD_MESSAGE) return;
loadPreview(String(data.taskKey || ""), String(data.previewKey || ""));
}
watch(() => [route.query.taskKey, route.query.reviewPreviewKey], loadPreview, { immediate: true });
onMounted(() => {
window.addEventListener("message", onParentMessage);
resizeObserver = new ResizeObserver(schedulePreviewHeight);
if (previewRoot.value) resizeObserver.observe(previewRoot.value);
mutationObserver = new MutationObserver(onPreviewDomChanged);
mutationObserver = new MutationObserver(schedulePreviewHeight);
if (previewRoot.value) mutationObserver.observe(previewRoot.value, { childList: true, subtree: true });
schedulePreviewHeight();
/* 首次冷启动也要走放行闸门(组件还没挂载,先保持遮罩) */
armReadyGate(loadVersion);
/* 通知父页:iframe 已就绪,可以开始接收热切换消息 */
window.parent?.postMessage({ type: PARENT_READY_MESSAGE }, window.location.origin);
});
onBeforeUnmount(() => {
window.removeEventListener("message", onParentMessage);
resizeObserver?.disconnect();
mutationObserver?.disconnect();
clearBootTimers();
if (animationFrame) cancelAnimationFrame(animationFrame);
});
function onPreviewDomChanged() {
schedulePreviewHeight();
/* 放行闸门期间 DOM 仍在变(接口回填、图片渲染),推迟放行 */
if (previewBooting.value) scheduleSettleCheck(loadVersion);
}
function schedulePreviewHeight() {
if (animationFrame) cancelAnimationFrame(animationFrame);
animationFrame = requestAnimationFrame(reportPreviewHeight);
@ -252,7 +89,7 @@ function reportPreviewHeight() {
));
window.parent?.postMessage({
type: PREVIEW_HEIGHT_MESSAGE,
previewKey: activePreviewKey.value,
previewKey: String(route.query.reviewPreviewKey || ""),
height,
}, window.location.origin);
}
@ -277,7 +114,7 @@ function guardPreviewInteraction(event) {
/*
* 步骤导航容器白名单:
* 只靠文案(第N步/上一步/下一步)判断太窄——行业需求分析、竞争环境分析等页面的步骤胶囊
* 文案是「01 PEST宏观环境分析 切换 →」,不匹配任何关键词,会被当成普通按钮拦掉,
* 文案是「01 PEST宏观环境分析 点击切换 →」,不匹配任何关键词,会被当成普通按钮拦掉,
* 表现为「点了没反应、也不报错」。凡落在已知步骤导航容器里的控件一律放行。
*/
const PREVIEW_STEP_NAV_CONTAINER = [
@ -298,7 +135,7 @@ function isStepNavigation(element) {
if (element.closest(PREVIEW_STEP_NAV_CONTAINER)) return true;
const label = String(element.getAttribute("aria-label") || "");
const text = `${label} ${String(element.textContent || "")}`.replace(/\s+/g, " ").trim();
return /(上一步|下一步|第\s*\d+\s*步|步骤\s*\d+|切换.*步骤|步骤.*切换)/.test(text);
return /(上一步|下一步|第\s*\d+\s*步|步骤\s*\d+|切换.*步骤|步骤.*切换|点击切换|当前步骤)/.test(text);
}
/* 只读态被拦截的操作要给提示,避免教师以为页面坏了 */

@ -214,9 +214,10 @@ const dialogVisible = ref(false)
const loading = ref(false)
const currentUserId = computed(() => userStore.userInfo.userId)
const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true || String(userStore.userInfo.roleId || userStore.userInfo.role) === "1")
const facultyManagementEnabled = computed(() => userStore.schoolProductConfig?.facultyManagementEnabled === true)
const majorManagementEnabled = computed(() => userStore.schoolProductConfig?.majorManagementEnabled === true)
const adminClassManagementEnabled = computed(() => userStore.schoolProductConfig?.adminClassManagementEnabled === true)
const legacyOrganizationManagementEnabled = computed(() => userStore.schoolProductConfig?.organizationMode !== "TEACHING_CLASS_ONLY")
const facultyManagementEnabled = computed(() => userStore.schoolProductConfig?.facultyManagementEnabled ?? legacyOrganizationManagementEnabled.value)
const majorManagementEnabled = computed(() => userStore.schoolProductConfig?.majorManagementEnabled ?? legacyOrganizationManagementEnabled.value)
const adminClassManagementEnabled = computed(() => userStore.schoolProductConfig?.adminClassManagementEnabled ?? legacyOrganizationManagementEnabled.value)
const isOrganizationManagementEnabled = computed(() => facultyManagementEnabled.value || majorManagementEnabled.value || adminClassManagementEnabled.value)
const formatDate = (cellValue) => {
const numeric = Number(cellValue)

@ -46,7 +46,7 @@
默认任务
</el-tag>
</div>
<el-button v-if="canOperateSelectedClass" type="danger" plain class="toolbar-btn toolbar-btn-danger" :loading="restoring" @click="restoreAllTasksDefaults">
<el-button v-if="selectedTeachingClass" type="danger" plain class="toolbar-btn toolbar-btn-danger" :loading="restoring" @click="restoreAllTasksDefaults">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 12a9 9 0 109-9 9.75 9.75 0 00-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
@ -148,7 +148,7 @@
<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
{{ canOperateSelectedClass ? "编辑任务" : "查看详情" }}
{{ selectedTeachingClass ? "编辑任务" : "查看详情" }}
</el-button>
</div>
@ -279,7 +279,7 @@
<span class="section-number">03</span>
<div class="section-info">
<h4>资料与步骤</h4>
<p>上传案例资料、案例数据、实训指导手册、AI辅助指导手册与参考答案,配置实训步骤</p>
<p>上传案例资料、案例数据、实训指导手册与AI排错指导手册,配置实训步骤</p>
</div>
</div>
<div v-for="slot in materialSlots" :key="slot.key" class="material-row">
@ -295,7 +295,7 @@
</div>
</div>
<div class="material-ops">
<el-upload v-if="!isReadonly" action="#" :auto-upload="false" :show-file-list="false" :accept="slot.accept" :on-change="(file) => handleMaterialChange(slot.key, file)">
<el-upload v-if="!isReadonly" action="#" :auto-upload="false" :show-file-list="false" :on-change="(file) => handleMaterialChange(slot.key, file)">
<el-button type="primary" :loading="uploadingField === slot.key" class="upload-btn">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />
@ -312,7 +312,6 @@
<!-- 第一步选择题:编辑入口固定在第一个步骤行旁,仅三个白名单任务显示 -->
<StepOneQuestionBankPicker v-model:visible="bankPickerVisible" :load-questions="loadBankQuestions" :existing="taskForm.stepOneQuestions" @confirm="handleBankConfirm" />
<StepOneChoiceQuestionEditor v-model:visible="choiceEditorVisible" v-model="taskForm.stepOneQuestions" :task-name="taskForm.title" :load-questions="loadBankQuestions" />
<InterviewRecordsEditor v-if="taskForm.taskKey === 'target-user-profile'" v-model:visible="interviewEditorVisible" v-model="taskForm.interviewRecords" />
<!-- 步骤数量与顺序固定,仅允许修改名称 -->
<el-form-item label="步骤名称:">
@ -330,7 +329,6 @@
<el-button v-if="!isReadonly" type="primary" class="step-question-btn" @click="choiceEditorVisible = true">编辑题目{{ stepOneQuestionCount ? `(${stepOneQuestionCount}题)` : "" }}</el-button>
<span v-else class="step-question-tag">已配置 {{ stepOneQuestionCount }} 道题</span>
</template>
<el-button v-if="!isReadonly && taskForm.taskKey === 'target-user-profile' && index === 3" type="primary" plain class="step-interview-btn" @click="interviewEditorVisible = true">编辑访谈记录</el-button>
</div>
</div>
</div>
@ -370,8 +368,6 @@ import * as indexApi from "@/api/teacher";
import useUserStore from "@/store/modules/user";
import StepOneChoiceQuestionEditor from "@/views/components/StepOneChoiceQuestionEditor.vue";
import StepOneQuestionBankPicker from "@/views/components/StepOneQuestionBankPicker.vue";
import InterviewRecordsEditor from "@/views/components/InterviewRecordsEditor.vue";
import { parseInterviewRecords } from "@/utils/interviewRecords";
import { parseStepOneChoiceQuestions, supportsStepOneChoiceQuestions } from "@/utils/stepOneChoiceQuestions";
import { getQuestions } from "@/api/exam";
@ -387,14 +383,12 @@ const restoring = ref(false);
const uploadingField = ref("");
const choiceEditorVisible = ref(false);
const bankPickerVisible = ref(false);
const interviewEditorVisible = ref(false);
// 五类资料槽位:key 对应 taskForm 的 `${key}Name` / `${key}Url` 字段。
// 四类资料槽位:key 对应 taskForm 的 `${key}Name` / `${key}Url` 字段,不限制文件类型
const materialSlots = [
{ key: "material", label: "案例资料" },
{ key: "trainingData", label: "案例数据" },
{ key: "guideManual", label: "实训指导手册" },
{ key: "aiManual", label: "AI辅助指导手册" },
{ key: "referenceAnswer", label: "参考答案", accept: ".pdf,application/pdf" },
];
const tasks = ref([]);
const classList = ref([]);
@ -403,7 +397,7 @@ const dialogVisible = ref(false);
const dialogMode = ref("view");
const taskForm = reactive(createEmptyTask());
const currentUserId = computed(() => userStore.userInfo.userId);
const isManagerTeacher = computed(() => userStore.userInfo.teacherAdmin === true);
const isReadonly = computed(() => dialogMode.value === "view");
const stepOneQuestionCount = computed(() => taskForm.stepOneQuestions?.length || 0);
const projects = computed(() => [...new Set(tasks.value.map((task) => task.project).filter(Boolean))]);
const projectOptions = computed(() => {
@ -414,16 +408,12 @@ const projectOptions = computed(() => {
});
const teachingClassList = computed(() => {
return classList.value.filter((schoolClass) => {
return normalizeClassType(schoolClass) === "TEACHING"
&& (isManagerTeacher.value || String(schoolClass.createdBy || "") === String(currentUserId.value || ""));
return normalizeClassType(schoolClass) === "TEACHING" && String(schoolClass.createdBy || "") === String(currentUserId.value || "");
});
});
const selectedTeachingClass = computed(() => {
return teachingClassList.value.find((schoolClass) => schoolClass.schoolClassId === selectedTeachingClassId.value);
});
const canOperateSelectedClass = computed(() => Boolean(selectedTeachingClass.value)
&& String(selectedTeachingClass.value.createdBy || "") === String(currentUserId.value || ""));
const isReadonly = computed(() => dialogMode.value === "view" || !canOperateSelectedClass.value);
const filteredTasks = computed(() => {
const text = keyword.value.trim();
@ -524,11 +514,11 @@ function viewTask(task) {
}
function editTask(task) {
openTaskDialog(task, canOperateSelectedClass.value ? "edit" : "view");
openTaskDialog(task, "edit");
}
function handleTaskAction(task) {
if (!canOperateSelectedClass.value) {
if (!selectedTeachingClass.value) {
viewTask(task);
return;
}
@ -552,10 +542,7 @@ function createEmptyTask() {
guideManualUrl: "",
aiManualName: "",
aiManualUrl: "",
referenceAnswerName: "",
referenceAnswerUrl: "",
stepOneQuestions: [],
interviewRecords: parseInterviewRecords(),
steps: createBuiltinSteps(),
sort: 0,
enabled: true,
@ -590,7 +577,6 @@ function normalizeTask(task) {
const trainingData = normalizeMaterial(task.trainingDataName, task.trainingDataUrl);
const guideManual = normalizeMaterial(task.guideManualName, task.guideManualUrl);
const aiManual = normalizeMaterial(task.aiManualName, task.aiManualUrl);
const referenceAnswer = normalizeMaterial(task.referenceAnswerName, task.referenceAnswerUrl);
return {
id: task.id,
taskKey: task.taskKey,
@ -607,10 +593,7 @@ function normalizeTask(task) {
guideManualUrl: guideManual.url,
aiManualName: aiManual.name,
aiManualUrl: aiManual.url,
referenceAnswerName: referenceAnswer.name,
referenceAnswerUrl: referenceAnswer.url,
stepOneQuestions: parseStepOneChoiceQuestions(task.stepOneQuestions),
interviewRecords: parseInterviewRecords(task.interviewRecords),
steps: normalizeSteps(parseArray(task.steps, createBuiltinSteps())),
sort: task.sort || 0,
enabled: task.enabled !== false,
@ -700,7 +683,6 @@ function cloneTask(task) {
return {
...task,
objectives: [...(task.objectives?.length ? task.objectives : [""])],
interviewRecords: parseInterviewRecords(task.interviewRecords),
steps: normalizeSteps(task.steps?.length ? task.steps : createBuiltinSteps()),
};
}
@ -717,13 +699,8 @@ function removeObjective(index) {
async function handleMaterialChange(slotKey, file) {
const rawFile = file?.raw;
if (!rawFile) return;
if (slotKey === "referenceAnswer" && !isPdfFile(rawFile)) {
proxy?.$modal?.msgError?.("参考答案仅支持 PDF 文件(.pdf)");
return;
}
const data = new FormData();
data.append("file", rawFile);
data.append("materialType", slotKey);
uploadingField.value = slotKey;
try {
const res = await uploadTrainingTaskMaterial(data);
@ -737,11 +714,6 @@ async function handleMaterialChange(slotKey, file) {
}
}
function isPdfFile(file) {
const name = String(file?.name || "").trim().toLowerCase();
return name.endsWith(".pdf");
}
function clearMaterial(slotKey) {
taskForm[`${slotKey}Name`] = "";
taskForm[`${slotKey}Url`] = "";
@ -764,7 +736,7 @@ async function submitTask() {
}
async function restoreTaskDefault() {
if (!canOperateSelectedClass.value || !taskForm.taskKey) return;
if (!selectedTeachingClass.value || !taskForm.taskKey) return;
const confirmed = await confirmRestoreDefault("恢复此任务默认内容");
if (!confirmed) return;
restoring.value = true;
@ -779,7 +751,7 @@ async function restoreTaskDefault() {
}
async function restoreAllTasksDefaults() {
if (!canOperateSelectedClass.value) return;
if (!selectedTeachingClass.value) return;
const confirmed = await confirmRestoreDefault("恢复本班全部默认任务");
if (!confirmed) return;
restoring.value = true;
@ -854,10 +826,7 @@ function buildPayload() {
guideManualUrl: taskForm.guideManualUrl,
aiManualName: taskForm.aiManualName,
aiManualUrl: taskForm.aiManualUrl,
referenceAnswerName: taskForm.referenceAnswerName,
referenceAnswerUrl: taskForm.referenceAnswerUrl,
stepOneQuestions: JSON.stringify(taskForm.stepOneQuestions || []),
interviewRecords: JSON.stringify(taskForm.interviewRecords || []),
sort: taskForm.sort,
enabled: taskForm.enabled,
};
@ -1607,8 +1576,6 @@ function buildPayload() {
flex: 1;
}
.step-interview-btn { margin-left: 8px; white-space: nowrap; }
.step-question-btn {
flex-shrink: 0;
height: 32px;

@ -33,13 +33,11 @@
:aria-current="activeStep === index + 1 ? 'step' : undefined" @click="goToStepFromTab(index + 1)">
<span class="step-marker">{{ String(index + 1).padStart(2, "0") }}</span><span class="step-copy"><b>{{ step
}}</b><small>{{ activeStep === index + 1
? '' : '' }}</small></span>
? '当前步骤 →' : '点击切换 →' }}</small></span>
</button>
<span v-if="index < trainingSteps.length - 1" class="step-connector" aria-hidden="true" />
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="activeStep" :disabled="saving" />
<section v-if="activeStep === 1">
<header class="step-heading">
@ -168,12 +166,7 @@
<p class="scoring-guide">通过Min-Max归一法将各维度原始数据转换为0-10分标准化得分,计算规则如下:<br>
正向指标(越大越好,如搜索量、点击率、转化率、访客数、匹配度),得分=(该渠道值−最小值)/(最大值−最小值)× 10<br>
逆向指标(越小越好,如供需比、CPC):得分=(最大值−该渠道值)/(最大值−最小值)× 10</p>
<div class="table-actions">
<input ref="scoreExcelInput" type="file" accept=".xlsx,.xls" hidden @change="importScoreExcel" />
<el-button :disabled="!scoreRows.length || importingScores" @click="downloadScoreTemplate">下载导入模板</el-button>
<el-button type="primary" :loading="importingScores" :disabled="!scoreRows.length || saving || validating"
@click="scoreExcelInput?.click()">导入 Excel</el-button>
<el-button type="primary" plain @click="exportScoreRows"><el-icon>
<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">
@ -210,7 +203,6 @@
</table>
</div>
<p class="hint">渠道名称同步第二步,权重同步第一步。每项得分乘以对应权重(按百分比折算)并相加得到加权得分;系统会依据已保存的前两步数据检测计算结果。</p>
<p class="hint">可下载模板批量填写后导入(支持 .xlsx、.xls)。导入更新文件中同名渠道的得分,空白得分会清空,其他渠道保留;权重不变,导入后请保存进度。</p>
<p class="step-three-notice">说明:渠道来自第二步,权重来自第一步;每个维度得分乘以权重后相加即为加权得分。计算结果不一致时仍可进入下一步,系统会记录检测结果,供 AI
助评扣分参考。</p>
</section>
@ -279,19 +271,14 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, Download, Minus, Plus } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { ElMessage } from "element-plus"
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue"
import TrainingTaskToolbar from "@/views/components/TrainingTaskToolbar.vue"
import { getTrainingTaskByKey } from "@/api/trainingTask"
import { deleteStudentTrainingAnswer, getStudentTrainingAnswer, saveStudentTrainingAnswer, validateReleaseChannelEvaluationStepOne, validateReleaseChannelEvaluationStepTwo, validateReleaseChannelEvaluationStepThree, validateReleaseChannelEvaluationStepFour } from "@/api/studentTrainingAnswer"
import { parseTrainingArray } from "@/views/training/taskKeyMap"
import { parseScoreExcelRows, scoreExcelColumns } from "./releaseChannelScoreExcel"
const TASK_KEY = "release-channel-evaluation"
const RELEASE_CHANNEL_GUIDE_URL = "/file/training-materials/release-channel-evaluation/21.实训操作说明.docx"
@ -300,8 +287,6 @@ const briefOpen = ref(true)
const taskConfig = ref(null)
const saving = ref(false)
const validating = ref(false)
const scoreExcelInput = ref(null)
const importingScores = ref(false)
let nextId = 1
const makeRow = (values = {}) => ({ id: nextId++, ...values })
const defaultWeightRows = () => [
@ -384,62 +369,9 @@ function downloadBuiltInFile(url, fileName) {
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") }
async function downloadScoreTemplate() {
try {
const XLSX = await import("xlsx")
const workbook = XLSX.utils.book_new()
const headers = scoreExcelColumns(scoringMetrics).map((column) => column.label)
const sheet = XLSX.utils.aoa_to_sheet([headers, ...scoreRows.value.map((row) => [row.channel])])
sheet["!cols"] = headers.map(() => ({ wch: 22 }))
XLSX.utils.book_append_sheet(workbook, sheet, "归一化得分")
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([
["填写说明"],
["渠道名称来自第二步,请保持一致;权重沿用第一步,无需在 Excel 中填写。"],
["七项维度得分填写 0–10 的数字,最多 1 位小数;加权得分填写非负数字,最多 2 位小数。"],
["请自行计算并填写得分,模板不会自动计算或填入答案。"],
["导入更新同名渠道的得分,空白得分会清空;未出现在文件中的渠道保持不变。"],
["只读取第一张工作表,导入后请点击页面的保存按钮。"],
]), "填写说明")
XLSX.writeFile(workbook, "产品发布渠道评估-归一化得分导入模板.xlsx")
} catch (error) { ElMessage.error("模板下载失败,请重试") }
}
async function importScoreExcel(event) {
const input = event.target
const file = input.files?.[0]
if (!file || importingScores.value || saving.value || validating.value) return
importingScores.value = true
const currentRows = scoreRows.value
try {
if (!/\.(xlsx|xls)$/i.test(file.name)) throw new Error("请选择 .xlsx 或 .xls 格式的 Excel 文件")
const XLSX = await import("xlsx")
const workbook = XLSX.read(await file.arrayBuffer(), { type: "array" })
const sheet = workbook.Sheets[workbook.SheetNames[0]]
if (!sheet) throw new Error("Excel 中没有工作表")
const rows = parseScoreExcelRows(XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false, defval: "", blankrows: true, range: 0 }), scoringMetrics, currentRows.map((row) => row.channel))
try {
await ElMessageBox.confirm(`将更新 ${rows.length} 个同名渠道的得分,空白得分会清空,其他渠道和权重保留。是否继续?`, "导入归一化得分", { type: "warning", confirmButtonText: "导入", cancelButtonText: "取消" })
} catch { return }
if (scoreRows.value !== currentRows || activeStep.value !== 3) throw new Error("页面数据已变化,请回到归一化评分重新导入")
const imported = new Map(rows.map((row) => [row.channel, row]))
scoreRows.value = currentRows.map((row) => {
const values = imported.get(String(row.channel).trim())
return values ? { ...row, weightedScore: values.weightedScore, dimensions: row.dimensions.map((metric) => ({ ...metric, score: values[metric.key] })) } : row
})
ElMessage.success(`已导入 ${rows.length} 个渠道的得分,请保存进度`)
} catch (error) { ElMessage.error(error?.message || "Excel 导入失败,请检查文件内容") }
finally { importingScores.value = false; input.value = "" }
}
function restoreRows(raw, target, defaults, fields) { try { const saved = typeof raw === "string" ? JSON.parse(raw || "{}") : raw; if (!Array.isArray(saved?.rows)) return; const keyField = fields[0]; const presetFlags = new Map(defaults().map((row) => [row[keyField], Boolean(row.preset)])); target.value = saved.rows.map((row) => { const value = Object.fromEntries(fields.map((field) => [field, row?.[field]])); if (target === weightRows) return makeRow({ ...value, suggestion: weightSuggestions[value.dimension] || "", preset: presetFlags.get(value[keyField]) || false }); if (target === channelRows) return makeRow({ ...value, preset: presetFlags.get(value[keyField]) || false }); return makeRow(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() })
const numericExcelTables = excelComputed(() => {
if (activeStep.value === 1) return [et('weights', '发布渠道评估权重', weightRows.value, [fc('dimension', '评估维度'), rc('weight', '权重(%)', {precision: 2})])];
if (activeStep.value === 2) return [et('channels', '发布渠道基础数据', channelRows.value, [tc('channel', '渠道', {maxLength: 30}), nc('dailySearchVolume', '日均搜索量', {precision: 0}), nc('supplyDemandRatio', '供需比', {precision: 4}), rc('averageClickRate', '平均点击率(%)', {precision: 2}), nc('averageCpc', '平均CPC(元)', {precision: 2}), rc('averageConversionRate', '平均转化率(%)', {precision: 2}), nc('existingVisitorCount', '现有访客数', {precision: 0}), nc('matchingScore', '匹配度', {min: 1, max: 100, precision: 0})], {maxRows: 10000, createRow: () => makeRow({channel: ''})})];
if (activeStep.value === 4) return [et('ranking', '发布渠道排名', rankingRows.value, [tc('channel', '渠道', {maxLength: 30}), nc('weightedScore', '加权得分', {precision: 2})])];
return [];
});
</script>
<style scoped lang="scss">

@ -33,13 +33,11 @@
:aria-current="activeStep === index + 1 ? 'step' : undefined" @click="goToStepFromTab(index + 1)">
<span class="step-marker">{{ String(index + 1).padStart(2, "0") }}</span>
<span class="step-copy"><strong class="step-name">{{ step }}</strong><span class="step-action">{{
activeStep === index + 1 ? '' : '' }} →</span></span>
activeStep === index + 1 ? '当前步骤' : '点击切换' }} →</span></span>
</button>
<span v-if="index < trainingSteps.length - 1" class="step-connector" aria-hidden="true" />
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="activeStep" :disabled="saving" />
<section v-if="activeStep === 1" class="budget-form">
<header class="step-heading">
@ -320,10 +318,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { computed, onMounted, ref } from "vue"
import { ArrowLeft, ArrowRight, CircleCheck, Minus, Plus } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
@ -450,13 +444,6 @@ function readRows(raw) { try { const saved = typeof raw === "string" ? JSON.pars
async function loadReleaseChannels() { try { const result = await getStudentTrainingAnswer(RELEASE_CHANNEL_TASK_KEY); const saved = typeof result?.data?.step2Answer === "string" ? JSON.parse(result.data.step2Answer || "{}") : result?.data?.step2Answer || {}; availableChannels.value = [...new Set((Array.isArray(saved?.rows) ? saved.rows : []).map((row) => String(row?.channel || "").trim()).filter(Boolean))] } catch (error) { availableChannels.value = [] } }
async function loadProgress() { try { const result = await getStudentTrainingAnswer(TASK_KEY); const answer = result?.data || {}; restoreBudget(answer.step1Answer); syncStrategyRows(readRows(answer.step2Answer)); restorePerformance(answer.step3Answer); restoreEvaluation(answer.step4Answer); activeStep.value = Math.min(Math.max(Number(answer.currentStep) || 1, 1), 4) } catch (error) { restoreBudget(); syncStrategyRows(); restorePerformance(); restoreEvaluation() } }
onMounted(async () => { try { const result = await getTrainingTaskByKey(TASK_KEY); taskConfig.value = result?.data || null } catch (error) { taskConfig.value = null } await Promise.all([loadReleaseChannels(), loadProgress()]) })
const numericExcelTables = excelComputed(() => {
if (activeStep.value === 1) return [et('budget', '投放预算分配', budgetRows.value, [tc('channel', '渠道', {values: availableChannels.value}), tc('channelPositioning', '渠道定位', {values: channelPositionings}), rc('budgetPercentage', '预算占比(%)', {precision: 2}), ...[['coldStartBudget', '冷启动预算(元)'], ['growthBudget', '增长期预算(元)'], ['stableBudget', '稳定期预算(元)']].map(([k,l]) => nc(k,l,{precision: 2}))], {maxRows: 5, createRow: () => makeRow()})];
if (activeStep.value === 3) return [et('performance', '投放数据核算', performanceRows.value, [fc('channel', '渠道'), nc('impressions', '曝光量', {precision: 0}), nc('clicks', '点击量', {precision: 0}), nc('clickRate', '点击率(%)', {percent: true, precision: 2}), nc('turnover', '成交额(元)', {precision: 2}), nc('promotionCost', '推广费用(元)', {precision: 2}), nc('actualRoi', '实际ROI', {precision: 2})])];
return [];
});
</script>
<style scoped lang="scss">
@ -1382,7 +1369,7 @@ return [];
}
}
/* 步骤:教育蓝实底 */
/* 当前步骤:教育蓝实底 */
&.active {
border-color: #2563eb !important;
background: #2563eb !important;

@ -1,46 +0,0 @@
export function scoreExcelColumns(metrics) {
return [
{ key: "channel", label: "渠道" },
...metrics.map((metric) => ({ key: metric.key, label: `${metric.dimension}得分`, alias: metric.label })),
{ key: "weightedScore", label: "加权得分" },
];
}
const headerName = (value) => String(value ?? "").replace(/\s/g, "");
const hasValue = (row) => Array.isArray(row) && row.some((value) => String(value ?? "").trim());
export function parseScoreExcelRows(sheetRows, metrics, channels) {
const headerIndex = sheetRows.findIndex(hasValue);
if (headerIndex < 0) throw new Error("Excel 中没有数据,请按模板填写后导入");
const columns = scoreExcelColumns(metrics);
const headers = sheetRows[headerIndex].map(headerName);
const indexes = columns.map((column) => {
const matches = headers.map((name, index) => [name, index]).filter(([name]) => name === headerName(column.label) || (column.alias && name === headerName(column.alias)));
if (!matches.length) throw new Error(`Excel 缺少表头:${column.label}`);
if (matches.length > 1) throw new Error(`Excel 表头重复:${column.label}`);
return matches[0][1];
});
const allowedChannels = new Set(channels.map((channel) => String(channel ?? "").trim()));
if (allowedChannels.size !== channels.length || allowedChannels.has("")) throw new Error("第二步渠道名称为空或重复,请先修正渠道数据");
const seen = new Set();
const rows = sheetRows.slice(headerIndex + 1).map((values, index) => ({ values, line: headerIndex + index + 2 })).filter(({ values }) => hasValue(values));
if (!rows.length) throw new Error("Excel 只有表头,没有可导入的渠道得分");
return rows.map(({ values, line }) => Object.fromEntries(columns.map((column, index) => {
const value = String(values[indexes[index]] ?? "").trim();
const field = `Excel 第 ${line} 行「${column.label}」`;
if (column.key === "channel") {
if (!value) throw new Error(`${field}不能为空`);
if (!allowedChannels.has(value)) throw new Error(`${field}“${value}”不存在,请先在第二步添加该渠道`);
if (seen.has(value)) throw new Error(`${field}“${value}”重复`);
seen.add(value);
return [column.key, value];
}
if (!value) return [column.key, undefined];
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value) || !Number.isFinite(Number(value))) throw new Error(`${field}请填写非负数字`);
const weighted = column.key === "weightedScore";
if (!weighted && Number(value) > 10) throw new Error(`${field}必须在 0–10 之间`);
const fraction = value.split(".")[1]?.replace(/0+$/, "") || "";
if (fraction.length > (weighted ? 2 : 1)) throw new Error(`${field}最多保留 ${weighted ? 2 : 1} 位小数`);
return [column.key, Number(value)];
})));
}

@ -88,8 +88,6 @@
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="pageKey + ':' + currentStep" :disabled="saving" />
<section v-if="processRows.length" class="process-step-card">
<div v-if="configuredSteps.length" class="step-title-row">
<div>
@ -434,10 +432,6 @@
</template>
<script setup>
import TrainingExcelTools from '@/views/components/TrainingExcelTools.vue';
import { computed as excelComputed } from 'vue';
import { excelTable as et, numberColumn as nc, rateColumn as rc, textColumn as tc, fixedColumn as fc } from '@/views/training/numericTableExcel.mjs';
import { ArrowLeft, ArrowRight, CircleCheck, Upload } from "@element-plus/icons-vue";
import { getTrainingTaskByKey } from "@/api/trainingTask";
import { getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer";
@ -861,7 +855,7 @@ function startComprehensiveNavDrag(event) {
comprehensiveNavDrag.startScrollLeft = nav.scrollLeft;
comprehensiveNavDrag.moved = false;
// 按下时不立即捕获指针:捕获会把后续 click 重定向到容器,
// 步骤按钮的 @click 将永远收不到事件(切换无响应)。
// 步骤按钮的 @click 将永远收不到事件(点击切换无响应)。
// 只有拖动超过阈值、确认是拖拽后再捕获(见 moveComprehensiveNavDrag)。
comprehensiveNavDrag.captured = false;
comprehensiveNavDragging.value = true;
@ -1717,63 +1711,6 @@ function exportOutcome() {
URL.revokeObjectURL(url);
proxy?.$modal?.msgSuccess("导出成功");
}
const numericExcelTables = excelComputed(() => {
if (!isComprehensiveCaseTraining.value) return [];
const number = (key, label, options = {}) => nc(key, label, {string: true, ...options});
const rate = (key, label, options = {}) => rc(key, label, {string: true, ...options});
const pair = [number('smallCost', '小批量单台成本(元)'), number('largeCost', '大批量单台成本(元)')];
if (currentStep.value === 2) {
const state = comprehensiveStepTwo.value;
return [
et('primary', '综合实训-一级指标权重', comprehensiveIndicators.map(g => ({key: g.key, label: g.label, value: state.primaryWeights[g.key]})), [fc('label', '一级指标'), rate('value', '一级指标权重(%)')], {apply: next => next.forEach(r => {state.primaryWeights[r.key] = r.value;})}),
et('dimensions', '综合实训-维度权重', comprehensiveIndicators.flatMap(g => g.dimensions.map(d => ({key: d.key, label: d.label, weight: state.dimensionWeights[d.key], total: state.totalWeights[d.key]}))), [fc('label', '评估维度'), rate('weight', '维度内权重(%)'), rate('total', '总权重(%)')], {apply: next => next.forEach(r => {state.dimensionWeights[r.key] = r.weight; state.totalWeights[r.key] = r.total;})}),
et('categories', '综合实训-品类综合得分', state.categoryScores, [tc('name', '产品品类'), number('score', '综合得分')]),
et('reviews', '综合实训-品类好评率', state.reviews.map((r,i) => ({...r, category: comprehensiveReviewCategory(i)})), [fc('category', '产品品类'), rate('favorableRate', '好评率(%)')], {apply: next => next.forEach((r,i) => {state.reviews[i].favorableRate = r.favorableRate;})}),
];
}
if (currentStep.value === 4) return [et('rice', '综合实训-RICE评分', comprehensiveStepFour.value.riceRows, [tc('featureName', '功能名称'), number('reach', 'Reach覆盖范围'), number('impact', 'Impact影响程度'), rate('confidence', 'Confidence置信度(%)', {get: r => {const v = String(r.confidence ?? '').trim(); const n = Number(v.replace('%', '')); return !v ? '' : v.includes('%') || n > 1 ? n : n * 100;}, set: (r,v) => {r.confidence = v === '' ? '' : String(Number(v) / 100);}}), number('effort', 'Effort人月')])];
if (currentStep.value === 6) {
const state = comprehensiveStepSix.value;
return [
et('bom', '综合实训-物料批量成本', state.bomRows, [tc('name', '物料名称'), tc('specification', '选型规格参数'), ...pair]),
et('manufacturing', '综合实训-制造费用', state.manufacturingRows, [tc('name', '费用名称'), ...pair]),
et('supply-weights', '综合实训-供应渠道权重', state.weightRows, [fc('label', '评估维度'), rate('trialWeight', '试产权重(%)'), rate('massWeight', '量产权重(%)')]),
et('supply-scores', '综合实训-供应渠道评分', state.channelRows, [tc('channel', '渠道'), ...comprehensiveProcurementDimensions.map(d => number(d.key, d.label, {max: 10}))]),
];
}
if (currentStep.value === 7) {
const state = comprehensiveStepSeven.value;
return [
et('forecast', '综合实训-采购预测', state.forecastRows, [fc('month', '预测月份'), number('forecastSales', '预测销量(台)')]),
et('markup', '综合实训-成本加成比例', state.costPricingRows, [fc('channel', '渠道'), number('markup', '加成率(%)', {percent: true})]),
et('competitors', '综合实训-竞品售价', state.competitorRows, [tc('type', '竞品类型'), tc('brand', '品牌'), number('price', '售价(元)'), tc('advantage', '差异化优势')]),
et('value', '综合实训-用户感知价值', state.valueRows, [tc('item', '价值感知项'), number('value', '感知价值(元)')]),
et('psm', '综合实训-PSM价格敏感度', state.psmRows, [tc('range', '价格区间'), rate('tooExpensive', '太贵(%)'), rate('tooCheap', '太便宜(%)'), rate('acceptable', '贵但可接受(%)'), rate('bargain', '便宜划算(%)')]),
et('summary', '综合实训-定价方法汇总', state.summaryRows, [fc('method', '定价方法'), tc('result', '测算结果'), rate('margin', '毛利润率(%)', {min: null})]),
];
}
if (currentStep.value === 8) {
const state = comprehensiveStepEight.value;
return [
et('abc', '综合实训-品类营收结构', state.abcRows, [tc('name', '品类名称'), number('revenue', '营收贡献'), rate('salesShare', '营收占比(%)'), rate('cumulativeShare', '累计占比(%)')]),
et('channel-weights', '综合实训-发布渠道权重', state.channelWeightRows, [tc('name', '评估维度'), tc('description', '维度说明'), rate('weight', '权重(%)')]),
et('channel-scores', '综合实训-发布渠道得分', state.channelScoreRows, [tc('channel', '渠道'), ...state.channelWeightRows.map((d,i) => number(d.id, (d.name.trim() || ('维度' + (i+1))) + '得分', {max: 10, get: r => r.scores[d.id], set: (r,v) => {r.scores[d.id] = v;}}))]),
];
}
if (currentStep.value === 9) {
const state = comprehensiveStepNine.value;
return [
et('budget', '综合实训-投放预算', state.budgetRows, [tc('channel', '渠道'), rate('share', '预算占比(%)'), number('launchBudget', '冷启动预算(元)'), number('growthBudget', '增长期预算(元)'), number('stableBudget', '稳定期预算(元)')]),
et('roi', '综合实训-投放效果', state.roiRows, [tc('channel', '渠道'), rate('clickRate', '点击率(%)'), number('roi', 'ROI')]),
et('funnel', '综合实训-全链路转化率', state.funnelRows, [fc('node', '链路节点'), ...state.funnelChannels.map((c,i) => rate(c.id, (c.name.trim() || ('渠道' + (i+1))) + '转化率(%)', {get: r => r.values[c.id], set: (r,v) => {r.values[c.id] = v;}})), rate('industryAverage', '行业平均值(%)')]),
et('diagnosis', '综合实训-异常节点数据', state.funnelDiagnoses, [tc('channel', '渠道'), tc('node', '链路节点'), rate('storeRate', '本店转化率(%)'), rate('industryRate', '行业转化率(%)')]),
et('ab', '综合实训-AB测试数据', state.abRows, [fc('metric', '指标'), rate('control', '对照组(%)'), rate('experiment', '实验组(%)')]),
];
}
return [];
});
</script>
<style lang="scss" scoped>

@ -1,97 +0,0 @@
// Only fields explicitly listed by the training page can be imported.
export const textColumn = (key, label, options = {}) => ({ key, label, type: 'text', ...options });
export const fixedColumn = (key, label) => textColumn(key, label, { readonly: true });
export const numberColumn = (key, label, options = {}) => ({ key, label, type: 'number', min: 0, ...options });
export const rateColumn = (key, label, options = {}) => numberColumn(key, label, { max: 100, percent: true, ...options });
export const cloneRows = (rows) => JSON.parse(JSON.stringify(rows));
export const cellValue = (row, column) => column.get ? column.get(row) : row[column.key];
export function excelTable(id, title, rows, columns, options = {}) {
return { id, title, rows, columns, ...options,
apply: options.apply || ((next) => rows.splice(0, rows.length, ...next)),
};
}
export function templateRows(table) {
const count = Math.max(table.rows.length, table.templateRowCount || 0);
return [['序号', ...table.columns.map((column) => column.label)], ...Array.from({ length: count }, (_, index) => [index + 1,
...table.columns.map((column) => column.type === 'number' ? '' : cellValue(table.rows[index] || {}, column) ?? ''),
])];
}
function parseNumber(value, column, location) {
if (value === '' || value === null || value === undefined) return column.string ? '' : undefined;
let source = String(value).trim();
if (column.percent) source = source.replace(/[%%]$/, '').trim();
if (/^-?\d{1,3}(,\d{3})+(\.\d+)?$/.test(source)) source = source.replace(/,/g, '');
if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(source)) throw new Error(`${location}请输入有效数字`);
const number = Number(source);
if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER || (column.min != null && number < column.min) || (column.max != null && number > column.max)) {
throw new Error(`${location}数值超出范围${column.min != null ? `,最小 ${column.min}` : ''}${column.max != null ? `,最大 ${column.max}` : ''}`);
}
const decimal = source.split('.')[1]?.replace(/0+$/, '') || '';
if (column.precision != null && decimal.length > column.precision) throw new Error(`${location}最多允许 ${column.precision} 位小数`);
return column.string ? String(number) : number;
}
export function parseTableRows(sheetRows, table) {
const blank = (value) => value == null || String(value).trim() === '';
const headerIndex = sheetRows.findIndex((row) => row.some((value) => !blank(value)));
if (headerIndex < 0) throw new Error('Excel 中没有表头');
const headers = sheetRows[headerIndex].map((value) => String(value ?? '').trim());
const expected = ['序号', ...table.columns.map((column) => column.label)];
if (new Set(expected).size !== expected.length) throw new Error('当前表格列名重复,请先调整页面中的名称');
const nonemptyHeaders = headers.filter(Boolean);
if (new Set(nonemptyHeaders).size !== nonemptyHeaders.length) throw new Error('Excel 表头有重复列');
const positions = expected.map((label) => headers.indexOf(label));
if (positions.includes(-1)) throw new Error(`缺少列:${expected.filter((_, index) => positions[index] < 0).join('、')},请下载本表模板`);
if (nonemptyHeaders.some((label) => !expected.includes(label))) throw new Error('包含不属于本表的列,请使用本表模板');
const next = cloneRows(table.rows);
const updates = new Map();
for (let index = headerIndex + 1; index < sheetRows.length; index += 1) {
const row = sheetRows[index];
if (row.every(blank)) continue;
if (row.some((value, position) => !blank(value) && !positions.includes(position))) throw new Error(`第 ${index + 1} 行有无表头的数据`);
const serial = String(row[positions[0]] ?? '').trim();
if (!/^[1-9]\d*$/.test(serial)) throw new Error(`第 ${index + 1} 行序号须为正整数`);
const targetIndex = Number(serial) - 1;
// Extra blank template rows are placeholders; an existing row can intentionally be cleared.
if (targetIndex >= table.rows.length && positions.slice(1).every((position) => blank(row[position]))) continue;
if (targetIndex >= (table.maxRows ?? table.rows.length)) throw new Error(`第 ${index + 1} 行序号超出本表行数范围`);
if (updates.has(targetIndex)) throw new Error(`第 ${index + 1} 行序号重复`);
const target = next[targetIndex] || (table.createRow ? table.createRow(targetIndex) : null);
if (!target) throw new Error(`第 ${index + 1} 行不存在,请重新下载模板`);
table.columns.forEach((column, columnIndex) => {
const raw = row[positions[columnIndex + 1]];
const location = `第 ${index + 1} 行「${column.label}」:`;
if (column.readonly) {
if (String(raw ?? '').trim() !== String(cellValue(target, column) ?? '').trim()) throw new Error(`${location}与当前页面不一致,请重新下载模板`);
return;
}
const value = column.type === 'number' ? parseNumber(raw, column, location) : String(raw ?? '').trim();
if (column.values && value && !column.values.includes(value)) throw new Error(`${location}只能填写 ${column.values.join('、')}`);
if (column.maxLength && value.length > column.maxLength) throw new Error(`${location}最多 ${column.maxLength} 个字符`);
if (column.set) column.set(target, value); else target[column.key] = value;
});
updates.set(targetIndex, target);
}
if (!updates.size) throw new Error('没有可导入的数据行');
const last = Math.max(next.length - 1, ...updates.keys());
for (let index = 0; index <= last; index += 1) {
if (updates.has(index)) next[index] = updates.get(index);
else if (!next[index]) throw new Error('新增行的序号须连续,不能跳行');
}
return { rows: next, count: updates.size };
}
export async function importTableFile(file, table, { readWorkbook, confirm, isCurrent }) {
if (!/\.(xls|xlsx)$/i.test(file.name)) throw new Error('请选择 .xls 或 .xlsx 文件');
if (file.size > 5 * 1024 * 1024) throw new Error('Excel 文件不能超过 5MB');
const before = JSON.stringify(table.rows);
const sheetRows = await readWorkbook(file);
const result = parseTableRows(sheetRows, table);
await confirm(`将更新「${table.title}」中的 ${result.count} 行,导入行的空白数值会清空对应输入。未导入的行保留。是否继续?`);
if (!isCurrent() || JSON.stringify(table.rows) !== before) throw new Error('当前步骤或表格已变化,请重新导入');
table.apply(result.rows);
return result.count;
}

@ -68,7 +68,7 @@ export function getStudentTrainingStepCount(taskKey, fallback = 4) {
}
export function resolveTrainingTaskKey(route, explicitTaskKey = "") {
return explicitTaskKey || route?.meta?.pageKey || route?.params?.pageKey || trainingTaskKeyByPath[route?.path] || "";
return explicitTaskKey || route?.meta?.pageKey || trainingTaskKeyByPath[route?.path] || "";
}
export function parseTrainingArray(value, fallback = []) {

@ -1,39 +0,0 @@
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 dialogueSource = fs.readFileSync(path.join(root, "src/views/analysis-of-students/dialogue.vue"), "utf8");
const indexApiSource = fs.readFileSync(path.join(root, "src/api/index.js"), "utf8");
const projectStudyTimeSource = fs.readFileSync(path.join(root, "src/api/projectStudyTime.js"), "utf8");
test("learning analysis api treats AI service error text as failure", () => {
const requestBlock = apiSource.match(/export function getLearningAnalysis[\s\S]*?\n}/)?.[0] || "";
assert.match(requestBlock, /\^error\\b\/i/);
assert.match(requestBlock, /throw new Error\(text\)/);
});
test("dialogue page falls back to the AI chat channel with the same learning data", () => {
assert.match(dialogueSource, /openAssistantStream/);
const fallbackBlock = dialogueSource.match(/专用学情分析接口不可用时[\s\S]*?openAssistantStream\([\s\S]*?\);/)?.[0] || "";
assert.match(fallbackBlock, /stuNeed/);
assert.match(fallbackBlock, /JSON\.stringify\(stuData\)/);
});
test("kimi4 stream requests fail loudly on non-2xx responses", () => {
assert.match(dialogueSource, /if \(!resp\.ok \|\| !resp\.body\)/);
});
test("sendMessage never leaves the pending state stuck", () => {
const sendBlock = dialogueSource.match(/const sendMessage = async \(\) => \{[\s\S]*?\n};/)?.[0] || "";
assert.match(sendBlock, /finally\s*\{\s*isRequestPending\.value = false/);
});
test("score apis suppress duplicate interceptor toasts", () => {
const reportBlock = indexApiSource.match(/export const getCurrentExperimentReport[\s\S]*?\n}/)?.[0] || "";
const studyTimeBlock = projectStudyTimeSource.match(/export function getCurrentProjectStudyTime[\s\S]*?\n}/)?.[0] || "";
assert.match(reportBlock, /skipErrorMessage:\s*true/);
assert.match(studyTimeBlock, /skipErrorMessage:\s*true/);
});

@ -1,149 +0,0 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const Vue = require("vue");
const XLSX = require("xlsx");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
const { compile } = require("@vue/compiler-dom");
const { renderToString } = require("@vue/server-renderer");
const sourcePath = path.resolve(__dirname, "../src/views/assessment/optimization.vue");
const source = fs.readFileSync(sourcePath, "utf8");
const helpersSource = fs.readFileSync(path.resolve(__dirname, "../src/views/assessment/categoryOptimizationExcel.js"), "utf8");
function helpers() {
const context = {};
vm.runInNewContext(helpersSource.replace(/export /g, "") + "\nglobalThis.exports={CATEGORY_EXCEL_COLUMNS,sanitizeCategoryNumber,parseCategoryExcelRows};", context);
return context.exports;
}
const plain = (value) => JSON.parse(JSON.stringify(value));
function workbookBytes(rows, bookType = "xlsx") {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), "品类数据");
return XLSX.write(workbook, { type: "buffer", bookType });
}
function fileEvent(bytes, name = "品类数据.xlsx") {
const target = { value: name, files: [{ name, arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) }] };
return { target };
}
function pageHarness(confirm = true) {
const messages = [], saved = [], downloads = [];
const context = { ...Vue, ...helpers(), onMounted() {}, defineAsyncComponent: () => ({}),
ElMessage: { success: (value) => messages.push(value), error: (value) => messages.push(value) },
ElMessageBox: { confirm: async () => { if (!confirm) throw new Error("cancel"); } },
parseTrainingArray: (value, fallback = []) => Array.isArray(value) ? value : fallback,
XLSX_IMPORT: { ...XLSX, writeFile: (workbook, filename) => downloads.push({ workbook, filename }) },
saveStudentTrainingAnswer: async (taskKey, payload) => saved.push({ taskKey, payload }),
};
const script = parse(source).descriptor.scriptSetup.content.replace(/^import .*\r?\n/gm, "").replaceAll('await import("xlsx")', "XLSX_IMPORT");
vm.runInNewContext(script + "\nglobalThis.page={categoryRows,importCategoryExcel,downloadCategoryTemplate,saveCurrentProgress,importingCategories};", context);
return { ...context.page, messages, saved, downloads };
}
test("numeric inputs ignore non numeric characters and preserve decimal editing", () => {
const { sanitizeCategoryNumber: clean, CATEGORY_EXCEL_COLUMNS: columns } = helpers();
for (const { key } of columns.slice(1)) {
assert.equal(clean("abc中文$%+-", key), "");
assert.equal(clean("1a2.3$4", key), "12.34");
assert.equal(clean("1.2.3", key), "1.23");
assert.equal(clean("0.", key), "0.");
assert.equal(clean(".5", key), "0.5");
assert.equal(clean(null, key), "");
}
assert.equal(clean("101.25", "capitalOccupancyRate"), "100");
assert.equal(clean("12.345", "sellThroughRate"), "12.34");
assert.equal(clean("12345.678", "revenue"), "12345.678");
});
test("xls and xlsx imports map reordered headers and Excel percentages correctly", () => {
const { CATEGORY_EXCEL_COLUMNS: columns, parseCategoryExcelRows: parseRows } = helpers();
for (const bookType of ["xlsx", "xls"]) {
const headers = Array.from(columns, (column) => column.label);
const sheet = XLSX.utils.aoa_to_sheet([headers, ["ABC品类", 600, 0.6, 0.6, 1250, 0.25, 0.75, 0.3]]);
for (const cell of ["C2", "D2", "F2", "G2", "H2"]) sheet[cell].z = "0.00%";
sheet.E2.z = "#,##0.00";
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, "数据");
const parsed = XLSX.read(XLSX.write(workbook, { type: "buffer", bookType }), { type: "buffer" });
const rows = XLSX.utils.sheet_to_json(parsed.Sheets[parsed.SheetNames[0]], { header: 1, defval: "", raw: false });
const result = plain(parseRows(rows.map((row) => row.slice().reverse())));
assert.deepEqual(result, [{ categoryName: "ABC品类", revenue: "600", revenueShare: "60.00", cumulativeShare: "60.00", inventoryCapital: "1250.00", capitalOccupancyRate: "25.00", sellThroughRate: "75.00", grossMargin: "30.00" }]);
}
});
test("invalid Excel rows fail as a batch while optional columns stay blank", () => {
const { parseCategoryExcelRows: parseRows } = helpers();
const headers = ["品类名称", "近12个月营收(万元)"];
assert.throws(() => parseRows([]), /没有数据/);
assert.throws(() => parseRows([headers]), /没有可导入/);
assert.throws(() => parseRows([["品类名称"], ["测试"]]), /缺少表头/);
assert.throws(() => parseRows([[...headers, "近12个月营收"], ["A", 1, 1]]), /表头重复/);
assert.throws(() => parseRows([headers, ["A", 1], ["B", "12abc"]]), /第 3 行/);
assert.throws(() => parseRows([headers, ["A", -1]]), /只接受数字/);
assert.throws(() => parseRows([headers, ...Array.from({ length: 31 }, () => ["A", 1])]), /最多导入 30 行/);
assert.throws(() => parseRows([[...headers, "资金占用率(%)"], ["A", 1, "101%"]]), /不能超过 100/);
const [row] = plain(parseRows([[], headers, [], ["A", 0]]));
assert.equal(row.revenue, "0");
assert.equal(row.inventoryCapital, "");
assert.equal(row.capitalOccupancyRate, "");
});
test("page import preserves current work on invalid files or cancellation and saves accepted data", async () => {
const { CATEGORY_EXCEL_COLUMNS: columns } = helpers();
const headers = Array.from(columns, (column) => column.label);
const valid = workbookBytes([headers, ["导入品类", 100, 100, 100, 20, 25, 75, 30]]);
const page = pageHarness();
page.categoryRows.value = [{ id: "old-row", categoryName: "原有品类", revenue: "60" }];
await page.importCategoryExcel(fileEvent(workbookBytes([headers, ["错误数据", "abc"]])));
assert.equal(page.categoryRows.value[0].id, "old-row");
assert.match(page.messages.at(-1), /只接受数字/);
assert.equal(page.importingCategories.value, false);
const cancelled = pageHarness(false);
cancelled.categoryRows.value = [{ id: "keep-me" }];
await cancelled.importCategoryExcel(fileEvent(valid));
assert.equal(cancelled.categoryRows.value[0].id, "keep-me");
const event = fileEvent(valid);
await page.importCategoryExcel(event);
assert.equal(event.target.value, "");
assert.equal(page.categoryRows.value.length, 1);
assert.equal(page.categoryRows.value[0].categoryName, "导入品类");
assert.equal(page.categoryRows.value[0].abcClassification, "");
await page.saveCurrentProgress();
const payload = page.saved[0].payload;
assert.equal(payload.saveAction, "SAVE");
assert.equal(JSON.parse(payload.step1Answer).categoryRows[0].revenue, "100");
assert.equal(JSON.parse(payload.step1Answer).categoryRows[0].capitalOccupancyRate, 25);
});
test("template download contains the page columns without importing sample answers", async () => {
const page = pageHarness();
await page.downloadCategoryTemplate();
const { workbook, filename } = page.downloads[0];
assert.match(filename, /\.xlsx$/);
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { header: 1 });
assert.equal(rows.length, 1);
assert.equal(rows[0].length, 8);
assert.equal(rows[0][0], "品类名称");
assert.equal(workbook.SheetNames[1], "填写说明");
});
test("all seven numeric template bindings filter pasted text while category names remain text", async () => {
const { descriptor, errors } = parse(source);
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "category-import" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: sourcePath, id: "category-import" }).errors, []);
const rowTemplate = source.match(/<tr v-for="\(row, index\) in categoryRows"[\s\S]*?<\/tr>/)[0];
const render = new Function("Vue", compile(rowTemplate, { prefixIdentifiers: true }).code)(Vue);
const row = Vue.reactive({ categoryName: "ABC品类", revenue: "", revenueShare: "", cumulativeShare: "", inventoryCapital: "", capitalOccupancyRate: null, sellThroughRate: null, grossMargin: "" });
const handlers = [];
const app = Vue.createSSRApp({ setup: () => ({ categoryRows: [row], sanitizeCategoryNumber: helpers().sanitizeCategoryNumber }), render });
app.component("el-input", { props: ["modelValue"], setup: (props, { attrs }) => { handlers.push({ label: attrs["aria-label"], update: attrs["onUpdate:modelValue"] }); return () => Vue.h("input", { value: props.modelValue }); } });
await renderToString(app);
assert.equal(handlers.length, 8);
for (const handler of handlers.slice(1)) handler.update("1a2.3#4");
for (const key of Object.keys(row).filter((key) => key !== "categoryName")) assert.equal(row[key], "12.34", key);
assert.equal(row.categoryName, "ABC品类");
for (const handler of handlers.slice(1)) handler.update("ABC@中文");
for (const key of Object.keys(row).filter((key) => key !== "categoryName")) assert.equal(row[key], "", key);
});

@ -1,741 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const Vue = require('vue');
const XLSX = require('xlsx');
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc');
const babel = require('@babel/parser');
const helperPath = path.resolve(__dirname, '../src/views/training/numericTableExcel.mjs');
const helpers = import(require('node:url').pathToFileURL(helperPath).href);
const plain = value => JSON.parse(JSON.stringify(value));
const pages = {
'channel/index': [1, 3, 4], 'channel/supplier': [1, 2],
'product/hardware-cost': [1, 2, 3], 'product/price': [1, 2, 3, 4],
'test/index': [1, 2, 4], 'test/promotion': [1, 3],
'demand/feature-conversion': [2], 'assessment/diagnosis': [1, 3],
'demand/business-feasibility': [1], 'product/market-opportunity-selection': [2, 3, 5],
'assessment/index': [1], 'training/GenericTrainingPage': [2, 4, 6, 7, 8, 9],
'portraitModel/components/funnelAnalysis': [1],
'digitalMarketingAlgorithms/components/descriptiveStatistics': [1],
};
async function harness(page, overrides = {}) {
const helper = await helpers;
const filename = path.resolve(__dirname, '../src/views/' + page + '.vue');
const descriptor = parse(fs.readFileSync(filename, 'utf8')).descriptor;
compileScript(descriptor, { id: 'numeric-excel' });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'numeric-excel' }).errors, []);
let script = descriptor.scriptSetup.content;
const nodes = babel.parse(script, { sourceType: 'module' }).program.body;
const names = [];
const context = { ...Vue, console, setTimeout, clearTimeout,
onMounted() {}, onBeforeUnmount() {}, onUnmounted() {}, watch() {}, watchEffect() {},
getCurrentInstance: () => ({ proxy: { $modal: {} } }),
useRoute: () => ({ meta: { pageKey: 'comprehensive-case-training' }, params: {} }),
defineProps: () => ({ previewTaskKey: '' }),
};
for (const node of nodes) {
if (node.type === 'ImportDeclaration') {
for (const specifier of node.specifiers) {
const local = specifier.local.name;
const imported = specifier.imported?.name;
if (node.source.value === 'vue') context[local] = context[imported];
else if (node.source.value.includes('numericTableExcel')) context[local] = helper[imported];
else if (local === 'getUserInfo') context[local] = () => '{}';
else if (local === 'useAlgorithmStore') context[local] = () => ({userDataLabel: []});
else if (local === 'getStudentTrainingPage') context[local] = () => ({ fields: [], tableRows: [], processRows: [], title: '综合实训' });
else if (local === 'parseTrainingArray') context[local] = (value, fallback = []) => Array.isArray(value) && value.length ? value : fallback;
else context[local] = () => ({});
}
} else if (node.type === 'VariableDeclaration') {
for (const item of node.declarations) if (item.id.type === 'Identifier') names.push(item.id.name);
} else if (node.type === 'FunctionDeclaration') names.push(node.id.name);
}
for (const node of [...nodes].reverse()) if (node.type === 'ImportDeclaration') script = script.slice(0, node.start) + script.slice(node.end);
Object.assign(context, overrides);
script = script.replaceAll('import.meta.env.VITE_APP_BASE_API', "'/api'").replaceAll("await import('xlsx')", 'XLSX_IMPORT');
vm.runInNewContext(script + '\nglobalThis.page = {' + names.join(',') + '};', context, { filename });
return context.page;
}
for (const [page, steps] of Object.entries(pages)) test('numeric Excel round trip ' + page, async () => {
const h = await helpers;
const state = await harness(page);
if (page === 'product/market-opportunity-selection') for (const name of ['stepOnePassed','stepTwoPassed','stepFourPassed']) state[name].value = true;
if (page === 'product/hardware-cost') state.syncStepTwoRows(state.rows.value);
if (page === 'test/index') { state.syncScoreRows(); state.syncRankingRows(); }
if (page === 'test/promotion') { state.addBudgetRow(); state.budgetRows.value[0].channel = '天猫'; state.availableChannels.value = ['天猫']; state.syncPerformanceRows(); }
for (const step of steps) {
if (state.currentStep) state.currentStep.value = step;
else if (state.activeStep) state.activeStep.value = step;
else if (page === 'demand/feature-conversion') state.form.value.activeStep = step;
const tables = state.numericExcelTables.value;
assert.ok(tables.length, page + ' step ' + step);
for (const table of tables) {
assert.ok(table.rows.length, table.title + ' has rows');
table.columns.filter(column => column.readonly).forEach(column => table.rows.forEach(row => assert.notEqual(h.cellValue(row, column), undefined, table.title + ' / ' + column.label + ' exists')));
const data = h.templateRows(table);
for (let index = 1; index <= table.rows.length; index++) {
table.columns.forEach((column, ci) => {
if (column.type === 'number') data[index][ci + 1] = column.min > 0 ? column.min : 1;
});
}
// Export with the same first-sheet format as the toolbar, then read real XLS/XLSX bytes.
for (const bookType of ['xls', 'xlsx']) {
const book = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book, XLSX.utils.aoa_to_sheet(data), '填写数据');
const read = XLSX.read(XLSX.write(book, { type: 'buffer', bookType }), { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json(read.Sheets[read.SheetNames[0]], { header: 1, raw: false, defval: '', range: 0 });
const before = plain(table.rows);
const imported = h.parseTableRows(rows, table);
assert.equal(imported.count, table.rows.length, table.title);
table.apply(imported.rows);
table.columns.filter(c => c.type === 'number').forEach(column => {
const current = state.numericExcelTables.value.find(t => t.id === table.id);
current.rows.forEach(row => assert.equal(Number(h.cellValue(row, column)), column.min > 0 ? column.min : 1, table.title + ' / ' + column.label));
});
// Fields excluded from the import schema (IDs, narrative, derived classification) survive.
for (let i = 0; i < before.length; i++) {
const after = state.numericExcelTables.value.find(t => t.id === table.id).rows[i];
if ('id' in before[i]) assert.equal(after.id, before[i].id);
}
}
}
}
});
test('numeric Excel validates the entire file before mutation', async () => {
const h = await helpers;
const rows = [{ id: 'a', name: '天猫', count: 4, rate: 6, note: '保留' }, { id: 'b', name: '京东', count: 8, rate: 9 }];
const table = h.excelTable('x', '数据', rows, [h.fixedColumn('name', '渠道'), h.numberColumn('count', '数量', {precision: 0}), h.rateColumn('rate', '占比(%)', {precision: 2})]);
const before = JSON.stringify(rows);
const header = ['序号','渠道','数量','占比(%)'];
for (const bad of ['abc', '-1', '1.2', '1e3', '1,2', '=1+2']) {
assert.throws(() => h.parseTableRows([header,[1,'天猫',12,25],[2,'京东',bad,15]], table));
assert.equal(JSON.stringify(rows), before);
}
for (const invalid of [
[header,[1,'天猫',1,'101%']], [header,[1,'天猫',1,'1.001']],
[header,[1,'天猫',1,5],[1,'天猫',2,6]], [header,[3,'未知',1,5]],
[header,[1,'已改名',1,5]], [['序号','渠道','数量'],[1,'天猫',1]],
[['序号','渠道','数量','数量','占比(%)'],[1,'天猫',1,2,5]],
]) assert.throws(() => h.parseTableRows(invalid, table));
const accepted = h.parseTableRows([[], ['占比(%)','数量','渠道','序号'], ['25%','1,200','京东',2], [], ['0','0','天猫',1]], table);
table.apply(accepted.rows);
assert.equal(rows[1].count,1200); assert.equal(rows[1].rate,25); assert.equal(rows[0].count,0);
assert.equal(rows[0].note,'保留'); assert.equal(rows[0].id,'a');
});
test('numeric Excel cancel and stale imports preserve current work', async () => {
const h = await helpers;
const rows = [{ name:'物料', amount:3 }];
const table = h.excelTable('x','物料',rows,[h.textColumn('name','名称'),h.numberColumn('amount','金额')]);
const file = {name:'data.xlsx',size:10};
const readWorkbook = async () => [['序号','名称','金额'],[1,'物料',99]];
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{throw Error('cancel');},isCurrent:()=>true}));
assert.equal(rows[0].amount,3);
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{},isCurrent:()=>false}),/已变化/);
assert.equal(rows[0].amount,3);
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{rows[0].amount=8;},isCurrent:()=>true}),/已变化/);
assert.equal(rows[0].amount,8);
await assert.rejects(h.importTableFile({...file,name:'data.csv'},table,{readWorkbook}),/xls/);
await assert.rejects(h.importTableFile({...file,size:6*1024*1024},table,{readWorkbook}),/5MB/);
});
test('numeric Excel adds BOM rows without importing computed values', async () => {
const h = await helpers;
const state = await harness('product/hardware-cost');
const table = state.numericExcelTables.value[0];
const rows = h.templateRows(table);
assert.equal(rows.length,11);
assert.ok(!rows[0].includes('金额(元)'));
for (let i=1;i<=10;i++) rows[i]=[i,'物料'+i,'规格',i===1?'1,200.50':'2',2];
const result=h.parseTableRows(rows,table); table.apply(result.rows);
assert.equal(state.rows.value.length,10);
assert.equal(state.rowAmount(state.rows.value[0]),2401);
const bad=h.templateRows(table); bad.push([41,'超行','规格',1,1]);
assert.throws(()=>h.parseTableRows(bad,table));
assert.equal(state.rows.value.length,10);
});
test('numeric Excel toolbar downloads a blank workbook and imports through confirmation', async () => {
const h = await helpers;
const rows = [{id:'keep-id',name:'天猫',rate:66,note:'原有分析'}];
const tables = [h.excelTable('rates','渠道占比',rows,[h.fixedColumn('name','渠道'),h.rateColumn('rate','占比(%)')])];
const props = Vue.reactive({tables,contextKey:1,disabled:false});
const downloads=[], errors=[], successes=[];
let confirm=true;
const component = await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{error:m=>errors.push(m),success:m=>successes.push(m)},
ElMessageBox:{confirm:async()=>{if(!confirm)throw 'cancel';}},
});
await component.downloadTemplate();
assert.equal(downloads.length,1);
const book=downloads[0].workbook;
const sheet=book.Sheets[book.SheetNames[0]];
assert.deepEqual(XLSX.utils.sheet_to_json(sheet,{header:1,defval:''}),[['序号','渠道','占比(%)'],[1,'天猫','']]);
sheet.C2={t:'s',v:'25%'};
const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'});
const event=()=>({target:{value:'file',files:[{name:'rates.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}});
confirm=false; await component.importFile(event()); assert.equal(rows[0].rate,66);
confirm=true; const input=event(); await component.importFile(input);
assert.equal(input.target.value,''); assert.equal(rows[0].rate,25);
assert.equal(rows[0].id,'keep-id'); assert.equal(rows[0].note,'原有分析');
assert.equal(successes.length,1); assert.deepEqual(errors,[]);
props.disabled=true; await component.importFile(event()); assert.equal(successes.length,1);
});
test('numeric Excel preserves percentage semantics and clears existing scalar rows', async () => {
const h=await helpers;
const state=await harness('training/GenericTrainingPage'); state.currentStep.value=4;
const table=state.numericExcelTables.value[0];
const rows=h.templateRows(table);
rows[1]=[1,'功能',1,1,'1%',1];
table.apply(h.parseTableRows(rows,table).rows);
assert.equal(state.comprehensiveStepFour.value.riceRows[0].confidence,'0.01');
assert.equal(state.comprehensiveRiceScore(state.comprehensiveStepFour.value.riceRows[0]),'0.0');
const scalar=[{value:8}];
const scalarTable=h.excelTable('scalar','数值',scalar,[h.numberColumn('value','数值')]);
scalarTable.apply(h.parseTableRows([['序号','数值'],[1,'']],scalarTable).rows);
assert.equal(scalar[0].value,undefined);
const efficacy=await harness('assessment/index');
const weight=efficacy.numericExcelTables.value[1];
const input=h.templateRows(weight); input[1]=[1,'商品采购合格率','30%',24];
weight.apply(h.parseTableRows(input,weight).rows);
assert.equal(efficacy.parsePercentage(efficacy.data.value[0].currentWeight),0.3);
});
test('numeric Excel BOM imports 16 rows through workbook controls and saves the calculated total', async () => {
for (const bookType of ['xls','xlsx']) {
const saved=[], checks=[];
const state=await harness('product/hardware-cost',{
validateHardwareCostStepOne:async payload=>{checks.push(plain(payload));return {data:{}};},
saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}),
});
const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false});
const downloads=[], errors=[];
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{success(){},error:message=>errors.push(message)},ElMessageBox:{confirm:async()=>{}},
});
await tools.downloadTemplate();
const workbook=downloads[0].workbook;
const data=[['序号','物料名称','选型规格参数','单价(元)','数量'],...Array.from({length:16},(_,i)=>[i+1,'元器件'+(i+1),'规格'+(i+1),(i+1)+0.5,2])];
workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet(data);
const bytes=XLSX.write(workbook,{type:'buffer',bookType});
const input={target:{value:'bom',files:[{name:'BOM.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}};
await tools.importFile(input);
assert.deepEqual(errors,[]);
assert.equal(input.target.value,'');
assert.equal(saved.length,0,'import updates the form until the student saves');
assert.equal(state.rows.value.length,16);
assert.equal(state.rows.value[15].materialName,'元器件16');
assert.equal(state.rows.value[15].specification,'规格16');
assert.equal(state.totalAmount.value,288);
await state.saveStepOne(false);
assert.equal(checks.length,1);
assert.equal(checks[0].items.length,16);
assert.equal(saved.length,1);
assert.equal(saved[0].key,'hardware-cost');
const answer=JSON.parse(saved[0].payload.step1Answer);
assert.equal(answer.items.length,16); assert.equal(answer.totalAmount,'288.00');
assert.equal(answer.items[15].unitPrice,16.5); assert.equal(answer.items[15].quantity,2);
assert.equal(state.costRows.value.length,16,'saved materials continue into step two');
}
});
test('numeric Excel BOM supports 40 rows and rejects excess rows or invalid quantities atomically', async () => {
const h=await helpers;
const state=await harness('product/hardware-cost');
const table=state.numericExcelTables.value[0];
const data=[h.templateRows(table)[0],...Array.from({length:40},(_,i)=>[i+1,'元器件'+(i+1),'规格',1.25,2])];
table.apply(h.parseTableRows(data,table).rows);
assert.equal(state.rows.value.length,40); assert.equal(state.totalAmount.value,100);
const before=JSON.stringify(state.rows.value);
assert.throws(()=>h.parseTableRows([...data,[41,'多余物料','规格',1,1]],state.numericExcelTables.value[0]),/范围/);
for (const quantity of [0,-1,1.5,10000,'abc']) {
const bad=data.map(row=>[...row]); bad[2][4]=quantity;
assert.throws(()=>h.parseTableRows(bad,state.numericExcelTables.value[0]));
assert.equal(JSON.stringify(state.rows.value),before);
}
});
test('numeric Excel BOM first and second steps render import controls directly above their tables', async () => {
const filename=path.resolve(__dirname,'../src/views/product/hardware-cost.vue');
const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor;
const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content);
const ssrRender=new Function('require',code)(require);
const state=await harness('product/hardware-cost');
const render=async step=>{
state.currentStep.value=step;
const app=Vue.createSSRApp({setup:()=>state,ssrRender});
app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null});
for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElIcon','ArrowLeft','ArrowRight','CircleCheck','DataAnalysis']) app.component(name,{render:()=>null});
app.config.warnHandler=()=>{};
return require('@vue/server-renderer').renderToString(app);
};
const html=await render(1);
const toolbar=html.indexOf('data-test-excel="bom"');
assert.ok(toolbar>html.indexOf('第一行是可编辑示例'));
assert.ok(toolbar<html.indexOf('class="bom-table-wrap"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/单价(元)/); assert.match(html,/金额(元)/);
const batch=await render(2);
const batchTools=batch.indexOf('data-test-excel="batch"');
assert.ok(batchTools>batch.indexOf('100 台与 10000 台单台成本'));
assert.ok(batchTools<batch.indexOf('class="bom-table-wrap"'));
assert.match(batch,/小批量 100 台(元\/台)/); assert.match(batch,/大批量 10000 台(元\/台)/);
for (const step of [2,3]) assert.equal(((await render(step)).match(/data-test-excel=/g)||[]).length,1);
});
test('numeric Excel BOM batch costs import 16 materials and save without changing constraints or step one', async () => {
for (const bookType of ['xls','xlsx']) {
const saved=[], validations=[], errors=[], downloads=[];
const state=await harness('product/hardware-cost',{
validateHardwareCostStepTwo:async payload=>{
validations.push(plain(payload));
return {data:{...payload,valid:true,
smallBatchTotal:payload.items.reduce((sum,r)=>sum+r.smallBatchUnitCost,0),
largeBatchTotal:payload.items.reduce((sum,r)=>sum+r.largeBatchUnitCost,0)}};
},
saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}),
});
state.rows.value=Array.from({length:16},(_,i)=>({...state.createBlankRow(),materialName:'物料'+(i+1),specification:'规格'+(i+1),unitPrice:'1',quantity:1}));
const original=plain(state.rows.value);
state.savedStepOneItems.value=state.stepOnePayload().items;
state.syncStepTwoRows(); state.currentStep.value=2;
state.stepTwo.smallBatchConstraint='210'; state.stepTwo.largeBatchConstraint='150';
const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false});
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}},
});
await tools.downloadTemplate();
const workbook=downloads[0].workbook;
const sheet=workbook.Sheets[workbook.SheetNames[0]];
const data=XLSX.utils.sheet_to_json(sheet,{header:1,defval:''});
assert.equal(data.length,17);
assert.ok(data.slice(1).every(r=>r[2]===''&&r[3]===''));
assert.deepEqual(data.slice(1).map(r=>r[1]),original.map(r=>r.materialName));
const filled=data.map((row,index)=>index===0?row:[...row.slice(0,2),index===1?0:index,index===1?0:index/2]);
// Keep each row's serial when changing the row order in Excel.
workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet([filled[0],...filled.slice(1).reverse()]);
const bytes=XLSX.write(workbook,{type:'buffer',bookType});
await tools.importFile({target:{value:'batch',files:[{name:'成本.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.deepEqual(errors,[]); assert.equal(saved.length,0);
assert.equal(state.costRows.value.length,16);
assert.equal(state.costRows.value[0].smallBatchUnitCost,'0');
assert.equal(state.costRows.value[15].largeBatchUnitCost,'8');
assert.equal(state.smallBatchTotal.value,135); assert.equal(state.largeBatchTotal.value,67.5);
assert.equal(state.stepTwo.smallBatchConstraint,'210'); assert.equal(state.stepTwo.largeBatchConstraint,'150');
assert.deepEqual(plain(state.rows.value),original);
await state.saveStepTwo();
assert.equal(validations.length,1); assert.equal(saved.length,1);
assert.equal(saved[0].key,'hardware-cost');
assert.equal(saved[0].payload.currentStep,2);
const answer=JSON.parse(saved[0].payload.step2Answer);
assert.equal(answer.items.length,16); assert.equal(answer.smallBatchTotal,135); assert.equal(answer.largeBatchTotal,67.5);
assert.equal(answer.smallBatchConstraint,210); assert.equal(answer.largeBatchConstraint,150);
assert.equal(state.stepTwoSaved.value,true);
assert.deepEqual(plain(state.rows.value),original);
}
});
test('numeric Excel BOM batch costs reject renamed materials and bad costs without partial updates', async () => {
const h=await helpers;
const state=await harness('product/hardware-cost');
state.rows.value=Array.from({length:3},(_,i)=>({...state.createBlankRow(),materialName:'物料'+(i+1)}));
state.syncStepTwoRows(state.rows.value); state.currentStep.value=2;
state.stepTwo.smallBatchConstraint='210'; state.stepTwo.largeBatchConstraint='150';
const table=state.numericExcelTables.value[0];
const header=h.templateRows(table)[0];
const before=JSON.stringify(state.costRows.value);
for (const bad of [[2,'改名物料',2,1],[2,'物料2',-1,1],[2,'物料2','abc',1],[4,'物料4',2,1],[1,'物料1',2,1]]) {
assert.throws(()=>h.parseTableRows([header,[1,'物料1',1,0.5],bad],table));
assert.equal(JSON.stringify(state.costRows.value),before);
}
const file={name:'成本.xlsx',size:100};
await assert.rejects(h.importTableFile(file,table,{
readWorkbook:async()=>[header,[2,'物料2',22,11]],
confirm:async()=>{throw Error('cancel');},isCurrent:()=>true,
}));
assert.equal(JSON.stringify(state.costRows.value),before);
table.apply(h.parseTableRows([header,[2,'物料2',22,11]],table).rows);
assert.equal(state.costRows.value[0].smallBatchUnitCost,'');
assert.equal(state.costRows.value[1].smallBatchUnitCost,'22');
assert.equal(state.costRows.value[1].largeBatchUnitCost,'11');
assert.equal(state.costRows.value[2].smallBatchUnitCost,'');
assert.equal(state.stepTwo.smallBatchConstraint,'210'); assert.equal(state.stepTwo.largeBatchConstraint,'150');
});
test('numeric Excel supplier scores import five channels and save both weighted scenarios without changing weights', async () => {
for (const bookType of ['xls','xlsx']) {
const saved=[], downloads=[], errors=[];
let state;
state=await harness('channel/supplier',{
ElMessage:{success(){},error:m=>errors.push(m),warning:m=>errors.push(m)},
validateSupplierEvaluationStepTwo:async payload=>{
const total=(r,scenario)=>Number(r.scores.reduce((sum,d)=>sum+d.score*state.rows.value.find(w=>w.name===d.dimension)[scenario+'Weight']/100,0).toFixed(2));
return {data:{valid:true,weights:state.buildStepOnePayload().items,
smallBatchChannels:payload.smallBatchChannels.map(r=>({...r,weightedTotal:total(r,'smallBatch')})),
largeBatchChannels:payload.largeBatchChannels.map(r=>({...r,weightedTotal:total(r,'largeBatch')}))}};
},
saveStudentTrainingAnswer:async(key,payload)=>saved.push({key,payload}),
});
const small=[15,25,20,25,15], large=[40,15,25,10,10];
state.rows.value.forEach((r,i)=>{r.smallBatchWeight=small[i];r.largeBatchWeight=large[i];});
state.stepOneSaved.value=true; state.currentStep.value=2;
const weights=plain(state.rows.value), ids=state.channelRows.value.map(r=>r.id);
state.channelRows.value.forEach(r=>{r.smallWeightedTotal=99;r.largeWeightedTotal=99;});
const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false});
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}},
});
await tools.downloadTemplate();
const workbook=downloads[0].workbook;
const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''});
assert.deepEqual(template[0],['序号','渠道','采购成本','交货周期','品质可靠性','采购灵活性','服务支持']);
assert.equal(template.length,6);
assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v==='')));
const scores=[[9,7,10,6,7],[7,9,8,9,8],[4,5,4,8,5],[9,8,8,6,10],[0,3,9,5,10]];
const data=[template[0],...scores.map((r,i)=>[i+1,'渠道'+(i+1),...r]).reverse()];
workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet(data);
const bytes=XLSX.write(workbook,{type:'buffer',bookType});
await tools.importFile({target:{value:'scores',files:[{name:'供应渠道评分.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.deepEqual(errors,[]); assert.equal(saved.length,0);
assert.deepEqual(plain(state.rows.value),weights);
assert.deepEqual(state.channelRows.value.map(r=>r.id),ids);
state.channelRows.value.forEach((row,i)=>{
assert.equal(row.channel,'渠道'+(i+1));
state.rows.value.forEach((dimension,j)=>assert.equal(row.scores[dimension.key],scores[i][j]));
assert.equal(row.smallWeightedTotal,null); assert.equal(row.largeWeightedTotal,null);
const expected=weights=>scores[i].reduce((sum,value,j)=>sum+value*weights[j]/100,0).toFixed(2);
assert.equal(state.weightedScore(row,'smallBatch'),expected(small));
assert.equal(state.weightedScore(row,'largeBatch'),expected(large));
});
assert.equal(await state.saveStepTwo(),true);
assert.equal(saved.length,1); assert.equal(saved[0].key,'supplier-evaluation');
const answer=JSON.parse(saved[0].payload.step2Answer);
assert.equal(answer.smallBatchChannels.length,5); assert.equal(answer.largeBatchChannels.length,5);
assert.equal(answer.smallBatchChannels[0].weightedTotal,7.65);
assert.equal(answer.largeBatchChannels[0].weightedTotal,8.45);
assert.deepEqual(plain(state.rows.value),weights);
assert.equal(state.stepTwoSaved.value,true);
}
});
test('numeric Excel supplier scores reject invalid scores and preserve unlisted channels or cancellation', async () => {
const h=await helpers;
const state=await harness('channel/supplier'); state.currentStep.value=2;
const table=state.numericExcelTables.value[0];
const header=h.templateRows(table)[0];
const before=JSON.stringify(state.channelRows.value), weights=JSON.stringify(state.rows.value);
for(const score of [-1,11,1.5,'abc']) {
assert.throws(()=>h.parseTableRows([header,[1,'有效渠道',1,2,3,4,5],[2,'无效渠道',score,2,3,4,5]],table));
assert.equal(JSON.stringify(state.channelRows.value),before);
}
assert.throws(()=>h.parseTableRows([header,[6,'超出五行',1,2,3,4,5]],table));
assert.throws(()=>h.parseTableRows([header,[1,'重复1',1,2,3,4,5],[1,'重复2',1,2,3,4,5]],table));
assert.throws(()=>h.parseTableRows([[...header,'试产加权总分'],[1,'渠道',1,2,3,4,5,9]],table));
await assert.rejects(h.importTableFile({name:'评分.xlsx',size:100},table,{
readWorkbook:async()=>[header,[2,'渠道2',10,0,3,4,5]],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true,
}));
assert.equal(JSON.stringify(state.channelRows.value),before);
table.apply(h.parseTableRows([header,[2,'渠道2',10,0,3,4,5]],table).rows);
assert.equal(state.channelRows.value[0].channel,'');
assert.equal(state.channelRows.value[1].channel,'渠道2');
assert.equal(state.channelRows.value[1].scores.procurementCost,10);
assert.equal(state.channelRows.value[1].scores.deliveryCycle,0);
assert.equal(state.channelRows.value[2].channel,'');
assert.equal(JSON.stringify(state.rows.value),weights);
});
test('numeric Excel supplier step two renders one import toolbar inside the scoring section', async () => {
const filename=path.resolve(__dirname,'../src/views/channel/supplier.vue');
const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor;
const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content);
const ssrRender=new Function('require',code)(require);
const state=await harness('channel/supplier');
const render=async step=>{
state.currentStep.value=step;
const app=Vue.createSSRApp({setup:()=>state,ssrRender});
app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null});
for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElIcon','ArrowLeft','ArrowRight','CircleCheck','Plus','Delete']) app.component(name,{render:()=>null});
app.directive('loading',{}); app.config.warnHandler=()=>{};
return require('@vue/server-renderer').renderToString(app);
};
const html=await render(2);
const toolbar=html.indexOf('data-test-excel="scores"');
assert.ok(toolbar>html.indexOf('供应渠道评分与加权对比'));
assert.ok(toolbar<html.indexOf('class="table-scroll"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/维度评分(0–10 分)/);
assert.equal(((await render(1)).match(/data-test-excel=/g)||[]).length,1);
assert.equal(((await render(3)).match(/data-test-excel=/g)||[]).length,0);
});
test('numeric Excel ignores a pending import after its table controls unmount', async () => {
const h=await helpers;
const state=await harness('channel/supplier'); state.currentStep.value=2;
const before=JSON.stringify(state.channelRows.value);
const table=state.numericExcelTables.value[0];
let unmount;
const errors=[];
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>({tables:[table],contextKey:2,disabled:false}),
onBeforeUnmount:callback=>{unmount=callback;},
XLSX_IMPORT:XLSX,
ElMessage:{success(){throw Error('Unmounted controls must not apply the import');},error:m=>errors.push(m)},
ElMessageBox:{confirm:async()=>{state.currentStep.value=1;unmount();}},
});
const book=XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet([h.templateRows(table)[0],[1,'不应回填的渠道',1,2,3,4,5]]),'填写数据');
const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'});
await tools.importFile({target:{value:'file',files:[{name:'评分.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.equal(JSON.stringify(state.channelRows.value),before);
assert.equal(errors.length,1); assert.match(errors[0],/已变化/);
});
test('numeric Excel PSM imports six price ranges and saves percentages without changing chart or price points', async () => {
for(const bookType of ['xls','xlsx']) {
const saved=[], validations=[], errors=[], downloads=[];
const state=await harness('product/price',{
validateProductPricingStepFour:async payload=>{validations.push(plain(payload));return {data:payload};},
saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}),
});
state.currentStep.value=4;
const ranges=['≤399元','399~499元','499~599元','599~699元','699~799元','≥799元'];
state.psmRows.value.forEach((r,i)=>{r.priceRange=ranges[i];});
Object.assign(state.psmPricePoints,{optimalPrice:'599',acceptablePrice:'699',acceptableRange:'499~699元'});
Object.assign(state.psmChart,{url:'/file/existing-chart.png',name:'已有折线图.png'});
state.unitCost.value='99'; state.validationMessage.value='旧的校验提示';
const ids=state.psmRows.value.map(r=>r.id), chart=plain(state.psmChart), points=plain(state.psmPricePoints);
const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false});
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}},
});
await tools.downloadTemplate();
const workbook=downloads[0].workbook;
const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''});
assert.equal(template.length,7);
assert.deepEqual(template.slice(1).map(r=>r[1]),ranges);
assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v==='')));
const values=[[0,100,3,100],[3,60,11.5,50],[9,30,29,18],[29,14,71,8],[67,6,91,3],[100,2,100,1]];
const data=[template[0],...values.map((r,i)=>[i+1,ranges[i],...r]).reverse()];
const sheet=XLSX.utils.aoa_to_sheet(data);
sheet.E2={t:'n',v:1,z:'0%'}; // A genuine Excel percentage cell, displayed as 100%.
sheet.E6={t:'s',v:'11.5%'};
workbook.Sheets[workbook.SheetNames[0]]=sheet;
const bytes=XLSX.write(workbook,{type:'buffer',bookType});
await tools.importFile({target:{value:'psm',files:[{name:'PSM.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.deepEqual(errors,[]); assert.equal(saved.length,0);
assert.deepEqual(plain(state.psmRows.value.map(r=>r.id)),plain(ids));
state.psmRows.value.forEach((row,i)=>{
assert.equal(row.priceRange,ranges[i]);
['tooExpensive','tooCheap','expensiveAcceptable','cheapValue'].forEach((field,j)=>assert.equal(Number(row[field]),values[i][j]));
});
assert.equal(state.validationMessage.value,'');
assert.equal(state.unitCost.value,'99');
assert.deepEqual(plain(state.psmChart),chart); assert.deepEqual(plain(state.psmPricePoints),points);
assert.equal(await state.saveStepFour(),true);
assert.equal(validations.length,1); assert.equal(saved.length,1);
assert.equal(saved[0].key,'product-pricing'); assert.equal(saved[0].payload.currentStep,4);
const answer=JSON.parse(saved[0].payload.step4Answer);
assert.equal(answer.psmRows.length,6); assert.equal(answer.psmRows[1].expensiveAcceptable,11.5);
assert.equal(answer.psmRows[5].tooExpensive,100);
assert.equal(answer.chart.url,chart.url); assert.equal(answer.pricePoints.optimalPrice,599);
const restored=await harness('product/price'); restored.applyStepFourProgress(answer);
assert.equal(restored.psmRows.value[1].expensiveAcceptable,11.5);
}
});
test('numeric Excel PSM rejects invalid percentages and changed price ranges without overwriting existing rows', async () => {
const h=await helpers;
const state=await harness('product/price'); state.currentStep.value=4;
state.psmRows.value.forEach(r=>{r.tooExpensive='1';r.tooCheap='2';r.expensiveAcceptable='3';r.cheapValue='4';});
const table=state.numericExcelTables.value[0];
const header=h.templateRows(table)[0], before=JSON.stringify(state.psmRows.value);
const first=state.psmRows.value[0].priceRange, second=state.psmRows.value[1].priceRange;
for(const bad of [-1,100.01,'abc','1.2.3']) {
assert.throws(()=>h.parseTableRows([header,[1,first,5,6,7,8],[2,second,bad,2,3,4]],table));
assert.equal(JSON.stringify(state.psmRows.value),before);
}
assert.throws(()=>h.parseTableRows([header,[1,'改动了价格区间',5,6,7,8]],table));
assert.throws(()=>h.parseTableRows([header,[1,first,5,6,7,8],[1,first,5,6,7,8]],table));
await assert.rejects(h.importTableFile({name:'PSM.xlsx',size:100},table,{
readWorkbook:async()=>[header,[2,second,'25%',2,3,4]],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true,
}));
assert.equal(JSON.stringify(state.psmRows.value),before);
state.validationMessage.value='旧提示';
table.apply(h.parseTableRows([header,[2,second,'25%',2,3,4]],table).rows);
assert.equal(state.psmRows.value[0].tooExpensive,'1');
assert.equal(state.psmRows.value[1].tooExpensive,'25');
assert.equal(state.psmRows.value[2].tooExpensive,'1');
assert.equal(state.validationMessage.value,'');
});
test('numeric Excel PSM import controls render above the fourth step table with original units', async () => {
const filename=path.resolve(__dirname,'../src/views/product/price.vue');
const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor;
const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content);
const ssrRender=new Function('require',code)(require);
const state=await harness('product/price');
const render=async step=>{
state.currentStep.value=step;
const app=Vue.createSSRApp({setup:()=>state,ssrRender});
app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null});
for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElButton','ElSelect','ElOption','ElImage','ElIcon','ArrowLeft','ArrowRight','CircleCheck']) app.component(name,{render:()=>null});
app.config.warnHandler=()=>{};
return require('@vue/server-renderer').renderToString(app);
};
const html=await render(4);
const toolbar=html.indexOf('data-test-excel="psm"');
assert.ok(toolbar>html.indexOf('class="psm-toolbar"'));
assert.ok(toolbar<html.indexOf('class="table-scroll"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/价格(元)/); assert.match(html,/累计占比(%)/);
for(const step of [1,2,3]) assert.equal(((await render(step)).match(/data-test-excel=/g)||[]).length,1);
});
test('numeric Excel diagnosis imports current channel rates and industry averages through save and validation', async () => {
for(const bookType of ['xls','xlsx']) {
const saved=[], validations=[], downloads=[], errors=[];
const state=await harness('assessment/diagnosis',{
saveStudentTrainingAnswer:async(key,payload)=>saved.push({key,payload}),
validateProductDiagnosisIterationStepOne:async data=>{validations.push(plain(data));return {data:{valid:true}};},
});
state.addFunnelChannel(); state.channels.value[4].name='唯品会';
Object.assign(state.funnelChart.value,{url:'/file/existing-funnel.png',name:'已有漏斗图.png'});
Object.assign(state.anomalyRows.value[0],{channelId:'tmall',channel:'天猫',linkNode:state.nodes[0],storeConversionRate:5,industryAverageConversionRate:6,anomalyAnalysis:'保留分析'});
const channels=plain(state.channels.value), anomaly=plain(state.anomalyRows.value), chart=plain(state.funnelChart.value);
const props=Vue.reactive({get tables(){return state.numericExcelTables.value.filter(t=>t.id==='funnel');},get contextKey(){return state.currentStep.value;},disabled:false});
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}},
});
await tools.downloadTemplate();
const workbook=downloads[0].workbook;
const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''});
assert.equal(template.length,6); assert.equal(template[0].length,8);
assert.deepEqual(template[0].slice(2,-1),channels.map(c=>c.name+'转化率(%)'));
assert.equal(template[0].at(-1),'行业平均值(%)');
assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v==='')));
const values=state.nodes.map((_,i)=>channels.map((_,j)=>i===0&&j===0?0:i===4&&j===4?100:i*10+j+0.25));
const industry=[3.5,8.5,32,90.5,4.8];
const rows=[template[0],...state.nodes.map((node,i)=>[i+1,node,...values[i],industry[i]]).reverse()];
const sheet=XLSX.utils.aoa_to_sheet(rows);
sheet.G2={t:'n',v:1,z:'0%'}; sheet.H2={t:'n',v:0.048,z:'0.00%'};
workbook.Sheets[workbook.SheetNames[0]]=sheet;
const bytes=XLSX.write(workbook,{type:'buffer',bookType});
await tools.importFile({target:{value:'funnel',files:[{name:'转化率.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.deepEqual(errors,[]); assert.equal(saved.length,0);
assert.deepEqual(plain(state.channels.value),channels);
assert.deepEqual(plain(state.anomalyRows.value),anomaly); assert.deepEqual(plain(state.funnelChart.value),chart);
state.conversionRates.value.forEach((row,i)=>{
assert.equal(row.linkNode,state.nodes[i]); assert.equal(row.industryAverage,industry[i]);
channels.forEach((channel,j)=>assert.equal(row.channelRates[channel.id],values[i][j]));
});
assert.equal(state.funnelRatesComplete.value,true);
await state.persistStepOne(false);
assert.equal(saved[0].key,'product-diagnosis-iteration');
assert.equal(saved[0].payload.currentStep,1);
const answer=JSON.parse(saved[0].payload.step1Answer);
assert.equal(answer.channels.length,5); assert.equal(answer.conversionRates.length,5);
assert.equal(answer.conversionRates[4].industryAverage,4.8);
assert.equal(answer.funnelChartUrl,chart.url); assert.equal(answer.anomalyRows[0].anomalyAnalysis,'保留分析');
await state.validateStepOne();
assert.equal(validations.length,1); assert.equal(state.currentStep.value,2);
assert.equal(saved.at(-1).payload.currentStep,2);
}
});
test('numeric Excel diagnosis rejects invalid rates and wrong channel or node templates atomically', async () => {
const h=await helpers;
const state=await harness('assessment/diagnosis');
state.conversionRates.value.forEach(row=>{row.industryAverage=7;state.channels.value.forEach(c=>{row.channelRates[c.id]=8;});});
const table=state.numericExcelTables.value.find(t=>t.id==='funnel'), header=h.templateRows(table)[0];
const valid=[1,state.nodes[0],1,2,3,4,5], before=JSON.stringify(state.conversionRates.value);
for(const value of [-1,100.01,1.001,'abc']) {
const bad=[2,state.nodes[1],value,2,3,4,5];
assert.throws(()=>h.parseTableRows([header,valid,bad],table));
assert.equal(JSON.stringify(state.conversionRates.value),before);
}
const changedHeader=[...header]; changedHeader[2]='其他渠道转化率(%)';
assert.throws(()=>h.parseTableRows([changedHeader,valid],table));
assert.throws(()=>h.parseTableRows([header,[1,'未知节点',1,2,3,4,5]],table));
assert.throws(()=>h.parseTableRows([header,valid,valid],table));
await assert.rejects(h.importTableFile({name:'转化率.xlsx',size:100},table,{
readWorkbook:async()=>[header,valid],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true,
}));
assert.equal(JSON.stringify(state.conversionRates.value),before);
table.apply(h.parseTableRows([header,valid],table).rows);
assert.equal(state.conversionRates.value[0].channelRates.tmall,1);
assert.equal(state.conversionRates.value[1].channelRates.tmall,8);
assert.equal(state.conversionRates.value[1].industryAverage,7);
});
test('numeric Excel diagnosis stops pending imports when channel names or columns change', async () => {
const h=await helpers;
for(const change of ['rename','add','remove']) {
const errors=[];
const state=await harness('assessment/diagnosis');
state.conversionRates.value.forEach(row=>state.channels.value.forEach(c=>{row.channelRates[c.id]=7;}));
const props=Vue.reactive({get tables(){return state.numericExcelTables.value.filter(t=>t.id==='funnel');},contextKey:1,disabled:false});
const table=props.tables[0];
const tools=await harness('components/TrainingExcelTools',{
defineProps:()=>props,XLSX_IMPORT:XLSX,
ElMessage:{success(){throw Error('Changed channel configuration must reject import');},error:m=>errors.push(m)},
ElMessageBox:{confirm:async()=>{
if(change==='rename')state.channels.value[0].name='新的渠道名称';
if(change==='add')state.addFunnelChannel();
if(change==='remove')state.removeFunnelChannel('tmall');
}},
});
const book=XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet([h.templateRows(table)[0],[1,state.nodes[0],99,99,99,99,99]]),'填写数据');
const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'});
await tools.importFile({target:{value:'funnel',files:[{name:'转化率.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}});
assert.equal(state.conversionRates.value[0].channelRates.jd,7);
assert.equal(state.conversionRates.value[0].industryAverage,null);
assert.equal(errors.length,1); assert.match(errors[0],/已变化/);
if(change==='rename')assert.equal(state.channels.value[0].name,'新的渠道名称');
if(change==='add')assert.equal(state.channels.value.length,5);
if(change==='remove')assert.equal(state.channels.value.some(c=>c.id==='tmall'),false);
}
});
test('numeric Excel diagnosis first step renders separate controls above the funnel and anomaly tables', async () => {
const filename=path.resolve(__dirname,'../src/views/assessment/diagnosis.vue');
const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor;
const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content);
const ssrRender=new Function('require',code)(require);
const state=await harness('assessment/diagnosis');
const render=async step=>{
state.currentStep.value=step;
const app=Vue.createSSRApp({setup:()=>state,ssrRender});
app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables.map(t=>t.id).join(',')},'下载 Excel 模板 / 导入 Excel'):null});
for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElSelect','ElOption','ElImage','ElIcon','ArrowLeft','ArrowRight','CircleCheck']) app.component(name,{render:()=>null});
app.config.warnHandler=()=>{};
return require('@vue/server-renderer').renderToString(app);
};
const html=await render(1), funnel=html.indexOf('data-test-excel="funnel"'), anomaly=html.indexOf('data-test-excel="anomaly"');
assert.ok(funnel>html.indexOf('计算各节点转化率'));
assert.ok(funnel<html.indexOf('class="table-wrap"'));
assert.ok(anomaly>html.indexOf('定位异常节点'));
assert.ok(anomaly<html.indexOf('class="diagnosis-table"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,2);
assert.match(html,/class="unit">%/);
assert.equal(((await render(2)).match(/data-test-excel=/g)||[]).length,0);
assert.match(await render(3),/data-test-excel="ab"/);
});

@ -1,195 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { pathToFileURL } = require('node:url');
const Vue = require('vue');
const XLSX = require('xlsx');
const babel = require('@babel/parser');
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc');
const filename = path.resolve(__dirname, '../src/views/foundation/product-development-process.vue');
const source = fs.readFileSync(filename, 'utf8');
const helpers = import(pathToFileURL(path.resolve(__dirname, '../src/views/foundation/processScheduleExcel.mjs')).href);
const plain = value => JSON.parse(JSON.stringify(value));
async function harness(options = {}) {
const helper = await helpers;
let script = parse(source).descriptor.scriptSetup.content;
const ast = babel.parse(script, { sourceType: 'module' }).program.body;
for (const node of [...ast].reverse()) if (node.type === 'ImportDeclaration') script = script.slice(0, node.start) + script.slice(node.end);
const saved = [], downloads = [], messages = [], validations = [];
const context = { ...Vue, ...helper, onMounted() {}, watch() {},
getCurrentInstance: () => ({ proxy: { $modal: { msgSuccess: m => messages.push(m), msgError: m => messages.push(m), msgWarning: m => messages.push(m) } } }),
useUserStore: () => ({ userInfo: { userId: 'local-test' } }),
localStorage: { removeItem() {}, getItem: () => null, setItem() {} },
parseTrainingArray: (value, fallback) => Array.isArray(value) && value.length ? value : fallback,
XLSX: { ...XLSX, writeFile: (workbook, name) => downloads.push({ workbook, name }) },
ElMessageBox: { confirm: async () => { if (options.confirm) await options.confirm(); } },
saveStudentTrainingAnswer: async (key, payload) => saved.push({ key, payload }),
checkProductDevelopmentProcessStepTwo: async items => validations.push(plain(items)),
};
vm.runInNewContext(script + '\nglobalThis.page={processRows,currentStep,stepOnePassed,stepTwoPassed,importingSchedule,checking,saving,downloadScheduleTemplate,importScheduleExcel,exportScheduleList,saveCurrentProgress,saveAndGoToStepThree,buildStepTwoOutcome,restoreStepTwoOutcome,getStepTwoValidationMessage};', context);
const page = context.page;
page.currentStep.value = 2;
page.stepOnePassed.value = true;
page.processRows.value.forEach((row, index) => { row.classification = index % 2 ? '非关键任务' : '关键任务'; });
return { page, saved, downloads, messages, validations };
}
function workbookBytes(rows, bookType = 'xlsx', date1904 = false) {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), 'WBS排期表');
workbook.Workbook = { WBProps: { date1904 } };
return XLSX.write(workbook, { type: 'buffer', bookType });
}
function event(bytes, name = '排期.xlsx') {
return { target: { value: name, files: [{ name, size: bytes.length, arrayBuffer: async () => bytes }] } };
}
const headers = ['任务编号', '开始时间', '完成时间', '项目依赖关系'];
test('WBS Excel imports real xls and xlsx dates by task number and saves existing payloads', async () => {
for (const bookType of ['xls', 'xlsx']) {
const { page, saved, validations } = await harness();
const before = plain(page.processRows.value);
const data = [['完成时间', '是否关键任务', '任务编号', '项目依赖关系', '开始时间'],
...before.map((row, index) => [index === 0 ? 46325 : '2026/10/29', '修改分类也不生效', row.taskNo, '开始-开始(SS)', index === 0 ? 46315 : '2026年10月20日']).reverse()];
const input = event(workbookBytes(data, bookType), '排期.' + bookType);
await page.importScheduleExcel(input);
assert.equal(input.target.value, '');
assert.equal(saved.length, 0, 'Import does not submit answers');
assert.equal(page.currentStep.value, 2);
assert.equal(page.processRows.value[0].startDate, '2026-10-20');
assert.equal(page.processRows.value[0].endDate, '2026-10-30');
assert.equal(page.getStepTwoValidationMessage(), '');
page.processRows.value.forEach((row, index) => {
assert.equal(row.classification, before[index].classification);
assert.equal(row.task, before[index].task);
assert.equal(row.stage, before[index].stage);
assert.equal(row.taskNo, before[index].taskNo);
});
await page.saveCurrentProgress();
const payload = saved[0];
assert.equal(payload.key, 'product-development-process');
assert.equal(payload.payload.currentStep, 2);
const restored = await harness();
restored.page.restoreStepTwoOutcome(payload.payload.step2Answer);
assert.equal(restored.page.processRows.value[0].startDate, '2026-10-20');
assert.equal(restored.page.processRows.value[0].dependency, '开始-开始(SS)');
await page.saveAndGoToStepThree();
assert.equal(validations.length, 1);
assert.equal(validations[0].length, 19);
assert.equal(page.currentStep.value, 3);
}
});
test('WBS Excel template is blank and the existing exported list can be imported', async () => {
const { page, downloads } = await harness();
page.processRows.value[0].startDate = '2026-10-20';
page.processRows.value[0].endDate = '2026-10-21';
page.processRows.value[0].dependency = '无前置任务';
page.downloadScheduleTemplate();
const template = downloads[0].workbook;
assert.deepEqual(template.SheetNames, ['WBS排期表', '填写说明']);
const rows = XLSX.utils.sheet_to_json(template.Sheets.WBS排期表, { header: 1, defval: '' });
assert.equal(rows.length, 20);
assert.deepEqual(rows[0], ['阶段','任务编号','具体工作任务','是否关键任务','开始时间','完成时间','项目依赖关系']);
assert.ok(rows.slice(1).every(row => row.slice(4).every(value => value === '')));
assert.equal(rows[1][3], '关键任务');
page.exportScheduleList();
const bytes = XLSX.write(downloads[1].workbook, { type: 'buffer', bookType: 'xlsx' });
page.processRows.value[0].startDate = '2026-09-01';
await page.importScheduleExcel(event(bytes));
assert.equal(page.processRows.value[0].startDate, '2026-10-20');
assert.equal(page.processRows.value[0].dependency, '无前置任务');
});
test('WBS Excel rejects bad rows atomically and preserves tasks not imported', async () => {
const { page } = await harness();
page.processRows.value[1].startDate = '2026-09-01';
const before = plain(page.processRows.value);
const invalid = [
[headers, ['1.1','2026-02-29','2026-03-01','SS']],
[headers, ['1.1','2026-10-22','2026-10-20','SS']],
[headers, ['9.9','2026-10-20','2026-10-21','SS']],
[headers, ['1.1','2026-10-20','2026-10-21','SS'], ['1.1','','','']],
[headers, ['1.1','20/10/2026','','']],
[headers, ['1.1','2026-10-20','','x'.repeat(101)]],
[headers, ['','2026-10-20','','']],
[['任务编号','开始时间','开始日期','完成时间','项目依赖关系'], ['1.1','','','','']],
[['任务编号','开始时间','完成时间'], ['1.1','','']],
[headers],
];
for (const bad of invalid) {
const rows = bad[0] === headers ? [headers, ['1.2','2026-10-20','2026-10-21','SS'], ...bad.slice(1)] : bad;
// Header-only file should also be rejected rather than importing the valid prefix.
await page.importScheduleExcel(event(workbookBytes(bad.length === 1 ? bad : rows)));
assert.deepEqual(plain(page.processRows.value), before);
}
await page.importScheduleExcel(event(workbookBytes([[], ['完成日期','任务编号','开始日期','项目依赖关系'], [], ['2026.10.21',1.1,'2026-10-20','无前置任务']])));
assert.equal(page.processRows.value[0].startDate, '2026-10-20');
assert.deepEqual(plain(page.processRows.value[1]), before[1]);
await page.importScheduleExcel(event(workbookBytes([headers, ['1.1','','','']])));
assert.equal(page.processRows.value[0].startDate, '');
});
test('WBS Excel cancellation, prerequisite and concurrent edit guards preserve the page', async () => {
const bytes = workbookBytes([headers, ['1.1','2026-10-20','2026-10-21','SS']]);
const cancel = await harness({ confirm: async () => { throw 'cancel'; } });
const original = plain(cancel.page.processRows.value);
await cancel.page.importScheduleExcel(event(bytes));
assert.deepEqual(plain(cancel.page.processRows.value), original);
assert.deepEqual(cancel.messages, []);
const options = {};
const state = await harness(options);
options.confirm = async () => { state.page.processRows.value[0].dependency = '用户刚填写'; };
await state.page.importScheduleExcel(event(bytes));
assert.equal(state.page.processRows.value[0].dependency, '用户刚填写');
assert.equal(state.page.processRows.value[0].startDate, '');
options.confirm = async () => { state.page.currentStep.value = 3; };
await state.page.importScheduleExcel(event(bytes));
assert.equal(state.page.processRows.value[0].startDate, '');
state.page.currentStep.value = 2;
state.page.stepOnePassed.value = false;
options.confirm = async () => { throw Error('Prerequisite guard did not run'); };
const blocked = event(bytes); blocked.target.files[0].arrayBuffer = async () => { throw Error('File should not be read'); };
await state.page.importScheduleExcel(blocked);
assert.equal(blocked.target.value, '');
state.page.stepOnePassed.value = true;
const invalidFile = event(bytes, 'data.csv');
await state.page.importScheduleExcel(invalidFile);
const oversized = event(bytes); oversized.target.files[0].size = 6 * 1024 * 1024;
await state.page.importScheduleExcel(oversized);
assert.equal(state.page.processRows.value[0].startDate, '');
assert.equal(state.page.importingSchedule.value, false);
});
test('WBS Excel accepts leap dates and both Excel date systems without timezone shifts', async () => {
const { parseScheduleDate } = await helpers;
const options = { parseDateCode: XLSX.SSF.parse_date_code };
assert.equal(parseScheduleDate('2028-2-29','日期:',options), '2028-02-29');
assert.equal(parseScheduleDate(46315,'日期:',options), '2026-10-20');
assert.equal(parseScheduleDate(0,'日期:',{...options,date1904:true}), '1904-01-01');
assert.throws(() => parseScheduleDate(60,'日期:',options), /日期不存在/);
assert.throws(() => parseScheduleDate(46315.5,'日期:',options), /不要包含时间/);
for (const value of ['2026-04-31','2026-13-01','0000-01-01','2026-00-00','not-a-date']) assert.throws(() => parseScheduleDate(value,'日期:',options));
for (const date1904 of [false,true]) {
const state = await harness();
const start = 46315 - (date1904 ? 1462 : 0);
await state.page.importScheduleExcel(event(workbookBytes([headers,['1.1',start,start+1,'SS']], 'xlsx', date1904)));
assert.equal(state.page.processRows.value[0].startDate, '2026-10-20');
}
});
test('WBS Excel controls compile inside step two with the prerequisite restriction', () => {
const descriptor = parse(source).descriptor;
compileScript(descriptor, { id: 'wbs-excel' });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'wbs-excel' }).errors, []);
const start = source.indexOf('<template v-else-if="currentStep === 2">');
const end = source.indexOf('<template v-else-if="currentStep === 3">');
for (const handler of ['downloadScheduleTemplate','importScheduleExcel']) {
const index = source.indexOf(handler);
assert.ok(index > start && index < end);
}
assert.match(source.slice(start,end), /:disabled="!hasCompletedStepOne \|\| checking \|\| saving \|\| importingSchedule"/);
});

@ -1,51 +0,0 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
const editors = ["teacherEnd", "schoolAdmin"].map((role) => path.resolve(__dirname, `../src/views/${role}/trainingTask/index.vue`));
function page(filename) {
const source = fs.readFileSync(filename, "utf8");
const calls = [], errors = [];
const context = { taskForm: { referenceAnswerName: "existing.pdf", referenceAnswerUrl: "/file/existing.pdf" }, uploadingField: { value: "" },
proxy: { $modal: { msgError: (text) => errors.push(text), msgSuccess() {} } },
FormData: class { constructor() { this.values = new Map(); } append(key, value) { this.values.set(key, value); } get(key) { return this.values.get(key); } },
normalizeMaterialUrl: (value) => value, materialLabel: (key) => key,
uploadTrainingTaskMaterial: async (data) => { calls.push(data); return { originalFilename: data.get("file").name, url: "/file/uploaded.pdf" }; },
};
const handlers = source.slice(source.indexOf("async function handleMaterialChange("), source.indexOf("function clearMaterial("));
const slots = source.match(/const materialSlots = \[[\s\S]*?\];/)[0];
vm.runInNewContext(slots + "\n" + handlers + "\nglobalThis.page={handleMaterialChange,materialSlots};", context);
return { ...context, ...context.page, source, calls, errors };
}
test("both task editors block non PDF reference uploads without replacing existing files", async () => {
for (const filename of editors) {
const editor = page(filename);
assert.equal(editor.materialSlots.find((slot) => slot.key === "referenceAnswer").accept, ".pdf,application/pdf");
for (const name of ["answer.doc", "answer.docx", "answer.xlsx", "answer.pdf.exe"]) {
await editor.handleMaterialChange("referenceAnswer", { raw: { name, type: "application/pdf" } });
}
assert.equal(editor.calls.length, 0);
assert.equal(editor.errors.length, 4);
assert.match(editor.errors[0], /仅支持 PDF/);
assert.equal(editor.taskForm.referenceAnswerName, "existing.pdf");
assert.equal(editor.taskForm.referenceAnswerUrl, "/file/existing.pdf");
}
});
test("PDF reference uploads and other materials keep separate upload rules", async () => {
for (const filename of editors) {
const editor = page(filename);
await editor.handleMaterialChange("referenceAnswer", { raw: { name: "答案.PDF" } });
assert.equal(editor.calls[0].get("materialType"), "referenceAnswer");
assert.equal(editor.taskForm.referenceAnswerName, "答案.PDF");
assert.equal(editor.taskForm.referenceAnswerUrl, "/file/uploaded.pdf");
await editor.handleMaterialChange("material", { raw: { name: "案例.docx" } });
assert.equal(editor.calls[1].get("materialType"), "material");
assert.equal(editor.taskForm.materialName, "案例.docx");
const { descriptor, errors } = parse(editor.source);
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "reference-answer-upload" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: "reference-answer-upload" }).errors, []);
}
});

@ -1,132 +0,0 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const Vue = require("vue");
const XLSX = require("xlsx");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
const filename = path.resolve(__dirname, "../src/views/test/index.vue");
const source = fs.readFileSync(filename, "utf8");
const helperSource = fs.readFileSync(path.resolve(__dirname, "../src/views/test/releaseChannelScoreExcel.js"), "utf8");
const plain = (value) => JSON.parse(JSON.stringify(value));
function harness(confirm = true) {
const messages = [], saved = [], downloads = [];
const context = { ...Vue, excelComputed: Vue.computed, onMounted() {},
ElMessage: { success: (value) => messages.push(value), error: (value) => messages.push(value) },
ElMessageBox: { confirm: async () => { if (!confirm) throw new Error("cancel"); } },
XLSX_IMPORT: { ...XLSX, writeFile: (workbook, name) => downloads.push({ workbook, name }) },
saveStudentTrainingAnswer: async (taskKey, payload) => saved.push({ taskKey, payload }),
};
const script = parse(source).descriptor.scriptSetup.content.replace(/^import .*\r?\n/gm, "").replaceAll('await import("xlsx")', "XLSX_IMPORT");
vm.runInNewContext(helperSource.replace(/export /g, "") + "\n" + script + "\nglobalThis.page={activeStep,weightRows,channelRows,scoreRows,scoringMetrics,importingScores,importScoreExcel,downloadScoreTemplate,saveScoreStep,syncScoreRows,parseScoreExcelRows,scoreExcelColumns};", context);
const page = context.page;
page.activeStep.value = 3;
page.weightRows.value.forEach((row, index) => { row.weight = index === 0 ? 40 : 10; });
page.channelRows.value = [{ channel: "天猫" }, { channel: "京东" }];
page.syncScoreRows();
page.scoreRows.value.forEach((row) => { row.weightedScore = 9; row.dimensions.forEach((metric) => { metric.score = 9; }); });
return { ...page, messages, saved, downloads };
}
function bytes(rows, bookType = "xlsx") {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), "得分");
return XLSX.write(workbook, { type: "buffer", bookType });
}
function fileEvent(data, bookType = "xlsx") {
return { target: { value: `得分.${bookType}`, files: [{ name: `得分.${bookType}`, arrayBuffer: async () => data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) }] } };
}
const headers = (page) => Array.from(page.scoreExcelColumns(page.scoringMetrics), (column) => column.label);
const validRow = ["京东", 0, 1.5, 2, 3, 4, 10, 6, 3.25];
test("score xls and xlsx imports match channels and preserve weights through save", async () => {
for (const bookType of ["xls", "xlsx"]) {
const page = harness();
const previous = plain(page.scoreRows.value);
const input = fileEvent(bytes([headers(page).reverse(), validRow.slice().reverse()], bookType), bookType);
await page.importScoreExcel(input);
const rows = plain(page.scoreRows.value);
assert.deepEqual(rows[0], previous[0]);
assert.equal(rows[1].id, previous[1].id);
assert.equal(rows[1].channel, "京东");
assert.equal(rows[1].weightedScore, 3.25);
assert.deepEqual(rows[1].dimensions.map((metric) => metric.score), validRow.slice(1, 8));
assert.deepEqual(rows[1].dimensions.map((metric) => metric.weight), [40, 10, 10, 10, 10, 10, 10]);
assert.equal(page.importingScores.value, false);
assert.equal(input.target.value, "");
assert.equal(page.saved.length, 0);
await page.saveScoreStep();
assert.equal(page.saved[0].taskKey, "release-channel-evaluation");
assert.equal(page.saved[0].payload.currentStep, 3);
const answer = JSON.parse(page.saved[0].payload.step3Answer);
assert.equal(answer.rows[1].dimensions[0].score, 0);
assert.equal(answer.rows[1].dimensions[0].weight, 40);
assert.equal(answer.rows[1].weightedScore, 3.25);
}
});
test("invalid or cancelled score imports leave all existing rows unchanged", async () => {
const page = harness();
const original = plain(page.scoreRows.value);
const invalidRows = [
["未知渠道", ...validRow.slice(1)],
["京东", "abc", ...validRow.slice(2)],
["京东", -1, ...validRow.slice(2)],
["京东", 10.1, ...validRow.slice(2)],
["京东", 1.23, ...validRow.slice(2)],
["京东", "10%", ...validRow.slice(2)],
[...validRow.slice(0, 8), 1.234],
];
for (const invalid of invalidRows) {
await page.importScoreExcel(fileEvent(bytes([headers(page), ["天猫", ...validRow.slice(1)], invalid])));
assert.deepEqual(plain(page.scoreRows.value), original);
assert.match(page.messages.at(-1), /第 3 行/);
}
const parseRows = (rows) => page.parseScoreExcelRows(rows, page.scoringMetrics, ["天猫", "京东"]);
assert.throws(() => parseRows([]), /没有数据/);
assert.throws(() => parseRows([headers(page)]), /没有可导入/);
assert.throws(() => parseRows([["渠道"], validRow]), /缺少表头/);
assert.throws(() => parseRows([[...headers(page), "市场规模得分"], validRow]), /表头重复/);
assert.throws(() => parseRows([headers(page), validRow, validRow]), /重复/);
assert.throws(() => parseRows([[], headers(page), [], ["", 1]]), /第 4 行/);
await page.importScoreExcel(fileEvent(bytes([[], headers(page), [], ["京东", "abc"]])));
assert.match(page.messages.at(-1), /第 4 行/);
assert.deepEqual(plain(page.scoreRows.value), original);
const cancelled = harness(false);
const beforeCancel = plain(cancelled.scoreRows.value);
await cancelled.importScoreExcel(fileEvent(bytes([headers(cancelled), validRow])));
assert.deepEqual(plain(cancelled.scoreRows.value), beforeCancel);
assert.equal(cancelled.saved.length, 0);
assert.equal(cancelled.importingScores.value, false);
});
test("score template contains current channels and blank scores and round trips without changing weights", async () => {
const page = harness();
await page.downloadScoreTemplate();
const { workbook, name } = page.downloads[0];
assert.match(name, /\.xlsx$/);
assert.equal(workbook.SheetNames[1], "填写说明");
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { header: 1 });
assert.deepEqual(rows, [headers(page), ["天猫"], ["京东"]]);
const originalWeights = plain(page.scoreRows.value.map((row) => row.dimensions.map((metric) => metric.weight)));
await page.importScoreExcel(fileEvent(XLSX.write(workbook, { type: "buffer", bookType: "xlsx" })));
for (const row of page.scoreRows.value) {
assert.equal(row.weightedScore, undefined);
for (const metric of row.dimensions) assert.equal(metric.score, undefined);
}
assert.deepEqual(plain(page.scoreRows.value.map((row) => row.dimensions.map((metric) => metric.weight))), originalWeights);
});
test("score Excel controls compile and are confined to step three", () => {
const { descriptor, errors } = parse(source);
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "score-import" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: "score-import" }).errors, []);
const thirdStep = descriptor.template.content.split('<section v-else-if="activeStep === 3">')[1].split("</section>")[0];
for (const handler of ["downloadScoreTemplate", "importScoreExcel"]) {
assert.equal(descriptor.template.content.split(handler).length - 1, 1);
assert.ok(thirdStep.includes(handler));
}
assert.match(thirdStep, /accept="\.xlsx,\.xls"/);
});

@ -1,53 +0,0 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { ref, computed } = require("vue");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
test("school defaults display task names and submit task keys with the selected state", async () => {
const filename = path.resolve(__dirname, "../src/views/teacherEnd/defaultTask/index.vue");
const { descriptor, errors } = parse(fs.readFileSync(filename, "utf8"));
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "default-task-test" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: "default-task-test" }).errors, []);
assert.match(descriptor.template.content, /\{\{ taskNameFor\(row\.module\) \}\}/);
let saved;
const context = vm.createContext({
ref,
computed,
onMounted() {},
getCurrentInstance: () => ({ proxy: { $modal: { msgSuccess() {} } } }),
useUserStore: () => ({ userInfo: { teacherAdmin: true } }),
teacherApi: {
getSchoolDefaultTasks: async () => ({ data: { status: "READY", tasks: [
{ module: "new-product-survey", disabledStatus: 0, sort: 1 },
{ module: "product-development-factors", disabledStatus: 1, sort: 2 },
{ module: "__TEACHING_CLASS_TASK_PUBLICATION__", disabledStatus: 1, sort: 0 },
] } }),
saveSchoolDefaultTasks: async (tasks) => { saved = JSON.parse(JSON.stringify(tasks)); },
},
listTrainingTasks: async (params) => {
assert.equal(params.enabledOnly, false);
return { data: [
{ taskKey: "new-product-survey", taskName: "新产品调查与分析" },
{ taskKey: "product-development-factors", taskName: "产品开发关键因素" },
] };
},
});
vm.runInContext(descriptor.scriptSetup.content.replace(/^import .*;\r?\n/gm, ""), context);
const page = vm.runInContext("({ loadTasks, saveTasks, tasks, taskNameFor })", context);
await page.loadTasks();
assert.equal(page.taskNameFor("new-product-survey"), "新产品调查与分析");
assert.equal(page.tasks.value.length, 2);
page.tasks.value[0].disabledStatus = 1;
await page.saveTasks();
assert.deepEqual(saved, [
{ module: "new-product-survey", disabledStatus: 1, sort: 1 },
{ module: "product-development-factors", disabledStatus: 1, sort: 2 },
]);
});

@ -1,185 +0,0 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const Vue = require("vue");
const { ref, reactive, computed, watch, nextTick, createSSRApp, h } = Vue;
const { renderToString } = require("@vue/server-renderer");
const { compile } = require("@vue/compiler-dom");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
const read = (file) => fs.readFileSync(path.resolve(__dirname, "../src", file), "utf8");
const stripImports = (source) => source.replace(/^import .*;?\r?\n/gm, "");
function storeHarness(fetchConfig) {
const context = { defineStore: (_, definition) => definition, getToken: () => "token-A", getUserInfo: () => '{"roleId":3}', getCurrentSchoolProductConfig: fetchConfig };
const source = stripImports(read("store/modules/user.js")).replaceAll("import.meta.env.VITE_APP_BASE_API", '"/"').replace("export default useUserStore;", "globalThis.definition = useUserStore;");
vm.runInNewContext(source, context);
const state = context.definition.state();
state.ensureSchoolProductConfig = function () { return context.definition.actions.ensureSchoolProductConfig.call(this); };
return state;
}
test("configuration refresh follows platform changes and clears failed cached permissions", async () => {
let enabled = true;
let fail = false;
let calls = 0;
const state = storeHarness(async () => {
calls++;
if (fail) throw new Error("offline");
return { data: { adminClassManagementEnabled: enabled } };
});
await state.ensureSchoolProductConfig();
enabled = false;
assert.equal((await state.ensureSchoolProductConfig()).adminClassManagementEnabled, false);
assert.equal(calls, 2);
fail = true;
await assert.rejects(state.ensureSchoolProductConfig(), /offline/);
assert.equal(state.schoolProductConfig, null);
});
test("concurrent loads share a request and an old login cannot overwrite the current school", async () => {
const pending = [];
const state = storeHarness(() => new Promise((resolve) => pending.push(resolve)));
const first = state.ensureSchoolProductConfig();
assert.equal(state.ensureSchoolProductConfig(), first);
state.token = "token-B";
const second = state.ensureSchoolProductConfig();
pending[1]({ data: { schoolId: "B" } });
await second;
pending[0]({ data: { schoolId: "A" } });
await first;
assert.equal(state.schoolProductConfig.schoolId, "B");
});
test("ordinary teacher navigation refreshes configuration before continuing", async () => {
let refreshed = 0;
const state = { userInfo: { roleId: 3 }, ensureSchoolProductConfig: async () => { refreshed++; return { facultyManagementEnabled: true }; } };
let guard;
const context = { router: { beforeEach: (fn) => { guard = fn; }, afterEach() {} }, NProgress: { configure() {}, start() {}, done() {} }, getToken: () => "token", getUserInfo: () => '{"roleId":3}', useUserStore: () => state, usePermissionStore: () => ({ getRoutersPermission: async () => {} }), ElMessage: { error: (message) => assert.fail(message) } };
vm.runInNewContext(stripImports(read("permission.js")), context);
await new Promise((resolve) => guard({ path: "/teacher/index", matched: [{ meta: {} }] }, {}, resolve));
assert.equal(refreshed, 1);
const sidebar = read("layout/components/Sidebar/index.vue");
assert.match(sidebar, /addEventListener\("focus", refreshSchoolConfiguration\)/);
assert.match(sidebar, /removeEventListener\("focus", refreshSchoolConfiguration\)/);
assert.match(sidebar, /JSON\.stringify\(userStore\.schoolProductConfig\)/);
});
test("late school responses cannot overwrite the school being edited or its save target", async () => {
const filename = "views/platformAdmin/school/index.vue";
const { descriptor, errors } = parse(read(filename));
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "school-editor" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: "school-editor" }).errors, []);
const pending = {};
const saved = [];
const context = { ref, reactive, computed, chinaRegions: [], onMounted() {}, ElMessage: { success() {} }, getPlatformSchools: async () => ({ data: { list: [], total: 0 } }), getPlatformSchoolProductConfig: (id) => new Promise((resolve) => { pending[id] = resolve; }), updatePlatformSchoolProductConfig: async (id, config) => saved.push({ id, ...config }), updatePlatformSchool: async () => {} };
vm.runInNewContext(stripImports(descriptor.scriptSetup.content) + "\nglobalThis.page = {openEdit, openCreate, submit, editingId, productConfig, configLoading};", context);
const page = context.page;
const a = page.openEdit({ schoolId: "A" });
const b = page.openEdit({ schoolId: "B" });
await page.submit();
assert.equal(saved.length, 0);
pending.B({ data: { schoolId: "B", organizationMode: "TEACHING_CLASS_ONLY", adminClassManagementEnabled: false } });
await b;
pending.A({ data: { schoolId: "A", organizationMode: "ADMIN_CLASS_ENABLED", adminClassManagementEnabled: true } });
await a;
assert.equal(page.productConfig.value.schoolId, "B");
await page.submit();
assert.equal(saved[0].id, "B");
assert.equal(saved[0].adminClassManagementEnabled, false);
const c = page.openEdit({ schoolId: "C" });
page.openCreate();
pending.C({ data: { schoolId: "C" } });
await c;
assert.equal(page.editingId.value, "");
assert.equal(page.productConfig.value.schoolId, undefined);
});
test("custom organization modes use the teacher roster import and template in both pages", async () => {
const source = read("views/teacherEnd/class/index.vue");
const declarations = source.split(/\r?\n/).filter((line) => /^const (legacyAdminEnabled|facultyManagementEnabled|majorManagementEnabled|adminClassManagementEnabled|isTeacherRosterMode) =/.test(line)).join("\n");
const sheets = [];
let imported = false;
const xlsx = { utils: { aoa_to_sheet: (rows) => { sheets.push(rows); return {}; }, book_new: () => ({}), book_append_sheet() {} }, writeFile() {} };
const context = { computed, userStore: { schoolProductConfig: { organizationMode: "CUSTOM", studentRosterOwner: "TEACHER", facultyManagementEnabled: true, majorManagementEnabled: true, adminClassManagementEnabled: false } }, selectedTeachingClass: { value: { schoolClassId: "class-A" } }, indexApi: { importTeacherRosterMembers: async (id) => { imported = id === "class-A"; } }, FormData: class { append() {} }, handleMemberImportSuccess() {}, xlsx };
const upload = source.slice(source.indexOf("function uploadMemberImport("), source.indexOf("function handleMemberImportSuccess("));
const download = source.slice(source.indexOf("async function downloadMemberImportTemplate("), source.indexOf("/* 2026-10-12 停用:名单创建模板下载"));
vm.runInNewContext(declarations + "\n" + upload + "\n" + download.replace('await import("xlsx")', "xlsx") + "\nglobalThis.page={uploadMemberImport,downloadMemberImportTemplate,isTeacherRosterMode};", context);
const studentMode = read("views/teacherEnd/student/index.vue").split(/\r?\n/).find((line) => line.startsWith("const isTeacherRosterMode ="));
const student = { computed, userStore: context.userStore };
vm.runInNewContext(studentMode + "\nglobalThis.mode=isTeacherRosterMode.value;", student);
assert.equal(context.page.isTeacherRosterMode.value, student.mode);
await context.page.uploadMemberImport({ file: {} });
assert.equal(imported, true);
await context.page.downloadMemberImportTemplate();
assert.deepEqual(Array.from(sheets[0][0]), ["学生姓名", "学号"]);
});
test("class actions allow same school managers and owners while preserving restrictions", () => {
const source = read("views/teacherEnd/class/index.vue");
const context = { currentUserId: { value: "manager-A" }, currentSchoolId: { value: "school-A" }, adminClassManagementEnabled: { value: true }, userStore: { userInfo: { teacherAdmin: true } } };
vm.runInNewContext(source.slice(source.indexOf("function normalizeClassType("), source.indexOf("function getList(")) + "\nglobalThis.allowed=canOperateClass;", context);
const teaching = { schoolId: "school-A", createdBy: "teacher-B", classType: "TEACHING", dataSource: "LOCAL" };
assert.equal(context.allowed(teaching), true);
assert.equal(context.allowed({ ...teaching, schoolId: "school-B" }), false);
assert.equal(context.allowed({ ...teaching, dataSource: "ZHIYUN" }), false);
context.userStore.userInfo.teacherAdmin = false;
assert.equal(context.allowed(teaching), false);
assert.equal(context.allowed({ ...teaching, createdBy: "manager-A" }), true);
context.adminClassManagementEnabled.value = false;
assert.equal(context.allowed({ ...teaching, classType: "ADMIN" }), false);
});
test("teaching only page never renders administrative tabs during loading failures or recovery", async () => {
let fail = false;
const state = reactive(storeHarness(async () => {
if (fail) throw new Error("offline");
return { data: { organizationMode: "TEACHING_CLASS_ONLY", studentRosterOwner: "TEACHER", facultyManagementEnabled: false, majorManagementEnabled: false, adminClassManagementEnabled: false } };
}));
const source = read("views/teacherEnd/class/index.vue");
const declarations = source.split(/\r?\n/).filter((line) => /^const (activeClassType|legacyAdminEnabled|facultyManagementEnabled|majorManagementEnabled|adminClassManagementEnabled|isTeacherRosterMode) =/.test(line)).join("\n");
const modeWatch = source.slice(source.indexOf("watch(adminClassManagementEnabled,"), source.indexOf("</script>", source.indexOf("watch(adminClassManagementEnabled,")));
const context = { ref, computed, watch, userStore: state };
vm.runInNewContext(declarations + "\n" + modeWatch + "\nglobalThis.page={activeClassType,adminClassManagementEnabled};", context);
const tabsTemplate = source.match(/<el-tabs\b[\s\S]*?<\/el-tabs>/)[0];
const render = new Function("Vue", compile(tabsTemplate, { prefixIdentifiers: true }).code)(Vue);
async function renderTabs() {
const app = createSSRApp({ setup: () => ({ ...context.page, adminClassCount: 2, teachingClassCount: 3, handleTabChange() {} }), render });
app.component("el-tabs", { setup: (_, { slots }) => () => h("nav", slots.default?.()) });
app.component("el-tab-pane", { props: ["label"], setup: (props) => () => h("span", props.label) });
return renderToString(app);
}
async function expectTeachingOnly() {
await nextTick();
assert.equal(context.page.adminClassManagementEnabled.value, false);
assert.equal(context.page.activeClassType.value, "TEACHING");
assert.doesNotMatch(await renderTabs(), /行政班/);
}
await expectTeachingOnly();
for (let i = 0; i < 3; i++) {
await state.ensureSchoolProductConfig();
await expectTeachingOnly();
}
fail = true;
await assert.rejects(state.ensureSchoolProductConfig(), /offline/);
await expectTeachingOnly();
fail = false;
await state.ensureSchoolProductConfig();
await expectTeachingOnly();
state.schoolProductConfig = { organizationMode: "ADMIN_CLASS_ENABLED", adminClassManagementEnabled: true };
await nextTick();
assert.match(await renderTabs(), /行政班/);
});
test("missing school configuration blocks management navigation instead of enabling administrative classes", async () => {
let guard;
const messages = [];
const context = { router: { beforeEach: (fn) => { guard = fn; }, afterEach() {} }, NProgress: { configure() {}, start() {}, done() {} }, getToken: () => "token", getUserInfo: () => '{"roleId":3}', useUserStore: () => ({ userInfo: { roleId: 3 }, ensureSchoolProductConfig: async () => null }), usePermissionStore: () => ({ getRoutersPermission: async () => assert.fail("navigation must be blocked") }), ElMessage: { error: (message) => messages.push(message) } };
vm.runInNewContext(stripImports(read("permission.js")), context);
const result = await new Promise((resolve) => guard({ path: "/class/index", matched: [{ meta: { awaitSchoolProductConfig: true } }] }, {}, resolve));
assert.equal(result, false);
assert.equal(messages.length, 1);
});

@ -24,7 +24,7 @@ assert(/requiresFacultyManagement:\s*true/.test(sidebar), "the teacher course-st
assert(/requiresMajorManagement:\s*true/.test(sidebar), "the teacher course-style major item must declare its capability");
assert(/filterTeacherManageNavigation\(teacherManageNav\)/.test(sidebar), "the teacher course-style sidebar must filter its hard-coded navigation before rendering");
assert(/currentCourseNav = computed\([\s\S]*?filterTeacherManageNavigation\(teacherManageNav\)/.test(sidebar), "teachers must render the filtered course-style navigation instead of the raw hard-coded menu");
assert(/watch\(\s*\(\) => JSON\.stringify\(userStore\.schoolProductConfig\)/.test(sidebar), "sidebar must refresh when any school capability changes, including custom modes");
assert(/watch\(\s*\(\) => userStore\.schoolProductConfig\?\.organizationMode/.test(sidebar), "sidebar must refresh when the asynchronous school configuration arrives");
assert(/organizationMode/.test(platformSchool) && /updatePlatformSchoolProductConfig/.test(platformSchool), "platform school editor must manage organization mode");
assert(/行政班管理/.test(platformSchool), "platform school editor must expose administrative-class management controls");
assert(/v-model="productConfig\.facultyManagementEnabled"/.test(platformSchool), "platform school editor must configure faculty management with a switch");
@ -34,7 +34,7 @@ assert(/requiresFacultyManagement/.test(router) && /requiresMajorManagement/.tes
assert(/adminClassManagementEnabled/.test(teacherClass), "teacher class page must derive administrative-class controls from the switch");
assert(/isTeacherRosterMode/.test(teacherClass), "teacher class page must recognize teacher-managed roster mode");
assert(!/!this\.userInfo\?\.schoolId\s*\|\|\s*this\.userInfo\?\.roleId\s*==\s*1/.test(userStore), "school configuration loading must not be skipped because cached user info lacks schoolId");
assert(/this\.userInfo\?\.roleId\s*==\s*1/.test(userStore) && /getCurrentSchoolProductConfig\(\)/.test(userStore), "every non-platform user must load school configuration from the backend token");
assert(/this\.userInfo\?\.roleId\s*==\s*1/.test(userStore) && /return getCurrentSchoolProductConfig\(\)/.test(userStore), "every non-platform user must load school configuration from the backend token");
assert(/await userStore\.ensureSchoolProductConfig\(\)/.test(sidebar), "school menus must load the product configuration before they are generated");
assert(/const facultyEnabled = config\?\.facultyManagementEnabled === true;/.test(sidebar), "faculty menus must fail closed until their school capability is confirmed");
assert(/const majorEnabled = config\?\.majorManagementEnabled === true;/.test(sidebar), "major menus must fail closed until their school capability is confirmed");

@ -5,14 +5,11 @@ const assert = require("node:assert/strict");
const source = fs.readFileSync(path.resolve(__dirname, "../src/views/student/index.vue"), "utf8");
test("学生首页按老师评分优先、AI评分兜底显示成绩", () => {
test("学生首页并列展示 AI 评分和老师评分", () => {
assert.match(source, /AI评分/);
assert.match(source, /老师评分/);
assert.match(source, /report\.value\.teacherScore/);
assert.match(source, /report\.value\.aiAssessmentScore/);
assert.match(source, /hasTeacherScore\.value \? formatScore\(teacherScore\.value\) : formatScore\(aiScore\.value\)/);
assert.match(source, /const hasScore = computed\(\(\) => hasTeacherScore\.value \|\| hasAiScore\.value\)/);
assert.match(source, /评分:<\/span>\s*<strong>\{\{ displayScore \}\}/);
assert.doesNotMatch(source, /scoreLabel/);
assert.doesNotMatch(source, /summary-unit/);
assert.match(source, /formatTeacherScore/);
});
test("学生首页成绩摘要保持单行且不展示当前排名", () => {
@ -22,10 +19,9 @@ test("学生首页成绩摘要保持单行且不展示当前排名", () => {
assert.doesNotMatch(source, /rank-copy/);
});
test("没有任何成绩时保持空值并显示占位符", () => {
assert.match(source, /totalScore: null, aiAssessmentScore: null, teacherScore: null/);
assert.match(source, /if \(value === null \|\| value === undefined \|\| value === ""\) return "—"/);
assert.match(source, /const aiScore = computed\(\(\) => report\.value\.aiAssessmentScore \?\? report\.value\.aiScore \?\? null\)/);
test("老师未评分时不拼接分数单位", () => {
assert.match(source, /const hasTeacherScore = \(value\) => value !== null && value !== undefined && value !== ""/);
assert.match(source, /v-if="hasTeacherScore\(teacherScore\)"/);
});
console.log("student home AI and teacher score static checks passed");

@ -1,20 +0,0 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const taskPage = fs.readFileSync(path.join(root, "src/views/teacherEnd/task/index.vue"), "utf8");
assert(taskPage.includes("function sameValue(left, right)"), "task assignment must normalize class owner identifiers before comparing them");
assert.match(
taskPage,
/const teachingClassList = computed\(\(\) => classList\.value\.filter\(\(item\) =>[\s\S]*sameValue\(item\.createdBy, currentUserId\.value\)/,
"task assignment class options must be limited to classes created by the current teacher"
);
assert.match(
taskPage,
/const canOperateSelectedClass = computed\(\(\) => sameValue\(selectedClass\.value\?\.createdBy, currentUserId\.value\)\)/,
"task assignment operations must use the same current-teacher ownership check"
);
console.log("task assignment class options are scoped to the current teacher");

@ -19,13 +19,10 @@ assert((taskPage.match(/if \(!isActiveLoad\(requestedClassId, requestGeneration\
assert(taskPage.includes("let activeLoadGeneration = 0;"), "overlapping class loads must use a shared generation");
assert(taskPage.includes("const requestGeneration = ++activeLoadGeneration;"), "each class load must advance the active generation");
assert(taskPage.includes("if (requestGeneration === activeLoadGeneration) loading.value = false;"), "only the active class load may clear the loading indicator");
assert(taskPage.includes("projectNumber: String(projectIndex + 1)"), "projects must render chapter numbers");
assert(taskPage.includes("taskNumber: `${projectIndex + 1}.${taskIndex + 1}`"), "tasks must render nested chapter numbers");
assert(taskPage.includes("let selectionSyncGeneration = -1;"), "programmatic selection synchronization must be tracked");
assert(taskPage.includes("if (selectionSyncGeneration === activeLoadGeneration) return;"), "programmatic table selection events must not overwrite task keys");
assert(taskPage.includes("getTaskPublication"), "task allocation must load the selected class publication state");
assert(taskPage.includes("function defaultPublishedTaskKeys()"), "an unconfigured class must use an explicit default task selection");
assert(taskPage.includes("groupedTasks.value[0]?.tasks.slice(0, 3)"), "an unconfigured class must default to the first three tasks of the first project");
assert(taskPage.includes("referenceAnswerEnabled"), "task allocation must expose reference answer visibility state");
assert(taskPage.includes("updateTaskReferenceAnswerVisibility"), "task allocation must persist reference answer visibility");
assert(/tasks\.value\s+\.filter\(\(task\) => task\.taskKey !== comprehensiveTaskKey\)\s+\.map\(\(task\) => task\.taskKey\)/.test(taskPage), "an unconfigured class must keep comprehensive training unpublished until the teacher explicitly selects it");
assert(taskPage.includes("保存发布配置"), "task allocation must require an explicit save");
assert(api.includes("selectTaskPublicationByClassId"), "publication API missing");
assert(sidebar.includes("buildStudentTaskSections"), "student menu must be generated from the published training task list");

@ -70,12 +70,6 @@ assert.match(reviewPanel, /prop="name" label="姓名" width="74"/);
assert.match(reviewPanel, /prop="username" label="学号" width="88"/);
assert.match(reviewPanel, /label="AI评分" width="66"/);
assert.match(reviewPanel, /label="老师评分" width="94"/);
const referencePreviewFragment = reviewPanel.match(/referenceAnswerSrc\.value = `\$\{referenceAnswerObjectUrl\}(#[^`]+)`/)?.[1];
assert.ok(referencePreviewFragment, "参考答案应配置 PDF 预览参数");
const referencePreviewParams = new URLSearchParams(referencePreviewFragment.slice(1));
assert.equal(referencePreviewParams.get("navpanes"), "0", "参考答案应默认隐藏缩略图侧栏");
assert.equal(referencePreviewParams.get("toolbar"), "1", "参考答案应保留缩放、翻页等工具");
assert.equal(referencePreviewParams.get("pagemode"), "none", "保留其他 PDF 查看器的无侧栏参数");
assert.doesNotMatch(reviewPanel, /task-review__student-preview\s*\{[^}]*background:/, "嵌入框不得覆盖学生页面底色");
assert.doesNotMatch(reviewPanel, /<el-collapse[\s\S]*?formatAnswer/);

@ -1,40 +0,0 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const frontendRoot = path.resolve(__dirname, "..");
const backendRoot = path.resolve(frontendRoot, "..", "link_commerce");
const readFrontend = (file) => fs.readFileSync(path.join(frontendRoot, file), "utf8");
const readBackend = (file) => fs.readFileSync(path.join(backendRoot, file), "utf8");
const taskPage = readFrontend("src/views/teacherEnd/task/index.vue");
const trainingTaskPage = readFrontend("src/views/teacherEnd/trainingTask/index.vue");
const scorePage = readFrontend("src/views/teacherEnd/score/index.vue");
const reviewPage = readFrontend("src/views/teacherEnd/score/TaskReviewPanel.vue");
const teacherHome = readFrontend("src/views/teacherEnd/index.vue");
const examService = readBackend("src/main/java/com/sztzjy/linkCommerce/service/ExamService.java");
assert.match(taskPage, /const isManagerTeacher = computed\(\(\) => userStore\.userInfo\.teacherAdmin === true\)/);
assert.match(taskPage, /isManagerTeacher\.value \|\| sameValue\(item\.createdBy, currentUserId\.value\)/);
assert.match(trainingTaskPage, /const isManagerTeacher = computed\(\(\) => userStore\.userInfo\.teacherAdmin === true\)/);
assert.match(trainingTaskPage, /isManagerTeacher\.value \|\| String\(schoolClass\.createdBy \|\| ""\) === String\(currentUserId\.value \|\| ""\)/);
assert.match(trainingTaskPage, /const isReadonly = computed\(\(\) => dialogMode\.value === "view" \|\| !canOperateSelectedClass\.value\)/);
assert.match(scorePage, /const isManagerTeacher = computed\(\(\) => userStore\.userInfo\.teacherAdmin === true\)/);
assert.match(scorePage, /isManagerTeacher\.value \|\| String\(item\.createdBy \|\| ""\) === currentUserId\.value/);
assert.match(scorePage, /isManagerTeacher\.value \|\| String\(selectedTeachingClass\.value\.createdBy \|\| ""\) === currentUserId\.value/);
assert.match(reviewPage, /const filterTeachingClasses = \(classes\) =>/);
assert.match(reviewPage, /isManagerTeacher\.value \|\| String\(item\.createdBy \|\| ""\) === currentUserId\.value/);
assert.match(reviewPage, /isManagerTeacher\.value \|\| String\(currentClass\.createdBy \|\| ""\) === currentUserId\.value/);
assert.match(teacherHome, /const loadClasses = userStore\.userInfo\.teacherAdmin === true/);
assert.match(teacherHome, /teacherApi\.getAccessibleTeachingClasses/);
assert.match(teacherHome, /teacherApi\.getOwnedTeachingClasses/);
assert.match(examService, /where school_id=\? and \(status is null or status=1\)/);
assert.match(examService, /if \(!isTeacherAdmin\(teacher\)\)/);
assert.match(examService, /teacher_admin=1/);
console.log("teacher class dropdowns are scoped by owner with manager-teacher access");

@ -1,22 +0,0 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const editor = fs.readFileSync(
path.join(root, "src/views/teacherEnd/trainingTask/index.vue"),
"utf8"
);
assert(/key: "referenceAnswer",\s*label: "参考答案"/.test(editor));
assert(/accept: "\.pdf,application\/pdf"/.test(editor), "reference answers should expose PDF file types");
assert(/referenceAnswerName: ""/.test(editor));
assert(/referenceAnswerUrl: ""/.test(editor));
assert(/referenceAnswerName: referenceAnswer\.name/.test(editor));
assert(/referenceAnswerUrl: referenceAnswer\.url/.test(editor));
assert(/referenceAnswerName: taskForm\.referenceAnswerName/.test(editor));
assert(/referenceAnswerUrl: taskForm\.referenceAnswerUrl/.test(editor));
assert(/slotKey === "referenceAnswer" && !isPdfFile\(rawFile\)/.test(editor));
assert(/name\.endsWith\("\.pdf"\)/.test(editor));
console.log("teacher reference-answer upload contract passed");
Loading…
Cancel
Save